]>
git.proxmox.com Git - pve-access-control.git/blob - PVE/RPCEnvironment.pm
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|ha)$/;
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)
191 # ha ... access from HA resource manager agent (rgmanager)
202 foreach my $p (keys %params) {
203 if ($p eq 'atfork') {
204 $self->{$p} = $params{$p};
206 die "unknown option '$p'";
212 my ($sysname, $nodename) = POSIX
::uname
();
214 $nodename =~ s/\..*$//; # strip domain part, if any
216 $self->{nodename
} = $nodename;
224 die "not initialized" if !$pve_env;
230 my ($self, $enable_upload) = @_;
232 if ($self->{request_rec
}) {
234 if ($enable_upload) {
235 $cgi = CGI-
>new($self->{request_rec
});
237 # disable upload using empty upload_hook
238 $cgi = CGI-
>new($self->{request_rec
}, sub {}, undef, 0);
241 my $params = $cgi->Vars();
243 } elsif ($self->{params
}) {
244 return $self->{params
};
246 die "no parameters registered";
250 sub get_upload_info
{
251 my ($self, $param) = @_;
253 my $cgi = $self->{cgi
};
254 die "CGI not initialized" if !$cgi;
256 my $pd = $cgi->param($param);
257 die "unable to get cgi parameter info\n" if !$pd;
258 my $info = $cgi->uploadInfo($pd);
259 die "unable to get cgi upload info\n" if !$info;
261 my $res = { %$info };
263 my $tmpfilename = $cgi->tmpFileName($pd);
264 die "unable to get cgi upload file name\n" if !$tmpfilename;
265 $res->{tmpfilename
} = $tmpfilename;
267 #my $hndl = $cgi->upload($param);
268 #die "unable to get cgi upload handle\n" if !$hndl;
269 #$res->{handle} = $hndl->handle;
274 # init_request - must be called before each RPC request
276 my ($self, %params) = @_;
278 PVE
::Cluster
::cfs_update
();
280 $self->{result_attributes
} = {};
282 my $userconfig; # we use this for regression tests
283 foreach my $p (keys %params) {
284 if ($p eq 'userconfig') {
285 $userconfig = $params{$p};
286 } elsif ($p eq 'request_rec') {
287 # pass Apache2::RequestRec
288 $self->{request_rec
} = $params{$p};
289 } elsif ($p eq 'params') {
290 $self->{params
} = $params{$p};
292 die "unknown parameter '$p'";
297 $self->{aclcache
} = {};
299 my $ucdata = PVE
::Tools
::file_get_contents
($userconfig);
300 my $cfg = PVE
::AccessControl
::parse_user_config
($userconfig, $ucdata);
301 $self->{user_cfg
} = $cfg;
303 my $ucvers = PVE
::Cluster
::cfs_file_version
('user.cfg');
304 if (!$self->{aclcache
} || !defined($self->{aclversion
}) ||
305 !defined($ucvers) || ($ucvers ne $self->{aclversion
})) {
306 $self->{aclversion
} = $ucvers;
307 my $cfg = PVE
::Cluster
::cfs_read_file
('user.cfg');
308 $self->{user_cfg
} = $cfg;
313 $self->{user_cfg
} = {};
314 die "Unable to load access control list: $err";
319 my ($self, $ip) = @_;
321 $self->{client_ip
} = $ip;
327 return $self->{client_ip
};
330 sub set_result_attrib
{
331 my ($self, $key, $value) = @_;
333 $self->{result_attributes
}->{$key} = $value;
336 sub get_result_attrib
{
337 my ($self, $key) = @_;
339 return $self->{result_attributes
}->{$key};
343 my ($self, $lang) = @_;
345 # fixme: initialize I18N
347 $self->{language
} = $lang;
353 return $self->{language
};
357 my ($self, $user) = @_;
361 $self->{user
} = $user;
367 die "user name not set\n" if !$self->{user
};
369 return $self->{user
};
372 # read/update list of active workers
373 # we move all finished tasks to the archive index,
374 # but keep aktive and most recent task in the active file.
375 # $nocheck ... consider $new_upid still running (avoid that
376 # we try to read the reult to early.
378 my ($new_upid, $nocheck) = @_;
380 my $lkfn = "/var/log/pve/tasks/.active.lock";
386 my $tasklist = PVE
::INotify
::read_file
('active');
390 my $thash = {}; # only list task once
392 my $check_task = sub {
393 my ($task, $running) = @_;
395 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
401 delete $task->{pstart
};
404 foreach my $task (@$tasklist) {
405 my $upid = $task->{upid
};
406 next if $thash->{$upid};
407 $thash->{$upid} = $task;
411 if ($new_upid && !(my $task = $thash->{$new_upid})) {
412 $task = PVE
::Tools
::upid_decode
($new_upid);
413 $task->{upid
} = $new_upid;
414 $thash->{$new_upid} = $task;
415 &$check_task($task, $nocheck);
419 @ta = sort { $b->{starttime
} cmp $a->{starttime
} } @ta;
421 my $save = defined($new_upid);
423 foreach my $task (@ta) {
424 next if $task->{endtime
};
425 $task->{endtime
} = time();
426 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
432 foreach my $task (@ta) {
433 if (!$task->{saved
}) {
434 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime
});
443 my $filename = "/var/log/pve/tasks/index";
445 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
446 die "unable to open file '$filename' - $!\n";
447 PVE
::Tools
::safe_print
($filename, $fh, $archive);
450 die "unable to close file '$filename' - $!\n";
455 foreach my $task (@arlist) { # mark as not saved
459 my $maxsize = 50000; # about 1000 entries
460 if ($size > $maxsize) {
461 rename($filename, "$filename.1");
465 # we try to reduce the amount of data
466 # list all running tasks and task and a few others
467 # try to limit to 25 tasks
469 my $max = 25 - scalar(@$tlist);
470 foreach my $task (@ta) {
476 PVE
::INotify
::write_file
('active', $tlist) if $save;
481 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
487 my $kill_process_group = sub {
488 my ($pid, $pstart) = @_;
490 # send kill to process group (negative pid)
493 # always send signal to all pgrp members
494 kill(15, $kpid); # send TERM signal
496 # give max 5 seconds to shut down
497 for (my $i = 0; $i < 5; $i++) {
498 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
507 my ($upid, $killit) = @_;
509 my $task = PVE
::Tools
::upid_decode
($upid);
511 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
513 return 0 if !$running;
516 &$kill_process_group($task->{pid
});
523 # start long running workers
524 # STDIN is redirected to /dev/null
525 # STDOUT,STDERR are redirected to the filename returned by upid_decode
526 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
528 my ($self, $dtype, $id, $user, $function) = @_;
530 $dtype = 'unknown' if !defined ($dtype);
531 $id = '' if !defined ($id);
533 $user = 'root@pve' if !defined ($user);
535 my $sync = $self->{type
} eq 'cli' ?
1 : 0;
540 local $SIG{TERM
} = 'IGNORE';
542 my $starttime = time ();
544 my @psync = POSIX
::pipe();
545 my @csync = POSIX
::pipe();
547 my $node = $self->{nodename
};
550 die "unable to fork worker - $!" if !defined($cpid);
552 my $workerpuid = $cpid ?
$cpid : $$;
554 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
555 die "unable to read process start time";
557 my $upid = PVE
::Tools
::upid_encode
({
558 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
559 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
563 if (!$cpid) { # child
567 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
569 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
571 # set sess/process group - we want to be able to kill the
572 # whole process group
575 POSIX
::close ($psync[0]);
576 POSIX
::close ($csync[1]);
578 $outfh = $sync ?
$psync[1] : undef;
581 PVE
::INotify
::inotify_close
();
583 if (my $atfork = $self->{atfork
}) {
587 # same algorythm as used inside SA
589 my $fd = fileno (STDIN
);
593 POSIX
::close(0) if $fd != 0;
595 die "unable to redirect STDIN - $!"
596 if !open(STDIN
, "</dev/null");
598 $outfh = PVE
::Tools
::upid_open
($upid);
603 $fd = fileno(STDOUT
);
605 POSIX
::close (1) if $fd != 1;
607 die "unable to redirect STDOUT - $!"
608 if !open(STDOUT
, ">&", $outfh);
610 STDOUT-
>autoflush (1);
612 # redirect STDERR to STDOUT
613 $fd = fileno (STDERR
);
615 POSIX
::close(2) if $fd != 2;
617 die "unable to redirect STDERR - $!"
618 if !open(STDERR
, ">&1");
620 STDERR-
>autoflush(1);
623 my $msg = "ERROR: $err";
624 POSIX
::write($psync[1], $msg, length ($msg));
625 POSIX
::close($psync[1]);
630 # sync with parent (signal that we are ready)
634 POSIX
::write($psync[1], $upid, length ($upid));
635 POSIX
::close($psync[1]);
639 # sync with parent (wait until parent is ready)
640 POSIX
::read($csync[0], $readbuf, 4096);
641 die "parent setup error\n" if $readbuf ne 'OK';
643 if ($self->{type
} eq 'ha') {
644 print "task started by HA resource agent\n";
646 eval { &$function($upid); };
652 print STDERR
"TASK ERROR: $err\n";
655 print STDERR
"TASK OK\n";
663 POSIX
::close ($psync[1]);
664 POSIX
::close ($csync[0]);
667 # sync with child (wait until child starts)
668 POSIX
::read($psync[0], $readbuf, 4096);
671 POSIX
::close($psync[0]);
672 &$register_worker($cpid, $user, $upid);
678 die "got no worker upid - start worker failed\n" if !$readbuf;
680 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
681 die "starting worker failed: $1\n";
684 if ($readbuf ne $upid) {
685 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
689 $outfh = PVE
::Tools
::upid_open
($upid);
696 POSIX
::write($csync[1], $msg, length ($msg));
697 POSIX
::close($csync[1]);
700 POSIX
::close($csync[1]);
701 kill(-9, $cpid); # make sure it gets killed
705 PVE
::Cluster
::log_msg
('info', $user, "starting task $upid");
707 my $tlist = active_workers
($upid, $sync);
708 PVE
::Cluster
::broadcast_tasklist
($tlist);
717 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
718 # always send signal to all pgrp members
720 if ($int_count < 3) {
721 kill(15, $kpid); # send TERM signal
723 kill(9, $kpid); # send KILL signal
727 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
729 my $select = new IO
::Select
;
730 my $fh = IO
::Handle-
>new_from_fd($psync[0], 'r');
733 while ($select->count) {
734 my @handles = $select->can_read(1);
735 if (scalar(@handles)) {
736 my $count = sysread ($handles[0], $readbuf, 4096);
737 if (!defined ($count)) {
739 die "sync pipe read error: $err\n";
741 last if $count == 0; # eof
744 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
747 if ($data =~ m/^TASK OK$/) {
749 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
760 # some commands daemonize without closing stdout
761 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
767 POSIX
::close($psync[0]);
769 if ($outbuf) { # just to be sure
772 print $outfh $outbuf;
778 print STDERR
"$err\n";
780 print $outfh "TASK ERROR: $err\n";
784 &$kill_process_group($cpid, $pstart); # make sure it gets killed
790 &$log_task_result($upid, $user, $res);
793 return wantarray ?
($upid, $res) : $upid;