add a way to return file changes (diffs)
[pve-access-control.git] / PVE / RPCEnvironment.pm
CommitLineData
2c3a6c0a
DM
1package PVE::RPCEnvironment;
2
3use strict;
4use warnings;
8d6e045f 5use POSIX qw(:sys_wait_h EINTR);
b28410fc 6use IO::Handle;
2c3a6c0a 7use IO::File;
b28410fc 8use IO::Select;
2c3a6c0a
DM
9use Fcntl qw(:flock);
10use PVE::SafeSyslog;
11use PVE::Tools;
12use PVE::INotify;
13use PVE::Cluster;
14use PVE::ProcFSTools;
15use PVE::AccessControl;
7b24102d 16use CGI;
2c3a6c0a
DM
17
18# we use this singleton class to pass RPC related environment values
19
20my $pve_env;
21
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)
29
30my $WORKER_PIDS;
31
32my $log_task_result = sub {
33 my ($upid, $user, $status) = @_;
34
35 my $msg = 'successful';
36 my $pri = 'info';
37 if ($status != 0) {
38 my $ec = $status >> 8;
39 my $ic = $status & 255;
40 $msg = $ec ? "failed ($ec)" : "interrupted ($ic)";
41 $pri = 'err';
42 }
43 my $tlist = active_workers($upid);
44 PVE::Cluster::broadcast_tasklist($tlist);
45 my $task;
46 foreach my $t (@$tlist) {
47 if ($t->{upid} eq $upid) {
48 $task = $t;
49 last;
50 }
51 }
52 if ($task && $task->{status}) {
53 $msg = $task->{status};
54 }
55 PVE::Cluster::log_msg($pri, $user, "end task $upid $msg");
56};
57
58my $worker_reaper = sub {
59 local $!; local $?;
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}, $?);
66 }
67 delete ($WORKER_PIDS->{$pid});
68 }
69 }
70};
71
72my $register_worker = sub {
73 my ($pid, $user, $upid) = @_;
74
75 return if !$pid;
76
77 # do not register if already finished
78 my $waitpid = waitpid ($pid, WNOHANG);
79 if (defined($waitpid) && ($waitpid == $pid)) {
80 delete ($WORKER_PIDS->{$pid});
81 return;
82 }
83
84 $WORKER_PIDS->{$pid} = {
85 user => $user,
86 upid => $upid,
87 };
88};
89
90# ACL cache
91
92my $compile_acl = sub {
93 my ($self, $user) = @_;
94
95 my $res = {};
96 my $cfg = $self->{user_cfg};
97
98 return undef if !$cfg->{roles};
99
100 if ($user eq 'root@pam') { # root can do anything
101 return {'/' => $cfg->{roles}->{'Administrator'}};
102 }
103
104 foreach my $path (sort keys %{$cfg->{acl}}) {
105 my @ra = PVE::AccessControl::roles($cfg, $user, $path);
106
107 my $privs = {};
108 foreach my $role (@ra) {
109 if (my $privset = $cfg->{roles}->{$role}) {
110 foreach my $p (keys %$privset) {
111 $privs->{$p} = 1;
112 }
113 }
114 }
115
116 $res->{$path} = $privs;
117 }
118
119 return $res;
120};
121
122sub permissions {
123 my ($self, $user, $path) = @_;
124
125 $user = PVE::AccessControl::verify_username($user, 1);
126 return {} if !$user;
127
128 my $cache = $self->{aclcache};
129
130 my $acl = $cache->{$user};
131
132 if (!$acl) {
133 if (!($acl = &$compile_acl($self, $user))) {
134 return {};
135 }
136 $cache->{$user} = $acl;
137 }
138
139 my $perm;
140
141 if (!($perm = $acl->{$path})) {
142 $perm = {};
143 foreach my $p (sort keys %$acl) {
144 my $final = ($path eq $p);
145
146 next if !(($p eq '/') || $final || ($path =~ m|^$p/|));
147
148 $perm = $acl->{$p};
149 }
150 $acl->{$path} = $perm;
151 }
152
153 return $perm;
154}
155
156sub check {
157 my ($self, $user, $path, $privs) = @_;
158
159 my $perm = $self->permissions($user, $path);
160
161 foreach my $priv (@$privs) {
162 return undef if !$perm->{$priv};
163 };
164
165 return 1;
166};
167
168sub user_enabled {
169 my ($self, $user) = @_;
170
171 my $cfg = $self->{user_cfg};
172 return PVE::AccessControl::user_enabled($cfg, $user);
173}
174
175# initialize environment - must be called once at program startup
176sub init {
177 my ($class, $type, %params) = @_;
178
179 $class = ref($class) || $class;
180
181 die "already initialized" if $pve_env;
182
e42eedbc 183 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
2c3a6c0a
DM
184
185 $SIG{CHLD} = $worker_reaper;
186
187 # environment types
188 # cli ... command started fron command line
189 # pub ... access from public server (apache)
190 # priv ... access from private server (pvedaemon)
e42eedbc 191 # ha ... access from HA resource manager agent (rgmanager)
2c3a6c0a
DM
192
193 my $self = {
194 user_cfg => {},
195 aclcache => {},
196 aclversion => undef,
197 type => $type,
198 };
199
200 bless $self, $class;
201
202 foreach my $p (keys %params) {
203 if ($p eq 'atfork') {
204 $self->{$p} = $params{$p};
205 } else {
206 die "unknown option '$p'";
207 }
208 }
209
210 $pve_env = $self;
211
212 my ($sysname, $nodename) = POSIX::uname();
213
214 $nodename =~ s/\..*$//; # strip domain part, if any
215
216 $self->{nodename} = $nodename;
217
218 return $self;
219};
220
221# get the singleton
222sub get {
223
224 die "not initialized" if !$pve_env;
225
226 return $pve_env;
227}
228
7b24102d
DM
229sub parse_params {
230 my ($self, $enable_upload) = @_;
231
232 if ($self->{request_rec}) {
233 my $cgi;
234 if ($enable_upload) {
235 $cgi = CGI->new($self->{request_rec});
236 } else {
237 # disable upload using empty upload_hook
238 $cgi = CGI->new($self->{request_rec}, sub {}, undef, 0);
239 }
240 $self->{cgi} = $cgi;
241 my $params = $cgi->Vars();
242 return $params;
243 } elsif ($self->{params}) {
244 return $self->{params};
245 } else {
246 die "no parameters registered";
247 }
248}
249
250sub get_upload_info {
251 my ($self, $param) = @_;
252
253 my $cgi = $self->{cgi};
254 die "CGI not initialized" if !$cgi;
255
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;
260
261 my $res = { %$info };
262
263 my $tmpfilename = $cgi->tmpFileName($pd);
264 die "unable to get cgi upload file name\n" if !$tmpfilename;
265 $res->{tmpfilename} = $tmpfilename;
266
267 #my $hndl = $cgi->upload($param);
268 #die "unable to get cgi upload handle\n" if !$hndl;
269 #$res->{handle} = $hndl->handle;
270
271 return $res;
272}
273
2c3a6c0a
DM
274# init_request - must be called before each RPC request
275sub init_request {
276 my ($self, %params) = @_;
277
278 PVE::Cluster::cfs_update();
279
272fe9ff
DM
280 $self->{result_count} = undef;
281 $self->{result_changes} = undef;
282
2c3a6c0a
DM
283 my $userconfig; # we use this for regression tests
284 foreach my $p (keys %params) {
285 if ($p eq 'userconfig') {
286 $userconfig = $params{$p};
7b24102d
DM
287 } elsif ($p eq 'request_rec') {
288 # pass Apache2::RequestRec
289 $self->{request_rec} = $params{$p};
290 } elsif ($p eq 'params') {
291 $self->{params} = $params{$p};
2c3a6c0a
DM
292 } else {
293 die "unknown parameter '$p'";
294 }
295 }
296
297 eval {
298 $self->{aclcache} = {};
299 if ($userconfig) {
300 my $ucdata = PVE::Tools::file_get_contents($userconfig);
301 my $cfg = PVE::AccessControl::parse_user_config($userconfig, $ucdata);
302 $self->{user_cfg} = $cfg;
303 } else {
304 my $ucvers = PVE::Cluster::cfs_file_version('user.cfg');
305 if (!$self->{aclcache} || !defined($self->{aclversion}) ||
306 !defined($ucvers) || ($ucvers ne $self->{aclversion})) {
307 $self->{aclversion} = $ucvers;
308 my $cfg = PVE::Cluster::cfs_read_file('user.cfg');
309 $self->{user_cfg} = $cfg;
310 }
311 }
312 };
313 if (my $err = $@) {
314 $self->{user_cfg} = {};
315 die "Unable to load access control list: $err";
316 }
317}
318
319sub set_client_ip {
320 my ($self, $ip) = @_;
321
322 $self->{client_ip} = $ip;
323}
324
325sub get_client_ip {
326 my ($self) = @_;
327
328 return $self->{client_ip};
329}
330
331sub set_result_count {
332 my ($self, $count) = @_;
333
334 $self->{result_count} = $count;
335}
336
337sub get_result_count {
338 my ($self) = @_;
339
340 return $self->{result_count};
341}
342
272fe9ff
DM
343sub set_result_changes {
344 my ($self, $diff) = @_;
345
346 $self->{result_changes} = $diff;
347}
348
349sub get_result_changes {
350 my ($self) = @_;
351
352 return $self->{result_changes};
353}
354
2c3a6c0a
DM
355sub set_language {
356 my ($self, $lang) = @_;
357
358 # fixme: initialize I18N
359
360 $self->{language} = $lang;
361}
362
363sub get_language {
364 my ($self) = @_;
365
366 return $self->{language};
367}
368
369sub set_user {
370 my ($self, $user) = @_;
371
372 # fixme: get ACLs
373
374 $self->{user} = $user;
375}
376
377sub get_user {
378 my ($self) = @_;
379
380 die "user name not set\n" if !$self->{user};
381
382 return $self->{user};
383}
384
385# read/update list of active workers
386# we move all finished tasks to the archive index,
387# but keep aktive and most recent task in the active file.
5bf71a96
DM
388# $nocheck ... consider $new_upid still running (avoid that
389# we try to read the reult to early.
2c3a6c0a 390sub active_workers {
5bf71a96 391 my ($new_upid, $nocheck) = @_;
2c3a6c0a
DM
392
393 my $lkfn = "/var/log/pve/tasks/.active.lock";
394
395 my $timeout = 10;
396
397 my $code = sub {
398
399 my $tasklist = PVE::INotify::read_file('active');
400
401 my @ta;
402 my $tlist = [];
403 my $thash = {}; # only list task once
404
405 my $check_task = sub {
d33d0735 406 my ($task, $running) = @_;
2c3a6c0a 407
d33d0735 408 if ($running || PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart})) {
2c3a6c0a
DM
409 push @$tlist, $task;
410 } else {
411 delete $task->{pid};
412 push @ta, $task;
413 }
414 delete $task->{pstart};
415 };
416
417 foreach my $task (@$tasklist) {
418 my $upid = $task->{upid};
419 next if $thash->{$upid};
420 $thash->{$upid} = $task;
421 &$check_task($task);
422 }
423
424 if ($new_upid && !(my $task = $thash->{$new_upid})) {
425 $task = PVE::Tools::upid_decode($new_upid);
426 $task->{upid} = $new_upid;
427 $thash->{$new_upid} = $task;
d33d0735 428 &$check_task($task, $nocheck);
2c3a6c0a
DM
429 }
430
431
432 @ta = sort { $b->{starttime} cmp $a->{starttime} } @ta;
433
434 my $save = defined($new_upid);
435
436 foreach my $task (@ta) {
437 next if $task->{endtime};
438 $task->{endtime} = time();
439 $task->{status} = PVE::Tools::upid_read_status($task->{upid});
440 $save = 1;
441 }
442
443 my $archive = '';
444 my @arlist = ();
445 foreach my $task (@ta) {
446 if (!$task->{saved}) {
447 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime});
448 $save = 1;
449 push @arlist, $task;
450 $task->{saved} = 1;
451 }
452 }
453
454 if ($archive) {
455 my $size = 0;
456 my $filename = "/var/log/pve/tasks/index";
457 eval {
458 my $fh = IO::File->new($filename, '>>', 0644) ||
459 die "unable to open file '$filename' - $!\n";
460 PVE::Tools::safe_print($filename, $fh, $archive);
461 $size = -s $fh;
462 close($fh) ||
463 die "unable to close file '$filename' - $!\n";
464 };
465 my $err = $@;
466 if ($err) {
467 syslog('err', $err);
468 foreach my $task (@arlist) { # mark as not saved
469 $task->{saved} = 0;
470 }
471 }
472 my $maxsize = 50000; # about 1000 entries
473 if ($size > $maxsize) {
474 rename($filename, "$filename.1");
475 }
476 }
477
478 # we try to reduce the amount of data
479 # list all running tasks and task and a few others
480 # try to limit to 25 tasks
481 my $ctime = time();
482 my $max = 25 - scalar(@$tlist);
483 foreach my $task (@ta) {
484 last if $max <= 0;
485 push @$tlist, $task;
486 $max--;
487 }
488
489 PVE::INotify::write_file('active', $tlist) if $save;
490
491 return $tlist;
492 };
493
494 my $res = PVE::Tools::lock_file($lkfn, $timeout, $code);
495 die $@ if $@;
496
497 return $res;
498}
499
b9e47e57
DM
500my $kill_process_group = sub {
501 my ($pid, $pstart) = @_;
502
503 # send kill to process group (negative pid)
504 my $kpid = -$pid;
505
506 # always send signal to all pgrp members
507 kill(15, $kpid); # send TERM signal
508
509 # give max 5 seconds to shut down
510 for (my $i = 0; $i < 5; $i++) {
511 return if !PVE::ProcFSTools::check_process_running($pid, $pstart);
512 sleep (1);
513 }
514
515 # to be sure
516 kill(9, $kpid);
517};
518
519sub check_worker {
520 my ($upid, $killit) = @_;
521
522 my $task = PVE::Tools::upid_decode($upid);
523
524 my $running = PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart});
525
526 return 0 if !$running;
527
528 if ($killit) {
529 &$kill_process_group($task->{pid});
530 return 0;
531 }
532
533 return 1;
534}
535
2c3a6c0a
DM
536# start long running workers
537# STDIN is redirected to /dev/null
538# STDOUT,STDERR are redirected to the filename returned by upid_decode
539# NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
540sub fork_worker {
541 my ($self, $dtype, $id, $user, $function) = @_;
542
543 $dtype = 'unknown' if !defined ($dtype);
544 $id = '' if !defined ($id);
545
546 $user = 'root@pve' if !defined ($user);
547
548 my $sync = $self->{type} eq 'cli' ? 1 : 0;
549
550 local $SIG{INT} =
551 local $SIG{QUIT} =
552 local $SIG{PIPE} =
553 local $SIG{TERM} = 'IGNORE';
554
555 my $starttime = time ();
556
557 my @psync = POSIX::pipe();
558 my @csync = POSIX::pipe();
559
560 my $node = $self->{nodename};
561
562 my $cpid = fork();
563 die "unable to fork worker - $!" if !defined($cpid);
564
565 my $workerpuid = $cpid ? $cpid : $$;
566
567 my $pstart = PVE::ProcFSTools::read_proc_starttime($workerpuid) ||
568 die "unable to read process start time";
569
570 my $upid = PVE::Tools::upid_encode ({
571 node => $node, pid => $workerpuid, pstart => $pstart,
572 starttime => $starttime, type => $dtype, id => $id, user => $user });
573
574 my $outfh;
575
576 if (!$cpid) { # child
577
578 $0 = "task $upid";
579
580 $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub { die "received interrupt\n"; };
581
582 $SIG{CHLD} = $SIG{PIPE} = 'DEFAULT';
583
584 # set sess/process group - we want to be able to kill the
585 # whole process group
586 POSIX::setsid();
587
588 POSIX::close ($psync[0]);
589 POSIX::close ($csync[1]);
590
591 $outfh = $sync ? $psync[1] : undef;
592
593 eval {
594 PVE::INotify::inotify_close();
595
596 if (my $atfork = $self->{atfork}) {
597 &$atfork();
598 }
599
600 # same algorythm as used inside SA
601 # STDIN = /dev/null
602 my $fd = fileno (STDIN);
2c3a6c0a 603
5a941ebe
DM
604 if (!$sync) {
605 close STDIN;
606 POSIX::close(0) if $fd != 0;
607
608 die "unable to redirect STDIN - $!"
609 if !open(STDIN, "</dev/null");
610
611 $outfh = PVE::Tools::upid_open($upid);
612 }
2c3a6c0a 613
2c3a6c0a
DM
614
615 # redirect STDOUT
616 $fd = fileno(STDOUT);
617 close STDOUT;
618 POSIX::close (1) if $fd != 1;
619
620 die "unable to redirect STDOUT - $!"
621 if !open(STDOUT, ">&", $outfh);
622
623 STDOUT->autoflush (1);
624
625 # redirect STDERR to STDOUT
626 $fd = fileno (STDERR);
627 close STDERR;
628 POSIX::close(2) if $fd != 2;
629
630 die "unable to redirect STDERR - $!"
631 if !open(STDERR, ">&1");
632
633 STDERR->autoflush(1);
634 };
635 if (my $err = $@) {
636 my $msg = "ERROR: $err";
637 POSIX::write($psync[1], $msg, length ($msg));
638 POSIX::close($psync[1]);
639 POSIX::_exit(1);
b9e47e57 640 kill(-9, $$);
2c3a6c0a
DM
641 }
642
f6f2d51f 643 # sync with parent (signal that we are ready)
2c3a6c0a
DM
644 if ($sync) {
645 print "$upid\n";
646 } else {
647 POSIX::write($psync[1], $upid, length ($upid));
648 POSIX::close($psync[1]);
649 }
650
651 my $readbuf = '';
652 # sync with parent (wait until parent is ready)
653 POSIX::read($csync[0], $readbuf, 4096);
654 die "parent setup error\n" if $readbuf ne 'OK';
655
e42eedbc
DM
656 if ($self->{type} eq 'ha') {
657 print "task started by HA resource agent\n";
658 }
2c3a6c0a
DM
659 eval { &$function($upid); };
660 my $err = $@;
661 if ($err) {
662 chomp $err;
663 $err =~ s/\n/ /mg;
664 syslog('err', $err);
665 print STDERR "TASK ERROR: $err\n";
666 POSIX::_exit(-1);
667 } else {
668 print STDERR "TASK OK\n";
b9e47e57 669 POSIX::_exit(0);
2c3a6c0a 670 }
b9e47e57 671 kill(-9, $$);
2c3a6c0a
DM
672 }
673
674 # parent
675
676 POSIX::close ($psync[1]);
677 POSIX::close ($csync[0]);
678
679 my $readbuf = '';
680 # sync with child (wait until child starts)
681 POSIX::read($psync[0], $readbuf, 4096);
682
683 if (!$sync) {
684 POSIX::close($psync[0]);
685 &$register_worker($cpid, $user, $upid);
686 } else {
687 chomp $readbuf;
688 }
689
690 eval {
691 die "got no worker upid - start worker failed\n" if !$readbuf;
692
693 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
694 die "starting worker failed: $1\n";
695 }
696
697 if ($readbuf ne $upid) {
698 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
699 }
700
701 if ($sync) {
702 $outfh = PVE::Tools::upid_open($upid);
703 }
704 };
705 my $err = $@;
706
707 if (!$err) {
708 my $msg = 'OK';
709 POSIX::write($csync[1], $msg, length ($msg));
710 POSIX::close($csync[1]);
711
712 } else {
713 POSIX::close($csync[1]);
b9e47e57 714 kill(-9, $cpid); # make sure it gets killed
2c3a6c0a
DM
715 die $err;
716 }
717
718 PVE::Cluster::log_msg('info', $user, "starting task $upid");
719
5bf71a96 720 my $tlist = active_workers($upid, $sync);
2c3a6c0a
DM
721 PVE::Cluster::broadcast_tasklist($tlist);
722
723 my $res = 0;
724
725 if ($sync) {
726 my $count;
727 my $outbuf = '';
8d6e045f 728 my $int_count = 0;
2c3a6c0a 729 eval {
8d6e045f 730 local $SIG{INT} = local $SIG{QUIT} = local $SIG{TERM} = sub {
527b2e7a
DM
731 # always send signal to all pgrp members
732 my $kpid = -$cpid;
8d6e045f 733 if ($int_count < 3) {
527b2e7a 734 kill(15, $kpid); # send TERM signal
8d6e045f 735 } else {
527b2e7a 736 kill(9, $kpid); # send KILL signal
8d6e045f
DM
737 }
738 $int_count++;
739 };
2c3a6c0a 740 local $SIG{PIPE} = sub { die "broken pipe\n"; };
b28410fc
DM
741
742 my $select = new IO::Select;
743 my $fh = IO::Handle->new_from_fd($psync[0], 'r');
744 $select->add($fh);
745
746 while ($select->count) {
747 my @handles = $select->can_read(1);
748 if (scalar(@handles)) {
749 my $count = sysread ($handles[0], $readbuf, 4096);
750 if (!defined ($count)) {
751 my $err = $!;
752 die "sync pipe read error: $err\n";
2c3a6c0a 753 }
b28410fc
DM
754 last if $count == 0; # eof
755
756 $outbuf .= $readbuf;
757 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
758 my $line = $1;
759 my $data = $2;
760 if ($data =~ m/^TASK OK$/) {
761 # skip
762 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
763 print STDERR "$1\n";
764 } else {
765 print $line;
766 }
767 if ($outfh) {
768 print $outfh $line;
769 $outfh->flush();
770 }
2c3a6c0a 771 }
b28410fc
DM
772 } else {
773 # some commands daemonize without closing stdout
774 last if !PVE::ProcFSTools::check_process_running($cpid);
2c3a6c0a
DM
775 }
776 }
777 };
778 my $err = $@;
779
780 POSIX::close($psync[0]);
781
782 if ($outbuf) { # just to be sure
783 print $outbuf;
784 if ($outfh) {
785 print $outfh $outbuf;
786 }
787 }
788
789 if ($err) {
790 $err =~ s/\n/ /mg;
791 print STDERR "$err\n";
792 if ($outfh) {
793 print $outfh "TASK ERROR: $err\n";
794 }
2c3a6c0a
DM
795 }
796
b9e47e57
DM
797 &$kill_process_group($cpid, $pstart); # make sure it gets killed
798
2c3a6c0a
DM
799 close($outfh);
800
b9e47e57 801 waitpid($cpid, 0);
2c3a6c0a
DM
802 $res = $?;
803 &$log_task_result($upid, $user, $res);
804 }
805
806 return wantarray ? ($upid, $res) : $upid;
807}
808
8091;