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