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