]> git.proxmox.com Git - pve-common.git/blob - src/PVE/RESTEnvironment.pm
Network: stop using ifconfig
[pve-common.git] / src / PVE / RESTEnvironment.pm
1 package PVE::RESTEnvironment;
2
3 # NOTE: you can/should provide your own specialice class, and
4 # use this a bas class (as example see PVE::RPCEnvironment).
5
6 # we use this singleton class to pass RPC related environment values
7
8 use strict;
9 use warnings;
10 use POSIX qw(:sys_wait_h EINTR);
11 use IO::Handle;
12 use IO::File;
13 use IO::Select;
14 use Fcntl qw(:flock);
15 use PVE::Exception qw(raise raise_perm_exc);
16 use PVE::SafeSyslog;
17 use PVE::Tools;
18 use PVE::INotify;
19 use PVE::ProcFSTools;
20
21
22 my $rest_env;
23
24 # save $SIG{CHLD} handler implementation.
25 # simply set $SIG{CHLD} = $worker_reaper;
26 # and register forked processes with &$register_worker(pid)
27 # Note: using $SIG{CHLD} = 'IGNORE' or $SIG{CHLD} = sub { wait (); } or ...
28 # has serious side effects, because perls built in system() and open()
29 # functions can't get the correct exit status of a child. So we cant use
30 # that (also see perlipc)
31
32 my $WORKER_PIDS;
33 my $WORKER_FLAG = 0;
34
35 my $log_task_result = sub {
36 my ($upid, $user, $status) = @_;
37
38 return if !$rest_env;
39
40 my $msg = 'successful';
41 my $pri = 'info';
42 if ($status != 0) {
43 my $ec = $status >> 8;
44 my $ic = $status & 255;
45 $msg = $ec ? "failed ($ec)" : "interrupted ($ic)";
46 $pri = 'err';
47 }
48
49 my $tlist = $rest_env->active_workers($upid);
50 $rest_env->broadcast_tasklist($tlist);
51
52 my $task;
53 foreach my $t (@$tlist) {
54 if ($t->{upid} eq $upid) {
55 $task = $t;
56 last;
57 }
58 }
59 if ($task && $task->{status}) {
60 $msg = $task->{status};
61 }
62
63 $rest_env->log_cluster_msg($pri, $user, "end task $upid $msg")
64 if $rest_env;
65 };
66
67 my $worker_reaper = sub {
68 local $!; local $?;
69 foreach my $pid (keys %$WORKER_PIDS) {
70 my $waitpid = waitpid ($pid, WNOHANG);
71 if (defined($waitpid) && ($waitpid == $pid)) {
72 my $info = $WORKER_PIDS->{$pid};
73 if ($info && $info->{upid} && $info->{user}) {
74 &$log_task_result($info->{upid}, $info->{user}, $?);
75 }
76 delete ($WORKER_PIDS->{$pid});
77 }
78 }
79 };
80
81 my $register_worker = sub {
82 my ($pid, $user, $upid) = @_;
83
84 return if !$pid;
85
86 # do not register if already finished
87 my $waitpid = waitpid ($pid, WNOHANG);
88 if (defined($waitpid) && ($waitpid == $pid)) {
89 delete ($WORKER_PIDS->{$pid});
90 return;
91 }
92
93 $WORKER_PIDS->{$pid} = {
94 user => $user,
95 upid => $upid,
96 };
97 };
98
99 # initialize environment - must be called once at program startup
100 sub init {
101 my ($class, $type, %params) = @_;
102
103 $class = ref($class) || $class;
104
105 die "already initialized" if $rest_env;
106
107 die "unknown environment type"
108 if !$type || $type !~ m/^(cli|pub|priv|ha)$/;
109
110 $SIG{CHLD} = $worker_reaper;
111
112 # environment types
113 # cli ... command started fron command line
114 # pub ... access from public server (apache)
115 # priv ... access from private server (pvedaemon)
116 # ha ... access from HA resource manager agent (rgmanager)
117
118 my $self = { type => $type };
119
120 bless $self, $class;
121
122 foreach my $p (keys %params) {
123 if ($p eq 'atfork') {
124 $self->{$p} = $params{$p};
125 } else {
126 die "unknown option '$p'";
127 }
128 }
129
130 $rest_env = $self;
131
132 my ($sysname, $nodename) = POSIX::uname();
133
134 $nodename =~ s/\..*$//; # strip domain part, if any
135
136 $self->{nodename} = $nodename;
137
138 return $self;
139 };
140
141 # convenience function for command line tools
142 sub setup_default_cli_env {
143 my ($class, $username) = @_;
144
145 $class = ref($class) || $class;
146
147 $username //= 'root@pam';
148
149 PVE::INotify::inotify_init();
150
151 my $rpcenv = $class->init('cli');
152 $rpcenv->init_request();
153 $rpcenv->set_language($ENV{LANG});
154 $rpcenv->set_user($username);
155
156 die "please run as root\n"
157 if ($username eq 'root@pam') && ($> != 0);
158 }
159
160 # get the singleton
161 sub get {
162
163 die "REST environment not initialized" if !$rest_env;
164
165 return $rest_env;
166 }
167
168 sub set_client_ip {
169 my ($self, $ip) = @_;
170
171 $self->{client_ip} = $ip;
172 }
173
174 sub get_client_ip {
175 my ($self) = @_;
176
177 return $self->{client_ip};
178 }
179
180 sub set_result_attrib {
181 my ($self, $key, $value) = @_;
182
183 $self->{result_attributes}->{$key} = $value;
184 }
185
186 sub get_result_attrib {
187 my ($self, $key) = @_;
188
189 return $self->{result_attributes}->{$key};
190 }
191
192 sub set_language {
193 my ($self, $lang) = @_;
194
195 # fixme: initialize I18N
196
197 $self->{language} = $lang;
198 }
199
200 sub get_language {
201 my ($self) = @_;
202
203 return $self->{language};
204 }
205
206 sub set_user {
207 my ($self, $user) = @_;
208
209 $self->{user} = $user;
210 }
211
212 sub get_user {
213 my ($self) = @_;
214
215 die "user name not set\n" if !$self->{user};
216
217 return $self->{user};
218 }
219
220 sub is_worker {
221 my ($class) = @_;
222
223 return $WORKER_FLAG;
224 }
225
226 # read/update list of active workers
227 # we move all finished tasks to the archive index,
228 # but keep aktive and most recent task in the active file.
229 # $nocheck ... consider $new_upid still running (avoid that
230 # we try to read the reult to early.
231 sub active_workers {
232 my ($self, $new_upid, $nocheck) = @_;
233
234 my $lkfn = "/var/log/pve/tasks/.active.lock";
235
236 my $timeout = 10;
237
238 my $code = sub {
239
240 my $tasklist = PVE::INotify::read_file('active');
241
242 my @ta;
243 my $tlist = [];
244 my $thash = {}; # only list task once
245
246 my $check_task = sub {
247 my ($task, $running) = @_;
248
249 if ($running || PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart})) {
250 push @$tlist, $task;
251 } else {
252 delete $task->{pid};
253 push @ta, $task;
254 }
255 delete $task->{pstart};
256 };
257
258 foreach my $task (@$tasklist) {
259 my $upid = $task->{upid};
260 next if $thash->{$upid};
261 $thash->{$upid} = $task;
262 &$check_task($task);
263 }
264
265 if ($new_upid && !(my $task = $thash->{$new_upid})) {
266 $task = PVE::Tools::upid_decode($new_upid);
267 $task->{upid} = $new_upid;
268 $thash->{$new_upid} = $task;
269 &$check_task($task, $nocheck);
270 }
271
272
273 @ta = sort { $b->{starttime} cmp $a->{starttime} } @ta;
274
275 my $save = defined($new_upid);
276
277 foreach my $task (@ta) {
278 next if $task->{endtime};
279 $task->{endtime} = time();
280 $task->{status} = PVE::Tools::upid_read_status($task->{upid});
281 $save = 1;
282 }
283
284 my $archive = '';
285 my @arlist = ();
286 foreach my $task (@ta) {
287 if (!$task->{saved}) {
288 $archive .= sprintf("%s %08X %s\n", $task->{upid}, $task->{endtime}, $task->{status});
289 $save = 1;
290 push @arlist, $task;
291 $task->{saved} = 1;
292 }
293 }
294
295 if ($archive) {
296 my $size = 0;
297 my $filename = "/var/log/pve/tasks/index";
298 eval {
299 my $fh = IO::File->new($filename, '>>', 0644) ||
300 die "unable to open file '$filename' - $!\n";
301 PVE::Tools::safe_print($filename, $fh, $archive);
302 $size = -s $fh;
303 close($fh) ||
304 die "unable to close file '$filename' - $!\n";
305 };
306 my $err = $@;
307 if ($err) {
308 syslog('err', $err);
309 foreach my $task (@arlist) { # mark as not saved
310 $task->{saved} = 0;
311 }
312 }
313 my $maxsize = 50000; # about 1000 entries
314 if ($size > $maxsize) {
315 rename($filename, "$filename.1");
316 }
317 }
318
319 # we try to reduce the amount of data
320 # list all running tasks and task and a few others
321 # try to limit to 25 tasks
322 my $ctime = time();
323 my $max = 25 - scalar(@$tlist);
324 foreach my $task (@ta) {
325 last if $max <= 0;
326 push @$tlist, $task;
327 $max--;
328 }
329
330 PVE::INotify::write_file('active', $tlist) if $save;
331
332 return $tlist;
333 };
334
335 my $res = PVE::Tools::lock_file($lkfn, $timeout, $code);
336 die $@ if $@;
337
338 return $res;
339 }
340
341 my $kill_process_group = sub {
342 my ($pid, $pstart) = @_;
343
344 # send kill to process group (negative pid)
345 my $kpid = -$pid;
346
347 # always send signal to all pgrp members
348 kill(15, $kpid); # send TERM signal
349
350 # give max 5 seconds to shut down
351 for (my $i = 0; $i < 5; $i++) {
352 return if !PVE::ProcFSTools::check_process_running($pid, $pstart);
353 sleep (1);
354 }
355
356 # to be sure
357 kill(9, $kpid);
358 };
359
360 sub check_worker {
361 my ($self, $upid, $killit) = @_;
362
363 my $task = PVE::Tools::upid_decode($upid);
364
365 my $running = PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart});
366
367 return 0 if !$running;
368
369 if ($killit) {
370 &$kill_process_group($task->{pid});
371 return 0;
372 }
373
374 return 1;
375 }
376
377 # start long running workers
378 # STDIN is redirected to /dev/null
379 # STDOUT,STDERR are redirected to the filename returned by upid_decode
380 # NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
381 sub fork_worker {
382 my ($self, $dtype, $id, $user, $function, $background) = @_;
383
384 $dtype = 'unknown' if !defined ($dtype);
385 $id = '' if !defined ($id);
386
387 $user = 'root@pve' if !defined ($user);
388
389 my $sync = ($self->{type} eq 'cli' && !$background) ? 1 : 0;
390
391 local $SIG{INT} =
392 local $SIG{QUIT} =
393 local $SIG{PIPE} =
394 local $SIG{TERM} = 'IGNORE';
395
396 my $starttime = time ();
397
398 my @psync = POSIX::pipe();
399 my @csync = POSIX::pipe();
400
401 my $node = $self->{nodename};
402
403 my $cpid = fork();
404 die "unable to fork worker - $!" if !defined($cpid);
405
406 my $workerpuid = $cpid ? $cpid : $$;
407
408 my $pstart = PVE::ProcFSTools::read_proc_starttime($workerpuid) ||
409 die "unable to read process start time";
410
411 my $upid = PVE::Tools::upid_encode ({
412 node => $node, pid => $workerpuid, pstart => $pstart,
413 starttime => $starttime, type => $dtype, id => $id, user => $user });
414
415 my $outfh;
416
417 if (!$cpid) { # child
418
419 $0 = "task $upid";
420 $WORKER_FLAG = 1;
421
422 $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub { die "received interrupt\n"; };
423
424 $SIG{CHLD} = $SIG{PIPE} = 'DEFAULT';
425
426 # set sess/process group - we want to be able to kill the
427 # whole process group
428 POSIX::setsid();
429
430 POSIX::close ($psync[0]);
431 POSIX::close ($csync[1]);
432
433 $outfh = $sync ? $psync[1] : undef;
434
435 eval {
436 PVE::INotify::inotify_close();
437
438 if (my $atfork = $self->{atfork}) {
439 &$atfork();
440 }
441
442 # same algorythm as used inside SA
443 # STDIN = /dev/null
444 my $fd = fileno (STDIN);
445
446 if (!$sync) {
447 close STDIN;
448 POSIX::close(0) if $fd != 0;
449
450 die "unable to redirect STDIN - $!"
451 if !open(STDIN, "</dev/null");
452
453 $outfh = PVE::Tools::upid_open($upid);
454 }
455
456
457 # redirect STDOUT
458 $fd = fileno(STDOUT);
459 close STDOUT;
460 POSIX::close (1) if $fd != 1;
461
462 die "unable to redirect STDOUT - $!"
463 if !open(STDOUT, ">&", $outfh);
464
465 STDOUT->autoflush (1);
466
467 # redirect STDERR to STDOUT
468 $fd = fileno (STDERR);
469 close STDERR;
470 POSIX::close(2) if $fd != 2;
471
472 die "unable to redirect STDERR - $!"
473 if !open(STDERR, ">&1");
474
475 STDERR->autoflush(1);
476 };
477 if (my $err = $@) {
478 my $msg = "ERROR: $err";
479 POSIX::write($psync[1], $msg, length ($msg));
480 POSIX::close($psync[1]);
481 POSIX::_exit(1);
482 kill(-9, $$);
483 }
484
485 # sync with parent (signal that we are ready)
486 if ($sync) {
487 print "$upid\n";
488 } else {
489 POSIX::write($psync[1], $upid, length ($upid));
490 POSIX::close($psync[1]);
491 }
492
493 my $readbuf = '';
494 # sync with parent (wait until parent is ready)
495 POSIX::read($csync[0], $readbuf, 4096);
496 die "parent setup error\n" if $readbuf ne 'OK';
497
498 if ($self->{type} eq 'ha') {
499 print "task started by HA resource agent\n";
500 }
501 eval { &$function($upid); };
502 my $err = $@;
503 if ($err) {
504 chomp $err;
505 $err =~ s/\n/ /mg;
506 syslog('err', $err);
507 print STDERR "TASK ERROR: $err\n";
508 POSIX::_exit(-1);
509 } else {
510 print STDERR "TASK OK\n";
511 POSIX::_exit(0);
512 }
513 kill(-9, $$);
514 }
515
516 # parent
517
518 POSIX::close ($psync[1]);
519 POSIX::close ($csync[0]);
520
521 my $readbuf = '';
522 # sync with child (wait until child starts)
523 POSIX::read($psync[0], $readbuf, 4096);
524
525 if (!$sync) {
526 POSIX::close($psync[0]);
527 &$register_worker($cpid, $user, $upid);
528 } else {
529 chomp $readbuf;
530 }
531
532 eval {
533 die "got no worker upid - start worker failed\n" if !$readbuf;
534
535 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
536 die "starting worker failed: $1\n";
537 }
538
539 if ($readbuf ne $upid) {
540 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
541 }
542
543 if ($sync) {
544 $outfh = PVE::Tools::upid_open($upid);
545 }
546 };
547 my $err = $@;
548
549 if (!$err) {
550 my $msg = 'OK';
551 POSIX::write($csync[1], $msg, length ($msg));
552 POSIX::close($csync[1]);
553
554 } else {
555 POSIX::close($csync[1]);
556 kill(-9, $cpid); # make sure it gets killed
557 die $err;
558 }
559
560 $self->log_cluster_msg('info', $user, "starting task $upid");
561
562 my $tlist = $self->active_workers($upid, $sync);
563 $self->broadcast_tasklist($tlist);
564
565 my $res = 0;
566
567 if ($sync) {
568 my $count;
569 my $outbuf = '';
570 my $int_count = 0;
571 eval {
572 local $SIG{INT} = local $SIG{QUIT} = local $SIG{TERM} = sub {
573 # always send signal to all pgrp members
574 my $kpid = -$cpid;
575 if ($int_count < 3) {
576 kill(15, $kpid); # send TERM signal
577 } else {
578 kill(9, $kpid); # send KILL signal
579 }
580 $int_count++;
581 };
582 local $SIG{PIPE} = sub { die "broken pipe\n"; };
583
584 my $select = new IO::Select;
585 my $fh = IO::Handle->new_from_fd($psync[0], 'r');
586 $select->add($fh);
587
588 while ($select->count) {
589 my @handles = $select->can_read(1);
590 if (scalar(@handles)) {
591 my $count = sysread ($handles[0], $readbuf, 4096);
592 if (!defined ($count)) {
593 my $err = $!;
594 die "sync pipe read error: $err\n";
595 }
596 last if $count == 0; # eof
597
598 $outbuf .= $readbuf;
599 while ($outbuf =~ s/^(([^\010\r\n]*)(\r|\n|(\010)+|\r\n))//s) {
600 my $line = $1;
601 my $data = $2;
602 if ($data =~ m/^TASK OK$/) {
603 # skip
604 } elsif ($data =~ m/^TASK ERROR: (.+)$/) {
605 print STDERR "$1\n";
606 } else {
607 print $line;
608 }
609 if ($outfh) {
610 print $outfh $line;
611 $outfh->flush();
612 }
613 }
614 } else {
615 # some commands daemonize without closing stdout
616 last if !PVE::ProcFSTools::check_process_running($cpid);
617 }
618 }
619 };
620 my $err = $@;
621
622 POSIX::close($psync[0]);
623
624 if ($outbuf) { # just to be sure
625 print $outbuf;
626 if ($outfh) {
627 print $outfh $outbuf;
628 }
629 }
630
631 if ($err) {
632 $err =~ s/\n/ /mg;
633 print STDERR "$err\n";
634 if ($outfh) {
635 print $outfh "TASK ERROR: $err\n";
636 }
637 }
638
639 &$kill_process_group($cpid, $pstart); # make sure it gets killed
640
641 close($outfh);
642
643 waitpid($cpid, 0);
644 $res = $?;
645 &$log_task_result($upid, $user, $res);
646 }
647
648 return wantarray ? ($upid, $res) : $upid;
649 }
650
651 # Abstract function
652
653 sub log_cluster_msg {
654 my ($self, $pri, $user, $msg) = @_;
655
656 syslog($pri, "%s", $msg);
657
658 # PVE::Cluster::log_msg($pri, $user, $msg);
659 }
660
661 sub broadcast_tasklist {
662 my ($self, $tlist) = @_;
663
664 # PVE::Cluster::broadcast_tasklist($tlist);
665 }
666
667 sub check_api2_permissions {
668 my ($self, $perm, $username, $param) = @_;
669
670 return 1 if !$username && $perm->{user} eq 'world';
671
672 raise_perm_exc("user != null") if !$username;
673
674 return 1 if $username eq 'root@pam';
675
676 raise_perm_exc('user != root@pam') if !$perm;
677
678 return 1 if $perm->{user} && $perm->{user} eq 'all';
679
680 ##return $self->exec_api2_perm_check($perm->{check}, $username, $param)
681 ##if $perm->{check};
682
683 raise_perm_exc();
684 }
685
686 # init_request - should be called before each REST/CLI request
687 sub init_request {
688 my ($self, %params) = @_;
689
690 # implement in subclass
691 }
692
693 1;