]>
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
15 use POSIX
qw(:sys_wait_h EINTR);
17 use PVE
::Exception
qw(raise raise_perm_exc);
25 # save $SIG{CHLD} handler implementation.
26 # simply set $SIG{CHLD} = $worker_reaper;
27 # and register forked processes with &$register_worker(pid)
28 # Note: using $SIG{CHLD} = 'IGNORE' or $SIG{CHLD} = sub { wait (); } or ...
29 # has serious side effects, because perls built in system() and open()
30 # functions can't get the correct exit status of a child. So we can't use
31 # that (also see perlipc)
36 my $log_task_result = sub {
37 my ($upid, $user, $status) = @_;
41 my $msg = 'successful';
44 my $ec = $status >> 8;
45 my $ic = $status & 255;
46 $msg = $ec ?
"failed ($ec)" : "interrupted ($ic)";
50 my $tlist = $rest_env->active_workers($upid);
51 eval { $rest_env->broadcast_tasklist($tlist); };
52 syslog
('err', $@) if $@;
55 foreach my $t (@$tlist) {
56 if ($t->{upid
} eq $upid) {
61 if ($task && $task->{status
}) {
62 $msg = $task->{status
};
65 $rest_env->log_cluster_msg($pri, $user, "end task $upid $msg");
68 my $worker_reaper = sub {
70 foreach my $pid (keys %$WORKER_PIDS) {
71 my $waitpid = waitpid ($pid, WNOHANG
);
72 if (defined($waitpid) && ($waitpid == $pid)) {
73 my $info = $WORKER_PIDS->{$pid};
74 if ($info && $info->{upid
} && $info->{user
}) {
75 &$log_task_result($info->{upid
}, $info->{user
}, $?);
77 delete ($WORKER_PIDS->{$pid});
82 my $register_worker = sub {
83 my ($pid, $user, $upid) = @_;
87 # do not register if already finished
88 my $waitpid = waitpid ($pid, WNOHANG
);
89 if (defined($waitpid) && ($waitpid == $pid)) {
90 delete ($WORKER_PIDS->{$pid});
94 $WORKER_PIDS->{$pid} = {
100 # initialize environment - must be called once at program startup
102 my ($class, $type, %params) = @_;
104 $class = ref($class) || $class;
106 die "already initialized" if $rest_env;
108 die "unknown environment type"
109 if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
111 $SIG{CHLD
} = $worker_reaper;
114 # cli ... command started fron command line
115 # pub ... access from public server (pveproxy)
116 # priv ... access from private server (pvedaemon)
117 # ha ... access from HA resource manager agent (pve-ha-manager)
126 foreach my $p (keys %params) {
127 if ($p eq 'atfork') {
128 $self->{$p} = $params{$p};
130 die "unknown option '$p'";
136 my ($sysname, $nodename) = POSIX
::uname
();
138 $nodename =~ s/\..*$//; # strip domain part, if any
140 $self->{nodename
} = $nodename;
145 # convenience function for command line tools
146 sub setup_default_cli_env
{
147 my ($class, $username) = @_;
149 $class = ref($class) || $class;
151 $username //= 'root@pam';
153 PVE
::INotify
::inotify_init
();
155 my $rpcenv = $class->init('cli');
156 $rpcenv->init_request();
157 $rpcenv->set_language($ENV{LANG
});
158 $rpcenv->set_user($username);
160 die "please run as root\n"
161 if ($username eq 'root@pam') && ($> != 0);
167 die "REST environment not initialized" if !$rest_env;
173 my ($self, $ip) = @_;
175 $self->{client_ip
} = $ip;
181 return $self->{client_ip
};
184 sub set_result_attrib
{
185 my ($self, $key, $value) = @_;
187 $self->{result_attributes
}->{$key} = $value;
190 sub get_result_attrib
{
191 my ($self, $key) = @_;
193 return $self->{result_attributes
}->{$key};
197 my ($self, $lang) = @_;
199 # fixme: initialize I18N
201 $self->{language
} = $lang;
207 return $self->{language
};
211 my ($self, $user) = @_;
213 $self->{user
} = $user;
217 my ($self, $noerr) = @_;
219 return $self->{user
} if defined($self->{user
}) || $noerr;
221 die "user name not set\n";
224 sub set_u2f_challenge
{
225 my ($self, $challenge) = @_;
227 $self->{u2f_challenge
} = $challenge;
230 sub get_u2f_challenge
{
231 my ($self, $noerr) = @_;
233 return $self->{u2f_challenge
} if defined($self->{u2f_challenge
}) || $noerr;
235 die "no active u2f challenge\n";
238 sub set_request_host
{
239 my ($self, $host) = @_;
241 $self->{request_host
} = $host;
244 sub get_request_host
{
245 my ($self, $noerr) = @_;
247 return $self->{request_host
} if defined($self->{request_host
}) || $noerr;
249 die "no hostname available in current environment\n";
258 # read/update list of active workers
259 # we move all finished tasks to the archive index,
260 # but keep aktive and most recent task in the active file.
261 # $nocheck ... consider $new_upid still running (avoid that
262 # we try to read the reult to early.
264 my ($self, $new_upid, $nocheck) = @_;
266 my $lkfn = "/var/log/pve/tasks/.active.lock";
272 my $tasklist = PVE
::INotify
::read_file
('active');
276 my $thash = {}; # only list task once
278 my $check_task = sub {
279 my ($task, $running) = @_;
281 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
287 delete $task->{pstart
};
290 foreach my $task (@$tasklist) {
291 my $upid = $task->{upid
};
292 next if $thash->{$upid};
293 $thash->{$upid} = $task;
297 if ($new_upid && !(my $task = $thash->{$new_upid})) {
298 $task = PVE
::Tools
::upid_decode
($new_upid);
299 $task->{upid
} = $new_upid;
300 $thash->{$new_upid} = $task;
301 &$check_task($task, $nocheck);
305 @ta = sort { $b->{starttime
} <=> $a->{starttime
} } @ta;
307 my $save = defined($new_upid);
309 foreach my $task (@ta) {
310 next if $task->{endtime
};
311 $task->{endtime
} = time();
312 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
318 foreach my $task (@ta) {
319 if (!$task->{saved
}) {
320 $archive .= sprintf("%s %08X %s\n", $task->{upid
}, $task->{endtime
}, $task->{status
});
329 my $filename = "/var/log/pve/tasks/index";
331 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
332 die "unable to open file '$filename' - $!\n";
333 PVE
::Tools
::safe_print
($filename, $fh, $archive);
336 die "unable to close file '$filename' - $!\n";
341 foreach my $task (@arlist) { # mark as not saved
345 my $maxsize = 50000; # about 1000 entries
346 if ($size > $maxsize) {
347 rename($filename, "$filename.1");
351 # we try to reduce the amount of data
352 # list all running tasks and task and a few others
353 # try to limit to 25 tasks
354 my $max = 25 - scalar(@$tlist);
355 foreach my $task (@ta) {
361 PVE
::INotify
::write_file
('active', $tlist) if $save;
366 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
372 my $kill_process_group = sub {
373 my ($pid, $pstart) = @_;
375 # send kill to process group (negative pid)
378 # always send signal to all pgrp members
379 kill(15, $kpid); # send TERM signal
381 # give max 5 seconds to shut down
382 for (my $i = 0; $i < 5; $i++) {
383 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
392 my ($self, $upid, $killit) = @_;
394 my $task = PVE
::Tools
::upid_decode
($upid);
396 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
398 return 0 if !$running;
401 &$kill_process_group($task->{pid
});
408 # acts almost as tee: writes an output both to STDOUT and a task log,
409 # we differ as we're worker aware and look also at the childs control pipe,
410 # so we know if the function could be executed successfully or not.
411 my $tee_worker = sub {
412 my ($childfd, $ctrlfd, $taskfh, $cpid) = @_;
416 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
417 # always send signal to all pgrp members
419 if ($int_count < 3) {
420 kill(15, $kpid); # send TERM signal
422 kill(9, $kpid); # send KILL signal
426 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
428 my $select = new IO
::Select
;
429 my $fh = IO
::Handle-
>new_from_fd($childfd, 'r');
434 while ($select->count) {
435 my @handles = $select->can_read(1);
436 if (scalar(@handles)) {
437 my $count = sysread ($handles[0], $readbuf, 4096);
438 if (!defined ($count)) {
440 die "sync pipe read error: $err\n";
442 last if $count == 0; # eof
447 print $taskfh $readbuf;
450 # some commands daemonize without closing stdout
451 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
455 POSIX
::read($ctrlfd, $readbuf, 4096);
456 if ($readbuf =~ m/^TASK OK\n?$/) {
457 # skip printing to stdout
458 print $taskfh $readbuf;
459 } elsif ($readbuf =~ m/^TASK ERROR: (.*)\n?$/) {
461 print $taskfh "\n$readbuf"; # ensure start on new line for webUI
462 } elsif ($readbuf =~ m/^TASK WARNINGS: (\d+)\n?$/) {
463 print STDERR
"Task finished with $1 warning(s)!\n";
464 print $taskfh "\n$readbuf"; # ensure start on new line for webUI
466 die "got unexpected control message: $readbuf\n";
472 POSIX
::close($childfd);
473 POSIX
::close($ctrlfd);
477 print STDERR
"$err\n";
478 print $taskfh "TASK ERROR: $err\n";
482 # start long running workers
483 # STDIN is redirected to /dev/null
484 # STDOUT,STDERR are redirected to the filename returned by upid_decode
485 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
487 my ($self, $dtype, $id, $user, $function, $background) = @_;
489 $dtype = 'unknown' if !defined ($dtype);
490 $id = '' if !defined ($id);
492 $user = 'root@pve' if !defined ($user);
494 my $sync = ($self->{type
} eq 'cli' && !$background) ?
1 : 0;
499 local $SIG{TERM
} = 'IGNORE';
501 my $starttime = time ();
503 my @psync = POSIX
::pipe();
504 my @csync = POSIX
::pipe();
505 my @ctrlfd = POSIX
::pipe() if $sync;
507 my $node = $self->{nodename
};
510 die "unable to fork worker - $!" if !defined($cpid);
512 my $workerpuid = $cpid ?
$cpid : $$;
514 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
515 die "unable to read process start time";
517 my $upid = PVE
::Tools
::upid_encode
({
518 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
519 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
523 if (!$cpid) { # child
528 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
530 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
531 $SIG{TTOU
} = 'IGNORE';
534 # set session/process group allows to kill the process group
535 if ($sync && -t STDIN
) {
536 # some sync'ed workers operate on the tty but setsid sessions lose
537 # the tty, so just create a new pgroup and give it the tty
538 $ppgid = POSIX
::getpgrp() or die "failed to get old pgid: $!\n";
539 POSIX
::setpgid
(0, 0) or die "failed to setpgid: $!\n";
540 POSIX
::tcsetpgrp
(fileno(STDIN
), $$) or die "failed to tcsetpgrp: $!\n";
545 POSIX
::close ($psync[0]);
546 POSIX
::close ($ctrlfd[0]) if $sync;
547 POSIX
::close ($csync[1]);
549 $outfh = $sync ?
$psync[1] : undef;
550 my $resfh = $sync ?
$ctrlfd[1] : undef;
553 PVE
::INotify
::inotify_close
();
555 if (my $atfork = $self->{atfork
}) {
559 # same algorithm as used inside SA
561 my $fd = fileno (STDIN
);
565 POSIX
::close(0) if $fd != 0;
567 die "unable to redirect STDIN - $!"
568 if !open(STDIN
, "</dev/null");
570 $outfh = PVE
::Tools
::upid_open
($upid);
571 $resfh = fileno($outfh);
576 $fd = fileno(STDOUT
);
578 POSIX
::close (1) if $fd != 1;
580 die "unable to redirect STDOUT - $!"
581 if !open(STDOUT
, ">&", $outfh);
583 STDOUT-
>autoflush (1);
585 # redirect STDERR to STDOUT
586 $fd = fileno (STDERR
);
588 POSIX
::close(2) if $fd != 2;
590 die "unable to redirect STDERR - $!"
591 if !open(STDERR
, ">&1");
593 STDERR-
>autoflush(1);
596 my $msg = "ERROR: $err";
597 POSIX
::write($psync[1], $msg, length ($msg));
598 POSIX
::close($psync[1]);
603 # sync with parent (signal that we are ready)
604 POSIX
::write($psync[1], $upid, length ($upid));
605 POSIX
::close($psync[1]) if !$sync; # don't need output pipe if async
609 # sync with parent (wait until parent is ready)
610 POSIX
::read($csync[0], $readbuf, 4096);
611 die "parent setup error\n" if $readbuf ne 'OK';
613 if ($self->{type
} eq 'ha') {
614 print "task started by HA resource agent\n";
618 my ($msg, $exitcode);
624 $msg = "TASK ERROR: $err\n";
626 } elsif (my $warnings = $self->{warning_count
}) {
627 $msg = "TASK WARNINGS: $warnings\n";
633 POSIX
::write($resfh, $msg, length($msg));
636 POSIX
::close($resfh);
638 POSIX
::tcsetpgrp
(fileno(STDIN
), $ppgid) or
639 die "failed to tcsetpgrp to parent: $!\n";
642 POSIX
::_exit
($exitcode);
643 kill(-9, $$); # not really needed, just to be sure
648 POSIX
::close ($psync[1]);
649 POSIX
::close ($ctrlfd[1]) if $sync;
650 POSIX
::close ($csync[0]);
653 # sync with child (wait until child starts)
654 POSIX
::read($psync[0], $readbuf, 4096);
657 POSIX
::close($psync[0]);
658 &$register_worker($cpid, $user, $upid);
664 die "got no worker upid - start worker failed\n" if !$readbuf;
666 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
667 die "starting worker failed: $1\n";
670 if ($readbuf ne $upid) {
671 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
675 $outfh = PVE
::Tools
::upid_open
($upid);
682 POSIX
::write($csync[1], $msg, length ($msg));
683 POSIX
::close($csync[1]);
686 POSIX
::close($csync[1]);
687 kill(-9, $cpid); # make sure it gets killed
691 $self->log_cluster_msg('info', $user, "starting task $upid");
693 my $tlist = $self->active_workers($upid, $sync);
694 eval { $self->broadcast_tasklist($tlist); };
695 syslog
('err', $@) if $@;
701 $tee_worker->($psync[0], $ctrlfd[0], $outfh, $cpid);
703 &$kill_process_group($cpid, $pstart); # make sure it gets killed
709 &$log_task_result($upid, $user, $res);
712 return wantarray ?
($upid, $res) : $upid;
716 my ($self, $message) = @_;
720 print STDERR
"WARN: $message\n";
722 $self->{warning_count
}++;
727 sub log_cluster_msg
{
728 my ($self, $pri, $user, $msg) = @_;
730 syslog
($pri, "%s", $msg);
732 # PVE::Cluster::log_msg($pri, $user, $msg);
735 sub broadcast_tasklist
{
736 my ($self, $tlist) = @_;
738 # PVE::Cluster::broadcast_tasklist($tlist);
741 sub check_api2_permissions
{
742 my ($self, $perm, $username, $param) = @_;
744 return 1 if !$username && $perm->{user
} eq 'world';
746 raise_perm_exc
("user != null") if !$username;
748 return 1 if $username eq 'root@pam';
750 raise_perm_exc
('user != root@pam') if !$perm;
752 return 1 if $perm->{user
} && $perm->{user
} eq 'all';
754 ##return $self->exec_api2_perm_check($perm->{check}, $username, $param)
760 # init_request - should be called before each REST/CLI request
762 my ($self, %params) = @_;
764 $self->{result_attributes
} = {}
766 # if you nedd more, implement in subclass