]>
git.proxmox.com Git - pve-access-control.git/blob - PVE/RPCEnvironment.pm
16b8ba8ad59079603f3cc147b40e2d4438198f87
1 package PVE
::RPCEnvironment
;
5 use POSIX
qw(:sys_wait_h EINTR);
10 use PVE
::Exception
qw(raise raise_perm_exc);
16 use PVE
::AccessControl
;
19 # we use this singleton class to pass RPC related environment values
23 # save $SIG{CHLD} handler implementation.
24 # simply set $SIG{CHLD} = $worker_reaper;
25 # and register forked processes with &$register_worker(pid)
26 # Note: using $SIG{CHLD} = 'IGNORE' or $SIG{CHLD} = sub { wait (); } or ...
27 # has serious side effects, because perls built in system() and open()
28 # functions can't get the correct exit status of a child. So we cant use
29 # that (also see perlipc)
33 my $log_task_result = sub {
34 my ($upid, $user, $status) = @_;
36 my $msg = 'successful';
39 my $ec = $status >> 8;
40 my $ic = $status & 255;
41 $msg = $ec ?
"failed ($ec)" : "interrupted ($ic)";
44 my $tlist = active_workers
($upid);
45 PVE
::Cluster
::broadcast_tasklist
($tlist);
47 foreach my $t (@$tlist) {
48 if ($t->{upid
} eq $upid) {
53 if ($task && $task->{status
}) {
54 $msg = $task->{status
};
56 PVE
::Cluster
::log_msg
($pri, $user, "end task $upid $msg");
59 my $worker_reaper = sub {
61 foreach my $pid (keys %$WORKER_PIDS) {
62 my $waitpid = waitpid ($pid, WNOHANG
);
63 if (defined($waitpid) && ($waitpid == $pid)) {
64 my $info = $WORKER_PIDS->{$pid};
65 if ($info && $info->{upid
} && $info->{user
}) {
66 &$log_task_result($info->{upid
}, $info->{user
}, $?);
68 delete ($WORKER_PIDS->{$pid});
73 my $register_worker = sub {
74 my ($pid, $user, $upid) = @_;
78 # do not register if already finished
79 my $waitpid = waitpid ($pid, WNOHANG
);
80 if (defined($waitpid) && ($waitpid == $pid)) {
81 delete ($WORKER_PIDS->{$pid});
85 $WORKER_PIDS->{$pid} = {
93 my $compile_acl = sub {
94 my ($self, $user) = @_;
97 my $cfg = $self->{user_cfg
};
99 return undef if !$cfg->{roles
};
101 if ($user eq 'root@pam') { # root can do anything
102 return {'/' => $cfg->{roles
}->{'Administrator'}};
105 foreach my $path (sort keys %{$cfg->{acl
}}) {
106 my @ra = PVE
::AccessControl
::roles
($cfg, $user, $path);
109 foreach my $role (@ra) {
110 if (my $privset = $cfg->{roles
}->{$role}) {
111 foreach my $p (keys %$privset) {
117 $res->{$path} = $privs;
124 my ($self, $user, $path) = @_;
126 $user = PVE
::AccessControl
::verify_username
($user, 1);
129 my $cache = $self->{aclcache
};
131 my $acl = $cache->{$user};
134 if (!($acl = &$compile_acl($self, $user))) {
137 $cache->{$user} = $acl;
142 if (!($perm = $acl->{$path})) {
144 foreach my $p (sort keys %$acl) {
145 my $final = ($path eq $p);
147 next if !(($p eq '/') || $final || ($path =~ m
|^$p/|));
151 $acl->{$path} = $perm;
158 my ($self, $user, $path, $privs, $noerr) = @_;
160 my $perm = $self->permissions($user, $path);
162 foreach my $priv (@$privs) {
163 PVE
::AccessControl
::verify_privname
($priv);
164 if (!$perm->{$priv}) {
165 return undef if $noerr;
166 raise_perm_exc
("$path, $priv");
174 my ($self, $user, $path, $privs, $noerr) = @_;
176 my $perm = $self->permissions($user, $path);
179 foreach my $priv (@$privs) {
180 PVE
::AccessControl
::verify_privname
($priv);
181 if ($perm->{$priv}) {
189 return undef if $noerr;
191 raise_perm_exc
("$path, " . join("|", @$privs));
194 sub check_user_enabled
{
195 my ($self, $user, $noerr) = @_;
197 my $cfg = $self->{user_cfg
};
198 return PVE
::AccessControl
::check_user_enabled
($cfg, $user, $noerr);
201 sub check_user_exist
{
202 my ($self, $user, $noerr) = @_;
204 my $cfg = $self->{user_cfg
};
205 return PVE
::AccessControl
::check_user_exist
($cfg, $user, $noerr);
208 sub is_group_member
{
209 my ($self, $group, $user) = @_;
211 my $cfg = $self->{user_cfg
};
213 return 0 if !$cfg->{groups
}->{$group};
215 return defined($cfg->{groups
}->{$group}->{users
}->{$user});
219 my ($self, $user, $getPath, $privs, $any) = @_;
221 my $cfg = $self->{user_cfg
};
224 foreach my $group (keys %{$cfg->{groups
}}) {
226 if ($self->check_any($user, &$getPath($group), $privs, 1)) {
227 $groups->{$group} = $cfg->{groups
}->{$group};
230 if ($self->check($user, &$getPath($group), $privs, 1)) {
231 $groups->{$group} = $cfg->{groups
}->{$group};
239 sub group_member_join
{
240 my ($self, $grouplist) = @_;
244 my $cfg = $self->{user_cfg
};
245 foreach my $group (@$grouplist) {
246 my $data = $cfg->{groups
}->{$group};
248 foreach my $user (keys %{$data->{users
}}) {
256 # initialize environment - must be called once at program startup
258 my ($class, $type, %params) = @_;
260 $class = ref($class) || $class;
262 die "already initialized" if $pve_env;
264 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
266 $SIG{CHLD
} = $worker_reaper;
269 # cli ... command started fron command line
270 # pub ... access from public server (apache)
271 # priv ... access from private server (pvedaemon)
272 # ha ... access from HA resource manager agent (rgmanager)
283 foreach my $p (keys %params) {
284 if ($p eq 'atfork') {
285 $self->{$p} = $params{$p};
287 die "unknown option '$p'";
293 my ($sysname, $nodename) = POSIX
::uname
();
295 $nodename =~ s/\..*$//; # strip domain part, if any
297 $self->{nodename
} = $nodename;
305 die "not initialized" if !$pve_env;
311 my ($self, $enable_upload) = @_;
313 if ($self->{request_rec
}) {
315 if ($enable_upload) {
316 $cgi = CGI-
>new($self->{request_rec
});
318 # disable upload using empty upload_hook
319 $cgi = CGI-
>new($self->{request_rec
}, sub {}, undef, 0);
322 my $params = $cgi->Vars();
323 return PVE
::Tools
::decode_utf8_parameters
($params);
324 } elsif ($self->{params
}) {
325 return $self->{params
};
327 die "no parameters registered";
331 sub get_upload_info
{
332 my ($self, $param) = @_;
334 my $cgi = $self->{cgi
};
335 die "CGI not initialized" if !$cgi;
337 my $pd = $cgi->param($param);
338 die "unable to get cgi parameter info\n" if !$pd;
339 my $info = $cgi->uploadInfo($pd);
340 die "unable to get cgi upload info\n" if !$info;
342 my $res = { %$info };
344 my $tmpfilename = $cgi->tmpFileName($pd);
345 die "unable to get cgi upload file name\n" if !$tmpfilename;
346 $res->{tmpfilename
} = $tmpfilename;
348 #my $hndl = $cgi->upload($param);
349 #die "unable to get cgi upload handle\n" if !$hndl;
350 #$res->{handle} = $hndl->handle;
355 # init_request - must be called before each RPC request
357 my ($self, %params) = @_;
359 PVE
::Cluster
::cfs_update
();
361 $self->{result_attributes
} = {};
363 my $userconfig; # we use this for regression tests
364 foreach my $p (keys %params) {
365 if ($p eq 'userconfig') {
366 $userconfig = $params{$p};
367 } elsif ($p eq 'request_rec') {
368 # pass Apache2::RequestRec
369 $self->{request_rec
} = $params{$p};
370 } elsif ($p eq 'params') {
371 $self->{params
} = $params{$p};
373 die "unknown parameter '$p'";
378 $self->{aclcache
} = {};
380 my $ucdata = PVE
::Tools
::file_get_contents
($userconfig);
381 my $cfg = PVE
::AccessControl
::parse_user_config
($userconfig, $ucdata);
382 $self->{user_cfg
} = $cfg;
384 my $ucvers = PVE
::Cluster
::cfs_file_version
('user.cfg');
385 if (!$self->{aclcache
} || !defined($self->{aclversion
}) ||
386 !defined($ucvers) || ($ucvers ne $self->{aclversion
})) {
387 $self->{aclversion
} = $ucvers;
388 my $cfg = PVE
::Cluster
::cfs_read_file
('user.cfg');
389 $self->{user_cfg
} = $cfg;
394 $self->{user_cfg
} = {};
395 die "Unable to load access control list: $err";
400 my ($self, $ip) = @_;
402 $self->{client_ip
} = $ip;
408 return $self->{client_ip
};
411 sub set_result_attrib
{
412 my ($self, $key, $value) = @_;
414 $self->{result_attributes
}->{$key} = $value;
417 sub get_result_attrib
{
418 my ($self, $key) = @_;
420 return $self->{result_attributes
}->{$key};
424 my ($self, $lang) = @_;
426 # fixme: initialize I18N
428 $self->{language
} = $lang;
434 return $self->{language
};
438 my ($self, $user) = @_;
442 $self->{user
} = $user;
448 die "user name not set\n" if !$self->{user
};
450 return $self->{user
};
453 # read/update list of active workers
454 # we move all finished tasks to the archive index,
455 # but keep aktive and most recent task in the active file.
456 # $nocheck ... consider $new_upid still running (avoid that
457 # we try to read the reult to early.
459 my ($new_upid, $nocheck) = @_;
461 my $lkfn = "/var/log/pve/tasks/.active.lock";
467 my $tasklist = PVE
::INotify
::read_file
('active');
471 my $thash = {}; # only list task once
473 my $check_task = sub {
474 my ($task, $running) = @_;
476 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
482 delete $task->{pstart
};
485 foreach my $task (@$tasklist) {
486 my $upid = $task->{upid
};
487 next if $thash->{$upid};
488 $thash->{$upid} = $task;
492 if ($new_upid && !(my $task = $thash->{$new_upid})) {
493 $task = PVE
::Tools
::upid_decode
($new_upid);
494 $task->{upid
} = $new_upid;
495 $thash->{$new_upid} = $task;
496 &$check_task($task, $nocheck);
500 @ta = sort { $b->{starttime
} cmp $a->{starttime
} } @ta;
502 my $save = defined($new_upid);
504 foreach my $task (@ta) {
505 next if $task->{endtime
};
506 $task->{endtime
} = time();
507 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
513 foreach my $task (@ta) {
514 if (!$task->{saved
}) {
515 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime
});
524 my $filename = "/var/log/pve/tasks/index";
526 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
527 die "unable to open file '$filename' - $!\n";
528 PVE
::Tools
::safe_print
($filename, $fh, $archive);
531 die "unable to close file '$filename' - $!\n";
536 foreach my $task (@arlist) { # mark as not saved
540 my $maxsize = 50000; # about 1000 entries
541 if ($size > $maxsize) {
542 rename($filename, "$filename.1");
546 # we try to reduce the amount of data
547 # list all running tasks and task and a few others
548 # try to limit to 25 tasks
550 my $max = 25 - scalar(@$tlist);
551 foreach my $task (@ta) {
557 PVE
::INotify
::write_file
('active', $tlist) if $save;
562 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
568 my $kill_process_group = sub {
569 my ($pid, $pstart) = @_;
571 # send kill to process group (negative pid)
574 # always send signal to all pgrp members
575 kill(15, $kpid); # send TERM signal
577 # give max 5 seconds to shut down
578 for (my $i = 0; $i < 5; $i++) {
579 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
588 my ($upid, $killit) = @_;
590 my $task = PVE
::Tools
::upid_decode
($upid);
592 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
594 return 0 if !$running;
597 &$kill_process_group($task->{pid
});
604 # start long running workers
605 # STDIN is redirected to /dev/null
606 # STDOUT,STDERR are redirected to the filename returned by upid_decode
607 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
609 my ($self, $dtype, $id, $user, $function) = @_;
611 $dtype = 'unknown' if !defined ($dtype);
612 $id = '' if !defined ($id);
614 $user = 'root@pve' if !defined ($user);
616 my $sync = $self->{type
} eq 'cli' ?
1 : 0;
621 local $SIG{TERM
} = 'IGNORE';
623 my $starttime = time ();
625 my @psync = POSIX
::pipe();
626 my @csync = POSIX
::pipe();
628 my $node = $self->{nodename
};
631 die "unable to fork worker - $!" if !defined($cpid);
633 my $workerpuid = $cpid ?
$cpid : $$;
635 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
636 die "unable to read process start time";
638 my $upid = PVE
::Tools
::upid_encode
({
639 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
640 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
644 if (!$cpid) { # child
648 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
650 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
652 # set sess/process group - we want to be able to kill the
653 # whole process group
656 POSIX
::close ($psync[0]);
657 POSIX
::close ($csync[1]);
659 $outfh = $sync ?
$psync[1] : undef;
662 PVE
::INotify
::inotify_close
();
664 if (my $atfork = $self->{atfork
}) {
668 # same algorythm as used inside SA
670 my $fd = fileno (STDIN
);
674 POSIX
::close(0) if $fd != 0;
676 die "unable to redirect STDIN - $!"
677 if !open(STDIN
, "</dev/null");
679 $outfh = PVE
::Tools
::upid_open
($upid);
684 $fd = fileno(STDOUT
);
686 POSIX
::close (1) if $fd != 1;
688 die "unable to redirect STDOUT - $!"
689 if !open(STDOUT
, ">&", $outfh);
691 STDOUT-
>autoflush (1);
693 # redirect STDERR to STDOUT
694 $fd = fileno (STDERR
);
696 POSIX
::close(2) if $fd != 2;
698 die "unable to redirect STDERR - $!"
699 if !open(STDERR
, ">&1");
701 STDERR-
>autoflush(1);
704 my $msg = "ERROR: $err";
705 POSIX
::write($psync[1], $msg, length ($msg));
706 POSIX
::close($psync[1]);
711 # sync with parent (signal that we are ready)
715 POSIX
::write($psync[1], $upid, length ($upid));
716 POSIX
::close($psync[1]);
720 # sync with parent (wait until parent is ready)
721 POSIX
::read($csync[0], $readbuf, 4096);
722 die "parent setup error\n" if $readbuf ne 'OK';
724 if ($self->{type
} eq 'ha') {
725 print "task started by HA resource agent\n";
727 eval { &$function($upid); };
733 print STDERR
"TASK ERROR: $err\n";
736 print STDERR
"TASK OK\n";
744 POSIX
::close ($psync[1]);
745 POSIX
::close ($csync[0]);
748 # sync with child (wait until child starts)
749 POSIX
::read($psync[0], $readbuf, 4096);
752 POSIX
::close($psync[0]);
753 &$register_worker($cpid, $user, $upid);
759 die "got no worker upid - start worker failed\n" if !$readbuf;
761 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
762 die "starting worker failed: $1\n";
765 if ($readbuf ne $upid) {
766 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
770 $outfh = PVE
::Tools
::upid_open
($upid);
777 POSIX
::write($csync[1], $msg, length ($msg));
778 POSIX
::close($csync[1]);
781 POSIX
::close($csync[1]);
782 kill(-9, $cpid); # make sure it gets killed
786 PVE
::Cluster
::log_msg
('info', $user, "starting task $upid");
788 my $tlist = active_workers
($upid, $sync);
789 PVE
::Cluster
::broadcast_tasklist
($tlist);
798 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
799 # always send signal to all pgrp members
801 if ($int_count < 3) {
802 kill(15, $kpid); # send TERM signal
804 kill(9, $kpid); # send KILL signal
808 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
810 my $select = new IO
::Select
;
811 my $fh = IO
::Handle-
>new_from_fd($psync[0], 'r');
814 while ($select->count) {
815 my @handles = $select->can_read(1);
816 if (scalar(@handles)) {
817 my $count = sysread ($handles[0], $readbuf, 4096);
818 if (!defined ($count)) {
820 die "sync pipe read error: $err\n";
822 last if $count == 0; # eof
825 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
828 if ($data =~ m/^TASK OK$/) {
830 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
841 # some commands daemonize without closing stdout
842 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
848 POSIX
::close($psync[0]);
850 if ($outbuf) { # just to be sure
853 print $outfh $outbuf;
859 print STDERR
"$err\n";
861 print $outfh "TASK ERROR: $err\n";
865 &$kill_process_group($cpid, $pstart); # make sure it gets killed
871 &$log_task_result($upid, $user, $res);
874 return wantarray ?
($upid, $res) : $upid;