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