]>
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);
19 use PVE
::Exception
qw(raise raise_perm_exc);
25 our @EXPORT_OK = qw(log_warn);
29 # save $SIG{CHLD} handler implementation.
30 # simply set $SIG{CHLD} = $worker_reaper;
31 # and register forked processes with &$register_worker(pid)
32 # Note: using $SIG{CHLD} = 'IGNORE' or $SIG{CHLD} = sub { wait (); } or ...
33 # has serious side effects, because perls built in system() and open()
34 # functions can't get the correct exit status of a child. So we can't use
35 # that (also see perlipc)
40 my $log_task_result = sub {
41 my ($upid, $user, $status) = @_;
45 my $msg = 'successful';
48 my $ec = $status >> 8;
49 my $ic = $status & 255;
50 $msg = $ec ?
"failed ($ec)" : "interrupted ($ic)";
54 my $tlist = $rest_env->active_workers($upid);
55 eval { $rest_env->broadcast_tasklist($tlist); };
56 syslog
('err', $@) if $@;
59 foreach my $t (@$tlist) {
60 if ($t->{upid
} eq $upid) {
65 if ($task && $task->{status
}) {
66 $msg = $task->{status
};
69 $rest_env->log_cluster_msg($pri, $user, "end task $upid $msg");
72 my $worker_reaper = sub {
74 foreach my $pid (keys %$WORKER_PIDS) {
75 my $waitpid = waitpid ($pid, WNOHANG
);
76 if (defined($waitpid) && ($waitpid == $pid)) {
77 my $info = $WORKER_PIDS->{$pid};
78 if ($info && $info->{upid
} && $info->{user
}) {
79 &$log_task_result($info->{upid
}, $info->{user
}, $?);
81 delete ($WORKER_PIDS->{$pid});
86 my $register_worker = sub {
87 my ($pid, $user, $upid) = @_;
91 # do not register if already finished
92 my $waitpid = waitpid ($pid, WNOHANG
);
93 if (defined($waitpid) && ($waitpid == $pid)) {
94 delete ($WORKER_PIDS->{$pid});
98 $WORKER_PIDS->{$pid} = {
104 # initialize environment - must be called once at program startup
106 my ($class, $type, %params) = @_;
108 $class = ref($class) || $class;
110 die "already initialized" if $rest_env;
112 die "unknown environment type"
113 if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
116 # when we're using AnyEvent, we have to postpone the call to worker_reaper, otherwise it
117 # might interfere with running api calls
118 if (defined($AnyEvent::MODEL
)) {
119 AnyEvent
::postpone
{ $worker_reaper->() };
126 # cli ... command started fron command line
127 # pub ... access from public server (pveproxy)
128 # priv ... access from private server (pvedaemon)
129 # ha ... access from HA resource manager agent (pve-ha-manager)
138 foreach my $p (keys %params) {
139 if ($p eq 'atfork') {
140 $self->{$p} = $params{$p};
142 die "unknown option '$p'";
148 my ($sysname, $nodename) = POSIX
::uname
();
150 $nodename =~ s/\..*$//; # strip domain part, if any
152 $self->{nodename
} = $nodename;
157 # convenience function for command line tools
158 sub setup_default_cli_env
{
159 my ($class, $username) = @_;
161 $class = ref($class) || $class;
163 $username //= 'root@pam';
165 PVE
::INotify
::inotify_init
();
167 my $rpcenv = $class->init('cli');
168 $rpcenv->init_request();
169 $rpcenv->set_language($ENV{LANG
});
170 $rpcenv->set_user($username);
172 die "please run as root\n"
173 if ($username eq 'root@pam') && ($> != 0);
179 die "REST environment not initialized" if !$rest_env;
185 my ($self, $ip) = @_;
187 $self->{client_ip
} = $ip;
193 return $self->{client_ip
};
196 sub set_result_attrib
{
197 my ($self, $key, $value) = @_;
199 $self->{result_attributes
}->{$key} = $value;
202 sub get_result_attrib
{
203 my ($self, $key) = @_;
205 return $self->{result_attributes
}->{$key};
209 my ($self, $lang) = @_;
211 # fixme: initialize I18N
213 $self->{language
} = $lang;
219 return $self->{language
};
223 my ($self, $user) = @_;
225 $self->{user
} = $user;
229 my ($self, $noerr) = @_;
231 return $self->{user
} if defined($self->{user
}) || $noerr;
233 die "user name not set\n";
236 sub set_u2f_challenge
{
237 my ($self, $challenge) = @_;
239 $self->{u2f_challenge
} = $challenge;
242 sub get_u2f_challenge
{
243 my ($self, $noerr) = @_;
245 return $self->{u2f_challenge
} if defined($self->{u2f_challenge
}) || $noerr;
247 die "no active u2f challenge\n";
250 sub set_request_host
{
251 my ($self, $host) = @_;
253 $self->{request_host
} = $host;
256 sub get_request_host
{
257 my ($self, $noerr) = @_;
259 return $self->{request_host
} if defined($self->{request_host
}) || $noerr;
261 die "no hostname available in current environment\n";
270 # read/update list of active workers.
272 # we move all finished tasks to the archive index, but keep active, and most recent tasks in the
274 # $nocheck ... consider $new_upid still running (avoid that we try to read the result to early).
276 my ($self, $new_upid, $nocheck) = @_;
280 my $res = PVE
::Tools
::lock_file
("/var/log/pve/tasks/.active.lock", $timeout, sub {
281 my $tasklist = PVE
::INotify
::read_file
('active');
285 my $thash = {}; # only list task once
287 my $check_task = sub {
288 my ($task, $running) = @_;
290 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
296 delete $task->{pstart
};
299 foreach my $task (@$tasklist) {
300 my $upid = $task->{upid
};
301 next if $thash->{$upid};
302 $thash->{$upid} = $task;
306 if ($new_upid && !$thash->{$new_upid}) {
307 my $task = PVE
::Tools
::upid_decode
($new_upid);
308 $task->{upid
} = $new_upid;
309 $thash->{$new_upid} = $task;
310 &$check_task($task, $nocheck);
314 @ta = sort { $b->{starttime
} <=> $a->{starttime
} } @ta;
316 my $save = defined($new_upid);
318 foreach my $task (@ta) {
319 next if $task->{endtime
};
320 $task->{endtime
} = time();
321 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
327 foreach my $task (@ta) {
328 if (!$task->{saved
}) {
329 $archive .= sprintf("%s %08X %s\n", $task->{upid
}, $task->{endtime
}, $task->{status
});
338 my $filename = "/var/log/pve/tasks/index";
340 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
341 die "unable to open file '$filename' - $!\n";
342 PVE
::Tools
::safe_print
($filename, $fh, $archive);
345 die "unable to close file '$filename' - $!\n";
350 foreach my $task (@arlist) { # mark as not saved
354 my $maxsize = 50000; # about 1000 entries
355 if ($size > $maxsize) {
356 rename($filename, "$filename.1");
360 # we try to reduce the amount of data list all running tasks and task and a few others
361 my $MAX_FINISHED = 25;
362 my $max = $MAX_FINISHED - scalar(@$tlist);
363 foreach my $task (@ta) {
369 PVE
::INotify
::write_file
('active', $tlist) if $save;
378 my $kill_process_group = sub {
379 my ($pid, $pstart) = @_;
381 # send kill to process group (negative pid)
384 # always send signal to all pgrp members
385 kill(15, $kpid); # send TERM signal
387 # give max 5 seconds to shut down
388 for (my $i = 0; $i < 5; $i++) {
389 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
398 my ($self, $upid, $killit) = @_;
400 my $task = PVE
::Tools
::upid_decode
($upid);
402 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
404 return 0 if !$running;
407 &$kill_process_group($task->{pid
});
414 # acts almost as tee: writes an output both to STDOUT and a task log,
415 # we differ as we're worker aware and look also at the childs control pipe,
416 # so we know if the function could be executed successfully or not.
417 my $tee_worker = sub {
418 my ($childfd, $ctrlfd, $taskfh, $cpid) = @_;
422 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
423 # always send signal to all pgrp members
425 if ($int_count < 3) {
426 kill(15, $kpid); # send TERM signal
428 kill(9, $kpid); # send KILL signal
432 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
434 my $select = IO
::Select-
>new();
435 my $fh = IO
::Handle-
>new_from_fd($childfd, 'r');
440 while ($select->count) {
441 my @handles = $select->can_read(1);
442 if (scalar(@handles)) {
443 my $count = sysread ($handles[0], $readbuf, 4096);
444 if (!defined ($count)) {
446 die "sync pipe read error: $err\n";
448 last if $count == 0; # eof
453 print $taskfh $readbuf;
456 # some commands daemonize without closing stdout
457 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
461 POSIX
::read($ctrlfd, $readbuf, 4096);
462 if ($readbuf =~ m/^TASK OK\n?$/) {
463 # skip printing to stdout
464 print $taskfh $readbuf;
465 } elsif ($readbuf =~ m/^TASK ERROR: (.*)\n?$/) {
467 print $taskfh "\n$readbuf"; # ensure start on new line for webUI
468 } elsif ($readbuf =~ m/^TASK WARNINGS: (\d+)\n?$/) {
469 print STDERR
"Task finished with $1 warning(s)!\n";
470 print $taskfh "\n$readbuf"; # ensure start on new line for webUI
472 die "got unexpected control message: $readbuf\n";
478 POSIX
::close($childfd);
479 POSIX
::close($ctrlfd);
483 print STDERR
"$err\n";
484 print $taskfh "TASK ERROR: $err\n";
488 # start long running workers
489 # STDIN is redirected to /dev/null
490 # STDOUT,STDERR are redirected to the filename returned by upid_decode
491 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
493 my ($self, $dtype, $id, $user, $function, $background) = @_;
495 $dtype = 'unknown' if !defined ($dtype);
496 $id = '' if !defined ($id);
498 # note: below is only used for the task log entry
499 $user = $self->get_user(1) // 'root@pam' if !defined($user);
501 my $sync = ($self->{type
} eq 'cli' && !$background) ?
1 : 0;
506 local $SIG{TERM
} = 'IGNORE';
508 my $starttime = time ();
510 my @psync = POSIX
::pipe();
511 my @csync = POSIX
::pipe();
512 my @ctrlfd = $sync ? POSIX
::pipe() : ();
514 my $node = $self->{nodename
};
517 die "unable to fork worker - $!" if !defined($cpid);
519 my $workerpuid = $cpid ?
$cpid : $$;
521 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
522 die "unable to read process start time";
524 my $upid = PVE
::Tools
::upid_encode
({
525 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
526 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
530 if (!$cpid) { # child
535 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
537 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
538 $SIG{TTOU
} = 'IGNORE';
541 # set session/process group allows to kill the process group
542 if ($sync && -t STDIN
) {
543 # some sync'ed workers operate on the tty but setsid sessions lose
544 # the tty, so just create a new pgroup and give it the tty
545 $ppgid = POSIX
::getpgrp() or die "failed to get old pgid: $!\n";
546 POSIX
::setpgid
(0, 0) or die "failed to setpgid: $!\n";
547 POSIX
::tcsetpgrp
(fileno(STDIN
), $$) or die "failed to tcsetpgrp: $!\n";
552 POSIX
::close ($psync[0]);
553 POSIX
::close ($ctrlfd[0]) if $sync;
554 POSIX
::close ($csync[1]);
556 $outfh = $sync ?
$psync[1] : undef;
557 my $resfh = $sync ?
$ctrlfd[1] : undef;
560 PVE
::INotify
::inotify_close
();
562 if (my $atfork = $self->{atfork
}) {
566 # same algorithm as used inside SA
568 my $fd = fileno (STDIN
);
572 POSIX
::close(0) if $fd != 0;
574 open(STDIN
, '<', '/dev/null') or die "unable to redirect STDIN - $!";
576 $outfh = PVE
::Tools
::upid_open
($upid);
577 $resfh = fileno($outfh);
582 $fd = fileno(STDOUT
);
584 POSIX
::close (1) if $fd != 1;
586 open(STDOUT
, ">&", $outfh) or die "unable to redirect STDOUT - $!";
588 STDOUT-
>autoflush (1);
590 # redirect STDERR to STDOUT
591 $fd = fileno (STDERR
);
593 POSIX
::close(2) if $fd != 2;
595 open(STDERR
, '>&', '1') or die "unable to redirect STDERR - $!";
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