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