]>
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
;
17 # we use this singleton class to pass RPC related environment values
21 # save $SIG{CHLD} handler implementation.
22 # simply set $SIG{CHLD} = $worker_reaper;
23 # and register forked processes with &$register_worker(pid)
24 # Note: using $SIG{CHLD} = 'IGNORE' or $SIG{CHLD} = sub { wait (); } or ...
25 # has serious side effects, because perls built in system() and open()
26 # functions can't get the correct exit status of a child. So we cant use
27 # that (also see perlipc)
31 my $log_task_result = sub {
32 my ($upid, $user, $status) = @_;
34 my $msg = 'successful';
37 my $ec = $status >> 8;
38 my $ic = $status & 255;
39 $msg = $ec ?
"failed ($ec)" : "interrupted ($ic)";
42 my $tlist = active_workers
($upid);
43 PVE
::Cluster
::broadcast_tasklist
($tlist);
45 foreach my $t (@$tlist) {
46 if ($t->{upid
} eq $upid) {
51 if ($task && $task->{status
}) {
52 $msg = $task->{status
};
54 PVE
::Cluster
::log_msg
($pri, $user, "end task $upid $msg");
57 my $worker_reaper = sub {
59 foreach my $pid (keys %$WORKER_PIDS) {
60 my $waitpid = waitpid ($pid, WNOHANG
);
61 if (defined($waitpid) && ($waitpid == $pid)) {
62 my $info = $WORKER_PIDS->{$pid};
63 if ($info && $info->{upid
} && $info->{user
}) {
64 &$log_task_result($info->{upid
}, $info->{user
}, $?);
66 delete ($WORKER_PIDS->{$pid});
71 my $register_worker = sub {
72 my ($pid, $user, $upid) = @_;
76 # do not register if already finished
77 my $waitpid = waitpid ($pid, WNOHANG
);
78 if (defined($waitpid) && ($waitpid == $pid)) {
79 delete ($WORKER_PIDS->{$pid});
83 $WORKER_PIDS->{$pid} = {
91 my $compile_acl = sub {
92 my ($self, $user) = @_;
95 my $cfg = $self->{user_cfg
};
97 return undef if !$cfg->{roles
};
99 if ($user eq 'root@pam') { # root can do anything
100 return {'/' => $cfg->{roles
}->{'Administrator'}};
103 foreach my $path (sort keys %{$cfg->{acl
}}) {
104 my @ra = PVE
::AccessControl
::roles
($cfg, $user, $path);
107 foreach my $role (@ra) {
108 if (my $privset = $cfg->{roles
}->{$role}) {
109 foreach my $p (keys %$privset) {
115 $res->{$path} = $privs;
122 my ($self, $user, $path) = @_;
124 $user = PVE
::AccessControl
::verify_username
($user, 1);
127 my $cache = $self->{aclcache
};
129 my $acl = $cache->{$user};
132 if (!($acl = &$compile_acl($self, $user))) {
135 $cache->{$user} = $acl;
140 if (!($perm = $acl->{$path})) {
142 foreach my $p (sort keys %$acl) {
143 my $final = ($path eq $p);
145 next if !(($p eq '/') || $final || ($path =~ m
|^$p/|));
149 $acl->{$path} = $perm;
156 my ($self, $user, $path, $privs) = @_;
158 my $perm = $self->permissions($user, $path);
160 foreach my $priv (@$privs) {
161 return undef if !$perm->{$priv};
168 my ($self, $user) = @_;
170 my $cfg = $self->{user_cfg
};
171 return PVE
::AccessControl
::user_enabled
($cfg, $user);
174 # initialize environment - must be called once at program startup
176 my ($class, $type, %params) = @_;
178 $class = ref($class) || $class;
180 die "already initialized" if $pve_env;
182 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv)$/;
184 $SIG{CHLD
} = $worker_reaper;
187 # cli ... command started fron command line
188 # pub ... access from public server (apache)
189 # priv ... access from private server (pvedaemon)
200 foreach my $p (keys %params) {
201 if ($p eq 'atfork') {
202 $self->{$p} = $params{$p};
204 die "unknown option '$p'";
210 my ($sysname, $nodename) = POSIX
::uname
();
212 $nodename =~ s/\..*$//; # strip domain part, if any
214 $self->{nodename
} = $nodename;
222 die "not initialized" if !$pve_env;
227 # init_request - must be called before each RPC request
229 my ($self, %params) = @_;
231 PVE
::Cluster
::cfs_update
();
233 my $userconfig; # we use this for regression tests
234 foreach my $p (keys %params) {
235 if ($p eq 'userconfig') {
236 $userconfig = $params{$p};
238 die "unknown parameter '$p'";
243 $self->{aclcache
} = {};
245 my $ucdata = PVE
::Tools
::file_get_contents
($userconfig);
246 my $cfg = PVE
::AccessControl
::parse_user_config
($userconfig, $ucdata);
247 $self->{user_cfg
} = $cfg;
249 my $ucvers = PVE
::Cluster
::cfs_file_version
('user.cfg');
250 if (!$self->{aclcache
} || !defined($self->{aclversion
}) ||
251 !defined($ucvers) || ($ucvers ne $self->{aclversion
})) {
252 $self->{aclversion
} = $ucvers;
253 my $cfg = PVE
::Cluster
::cfs_read_file
('user.cfg');
254 $self->{user_cfg
} = $cfg;
259 $self->{user_cfg
} = {};
260 die "Unable to load access control list: $err";
265 my ($self, $ip) = @_;
267 $self->{client_ip
} = $ip;
273 return $self->{client_ip
};
276 sub set_result_count
{
277 my ($self, $count) = @_;
279 $self->{result_count
} = $count;
282 sub get_result_count
{
285 return $self->{result_count
};
289 my ($self, $lang) = @_;
291 # fixme: initialize I18N
293 $self->{language
} = $lang;
299 return $self->{language
};
303 my ($self, $user) = @_;
307 $self->{user
} = $user;
313 die "user name not set\n" if !$self->{user
};
315 return $self->{user
};
318 # read/update list of active workers
319 # we move all finished tasks to the archive index,
320 # but keep aktive and most recent task in the active file.
321 # $nocheck ... consider $new_upid still running (avoid that
322 # we try to read the reult to early.
324 my ($new_upid, $nocheck) = @_;
326 my $lkfn = "/var/log/pve/tasks/.active.lock";
332 my $tasklist = PVE
::INotify
::read_file
('active');
336 my $thash = {}; # only list task once
338 my $check_task = sub {
339 my ($task, $running) = @_;
341 if ($running || PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
})) {
347 delete $task->{pstart
};
350 foreach my $task (@$tasklist) {
351 my $upid = $task->{upid
};
352 next if $thash->{$upid};
353 $thash->{$upid} = $task;
357 if ($new_upid && !(my $task = $thash->{$new_upid})) {
358 $task = PVE
::Tools
::upid_decode
($new_upid);
359 $task->{upid
} = $new_upid;
360 $thash->{$new_upid} = $task;
361 &$check_task($task, $nocheck);
365 @ta = sort { $b->{starttime
} cmp $a->{starttime
} } @ta;
367 my $save = defined($new_upid);
369 foreach my $task (@ta) {
370 next if $task->{endtime
};
371 $task->{endtime
} = time();
372 $task->{status
} = PVE
::Tools
::upid_read_status
($task->{upid
});
378 foreach my $task (@ta) {
379 if (!$task->{saved
}) {
380 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime
});
389 my $filename = "/var/log/pve/tasks/index";
391 my $fh = IO
::File-
>new($filename, '>>', 0644) ||
392 die "unable to open file '$filename' - $!\n";
393 PVE
::Tools
::safe_print
($filename, $fh, $archive);
396 die "unable to close file '$filename' - $!\n";
401 foreach my $task (@arlist) { # mark as not saved
405 my $maxsize = 50000; # about 1000 entries
406 if ($size > $maxsize) {
407 rename($filename, "$filename.1");
411 # we try to reduce the amount of data
412 # list all running tasks and task and a few others
413 # try to limit to 25 tasks
415 my $max = 25 - scalar(@$tlist);
416 foreach my $task (@ta) {
422 PVE
::INotify
::write_file
('active', $tlist) if $save;
427 my $res = PVE
::Tools
::lock_file
($lkfn, $timeout, $code);
433 my $kill_process_group = sub {
434 my ($pid, $pstart) = @_;
436 # send kill to process group (negative pid)
439 # always send signal to all pgrp members
440 kill(15, $kpid); # send TERM signal
442 # give max 5 seconds to shut down
443 for (my $i = 0; $i < 5; $i++) {
444 return if !PVE
::ProcFSTools
::check_process_running
($pid, $pstart);
453 my ($upid, $killit) = @_;
455 my $task = PVE
::Tools
::upid_decode
($upid);
457 my $running = PVE
::ProcFSTools
::check_process_running
($task->{pid
}, $task->{pstart
});
459 return 0 if !$running;
462 &$kill_process_group($task->{pid
});
469 # start long running workers
470 # STDIN is redirected to /dev/null
471 # STDOUT,STDERR are redirected to the filename returned by upid_decode
472 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
474 my ($self, $dtype, $id, $user, $function) = @_;
476 $dtype = 'unknown' if !defined ($dtype);
477 $id = '' if !defined ($id);
479 $user = 'root@pve' if !defined ($user);
481 my $sync = $self->{type
} eq 'cli' ?
1 : 0;
486 local $SIG{TERM
} = 'IGNORE';
488 my $starttime = time ();
490 my @psync = POSIX
::pipe();
491 my @csync = POSIX
::pipe();
493 my $node = $self->{nodename
};
496 die "unable to fork worker - $!" if !defined($cpid);
498 my $workerpuid = $cpid ?
$cpid : $$;
500 my $pstart = PVE
::ProcFSTools
::read_proc_starttime
($workerpuid) ||
501 die "unable to read process start time";
503 my $upid = PVE
::Tools
::upid_encode
({
504 node
=> $node, pid
=> $workerpuid, pstart
=> $pstart,
505 starttime
=> $starttime, type
=> $dtype, id
=> $id, user
=> $user });
509 if (!$cpid) { # child
513 $SIG{INT
} = $SIG{QUIT
} = $SIG{TERM
} = sub { die "received interrupt\n"; };
515 $SIG{CHLD
} = $SIG{PIPE
} = 'DEFAULT';
517 # set sess/process group - we want to be able to kill the
518 # whole process group
521 POSIX
::close ($psync[0]);
522 POSIX
::close ($csync[1]);
524 $outfh = $sync ?
$psync[1] : undef;
527 PVE
::INotify
::inotify_close
();
529 if (my $atfork = $self->{atfork
}) {
533 # same algorythm as used inside SA
535 my $fd = fileno (STDIN
);
539 POSIX
::close(0) if $fd != 0;
541 die "unable to redirect STDIN - $!"
542 if !open(STDIN
, "</dev/null");
544 $outfh = PVE
::Tools
::upid_open
($upid);
549 $fd = fileno(STDOUT
);
551 POSIX
::close (1) if $fd != 1;
553 die "unable to redirect STDOUT - $!"
554 if !open(STDOUT
, ">&", $outfh);
556 STDOUT-
>autoflush (1);
558 # redirect STDERR to STDOUT
559 $fd = fileno (STDERR
);
561 POSIX
::close(2) if $fd != 2;
563 die "unable to redirect STDERR - $!"
564 if !open(STDERR
, ">&1");
566 STDERR-
>autoflush(1);
569 my $msg = "ERROR: $err";
570 POSIX
::write($psync[1], $msg, length ($msg));
571 POSIX
::close($psync[1]);
576 # sync with parent (signal that we are ready)
580 POSIX
::write($psync[1], $upid, length ($upid));
581 POSIX
::close($psync[1]);
585 # sync with parent (wait until parent is ready)
586 POSIX
::read($csync[0], $readbuf, 4096);
587 die "parent setup error\n" if $readbuf ne 'OK';
589 eval { &$function($upid); };
595 print STDERR
"TASK ERROR: $err\n";
598 print STDERR
"TASK OK\n";
606 POSIX
::close ($psync[1]);
607 POSIX
::close ($csync[0]);
610 # sync with child (wait until child starts)
611 POSIX
::read($psync[0], $readbuf, 4096);
614 POSIX
::close($psync[0]);
615 &$register_worker($cpid, $user, $upid);
621 die "got no worker upid - start worker failed\n" if !$readbuf;
623 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
624 die "starting worker failed: $1\n";
627 if ($readbuf ne $upid) {
628 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
632 $outfh = PVE
::Tools
::upid_open
($upid);
639 POSIX
::write($csync[1], $msg, length ($msg));
640 POSIX
::close($csync[1]);
643 POSIX
::close($csync[1]);
644 kill(-9, $cpid); # make sure it gets killed
648 PVE
::Cluster
::log_msg
('info', $user, "starting task $upid");
650 my $tlist = active_workers
($upid, $sync);
651 PVE
::Cluster
::broadcast_tasklist
($tlist);
660 local $SIG{INT
} = local $SIG{QUIT
} = local $SIG{TERM
} = sub {
661 # always send signal to all pgrp members
663 if ($int_count < 3) {
664 kill(15, $kpid); # send TERM signal
666 kill(9, $kpid); # send KILL signal
670 local $SIG{PIPE
} = sub { die "broken pipe\n"; };
672 my $select = new IO
::Select
;
673 my $fh = IO
::Handle-
>new_from_fd($psync[0], 'r');
676 while ($select->count) {
677 my @handles = $select->can_read(1);
678 if (scalar(@handles)) {
679 my $count = sysread ($handles[0], $readbuf, 4096);
680 if (!defined ($count)) {
682 die "sync pipe read error: $err\n";
684 last if $count == 0; # eof
687 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
690 if ($data =~ m/^TASK OK$/) {
692 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
703 # some commands daemonize without closing stdout
704 last if !PVE
::ProcFSTools
::check_process_running
($cpid);
710 POSIX
::close($psync[0]);
712 if ($outbuf) { # just to be sure
715 print $outfh $outbuf;
721 print STDERR
"$err\n";
723 print $outfh "TASK ERROR: $err\n";
727 &$kill_process_group($cpid, $pstart); # make sure it gets killed
733 &$log_task_result($upid, $user, $res);
736 return wantarray ?
($upid, $res) : $upid;