]>
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
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 can't 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 eval { $rest_env->broadcast_tasklist($tlist); };
51 syslog
('err', $@) if $@;
54 foreach my $t (@$tlist) {
55 if ($t->{upid
} eq $upid) {
60 if ($task && $task->{status
}) {
61 $msg = $task->{status
};
64 $rest_env->log_cluster_msg($pri, $user, "end task $upid $msg");
67 my $worker_reaper = sub {
69 foreach my $pid (keys %$WORKER_PIDS) {
70 my $waitpid = waitpid ($pid, WNOHANG
);
71 if (defined($waitpid) && ($waitpid == $pid)) {
72 my $info = $WORKER_PIDS->{$pid};
73 if ($info && $info->{upid
} && $info->{user
}) {
74 &$log_task_result($info->{upid
}, $info->{user
}, $?);
76 delete ($WORKER_PIDS->{$pid});
81 my $register_worker = sub {
82 my ($pid, $user, $upid) = @_;
86 # do not register if already finished
87 my $waitpid = waitpid ($pid, WNOHANG
);
88 if (defined($waitpid) && ($waitpid == $pid)) {
89 delete ($WORKER_PIDS->{$pid});
93 $WORKER_PIDS->{$pid} = {
99 # initialize environment - must be called once at program startup
101 my ($class, $type, %params) = @_;
103 $class = ref($class) || $class;
105 die "already initialized" if $rest_env;
107 die "unknown environment type"
108 if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
110 $SIG{CHLD
} = $worker_reaper;
113 # cli ... command started fron command line
114 # pub ... access from public server (pveproxy)
115 # priv ... access from private server (pvedaemon)
116 # ha ... access from HA resource manager agent (pve-ha-manager)
118 my $self = { type
=> $type };
122 foreach my $p (keys %params) {
123 if ($p eq 'atfork') {
124 $self->{$p} = $params{$p};
126 die "unknown option '$p'";
132 my ($sysname, $nodename) = POSIX
::uname
();
134 $nodename =~ s/\..*$//; # strip domain part, if any
136 $self->{nodename
} = $nodename;
141 # convenience function for command line tools
142 sub setup_default_cli_env
{
143 my ($class, $username) = @_;
145 $class = ref($class) || $class;
147 $username //= 'root@pam';
149 PVE
::INotify
::inotify_init
();
151 my $rpcenv = $class->init('cli');
152 $rpcenv->init_request();
153 $rpcenv->set_language($ENV{LANG
});
154 $rpcenv->set_user($username);
156 die "please run as root\n"
157 if ($username eq 'root@pam') && ($> != 0);
163 die "REST environment not initialized" if !$rest_env;
169 my ($self, $ip) = @_;
171 $self->{client_ip
} = $ip;
177 return $self->{client_ip
};
180 sub set_result_attrib
{
181 my ($self, $key, $value) = @_;
183 $self->{result_attributes
}->{$key} = $value;
186 sub get_result_attrib
{
187 my ($self, $key) = @_;
189 return $self->{result_attributes
}->{$key};
193 my ($self, $lang) = @_;
195 # fixme: initialize I18N
197 $self->{language
} = $lang;
203 return $self->{language
};
207 my ($self, $user) = @_;
209 $self->{user
} = $user;
213 my ($self, $noerr) = @_;
215 return $self->{user
} if defined($self->{user
}) || $noerr;
217 die "user name not set\n";
220 sub set_u2f_challenge
{
221 my ($self, $challenge) = @_;
223 $self->{u2f_challenge
} = $challenge;
226 sub get_u2f_challenge
{
227 my ($self, $noerr) = @_;
229 return $self->{u2f_challenge
} if defined($self->{u2f_challenge
}) || $noerr;
231 die "no active u2f challenge\n";
234 sub set_request_host
{
235 my ($self, $host) = @_;
237 $self->{request_host
} = $host;
240 sub get_request_host
{
241 my ($self, $noerr) = @_;
243 return $self->{request_host
} if defined($self->{request_host
}) || $noerr;
245 die "no hostname available in current environment\n";
254 # read/update list of active workers
255 # we move all finished tasks to the archive index,
256 # but keep aktive and most recent task in the active file.
257 # $nocheck ... consider $new_upid still running (avoid that
258 # we try to read the reult to early.
260 my ($self, $new_upid, $nocheck) = @_;
262 my $lkfn = "/var/log/pve/tasks/.active.lock";
268 my $tasklist = PVE
::INotify
::read_file
('active');
272 my $thash = {}; # only list task once
274 my $check_task = sub {
275 my ($task, $running) = @_;
277 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
283 delete $task->{pstart
};
286 foreach my $task (@$tasklist) {
287 my $upid = $task->{upid
};
288 next if $thash->{$upid};
289 $thash->{$upid} = $task;
293 if ($new_upid && !(my $task = $thash->{$new_upid})) {
294 $task = PVE
::Tools
::upid_decode
($new_upid);
295 $task->{upid
} = $new_upid;
296 $thash->{$new_upid} = $task;
297 &$check_task($task, $nocheck);
301 @ta = sort { $b->{starttime
} <=> $a->{starttime
} } @ta;
303 my $save = defined($new_upid);
305 foreach my $task (@ta) {
306 next if $task->{endtime
};
307 $task->{endtime
} = time();
308 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
314 foreach my $task (@ta) {
315 if (!$task->{saved
}) {
316 $archive .= sprintf("%s %08X %s\n", $task->{upid
}, $task->{endtime
}, $task->{status
});
325 my $filename = "/var/log/pve/tasks/index";
327 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
328 die "unable to open file '$filename' - $!\n";
329 PVE
::Tools
::safe_print
($filename, $fh, $archive);
332 die "unable to close file '$filename' - $!\n";
337 foreach my $task (@arlist) { # mark as not saved
341 my $maxsize = 50000; # about 1000 entries
342 if ($size > $maxsize) {
343 rename($filename, "$filename.1");
347 # we try to reduce the amount of data
348 # list all running tasks and task and a few others
349 # try to limit to 25 tasks
350 my $max = 25 - scalar(@$tlist);
351 foreach my $task (@ta) {
357 PVE
::INotify
::write_file
('active', $tlist) if $save;
362 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
368 my $kill_process_group = sub {
369 my ($pid, $pstart) = @_;
371 # send kill to process group (negative pid)
374 # always send signal to all pgrp members
375 kill(15, $kpid); # send TERM signal
377 # give max 5 seconds to shut down
378 for (my $i = 0; $i < 5; $i++) {
379 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
388 my ($self, $upid, $killit) = @_;
390 my $task = PVE
::Tools
::upid_decode
($upid);
392 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
394 return 0 if !$running;
397 &$kill_process_group($task->{pid
});
404 # acts almost as tee: writes an output both to STDOUT and a task log,
405 # we differ as we're worker aware and look also at the childs control pipe,
406 # so we know if the function could be executed successfully or not.
407 my $tee_worker = sub {
408 my ($childfd, $ctrlfd, $taskfh, $cpid) = @_;
412 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
413 # always send signal to all pgrp members
415 if ($int_count < 3) {
416 kill(15, $kpid); # send TERM signal
418 kill(9, $kpid); # send KILL signal
422 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
424 my $select = new IO
::Select
;
425 my $fh = IO
::Handle-
>new_from_fd($childfd, 'r');
430 while ($select->count) {
431 my @handles = $select->can_read(1);
432 if (scalar(@handles)) {
433 my $count = sysread ($handles[0], $readbuf, 4096);
434 if (!defined ($count)) {
436 die "sync pipe read error: $err\n";
438 last if $count == 0; # eof
443 print $taskfh $readbuf;
446 # some commands daemonize without closing stdout
447 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
451 # get status (error or OK)
452 POSIX
::read($ctrlfd, $readbuf, 4096);
453 if ($readbuf =~ m/^TASK OK\n?$/) {
454 # skip printing to stdout
455 print $taskfh $readbuf;
456 } elsif ($readbuf =~ m/^TASK ERROR: (.*)\n?$/) {
458 print $taskfh "\n$readbuf"; # ensure start on new line for webUI
460 die "got unexpected control message: $readbuf\n";
466 POSIX
::close($childfd);
467 POSIX
::close($ctrlfd);
471 print STDERR
"$err\n";
472 print $taskfh "TASK ERROR: $err\n";
476 # start long running workers
477 # STDIN is redirected to /dev/null
478 # STDOUT,STDERR are redirected to the filename returned by upid_decode
479 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
481 my ($self, $dtype, $id, $user, $function, $background) = @_;
483 $dtype = 'unknown' if !defined ($dtype);
484 $id = '' if !defined ($id);
486 $user = 'root@pve' if !defined ($user);
488 my $sync = ($self->{type
} eq 'cli' && !$background) ?
1 : 0;
493 local $SIG{TERM
} = 'IGNORE';
495 my $starttime = time ();
497 my @psync = POSIX
::pipe();
498 my @csync = POSIX
::pipe();
499 my @ctrlfd = POSIX
::pipe() if $sync;
501 my $node = $self->{nodename
};
504 die "unable to fork worker - $!" if !defined($cpid);
506 my $workerpuid = $cpid ?
$cpid : $$;
508 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
509 die "unable to read process start time";
511 my $upid = PVE
::Tools
::upid_encode
({
512 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
513 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
517 if (!$cpid) { # child
522 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
524 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
525 $SIG{TTOU
} = 'IGNORE';
528 # set session/process group allows to kill the process group
529 if ($sync && -t STDIN
) {
530 # some sync'ed workers operate on the tty but setsid sessions lose
531 # the tty, so just create a new pgroup and give it the tty
532 $ppgid = POSIX
::getpgrp() or die "failed to get old pgid: $!\n";
533 POSIX
::setpgid
(0, 0) or die "failed to setpgid: $!\n";
534 POSIX
::tcsetpgrp
(fileno(STDIN
), $$) or die "failed to tcsetpgrp: $!\n";
539 POSIX
::close ($psync[0]);
540 POSIX
::close ($ctrlfd[0]) if $sync;
541 POSIX
::close ($csync[1]);
543 $outfh = $sync ?
$psync[1] : undef;
544 my $resfh = $sync ?
$ctrlfd[1] : undef;
547 PVE
::INotify
::inotify_close
();
549 if (my $atfork = $self->{atfork
}) {
553 # same algorithm as used inside SA
555 my $fd = fileno (STDIN
);
559 POSIX
::close(0) if $fd != 0;
561 die "unable to redirect STDIN - $!"
562 if !open(STDIN
, "</dev/null");
564 $outfh = PVE
::Tools
::upid_open
($upid);
565 $resfh = fileno($outfh);
570 $fd = fileno(STDOUT
);
572 POSIX
::close (1) if $fd != 1;
574 die "unable to redirect STDOUT - $!"
575 if !open(STDOUT
, ">&", $outfh);
577 STDOUT-
>autoflush (1);
579 # redirect STDERR to STDOUT
580 $fd = fileno (STDERR
);
582 POSIX
::close(2) if $fd != 2;
584 die "unable to redirect STDERR - $!"
585 if !open(STDERR
, ">&1");
587 STDERR-
>autoflush(1);
590 my $msg = "ERROR: $err";
591 POSIX
::write($psync[1], $msg, length ($msg));
592 POSIX
::close($psync[1]);
597 # sync with parent (signal that we are ready)
598 POSIX
::write($psync[1], $upid, length ($upid));
599 POSIX
::close($psync[1]) if !$sync; # don't need output pipe if async
603 # sync with parent (wait until parent is ready)
604 POSIX
::read($csync[0], $readbuf, 4096);
605 die "parent setup error\n" if $readbuf ne 'OK';
607 if ($self->{type
} eq 'ha') {
608 print "task started by HA resource agent\n";
612 my ($msg, $exitcode);
618 $msg = "TASK ERROR: $err\n";
624 POSIX
::write($resfh, $msg, length($msg));
627 POSIX
::close($resfh);
629 POSIX
::tcsetpgrp
(fileno(STDIN
), $ppgid) or
630 die "failed to tcsetpgrp to parent: $!\n";
633 POSIX
::_exit
($exitcode);
634 kill(-9, $$); # not really needed, just to be sure
639 POSIX
::close ($psync[1]);
640 POSIX
::close ($ctrlfd[1]) if $sync;
641 POSIX
::close ($csync[0]);
644 # sync with child (wait until child starts)
645 POSIX
::read($psync[0], $readbuf, 4096);
648 POSIX
::close($psync[0]);
649 &$register_worker($cpid, $user, $upid);
655 die "got no worker upid - start worker failed\n" if !$readbuf;
657 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
658 die "starting worker failed: $1\n";
661 if ($readbuf ne $upid) {
662 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
666 $outfh = PVE
::Tools
::upid_open
($upid);
673 POSIX
::write($csync[1], $msg, length ($msg));
674 POSIX
::close($csync[1]);
677 POSIX
::close($csync[1]);
678 kill(-9, $cpid); # make sure it gets killed
682 $self->log_cluster_msg('info', $user, "starting task $upid");
684 my $tlist = $self->active_workers($upid, $sync);
685 eval { $self->broadcast_tasklist($tlist); };
686 syslog
('err', $@) if $@;
692 $tee_worker->($psync[0], $ctrlfd[0], $outfh, $cpid);
694 &$kill_process_group($cpid, $pstart); # make sure it gets killed
700 &$log_task_result($upid, $user, $res);
703 return wantarray ?
($upid, $res) : $upid;
708 sub log_cluster_msg
{
709 my ($self, $pri, $user, $msg) = @_;
711 syslog
($pri, "%s", $msg);
713 # PVE::Cluster::log_msg($pri, $user, $msg);
716 sub broadcast_tasklist
{
717 my ($self, $tlist) = @_;
719 # PVE::Cluster::broadcast_tasklist($tlist);
722 sub check_api2_permissions
{
723 my ($self, $perm, $username, $param) = @_;
725 return 1 if !$username && $perm->{user
} eq 'world';
727 raise_perm_exc
("user != null") if !$username;
729 return 1 if $username eq 'root@pam';
731 raise_perm_exc
('user != root@pam') if !$perm;
733 return 1 if $perm->{user
} && $perm->{user
} eq 'all';
735 ##return $self->exec_api2_perm_check($perm->{check}, $username, $param)
741 # init_request - should be called before each REST/CLI request
743 my ($self, %params) = @_;
745 $self->{result_attributes
} = {}
747 # if you nedd more, implement in subclass