📄 ams.java
字号:
/*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.
The updating of this file to JADE 2.0 has been partially supported by the IST-1999-10211 LEAP Project
GNU Lesser General Public License
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
package jade.domain;
//#APIDOC_EXCLUDE_FILE
//#MIDP_EXCLUDE_FILE
import java.io.FileWriter;
import jade.util.leap.Iterator;
import jade.util.leap.List;
import jade.util.leap.ArrayList;
import jade.util.leap.Map;
import jade.util.leap.HashMap;
import jade.util.InputQueue;
import jade.util.Logger;
import java.util.Hashtable;
import jade.core.*;
import jade.core.behaviours.*;
import jade.core.event.PlatformEvent;
import jade.core.event.MTPEvent;
import jade.domain.FIPAAgentManagement.InternalError;
import jade.domain.FIPAAgentManagement.*;
import jade.domain.JADEAgentManagement.*;
import jade.domain.introspection.*;
import jade.domain.mobility.*;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.content.*;
import jade.content.lang.*;
import jade.content.lang.sl.*;
import jade.content.onto.basic.Action;
import jade.mtp.MTPException;
import jade.mtp.MTPDescriptor;
import jade.security.JADESecurityException;
import jade.security.JADEPrincipal;
import jade.security.Credentials;
import java.util.Date;
/**
Standard <em>Agent Management System</em> agent. This class
implements <em><b>FIPA</b></em> <em>AMS</em> agent. <b>JADE</b>
applications cannot use this class directly, but interact with it
through <em>ACL</em> message passing.
@author Giovanni Rimassa - Universita' di Parma
@author Giovanni Caire - TILAB
@version $Date: 2007-09-03 10:57:46 +0200 (lun, 03 set 2007) $ $Revision: 5998 $
*/
public class ams extends Agent /*implements AgentManager.Listener*/ {
public static final String PERIODIC_LOG_DELAY = "jade_domain_ams_periodiclogdelay";
public static final String MAX_RESULTS = "jade_domain_ams_maxresult";
// Limit of searchConstraints.maxresult
// FIPA Agent Management Specification doc num: SC00023J (6.1.4 Search Constraints)
// a negative value of maxresults indicates that the sender agent is willing to receive
// all available results
private static final int DEFAULT_MAX_RESULTS = 100;
private static final int DEFAULT_PERIODIC_LOG_DELAY = -1;
private int amsMaxResults = DEFAULT_MAX_RESULTS;
private Logger logger;
// The AgentPlatform where information about agents is stored
private AgentManager myPlatform;
// The codec for the SL language
private Codec codec = new SLCodec();
// ACL Message to use for tool notification
private ACLMessage toolNotification = new ACLMessage(ACLMessage.INFORM);
// Buffer for AgentPlatform notifications
private InputQueue eventQueue = new InputQueue();
private AMSEventQueueFeeder queueFeeder;
private Hashtable pendingNewAgents = new Hashtable();
private Hashtable pendingDeadAgents = new Hashtable();
private Hashtable pendingClonedAgents = new Hashtable();
private Hashtable pendingMovedAgents = new Hashtable();
private Hashtable pendingRemovedContainers = new Hashtable();
private APDescription theProfile = new APDescription();
/**
This constructor creates a new <em>AMS</em> agent. Since a direct
reference to an Agent Platform implementation must be passed to
it, this constructor cannot be called from application
code. Therefore, no other <em>AMS</em> agent can be created
beyond the default one.
*/
public ams(AgentManager ap) {
logger = Logger.getMyLogger(FIPANames.AMS);
myPlatform = ap;
// GC-MODIFY-18022007-START
//myPlatform.addListener(this);
// GC-MODIFY-18022007-END
}
/**
AMS initialization
*/
protected void setup() {
// Agent Platform Description.
theProfile.setName("\"" + getHap() + "\"");
writeAPDescription(theProfile);
String sLogDelay = getProperty(PERIODIC_LOG_DELAY, String.valueOf(DEFAULT_PERIODIC_LOG_DELAY));
try {
int logDelay = Integer.parseInt(sLogDelay);
if (logDelay > 0) {
// Activate periodic log
addBehaviour(new TickerBehaviour(this, (long) logDelay) {
public void onTick() {
logger.log(Logger.INFO, "JADE AMS active...");
}
});
}
}
catch (Exception e) {
logger.log(Logger.WARNING, "Wrong periodic log delay value "+sLogDelay+". It must be an integer value.");
}
String sMaxResults = getProperty(MAX_RESULTS, String.valueOf(DEFAULT_MAX_RESULTS));
try {
amsMaxResults = Integer.parseInt(sMaxResults);
}
catch (Exception e) {
logger.log(Logger.WARNING, "Wrong max result limit "+sMaxResults+". It must be an integer value.");
}
// Register the supported ontologies
getContentManager().registerOntology(FIPAManagementOntology.getInstance());
getContentManager().registerOntology(JADEManagementOntology.getInstance());
getContentManager().registerOntology(IntrospectionOntology.getInstance());
// Use fully qualified name to avoid conflict with old jade.domain.MobilityOntology
getContentManager().registerOntology(jade.domain.mobility.MobilityOntology.getInstance());
// register the supported languages: all profiles of SL are ok for ams
getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL0);
getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL1);
getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL2);
getContentManager().registerLanguage(codec, FIPANames.ContentLanguage.FIPA_SL);
// The behaviour managing FIPA requests
MessageTemplate mtF = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.REQUEST), MessageTemplate.MatchOntology(FIPAManagementVocabulary.NAME));
Behaviour fipaResponderB = new AMSFipaAgentManagementBehaviour(this, mtF);
addBehaviour(fipaResponderB);
// The behaviour managing JADE requests
// MobilityOntology is matched for JADE 2.5 Backward compatibility
MessageTemplate mtJ = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.REQUEST), MessageTemplate.or(MessageTemplate.MatchOntology(JADEManagementVocabulary.NAME), MessageTemplate.MatchOntology(jade.domain.mobility.MobilityOntology.NAME)));
Behaviour jadeResponderB = new AMSJadeAgentManagementBehaviour(this, mtJ);
addBehaviour(jadeResponderB);
// The behaviours dealing with platform tools
Behaviour registerTool = new RegisterToolBehaviour();
Behaviour deregisterTool = new DeregisterToolBehaviour();
Behaviour eventManager = new EventManager();
addBehaviour(registerTool);
addBehaviour(deregisterTool);
addBehaviour(eventManager);
eventQueue.associate(eventManager);
// Initialize the message used for tools notification
toolNotification.setLanguage(FIPANames.ContentLanguage.FIPA_SL0);
toolNotification.setOntology(IntrospectionOntology.NAME);
toolNotification.setInReplyTo("tool-subscription");
}
//////////////////////////////////////////////////////////////////
// Methods implementing the actions of the JADEManagementOntology.
// All these methods
// - extract the necessary information from the requested Action
// object and format them properly (if necessary)
// - Call the corresponding method of the AgentManager using the
// permissions of the requester agent.
// - Convert eventual JADE-internal Exceptions into proper FIPAException.
// These methods are package-scoped as they are called by the
// AMSJadeAgentManagementBehaviour.
//////////////////////////////////////////////////////////////////
// CREATE AGENT
void createAgentAction(final CreateAgent ca, final AID requester, final JADEPrincipal requesterPrincipal, final Credentials requesterCredentials) throws FIPAException {
final String agentName = ca.getAgentName();
final AID agentID = new AID(agentName, AID.ISLOCALNAME);
final String className = ca.getClassName();
final ContainerID container = ca.getContainer();
if (logger.isLoggable(Logger.FINE))
logger.log(Logger.FINE, "Agent " + requester + " requesting Create-agent " + agentID + " on container " + container);
// Prepare arguments as a Object[]
Iterator it = ca.getAllArguments();
ArrayList listArg = new ArrayList();
while (it.hasNext()) {
listArg.add(it.next());
}
final Object[] args = listArg.toArray();
final JADEPrincipal owner = ca.getOwner();
final Credentials initialCredentials = ca.getInitialCredentials();
// Do the job in a separated thread to avoid deadlock
Thread auxThread = new Thread() {
public void run() {
try {
myPlatform.create(agentName, className, args, container, owner, initialCredentials, requesterPrincipal, requesterCredentials);
} catch (UnreachableException ue) {
// Send failure notification to the requester if any
sendFailureNotification(ca, agentID, new InternalError("Destination container unreachable. " + ue.getMessage()));
} catch (JADESecurityException ae) {
if (logger.isLoggable(Logger.SEVERE))
logger.log(Logger.SEVERE, "Agent " + requester.getName() + " does not have permission to perform action Create-agent: " + ae);
// Send failure notification to the requester if any
sendFailureNotification(ca, agentID, new Unauthorised());
} catch (NotFoundException nfe) {
// Send failure notification to the requester if any
sendFailureNotification(ca, agentID, new InternalError("Destination container not found. " + nfe.getMessage()));
} catch (NameClashException nce) {
// Send failure notification to the requester if any
sendFailureNotification(ca, agentID, new AlreadyRegistered());
} catch (Throwable t) {
// Send failure notification to the requester if any
sendFailureNotification(ca, agentID, new InternalError(t.getMessage()));
}
}
};
auxThread.start();
}
// KILL AGENT
void killAgentAction(KillAgent ka, AID requester, JADEPrincipal requesterPrincipal, Credentials requesterCredentials) throws FIPAException {
final AID agentID = ka.getAgent();
if (logger.isLoggable(Logger.FINE))
logger.log(Logger.FINE, "Agent " + requester + " requesting Kill-agent " + agentID);
try {
myPlatform.kill(agentID, requesterPrincipal, requesterCredentials);
} catch (JADESecurityException ae) {
if (logger.isLoggable(Logger.SEVERE))
logger.log(Logger.SEVERE, "Agent " + requester.getName() + " does not have permission to perform action KillAgent");
throw new Unauthorised();
} catch (UnreachableException ue) {
throw new InternalError("Container not reachable. " + ue.getMessage());
} catch (NotFoundException nfe) {
throw new InternalError("Agent not found. " + nfe.getMessage());
} catch (Exception e) {
e.printStackTrace();
throw new InternalError("Unexpected exception. " + e.getMessage());
}
}
// CLONE AGENT
void cloneAgentAction(CloneAction ca, AID requester) throws FIPAException {
MobileAgentDescription dsc = ca.getMobileAgentDescription();
final AID agentID = dsc.getName();
final ContainerID where = (ContainerID) dsc.getDestination();
final String newName = ca.getNewName();
if (logger.isLoggable(Logger.CONFIG))
logger.log(Logger.CONFIG, "Agent " + requester + " requesting Clone-agent " + agentID + " on container " + where);
try {
myPlatform.copy(agentID, where, newName);
} catch (JADESecurityException ae) {
if (logger.isLoggable(Logger.SEVERE))
logger.log(Logger.SEVERE, "Agent " + requester.getName() + " does not have permission to perform action CloneAgent");
throw new Unauthorised();
} catch (UnreachableException ue) {
throw new InternalError("Container not reachable. " + ue.getMessage());
} catch (NotFoundException nfe) {
throw new InternalError("NotFoundException. " + nfe.getMessage());
} catch (NameClashException nce) {
throw new AlreadyRegistered();
} catch (Exception e) {
e.printStackTrace();
throw new InternalError("Unexpected exception. " + e.getMessage());
}
}
// MOVE AGENT
void moveAgentAction(MoveAction ma, AID requester) throws FIPAException {
MobileAgentDescription dsc = ma.getMobileAgentDescription();
final AID agentID = dsc.getName();
final ContainerID where = (ContainerID) dsc.getDestination();
if (logger.isLoggable(Logger.FINE))
logger.log(Logger.FINE, "Agent " + requester + " requesting Move-agent " + agentID + " on container " + where);
try {
myPlatform.move(agentID, where);
} catch (JADESecurityException ae) {
if (logger.isLoggable(Logger.SEVERE))
logger.log(Logger.SEVERE, "Agent " + requester.getName() + " does not have permission to perform action MoveAgent");
throw new Unauthorised();
} catch (UnreachableException ue) {
throw new InternalError("Container not reachable. " + ue.getMessage());
} catch (NotFoundException nfe) {
throw new InternalError("NotFoundException. " + nfe.getMessage());
} catch (Exception e) {
e.printStackTrace();
throw new InternalError("Unexpected exception. " + e.getMessage());
}
}
// KILL CONTAINER
void killContainerAction(final KillContainer kc, final AID requester, final JADEPrincipal requesterPrincipal, final Credentials requesterCredentials) throws FIPAException {
final ContainerID cid = kc.getContainer();
if (logger.isLoggable(Logger.FINE)) {
logger.log(Logger.FINE, "Agent " + requester + " requesting Kill-container " + cid);
}
// Notify a KILL_CONTAINER_REQUESTED introspection event to all tools
KillContainerRequested kcr = new KillContainerRequested();
kcr.setContainer(cid);
EventRecord er = new EventRecord(kcr, here());
er.setWhen(new Date());
try {
notifyTools(er);
} catch (Exception e) {
// Should never happen
e.printStackTrace();
}
Thread auxThread = new Thread() {
public void run() {
try {
myPlatform.killContainer(cid, requesterPrincipal, requesterCredentials);
} catch (JADESecurityException ae) {
logger.log(Logger.SEVERE, "Agent " + requester.getName() + " does not have permission to perform action Kill-container: " + ae);
// Send failure notification to the requester if any
sendFailureNotification(kc, cid, new Unauthorised());
} catch (NotFoundException nfe) {
// Send failure notification to the requester if any
sendFailureNotification(kc, cid, new InternalError("Container not found. " + nfe.getMessage()));
} catch (UnreachableException ue) {
// Send failure notification to the requester if any
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -