]>
git.proxmox.com Git - pve-common.git/blob - src/PVE/RESTEnvironment.pm
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
11 use Exporter
qw(import);
16 use POSIX
qw(:sys_wait_h EINTR);
18 use PVE
::Exception
qw(raise raise_perm_exc);
24 our @EXPORT_OK = qw(log_warn);
28 # save $SIG{CHLD} handler implementation.
29 # simply set $SIG{CHLD} = $worker_reaper;
30 # and register forked processes with &$register_worker(pid)
31 # Note: using $SIG{CHLD} = 'IGNORE' or $SIG{CHLD} = sub { wait (); } or ...
32 # has serious side effects, because perls built in system() and open()
33 # functions can't get the correct exit status of a child. So we can't use
34 # that (also see perlipc)
39 my $log_task_result = sub {
40 my ($upid, $user, $status) = @_;
44 my $msg = 'successful';
47 my $ec = $status >> 8;
48 my $ic = $status & 255;
49 $msg = $ec ?
"failed ($ec)" : "interrupted ($ic)";
53 my $tlist = $rest_env->active_workers($upid);
54 eval { $rest_env->broadcast_tasklist($tlist); };
55 syslog
('err', $@) if $@;
58 foreach my $t (@$tlist) {
59 if ($t->{upid
} eq $upid) {
64 if ($task && $task->{status
}) {
65 $msg = $task->{status
};
68 $rest_env->log_cluster_msg($pri, $user, "end task $upid $msg");
71 my $worker_reaper = sub {
73 foreach my $pid (keys %$WORKER_PIDS) {
74 my $waitpid = waitpid ($pid, WNOHANG
);
75 if (defined($waitpid) && ($waitpid == $pid)) {
76 my $info = $WORKER_PIDS->{$pid};
77 if ($info && $info->{upid
} && $info->{user
}) {
78 &$log_task_result($info->{upid
}, $info->{user
}, $?);
80 delete ($WORKER_PIDS->{$pid});
85 my $register_worker = sub {
86 my ($pid, $user, $upid) = @_;
90 # do not register if already finished
91 my $waitpid = waitpid ($pid, WNOHANG
);
92 if (defined($waitpid) && ($waitpid == $pid)) {
93 delete ($WORKER_PIDS->{$pid});
97 $WORKER_PIDS->{$pid} = {
103 # initialize environment - must be called once at program startup
105 my ($class, $type, %params) = @_;
107 $class = ref($class) || $class;
109 die "already initialized" if $rest_env;
111 die "unknown environment type"
112 if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
114 $SIG{CHLD
} = $worker_reaper;
117 # cli ... command started fron command line
118 # pub ... access from public server (pveproxy)
119 # priv ... access from private server (pvedaemon)
120 # ha ... access from HA resource manager agent (pve-ha-manager)
129 foreach my $p (keys %params) {
130 if ($p eq 'atfork') {
131 $self->{$p} = $params{$p};
133 die "unknown option '$p'";
139 my ($sysname, $nodename) = POSIX
::uname
();
141 $nodename =~ s/\..*$//; # strip domain part, if any
143 $self->{nodename
} = $nodename;
148 # convenience function for command line tools
149 sub setup_default_cli_env
{
150 my ($class, $username) = @_;
152 $class = ref($class) || $class;
154 $username //= 'root@pam';
156 PVE
::INotify
::inotify_init
();
158 my $rpcenv = $class->init('cli');
159 $rpcenv->init_request();
160 $rpcenv->set_language($ENV{LANG
});
161 $rpcenv->set_user($username);
163 die "please run as root\n"
164 if ($username eq 'root@pam') && ($> != 0);
170 die "REST environment not initialized" if !$rest_env;
176 my ($self, $ip) = @_;
178 $self->{client_ip
} = $ip;
184 return $self->{client_ip
};
187 sub set_result_attrib
{
188 my ($self, $key, $value) = @_;
190 $self->{result_attributes
}->{$key} = $value;
193 sub get_result_attrib
{
194 my ($self, $key) = @_;
196 return $self->{result_attributes
}->{$key};
200 my ($self, $lang) = @_;
202 # fixme: initialize I18N
204 $self->{language
} = $lang;
210 return $self->{language
};
214 my ($self, $user) = @_;
216 $self->{user
} = $user;
220 my ($self, $noerr) = @_;
222 return $self->{user
} if defined($self->{user
}) || $noerr;
224 die "user name not set\n";
227 sub set_u2f_challenge
{
228 my ($self, $challenge) = @_;
230 $self->{u2f_challenge
} = $challenge;
233 sub get_u2f_challenge
{
234 my ($self, $noerr) = @_;
236 return $self->{u2f_challenge
} if defined($self->{u2f_challenge
}) || $noerr;
238 die "no active u2f challenge\n";
241 sub set_request_host
{
242 my ($self, $host) = @_;
244 $self->{request_host
} = $host;
247 sub get_request_host
{
248 my ($self, $noerr) = @_;
250 return $self->{request_host
} if defined($self->{request_host
}) || $noerr;
252 die "no hostname available in current environment\n";
261 # read/update list of active workers
262 # we move all finished tasks to the archive index,
263 # but keep aktive and most recent task in the active file.
264 # $nocheck ... consider $new_upid still running (avoid that
265 # we try to read the reult to early.
267 my ($self, $new_upid, $nocheck) = @_;
269 my $lkfn = "/var/log/pve/tasks/.active.lock";
275 my $tasklist = PVE
::INotify
::read_file
('active');
279 my $thash = {}; # only list task once
281 my $check_task = sub {
282 my ($task, $running) = @_;
284 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
290 delete $task->{pstart
};
293 foreach my $task (@$tasklist) {
294 my $upid = $task->{upid
};
295 next if $thash->{$upid};
296 $thash->{$upid} = $task;
300 if ($new_upid && !(my $task = $thash->{$new_upid})) {
301 $task = PVE
::Tools
::upid_decode
($new_upid);
302 $task->{upid
} = $new_upid;
303 $thash->{$new_upid} = $task;
304 &$check_task($task, $nocheck);
308 @ta = sort { $b->{starttime
} <=> $a->{starttime
} } @ta;
310 my $save = defined($new_upid);
312 foreach my $task (@ta) {
313 next if $task->{endtime
};
314 $task->{endtime
} = time();
315 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
321 foreach my $task (@ta) {
322 if (!$task->{saved
}) {
323 $archive .= sprintf("%s %08X %s\n", $task->{upid
}, $task->{endtime
}, $task->{status
});
332 my $filename = "/var/log/pve/tasks/index";
334 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
335 die "unable to open file '$filename' - $!\n";
336 PVE
::Tools
::safe_print
($filename, $fh, $archive);
339 die "unable to close file '$filename' - $!\n";
344 foreach my $task (@arlist) { # mark as not saved
348 my $maxsize = 50000; # about 1000 entries
349 if ($size > $maxsize) {
350 rename($filename, "$filename.1");
354 # we try to reduce the amount of data
355 # list all running tasks and task and a few others
356 # try to limit to 25 tasks
357 my $max = 25 - scalar(@$tlist);
358 foreach my $task (@ta) {
364 PVE
::INotify
::write_file
('active', $tlist) if $save;
369 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
375 my $kill_process_group = sub {
376 my ($pid, $pstart) = @_;
378 # send kill to process group (negative pid)
381 # always send signal to all pgrp members
382 kill(15, $kpid); # send TERM signal
384 # give max 5 seconds to shut down
385 for (my $i = 0; $i < 5; $i++) {
386 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
395 my ($self, $upid, $killit) = @_;
397 my $task = PVE
::Tools
::upid_decode
($upid);
399 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
401 return 0 if !$running;
404 &$kill_process_group($task->{pid
});
411 # acts almost as tee: writes an output both to STDOUT and a task log,
412 # we differ as we're worker aware and look also at the childs control pipe,
413 # so we know if the function could be executed successfully or not.
414 my $tee_worker = sub {
415 my ($childfd, $ctrlfd, $taskfh, $cpid) = @_;
419 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
420 # always send signal to all pgrp members
422 if ($int_count < 3) {
423 kill(15, $kpid); # send TERM signal
425 kill(9, $kpid); # send KILL signal
429 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
431 my $select = new IO
::Select
;
432 my $fh = IO
::Handle-
>new_from_fd($childfd, 'r');
437 while ($select->count) {
438 my @handles = $select->can_read(1);
439 if (scalar(@handles)) {
440 my $count = sysread ($handles[0], $readbuf, 4096);
441 if (!defined ($count)) {
443 die "sync pipe read error: $err\n";
445 last if $count == 0; # eof
450 print $taskfh $readbuf;
453 # some commands daemonize without closing stdout
454 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
458 POSIX
::read($ctrlfd, $readbuf, 4096);
459 if ($readbuf =~ m/^TASK OK\n?$/) {
460 # skip printing to stdout
461 print $taskfh $readbuf;
462 } elsif ($readbuf =~ m/^TASK ERROR: (.*)\n?$/) {
464 print $taskfh "\n$readbuf"; # ensure start on new line for webUI
465 } elsif ($readbuf =~ m/^TASK WARNINGS: (\d+)\n?$/) {
466 print STDERR
"Task finished with $1 warning(s)!\n";
467 print $taskfh "\n$readbuf"; # ensure start on new line for webUI
469 die "got unexpected control message: $readbuf\n";
475 POSIX
::close($childfd);
476 POSIX
::close($ctrlfd);
480 print STDERR
"$err\n";
481 print $taskfh "TASK ERROR: $err\n";
485 # start long running workers
486 # STDIN is redirected to /dev/null
487 # STDOUT,STDERR are redirected to the filename returned by upid_decode
488 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
490 my ($self, $dtype, $id, $user, $function, $background) = @_;
492 $dtype = 'unknown' if !defined ($dtype);
493 $id = '' if !defined ($id);
495 # note: below is only used for the task log entry
496 $user = $self->get_user(1) // 'root@pam' if !defined($user);
498 my $sync = ($self->{type
} eq 'cli' && !$background) ?
1 : 0;
503 local $SIG{TERM
} = 'IGNORE';
505 my $starttime = time ();
507 my @psync = POSIX
::pipe();
508 my @csync = POSIX
::pipe();
509 my @ctrlfd = POSIX
::pipe() if $sync;
511 my $node = $self->{nodename
};
514 die "unable to fork worker - $!" if !defined($cpid);
516 my $workerpuid = $cpid ?
$cpid : $$;
518 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
519 die "unable to read process start time";
521 my $upid = PVE
::Tools
::upid_encode
({
522 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
523 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
527 if (!$cpid) { # child
532 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
534 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
535 $SIG{TTOU
} = 'IGNORE';
538 # set session/process group allows to kill the process group
539 if ($sync && -t STDIN
) {
540 # some sync'ed workers operate on the tty but setsid sessions lose
541 # the tty, so just create a new pgroup and give it the tty
542 $ppgid = POSIX
::getpgrp() or die "failed to get old pgid: $!\n";
543 POSIX
::setpgid
(0, 0) or die "failed to setpgid: $!\n";
544 POSIX
::tcsetpgrp
(fileno(STDIN
), $$) or die "failed to tcsetpgrp: $!\n";
549 POSIX
::close ($psync[0]);
550 POSIX
::close ($ctrlfd[0]) if $sync;
551 POSIX
::close ($csync[1]);
553 $outfh = $sync ?
$psync[1] : undef;
554 my $resfh = $sync ?
$ctrlfd[1] : undef;
557 PVE
::INotify
::inotify_close
();
559 if (my $atfork = $self->{atfork
}) {
563 # same algorithm as used inside SA
565 my $fd = fileno (STDIN
);
569 POSIX
::close(0) if $fd != 0;
571 die "unable to redirect STDIN - $!"
572 if !open(STDIN
, "</dev/null");
574 $outfh = PVE
::Tools
::upid_open
($upid);
575 $resfh = fileno($outfh);
580 $fd = fileno(STDOUT
);
582 POSIX
::close (1) if $fd != 1;
584 die "unable to redirect STDOUT - $!"
585 if !open(STDOUT
, ">&", $outfh);
587 STDOUT-
>autoflush (1);
589 # redirect STDERR to STDOUT
590 $fd = fileno (STDERR
);
592 POSIX
::close(2) if $fd != 2;
594 die "unable to redirect STDERR - $!"
595 if !open(STDERR
, ">&1");
597 STDERR-
>autoflush(1);
600 my $msg = "ERROR: $err";
601 POSIX
::write($psync[1], $msg, length ($msg));
602 POSIX
::close($psync[1]);
607 # sync with parent (signal that we are ready)
608 POSIX
::write($psync[1], $upid, length ($upid));
609 POSIX
::close($psync[1]) if !$sync; # don't need output pipe if async
613 # sync with parent (wait until parent is ready)
614 POSIX
::read($csync[0], $readbuf, 4096);
615 die "parent setup error\n" if $readbuf ne 'OK';
617 if ($self->{type
} eq 'ha') {
618 print "task started by HA resource agent\n";
622 my ($msg, $exitcode);
628 $msg = "TASK ERROR: $err\n";
630 } elsif (my $warnings = $self->{warning_count
}) {
631 $msg = "TASK WARNINGS: $warnings\n";
637 POSIX
::write($resfh, $msg, length($msg));
640 POSIX
::close($resfh);
642 POSIX
::tcsetpgrp
(fileno(STDIN
), $ppgid) or
643 die "failed to tcsetpgrp to parent: $!\n";
646 POSIX
::_exit
($exitcode);
647 kill(-9, $$); # not really needed, just to be sure
652 POSIX
::close ($psync[1]);
653 POSIX
::close ($ctrlfd[1]) if $sync;
654 POSIX
::close ($csync[0]);
657 # sync with child (wait until child starts)
658 POSIX
::read($psync[0], $readbuf, 4096);
661 POSIX
::close($psync[0]);
662 &$register_worker($cpid, $user, $upid);
668 die "got no worker upid - start worker failed\n" if !$readbuf;
670 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
671 die "starting worker failed: $1\n";
674 if ($readbuf ne $upid) {
675 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
679 $outfh = PVE
::Tools
::upid_open
($upid);
686 POSIX
::write($csync[1], $msg, length ($msg));
687 POSIX
::close($csync[1]);
690 POSIX
::close($csync[1]);
691 kill(-9, $cpid); # make sure it gets killed
695 $self->log_cluster_msg('info', $user, "starting task $upid");
697 my $tlist = $self->active_workers($upid, $sync);
698 eval { $self->broadcast_tasklist($tlist); };
699 syslog
('err', $@) if $@;
705 $tee_worker->($psync[0], $ctrlfd[0], $outfh, $cpid);
707 &$kill_process_group($cpid, $pstart); # make sure it gets killed
713 &$log_task_result($upid, $user, $res);
716 return wantarray ?
($upid, $res) : $upid;
723 $rest_env->warn($message);
726 print STDERR
"WARN: $message\n";
731 my ($self, $message) = @_;
735 print STDERR
"WARN: $message\n";
737 $self->{warning_count
}++;
742 sub log_cluster_msg
{
743 my ($self, $pri, $user, $msg) = @_;
745 syslog
($pri, "%s", $msg);
747 # PVE::Cluster::log_msg($pri, $user, $msg);
750 sub broadcast_tasklist
{
751 my ($self, $tlist) = @_;
753 # PVE::Cluster::broadcast_tasklist($tlist);
756 sub check_api2_permissions
{
757 my ($self, $perm, $username, $param) = @_;
759 return 1 if !$username && $perm->{user
} eq 'world';
761 raise_perm_exc
("user != null") if !$username;
763 return 1 if $username eq 'root@pam';
765 raise_perm_exc
('user != root@pam') if !$perm;
767 return 1 if $perm->{user
} && $perm->{user
} eq 'all';
769 ##return $self->exec_api2_perm_check($perm->{check}, $username, $param)
775 # init_request - should be called before each REST/CLI request
777 my ($self, %params) = @_;
779 $self->{result_attributes
} = {}
781 # if you nedd more, implement in subclass