1 package PVE::RESTEnvironment;
3 # NOTE: you can/should provide your own specialice class, and
4 # use this a bas class (as example see PVE::RPCEnvironment).
6 # we use this singleton class to pass RPC related environment values
10 use POSIX qw(:sys_wait_h EINTR);
15 use PVE::Exception qw(raise raise_perm_exc);
24 # save $SIG{CHLD} handler implementation.
25 # simply set $SIG{CHLD} = $worker_reaper;
26 # and register forked processes with &$register_worker(pid)
27 # Note: using $SIG{CHLD} = 'IGNORE' or $SIG{CHLD} = sub { wait (); } or ...
28 # has serious side effects, because perls built in system() and open()
29 # functions can't get the correct exit status of a child. So we cant use
30 # that (also see perlipc)
35 my $log_task_result = sub {
36 my ($upid, $user, $status) = @_;
40 my $msg = 'successful';
43 my $ec = $status >> 8;
44 my $ic = $status & 255;
45 $msg = $ec ? "failed ($ec)" : "interrupted ($ic)";
49 my $tlist = $rest_env->active_workers($upid);
50 $rest_env->broadcast_tasklist($tlist);
53 foreach my $t (@$tlist) {
54 if ($t->{upid} eq $upid) {
59 if ($task && $task->{status}) {
60 $msg = $task->{status};
63 $rest_env->log_cluster_msg($pri, $user, "end task $upid $msg");
66 my $worker_reaper = sub {
68 foreach my $pid (keys %$WORKER_PIDS) {
69 my $waitpid = waitpid ($pid, WNOHANG);
70 if (defined($waitpid) && ($waitpid == $pid)) {
71 my $info = $WORKER_PIDS->{$pid};
72 if ($info && $info->{upid} && $info->{user}) {
73 &$log_task_result($info->{upid}, $info->{user}, $?);
75 delete ($WORKER_PIDS->{$pid});
80 my $register_worker = sub {
81 my ($pid, $user, $upid) = @_;
85 # do not register if already finished
86 my $waitpid = waitpid ($pid, WNOHANG);
87 if (defined($waitpid) && ($waitpid == $pid)) {
88 delete ($WORKER_PIDS->{$pid});
92 $WORKER_PIDS->{$pid} = {
98 # initialize environment - must be called once at program startup
100 my ($class, $type, %params) = @_;
102 $class = ref($class) || $class;
104 die "already initialized" if $rest_env;
106 die "unknown environment type"
107 if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
109 $SIG{CHLD} = $worker_reaper;
112 # cli ... command started fron command line
113 # pub ... access from public server (apache)
114 # priv ... access from private server (pvedaemon)
115 # ha ... access from HA resource manager agent (rgmanager)
117 my $self = { type => $type };
121 foreach my $p (keys %params) {
122 if ($p eq 'atfork') {
123 $self->{$p} = $params{$p};
125 die "unknown option '$p'";
131 my ($sysname, $nodename) = POSIX::uname();
133 $nodename =~ s/\..*$//; # strip domain part, if any
135 $self->{nodename} = $nodename;
140 # convenience function for command line tools
141 sub setup_default_cli_env {
142 my ($class, $username) = @_;
144 $class = ref($class) || $class;
146 $username //= 'root@pam';
148 PVE::INotify::inotify_init();
150 my $rpcenv = $class->init('cli');
151 $rpcenv->init_request();
152 $rpcenv->set_language($ENV{LANG});
153 $rpcenv->set_user($username);
155 die "please run as root\n"
156 if ($username eq 'root@pam') && ($> != 0);
162 die "REST environment not initialized" if !$rest_env;
168 my ($self, $ip) = @_;
170 $self->{client_ip} = $ip;
176 return $self->{client_ip};
179 sub set_result_attrib {
180 my ($self, $key, $value) = @_;
182 $self->{result_attributes}->{$key} = $value;
185 sub get_result_attrib {
186 my ($self, $key) = @_;
188 return $self->{result_attributes}->{$key};
192 my ($self, $lang) = @_;
194 # fixme: initialize I18N
196 $self->{language} = $lang;
202 return $self->{language};
206 my ($self, $user) = @_;
208 $self->{user} = $user;
212 my ($self, $noerr) = @_;
214 return $self->{user} if defined($self->{user}) || $noerr;
216 die "user name not set\n";
225 # read/update list of active workers
226 # we move all finished tasks to the archive index,
227 # but keep aktive and most recent task in the active file.
228 # $nocheck ... consider $new_upid still running (avoid that
229 # we try to read the reult to early.
231 my ($self, $new_upid, $nocheck) = @_;
233 my $lkfn = "/var/log/pve/tasks/.active.lock";
239 my $tasklist = PVE::INotify::read_file('active');
243 my $thash = {}; # only list task once
245 my $check_task = sub {
246 my ($task, $running) = @_;
248 if ($running || PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart})) {
254 delete $task->{pstart};
257 foreach my $task (@$tasklist) {
258 my $upid = $task->{upid};
259 next if $thash->{$upid};
260 $thash->{$upid} = $task;
264 if ($new_upid && !(my $task = $thash->{$new_upid})) {
265 $task = PVE::Tools::upid_decode($new_upid);
266 $task->{upid} = $new_upid;
267 $thash->{$new_upid} = $task;
268 &$check_task($task, $nocheck);
272 @ta = sort { $b->{starttime} cmp $a->{starttime} } @ta;
274 my $save = defined($new_upid);
276 foreach my $task (@ta) {
277 next if $task->{endtime};
278 $task->{endtime} = time();
279 $task->{status} = PVE::Tools::upid_read_status($task->{upid});
285 foreach my $task (@ta) {
286 if (!$task->{saved}) {
287 $archive .= sprintf("%s %08X %s\n", $task->{upid}, $task->{endtime}, $task->{status});
296 my $filename = "/var/log/pve/tasks/index";
298 my $fh = IO::File->new($filename, '>>', 0644) ||
299 die "unable to open file '$filename' - $!\n";
300 PVE::Tools::safe_print($filename, $fh, $archive);
303 die "unable to close file '$filename' - $!\n";
308 foreach my $task (@arlist) { # mark as not saved
312 my $maxsize = 50000; # about 1000 entries
313 if ($size > $maxsize) {
314 rename($filename, "$filename.1");
318 # we try to reduce the amount of data
319 # list all running tasks and task and a few others
320 # try to limit to 25 tasks
322 my $max = 25 - scalar(@$tlist);
323 foreach my $task (@ta) {
329 PVE::INotify::write_file('active', $tlist) if $save;
334 my $res = PVE::Tools::lock_file($lkfn, $timeout, $code);
340 my $kill_process_group = sub {
341 my ($pid, $pstart) = @_;
343 # send kill to process group (negative pid)
346 # always send signal to all pgrp members
347 kill(15, $kpid); # send TERM signal
349 # give max 5 seconds to shut down
350 for (my $i = 0; $i < 5; $i++) {
351 return if !PVE::ProcFSTools::check_process_running($pid, $pstart);
360 my ($self, $upid, $killit) = @_;
362 my $task = PVE::Tools::upid_decode($upid);
364 my $running = PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart});
366 return 0 if !$running;
369 &$kill_process_group($task->{pid});
376 # start long running workers
377 # STDIN is redirected to /dev/null
378 # STDOUT,STDERR are redirected to the filename returned by upid_decode
379 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
381 my ($self, $dtype, $id, $user, $function, $background) = @_;
383 $dtype = 'unknown' if !defined ($dtype);
384 $id = '' if !defined ($id);
386 $user = 'root@pve' if !defined ($user);
388 my $sync = ($self->{type} eq 'cli' && !$background) ? 1 : 0;
393 local $SIG{TERM} = 'IGNORE';
395 my $starttime = time ();
397 my @psync = POSIX::pipe();
398 my @csync = POSIX::pipe();
400 my $node = $self->{nodename};
403 die "unable to fork worker - $!" if !defined($cpid);
405 my $workerpuid = $cpid ? $cpid : $$;
407 my $pstart = PVE::ProcFSTools::read_proc_starttime($workerpuid) ||
408 die "unable to read process start time";
410 my $upid = PVE::Tools::upid_encode ({
411 node => $node, pid => $workerpuid, pstart => $pstart,
412 starttime => $starttime, type => $dtype, id => $id, user => $user });
416 if (!$cpid) { # child
421 $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub { die "received interrupt\n"; };
423 $SIG{CHLD} = $SIG{PIPE} = 'DEFAULT';
425 # set sess/process group - we want to be able to kill the
426 # whole process group
429 POSIX::close ($psync[0]);
430 POSIX::close ($csync[1]);
432 $outfh = $sync ? $psync[1] : undef;
435 PVE::INotify::inotify_close();
437 if (my $atfork = $self->{atfork}) {
441 # same algorythm as used inside SA
443 my $fd = fileno (STDIN);
447 POSIX::close(0) if $fd != 0;
449 die "unable to redirect STDIN - $!"
450 if !open(STDIN, "</dev/null");
452 $outfh = PVE::Tools::upid_open($upid);
457 $fd = fileno(STDOUT);
459 POSIX::close (1) if $fd != 1;
461 die "unable to redirect STDOUT - $!"
462 if !open(STDOUT, ">&", $outfh);
464 STDOUT->autoflush (1);
466 # redirect STDERR to STDOUT
467 $fd = fileno (STDERR);
469 POSIX::close(2) if $fd != 2;
471 die "unable to redirect STDERR - $!"
472 if !open(STDERR, ">&1");
474 STDERR->autoflush(1);
477 my $msg = "ERROR: $err";
478 POSIX::write($psync[1], $msg, length ($msg));
479 POSIX::close($psync[1]);
484 # sync with parent (signal that we are ready)
488 POSIX::write($psync[1], $upid, length ($upid));
489 POSIX::close($psync[1]);
493 # sync with parent (wait until parent is ready)
494 POSIX::read($csync[0], $readbuf, 4096);
495 die "parent setup error\n" if $readbuf ne 'OK';
497 if ($self->{type} eq 'ha') {
498 print "task started by HA resource agent\n";
500 eval { &$function($upid); };
506 print STDERR "TASK ERROR: $err\n";
509 print STDERR "TASK OK\n";
517 POSIX::close ($psync[1]);
518 POSIX::close ($csync[0]);
521 # sync with child (wait until child starts)
522 POSIX::read($psync[0], $readbuf, 4096);
525 POSIX::close($psync[0]);
526 &$register_worker($cpid, $user, $upid);
532 die "got no worker upid - start worker failed\n" if !$readbuf;
534 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
535 die "starting worker failed: $1\n";
538 if ($readbuf ne $upid) {
539 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
543 $outfh = PVE::Tools::upid_open($upid);
550 POSIX::write($csync[1], $msg, length ($msg));
551 POSIX::close($csync[1]);
554 POSIX::close($csync[1]);
555 kill(-9, $cpid); # make sure it gets killed
559 $self->log_cluster_msg('info', $user, "starting task $upid");
561 my $tlist = $self->active_workers($upid, $sync);
562 $self->broadcast_tasklist($tlist);
571 local $SIG{INT} = local $SIG{QUIT} = local $SIG{TERM} = sub {
572 # always send signal to all pgrp members
574 if ($int_count < 3) {
575 kill(15, $kpid); # send TERM signal
577 kill(9, $kpid); # send KILL signal
581 local $SIG{PIPE} = sub { die "broken pipe\n"; };
583 my $select = new IO::Select;
584 my $fh = IO::Handle->new_from_fd($psync[0], 'r');
587 while ($select->count) {
588 my @handles = $select->can_read(1);
589 if (scalar(@handles)) {
590 my $count = sysread ($handles[0], $readbuf, 4096);
591 if (!defined ($count)) {
593 die "sync pipe read error: $err\n";
595 last if $count == 0; # eof
598 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
601 if ($data =~ m/^TASK OK$/) {
603 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
614 # some commands daemonize without closing stdout
615 last if !PVE::ProcFSTools::check_process_running($cpid);
621 POSIX::close($psync[0]);
623 if ($outbuf) { # just to be sure
626 print $outfh $outbuf;
632 print STDERR "$err\n";
634 print $outfh "TASK ERROR: $err\n";
638 &$kill_process_group($cpid, $pstart); # make sure it gets killed
644 &$log_task_result($upid, $user, $res);
647 return wantarray ? ($upid, $res) : $upid;
652 sub log_cluster_msg {
653 my ($self, $pri, $user, $msg) = @_;
655 syslog($pri, "%s", $msg);
657 # PVE::Cluster::log_msg($pri, $user, $msg);
660 sub broadcast_tasklist {
661 my ($self, $tlist) = @_;
663 # PVE::Cluster::broadcast_tasklist($tlist);
666 sub check_api2_permissions {
667 my ($self, $perm, $username, $param) = @_;
669 return 1 if !$username && $perm->{user} eq 'world';
671 raise_perm_exc("user != null") if !$username;
673 return 1 if $username eq 'root@pam';
675 raise_perm_exc('user != root@pam') if !$perm;
677 return 1 if $perm->{user} && $perm->{user} eq 'all';
679 ##return $self->exec_api2_perm_check($perm->{check}, $username, $param)
685 # init_request - should be called before each REST/CLI request
687 my ($self, %params) = @_;
689 $self->{result_attributes} = {}
691 # if you nedd more, implement in subclass