]> git.proxmox.com Git - pve-common.git/blame - src/PVE/RESTEnvironment.pm
add u2f challenge accessors to RESTEnvironment
[pve-common.git] / src / PVE / RESTEnvironment.pm
CommitLineData
d9072797
DM
1package 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
8use strict;
9use warnings;
10use POSIX qw(:sys_wait_h EINTR);
11use IO::Handle;
12use IO::File;
13use IO::Select;
14use Fcntl qw(:flock);
15use PVE::Exception qw(raise raise_perm_exc);
16use PVE::SafeSyslog;
17use PVE::Tools;
18use PVE::INotify;
19use PVE::ProcFSTools;
20
21
22my $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()
fb3a1b29 29# functions can't get the correct exit status of a child. So we can't use
d9072797
DM
30# that (also see perlipc)
31
32my $WORKER_PIDS;
33my $WORKER_FLAG = 0;
34
35my $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);
9a42d8a2
TL
50 eval { $rest_env->broadcast_tasklist($tlist); };
51 syslog('err', $@) if $@;
d9072797
DM
52
53 my $task;
54 foreach my $t (@$tlist) {
55 if ($t->{upid} eq $upid) {
56 $task = $t;
57 last;
58 }
59 }
60 if ($task && $task->{status}) {
61 $msg = $task->{status};
62 }
63
ad7962b4 64 $rest_env->log_cluster_msg($pri, $user, "end task $upid $msg");
d9072797
DM
65};
66
67my $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
81my $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
100sub 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
142sub 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
161sub get {
162
163 die "REST environment not initialized" if !$rest_env;
164
165 return $rest_env;
166}
167
168sub set_client_ip {
169 my ($self, $ip) = @_;
170
171 $self->{client_ip} = $ip;
172}
173
174sub get_client_ip {
175 my ($self) = @_;
176
177 return $self->{client_ip};
178}
179
180sub set_result_attrib {
181 my ($self, $key, $value) = @_;
182
183 $self->{result_attributes}->{$key} = $value;
184}
185
186sub get_result_attrib {
187 my ($self, $key) = @_;
188
189 return $self->{result_attributes}->{$key};
190}
191
192sub set_language {
193 my ($self, $lang) = @_;
194
195 # fixme: initialize I18N
196
197 $self->{language} = $lang;
198}
199
200sub get_language {
201 my ($self) = @_;
202
203 return $self->{language};
204}
205
206sub set_user {
207 my ($self, $user) = @_;
208
209 $self->{user} = $user;
210}
211
212sub get_user {
8e6019b1 213 my ($self, $noerr) = @_;
d9072797 214
8e6019b1 215 return $self->{user} if defined($self->{user}) || $noerr;
d9072797 216
8e6019b1 217 die "user name not set\n";
d9072797
DM
218}
219
61aca93a
WB
220sub set_u2f_challenge {
221 my ($self, $challenge) = @_;
222
223 $self->{u2f_challenge} = $challenge;
224}
225
226sub get_u2f_challenge {
227 my ($self, $noerr) = @_;
228
229 return $self->{u2f_challenge} if defined($self->{u2f_challenge}) || $noerr;
230
231 die "no active u2f challenge\n";
232}
233
d9072797
DM
234sub is_worker {
235 my ($class) = @_;
236
237 return $WORKER_FLAG;
238}
239
240# read/update list of active workers
241# we move all finished tasks to the archive index,
242# but keep aktive and most recent task in the active file.
243# $nocheck ... consider $new_upid still running (avoid that
244# we try to read the reult to early.
245sub active_workers {
246 my ($self, $new_upid, $nocheck) = @_;
247
248 my $lkfn = "/var/log/pve/tasks/.active.lock";
249
250 my $timeout = 10;
251
252 my $code = sub {
253
254 my $tasklist = PVE::INotify::read_file('active');
255
256 my @ta;
257 my $tlist = [];
258 my $thash = {}; # only list task once
259
260 my $check_task = sub {
261 my ($task, $running) = @_;
262
263 if ($running || PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart})) {
264 push @$tlist, $task;
265 } else {
266 delete $task->{pid};
267 push @ta, $task;
268 }
269 delete $task->{pstart};
270 };
271
272 foreach my $task (@$tasklist) {
273 my $upid = $task->{upid};
274 next if $thash->{$upid};
275 $thash->{$upid} = $task;
276 &$check_task($task);
277 }
278
279 if ($new_upid && !(my $task = $thash->{$new_upid})) {
280 $task = PVE::Tools::upid_decode($new_upid);
281 $task->{upid} = $new_upid;
282 $thash->{$new_upid} = $task;
283 &$check_task($task, $nocheck);
284 }
285
286
8733bb80 287 @ta = sort { $b->{starttime} <=> $a->{starttime} } @ta;
d9072797
DM
288
289 my $save = defined($new_upid);
290
291 foreach my $task (@ta) {
292 next if $task->{endtime};
293 $task->{endtime} = time();
294 $task->{status} = PVE::Tools::upid_read_status($task->{upid});
295 $save = 1;
296 }
297
298 my $archive = '';
299 my @arlist = ();
300 foreach my $task (@ta) {
301 if (!$task->{saved}) {
302 $archive .= sprintf("%s %08X %s\n", $task->{upid}, $task->{endtime}, $task->{status});
303 $save = 1;
304 push @arlist, $task;
305 $task->{saved} = 1;
306 }
307 }
308
309 if ($archive) {
310 my $size = 0;
311 my $filename = "/var/log/pve/tasks/index";
312 eval {
313 my $fh = IO::File->new($filename, '>>', 0644) ||
314 die "unable to open file '$filename' - $!\n";
315 PVE::Tools::safe_print($filename, $fh, $archive);
316 $size = -s $fh;
317 close($fh) ||
318 die "unable to close file '$filename' - $!\n";
319 };
320 my $err = $@;
321 if ($err) {
322 syslog('err', $err);
323 foreach my $task (@arlist) { # mark as not saved
324 $task->{saved} = 0;
325 }
326 }
327 my $maxsize = 50000; # about 1000 entries
328 if ($size > $maxsize) {
329 rename($filename, "$filename.1");
330 }
331 }
332
333 # we try to reduce the amount of data
334 # list all running tasks and task and a few others
335 # try to limit to 25 tasks
d9072797
DM
336 my $max = 25 - scalar(@$tlist);
337 foreach my $task (@ta) {
338 last if $max <= 0;
339 push @$tlist, $task;
340 $max--;
341 }
342
343 PVE::INotify::write_file('active', $tlist) if $save;
344
345 return $tlist;
346 };
347
348 my $res = PVE::Tools::lock_file($lkfn, $timeout, $code);
349 die $@ if $@;
350
351 return $res;
352}
353
354my $kill_process_group = sub {
355 my ($pid, $pstart) = @_;
356
357 # send kill to process group (negative pid)
358 my $kpid = -$pid;
359
360 # always send signal to all pgrp members
361 kill(15, $kpid); # send TERM signal
362
363 # give max 5 seconds to shut down
364 for (my $i = 0; $i < 5; $i++) {
365 return if !PVE::ProcFSTools::check_process_running($pid, $pstart);
366 sleep (1);
367 }
368
369 # to be sure
370 kill(9, $kpid);
371};
372
373sub check_worker {
a313fe73 374 my ($self, $upid, $killit) = @_;
d9072797
DM
375
376 my $task = PVE::Tools::upid_decode($upid);
377
378 my $running = PVE::ProcFSTools::check_process_running($task->{pid}, $task->{pstart});
379
380 return 0 if !$running;
381
382 if ($killit) {
383 &$kill_process_group($task->{pid});
384 return 0;
385 }
386
387 return 1;
388}
389
3e2da216
TL
390# acts almost as tee: writes an output both to STDOUT and a task log,
391# we differ as we're worker aware and look also at the childs control pipe,
392# so we know if the function could be executed successfully or not.
393my $tee_worker = sub {
394 my ($childfd, $ctrlfd, $taskfh, $cpid) = @_;
395
396 eval {
397 my $int_count = 0;
398 local $SIG{INT} = local $SIG{QUIT} = local $SIG{TERM} = sub {
399 # always send signal to all pgrp members
400 my $kpid = -$cpid;
401 if ($int_count < 3) {
402 kill(15, $kpid); # send TERM signal
403 } else {
404 kill(9, $kpid); # send KILL signal
405 }
406 $int_count++;
407 };
408 local $SIG{PIPE} = sub { die "broken pipe\n"; };
409
410 my $select = new IO::Select;
411 my $fh = IO::Handle->new_from_fd($childfd, 'r');
412 $select->add($fh);
413
414 my $readbuf = '';
415 my $count;
416 while ($select->count) {
417 my @handles = $select->can_read(1);
418 if (scalar(@handles)) {
419 my $count = sysread ($handles[0], $readbuf, 4096);
420 if (!defined ($count)) {
421 my $err = $!;
422 die "sync pipe read error: $err\n";
423 }
424 last if $count == 0; # eof
425
426 print $readbuf;
427 select->flush();
428
429 print $taskfh $readbuf;
430 $taskfh->flush();
431 } else {
432 # some commands daemonize without closing stdout
433 last if !PVE::ProcFSTools::check_process_running($cpid);
434 }
435 }
436
437 # get status (error or OK)
438 POSIX::read($ctrlfd, $readbuf, 4096);
439 if ($readbuf =~ m/^TASK OK\n?$/) {
440 # skip printing to stdout
441 print $taskfh $readbuf;
442 } elsif ($readbuf =~ m/^TASK ERROR: (.*)\n?$/) {
443 print STDERR "$1\n";
444 print $taskfh "\n$readbuf"; # ensure start on new line for webUI
445 } else {
446 die "got unexpected control message: $readbuf\n";
447 }
448 $taskfh->flush();
449 };
450 my $err = $@;
451
452 POSIX::close($childfd);
453 POSIX::close($ctrlfd);
454
455 if ($err) {
456 $err =~ s/\n/ /mg;
457 print STDERR "$err\n";
458 print $taskfh "TASK ERROR: $err\n";
459 }
460};
461
d9072797
DM
462# start long running workers
463# STDIN is redirected to /dev/null
464# STDOUT,STDERR are redirected to the filename returned by upid_decode
465# NOTE: we simulate running in foreground if ($self->{type} eq 'cli')
466sub fork_worker {
467 my ($self, $dtype, $id, $user, $function, $background) = @_;
468
469 $dtype = 'unknown' if !defined ($dtype);
470 $id = '' if !defined ($id);
471
472 $user = 'root@pve' if !defined ($user);
473
474 my $sync = ($self->{type} eq 'cli' && !$background) ? 1 : 0;
475
476 local $SIG{INT} =
477 local $SIG{QUIT} =
478 local $SIG{PIPE} =
479 local $SIG{TERM} = 'IGNORE';
480
481 my $starttime = time ();
482
483 my @psync = POSIX::pipe();
484 my @csync = POSIX::pipe();
ed52a843 485 my @ctrlfd = POSIX::pipe() if $sync;
d9072797
DM
486
487 my $node = $self->{nodename};
488
489 my $cpid = fork();
490 die "unable to fork worker - $!" if !defined($cpid);
491
492 my $workerpuid = $cpid ? $cpid : $$;
493
494 my $pstart = PVE::ProcFSTools::read_proc_starttime($workerpuid) ||
495 die "unable to read process start time";
496
497 my $upid = PVE::Tools::upid_encode ({
498 node => $node, pid => $workerpuid, pstart => $pstart,
499 starttime => $starttime, type => $dtype, id => $id, user => $user });
500
501 my $outfh;
502
503 if (!$cpid) { # child
504
505 $0 = "task $upid";
506 $WORKER_FLAG = 1;
507
508 $SIG{INT} = $SIG{QUIT} = $SIG{TERM} = sub { die "received interrupt\n"; };
509
510 $SIG{CHLD} = $SIG{PIPE} = 'DEFAULT';
e97f807c 511 $SIG{TTOU} = 'IGNORE';
d9072797 512
6a09f096 513 my $ppgid;
aea06195 514 # set session/process group allows to kill the process group
e97f807c 515 if ($sync && -t STDIN) {
aea06195
TL
516 # some sync'ed workers operate on the tty but setsid sessions lose
517 # the tty, so just create a new pgroup and give it the tty
6a09f096 518 $ppgid = POSIX::getpgrp() or die "failed to get old pgid: $!\n";
4c99c559 519 POSIX::setpgid(0, 0) or die "failed to setpgid: $!\n";
e97f807c
SI
520 POSIX::tcsetpgrp(fileno(STDIN), $$) or die "failed to tcsetpgrp: $!\n";
521 } else {
522 POSIX::setsid();
523 }
d9072797
DM
524
525 POSIX::close ($psync[0]);
ed52a843 526 POSIX::close ($ctrlfd[0]) if $sync;
d9072797
DM
527 POSIX::close ($csync[1]);
528
529 $outfh = $sync ? $psync[1] : undef;
ed52a843 530 my $resfh = $sync ? $ctrlfd[1] : undef;
d9072797
DM
531
532 eval {
533 PVE::INotify::inotify_close();
534
535 if (my $atfork = $self->{atfork}) {
536 &$atfork();
537 }
538
fb3a1b29 539 # same algorithm as used inside SA
d9072797
DM
540 # STDIN = /dev/null
541 my $fd = fileno (STDIN);
542
543 if (!$sync) {
544 close STDIN;
545 POSIX::close(0) if $fd != 0;
546
547 die "unable to redirect STDIN - $!"
548 if !open(STDIN, "</dev/null");
549
550 $outfh = PVE::Tools::upid_open($upid);
4d9f4d62 551 $resfh = fileno($outfh);
d9072797
DM
552 }
553
554
555 # redirect STDOUT
556 $fd = fileno(STDOUT);
557 close STDOUT;
558 POSIX::close (1) if $fd != 1;
559
560 die "unable to redirect STDOUT - $!"
561 if !open(STDOUT, ">&", $outfh);
562
563 STDOUT->autoflush (1);
564
565 # redirect STDERR to STDOUT
566 $fd = fileno (STDERR);
567 close STDERR;
568 POSIX::close(2) if $fd != 2;
569
570 die "unable to redirect STDERR - $!"
571 if !open(STDERR, ">&1");
572
573 STDERR->autoflush(1);
574 };
575 if (my $err = $@) {
576 my $msg = "ERROR: $err";
577 POSIX::write($psync[1], $msg, length ($msg));
578 POSIX::close($psync[1]);
579 POSIX::_exit(1);
580 kill(-9, $$);
581 }
582
583 # sync with parent (signal that we are ready)
95109cc4
TL
584 POSIX::write($psync[1], $upid, length ($upid));
585 POSIX::close($psync[1]) if !$sync; # don't need output pipe if async
d9072797 586
2311859b
WB
587 eval {
588 my $readbuf = '';
589 # sync with parent (wait until parent is ready)
590 POSIX::read($csync[0], $readbuf, 4096);
591 die "parent setup error\n" if $readbuf ne 'OK';
d9072797 592
2311859b
WB
593 if ($self->{type} eq 'ha') {
594 print "task started by HA resource agent\n";
595 }
596 &$function($upid);
597 };
edbb302e 598 my ($msg, $exitcode);
d9072797
DM
599 my $err = $@;
600 if ($err) {
601 chomp $err;
602 $err =~ s/\n/ /mg;
603 syslog('err', $err);
edbb302e
SI
604 $msg = "TASK ERROR: $err\n";
605 $exitcode = -1;
d9072797 606 } else {
edbb302e
SI
607 $msg = "TASK OK\n";
608 $exitcode = 0;
d9072797 609 }
edbb302e 610 POSIX::write($resfh, $msg, length($msg));
6a09f096
SI
611
612 if ($sync) {
613 POSIX::close($resfh);
614 if ( -t STDIN) {
615 POSIX::tcsetpgrp(fileno(STDIN), $ppgid) or
616 die "failed to tcsetpgrp to parent: $!\n";
617 }
618 }
edbb302e 619 POSIX::_exit($exitcode);
a609b2f7 620 kill(-9, $$); # not really needed, just to be sure
d9072797
DM
621 }
622
623 # parent
624
625 POSIX::close ($psync[1]);
ed52a843 626 POSIX::close ($ctrlfd[1]) if $sync;
d9072797
DM
627 POSIX::close ($csync[0]);
628
629 my $readbuf = '';
630 # sync with child (wait until child starts)
631 POSIX::read($psync[0], $readbuf, 4096);
632
633 if (!$sync) {
634 POSIX::close($psync[0]);
635 &$register_worker($cpid, $user, $upid);
636 } else {
637 chomp $readbuf;
638 }
639
640 eval {
641 die "got no worker upid - start worker failed\n" if !$readbuf;
642
643 if ($readbuf =~ m/^ERROR:\s*(.+)$/m) {
644 die "starting worker failed: $1\n";
645 }
646
647 if ($readbuf ne $upid) {
648 die "got strange worker upid ('$readbuf' != '$upid') - start worker failed\n";
649 }
650
651 if ($sync) {
652 $outfh = PVE::Tools::upid_open($upid);
653 }
654 };
655 my $err = $@;
656
657 if (!$err) {
658 my $msg = 'OK';
659 POSIX::write($csync[1], $msg, length ($msg));
660 POSIX::close($csync[1]);
661
662 } else {
663 POSIX::close($csync[1]);
664 kill(-9, $cpid); # make sure it gets killed
665 die $err;
666 }
667
668 $self->log_cluster_msg('info', $user, "starting task $upid");
669
670 my $tlist = $self->active_workers($upid, $sync);
9a42d8a2
TL
671 eval { $self->broadcast_tasklist($tlist); };
672 syslog('err', $@) if $@;
d9072797
DM
673
674 my $res = 0;
675
676 if ($sync) {
ed52a843 677
3e2da216 678 $tee_worker->($psync[0], $ctrlfd[0], $outfh, $cpid);
d9072797
DM
679
680 &$kill_process_group($cpid, $pstart); # make sure it gets killed
681
682 close($outfh);
683
684 waitpid($cpid, 0);
685 $res = $?;
686 &$log_task_result($upid, $user, $res);
687 }
688
689 return wantarray ? ($upid, $res) : $upid;
690}
691
692# Abstract function
693
694sub log_cluster_msg {
695 my ($self, $pri, $user, $msg) = @_;
696
697 syslog($pri, "%s", $msg);
698
699 # PVE::Cluster::log_msg($pri, $user, $msg);
700}
701
702sub broadcast_tasklist {
703 my ($self, $tlist) = @_;
704
705 # PVE::Cluster::broadcast_tasklist($tlist);
706}
707
708sub check_api2_permissions {
709 my ($self, $perm, $username, $param) = @_;
710
711 return 1 if !$username && $perm->{user} eq 'world';
712
713 raise_perm_exc("user != null") if !$username;
714
715 return 1 if $username eq 'root@pam';
716
717 raise_perm_exc('user != root@pam') if !$perm;
718
719 return 1 if $perm->{user} && $perm->{user} eq 'all';
720
721 ##return $self->exec_api2_perm_check($perm->{check}, $username, $param)
722 ##if $perm->{check};
723
724 raise_perm_exc();
725}
726
727# init_request - should be called before each REST/CLI request
728sub init_request {
729 my ($self, %params) = @_;
730
dc9c3ffa
DM
731 $self->{result_attributes} = {}
732
733 # if you nedd more, implement in subclass
d9072797
DM
734}
735
7361;