View on
Ivan Kruglov > HADaemon-Control-0.5 > HADaemon::Control



Annotate this POD

View/Report Bugs
Module Version: 0.5   Source   Latest Release: HADaemon-Control-1.003


HADaemon::Control - Create init scripts for Perl high-available (HA) daemons


HADaemon::Control provides a library for creating init scripts for HA daemons in perl. It allows you to run one or more main processes accompanied by a set of standby processes. Standby processes constantly check presence of main ones and if later exits or dies promote themselves and replace gone main processes. By doing so, HADaemon::Control achieves high-availability and fault tolerance for a service provided by the deamon. Your perl script just needs to set the accessors for what and how you want something to run and the library takes care of the rest.

The library takes idea and interface from Daemon::Control and combine them with facilities of IPC::ConcurrencyLimit::WithStandby. IPC::ConcurrencyLimit::WithStandby implements a mechanism to limit the number of concurrent processes in a cooperative multiprocessing environment. For more information refer to the documentation of IPC::ConcurrencyLimit and IPC::ConcurrencyLimit::WithStandby


    #!/usr/bin/env perl

    use strict;
    use warnings;
    use HADaemon::Control;

    my $dc = HADaemon::Control->new({
        name => '',
        user => 'nobody',
        pid_dir => '/tmp/test',
        log_file => '/tmp/test.log',
        program => sub { sleep 10; },

    exit $dc->run();

You can then call the program:

    /usr/bin/ start

By default run will use @ARGV for the action, and exit with an LSB compatible exit code. For finer control, you can use run_command, which will return the exit code, and accepts the action as an argument. This enables more programatic control, as well as running multiple instances of HADaemon::Control from one script.

    my $dc = HADaemon::Control->new({

    my $exit = $daemon->run_command(“start”);


The constructor takes the following arguments.


The name of the program the daemon is controlling. This will be used in status messages. See also process_name_change.


This should be a coderef of actual programm to run.

    $daemon->program( sub { ... } );


This is an array ref of the arguments for the program. Args will be given to the program coderef as @_, the HADaemon::Control instance that called the coderef will be passed as the first arguments. Your arguments start at $_[1].

    $daemon->program_args( [ 'foo', 'bar' ] );


This option defines directory where all pidfile will be created



This option gives ability to tune settings of underlying IPC::ConcurrencyLimit::WithStandby object. By default HADaemon::Control sets following settings:

    ipc_cl_options => {
        type              => 'Flock',                             # the only supported type
        max_procs         => 1,                                   # one main process
        standby_max_procs => 1,                                   # one standby process
        interval          => 1,                                   # stanby tries to acquire main lock every second
        retries           => sub { 1 },                           # keep retrying forever
        path              => $daemon->pid_dir . '/lock/',         # path for main locks
        standby_path      => $daemon->pid_dir . '/lock-standby/', # path for standby locks


This option provides an alternative way of stopping main processes apart of sending a signal (ex. TERM). If specified, HADaemon::Control touch this file and wait kill_timeout seconds hoping that main processes will respect the file and exit. If not, normal termination loop is entered (i.e. sending sequence of signals TERM TERM INT KILL). The filename can include %p which is replaced by PID of a process. Default value is undef.


The path to stop file for standby process. See do_start, do_stop, do_restart for details. By default is set to:

    $daemon->standby_stop_file($daemon->pid_dir . '/standby-stop-file');


HADaemon::Control uses log_file for two purposes:

If you don't want to mix logs of the application and init script consider using stdout_file and stderr_file. Verbosity of logs of HADaemon::Control can be controled by HADC_TRACE environment variable.


If set, HADaemon::Control will set name of the process to name. Also, it adds process_name_change option into ipc_cl_options. As result, process_name_change makes nice names for both main and standby processes. For example:

    my $dc = HADaemon::Control->new({
        name => 'My test daemon',
        pid_dir => '/tmp/test',
        log_file => '/tmp/test.log',
        program => sub { sleep 10; },
        process_name_change => 1,

leads to:

    My test daemon              # name of main process
    My test daemon - standby    # name of standby process


When set, the username supplied to this accessor will be used to set the UID attribute. When this is used, uid will be changed from its initial settings if you set it (which you shouldn't, since you're using usernames instead of UIDs). See "uid" for setting numerical user ids.



When set, the groupname supplied to this accessor will be used to set the GID attribute. When this is used, gid will be changed from its initial settings if you set it (which you shouldn't, since you're using groupnames instead of GIDs). See "gid" for setting numerical group ids.



If provided, the UID that the program will drop to when forked. This will only work if you are running as root. Accepts numeric UID. For usernames please see "user".

    $daemon->uid( 1001 );


If provided, the GID that the program will drop to when forked. This will only work if you are running as root. Accepts numeric GID, for groupnames please see "group".

    $daemon->gid( 1001 );


If provided, the umask of the daemon will be set to the umask provided, note that the umask must be in oct. By default the umask will not be changed.

    $daemon->umask( 022 );


    $daemon->umask( oct("022") );


If provided, chdir to this directory before execution.


If provided stdout of main process will be redirected to the given file.

    $daemon->stdout_file( "/tmp/mydaemon.stdout" );


If provided stderr of main process will be redirected to the given file.

    $daemon->stderr_file( "/tmp/mydaemon.stderr" );


This provides an amount of time in seconds between kill signals being sent to the daemon. This value should be increased if your daemon has a longer shutdown period. By default 1 second is used.

    $daemon->kill_timeout( 7 );


If this boolean flag is set to a true value all output from the init script (NOT your daemon) to STDOUT will be suppressed.

    $daemon->quiet( 1 );


The constructor also takes the following arguments to generate init file. See "do_get_init_file".


The path of the script you are using HADaemon::Control in. This will be used in the LSB file generation to point it to the location of the script. If this is not provided, the absolute path of $0 will be used.


The name of the init config file to load. When provided your init script will source this file to include the environment variables. This is useful for setting a PERL5LIB and such things.

    $daemon->init_config( "/etc/default/my_program" );

    If you are using perlbrew, you probably want to set your init_config to
    C<$ENV{PERLBREW_ROOT} . '/etc/bashrc'>.


When given, whatever text is in this field will be dumped directly into the generated init file.

    $daemon->init_code( "Arbitrary code goes here." )


The value of this string is used for the 'Required-Start' value of the generated LSB init script. See for more information.

    $daemon->lsb_start( '$remote_fs $syslog' );


The value of this string is used for the 'Required-Stop' value of the generated LSB init script. See for more information.

    $daemon->lsb_stop( '$remote_fs $syslog' );


The value of this string is used for the 'Short-Description' value of the generated LSB init script. See for more information.

    $daemon->lsb_sdesc( 'My program...' );


The value of this string is used for the 'Description' value of the generated LSB init script. See for more information.

    $daemon->lsb_desc( 'My program controls a thing that does a thing.' );



This function will process an action on the HADaemon::Control instance. Valid arguments are those which a do_ method exists for, such as start, stop, restart. Returns the LSB exit code for the action processed.


This will make your program act as an init file, accepting input from the command line. Run will exit with 0 for success and uses LSB exit codes. As such no code should be used after ->run is called. Any code in your file should be before this. This is a shortcut for

    exit HADaemon::Control->new(...)->run_command( @ARGV );


Is called when start is given as an argument. Starts the forking and exits. The forking includes starting ipc_cl_options-{max_procs}> main and ipc_cl_options-{standby_max_procs}> standby processes. Exit with success only if all processes were spawned. Called by:

    /usr/bin/ start


Is called when stop is given as an argument. Stops the all running proceses which belongs to the daemon if it can. Stopping is done via:

Called by:

    /usr/bin/ stop


Is called when restart is given as an argument. This command triggers restart cycle which includes several steps:

Called by:

    /usr/bin/ restart


Is called when hard_restart is given as an argument. Calls do_stop and do_start. Called by:

    /usr/bin/ hard_restart


Is called when fork is given as an argument. This command is almost equal to do_start, but is design for periodical run in a cronjob. Called by:

    /usr/bin/ fork


Is called when reload is given as an argument. Sends a HUP signal to the main processes.

    /usr/bin/ reload


Is called when status is given as an argument. Displays the statuses of the program (i.e. all running processes), basic on the PID files. Called by:

    /usr/bin/ status


Is called when foreground is given as an argument. Starts the program or code reference and stays in the foreground -- no forking and locking is done, regardless of the compile-time arguments. Additionally, turns quiet on to avoid showing HADaemon::Control output.

    /usr/bin/ foreground


Is called when get_init_file is given as an argument. Dumps an LSB compatible init file, for use in /etc/init.d/. Called by:

    /usr/bin/ get_init_file


This is used to display status to the user. It accepts a message and a color. It will default to green text, if no color is explicitly given. Only supports red and green. If HADC_NO_COLORS environment variable is set no colors are used.

    $daemon->pretty_print( "My Status", "red" );


Ivan Kruglov,


This module was inspired by module Daemon::Control.

This module was originally developed for With approval from, this module was generalized and put on CPAN, for which the authors would like to express their gratitude.


(C) 2013, 2014 Ivan Kruglov. All rights reserved.

This code is available under the same license as Perl version 5.8.1 or higher.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.


The most current version of HADaemon::Control can be found at

syntax highlighting: