List<AgentInfo> stateUpdatedAgents = newArrayList(0);
Set<AgentIdentity> allAttachedAgents = getAgentManager().getAllAttachedAgents();
Map<String, AgentControllerIdentityImplementation> attachedAgentMap = newHashMap(allAttachedAgents);
for (AgentIdentity agentIdentity : allAttachedAgents) {
AgentControllerIdentityImplementation existingAgent = cast(agentIdentity);
attachedAgentMap.put(createKey(existingAgent), existingAgent);
}
Map<String, AgentInfo> agentsInDBMap = Maps.newHashMap();
// step1. check all agents in DB, whether they are attached to
// controller.
for (AgentInfo eachAgentInDB : getAllLocal()) {
String keyOfAgentInDB = createKey(eachAgentInDB);
agentsInDBMap.put(keyOfAgentInDB, eachAgentInDB);
AgentControllerIdentityImplementation agentIdentity = attachedAgentMap.remove(keyOfAgentInDB);
if (agentIdentity != null) {
// if the agent attached to current controller
if (!isCurrentRegion(agentIdentity)) {
if (eachAgentInDB.getState() != WRONG_REGION) {
eachAgentInDB.setApproved(false);
eachAgentInDB.setRegion(getConfig().getRegion());
eachAgentInDB.setState(WRONG_REGION);
updatedAgents.add(eachAgentInDB);
}
} else if (!hasSameInfo(eachAgentInDB, agentIdentity)) {
fillUp(eachAgentInDB, agentIdentity);
updatedAgents.add(eachAgentInDB);
} else if (!hasSameState(eachAgentInDB, agentIdentity)) {
eachAgentInDB.setState(getAgentManager().getAgentState(agentIdentity));
stateUpdatedAgents.add(eachAgentInDB);
} else if (eachAgentInDB.getApproved() == null) {
updatedAgents.add(fillUpApproval(eachAgentInDB));
}
} else { // the agent in DB is not attached to current controller
if (eachAgentInDB.getState() != INACTIVE) {
eachAgentInDB.setState(INACTIVE);
stateUpdatedAgents.add(eachAgentInDB);
}
}
}
// step2. check all attached agents, whether they are new, and not saved
// in DB.
for (AgentControllerIdentityImplementation agentIdentity : attachedAgentMap.values()) {
AgentInfo agentInfo = agentManagerRepository.findByIpAndHostName(
agentIdentity.getIp(),
agentIdentity.getName());
if (agentInfo == null) {
agentInfo = new AgentInfo();
newAgents.add(fillUp(agentInfo, agentIdentity));
} else {
updatedAgents.add(fillUp(agentInfo, agentIdentity));