]>
git.proxmox.com Git - pve-common.git/blob - src/PVE/RESTEnvironment.pm
e8a466c2245480b4f25c9cadd1c8a4c44dadaad1
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)
125 foreach my $p (keys %params) {
126 if ($p eq 'atfork') {
127 $self->{$p} = $params{$p};
129 die "unknown option '$p'";
135 my ($sysname, $nodename) = POSIX
::uname
();
137 $nodename =~ s/\..*$//; # strip domain part, if any
139 $self->{nodename
} = $nodename;
144 # convenience function for command line tools
145 sub setup_default_cli_env
{
146 my ($class, $username) = @_;
148 $class = ref($class) || $class;
150 $username //= 'root@pam';
152 PVE
::INotify
::inotify_init
();
154 my $rpcenv = $class->init('cli');
155 $rpcenv->init_request();
156 $rpcenv->set_language($ENV{LANG
});
157 $rpcenv->set_user($username);
159 die "please run as root\n"
160 if ($username eq 'root@pam') && ($> != 0);
166 die "REST environment not initialized" if !$rest_env;
172 my ($self, $ip) = @_;
174 $self->{client_ip
} = $ip;
180 return $self->{client_ip
};
183 sub set_result_attrib
{
184 my ($self, $key, $value) = @_;
186 $self->{result_attributes
}->{$key} = $value;
189 sub get_result_attrib
{
190 my ($self, $key) = @_;
192 return $self->{result_attributes
}->{$key};
196 my ($self, $lang) = @_;
198 # fixme: initialize I18N
200 $self->{language
} = $lang;
206 return $self->{language
};
210 my ($self, $user) = @_;
212 $self->{user
} = $user;
216 my ($self, $noerr) = @_;
218 return $self->{user
} if defined($self->{user
}) || $noerr;
220 die "user name not set\n";
223 sub set_u2f_challenge
{
224 my ($self, $challenge) = @_;
226 $self->{u2f_challenge
} = $challenge;
229 sub get_u2f_challenge
{
230 my ($self, $noerr) = @_;
232 return $self->{u2f_challenge
} if defined($self->{u2f_challenge
}) || $noerr;
234 die "no active u2f challenge\n";
237 sub set_request_host
{
238 my ($self, $host) = @_;
240 $self->{request_host
} = $host;
243 sub get_request_host
{
244 my ($self, $noerr) = @_;
246 return $self->{request_host
} if defined($self->{request_host
}) || $noerr;
248 die "no hostname available in current environment\n";
257 # read/update list of active workers
258 # we move all finished tasks to the archive index,
259 # but keep aktive and most recent task in the active file.
260 # $nocheck ... consider $new_upid still running (avoid that
261 # we try to read the reult to early.
263 my ($self, $new_upid, $nocheck) = @_;
265 my $lkfn = "/var/log/pve/tasks/.active.lock";
271 my $tasklist = PVE
::INotify
::read_file
('active');
275 my $thash = {}; # only list task once
277 my $check_task = sub {
278 my ($task, $running) = @_;
280 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
286 delete $task->{pstart
};
289 foreach my $task (@$tasklist) {
290 my $upid = $task->{upid
};
291 next if $thash->{$upid};
292 $thash->{$upid} = $task;
296 if ($new_upid && !(my $task = $thash->{$new_upid})) {
297 $task = PVE
::Tools
::upid_decode
($new_upid);
298 $task->{upid
} = $new_upid;
299 $thash->{$new_upid} = $task;
300 &$check_task($task, $nocheck);
304 @ta = sort { $b->{starttime
} <=> $a->{starttime
} } @ta;
306 my $save = defined($new_upid);
308 foreach my $task (@ta) {
309 next if $task->{endtime
};
310 $task->{endtime
} = time();
311 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
317 foreach my $task (@ta) {
318 if (!$task->{saved
}) {
319 $archive .= sprintf("%s %08X %s\n", $task->{upid
}, $task->{endtime
}, $task->{status
});
328 my $filename = "/var/log/pve/tasks/index";
330 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
331 die "unable to open file '$filename' - $!\n";
332 PVE
::Tools
::safe_print
($filename, $fh, $archive);
335 die "unable to close file '$filename' - $!\n";
340 foreach my $task (@arlist) { # mark as not saved
344 my $maxsize = 50000; # about 1000 entries
345 if ($size > $maxsize) {
346 rename($filename, "$filename.1");
350 # we try to reduce the amount of data
351 # list all running tasks and task and a few others
352 # try to limit to 25 tasks
353 my $max = 25 - scalar(@$tlist);
354 foreach my $task (@ta) {
360 PVE
::INotify
::write_file
('active', $tlist) if $save;
365 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
371 my $kill_process_group = sub {
372 my ($pid, $pstart) = @_;
374 # send kill to process group (negative pid)
377 # always send signal to all pgrp members
378 kill(15, $kpid); # send TERM signal
380 # give max 5 seconds to shut down
381 for (my $i = 0; $i < 5; $i++) {
382 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
391 my ($self, $upid, $killit) = @_;
393 my $task = PVE
::Tools
::upid_decode
($upid);
395 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
397 return 0 if !$running;
400 &$kill_process_group($task->{pid
});
407 # acts almost as tee: writes an output both to STDOUT and a task log,
408 # we differ as we're worker aware and look also at the childs control pipe,
409 # so we know if the function could be executed successfully or not.
410 my $tee_worker = sub {
411 my ($childfd, $ctrlfd, $taskfh, $cpid) = @_;
415 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
416 # always send signal to all pgrp members
418 if ($int_count < 3) {
419 kill(15, $kpid); # send TERM signal
421 kill(9, $kpid); # send KILL signal
425 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
427 my $select = new IO
::Select
;
428 my $fh = IO
::Handle-
>new_from_fd($childfd, 'r');
433 while ($select->count) {
434 my @handles = $select->can_read(1);
435 if (scalar(@handles)) {
436 my $count = sysread ($handles[0], $readbuf, 4096);
437 if (!defined ($count)) {
439 die "sync pipe read error: $err\n";
441 last if $count == 0; # eof
446 print $taskfh $readbuf;
449 # some commands daemonize without closing stdout
450 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
454 POSIX
::read($ctrlfd, $readbuf, 4096);
455 if ($readbuf =~ m/^TASK OK\n?$/) {
456 # skip printing to stdout
457 print $taskfh $readbuf;
458 } elsif ($readbuf =~ m/^TASK ERROR: (.*)\n?$/) {
460 print $taskfh "\n$readbuf"; # ensure start on new line for webUI
461 } elsif ($readbuf =~ m/^TASK WARNINGS: (\d+)\n?$/) {
462 print STDERR
"Task finished with $1 warning(s)!\n";
463 print $taskfh "\n$readbuf"; # ensure start on new line for webUI
465 die "got unexpected control message: $readbuf\n";
471 POSIX
::close($childfd);
472 POSIX
::close($ctrlfd);
476 print STDERR
"$err\n";
477 print $taskfh "TASK ERROR: $err\n";
481 # start long running workers
482 # STDIN is redirected to /dev/null
483 # STDOUT,STDERR are redirected to the filename returned by upid_decode
484 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
486 my ($self, $dtype, $id, $user, $function, $background) = @_;
488 $dtype = 'unknown' if !defined ($dtype);
489 $id = '' if !defined ($id);
491 $user = 'root@pve' if !defined ($user);
493 my $sync = ($self->{type
} eq 'cli' && !$background) ?
1 : 0;
498 local $SIG{TERM
} = 'IGNORE';
500 my $starttime = time ();
502 my @psync = POSIX
::pipe();
503 my @csync = POSIX
::pipe();
504 my @ctrlfd = POSIX
::pipe() if $sync;
506 my $node = $self->{nodename
};
509 die "unable to fork worker - $!" if !defined($cpid);
511 my $workerpuid = $cpid ?
$cpid : $$;
513 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
514 die "unable to read process start time";
516 my $upid = PVE
::Tools
::upid_encode
({
517 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
518 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
522 if (!$cpid) { # child
527 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
529 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
530 $SIG{TTOU
} = 'IGNORE';
533 # set session/process group allows to kill the process group
534 if ($sync && -t STDIN
) {
535 # some sync'ed workers operate on the tty but setsid sessions lose
536 # the tty, so just create a new pgroup and give it the tty
537 $ppgid = POSIX
::getpgrp() or die "failed to get old pgid: $!\n";
538 POSIX
::setpgid
(0, 0) or die "failed to setpgid: $!\n";
539 POSIX
::tcsetpgrp
(fileno(STDIN
), $$) or die "failed to tcsetpgrp: $!\n";
544 POSIX
::close ($psync[0]);
545 POSIX
::close ($ctrlfd[0]) if $sync;
546 POSIX
::close ($csync[1]);
548 $outfh = $sync ?
$psync[1] : undef;
549 my $resfh = $sync ?
$ctrlfd[1] : undef;
552 PVE
::INotify
::inotify_close
();
554 if (my $atfork = $self->{atfork
}) {
558 # same algorithm as used inside SA
560 my $fd = fileno (STDIN
);
564 POSIX
::close(0) if $fd != 0;
566 die "unable to redirect STDIN - $!"
567 if !open(STDIN
, "</dev/null");
569 $outfh = PVE
::Tools
::upid_open
($upid);
570 $resfh = fileno($outfh);
575 $fd = fileno(STDOUT
);
577 POSIX
::close (1) if $fd != 1;
579 die "unable to redirect STDOUT - $!"
580 if !open(STDOUT
, ">&", $outfh);
582 STDOUT-
>autoflush (1);
584 # redirect STDERR to STDOUT
585 $fd = fileno (STDERR
);
587 POSIX
::close(2) if $fd != 2;
589 die "unable to redirect STDERR - $!"
590 if !open(STDERR
, ">&1");
592 STDERR-
>autoflush(1);
595 my $msg = "ERROR: $err";
596 POSIX
::write($psync[1], $msg, length ($msg));
597 POSIX
::close($psync[1]);
602 # sync with parent (signal that we are ready)
603 POSIX
::write($psync[1], $upid, length ($upid));
604 POSIX
::close($psync[1]) if !$sync; # don't need output pipe if async
608 # sync with parent (wait until parent is ready)
609 POSIX
::read($csync[0], $readbuf, 4096);
610 die "parent setup error\n" if $readbuf ne 'OK';
612 if ($self->{type
} eq 'ha') {
613 print "task started by HA resource agent\n";
617 my ($msg, $exitcode);
623 $msg = "TASK ERROR: $err\n";
625 } elsif (my $warnings = $self->{warning_count
}) {
626 $msg = "TASK WARNINGS: $warnings\n";
632 POSIX
::write($resfh, $msg, length($msg));
635 POSIX
::close($resfh);
637 POSIX
::tcsetpgrp
(fileno(STDIN
), $ppgid) or
638 die "failed to tcsetpgrp to parent: $!\n";
641 POSIX
::_exit
($exitcode);
642 kill(-9, $$); # not really needed, just to be sure
647 POSIX
::close ($psync[1]);
648 POSIX
::close ($ctrlfd[1]) if $sync;
649 POSIX
::close ($csync[0]);
652 # sync with child (wait until child starts)
653 POSIX
::read($psync[0], $readbuf, 4096);
656 POSIX
::close($psync[0]);
657 &$register_worker($cpid, $user, $upid);
663 die "got no worker upid - start worker failed\n" if !$readbuf;
665 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
666 die "starting worker failed: $1\n";
669 if ($readbuf ne $upid) {
670 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
674 $outfh = PVE
::Tools
::upid_open
($upid);
681 POSIX
::write($csync[1], $msg, length ($msg));
682 POSIX
::close($csync[1]);
685 POSIX
::close($csync[1]);
686 kill(-9, $cpid); # make sure it gets killed
690 $self->log_cluster_msg('info', $user, "starting task $upid");
692 my $tlist = $self->active_workers($upid, $sync);
693 eval { $self->broadcast_tasklist($tlist); };
694 syslog
('err', $@) if $@;
700 $tee_worker->($psync[0], $ctrlfd[0], $outfh, $cpid);
702 &$kill_process_group($cpid, $pstart); # make sure it gets killed
708 &$log_task_result($upid, $user, $res);
711 return wantarray ?
($upid, $res) : $upid;
715 my ($self, $message) = @_;
719 print STDERR
"WARN: $message\n";
721 $self->{warning_count
}++;
726 sub log_cluster_msg
{
727 my ($self, $pri, $user, $msg) = @_;
729 syslog
($pri, "%s", $msg);
731 # PVE::Cluster::log_msg($pri, $user, $msg);
734 sub broadcast_tasklist
{
735 my ($self, $tlist) = @_;
737 # PVE::Cluster::broadcast_tasklist($tlist);
740 sub check_api2_permissions
{
741 my ($self, $perm, $username, $param) = @_;
743 return 1 if !$username && $perm->{user
} eq 'world';
745 raise_perm_exc
("user != null") if !$username;
747 return 1 if $username eq 'root@pam';
749 raise_perm_exc
('user != root@pam') if !$perm;
751 return 1 if $perm->{user
} && $perm->{user
} eq 'all';
753 ##return $self->exec_api2_perm_check($perm->{check}, $username, $param)
759 # init_request - should be called before each REST/CLI request
761 my ($self, %params) = @_;
763 $self->{result_attributes
} = {}
765 # if you nedd more, implement in subclass