/src/server/xmlprovider/src/keymind/keywatch/bundles/provider/xmlrpc/ServiceHandler.java
http://keywatch.googlecode.com/ · Java · 315 lines · 172 code · 54 blank · 89 comment · 29 complexity · 644406c55655d3b6180ffaf901e689a9 MD5 · raw file
- /**
- * -----------------------------------------------------------------------------------------------
- * File: ServiceHandler.java
- *
- * Copyright (c) 2007 by Keymind Computing as.
- * All rights reserved.
- *
- * This file is subject to the terms and conditions of the Apache Licence 2.0.
- * See the file LICENCE in the main directory of the Keywatch distribution for more details.
- *
- * Revision History (use svn log or TortoiseSVN):
- * $URL: http://keywatch.googlecode.com/svn/trunk/src/server/xmlprovider/src/keymind/keywatch/bundles/provider/xmlrpc/ServiceHandler.java $
- * $Date: 2009-08-10 13:12:17 +0200 (Mon, 10 Aug 2009) $
- * -----------------------------------------------------------------------------------------------
- */
- package keymind.keywatch.bundles.provider.xmlrpc;
-
- import keymind.keywatch.common.Log;
- import keymind.keywatch.domainmodel.eventDomain.*;
- import keymind.keywatch.services.eventmanagement.IEventManagement;
- import keymind.keywatch.services.eventmanagement.ITaskManagement;
-
- import java.util.Hashtable;
- import java.util.Date;
-
- /**
- * Handle incoming requests from agents
- */
- public class ServiceHandler implements Constants
- {
- private Context ctx;
- private Activator xmlProvider;
- private IEventManagement eventManager;
- private ITaskManagement taskManager;
- private Hashtable monitors;
-
- /**
- * C'tor
- */
- public ServiceHandler()
- {
- ctx = KeyXmlRpcServer.getCtx();
- xmlProvider = KeyXmlRpcServer.getXmlProvider();
- taskManager = KeyXmlRpcServer.getTaskManager();
- eventManager = KeyXmlRpcServer.getEventManager();
- monitors = KeyXmlRpcServer.getMonitors();
- }
-
-
- /**
- * Called by Java agents upon startup.
- *
- * @param agentHostId Unique host identifier. This may be a host name or an IP address.
- * @param agentPort Port number of agent. If 0, PORT_AGENT_DEFAULT will be used.
- * @param urlSuffix Optional URL suffix, such as "RPC2" which would yield "http://ip:agentPort/RPC2"
- * @param props A potentially empty string of task properties for the agent. Example: "labels=xyx,abc;timeout=20"
- * @return A boolean holding the result from handleAgentRegistration
- */
- public synchronized boolean OnAgentStartedEx(String agentHostId, int agentPort, String urlSuffix, String props)
- {
- return handleAgentRegistration(agentHostId, agentPort, urlSuffix, props);
- }
-
-
- /**
- * Called by agent upon startup. This causes the agents and all its jobs to
- * be registered as tasks under the provider task.
- *
- * @param hostId Unique host identifier. This may be a host name or an IP address.
- * @return A boolean holding the result from handleAgentRegistration
- */
- public boolean OnAgentStarted(String hostId)
- {
- return handleAgentRegistration(hostId, DEFAULT_AGENT_PORT, XMLRPC_SUFFIX, "");
- }
-
- /**
- * Called just before the agent terminates itself
- *
- * @param hostId Unique host identifier. This may be a host name or an IP address.
- * @param reason Reason for termination
- * @return True
- */
- public boolean OnAgentTerminated(String hostId, String reason)
- {
- Event event = new Event();
- event.setCreated(new Date(System.currentTimeMillis()));
- event.setName("Agent down");
- event.setHost(hostId);
-
- event.setShortDescription("The agent at '" + hostId + "' has terminated itself.");
- event.setLongDescription(reason);
-
- Severity severity = new Severity();
- severity.setEnumerator(SEVERITY_FATAL);
- event.setSeverity(severity);
- event.setProvider(null);
-
- IEventManagement eventMgmt = KeyXmlRpcServer.getEventManager();
- eventMgmt.putEvent(KeyXmlRpcServer.getCtx(), event);
-
- // Update running flag. This will prevent the agent monitor from generating an
- // unnecessary 'agent down' event.
- Task task = KeyXmlRpcServer.getTaskManager().getTaskByName(
- KeyXmlRpcServer.getCtx(), PROVIDER_NAME + "/" + hostId);
-
- if(task != null)
- {
- task.setIsRunning(Boolean.FALSE);
- KeyXmlRpcServer.getTaskManager().putTask(KeyXmlRpcServer.getCtx(), task);
- }
-
- return true;
- }
-
- /**
- * Generic agent registration
- *
- * @param agentHostId Host id of agent
- * @param agentPort Port to use to talk to agent
- * @param urlSuffix Suffix to append to URL
- * @param propertyList List of properties
- * @return boolean status of registration
- */
- private boolean handleAgentRegistration(String agentHostId, int agentPort, String urlSuffix, String propertyList)
- {
- boolean res = false;
-
- try
- {
- Log.info(Constants.PROVIDER_AGENT_REGISTERING_PREFIX + agentHostId);
-
- // Get a fresh tree to work on
- Task rootTask = KeyXmlRpcServer.getXmlProvider().getRootTask(KeyXmlRpcServer.getCtx());
- rootTask = KeyXmlRpcServer.getTaskManager().getTaskByName(KeyXmlRpcServer.getCtx(),
- rootTask.getName());
-
- // The name of the agent task is '<providername>/<hostname>', since only using
- // the host name would cause conflicts when more than one type of agent runs
- // on the same host.
- String agentTaskName = rootTask.getName() + "/" + agentHostId;
-
- // This means that the host name, as provided by the agent, must be
- // 1) an ip address, or 2) a registered host name, either in a name server or
- // the local hosts file
- String url = "http://" + agentHostId + ":" + agentPort + "/";
- if (urlSuffix != null && urlSuffix.length() > 0)
- {
- url += urlSuffix;
- }
-
- Task agentTask = KeyXmlRpcServer.findByName(rootTask, agentTaskName);
- if (agentTask == null)
- {
- agentTask = new Task();
- agentTask.setParentTask(rootTask);
- agentTask.setName(agentTaskName);
- agentTask.setIsActive(true);
- agentTask.setUrl(url);
- agentTask.setHost(agentHostId);
-
- // Default monitor rate is 1 minute
- agentTask.setMonitorRate(Constants.MONITOR_RATE_DEFAULT_MIN);
-
- // Update list of childs by copying the existing list (if any) and appending the new task
- KeyXmlRpcServer.addSubTask(rootTask, agentTask);
- }
- else
- {
- agentTask.setHost(agentHostId);
- }
-
- // Add/update properties supplied by the agent
- if (propertyList != null && propertyList.length() > 0)
- {
- propertyList = propertyList.trim();
- String[] props = propertyList.split(";");
-
- for (int i = 0; i < props.length; i++)
- {
- String prop = props[i];
-
- String[] keyval = prop.split("=");
- if (keyval != null && keyval.length == 2)
- {
- Property newProp = new Property();
- newProp.setName(keyval[0].trim());
- newProp.setValue(keyval[1].trim());
-
- KeyXmlRpcServer.setTaskProperty(agentTask, newProp);
- }
- }
- }
-
- // The agent is obviously running...
- agentTask.setIsRunning(true);
- agentTask.setIsActive(true);
-
- // Get jobs
- KeyXmlRpcClient c = new KeyXmlRpcClient(url);
-
- Job[] jobs = c.GetJobStatusAll();
-
- if (jobs != null)
- {
- for (int i = 0; i < jobs.length; i++)
- {
- Task jobTask = KeyXmlRpcServer.findByName(agentTask, jobs[i].getSignature());
-
- if (jobTask == null)
- {
- jobTask = new Task();
- jobTask.setParentTask(agentTask);
- jobTask.setName(jobs[i].getSignature());
- jobTask.setHost(agentHostId);
-
- // Set host property and add subtask to agent
- KeyXmlRpcServer.addSubTask(agentTask, jobTask);
- }
- else
- {
- // Set host property
- jobTask.setHost(agentHostId);
- }
-
- jobTask.setUrl(url);
- jobTask.setIsActive(jobs[i].isActive());
- jobTask.setSchedule(jobs[i].getSchedule());
-
- // Assume daemon scripts are running initially... it is too early to ask for
- // actual running status since the agent is just starting up.
- jobTask.setIsRunning(jobs[i].isDaemon());
-
- // Add 'labels' property?
- if (jobs[i].labels != null && jobs[i].labels.length() > 0)
- {
- Property[] jobProps = jobTask.getProperties();
-
- Property match = null;
- for (int j = 0; jobProps != null && j < jobProps.length; j++)
- {
- if (jobProps[j].getName().equals(PROPERTY_KEY_LABELS))
- {
- match = jobProps[j];
- break;
- }
- }
-
- // This means we only set the 'labels' once; further updates the props
- // must occur on the server.
- Property jobProp = new Property();
- jobProp.setName(PROPERTY_KEY_LABELS);
- jobProp.setValue(jobs[i].labels);
-
- // Add or update property
- KeyXmlRpcServer.setTaskProperty(jobTask, jobProp);
- }
-
- }// foreach job
-
- KeyXmlRpcServer.softDeleteMissingJobs(agentTask, jobs);
- }
-
- // Update the tree and refresh the cached version
- KeyXmlRpcServer.getTaskManager().updateTaskTree(ctx, rootTask);
- xmlProvider.setRootTask(ctx, taskManager.getTaskByName(ctx, rootTask.getName()));
-
- // We registered correctly and that's what the agent needs to know (even if
- // the monitoring setup below fails)
- res = true;
-
- /* Start monitoring the agent */
-
- // Make sure we get an agent Task instance with proper id set (since this may well
- // be the first time the agent registers and thus a new instance has been created.)
- agentTask = taskManager.getTaskByName(ctx, agentTask.getName());
-
- // Remove old monitor to reset stuff
- Thread oldMonitor = (Thread)monitors.get(url);
- if (oldMonitor != null)
- {
- oldMonitor.interrupt();
- }
-
- Thread monitorThread = new Thread(
- new AgentMonitor(ctx, agentTask, taskManager, eventManager));
-
- monitors.put(url, monitorThread);
-
- // Start monitoring
- monitorThread.start();
-
- Log.info(Constants.PROVIDER_AGENT_REGISTERED_PREFIX + agentHostId);
- }
- catch (Exception e)
- {
- Log.error(e.toString());
- }
-
- return res;
- }
-
-
- /**
- * Get properties
- *
- * @param keypattern A key, which may be partial
- * @return a string of properties
- */
- public String[] GetProperties(String keypattern)
- {
- return new String[0];
- }
-
- }// ServiceHandler