Class ServiceLauncher<S extends Service>
java.lang.Object
org.apache.hadoop.service.launcher.ServiceLauncher<S>
- Type Parameters:
S- service class to cast the generated service to.
- All Implemented Interfaces:
Thread.UncaughtExceptionHandler,LauncherArguments,LauncherExitCodes
public class ServiceLauncher<S extends Service>
extends Object
implements LauncherExitCodes, LauncherArguments, Thread.UncaughtExceptionHandler
A class to launch any YARN service by name.
It's designed to be subclassed for custom entry points.
Workflow:
- An instance of the class is created. It must be of the type
Service - If it implements
LaunchableService.bindArgs(Configuration, List), it is given the binding args off the CLI after all general configuration arguments have been stripped. - Its
Service.init(Configuration)andService.start()methods are called. - If it implements it,
LaunchableService.execute()is called and its return code used as the exit code. - Otherwise: it waits for the service to stop, assuming that the
Service.start()method spawns one or more thread to perform work - If any exception is raised and provides an exit code,
that is, it implements
ExitCodeProvider, the return value ofExitCodeProvider.getExitCode(), becomes the exit code of the command.
stderr.-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected static classA generic options parser which does not parse any of the traditional Hadoop options. -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected static final String[]List of the standard configurations to create (and so load in properties).static final StringThe name of this class.protected static final intPriority for the shutdown hook: 30.static final StringUsage message.protected static final Stringprotected static final StringFields inherited from interface org.apache.hadoop.service.launcher.LauncherArguments
ARG_CONF, ARG_CONF_PREFIXED, ARG_CONF_SHORT, ARG_CONFCLASS, ARG_CONFCLASS_PREFIXED, ARG_CONFCLASS_SHORT, E_PARSE_FAILEDFields inherited from interface org.apache.hadoop.service.launcher.LauncherExitCodes
EXIT_BAD_CONFIGURATION, EXIT_CLIENT_INITIATED_SHUTDOWN, EXIT_COMMAND_ARGUMENT_ERROR, EXIT_CONNECTIVITY_PROBLEM, EXIT_EXCEPTION_THROWN, EXIT_FAIL, EXIT_FORBIDDEN, EXIT_INTERRUPTED, EXIT_NOT_ACCEPTABLE, EXIT_NOT_FOUND, EXIT_OPERATION_NOT_ALLOWED, EXIT_OTHER_FAILURE, EXIT_SERVICE_CREATION_FAILURE, EXIT_SERVICE_LIFECYCLE_EXCEPTION, EXIT_SERVICE_UNAVAILABLE, EXIT_SUCCESS, EXIT_TASK_LAUNCH_FAILURE, EXIT_UNAUTHORIZED, EXIT_UNIMPLEMENTED, EXIT_UNSUPPORTED_VERSION, EXIT_USAGE -
Constructor Summary
ConstructorsConstructorDescriptionServiceLauncher(String serviceClassName) Create an instance of the launcher.ServiceLauncher(String serviceName, String serviceClassName) Create an instance of the launcher. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidSet thecommandOptionsfield to the result ofcreateOptions(); protected for subclasses and test access.protected static ExitUtil.ExitExceptionconvertToExitException(Throwable thrown) Convert an exception to anExitException.protected intcoreServiceLaunch(Configuration conf, S instance, List<String> processedArgs, boolean addShutdownHook, boolean execute) Launch the service.protected ConfigurationOverride point: create the base configuration for the service.protected GenericOptionsParsercreateGenericOptionsParser(Configuration conf, String[] argArray) Override point: create a generic options parser or subclass thereof.protected org.apache.commons.cli.OptionsOverride point: create an options instance to combine with the standard options set.protected voidReport an error.protected voidExit the JVM.protected voidExit the JVM using an exception for the exit code and message, invokingExitUtil.terminate(ExitUtil.ExitException).protected static voidexitWithMessage(int status, String message) Exit with a printed message.protected static voidExit with the usage exit codeLauncherExitCodes.EXIT_USAGEand messageUSAGE_MESSAGE.extractCommandOptions(Configuration conf, List<String> args) Extract the command options and apply them to the configuration, building an array of processed arguments to hand down to the service.protected ClassLoaderOverride point: get the classloader to use.final ConfigurationGet the configuration constructed from the command line arguments.Override point: Get a list of configuration classes to create.final SGet the service.final ExitUtil.ExitExceptionGet the exit exception used to end this service.final intThe exit code from a successful service execution.Get the service name viaService.getName().protected StringGet the usage message, ideally dynamically.launchService(Configuration conf, List<String> processedArgs, boolean addShutdownHook, boolean execute) Launch a service catching all exceptions and downgrading them to exit codes after logging.launchService(Configuration conf, S instance, List<String> processedArgs, boolean addShutdownHook, boolean execute) Launch a service catching all exceptions and downgrading them to exit codes after logging.voidlaunchServiceAndExit(List<String> args) Launch the service and exit.intstatic voidThis is the JVM entry point for the service launcher.parseCommandArgs(Configuration conf, List<String> args) Parse the command arguments, extracting the service class as the last element of the list (after extracting all the rest).protected voidOverride point: register this class as the handler for the control-C and SIGINT interrupts.protected ServiceLaunchExceptionserviceCreationFailure(Exception exception) Generate an exception announcing a failure to create the service.static voidserviceMain(String... args) Varargs version of the entry point for testing and other in-JVM use.static voidserviceMain(List<String> argsList) The real main function, which takes the arguments as a list.protected voidsetService(S s) Setter is to give subclasses the ability to manipulate the service.protected static StringstartupShutdownMessage(String classname, List<String> args) toString()voiduncaughtException(Thread thread, Throwable exception) Handler for uncaught exceptions: terminate the service.protected voidverifyConfigurationFilesExist(String[] filenames) Verify that all the specified filenames exist.protected voidPrint a warning message.
-
Field Details
-
SHUTDOWN_PRIORITY
protected static final int SHUTDOWN_PRIORITYPriority for the shutdown hook: 30.- See Also:
-
NAME
The name of this class.- See Also:
-
USAGE_NAME
- See Also:
-
USAGE_SERVICE_ARGUMENTS
- See Also:
-
USAGE_MESSAGE
Usage message. Text: "Usage: ServiceLauncher [--conf <conf file>] [--hadoopconf <configuration classname>] service-classname <service arguments>"- See Also:
-
DEFAULT_CONFIGS
List of the standard configurations to create (and so load in properties). The values are Hadoop, HDFS and YARN configurations.
-
-
Constructor Details
-
ServiceLauncher
Create an instance of the launcher.- Parameters:
serviceClassName- classname of the service
-
ServiceLauncher
Create an instance of the launcher.- Parameters:
serviceName- name of service for text messagesserviceClassName- classname of the service
-
-
Method Details
-
getService
Get the service. Null untilcoreServiceLaunch(Configuration, Service, List, boolean, boolean)has completed.- Returns:
- the service
-
setService
Setter is to give subclasses the ability to manipulate the service.- Parameters:
s- the new service
-
getConfiguration
Get the configuration constructed from the command line arguments.- Returns:
- the configuration used to create the service
-
getServiceExitCode
public final int getServiceExitCode()The exit code from a successful service execution.- Returns:
- the exit code.
-
getServiceException
Get the exit exception used to end this service.- Returns:
- an exception, which will be null until the service
has exited (and
System.exithas not been called)
-
toString
-
launchServiceAndExit
Launch the service and exit.- Parse the command line.
- Build the service configuration from it.
- Start the service.
- If it is a
LaunchableService: execute it - Otherwise: wait for it to finish.
- Exit passing the status code to the
exit(int, String)method.
- Parameters:
args- arguments to the service.arg[0]is assumed to be the service classname.
-
bindCommandOptions
protected void bindCommandOptions()Set thecommandOptionsfield to the result ofcreateOptions(); protected for subclasses and test access. -
getUsageMessage
Get the usage message, ideally dynamically.- Returns:
- the usage message
-
createOptions
protected org.apache.commons.cli.Options createOptions()Override point: create an options instance to combine with the standard options set. Important. Synchronize uses ofOptionwithOption.class- Returns:
- the new options
-
createConfiguration
Override point: create the base configuration for the service. Subclasses can override to create HDFS/YARN configurations etc.- Returns:
- the configuration to use as the service initializer.
-
getConfigurationsToCreate
Override point: Get a list of configuration classes to create.- Returns:
- the array of configs to attempt to create. If any are off the classpath, that is logged
-
loadConfigurationClasses
@VisibleForTesting public int loadConfigurationClasses()- Returns:
- This creates all the configurations defined by
getConfigurationsToCreate(), ensuring that the resources have been pushed in. If one cannot be loaded it is logged and the operation continues except in the case that the class does load but it isn't actually a subclass ofConfiguration. - Throws:
ExitUtil.ExitException- if a loaded class is of the wrong type
-
launchService
public ExitUtil.ExitException launchService(Configuration conf, List<String> processedArgs, boolean addShutdownHook, boolean execute) Launch a service catching all exceptions and downgrading them to exit codes after logging. SetsserviceExceptionto this value.- Parameters:
conf- configuration to useprocessedArgs- command line after the launcher-specific arguments have been stripped out.addShutdownHook- should a shutdown hook be added to terminate this service on shutdown. Tests should set this to false.execute- execute/wait for the service to stop.- Returns:
- an exit exception, which will have a status code of 0 if it worked
-
launchService
public ExitUtil.ExitException launchService(Configuration conf, S instance, List<String> processedArgs, boolean addShutdownHook, boolean execute) Launch a service catching all exceptions and downgrading them to exit codes after logging. SetsserviceExceptionto this value.- Parameters:
conf- configuration to useinstance- optional instance of the service.processedArgs- command line after the launcher-specific arguments have been stripped out.addShutdownHook- should a shutdown hook be added to terminate this service on shutdown. Tests should set this to false.execute- execute/wait for the service to stop.- Returns:
- an exit exception, which will have a status code of 0 if it worked
-
coreServiceLaunch
protected int coreServiceLaunch(Configuration conf, S instance, List<String> processedArgs, boolean addShutdownHook, boolean execute) throws Exception Launch the service. All exceptions that occur are propagated upwards. If the method returns a status code, it means that it got as far starting the service, and if it implementsLaunchableService, that the methodLaunchableService.execute()has completed. After this method returns, the service can be retrieved returned bygetService().- Parameters:
conf- configurationinstance- optional instance of the service.processedArgs- arguments after the configuration parameters have been stripped out.addShutdownHook- should a shutdown hook be added to terminate this service on shutdown. Tests should set this to false.execute- execute/wait for the service to stop- Returns:
- status code.
- Throws:
ClassNotFoundException- classname not on the classpathIllegalAccessException- not allowed at the classInstantiationException- not allowed to instantiate itInterruptedException- thread interruptedExitUtil.ExitException- any exception defining the status code.Exception- any other failure -if it implementsExitCodeProviderthen it defines the exit code for any containing exception
-
instantiateService
- Parameters:
conf- configuration to use- Returns:
- Instantiate the service defined in
serviceClassName. Sets theconfigurationfield to the the value ofconf, and theservicefield to the service created.
-
convertToExitException
Convert an exception to anExitException. This process may just be a simple pass through, otherwise a new exception is created with an exit code, the text of the supplied exception, and the supplied exception as an inner cause.- If is already the right type, pass it through.
- If it implements
ExitCodeProvider.getExitCode(), the exit code is extracted and used in the new exception. - Otherwise, the exit code
LauncherExitCodes.EXIT_EXCEPTION_THROWNis used.
- Parameters:
thrown- the exception thrown- Returns:
- an
ExitExceptionwith a status code
-
serviceCreationFailure
Generate an exception announcing a failure to create the service.- Parameters:
exception- inner exception.- Returns:
- a new exception, with the exit code
LauncherExitCodes.EXIT_SERVICE_CREATION_FAILURE
-
registerFailureHandling
protected void registerFailureHandling()Override point: register this class as the handler for the control-C and SIGINT interrupts. Subclasses can extend this with extra operations, such as an exception handler:Thread.setDefaultUncaughtExceptionHandler( new YarnUncaughtExceptionHandler()); -
uncaughtException
Handler for uncaught exceptions: terminate the service.- Specified by:
uncaughtExceptionin interfaceThread.UncaughtExceptionHandler- Parameters:
thread- threadexception- exception
-
getServiceName
Get the service name viaService.getName(). If the service is not instantiated, the classname is returned instead.- Returns:
- the service name
-
warn
Print a warning message.This tries to log to the log's warn() operation. If the log at that level is disabled it logs to system error
- Parameters:
text- warning text
-
error
Report an error.This tries to log to
LOG.error().If that log level is disabled disabled the message is logged to system error along with
thrown.toString()- Parameters:
message- message for the userthrown- the exception thrown
-
exit
Exit the JVM. This is method can be overridden for testing, throwing an exception instead. Any subclassed method MUST raise anExitExceptioninstance/subclass. The service launcher code assumes that after this method is invoked, no other code in the same method is called.- Parameters:
exitCode- code to exitmessage- input message.
-
exit
Exit the JVM using an exception for the exit code and message, invokingExitUtil.terminate(ExitUtil.ExitException). This is the standard way a launched service exits. An error code of 0 means success -nothing is printed. IfExitUtil.disableSystemExit()has been called, this method will throw the exception. The method may be subclassed for testing- Parameters:
ee- exit exception- Throws:
ExitUtil.ExitException- if ExitUtil exceptions are disabled
-
getClassLoader
Override point: get the classloader to use.- Returns:
- the classloader for loading a service class.
-
extractCommandOptions
Extract the command options and apply them to the configuration, building an array of processed arguments to hand down to the service.- Parameters:
conf- configuration to update.args- main arguments.args[0]is assumed to be the service classname and is skipped.- Returns:
- the remaining arguments
- Throws:
ExitUtil.ExitException- if JVM exiting is disabled.
-
parseCommandArgs
Parse the command arguments, extracting the service class as the last element of the list (after extracting all the rest). The fieldcommandOptionsfield must already have been set.- Parameters:
conf- configuration to useargs- command line argument list- Returns:
- the remaining arguments
- Throws:
ServiceLaunchException- if processing of arguments failed
-
createGenericOptionsParser
protected GenericOptionsParser createGenericOptionsParser(Configuration conf, String[] argArray) throws IOException Override point: create a generic options parser or subclass thereof.- Parameters:
conf- Hadoop configurationargArray- array of arguments- Returns:
- a generic options parser to parse the arguments
- Throws:
IOException- on any failure
-
verifyConfigurationFilesExist
Verify that all the specified filenames exist.- Parameters:
filenames- a list of files- Throws:
ServiceLaunchException- if a file is not found
-
startupShutdownMessage
- Parameters:
classname- the class of the serverargs- arguments- Returns:
- Build a log message for starting up and shutting down.
-
exitWithMessage
Exit with a printed message.- Parameters:
status- status codemessage- message message to print before exiting- Throws:
ExitUtil.ExitException- if exceptions are disabled
-
exitWithUsageMessage
protected static void exitWithUsageMessage()Exit with the usage exit codeLauncherExitCodes.EXIT_USAGEand messageUSAGE_MESSAGE.- Throws:
ExitUtil.ExitException- if exceptions are disabled
-
main
This is the JVM entry point for the service launcher. Converts the arguments to a list, then invokesserviceMain(List)- Parameters:
args- command line arguments.
-
serviceMain
Varargs version of the entry point for testing and other in-JVM use. Hands off toserviceMain(List)- Parameters:
args- command line arguments.
-
serviceMain
The real main function, which takes the arguments as a list. Argument 0 MUST be the service classname- Parameters:
argsList- the list of arguments
-