]> git.proxmox.com Git - pve-access-control.git/blob - PVE/RPCEnvironment.pm
8750e735ed0855ada738c0d0817ee091b669f813
[pve-access-control.git] / PVE / RPCEnvironment.pm
1 package PVE::RPCEnvironment;
2
3 use strict;
4 use warnings;
5 use POSIX qw(:sys_wait_h EINTR);
6 use IO::Handle;
7 use IO::File;
8 use IO::Select;
9 use Fcntl qw(:flock);
10 use PVE::Exception qw(raise raise_perm_exc);
11 use PVE::SafeSyslog;
12 use PVE::Tools;
13 use PVE::INotify;
14 use PVE::Cluster;
15 use PVE::ProcFSTools;
16 use PVE::AccessControl;
17 use CGI;
18
19 # we use this singleton class to pass RPC related environment values
20
21 my $pve_env;
22
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)
30
31 my $WORKER_PIDS;
32
33 my $log_task_result = sub {
34 my ($upid, $user, $status) = @_;
35
36 my $msg = 'successful';
37 my $pri = 'info';
38 if ($status != 0) {
39 my $ec = $status >> 8;
40 my $ic = $status & 255;
41 $msg = $ec ? "failed ($ec)" : "interrupted ($ic)";
42 $pri = 'err';
43 }
44 my $tlist = active_workers($upid);
45 PVE::Cluster::broadcast_tasklist($tlist);
46 my $task;
47 foreach my $t (@$tlist) {
48 if ($t->{upid} eq $upid) {
49 $task = $t;
50 last;
51 }
52 }
53 if ($task && $task->{status}) {
54 $msg = $task->{status};
55 }
56 PVE::Cluster::log_msg($pri, $user, "end task $upid $msg");
57 };
58
59 my $worker_reaper = sub {
60 local $!; local $?;
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}, $?);
67 }
68 delete ($WORKER_PIDS->{$pid});
69 }
70 }
71 };
72
73 my $register_worker = sub {
74 my ($pid, $user, $upid) = @_;
75
76 return if !$pid;
77
78 # do not register if already finished
79 my $waitpid = waitpid ($pid, WNOHANG);
80 if (defined($waitpid) && ($waitpid == $pid)) {
81 delete ($WORKER_PIDS->{$pid});
82 return;
83 }
84
85 $WORKER_PIDS->{$pid} = {
86 user => $user,
87 upid => $upid,
88 };
89 };
90
91 # ACL cache
92
93 my $compile_acl_path = sub {
94 my ($self, $user, $path) = @_;
95
96 my $cfg = $self->{user_cfg};
97
98 return undef if !$cfg->{roles};
99
100 die "internal error" if $user eq 'root@pam';
101
102 my $cache = $self->{aclcache};
103 $cache->{$user} = {} if !$cache->{$user};
104 my $data = $cache->{$user};
105
106 if (!$data->{poolroles}) {
107 $data->{poolroles} = {};
108
109 foreach my $pool (keys %{$cfg->{pools}}) {
110 my $d = $cfg->{pools}->{$pool};
111 my @ra = PVE::AccessControl::roles($cfg, $user, "/pool/$pool"); # pool roles
112 next if !scalar(@ra);
113 foreach my $vmid (keys %{$d->{vms}}) {
114 for my $role (@ra) {
115 $data->{poolroles}->{"/vms/$vmid"}->{$role} = 1;
116 }
117 }
118 foreach my $storeid (keys %{$d->{storage}}) {
119 for my $role (@ra) {
120 $data->{poolroles}->{"/storage/$storeid"}->{$role} = 1;
121 }
122 }
123 }
124 }
125
126 my @ra = PVE::AccessControl::roles($cfg, $user, $path);
127
128 # apply roles inherited from pools
129 # Note: assume we do not want to propagate those privs
130 if ($data->{poolroles}->{$path}) {
131 if (!($ra[0] && $ra[0] eq 'NoAccess')) {
132 if ($data->{poolroles}->{$path}->{NoAccess}) {
133 @ra = ('NoAccess');
134 } else {
135 foreach my $role (keys %{$data->{poolroles}->{$path}}) {
136 push @ra, $role;
137 }
138 }
139 }
140 }
141
142 $data->{roles}->{$path} = [ @ra ];
143
144 my $privs = {};
145 foreach my $role (@ra) {
146 if (my $privset = $cfg->{roles}->{$role}) {
147 foreach my $p (keys %$privset) {
148 $privs->{$p} = 1;
149 }
150 }
151 }
152 $data->{privs}->{$path} = $privs;
153
154 return $privs;
155 };
156
157 sub roles {
158 my ($self, $user, $path) = @_;
159
160 if ($user eq 'root@pam') { # root can do anything
161 return ('Administrator');
162 }
163
164 $user = PVE::AccessControl::verify_username($user, 1);
165 return () if !$user;
166
167 my $cache = $self->{aclcache};
168 $cache->{$user} = {} if !$cache->{$user};
169
170 my $acl = $cache->{$user};
171
172 my $roles = $acl->{roles}->{$path};
173 return @$roles if $roles;
174
175 &$compile_acl_path($self, $user, $path);
176 $roles = $acl->{roles}->{$path} || [];
177 return @$roles;
178 }
179
180 sub permissions {
181 my ($self, $user, $path) = @_;
182
183 if ($user eq 'root@pam') { # root can do anything
184 my $cfg = $self->{user_cfg};
185 return $cfg->{roles}->{'Administrator'};
186 }
187
188 $user = PVE::AccessControl::verify_username($user, 1);
189 return {} if !$user;
190
191 my $cache = $self->{aclcache};
192 $cache->{$user} = {} if !$cache->{$user};
193
194 my $acl = $cache->{$user};
195
196 my $perm = $acl->{privs}->{$path};
197 return $perm if $perm;
198
199 return &$compile_acl_path($self, $user, $path);
200 }
201
202 sub check {
203 my ($self, $user, $path, $privs, $noerr) = @_;
204
205 my $perm = $self->permissions($user, $path);
206
207 foreach my $priv (@$privs) {
208 PVE::AccessControl::verify_privname($priv);
209 if (!$perm->{$priv}) {
210 return undef if $noerr;
211 raise_perm_exc("$path, $priv");
212 }
213 };
214
215 return 1;
216 };
217
218 sub check_any {
219 my ($self, $user, $path, $privs, $noerr) = @_;
220
221 my $perm = $self->permissions($user, $path);
222
223 my $found = 0;
224 foreach my $priv (@$privs) {
225 PVE::AccessControl::verify_privname($priv);
226 if ($perm->{$priv}) {
227 $found = 1;
228 last;
229 }
230 };
231
232 return 1 if $found;
233
234 return undef if $noerr;
235
236 raise_perm_exc("$path, " . join("|", @$privs));
237 };
238
239 sub check_user_enabled {
240 my ($self, $user, $noerr) = @_;
241
242 my $cfg = $self->{user_cfg};
243 return PVE::AccessControl::check_user_enabled($cfg, $user, $noerr);
244 }
245
246 sub check_user_exist {
247 my ($self, $user, $noerr) = @_;
248
249 my $cfg = $self->{user_cfg};
250 return PVE::AccessControl::check_user_exist($cfg, $user, $noerr);
251 }
252
253 sub is_group_member {
254 my ($self, $group, $user) = @_;
255
256 my $cfg = $self->{user_cfg};
257
258 return 0 if !$cfg->{groups}->{$group};
259
260 return defined($cfg->{groups}->{$group}->{users}->{$user});
261 }
262
263 sub filter_groups {
264 my ($self, $user, $privs, $any) = @_;
265
266 my $cfg = $self->{user_cfg};
267
268 my $groups = {};
269 foreach my $group (keys %{$cfg->{groups}}) {
270 my $path = "/access/groups/$group";
271 if ($any) {
272 if ($self->check_any($user, $path, $privs, 1)) {
273 $groups->{$group} = $cfg->{groups}->{$group};
274 }
275 } else {
276 if ($self->check($user, $path, $privs, 1)) {
277 $groups->{$group} = $cfg->{groups}->{$group};
278 }
279 }
280 }
281
282 return $groups;
283 }
284
285 sub group_member_join {
286 my ($self, $grouplist) = @_;
287
288 my $users = {};
289
290 my $cfg = $self->{user_cfg};
291 foreach my $group (@$grouplist) {
292 my $data = $cfg->{groups}->{$group};
293 next if !$data;
294 foreach my $user (keys %{$data->{users}}) {
295 $users->{$user} = 1;
296 }
297 }
298
299 return $users;
300 }
301
302 sub check_perm_modify {
303 my ($self, $username, $path, $noerr) = @_;
304
305 return $self->check($username, '/access', [ 'Permissions.Modify' ], $noerr) if !$path;
306
307 my $testperms = [ 'Permissions.Modify' ];
308 if ($path =~ m|^/storage/.+$|) {
309 push @$testperms, 'Datastore.Allocate';
310 } elsif ($path =~ m|^/vms/.+$|) {
311 push @$testperms, 'VM.Allocate';
312 } elsif ($path =~ m|^/pool/.+$|) {
313 push @$testperms, 'Pool.Allocate';
314 }
315
316 return $self->check_any($username, $path, $testperms, $noerr);
317 }
318
319 sub exec_api2_perm_check {
320 my ($self, $check, $username, $param, $noerr) = @_;
321
322 # syslog("info", "CHECK " . join(', ', @$check));
323
324 my $ind = 0;
325 my $test = $check->[$ind++];
326 die "no permission test specified" if !$test;
327
328 if ($test eq 'and') {
329 while (my $subcheck = $check->[$ind++]) {
330 $self->exec_api2_perm_check($subcheck, $username, $param);
331 }
332 return 1;
333 } elsif ($test eq 'or') {
334 while (my $subcheck = $check->[$ind++]) {
335 return 1 if $self->exec_api2_perm_check($subcheck, $username, $param, 1);
336 }
337 return 0 if $noerr;
338 raise_perm_exc();
339 } elsif ($test eq 'perm') {
340 my ($t, $tmplpath, $privs, %options) = @$check;
341 my $any = $options{any};
342 die "missing parameters" if !($tmplpath && $privs);
343 my $path = PVE::Tools::template_replace($tmplpath, $param);
344 $path = PVE::AccessControl::normalize_path($path);
345 if ($any) {
346 return $self->check_any($username, $path, $privs, $noerr);
347 } else {
348 return $self->check($username, $path, $privs, $noerr);
349 }
350 } elsif ($test eq 'userid-group') {
351 my $userid = $param->{userid};
352 my ($t, $privs, %options) = @$check;
353 return 0 if !$options{groups_param} && !$self->check_user_exist($userid, $noerr);
354 if (!$self->check_any($username, "/access/groups", $privs, 1)) {
355 my $groups = $self->filter_groups($username, $privs, 1);
356 if ($options{groups_param}) {
357 my @group_param = PVE::Tools::split_list($param->{groups});
358 raise_perm_exc("/access/groups, " . join("|", @$privs)) if !scalar(@group_param);
359 foreach my $pg (@group_param) {
360 raise_perm_exc("/access/groups/$pg, " . join("|", @$privs))
361 if !$groups->{$pg};
362 }
363 } else {
364 my $allowed_users = $self->group_member_join([keys %$groups]);
365 if (!$allowed_users->{$userid}) {
366 return 0 if $noerr;
367 raise_perm_exc();
368 }
369 }
370 }
371 return 1;
372 } elsif ($test eq 'userid-param') {
373 my ($userid, undef, $realm) = verify_username($param->{userid});
374 return if !$self->check_user_exist($userid, $noerr);
375 my ($t, $subtest) = @$check;
376 die "missing parameters" if !$subtest;
377 if ($subtest eq 'self') {
378 return 1 if $username eq 'userid';
379 return 0 if $noerr;
380 raise_perm_exc();
381 } elsif ($subtest eq 'Realm.AllocateUser') {
382 my $path = "/access/realm/$realm";
383 return $self->check($username, $path, ['Realm.AllocateUser'], $noerr);
384 return 0 if $noerr;
385 raise_perm_exc("$path, 'Realm.AllocateUser'");
386 } else {
387 die "unknown userid-param test";
388 }
389 } elsif ($test eq 'perm-modify') {
390 my ($t, $tmplpath) = @$check;
391 my $path = PVE::Tools::template_replace($tmplpath, $param);
392 $path = PVE::AccessControl::normalize_path($path);
393 return $self->check_perm_modify($username, $path, $noerr);
394 } else {
395 die "unknown permission test";
396 }
397 };
398
399 sub check_api2_permissions {
400 my ($self, $perm, $username, $param) = @_;
401
402 return 1 if !$username && $perm->{user} eq 'world';
403
404 raise_perm_exc("user != null") if !$username;
405
406 return 1 if $username eq 'root@pam';
407
408 raise_perm_exc('user != root@pam') if !$perm;
409
410 return 1 if $perm->{user} && $perm->{user} eq 'all';
411
412 return $self->exec_api2_perm_check($perm->{check}, $username, $param)
413 if $perm->{check};
414
415 raise_perm_exc();
416 }
417
418 # initialize environment - must be called once at program startup
419 sub init {
420 my ($class, $type, %params) = @_;
421
422 $class = ref($class) || $class;
423
424 die "already initialized" if $pve_env;
425
426 die "unknown environment type" if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
427
428 $SIG{CHLD} = $worker_reaper;
429
430 # environment types
431 # cli ... command started fron command line
432 # pub ... access from public server (apache)
433 # priv ... access from private server (pvedaemon)
434 # ha ... access from HA resource manager agent (rgmanager)
435
436 my $self = {
437 user_cfg => {},
438 aclcache => {},
439 aclversion => undef,
440 type => $type,
441 };
442
443 bless $self, $class;
444
445 foreach my $p (keys %params) {
446 if ($p eq 'atfork') {
447 $self->{$p} = $params{$p};
448 } else {
449 die "unknown option '$p'";
450 }
451 }
452
453 $pve_env = $self;
454
455 my ($sysname, $nodename) = POSIX::uname();
456
457 $nodename =~ s/\..*$//; # strip domain part, if any
458
459 $self->{nodename} = $nodename;
460
461 return $self;
462 };
463
464 # get the singleton
465 sub get {
466
467 die "not initialized" if !$pve_env;
468
469 return $pve_env;
470 }
471
472 sub parse_params {
473 my ($self, $enable_upload) = @_;
474
475 if ($self->{request_rec}) {
476 my $cgi;
477 if ($enable_upload) {
478 $cgi = CGI->new($self->{request_rec});
479 } else {
480 # disable upload using empty upload_hook
481 $cgi = CGI->new($self->{request_rec}, sub {}, undef, 0);
482 }
483 $self->{cgi} = $cgi;
484 my $params = $cgi->Vars();
485 return PVE::Tools::decode_utf8_parameters($params);
486 } elsif ($self->{params}) {
487 return $self->{params};
488 } else {
489 die "no parameters registered";
490 }
491 }
492
493 sub get_upload_info {
494 my ($self, $param) = @_;
495
496 my $cgi = $self->{cgi};
497 die "CGI not initialized" if !$cgi;
498
499 my $pd = $cgi->param($param);
500 die "unable to get cgi parameter info\n" if !$pd;
501 my $info = $cgi->uploadInfo($pd);
502 die "unable to get cgi upload info\n" if !$info;
503
504 my $res = { %$info };
505
506 my $tmpfilename = $cgi->tmpFileName($pd);
507 die "unable to get cgi upload file name\n" if !$tmpfilename;
508 $res->{tmpfilename} = $tmpfilename;
509
510 #my $hndl = $cgi->upload($param);
511 #die "unable to get cgi upload handle\n" if !$hndl;
512 #$res->{handle} = $hndl->handle;
513
514 return $res;
515 }
516
517 # init_request - must be called before each RPC request
518 sub init_request {
519 my ($self, %params) = @_;
520
521 PVE::Cluster::cfs_update();
522
523 $self->{result_attributes} = {};
524
525 my $userconfig; # we use this for regression tests
526 foreach my $p (keys %params) {
527 if ($p eq 'userconfig') {
528 $userconfig = $params{$p};
529 } elsif ($p eq 'request_rec') {
530 # pass Apache2::RequestRec
531 $self->{request_rec} = $params{$p};
532 } elsif ($p eq 'params') {
533 $self->{params} = $params{$p};
534 } else {
535 die "unknown parameter '$p'";
536 }
537 }
538
539 eval {
540 $self->{aclcache} = {};
541 if ($userconfig) {
542 my $ucdata = PVE::Tools::file_get_contents($userconfig);
543 my $cfg = PVE::AccessControl::parse_user_config($userconfig, $ucdata);
544 $self->{user_cfg} = $cfg;
545 #print Dumper($cfg);
546 } else {
547 my $ucvers = PVE::Cluster::cfs_file_version('user.cfg');
548 if (!$self->{aclcache} || !defined($self->{aclversion}) ||
549 !defined($ucvers) || ($ucvers ne $self->{aclversion})) {
550 $self->{aclversion} = $ucvers;
551 my $cfg = PVE::Cluster::cfs_read_file('user.cfg');
552 $self->{user_cfg} = $cfg;
553 }
554 }
555 };
556 if (my $err = $@) {
557 $self->{user_cfg} = {};
558 die "Unable to load access control list: $err";
559 }
560 }
561
562 sub set_client_ip {
563 my ($self, $ip) = @_;
564
565 $self->{client_ip} = $ip;
566 }
567
568 sub get_client_ip {
569 my ($self) = @_;
570
571 return $self->{client_ip};
572 }
573
574 sub set_result_attrib {
575 my ($self, $key, $value) = @_;
576
577 $self->{result_attributes}->{$key} = $value;
578 }
579
580 sub get_result_attrib {
581 my ($self, $key) = @_;
582
583 return $self->{result_attributes}->{$key};
584 }
585
586 sub set_language {
587 my ($self, $lang) = @_;
588
589 # fixme: initialize I18N
590
591 $self->{language} = $lang;
592 }
593
594 sub get_language {
595 my ($self) = @_;
596
597 return $self->{language};
598 }
599
600 sub set_user {
601 my ($self, $user) = @_;
602
603 # fixme: get ACLs
604
605 $self->{user} = $user;
606 }
607
608 sub get_user {
609 my ($self) = @_;
610
611 die "user name not set\n" if !$self->{user};
612
613 return $self->{user};
614 }
615
616 # read/update list of active workers
617 # we move all finished tasks to the archive index,
618 # but keep aktive and most recent task in the active file.
619 # $nocheck ... consider $new_upid still running (avoid that
620 # we try to read the reult to early.
621 sub active_workers {
622 my ($new_upid, $nocheck) = @_;
623
624 my $lkfn = "/var/log/pve/tasks/.active.lock";
625
626 my $timeout = 10;
627
628 my $code = sub {
629
630 my $tasklist = PVE::INotify::read_file('active');
631
632 my @ta;
633 my $tlist = [];
634 my $thash = {}; # only list task once
635
636 my $check_task = sub {
637 my ($task, $running) = @_;
638
639 if ($running || PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart})) {
640 push @$tlist, $task;
641 } else {
642 delete $task->{pid};
643 push @ta, $task;
644 }
645 delete $task->{pstart};
646 };
647
648 foreach my $task (@$tasklist) {
649 my $upid = $task->{upid};
650 next if $thash->{$upid};
651 $thash->{$upid} = $task;
652 &$check_task($task);
653 }
654
655 if ($new_upid && !(my $task = $thash->{$new_upid})) {
656 $task = PVE::Tools::upid_decode($new_upid);
657 $task->{upid} = $new_upid;
658 $thash->{$new_upid} = $task;
659 &$check_task($task, $nocheck);
660 }
661
662
663 @ta = sort { $b->{starttime} cmp $a->{starttime} } @ta;
664
665 my $save = defined($new_upid);
666
667 foreach my $task (@ta) {
668 next if $task->{endtime};
669 $task->{endtime} = time();
670 $task->{status} = PVE::Tools::upid_read_status($task->{upid});
671 $save = 1;
672 }
673
674 my $archive = '';
675 my @arlist = ();
676 foreach my $task (@ta) {
677 if (!$task->{saved}) {
678 $archive .= sprintf("$task->{upid} %08X $task->{status}\n", $task->{endtime});
679 $save = 1;
680 push @arlist, $task;
681 $task->{saved} = 1;
682 }
683 }
684
685 if ($archive) {
686 my $size = 0;
687 my $filename = "/var/log/pve/tasks/index";
688 eval {
689 my $fh = IO::File->new($filename, '>>', 0644) ||
690 die "unable to open file '$filename' - $!\n";
691 PVE::Tools::safe_print($filename, $fh, $archive);
692 $size = -s $fh;
693 close($fh) ||
694 die "unable to close file '$filename' - $!\n";
695 };
696 my $err = $@;
697 if ($err) {
698 syslog('err', $err);
699 foreach my $task (@arlist) { # mark as not saved
700 $task->{saved} = 0;
701 }
702 }
703 my $maxsize = 50000; # about 1000 entries
704 if ($size > $maxsize) {
705 rename($filename, "$filename.1");
706 }
707 }
708
709 # we try to reduce the amount of data
710 # list all running tasks and task and a few others
711 # try to limit to 25 tasks
712 my $ctime = time();
713 my $max = 25 - scalar(@$tlist);
714 foreach my $task (@ta) {
715 last if $max <= 0;
716 push @$tlist, $task;
717 $max--;
718 }
719
720 PVE::INotify::write_file('active', $tlist) if $save;
721
722 return $tlist;
723 };
724
725 my $res = PVE::Tools::lock_file($lkfn, $timeout, $code);
726 die $@ if $@;
727
728 return $res;
729 }
730
731 my $kill_process_group = sub {
732 my ($pid, $pstart) = @_;
733
734 # send kill to process group (negative pid)
735 my $kpid = -$pid;
736
737 # always send signal to all pgrp members
738 kill(15, $kpid); # send TERM signal
739
740 # give max 5 seconds to shut down
741 for (my $i = 0; $i < 5; $i++) {
742 return if !PVE::ProcFSTools::check_process_running($pid, $pstart);
743 sleep (1);
744 }
745
746 # to be sure
747 kill(9, $kpid);
748 };
749
750 sub check_worker {
751 my ($upid, $killit) = @_;
752
753 my $task = PVE::Tools::upid_decode($upid);
754
755 my $running = PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart});
756
757 return 0 if !$running;
758
759 if ($killit) {
760 &$kill_process_group($task->{pid});
761 return 0;
762 }
763
764 return 1;
765 }
766
767 # start long running workers
768 # STDIN is redirected to /dev/null
769 # STDOUT,STDERR are redirected to the filename returned by upid_decode
770 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
771 sub fork_worker {
772 my ($self, $dtype, $id, $user, $function) = @_;
773
774 $dtype = 'unknown' if !defined ($dtype);
775 $id = '' if !defined ($id);
776
777 $user = 'root@pve' if !defined ($user);
778
779 my $sync = $self->{type} eq 'cli' ? 1 : 0;
780
781 local $SIG{INT} =
782 local $SIG{QUIT} =
783 local $SIG{PIPE} =
784 local $SIG{TERM} = 'IGNORE';
785
786 my $starttime = time ();
787
788 my @psync = POSIX::pipe();
789 my @csync = POSIX::pipe();
790
791 my $node = $self->{nodename};
792
793 my $cpid = fork();
794 die "unable to fork worker - $!" if !defined($cpid);
795
796 my $workerpuid = $cpid ? $cpid : $$;
797
798 my $pstart = PVE::ProcFSTools::read_proc_starttime($workerpuid) ||
799 die "unable to read process start time";
800
801 my $upid = PVE::Tools::upid_encode ({
802 node => $node, pid => $workerpuid, pstart => $pstart,
803 starttime => $starttime, type => $dtype, id => $id, user => $user });
804
805 my $outfh;
806
807 if (!$cpid) { # child
808
809 $0 = "task $upid";
810
811 $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub { die "received interrupt\n"; };
812
813 $SIG{CHLD} = $SIG{PIPE} = 'DEFAULT';
814
815 # set sess/process group - we want to be able to kill the
816 # whole process group
817 POSIX::setsid();
818
819 POSIX::close ($psync[0]);
820 POSIX::close ($csync[1]);
821
822 $outfh = $sync ? $psync[1] : undef;
823
824 eval {
825 PVE::INotify::inotify_close();
826
827 if (my $atfork = $self->{atfork}) {
828 &$atfork();
829 }
830
831 # same algorythm as used inside SA
832 # STDIN = /dev/null
833 my $fd = fileno (STDIN);
834
835 if (!$sync) {
836 close STDIN;
837 POSIX::close(0) if $fd != 0;
838
839 die "unable to redirect STDIN - $!"
840 if !open(STDIN, "</dev/null");
841
842 $outfh = PVE::Tools::upid_open($upid);
843 }
844
845
846 # redirect STDOUT
847 $fd = fileno(STDOUT);
848 close STDOUT;
849 POSIX::close (1) if $fd != 1;
850
851 die "unable to redirect STDOUT - $!"
852 if !open(STDOUT, ">&", $outfh);
853
854 STDOUT->autoflush (1);
855
856 # redirect STDERR to STDOUT
857 $fd = fileno (STDERR);
858 close STDERR;
859 POSIX::close(2) if $fd != 2;
860
861 die "unable to redirect STDERR - $!"
862 if !open(STDERR, ">&1");
863
864 STDERR->autoflush(1);
865 };
866 if (my $err = $@) {
867 my $msg = "ERROR: $err";
868 POSIX::write($psync[1], $msg, length ($msg));
869 POSIX::close($psync[1]);
870 POSIX::_exit(1);
871 kill(-9, $$);
872 }
873
874 # sync with parent (signal that we are ready)
875 if ($sync) {
876 print "$upid\n";
877 } else {
878 POSIX::write($psync[1], $upid, length ($upid));
879 POSIX::close($psync[1]);
880 }
881
882 my $readbuf = '';
883 # sync with parent (wait until parent is ready)
884 POSIX::read($csync[0], $readbuf, 4096);
885 die "parent setup error\n" if $readbuf ne 'OK';
886
887 if ($self->{type} eq 'ha') {
888 print "task started by HA resource agent\n";
889 }
890 eval { &$function($upid); };
891 my $err = $@;
892 if ($err) {
893 chomp $err;
894 $err =~ s/\n/ /mg;
895 syslog('err', $err);
896 print STDERR "TASK ERROR: $err\n";
897 POSIX::_exit(-1);
898 } else {
899 print STDERR "TASK OK\n";
900 POSIX::_exit(0);
901 }
902 kill(-9, $$);
903 }
904
905 # parent
906
907 POSIX::close ($psync[1]);
908 POSIX::close ($csync[0]);
909
910 my $readbuf = '';
911 # sync with child (wait until child starts)
912 POSIX::read($psync[0], $readbuf, 4096);
913
914 if (!$sync) {
915 POSIX::close($psync[0]);
916 &$register_worker($cpid, $user, $upid);
917 } else {
918 chomp $readbuf;
919 }
920
921 eval {
922 die "got no worker upid - start worker failed\n" if !$readbuf;
923
924 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
925 die "starting worker failed: $1\n";
926 }
927
928 if ($readbuf ne $upid) {
929 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
930 }
931
932 if ($sync) {
933 $outfh = PVE::Tools::upid_open($upid);
934 }
935 };
936 my $err = $@;
937
938 if (!$err) {
939 my $msg = 'OK';
940 POSIX::write($csync[1], $msg, length ($msg));
941 POSIX::close($csync[1]);
942
943 } else {
944 POSIX::close($csync[1]);
945 kill(-9, $cpid); # make sure it gets killed
946 die $err;
947 }
948
949 PVE::Cluster::log_msg('info', $user, "starting task $upid");
950
951 my $tlist = active_workers($upid, $sync);
952 PVE::Cluster::broadcast_tasklist($tlist);
953
954 my $res = 0;
955
956 if ($sync) {
957 my $count;
958 my $outbuf = '';
959 my $int_count = 0;
960 eval {
961 local $SIG{INT} = local $SIG{QUIT} = local $SIG{TERM} = sub {
962 # always send signal to all pgrp members
963 my $kpid = -$cpid;
964 if ($int_count < 3) {
965 kill(15, $kpid); # send TERM signal
966 } else {
967 kill(9, $kpid); # send KILL signal
968 }
969 $int_count++;
970 };
971 local $SIG{PIPE} = sub { die "broken pipe\n"; };
972
973 my $select = new IO::Select;
974 my $fh = IO::Handle->new_from_fd($psync[0], 'r');
975 $select->add($fh);
976
977 while ($select->count) {
978 my @handles = $select->can_read(1);
979 if (scalar(@handles)) {
980 my $count = sysread ($handles[0], $readbuf, 4096);
981 if (!defined ($count)) {
982 my $err = $!;
983 die "sync pipe read error: $err\n";
984 }
985 last if $count == 0; # eof
986
987 $outbuf .= $readbuf;
988 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
989 my $line = $1;
990 my $data = $2;
991 if ($data =~ m/^TASK OK$/) {
992 # skip
993 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
994 print STDERR "$1\n";
995 } else {
996 print $line;
997 }
998 if ($outfh) {
999 print $outfh $line;
1000 $outfh->flush();
1001 }
1002 }
1003 } else {
1004 # some commands daemonize without closing stdout
1005 last if !PVE::ProcFSTools::check_process_running($cpid);
1006 }
1007 }
1008 };
1009 my $err = $@;
1010
1011 POSIX::close($psync[0]);
1012
1013 if ($outbuf) { # just to be sure
1014 print $outbuf;
1015 if ($outfh) {
1016 print $outfh $outbuf;
1017 }
1018 }
1019
1020 if ($err) {
1021 $err =~ s/\n/ /mg;
1022 print STDERR "$err\n";
1023 if ($outfh) {
1024 print $outfh "TASK ERROR: $err\n";
1025 }
1026 }
1027
1028 &$kill_process_group($cpid, $pstart); # make sure it gets killed
1029
1030 close($outfh);
1031
1032 waitpid($cpid, 0);
1033 $res = $?;
1034 &$log_task_result($upid, $user, $res);
1035 }
1036
1037 return wantarray ? ($upid, $res) : $upid;
1038 }
1039
1040 1;