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