blib/lib/Ubic/Daemon.pm untested

filter: Statementstmt 0.0% 0 / 322 Branchbran 0.0% 0 / 126 Conditioncond 0.0% 0 / 68 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 23 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 546 SCAR 83.3
CC
64
Cov
0%
start_daemon
1560.0
check_daemon
110.0
stop_daemon
90.0
CRAP 4160.0
1 package Ubic::Daemon;
2 $Ubic::Daemon::VERSION = '1.59';
3 use strict;
4 use warnings;
5  
6 # ABSTRACT: daemon management utilities
7  
8  
9 use IO::Handle;
10 use IO::Select;
11 use POSIX qw(setsid :sys_wait_h);
12 use Time::HiRes qw(sleep);
13 use Params::Validate qw(:all);
14 use Carp;
15 use Config;
16  
17 use Ubic::Lockf;
18 use Ubic::AccessGuard;
19 use Ubic::Daemon::Status;
20 use Ubic::Daemon::PidState;
21  
22 use parent qw(Exporter);
23 our @EXPORT_OK = qw(start_daemon stop_daemon check_daemon);
24 our %EXPORT_TAGS = (
25 all => \@EXPORT_OK,
26 );
27  
28 our $OS;
29 sub import {
30 my %module = (
31 linux => 'Linux',
32 );
33  
34 # UBIC_DAEMON_OS support is here only for tests
35 my $module = $ENV{UBIC_DAEMON_OS} || $module{$^O} || 'POSIX';
36  
37 require "Ubic/Daemon/OS/$module.pm";
38 $OS = eval "Ubic::Daemon::OS::$module->new";
39 unless ($OS) {
40 die "failed to initialize OS-specific module $module: $@";
41 }
42 __PACKAGE__->export_to_level(1, @_);
43 }
44  
45 {
46 my @signame;
47 sub _signame {
48 my $signum = shift;
49 unless (@signame) {
50 @signame = split /\s+/, $Config{sig_name};
51 }
52 return $signame[$signum];
53  
54 }
55 }
56  
57 sub _log {
58 my $fh = shift;
59 return unless defined $fh;
60 print {$fh} '[', scalar(localtime), "]\t$$\t", @_, "\n";
61 }
62  
63 sub _log_exit_code {
64 my ($fh, $code, $pid) = @_;
65 if ($code == 0) {
66 _log($fh, "daemon $pid exited");
67 return;
68 }
69  
70 my $msg = "daemon $pid failed with \$? = $?";
71 if (my $signal = $? & 127) {
72 my $signame = _signame($signal);
73 if (defined $signame) {
74 $msg = "daemon $pid failed with signal $signame ($signal)";
75 }
76 else {
77 $msg = "daemon $pid failed with signal $signal";
78 }
79 }
80 elsif ($? & 128) {
81 $msg = "daemon $pid failed, core dumped";
82 }
83 elsif (my $code = $? >> 8) {
84 $msg = "daemon $pid failed, exit code $code";
85 }
86 _log($fh, $msg);
87 }
88  
89 sub stop_daemon($;@) {
90 my ($pidfile, @tail) = validate_pos(@_, { type => SCALAR }, 0);
91 my $options = validate(@tail, {
92 timeout => { default => 30, regex => qr/^\d+$/ },
93 });
94 my $timeout = $options->{timeout} if defined $options->{timeout};
95  
96 # TODO - move this check into Ubic::Daemon::PidState
97 my $pid_state = Ubic::Daemon::PidState->new($pidfile);
98 return 'not running' if $pid_state->is_empty;
99  
100 my $piddata = $pid_state->read;
101 unless ($piddata) {
102 return 'not running';
103 }
104 my $pid = $piddata->{pid};
105  
106 unless (check_daemon($pidfile)) {
107 return 'not running';
108 }
109 kill 15 => $pid;
110 my $trial = 1;
111 {
112 my $sleep = 0.1;
113 my $total_sleep = 0;
114 while (1) {
115 unless (check_daemon($pidfile)) {
116 return 'stopped';
117 }
118 last if $total_sleep >= $timeout;
119 sleep($sleep);
120 $total_sleep += $sleep;
121 $sleep += 0.1 * $trial if $sleep < 1;
122 $trial++;
123 }
124 }
125 unless (check_daemon($pidfile)) {
126 return 'stopped';
127 }
128 die "failed to stop daemon with pidfile '$pidfile' (pid $pid, timeout $timeout, trials $trial)";
129 }
130  
131 sub start_daemon($) {
132 my %options = validate(@_, {
133 bin => { type => SCALAR | ARRAYREF, optional => 1 },
134 function => { type => CODEREF, optional => 1 },
135 name => { type => SCALAR, optional => 1 },
136 pidfile => { type => SCALAR },
137 stdout => { type => SCALAR, default => '/dev/null' },
138 stderr => { type => SCALAR, default => '/dev/null' },
139 ubic_log => { type => SCALAR, optional => 1 },
140 term_timeout => { type => SCALAR, default => 10, regex => qr/^\d+$/ },
141 cwd => { type => SCALAR, optional => 1 },
142 env => { type => HASHREF, optional => 1 },
143 proxy_logs => { type => BOOLEAN, optional => 1 },
144 credentials => { isa => 'Ubic::Credentials', optional => 1 },
145 start_hook => { type => CODEREF, optional => 1 },
146 });
147 my ($bin, $function, $name, $pidfile, $stdout, $stderr, $ubic_log, $term_timeout, $cwd, $env, $credentials, $start_hook, $proxy_logs)
148 = @options{qw/ bin function name pidfile stdout stderr ubic_log term_timeout cwd env credentials start_hook proxy_logs /};
149 if (not defined $bin and not defined $function) {
150 croak "One of 'bin' and 'function' should be specified";
151 }
152 if (defined $bin and defined $function) {
153 croak "Only one of 'bin' and 'function' should be specified";
154 }
155 unless (defined $name) {
156 if (ref $bin) {
157 $name = join ' ', @$bin;
158 }
159 else {
160 $name = $bin || 'anonymous';
161 }
162 }
163  
164 if (check_daemon($pidfile)) {
165 croak "Daemon with pidfile $pidfile already running, can't start";
166 }
167  
168 my $pid_state = Ubic::Daemon::PidState->new($pidfile);
169 $pid_state->init;
170  
171 pipe my ($read_pipe, $write_pipe) or die "pipe failed";
172 my $child;
173  
174 unless ($child = fork) {
175 die "fork failed" unless defined $child;
176  
177 my $ubic_fh;
178 my $lock;
179 my $instant_exit = sub {
180 close($ubic_fh) if $ubic_fh;
181 STDOUT->flush;
182 STDERR->flush;
183 undef $lock;
184 POSIX::_exit(0); # don't allow any cleanup to happen - this process was forked from unknown environment, don't want to run unknown destructors
185 };
186  
187 eval {
188 close($read_pipe) or die "Can't close read pipe: $!";
189 # forking child - will reopen standard streams, daemonize itself, fork into daemon binary and wait for it
190  
191 {
192 my $tmp_pid = fork() and POSIX::_exit(0); # detach from parent process
193 die "fork failed" unless defined $tmp_pid;
194 }
195  
196 # Close all inherited filehandles except $write_pipe (it will be closed explicitly).
197 # Do not close fh if uses 'function' option instead of 'bin'
198 # ('function' support should be removed altogether because of this, actually; it's evil).
199 if ($bin) {
200 my $write_pipe_fd_num = fileno($write_pipe);
201 $OS->close_all_fh($write_pipe_fd_num); # except pipe
202 }
203  
204 my $open_handles_sub = sub {
205 my $guard;
206 $guard = Ubic::AccessGuard->new($credentials) if $credentials;
207 open STDOUT, ">>", $stdout or die "Can't write to '$stdout': $!";
208 open STDERR, ">>", $stderr or die "Can't write to '$stderr': $!";
209 STDOUT->autoflush(1);
210 STDERR->autoflush(1);
211 if (defined $ubic_log) {
212 open $ubic_fh, ">>", $ubic_log or die "Can't write to '$ubic_log': $!";
213 $ubic_fh->autoflush(1);
214 }
215 };
216 $open_handles_sub->();
217 my $stdin = '/dev/null';
218 open STDIN, "<", $stdin or die "Can't read from '$stdin': $!";
219  
220 $SIG{HUP} = 'ignore';
221 $0 = "ubic-guardian $name";
222 setsid; # ubic-daemon gets it's own session
223 _log($ubic_fh, "guardian name: $0");
224  
225 _log($ubic_fh, "obtaining lock...");
226  
227 # We're passing 'timeout' option to lockf call to get rid of races.
228 # There should be no races when Ubic::Daemon is used in context of
229 # ubic service, because services have an additional lock, but
230 # Ubic::Daemon can be useful without services as well.
231 $lock = $pid_state->lock(5) or die "Can't lock $pid_state";
232  
233 $pid_state->remove;
234 _log($ubic_fh, "got lock");
235  
236 my %daemon_pipes;
237 if (defined $proxy_logs) {
238 for my $handle (qw/stdout stderr/) {
239 pipe my ($read, $write) or die "pipe for daemon $handle failed";
240 $daemon_pipes{$handle} = {read => $read, write => $write};
241 }
242 }
243 my $child;
244 if ($child = fork) {
245 # guardian
246  
247 _log($ubic_fh, "guardian pid: $$");
248 _log($ubic_fh, "daemon pid: $child");
249  
250 my $child_guid = $OS->pid2guid($child);
251 unless ($child_guid) {
252 if ($OS->pid_exists($child)) {
253 die "Can't detect guid";
254 }
255 $? = 0;
256 unless (waitpid($child, WNOHANG) == $child) {
257 die "No pid $child but waitpid didn't collect $child status";
258 }
259 _log_exit_code($ubic_fh, $?, $child);
260 $pid_state->remove();
261 die "daemon exited immediately";
262 }
263 _log($ubic_fh, "child guid: $child_guid");
264 $pid_state->write({ pid => $child, guid => $child_guid });
265  
266 my $kill_sub = sub {
267 if ($term_timeout) {
268 _log($ubic_fh, "SIGTERM timeouted after $term_timeout second(s)");
269 }
270 _log($ubic_fh, "sending SIGKILL to $child");
271 kill -9 => $child;
272 _log($ubic_fh, "daemon $child probably killed by SIGKILL");
273 $pid_state->remove();
274 $instant_exit->();
275 };
276  
277 my $sigterm_sent;
278 $SIG{TERM} = sub {
279 if ($term_timeout > 0) {
280 $SIG{ALRM} = $kill_sub;
281 alarm($term_timeout);
282 _log($ubic_fh, "sending SIGTERM to $child");
283 kill -15 => $child;
284 $sigterm_sent = 1;
285 }
286 else {
287 $kill_sub->();
288 }
289 };
290 print {$write_pipe} "pidfile written\n" or die "Can't write to pipe: $!";
291 close $write_pipe or die "Can't close pipe: $!";
292 undef $write_pipe;
293  
294 if (defined $proxy_logs) {
295 $SIG{HUP} = sub {
296 eval { $open_handles_sub->() };
297 if ($@) {
298 _log($ubic_fh, "failed to reopen stdout/stderr handles: $@");
299 $kill_sub->();
300 }
301 else {
302 _log($ubic_fh, "reopened stdout/stderr");
303 }
304 };
305  
306 for my $handle (qw/stdout stderr/) {
307 close($daemon_pipes{$handle}{write}) or do {
308 _log($ubic_fh, "Can't close $handle write: $!");
309 die "Can't close $handle write: $!"
310 };
311 }
312 my $sel = IO::Select->new();
313 $sel->add($daemon_pipes{stdout}{read}, $daemon_pipes{stderr}{read});
314 my $BUFF_SIZE = 4096;
315 READ:
316 while ($OS->pid_exists($child)) { # this loop is needed because of timeout in can_read
317 while (my @ready = $sel->can_read(1)) {
318 my $exhausted = 0;
319 for my $handle (@ready) {
320 my $data;
321 my $bytes_read = sysread($handle, $data, $BUFF_SIZE);
322 die "Can't poll $handle: $!" unless defined $bytes_read; # handle EWOULDBLOCK?
323 $exhausted += 1 if $bytes_read == 0;
324 if (fileno $handle == fileno $daemon_pipes{stdout}{read}) {
325 print STDOUT $data;
326 }
327 if (fileno $handle == fileno $daemon_pipes{stderr}{read}) {
328 print STDERR $data;
329 }
330 }
331 last READ if $exhausted == @ready;
332 }
333 }
334 }
335  
336 $? = 0;
337 waitpid($child, 0);
338 my $code = $?;
339 if ($sigterm_sent and ($code & 127) == &POSIX::SIGTERM) {
340 # it's ok, we probably sent this signal ourselves
341 _log($ubic_fh, "daemon $child exited by sigterm");
342 }
343 else {
344 _log_exit_code($ubic_fh, $code, $child);
345 }
346 $pid_state->remove;
347 }
348 else {
349 # daemon
350  
351 die "fork failed" unless defined $child;
352  
353 # start new process group - become immune to kills at parent group and at the same time be able to kill all processes below
354 setpgrp;
355 $0 = "ubic-daemon $name";
356  
357 if (defined $cwd) {
358 chdir $cwd or die "chdir to '$cwd' failed: $!";
359 }
360 if (defined $env) {
361 for my $key (keys %{ $env }) {
362 $ENV{$key} = $env->{$key};
363 }
364 }
365 $start_hook->() if $start_hook;
366 $credentials->set() if $credentials;
367  
368 close($ubic_fh) if defined $ubic_fh;
369 $lock->dissolve;
370  
371 print {$write_pipe} "execing into daemon\n" or die "Can't write to pipe: $!";
372 close($write_pipe) or die "Can't close pipe: $!";
373 undef $write_pipe;
374  
375 if (defined $proxy_logs) {
376 # redirecting standard streams to pipes
377 close($daemon_pipes{$_}{read}) or die "Can't close $_ read: $!" for qw/stdout stderr/;
378 open STDOUT, '>&=', $daemon_pipes{stdout}{write} or die "Can't open stdout write: $!";
379 open STDERR, '>&=', $daemon_pipes{stderr}{write} or die "Can't open stderr write: $!";
380 }
381  
382 # finally, run underlying binary
383 if (ref $bin) {
384 exec(@$bin) or die "exec failed: $!";
385 }
386 elsif ($bin) {
387 exec($bin) or die "exec failed: $!";
388 }
389 else {
390 $function->();
391 }
392 }
393 };
394 if ($write_pipe) {
395 print {$write_pipe} "Error: $@\n";
396 $write_pipe->flush;
397 }
398 $instant_exit->();
399 }
400 waitpid($child, 0); # child should've exited immediately
401 close($write_pipe) or die "Can't close write_pipe: $!";
402  
403 my $out = '';
404 while ( my $data = <$read_pipe>) {
405 $out .= $data;
406 }
407 close($read_pipe) or die "Can't close read_pipe: $!";
408 if ($out =~ /^execing into daemon$/m and $out =~ /^pidfile written$/m) {
409 # TODO - check daemon's name to make sure that exec happened
410 return;
411 }
412 die "Failed to create daemon: '$out'";
413 }
414  
415 sub check_daemon {
416 my $pidfile = shift;
417 my $options = validate(@_, {
418 quiet => { optional => 1 },
419 });
420  
421 my $print = sub {
422 print @_, "\n" unless $options->{quiet};
423 };
424  
425 my $pid_state = Ubic::Daemon::PidState->new($pidfile);
426 return undef if $pid_state->is_empty;
427  
428 my $lock = $pid_state->lock;
429 my $piddata = $pid_state->read;
430 unless ($lock) {
431 # locked => daemon is alive
432 return Ubic::Daemon::Status->new({ pid => $piddata->{daemon}, guardian_pid => $piddata->{pid} });
433 }
434  
435 unless ($piddata) {
436 return undef;
437 }
438  
439 # acquired lock when pidfile exists
440 # checking whether just ubic-guardian died or whole process group
441 if ($piddata->{format} and $piddata->{format} eq 'old') {
442 die "deprecated pidfile format detected\n";
443 }
444 unless ($piddata->{daemon}) {
445 use Data::Dumper;
446 die "pidfile $pidfile exists, but daemon pid is not saved in it, so existing unguarded daemon can't be killed (piddata: ".Dumper($piddata).")";
447 }
448 unless ($OS->pid_exists($piddata->{daemon})) {
449 $pid_state->remove;
450 $print->("pidfile $pidfile removed - daemon with cached pid $piddata->{daemon} not found");
451 return undef;
452 }
453  
454 # TODO - wrap in eval and return undef if pid2cmd fails?
455 my $daemon_cmd = $OS->pid2cmd($piddata->{daemon});
456  
457 my $guid = $OS->pid2guid($piddata->{daemon});
458 unless ($guid) {
459 $print->("daemon '$daemon_cmd' from $pidfile just disappeared");
460 return undef;
461 }
462 if ($guid eq $piddata->{guid}) {
463 $print->("killing unguarded daemon '$daemon_cmd' with pid $piddata->{daemon} from $pidfile");
464 kill -9 => $piddata->{daemon};
465 $pid_state->remove;
466 $print->("pidfile $pidfile removed");
467 return undef;
468 }
469 $print->("daemon pid $piddata->{daemon} cached in pidfile $pidfile, ubic-guardian not found");
470 $print->("current process '$daemon_cmd' with pid $piddata->{daemon} has wrong guid ($piddata->{guid}, expected $guid) and will not be killed");
471 $print->("removing pidfile $pidfile");
472 $pid_state->remove;
473 return undef;
474 }
475  
476  
477 1;
478  
479 __END__