ControlFreak
view release on metacpan or search on metacpan
#!/usr/bin/env perl
use strict;
use warnings;
use File::Spec();
BEGIN {
if (-f File::Spec->catfile(qw(lib ControlFreak.pm))) {
require Find::Lib;
Find::Lib->import('lib');
}
}
use Getopt::Long;
use AnyEvent();
use AnyEvent::Socket();
use ControlFreak;
use Carp;
use Pod::Usage;
use POSIX 'SIGTERM';
my %options = ();
GetOptions(
"a|address=s" => \$options{address},
"d|daemon" => \$options{daemon},
"t|trap" => \$options{trap},
"home=s" => \$options{home},
"log-config-file" => \$options{log_config_file},
'h|help' => \$options{help},
'm|man' => \$options{man},
);
pod2usage(1) if $options{help};
pod2usage(-verbose => 2) if $options{man};
my $ctrl;
## make home, and export it in ENV
my $home = $options{home} || File::Spec->catdir($ENV{HOME}, '.controlfreak');
mkdir $home unless -d $home;
$ENV{CFKD_HOME} = $home;
## specify a default address in the form of a unix socket in $home
$options{address} = "unix:$home/sock"
unless $options{address};
my $log_config_file = $options{log_config_file};
if (! $log_config_file) {
## look at the default location and create it if it doesn't exist
$log_config_file = File::Spec->catfile($home, "log.config");
unless (-f $log_config_file) {
open LC, ">$log_config_file"
or croak "Cannot create $log_config_file: $!";
print LC ${ ControlFreak::Logger->default_config };
close LC;
chmod 0622, $log_config_file;
}
}
daemonize() if $options{daemon};
my $unix = ControlFreak::Util::parse_unix($options{address});
my $host;
my $service;
if ($unix) {
$host = "unix/";
$service = $unix;
}
else {
($host, $service) = AnyEvent::Socket::parse_hostport(
$options{address},
'11311',
);
}
$ctrl = ControlFreak->new(
log_config_file => $log_config_file,
home => $home,
);
my $console = ControlFreak::Console->new(
host => $host,
service => $service,
ctrl => $ctrl,
);
my $w = AnyEvent->signal(signal => "USR1", cb => sub {
$ctrl->log->safe_reinit;
});
$ctrl->set_console($console);
$ctrl->console->start;
## probably need to deal with signals
AnyEvent->condvar->recv;
sub daemonize {
my $pid;
my $sess_id;
## Fork and exit parent
if ($pid = fork) { exit 0; }
## Detach ourselves from the terminal
croak "Cannot detach from controlling terminal"
unless $sess_id = POSIX::setsid();
## Prevent possibility of acquiring a controlling terminal
$SIG{'HUP'} = 'IGNORE';
if ($pid = fork) { exit 0; }
## Change working directory
## to avoid locking a network filesystem or something
chdir "/";
( run in 1.730 second using v1.01-cache-2.11-cpan-cdf2f3d4e48 )