]>
git.proxmox.com Git - pve-access-control.git/blob - PVE/RPCEnvironment.pm
a0c0c3328f2313ce0f73d1e453808ea6b4f968ee
1 package PVE
::RPCEnvironment
;
5 use POSIX
qw(:sys_wait_h EINTR);
15 use PVE
::AccessControl
;
18 # we use this singleton class to pass RPC related environment values
22 # save $SIG{CHLD} handler implementation.
23 # simply set $SIG{CHLD} = $worker_reaper;
24 # and register forked processes with &$register_worker(pid)
25 # Note: using $SIG{CHLD} = 'IGNORE' or $SIG{CHLD} = sub { wait (); } or ...
26 # has serious side effects, because perls built in system() and open()
27 # functions can't get the correct exit status of a child. So we cant use
28 # that (also see perlipc)
32 my $log_task_result = sub {
33 my ($upid, $user, $status) = @_;
35 my $msg = 'successful';
38 my $ec = $status >> 8;
39 my $ic = $status & 255;
40 $msg = $ec ?
"failed ($ec)" : "interrupted ($ic)";
43 my $tlist = active_workers
($upid);
44 PVE
::Cluster
::broadcast_tasklist
($tlist);
46 foreach my $t (@$tlist) {
47 if ($t->{upid
} eq $upid) {
52 if ($task && $task->{status
}) {
53 $msg = $task->{status
};
55 PVE
::Cluster
::log_msg
($pri, $user, "end task $upid $msg");
58 my $worker_reaper = sub {
60 foreach my $pid (keys %$WORKER_PIDS) {
61 my $waitpid = waitpid ($pid, WNOHANG
);
62 if (defined($waitpid) && ($waitpid == $pid)) {
63 my $info = $WORKER_PIDS->{$pid};
64 if ($info && $info->{upid
} && $info->{user
}) {
65 &$log_task_result($info->{upid
}, $info->{user
}, $?);
67 delete ($WORKER_PIDS->{$pid});
72 my $register_worker = sub {
73 my ($pid, $user, $upid) = @_;
77 # do not register if already finished
78 my $waitpid = waitpid ($pid, WNOHANG
);
79 if (defined($waitpid) && ($waitpid == $pid)) {
80 delete ($WORKER_PIDS->{$pid});
84 $WORKER_PIDS->{$pid} = {
92 my $compile_acl = sub {
93 my ($self, $user) = @_;
96 my $cfg = $self->{user_cfg
};
98 return undef if !$cfg->{roles
};
100 if ($user eq 'root@pam') { # root can do anything
101 return {'/' => $cfg->{roles
}->{'Administrator'}};
104 foreach my $path (sort keys %{$cfg->{acl
}}) {
105 my @ra = PVE
::AccessControl
::roles
($cfg, $user, $path);
108 foreach my $role (@ra) {
109 if (my $privset = $cfg->{roles
}->{$role}) {
110 foreach my $p (keys %$privset) {
116 $res->{$path} = $privs;
123 my ($self, $user, $path) = @_;
125 $user = PVE
::AccessControl
::verify_username
($user, 1);
128 my $cache = $self->{aclcache
};
130 my $acl = $cache->{$user};
133 if (!($acl = &$compile_acl($self, $user))) {
136 $cache->{$user} = $acl;
141 if (!($perm = $acl->{$path})) {
143 foreach my $p (sort keys %$acl) {
144 my $final = ($path eq $p);
146 next if !(($p eq '/') || $final || ($path =~ m
|^$p/|));
150 $acl->{$path} = $perm;
157 my ($self, $user, $path, $privs) = @_;
159 my $perm = $self->permissions($user, $path);
161 foreach my $priv (@$privs) {
162 return undef if !$perm->{$priv};
169 my ($self, $user) = @_;
171 my $cfg = $self->{user_cfg
};
172 return PVE
::AccessControl
::user_enabled
($cfg, $user);
175 # initialize environment - must be called once at program startup
177 my ($class, $type, %params) = @_;
179 $class = ref($class) || $class;
181 die "already initialized" if $pve_env;
183 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv)$/;
185 $SIG{CHLD
} = $worker_reaper;
188 # cli ... command started fron command line
189 # pub ... access from public server (apache)
190 # priv ... access from private server (pvedaemon)
201 foreach my $p (keys %params) {
202 if ($p eq 'atfork') {
203 $self->{$p} = $params{$p};
205 die "unknown option '$p'";
211 my ($sysname, $nodename) = POSIX
::uname
();
213 $nodename =~ s/\..*$//; # strip domain part, if any
215 $self->{nodename
} = $nodename;
223 die "not initialized" if !$pve_env;
229 my ($self, $enable_upload) = @_;
231 if ($self->{request_rec
}) {
233 if ($enable_upload) {
234 $cgi = CGI-
>new($self->{request_rec
});
236 # disable upload using empty upload_hook
237 $cgi = CGI-
>new($self->{request_rec
}, sub {}, undef, 0);
240 my $params = $cgi->Vars();
242 } elsif ($self->{params
}) {
243 return $self->{params
};
245 die "no parameters registered";
249 sub get_upload_info
{
250 my ($self, $param) = @_;
252 my $cgi = $self->{cgi
};
253 die "CGI not initialized" if !$cgi;
255 my $pd = $cgi->param($param);
256 die "unable to get cgi parameter info\n" if !$pd;
257 my $info = $cgi->uploadInfo($pd);
258 die "unable to get cgi upload info\n" if !$info;
260 my $res = { %$info };
262 my $tmpfilename = $cgi->tmpFileName($pd);
263 die "unable to get cgi upload file name\n" if !$tmpfilename;
264 $res->{tmpfilename
} = $tmpfilename;
266 #my $hndl = $cgi->upload($param);
267 #die "unable to get cgi upload handle\n" if !$hndl;
268 #$res->{handle} = $hndl->handle;
273 # init_request - must be called before each RPC request
275 my ($self, %params) = @_;
277 PVE
::Cluster
::cfs_update
();
279 my $userconfig; # we use this for regression tests
280 foreach my $p (keys %params) {
281 if ($p eq 'userconfig') {
282 $userconfig = $params{$p};
283 } elsif ($p eq 'request_rec') {
284 # pass Apache2::RequestRec
285 $self->{request_rec
} = $params{$p};
286 } elsif ($p eq 'params') {
287 $self->{params
} = $params{$p};
289 die "unknown parameter '$p'";
294 $self->{aclcache
} = {};
296 my $ucdata = PVE
::Tools
::file_get_contents
($userconfig);
297 my $cfg = PVE
::AccessControl
::parse_user_config
($userconfig, $ucdata);
298 $self->{user_cfg
} = $cfg;
300 my $ucvers = PVE
::Cluster
::cfs_file_version
('user.cfg');
301 if (!$self->{aclcache
} || !defined($self->{aclversion
}) ||
302 !defined($ucvers) || ($ucvers ne $self->{aclversion
})) {
303 $self->{aclversion
} = $ucvers;
304 my $cfg = PVE
::Cluster
::cfs_read_file
('user.cfg');
305 $self->{user_cfg
} = $cfg;
310 $self->{user_cfg
} = {};
311 die "Unable to load access control list: $err";
316 my ($self, $ip) = @_;
318 $self->{client_ip
} = $ip;
324 return $self->{client_ip
};
327 sub set_result_count
{
328 my ($self, $count) = @_;
330 $self->{result_count
} = $count;
333 sub get_result_count
{
336 return $self->{result_count
};
340 my ($self, $lang) = @_;
342 # fixme: initialize I18N
344 $self->{language
} = $lang;
350 return $self->{language
};
354 my ($self, $user) = @_;
358 $self->{user
} = $user;
364 die "user name not set\n" if !$self->{user
};
366 return $self->{user
};
369 # read/update list of active workers
370 # we move all finished tasks to the archive index,
371 # but keep aktive and most recent task in the active file.
372 # $nocheck ... consider $new_upid still running (avoid that
373 # we try to read the reult to early.
375 my ($new_upid, $nocheck) = @_;
377 my $lkfn = "/var/log/pve/tasks/.active.lock";
383 my $tasklist = PVE
::INotify
::read_file
('active');
387 my $thash = {}; # only list task once
389 my $check_task = sub {
390 my ($task, $running) = @_;
392 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
398 delete $task->{pstart
};
401 foreach my $task (@$tasklist) {
402 my $upid = $task->{upid
};
403 next if $thash->{$upid};
404 $thash->{$upid} = $task;
408 if ($new_upid && !(my $task = $thash->{$new_upid})) {
409 $task = PVE
::Tools
::upid_decode
($new_upid);
410 $task->{upid
} = $new_upid;
411 $thash->{$new_upid} = $task;
412 &$check_task($task, $nocheck);
416 @ta = sort { $b->{starttime
} cmp $a->{starttime
} } @ta;
418 my $save = defined($new_upid);
420 foreach my $task (@ta) {
421 next if $task->{endtime
};
422 $task->{endtime
} = time();
423 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
429 foreach my $task (@ta) {
430 if (!$task->{saved
}) {
431 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime
});
440 my $filename = "/var/log/pve/tasks/index";
442 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
443 die "unable to open file '$filename' - $!\n";
444 PVE
::Tools
::safe_print
($filename, $fh, $archive);
447 die "unable to close file '$filename' - $!\n";
452 foreach my $task (@arlist) { # mark as not saved
456 my $maxsize = 50000; # about 1000 entries
457 if ($size > $maxsize) {
458 rename($filename, "$filename.1");
462 # we try to reduce the amount of data
463 # list all running tasks and task and a few others
464 # try to limit to 25 tasks
466 my $max = 25 - scalar(@$tlist);
467 foreach my $task (@ta) {
473 PVE
::INotify
::write_file
('active', $tlist) if $save;
478 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
484 my $kill_process_group = sub {
485 my ($pid, $pstart) = @_;
487 # send kill to process group (negative pid)
490 # always send signal to all pgrp members
491 kill(15, $kpid); # send TERM signal
493 # give max 5 seconds to shut down
494 for (my $i = 0; $i < 5; $i++) {
495 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
504 my ($upid, $killit) = @_;
506 my $task = PVE
::Tools
::upid_decode
($upid);
508 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
510 return 0 if !$running;
513 &$kill_process_group($task->{pid
});
520 # start long running workers
521 # STDIN is redirected to /dev/null
522 # STDOUT,STDERR are redirected to the filename returned by upid_decode
523 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
525 my ($self, $dtype, $id, $user, $function) = @_;
527 $dtype = 'unknown' if !defined ($dtype);
528 $id = '' if !defined ($id);
530 $user = 'root@pve' if !defined ($user);
532 my $sync = $self->{type
} eq 'cli' ?
1 : 0;
537 local $SIG{TERM
} = 'IGNORE';
539 my $starttime = time ();
541 my @psync = POSIX
::pipe();
542 my @csync = POSIX
::pipe();
544 my $node = $self->{nodename
};
547 die "unable to fork worker - $!" if !defined($cpid);
549 my $workerpuid = $cpid ?
$cpid : $$;
551 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
552 die "unable to read process start time";
554 my $upid = PVE
::Tools
::upid_encode
({
555 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
556 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
560 if (!$cpid) { # child
564 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
566 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
568 # set sess/process group - we want to be able to kill the
569 # whole process group
572 POSIX
::close ($psync[0]);
573 POSIX
::close ($csync[1]);
575 $outfh = $sync ?
$psync[1] : undef;
578 PVE
::INotify
::inotify_close
();
580 if (my $atfork = $self->{atfork
}) {
584 # same algorythm as used inside SA
586 my $fd = fileno (STDIN
);
590 POSIX
::close(0) if $fd != 0;
592 die "unable to redirect STDIN - $!"
593 if !open(STDIN
, "</dev/null");
595 $outfh = PVE
::Tools
::upid_open
($upid);
600 $fd = fileno(STDOUT
);
602 POSIX
::close (1) if $fd != 1;
604 die "unable to redirect STDOUT - $!"
605 if !open(STDOUT
, ">&", $outfh);
607 STDOUT-
>autoflush (1);
609 # redirect STDERR to STDOUT
610 $fd = fileno (STDERR
);
612 POSIX
::close(2) if $fd != 2;
614 die "unable to redirect STDERR - $!"
615 if !open(STDERR
, ">&1");
617 STDERR-
>autoflush(1);
620 my $msg = "ERROR: $err";
621 POSIX
::write($psync[1], $msg, length ($msg));
622 POSIX
::close($psync[1]);
627 # sync with parent (signal that we are ready)
631 POSIX
::write($psync[1], $upid, length ($upid));
632 POSIX
::close($psync[1]);
636 # sync with parent (wait until parent is ready)
637 POSIX
::read($csync[0], $readbuf, 4096);
638 die "parent setup error\n" if $readbuf ne 'OK';
640 eval { &$function($upid); };
646 print STDERR
"TASK ERROR: $err\n";
649 print STDERR
"TASK OK\n";
657 POSIX
::close ($psync[1]);
658 POSIX
::close ($csync[0]);
661 # sync with child (wait until child starts)
662 POSIX
::read($psync[0], $readbuf, 4096);
665 POSIX
::close($psync[0]);
666 &$register_worker($cpid, $user, $upid);
672 die "got no worker upid - start worker failed\n" if !$readbuf;
674 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
675 die "starting worker failed: $1\n";
678 if ($readbuf ne $upid) {
679 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
683 $outfh = PVE
::Tools
::upid_open
($upid);
690 POSIX
::write($csync[1], $msg, length ($msg));
691 POSIX
::close($csync[1]);
694 POSIX
::close($csync[1]);
695 kill(-9, $cpid); # make sure it gets killed
699 PVE
::Cluster
::log_msg
('info', $user, "starting task $upid");
701 my $tlist = active_workers
($upid, $sync);
702 PVE
::Cluster
::broadcast_tasklist
($tlist);
711 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
712 # always send signal to all pgrp members
714 if ($int_count < 3) {
715 kill(15, $kpid); # send TERM signal
717 kill(9, $kpid); # send KILL signal
721 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
723 my $select = new IO
::Select
;
724 my $fh = IO
::Handle-
>new_from_fd($psync[0], 'r');
727 while ($select->count) {
728 my @handles = $select->can_read(1);
729 if (scalar(@handles)) {
730 my $count = sysread ($handles[0], $readbuf, 4096);
731 if (!defined ($count)) {
733 die "sync pipe read error: $err\n";
735 last if $count == 0; # eof
738 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
741 if ($data =~ m/^TASK OK$/) {
743 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
754 # some commands daemonize without closing stdout
755 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
761 POSIX
::close($psync[0]);
763 if ($outbuf) { # just to be sure
766 print $outfh $outbuf;
772 print STDERR
"$err\n";
774 print $outfh "TASK ERROR: $err\n";
778 &$kill_process_group($cpid, $pstart); # make sure it gets killed
784 &$log_task_result($upid, $user, $res);
787 return wantarray ?
($upid, $res) : $upid;