org.rhq.enterprise.agent
Class AgentMain

java.lang.Object
  extended by org.rhq.enterprise.agent.AgentMain

public class AgentMain
extends Object

The main class of the agent runtime container.

Author:
John Mazzitelli

Constructor Summary
AgentMain()
          Constructor for AgentMain that loads the agent configuration and prepare some additional internal data.
AgentMain(String[] args)
          Constructor for AgentMain that accepts command line arguments, loads the agent configuration and prepare some additional internal data.
 
Method Summary
 void agentServerCommunicationsTrace(boolean enabled)
          This will enable/disable agent-server communication tracing.
 RemoteCommunicator createServerRemoteCommunicator(String transport, String address, int port, String transportParams)
          Creates a raw remote communicator that can talk to the given endpoint.
 FailoverListComposite downloadServerFailoverList()
          Downloads a new server failover list from the server and returns the failover list that is now in effect.
 boolean executePromptCommand(String command)
          A public method that allows any container object that has embedded this agent to execute prompt commands on this agent.
 String getAgentHomeDirectory()
          Returns the directory that is considered the "agent home" (i.e.
 AgentManagement getAgentManagementMBean()
          Returns the management MBean for this agent.
 AgentRegistrationResults getAgentRegistration()
          Returns non-null registration information if this agent successfully registered itself during this agent VM's lifetime.
 AgentRestartCounter getAgentRestartCounter()
          Returns the agent restart counter object.
 long getAgentServerClockDifference()
          Returns the number of milliseconds this agent thinks its clock is ahead or behind from its server's clock.
 ClientCommandSender getClientCommandSender()
          Returns the client sender which can be used to send commands to the server.
 AgentConfiguration getConfiguration()
          Returns the set of configuration preferences that the agent will use to configure things.
 mazz.i18n.Msg getI18NMsg()
          Returns the object that can be used to obtain I18N messages from the agent's resource bundle in the user's locale.
 AgentInputReader getIn()
          Returns the current input reader where the agent is getting its input.
 AgentPrintWriter getOut()
          Returns the output stream that displays messages to the user.
 Map<String,Class<? extends AgentPromptCommand>> getPromptCommands()
          Returns the map containing all the valid prompt command definitions.
 FailoverListComposite getServerFailoverList()
          Returns an iteratable list of servers that can be used as backups when this agent needs to failover to another server.
 ServiceContainer getServiceContainer()
          Returns the container that is managing our server-side communications services that accept and process incoming messages.
 long getStartTime()
          Returns the time (as reported by System.currentTimeMillis()) when the agent was started.
 String getUserInput(String prompt)
          Reads a line from the input stream and returns it.
 void hotDeployLogConfigurationFile(String logFilePath)
          This will hot-deploy a new log4j log configuration file.
 boolean isPluginContainerStarted()
          Returns true if the embedded plugin container has been started or false if its currently stopped.
 boolean isRegistered()
          Returns true if this agent is known to have previously been registered with the server.
 boolean isStarted()
          Returns true if the agent has started; false if the agent has either never been started or has been stopped.
 AgentConfiguration loadConfigurationFile(String file_name)
          Loads the given configuration file into the agent.
 AgentConfiguration loadConfigurationFile(String pref_node_name, String file_name)
          Same as loadConfigurationFile(String) except this allows you to indicate which preferences node the configuration is to be stored in.
static void main(String[] args)
          The main method that starts the whole thing.
 void overlaySystemPropertiesOnAgentConfiguration()
          This is an API that allows the caller to explicitly ensure that system properties are overlaid on top of the current agent configuration.
 void performPrimaryServerSwitchoverCheck()
          Asks the agent to check and see if it is currently connected to its primary server (as opposed to one of its secondary failover servers).
 void registerWithServer(long wait, boolean regenerate_token)
          This will send a registration request to the server.
 void serverClockNotification(long serverTime)
          This method should be called whenever the server time is known.
 void shutdown()
          Shuts down the agent gracefully.
 void shutdownPluginContainer()
          Shuts down the plugin container and all its child services and plugins.
 void start()
          This method will initialize all services and get the agent up and running.
 boolean startPluginContainer(long wait_for_registration)
          This starts up the plugin container.
 boolean switchToServer(String server)
          Tell the agent to immediately switch to another server.
 void updatePlugins()
          This asks that the agent update its plugins.
 boolean waitForServer(long wait_ms)
          This sleeps (blocking the calling thread) for at most the given number of milliseconds waiting for the RHQ Server to be discovered.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

AgentMain

public AgentMain()
          throws Exception
Constructor for AgentMain that loads the agent configuration and prepare some additional internal data.

Throws:
Exception - if failed to load the configuration properly

AgentMain

public AgentMain(String[] args)
          throws Exception
Constructor for AgentMain that accepts command line arguments, loads the agent configuration and prepare some additional internal data.

Parameters:
args - the command line arguments (may be null)
Throws:
Exception - if failed to load the configuration properly
Method Detail

main

public static void main(String[] args)
The main method that starts the whole thing.

Parameters:
args - the arguments passed on the command line (e.g. java org.rhq.enterprise.agent.AgentMain arg1 arg2 arg3)

getAgentHomeDirectory

public String getAgentHomeDirectory()
Returns the directory that is considered the "agent home" (i.e. the directory where the agent is installed).

Returns:
agent home directory, or empty string if it cannot be determined

isStarted

public boolean isStarted()
Returns true if the agent has started; false if the agent has either never been started or has been stopped.

Returns:
true if the agent is started; false if it is stopped.

isPluginContainerStarted

public boolean isPluginContainerStarted()
Returns true if the embedded plugin container has been started or false if its currently stopped.

Returns:
status of the plugin container

getStartTime

public long getStartTime()
Returns the time (as reported by System.currentTimeMillis()) when the agent was started. This returns 0 if the agent has been shutdown().

Returns:
time when the agent was started

getAgentServerClockDifference

public long getAgentServerClockDifference()
Returns the number of milliseconds this agent thinks its clock is ahead or behind from its server's clock. A positive value means the agent clock is ahead.

Returns:
time the agent-server clock difference

serverClockNotification

public void serverClockNotification(long serverTime)
This method should be called whenever the server time is known. This helps keep the getAgentServerClockDifference() up-to-date.

Parameters:
serverTime - the currently know value of the server clock (epoch millis)

start

public void start()
           throws Exception
This method will initialize all services and get the agent up and running.

Throws:
Exception - if failed to start

shutdown

public void shutdown()
Shuts down the agent gracefully.


getOut

public AgentPrintWriter getOut()
Returns the output stream that displays messages to the user.

Returns:
writer to which you can print messages to the user

getIn

public AgentInputReader getIn()
Returns the current input reader where the agent is getting its input. If null, this agent is in daemon mode and not currently accepting input.

Returns:
the input stream or null if the agent is not currently accepting input

getI18NMsg

public mazz.i18n.Msg getI18NMsg()
Returns the object that can be used to obtain I18N messages from the agent's resource bundle in the user's locale.

Returns:
object that can be used to obtain resource bundle messages

getConfiguration

public AgentConfiguration getConfiguration()
Returns the set of configuration preferences that the agent will use to configure things.

Returns:
configuration settings

getClientCommandSender

public ClientCommandSender getClientCommandSender()
Returns the client sender which can be used to send commands to the server. This may return null, which means the agent has been shutdown and it cannot send commands.

This is the agent's "remoting client".

Returns:
clientSender

getServiceContainer

public ServiceContainer getServiceContainer()
Returns the container that is managing our server-side communications services that accept and process incoming messages. This may return null, which means the agent has been shutdown and it cannot receive commands.

This is the agent's "remoting server".

Returns:
the service container that manages our communications services

getAgentManagementMBean

public AgentManagement getAgentManagementMBean()
Returns the management MBean for this agent. This is the MBean that provides management and monitoring functionality for this particular agent instance.

This will return null if the agent is not started or the management MBean was disabled.

Returns:
the agent management MBean instance

agentServerCommunicationsTrace

public void agentServerCommunicationsTrace(boolean enabled)
This will enable/disable agent-server communication tracing. This is for use mainly in development but can also be used for troubleshooting problems.

Parameters:
enabled - whether or not to turn on agent comm tracing

hotDeployLogConfigurationFile

public void hotDeployLogConfigurationFile(String logFilePath)
                                   throws Exception
This will hot-deploy a new log4j log configuration file. Use this to change, at runtime, the log settings so you can, for example, begin logging DEBUG messages to help troubleshoot problems.

Parameters:
logFilePath - the path to the log file - relative to the classloader or filesystem
Throws:
Exception - if failed to hot deploy the new log config

getServerFailoverList

public FailoverListComposite getServerFailoverList()
Returns an iteratable list of servers that can be used as backups when this agent needs to failover to another server.

Returns:
list of servers (may be empty but will not be null)

downloadServerFailoverList

public FailoverListComposite downloadServerFailoverList()
Downloads a new server failover list from the server and returns the failover list that is now in effect.

Returns:

performPrimaryServerSwitchoverCheck

public void performPrimaryServerSwitchoverCheck()
Asks the agent to check and see if it is currently connected to its primary server (as opposed to one of its secondary failover servers). If it is not connected to its primary, this call will trigger the agent to attempt to switch over. This switchover will occur asynchronously, and may not have occurred by the time this method returns. A side effect of this method is that the agent will also download a server failover list from its current server to make sure it is up-to-date.


getUserInput

public String getUserInput(String prompt)
Reads a line from the input stream and returns it. The given prompt will be displayed prior to reading stdin.

If prompt is null, the standard prompt is output.

If the input stream has been closed, null is returned.

Parameters:
prompt - the string that will be displayed to stdout before stdin is read
Returns:
line entered by the user
Throws:
RuntimeException - if failed to read input for some reason

getPromptCommands

public Map<String,Class<? extends AgentPromptCommand>> getPromptCommands()
Returns the map containing all the valid prompt command definitions. Map is keyed on the command string and the value is the Class of the AgentPromptCommand implementation.

Returns:
map of valid prompt commands

loadConfigurationFile

public AgentConfiguration loadConfigurationFile(String pref_node_name,
                                                String file_name)
                                         throws Exception
Same as loadConfigurationFile(String) except this allows you to indicate which preferences node the configuration is to be stored in. See the Java Preferences API for the definition of what a preferences node is.

Parameters:
pref_node_name - the node name that much match the node name in the configuration file that is to be loaded
file_name - the config file to load (should exist either on the file system or in the current thread's classloader)
Returns:
the properties that have been loaded from the given file wrapped in an AgentConfiguration object
Throws:
IllegalArgumentException - if the node name was invalid which occurs if the name has a forward slash (/) in it
IOException - if failed to load the configuration file
InvalidPreferencesFormatException - if the configuration file had an invalid format
BackingStoreException - if failed to access the preferences persistence store
Exception - on other failures

loadConfigurationFile

public AgentConfiguration loadConfigurationFile(String file_name)
                                         throws Exception
Loads the given configuration file into the agent. The file name will first be checked for existence on the file system. If it cannot be found, it will be assumed fileName specifies the file as found in the current class loader and the file will be searched there. An exception is thrown if the file cannot be found anywhere.

It is assumed that the agent's preference node name as defined by the -p command line argument is the one that matches the node name in the given configuration file.

The agent's configuration will be those settings found in the file - specifically, they are not overridden by system properties. If you want system properties to override any preferences found in the file, then you should call overlaySystemPropertiesOnAgentConfiguration() after this method returns

Parameters:
file_name - the config file to load (should exist either on the file system or in the current thread's classloader)
Returns:
the properties that have been loaded from the given file wrapped in an AgentConfiguration object
Throws:
IOException - if failed to load the configuration file
InvalidPreferencesFormatException - if the configuration file had an invalid format
BackingStoreException - if failed to access the preferences persistence store
Exception - on other failures

overlaySystemPropertiesOnAgentConfiguration

public void overlaySystemPropertiesOnAgentConfiguration()
This is an API that allows the caller to explicitly ensure that system properties are overlaid on top of the current agent configuration. You can use this after a call to loadConfigurationFile(String) when you want to allow system properties to override configuration preferences loaded from a file. Note that a runtime exception will be thrown if the agent has not yet loaded an initial configuration.

This method ignores AgentConfiguration.doNotOverridePreferencesWithSystemProperties() - in other words, this method will always overlay the system properties, even though the agent may have been configured not to. Use this method with caution since you are disobeying an agent configuration preference.


registerWithServer

public void registerWithServer(long wait,
                               boolean regenerate_token)
This will send a registration request to the server. This should be called when the agent has been started and sender has been created. It is public to allow anyone to ask the agent to re-register itself (such as via the register prompt command).

This registration process is asynchronous - this method returns immediately after spawning the thread unless the wait parameter is greater than 0. The registration will not be completed until the agent is able to successfully send a command to the server and get a response back. If the wait period is 0, the caller is not guaranteed this has happened when this method returns - the method return will only guarantee that the thread has been started. If the wait period is greater than 0, then when this method returns, the agent will have been registered or that amount of time has expired prior to successfully registering.

Parameters:
wait - the amount of time in milliseconds this method will wait for the registration process to complete before returning. If 0 or less, this method will not wait and will return as soon as the registration thread has started.
regenerate_token - if true, the agent will ask for a new token even if it was already assigned one. if false, the agent's existing token will not change.

getAgentRegistration

public AgentRegistrationResults getAgentRegistration()
Returns non-null registration information if this agent successfully registered itself during this agent VM's lifetime.

Returns:
agent registration information
See Also:
registerWithServer(long, boolean)

waitForServer

public boolean waitForServer(long wait_ms)
                      throws AgentNotSupportedException
This sleeps (blocking the calling thread) for at most the given number of milliseconds waiting for the RHQ Server to be discovered. This will return true if the server has come up and detected by the agent; false otherwise.

If wait_ms is 0 or less, this method will not wait at all; it will simply return the state of the server at is is known at the time the call is made.

Note that if the agent is shutdown, this method will not wait no matter what wait_ms is. If the agent is shutdown, false is returned immediately.

Parameters:
wait_ms - maximum number of milliseconds to wait
Returns:
true if the server is up, false if it is not yet up or the agent has shutdown
Throws:
AgentNotSupportedException - If the server is up but it told us we are the wrong version, then this is thrown. When this is thrown, the agent is currently in the midst of updating itself.

isRegistered

public boolean isRegistered()
Returns true if this agent is known to have previously been registered with the server. A false means this agent needs to register with the server before it can successfully communicate with the server.

Returns:
true if the agent is registered with the server

updatePlugins

public void updatePlugins()
This asks that the agent update its plugins. If the RHQ Server is already up and the agent has detected it, this method will immediately pull down the new/updated plugins. Otherwise, this will schedule the agent to update the plugins from the server once it comes up and the agent detects it.


startPluginContainer

public boolean startPluginContainer(long wait_for_registration)
This starts up the plugin container. The caller must ensure that the agent is either started or is being started. The plugin container must ensure that the agent is registered before it can be initialized, therefore, this method will ensure the agent is registered before starting the plugin container. If the agent is not registered, this method will wait for the agent to become registered for at most wait_for_registration millisecond. This method will wait indefinitely if that parameter's value is 0 or less. This method will also wait indefinitely until one or more plugins are available.

Parameters:
wait_for_registration - the amount of milliseconds this method will wait for the agent to become registered with the server; if 0 or less, this method blocks indefinitely
Returns:
true if the plugin container is started, false if it did not start

switchToServer

public boolean switchToServer(String server)
Tell the agent to immediately switch to another server. The given server can be a simple hostname in which case, the current transport, port and transport parameters being used to talk to the current server will stay the same. Otherwise, it will be assumed the server is a full endpoint URL.

Parameters:
server - the host of the server to switch to, or a full server endpoint URL
Returns:
true if successfully switched, false otherwise

getAgentRestartCounter

public AgentRestartCounter getAgentRestartCounter()
Returns the agent restart counter object.

Returns:
the agent restart counter

shutdownPluginContainer

public void shutdownPluginContainer()
Shuts down the plugin container and all its child services and plugins. If the plugin container has already been shutdown, this method does nothing and returns.


createServerRemoteCommunicator

public RemoteCommunicator createServerRemoteCommunicator(String transport,
                                                         String address,
                                                         int port,
                                                         String transportParams)
                                                  throws Exception
Creates a raw remote communicator that can talk to the given endpoint. This is public-scoped so the PrimaryServerSwitchoverThread can use this and the IdentifyPromptCommand can use this.

Parameters:
transport -
address -
port -
transportParams -
Returns:
the remote communicator
Throws:
Exception - if the communicator could not be created

executePromptCommand

public boolean executePromptCommand(String command)
                             throws Exception
A public method that allows any container object that has embedded this agent to execute prompt commands on this agent. This is useful if the container has another means by which it takes input from a user. Note, however, that if a prompt command requires additional input, it will use getIn() to read the input; so the caller must either ensure the input stream is valid or it must expect errors if it tries to execute those commands that require additional input.

Parameters:
command - the full command to execute, including the command name and arguments
Returns:
true if the prompt command hasn't shut the agent down, false if the agent was told by the prompt command to not accept any more input
Throws:
Exception


Copyright © 2008-2011 Red Hat, Inc.. All Rights Reserved.