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