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