⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 agentmobilityservice.java

📁 java实现的P2P多agent中间件
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
				nce.printStackTrace();
			}
			catch(IMTPException imtpe) {
				// Unexpected remote error
				if (transferState == 0) {
					myLogger.log(Logger.SEVERE,"Can't retrieve destination container. Abort transfer. " + imtpe.getMessage());
				}
				else if (transferState == 1) {
					myLogger.log(Logger.SEVERE,"Error creating agent on destination container. Abort transfer. " + imtpe.getMessage());
				}
				else if (transferState == 2) {
					myLogger.log(Logger.SEVERE,"Error transferring agent identity. Abort transfer. " + imtpe.getMessage());
					
					try {
						dest.handleTransferResult(agentID, TRANSFER_ABORT, messages);
					}
					catch (Exception e) {
						e.printStackTrace();
					}
				}
				else if (transferState == 3) {
					// PANIC !!!
					myLogger.log(Logger.SEVERE,"Error activating transferred agent. Can't roll back!!!. " + imtpe.getMessage());
				}
			}
			//#DOTNET_EXCLUDE_END
			/*#DOTNET_INCLUDE_BEGIN
			 catch(System.Exception exc)
			 {
			 if(myLogger.isLoggable(Logger.SEVERE))
			 myLogger.log(Logger.SEVERE,"Error in agent serialization. Abort transfer. " + exc.get_Message());
			 }
			 #DOTNET_INCLUDE_END*/
			finally {
				if (transferState <= 2) {
					// Something went wrong --> Roll back.
					a.restoreBufferedState();
				}
				myContainer.releaseLocalAgent(agentID);
			}
		}
		
		private void handleInformCloned(VerticalCommand cmd) throws IMTPException, NotFoundException, NameClashException, JADESecurityException { // HandleInformCloned start
			Object[] params = cmd.getParams();
			AID agentID = (AID)params[0];
			Location where = (Location)params[1];
			String newName = (String)params[2];
			
			try {
				//#J2ME_EXCLUDE_BEGIN	
				//Register the clone in the Code Locator in the case its father is a jar agent
				String containerName = myContainer.getID().getName();
				Agent agent = myContainer.acquireLocalAgent(agentID);
				String codeContainerName = getClassSite(agent);
				myContainer.releaseLocalAgent(agentID);

				//Check if the code is in the same container or in a remote one.
				AgentManagementService amSrv = (AgentManagementService) myFinder.findService(AgentManagementService.NAME);
				CodeLocator codeLocator = amSrv.getCodeLocator();
				
				if (codeContainerName == null) codeContainerName = containerName;
				if (containerName.equals(codeContainerName)) {
					if (codeLocator.isRegistered(agentID)) {
						if(myLogger.isLoggable(Logger.FINE)) {
							myLogger.log(Logger.FINE," adding clone " + newName  + " to code locator.");
						}
						
						codeLocator.cloneAgent(agentID, new AID(newName,AID.ISLOCALNAME));
					}	
				} else {
					//Send a CLONE_CODE_LOCATOR_ENTRY command to the container with the agent code.
					AgentMobilitySlice codeSlice = (AgentMobilitySlice) getSlice(codeContainerName);
					try {
						codeSlice.cloneCodeLocatorEntry(agentID, new AID(newName,AID.ISLOCALNAME));
					} catch (IMTPException imtpe) {
						// Try to get a newer slice and repeat...
						codeSlice = (AgentMobilitySlice) getSlice(codeContainerName);
						codeSlice.cloneCodeLocatorEntry(agentID, new AID(newName,AID.ISLOCALNAME));
					}
				}
				//#J2ME_EXCLUDE_END	
				
				//log("Cloning agent " + agentID + " on container " + where.getName(), 1);
				if(myLogger.isLoggable(Logger.CONFIG))
					myLogger.log(Logger.CONFIG,"Cloning agent " + agentID + " on container " + where.getName());
				
				Agent a = myContainer.acquireLocalAgent(agentID);
				if (a == null) {
					//System.out.println("Internal error: handleClone() called with a wrong name (" + agentID + ") !!!");
					if(myLogger.isLoggable(Logger.SEVERE))
						myLogger.log(Logger.SEVERE,"Internal error: handleClone() called with a wrong name (" + agentID + ") !!!");
					return;
				}
				
				AgentMobilitySlice dest = (AgentMobilitySlice)getSlice(where.getName());
				if (dest == null) {
					myLogger.log(Logger.SEVERE,"Destination "+where.getName()+" does not exist or does not support mobility");
					return;
				}
				if(myLogger.isLoggable(Logger.FINE))
					myLogger.log(Logger.FINE,"Destination container for agent " + agentID + " found");
				
				
				// Serialize the agent
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				ObjectOutputStream encoder = new ObjectOutputStream(out);
				encoder.writeObject(a);
				byte[] bytes = out.toByteArray();
				//log("Agent " + agentID + " correctly serialized", 2);
				if(myLogger.isLoggable(Logger.FINE))
					myLogger.log(Logger.FINE,"Agent " + agentID + " correctly serialized");
				
				
				// Gets the container where the agent classes can be retrieved
				String classSiteName = (String)sites.get(a);
				if (classSiteName == null) {
					// The agent was born on this container
					classSiteName = getLocalNode().getName();
				}
				
				// Create the agent on the destination container with the new AID
				AID newID = new AID(newName, AID.ISLOCALNAME);
				try {
					dest.createAgent(newID, bytes, classSiteName, CLONING, CREATE_AND_START);
				}
				catch(IMTPException imtpe) {
					// Try to get a newer slice and repeat...
					dest = (AgentMobilitySlice)getFreshSlice(where.getName());
					dest.createAgent(newID, bytes, classSiteName, CLONING, CREATE_AND_START);
				}
				if(myLogger.isLoggable(Logger.FINE))
					myLogger.log(Logger.FINE,"Cloned Agent " + newID + " correctly created on destination container");
				
			}
			catch (IOException ioe) {
				// Error in agent serialization
				throw new IMTPException("I/O serialization error in handleInformCloned()", ioe);
			}
			catch(ServiceException se) {
				throw new IMTPException("Destination container not found in handleInformCloned()", se);
			}
			//catch(Exception e){
				//throw new IMTPException("Error accessing to agent's code in handleInformCloned()", e);
			//}
			finally {
				myContainer.releaseLocalAgent(agentID);
			}
		}
		
	} // End of CommandSourceSink class
	
	
	// This inner class handles the messaging commands on the command
	// issuer side, turning them into horizontal commands and
	// forwarding them to remote slices when necessary.
	private class CommandTargetSink implements Sink {
		
		public void consume(VerticalCommand cmd) {
			
			try {
				String name = cmd.getName();
				if(name.equals(AgentMobilityHelper.REQUEST_MOVE)) {
					handleRequestMove(cmd);
				}
				else if(name.equals(AgentMobilityHelper.REQUEST_CLONE)) {
					handleRequestClone(cmd);
				}
				else if(name.equals(AgentMobilityHelper.INFORM_MOVED)) {
					handleInformMoved(cmd);
				}
				else if(name.equals(AgentMobilityHelper.INFORM_CLONED)) {
					handleInformCloned(cmd);
				}
			}
			catch(Throwable t) {
				cmd.setReturnValue(t);
			}
		}
		
		private void handleRequestMove(VerticalCommand cmd) throws IMTPException, NotFoundException {
			Object[] params = cmd.getParams();
			AID agentID = (AID)params[0];
			Location where = (Location)params[1];
			
			moveAgent(agentID, where);
		}
		
		private void handleRequestClone(VerticalCommand cmd) throws IMTPException, NotFoundException {
			Object[] params = cmd.getParams();
			AID agentID = (AID)params[0];
			Location where = (Location)params[1];
			String newName = (String)params[2];
			
			copyAgent(agentID, where, newName);
		}
		
		private void handleInformMoved(VerticalCommand cmd) {
			// Nothing to do here: INFORM_MOVED has no target-side action...
		}
		
		private void handleInformCloned(VerticalCommand cmd) throws JADESecurityException, NotFoundException, NameClashException {
			Object[] params = cmd.getParams();
			AID agentID = (AID)params[0];
			ContainerID cid = (ContainerID)params[1];
			Credentials creds = (Credentials)params[2];
			
			clonedAgent(agentID, cid, creds);
		}
		
		private void moveAgent(AID agentID, Location where) throws IMTPException, NotFoundException {
			Agent a = myContainer.acquireLocalAgent(agentID);
			
			if(a == null) {
				throw new NotFoundException("Move-Agent failed to find " + agentID);
			}
			a.doMove(where);
			
			myContainer.releaseLocalAgent(agentID);
		}
		
		private void copyAgent(AID agentID, Location where, String newName) throws IMTPException, NotFoundException {
			Agent a = myContainer.acquireLocalAgent(agentID);
			
			if(a == null)
				throw new NotFoundException("Clone-Agent failed to find " + agentID);
			a.doClone(where, newName);
			
			myContainer.releaseLocalAgent(agentID);
		}
		
		// FIXME: adjust principal
		private void clonedAgent(AID agentID, ContainerID cid, Credentials credentials) throws JADESecurityException, NotFoundException, NameClashException {
			MainContainer impl = myContainer.getMain();
			if(impl != null) {
				// Retrieve the ownership from the credentials
				String ownership = "NONE";
				if (credentials != null) {
					JADEPrincipal ownerPr = credentials.getOwner();
					if (ownerPr != null) {
						ownership = ownerPr.getName();
					}
				}
				try {
					// If the name is already in the GADT, throws NameClashException
					impl.bornAgent(agentID, cid, null, ownership, false);
				}
				catch(NameClashException nce) {
					try {
						ContainerID oldCid = impl.getContainerID(agentID);
						Node n = impl.getContainerNode(oldCid).getNode();
						
						// Perform a non-blocking ping to check...
						n.ping(false);
						
						// Ping succeeded: rethrow the NameClashException
						throw nce;
					}
					catch(NameClashException nce2) {
						throw nce2; // Let this one through...
					}
					catch(Exception e) {
						// Ping failed: forcibly replace the dead agent...
						impl.bornAgent(agentID, cid, null, ownership, true);
					}
				}
			}
		}
		
		
	} // End of CommandTargetSink class
	
	
	//#J2ME_EXCLUDE_BEGIN
	private class CommandOutgoingFilter extends Filter {

		protected boolean accept(VerticalCommand cmd) {
			String name = cmd.getName();
			if (name.equals(AgentManagementSlice.INFORM_KILLED)) {
				try {
					handleInformKilled(cmd);
				} catch (NotFoundException nfe) {
					if (myLogger.isLoggable(Logger.WARNING))
						myLogger.log(Logger.WARNING,
								"CommandOutgoingFilter: Error deleting remote CodeLocator entry: " + nfe);
				} catch (ServiceException se) {
					if (myLogger.isLoggable(Logger.WARNING))
						myLogger.log(Logger.WARNING,
								"CommandOutgoingFilter: Error deleting remote CodeLocator entry: " + se);
				} catch (IMTPException imtpe) {
					if (myLogger.isLoggable(Logger.WARNING))
						myLogger.log(Logger.WARNING,
								"CommandOutgoingFilter: Error deleting remote CodeLocator entry: " + imtpe);
				}
				
			}
			
			return true;
		}
		
		private void handleInformKilled(VerticalCommand cmd) throws IMTPException, NotFoundException, ServiceException {
			
			Object[] params = cmd.getParams();
			AID target = (AID)params[0];

			//log("Source Sink consuming command INFORM_KILLED. Name is "+target.getName(), 3);
			if(myLogger.isLoggable(Logger.CONFIG))
				myLogger.log(Logger.CONFIG,"Outgoing Filer accepting command INFORM_KILLED. Name is "+target.getName());
			
			// Remove CodeLocator entry.
			String containerName = myContainer.getID().getName();
			Agent agent = myContainer.acquireLocalAgent(target);
			String codeContainerName = getClassSite(agent);
			myContainer.releaseLocalAgent(target);

			//Check if the agent have migrated or not.
			if (codeContainerName != null) {
		
				// Check if the code is in a remote container (if its local it has
				// been removed by the AgentManagementService).
				if (!containerName.equals(codeContainerName)) {

					//Send a REMOVE_CODE_LOCATOR_ENTRY command to the container with the agent code.
					AgentMobilitySlice codeSlice = (AgentMobilitySlice) getSlice(codeContainerName);
					try {
						codeSlice.removeCodeLocatorEntry(target);						
					} catch (IMTPException imtpe) {
						// Try to get a newer slice and repeat...
						codeSlice = (AgentMobilitySlice) getSlice(codeContainerName);
						codeSlice.removeCodeLocatorEntry(target);
					}
				}
			}
		}
	} // End of CommandOutgoingFilter class
	//#J2ME_EXCLUDE_END
	
	
	/**
	 Inner mix-in class for this service: this class receives
	 commands through its <code>Filter</code> interface and serves
	 them, coordinating with remote parts of this service through
	 the <code>Slice</code> interface (that extends the
	 <code>Service.Slice</code> interface).
	 */
	private class ServiceComponent implements Service.Slice {
		
		
		// Implementation of the Service.Slice interface
		
		public Service getService() {
			return AgentMobilityService.this;
		}
		
		public Node getNode() throws ServiceException {
			try {
				return AgentMobilityService.this.getLocalNode();
			}
			catch(IMTPException imtpe) {
				throw new ServiceException("Problem in contacting the IMTP Manager", imtpe);
			}
		}
		
		public VerticalCommand serve(HorizontalCommand cmd) {
			VerticalCommand result = null;
			try {
				String cmdName = cmd.getName();
				Object[] params = cmd.getParams();

				if(cmdName.equals(AgentMobilitySlice.H_CREATEAGENT)) {
					AID agentID = (AID)params[0];
					byte[] serializedInstance = (byte[])params[1];
					String classSiteName = (String)params[2];
					boolean isCloned = ((Boolean)params[3]).booleanValue();
					boolean startIt = ((Boolean)params[4]).booleanValue();
					
					createAgent(agentID, serializedInstance, classSiteName, isCloned, startIt);
				}
				else if(cmdName.equals(AgentMobilitySlice.H_FETCHCLASSFILE)) {
					String className = (String)params[0];
					String agentName = (String)params[1];
					
					cmd.setReturnValue(fetchClassFile(className, agentName));
				}
				else if(cmdName.equals(AgentMobilitySlice.H_MOVEAGENT)) {
					GenericCommand gCmd = new GenericCommand(AgentMobilityHelper.REQUEST_MOVE, AgentMobilitySlice.NAME, null);
					AID agentID = (AID)params[0];
					Location where = (Location)params[1];
					gCmd.addParam(agentID);
					gCmd.addParam(where);
					
					result = gCmd;
				}
				else if(cmdName.equals(AgentMobilitySlice.H_COPYAGENT)) {
					GenericCommand gCmd = new GenericCommand(AgentMobilityHelper.REQUEST_CLONE, AgentMobilitySlice.NAME, null);
					AID agentID = (AID)params[0];
					Location where = (Location)params[1];
					String newName = (String)params[2];
					gCmd.addParam(agentID);
					gCmd.addParam(where);
					gCmd.addParam(newName);
					
					result = gCmd;
				}
				else if(cmdName.equals(AgentMobilitySlice.H_PREPARE)) {
					
					cmd.setReturnValue(new Boolean(prepare()));

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -