1 package PVE
::API2
::Nodes
::Nodeinfo
;
5 use POSIX
qw(LONG_MAX);
7 use Time
::Local
qw(timegm_nocheck);
8 use HTTP
::Status
qw(:constants);
14 use PVE
::Cluster
qw(cfs_read_file);
16 use PVE
::Exception
qw(raise raise_perm_exc raise_param_exc);
18 use PVE
::RPCEnvironment
;
19 use PVE
::JSONSchema
qw(get_standard_option);
20 use PVE
::AccessControl
;
26 use PVE
::HA
::Env
::PVE2
;
30 use PVE
::API2
::Subscription
;
31 use PVE
::API2
::Services
;
32 use PVE
::API2
::Network
;
35 use PVE
::API2
::Storage
::Status
;
38 use PVE
::API2
::LXC
::Status
;
39 use PVE
::API2
::VZDump
;
42 use PVE
::API2
::Firewall
::Host
;
43 use PVE
::API2
::Replication
;
44 use PVE
::API2
::Certificates
;
45 use PVE
::API2
::NodeConfig
;
46 use PVE
::API2
::Hardware
;
53 use base
qw(PVE::RESTHandler);
55 __PACKAGE__-
>register_method ({
56 subclass
=> "PVE::API2::Qemu",
60 __PACKAGE__-
>register_method ({
61 subclass
=> "PVE::API2::LXC",
65 __PACKAGE__-
>register_method ({
66 subclass
=> "PVE::API2::Ceph",
70 __PACKAGE__-
>register_method ({
71 subclass
=> "PVE::API2::VZDump",
75 __PACKAGE__-
>register_method ({
76 subclass
=> "PVE::API2::Services",
80 __PACKAGE__-
>register_method ({
81 subclass
=> "PVE::API2::Subscription",
82 path
=> 'subscription',
85 __PACKAGE__-
>register_method ({
86 subclass
=> "PVE::API2::Network",
90 __PACKAGE__-
>register_method ({
91 subclass
=> "PVE::API2::Tasks",
95 __PACKAGE__-
>register_method ({
96 subclass
=> "PVE::API2::Scan",
100 __PACKAGE__-
>register_method ({
101 subclass
=> "PVE::API2::Hardware",
106 __PACKAGE__-
>register_method ({
107 subclass
=> "PVE::API2::Storage::Status",
111 __PACKAGE__-
>register_method ({
112 subclass
=> "PVE::API2::Disks",
116 __PACKAGE__-
>register_method ({
117 subclass
=> "PVE::API2::APT",
121 __PACKAGE__-
>register_method ({
122 subclass
=> "PVE::API2::Firewall::Host",
126 __PACKAGE__-
>register_method ({
127 subclass
=> "PVE::API2::Replication",
128 path
=> 'replication',
131 __PACKAGE__-
>register_method ({
132 subclass
=> "PVE::API2::Certificates",
133 path
=> 'certificates',
137 __PACKAGE__-
>register_method ({
138 subclass
=> "PVE::API2::NodeConfig",
142 __PACKAGE__-
>register_method ({
146 permissions
=> { user
=> 'all' },
147 description
=> "Node index.",
149 additionalProperties
=> 0,
151 node
=> get_standard_option
('pve-node'),
160 links
=> [ { rel
=> 'child', href
=> "{name}" } ],
169 { name
=> 'version' },
170 { name
=> 'syslog' },
171 { name
=> 'status' },
172 { name
=> 'wakeonlan' },
173 { name
=> 'subscription' },
174 { name
=> 'report' },
176 { name
=> 'rrd' }, # fixme: remove?
177 { name
=> 'rrddata' },# fixme: remove?
178 { name
=> 'replication' },
179 { name
=> 'vncshell' },
180 { name
=> 'termproxy' },
181 { name
=> 'spiceshell' },
184 { name
=> 'services' },
186 { name
=> 'storage' },
189 { name
=> 'vzdump' },
190 { name
=> 'network' },
191 { name
=> 'aplinfo' },
192 { name
=> 'startall' },
193 { name
=> 'stopall' },
194 { name
=> 'netstat' },
195 { name
=> 'firewall' },
196 { name
=> 'certificates' },
197 { name
=> 'config' },
204 __PACKAGE__-
>register_method ({
209 permissions
=> { user
=> 'all' },
210 description
=> "API version details",
212 additionalProperties
=> 0,
214 node
=> get_standard_option
('pve-node'),
220 version
=> { type
=> 'string' },
221 release
=> { type
=> 'string' },
222 repoid
=> { type
=> 'string' },
226 my ($resp, $param) = @_;
228 return PVE
::pvecfg
::version_info
();
231 __PACKAGE__-
>register_method({
236 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
238 description
=> "Read node status",
241 additionalProperties
=> 0,
243 node
=> get_standard_option
('pve-node'),
260 my ($uptime, $idle) = PVE
::ProcFSTools
::read_proc_uptime
();
261 $res->{uptime
} = $uptime;
263 my ($avg1, $avg5, $avg15) = PVE
::ProcFSTools
::read_loadavg
();
264 $res->{loadavg
} = [ $avg1, $avg5, $avg15];
266 my ($sysname, $nodename, $release, $version, $machine) = POSIX
::uname
();
268 $res->{kversion
} = "$sysname $release $version";
270 $res->{cpuinfo
} = PVE
::ProcFSTools
::read_cpuinfo
();
272 my $stat = PVE
::ProcFSTools
::read_proc_stat
();
273 $res->{cpu
} = $stat->{cpu
};
274 $res->{wait} = $stat->{wait};
276 my $meminfo = PVE
::ProcFSTools
::read_meminfo
();
278 free
=> $meminfo->{memfree
},
279 total
=> $meminfo->{memtotal
},
280 used
=> $meminfo->{memused
},
284 shared
=> $meminfo->{memshared
},
288 free
=> $meminfo->{swapfree
},
289 total
=> $meminfo->{swaptotal
},
290 used
=> $meminfo->{swapused
},
293 $res->{pveversion
} = PVE
::pvecfg
::package() . "/" .
294 PVE
::pvecfg
::version_text
();
296 my $dinfo = df
('/', 1); # output is bytes
299 total
=> $dinfo->{blocks
},
300 avail
=> $dinfo->{bavail
},
301 used
=> $dinfo->{used
},
302 free
=> $dinfo->{blocks
} - $dinfo->{used
},
308 __PACKAGE__-
>register_method({
313 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
315 description
=> "Read tap/vm network device interface counters",
318 additionalProperties
=> 0,
320 node
=> get_standard_option
('pve-node'),
335 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
336 foreach my $dev (keys %$netdev) {
337 next if $dev !~ m/^(?:tap|veth)([1-9]\d*)i(\d+)$/;
346 in => $netdev->{$dev}->{transmit
},
347 out
=> $netdev->{$dev}->{receive
},
355 __PACKAGE__-
>register_method({
360 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
362 description
=> "Execute multiple commands in order.",
364 protected
=> 1, # avoid problems with proxy code
366 additionalProperties
=> 0,
368 node
=> get_standard_option
('pve-node'),
370 description
=> "JSON encoded array of commands.",
385 my $rpcenv = PVE
::RPCEnvironment
::get
();
386 my $user = $rpcenv->get_user();
388 my $commands = eval { decode_json
($param->{commands
}); };
390 die "commands param did not contain valid JSON: $@" if $@;
391 die "commands is not an array" if ref($commands) ne "ARRAY";
393 foreach my $cmd (@$commands) {
395 die "$cmd is not a valid command" if (ref($cmd) ne "HASH" || !$cmd->{path
} || !$cmd->{method});
399 my $path = "nodes/$param->{node}/$cmd->{path}";
402 my ($handler, $info) = PVE
::API2-
>find_handler($cmd->{method}, $path, $uri_param);
403 if (!$handler || !$info) {
404 die "no handler for '$path'\n";
407 foreach my $p (keys %{$cmd->{args
}}) {
408 raise_param_exc
({ $p => "duplicate parameter" }) if defined($uri_param->{$p});
409 $uri_param->{$p} = $cmd->{args
}->{$p};
412 # check access permissions
413 $rpcenv->check_api2_permissions($info->{permissions
}, $user, $uri_param);
417 data
=> $handler->handle($info, $uri_param),
421 my $resp = { status
=> HTTP_INTERNAL_SERVER_ERROR
};
422 if (ref($err) eq "PVE::Exception") {
423 $resp->{status
} = $err->{code
} if $err->{code
};
424 $resp->{errors
} = $err->{errors
} if $err->{errors
};
425 $resp->{message
} = $err->{msg
};
427 $resp->{message
} = $err;
437 __PACKAGE__-
>register_method({
442 check
=> ['perm', '/nodes/{node}', [ 'Sys.PowerMgmt' ]],
445 description
=> "Reboot or shutdown a node.",
448 additionalProperties
=> 0,
450 node
=> get_standard_option
('pve-node'),
452 description
=> "Specify the command.",
454 enum
=> [qw(reboot shutdown)],
458 returns
=> { type
=> "null" },
462 if ($param->{command
} eq 'reboot') {
463 system ("(sleep 2;/sbin/reboot)&");
464 } elsif ($param->{command
} eq 'shutdown') {
465 system ("(sleep 2;/sbin/poweroff)&");
471 __PACKAGE__-
>register_method({
476 check
=> ['perm', '/nodes/{node}', [ 'Sys.PowerMgmt' ]],
479 description
=> "Try to wake a node via 'wake on LAN' network packet.",
481 additionalProperties
=> 0,
483 node
=> get_standard_option
('pve-node', {
484 description
=> 'target node for wake on LAN packet',
486 my $members = PVE
::Cluster
::get_members
();
487 return [ grep { !$members->{$_}->{online
} } keys %$members ];
494 format
=> 'mac-addr',
495 description
=> 'MAC address used to assemble the WoL magic packet.',
500 my $node = $param->{node
};
502 die "'$node' is local node, cannot wake my self!\n"
503 if $node eq 'localhost' || $node eq PVE
::INotify
::nodename
();
505 PVE
::Cluster
::check_node_exists
($node);
507 my $config = PVE
::NodeConfig
::load_config
($node);
508 my $mac_addr = $config->{wakeonlan
};
509 if (!defined($mac_addr)) {
510 die "No wake on LAN MAC address defined for '$node'!\n";
514 my $packet = chr(0xff) x
6 . pack('H*', $mac_addr) x
16;
516 my $addr = gethostbyname('255.255.255.255');
517 my $port = getservbyname('discard', 'udp');
518 my $to = Socket
::pack_sockaddr_in
($port, $addr);
520 socket(my $sock, Socket
::AF_INET
, Socket
::SOCK_DGRAM
, Socket
::IPPROTO_UDP
)
521 || die "Unable to open socket: $!\n";
522 setsockopt($sock, Socket
::SOL_SOCKET
, Socket
::SO_BROADCAST
, 1)
523 || die "Unable to set socket option: $!\n";
525 send($sock, $packet, 0, $to)
526 || die "Unable to send packet: $!\n";
530 return $config->{wakeonlan
};
533 __PACKAGE__-
>register_method({
537 protected
=> 1, # fixme: can we avoid that?
539 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
541 description
=> "Read node RRD statistics (returns PNG)",
543 additionalProperties
=> 0,
545 node
=> get_standard_option
('pve-node'),
547 description
=> "Specify the time frame you are interested in.",
549 enum
=> [ 'hour', 'day', 'week', 'month', 'year' ],
552 description
=> "The list of datasources you want to display.",
553 type
=> 'string', format
=> 'pve-configid-list',
556 description
=> "The RRD consolidation function",
558 enum
=> [ 'AVERAGE', 'MAX' ],
566 filename
=> { type
=> 'string' },
572 return PVE
::Cluster
::create_rrd_graph
(
573 "pve2-node/$param->{node}", $param->{timeframe
},
574 $param->{ds
}, $param->{cf
});
578 __PACKAGE__-
>register_method({
582 protected
=> 1, # fixme: can we avoid that?
584 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
586 description
=> "Read node RRD statistics",
588 additionalProperties
=> 0,
590 node
=> get_standard_option
('pve-node'),
592 description
=> "Specify the time frame you are interested in.",
594 enum
=> [ 'hour', 'day', 'week', 'month', 'year' ],
597 description
=> "The RRD consolidation function",
599 enum
=> [ 'AVERAGE', 'MAX' ],
614 return PVE
::Cluster
::create_rrd_data
(
615 "pve2-node/$param->{node}", $param->{timeframe
}, $param->{cf
});
618 __PACKAGE__-
>register_method({
622 description
=> "Read system log",
625 check
=> ['perm', '/nodes/{node}', [ 'Sys.Syslog' ]],
629 additionalProperties
=> 0,
631 node
=> get_standard_option
('pve-node'),
644 pattern
=> '^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}(:\d{2})?)?$',
645 description
=> "Display all log since this date-time string.",
650 pattern
=> '^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}(:\d{2})?)?$',
651 description
=> "Display all log until this date-time string.",
655 description
=> "Service ID",
668 description
=> "Line number",
672 description
=> "Line text",
681 my $rpcenv = PVE
::RPCEnvironment
::get
();
682 my $user = $rpcenv->get_user();
683 my $node = $param->{node
};
686 if ($param->{service
}) {
687 my $service_aliases = {
688 'postfix' => 'postfix@-',
691 $service = $service_aliases->{$param->{service
}} // $param->{service
};
694 my ($count, $lines) = PVE
::Tools
::dump_journal
($param->{start
}, $param->{limit
},
695 $param->{since
}, $param->{until}, $service);
697 $rpcenv->set_result_attrib('total', $count);
704 __PACKAGE__-
>register_method ({
710 description
=> "Restricted to users on realm 'pam'",
711 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
713 description
=> "Creates a VNC Shell proxy.",
715 additionalProperties
=> 0,
717 node
=> get_standard_option
('pve-node'),
720 description
=> "Run 'apt-get dist-upgrade' instead of normal shell.",
727 description
=> "use websocket instead of standard vnc.",
731 description
=> "sets the width of the console in pixels.",
738 description
=> "sets the height of the console in pixels.",
746 additionalProperties
=> 0,
748 user
=> { type
=> 'string' },
749 ticket
=> { type
=> 'string' },
750 cert
=> { type
=> 'string' },
751 port
=> { type
=> 'integer' },
752 upid
=> { type
=> 'string' },
758 my $rpcenv = PVE
::RPCEnvironment
::get
();
760 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($rpcenv->get_user());
762 raise_perm_exc
("realm != pam") if $realm ne 'pam';
764 raise_perm_exc
('user != root@pam') if $param->{upgrade
} && $user ne 'root@pam';
766 my $node = $param->{node
};
768 my $authpath = "/nodes/$node";
770 my $ticket = PVE
::AccessControl
::assemble_vnc_ticket
($user, $authpath);
772 $sslcert = PVE
::Tools
::file_get_contents
("/etc/pve/pve-root-ca.pem", 8192)
775 my ($remip, $family);
777 if ($node ne PVE
::INotify
::nodename
()) {
778 ($remip, $family) = PVE
::Cluster
::remote_node_ip
($node);
780 $family = PVE
::Tools
::get_host_address_family
($node);
783 my $port = PVE
::Tools
::next_vnc_port
($family);
785 # NOTE: vncterm VNC traffic is already TLS encrypted,
786 # so we select the fastest chipher here (or 'none'?)
787 my $remcmd = $remip ?
788 ['/usr/bin/ssh', '-e', 'none', '-t', $remip] : [];
792 if ($user eq 'root@pam') {
793 if ($param->{upgrade
}) {
794 my $upgradecmd = "pveupgrade --shell";
795 $upgradecmd = PVE
::Tools
::shellquote
($upgradecmd) if $remip;
796 $shcmd = [ '/bin/bash', '-c', $upgradecmd ];
798 $shcmd = [ '/bin/login', '-f', 'root' ];
801 $shcmd = [ '/bin/login' ];
806 my $cmd = ['/usr/bin/vncterm', '-rfbport', $port,
807 '-timeout', $timeout, '-authpath', $authpath,
808 '-perm', 'Sys.Console'];
810 if ($param->{width
}) {
811 push @$cmd, '-width', $param->{width
};
814 if ($param->{height
}) {
815 push @$cmd, '-height', $param->{height
};
818 if ($param->{websocket
}) {
819 $ENV{PVE_VNC_TICKET
} = $ticket; # pass ticket to vncterm
820 push @$cmd, '-notls', '-listen', 'localhost';
823 push @$cmd, '-c', @$remcmd, @$shcmd;
828 syslog
('info', "starting vnc proxy $upid\n");
830 my $cmdstr = join (' ', @$cmd);
831 syslog
('info', "launch command: $cmdstr");
834 foreach my $k (keys %ENV) {
835 next if $k eq 'PVE_VNC_TICKET';
836 next if $k eq 'PATH' || $k eq 'TERM' || $k eq 'USER' || $k eq 'HOME' || $k eq 'LANG' || $k eq 'LANGUAGE';
841 PVE
::Tools
::run_command
($cmd, errmsg
=> "vncterm failed", keeplocale
=> 1);
844 syslog
('err', $err);
850 my $upid = $rpcenv->fork_worker('vncshell', "", $user, $realcmd);
852 PVE
::Tools
::wait_for_vnc_port
($port);
863 __PACKAGE__-
>register_method ({
869 description
=> "Restricted to users on realm 'pam'",
870 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
872 description
=> "Creates a VNC Shell proxy.",
874 additionalProperties
=> 0,
876 node
=> get_standard_option
('pve-node'),
879 description
=> "Run 'apt-get dist-upgrade' instead of normal shell.",
886 additionalProperties
=> 0,
888 user
=> { type
=> 'string' },
889 ticket
=> { type
=> 'string' },
890 port
=> { type
=> 'integer' },
891 upid
=> { type
=> 'string' },
897 my $rpcenv = PVE
::RPCEnvironment
::get
();
899 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($rpcenv->get_user());
901 raise_perm_exc
("realm != pam") if $realm ne 'pam';
903 my $node = $param->{node
};
905 my $authpath = "/nodes/$node";
907 my $ticket = PVE
::AccessControl
::assemble_vnc_ticket
($user, $authpath);
909 my ($remip, $family);
911 if ($node ne 'localhost' && $node ne PVE
::INotify
::nodename
()) {
912 ($remip, $family) = PVE
::Cluster
::remote_node_ip
($node);
914 $family = PVE
::Tools
::get_host_address_family
($node);
917 my $port = PVE
::Tools
::next_vnc_port
($family);
919 my $remcmd = $remip ?
920 ['/usr/bin/ssh', '-e', 'none', '-t', $remip , '--'] : [];
924 if ($user eq 'root@pam') {
925 if ($param->{upgrade
}) {
926 $concmd = [ '/usr/bin/pveupgrade', '--shell' ];
928 $concmd = [ '/bin/login', '-f', 'root' ];
931 $concmd = [ '/bin/login' ];
937 syslog
('info', "starting termproxy $upid\n");
939 my $cmd = ['/usr/bin/termproxy', $port, '--path', $authpath,
940 '--perm', 'Sys.Console', '--'];
941 push @$cmd, @$remcmd, @$concmd;
943 PVE
::Tools
::run_command
($cmd);
946 my $upid = $rpcenv->fork_worker('vncshell', "", $user, $realcmd);
948 PVE
::Tools
::wait_for_vnc_port
($port);
958 __PACKAGE__-
>register_method({
959 name
=> 'vncwebsocket',
960 path
=> 'vncwebsocket',
963 description
=> "Restricted to users on realm 'pam'. You also need to pass a valid ticket (vncticket).",
964 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
966 description
=> "Opens a weksocket for VNC traffic.",
968 additionalProperties
=> 0,
970 node
=> get_standard_option
('pve-node'),
972 description
=> "Ticket from previous call to vncproxy.",
977 description
=> "Port number returned by previous vncproxy call.",
987 port
=> { type
=> 'string' },
993 my $rpcenv = PVE
::RPCEnvironment
::get
();
995 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($rpcenv->get_user());
997 raise_perm_exc
("realm != pam") if $realm ne 'pam';
999 my $authpath = "/nodes/$param->{node}";
1001 PVE
::AccessControl
::verify_vnc_ticket
($param->{vncticket
}, $user, $authpath);
1003 my $port = $param->{port
};
1005 return { port
=> $port };
1008 __PACKAGE__-
>register_method ({
1009 name
=> 'spiceshell',
1010 path
=> 'spiceshell',
1015 description
=> "Restricted to users on realm 'pam'",
1016 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
1018 description
=> "Creates a SPICE shell.",
1020 additionalProperties
=> 0,
1022 node
=> get_standard_option
('pve-node'),
1023 proxy
=> get_standard_option
('spice-proxy', { optional
=> 1 }),
1026 description
=> "Run 'apt-get dist-upgrade' instead of normal shell.",
1032 returns
=> get_standard_option
('remote-viewer-config'),
1036 my $rpcenv = PVE
::RPCEnvironment
::get
();
1037 my $authuser = $rpcenv->get_user();
1039 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($authuser);
1041 raise_perm_exc
("realm != pam") if $realm ne 'pam';
1043 raise_perm_exc
('user != root@pam') if $param->{upgrade
} && $user ne 'root@pam';
1045 my $node = $param->{node
};
1046 my $proxy = $param->{proxy
};
1048 my $authpath = "/nodes/$node";
1049 my $permissions = 'Sys.Console';
1053 if ($user eq 'root@pam') {
1054 if ($param->{upgrade
}) {
1055 my $upgradecmd = "pveupgrade --shell";
1056 $shcmd = [ '/bin/bash', '-c', $upgradecmd ];
1058 $shcmd = [ '/bin/login', '-f', 'root' ];
1061 $shcmd = [ '/bin/login' ];
1064 my $title = "Shell on '$node'";
1066 return PVE
::API2Tools
::run_spiceterm
($authpath, $permissions, 0, $node, $proxy, $title, $shcmd);
1069 __PACKAGE__-
>register_method({
1074 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1076 description
=> "Read DNS settings.",
1079 additionalProperties
=> 0,
1081 node
=> get_standard_option
('pve-node'),
1086 additionalProperties
=> 0,
1089 description
=> "Search domain for host-name lookup.",
1094 description
=> 'First name server IP address.',
1099 description
=> 'Second name server IP address.',
1104 description
=> 'Third name server IP address.',
1113 my $res = PVE
::INotify
::read_file
('resolvconf');
1118 __PACKAGE__-
>register_method({
1119 name
=> 'update_dns',
1122 description
=> "Write DNS settings.",
1124 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1129 additionalProperties
=> 0,
1131 node
=> get_standard_option
('pve-node'),
1133 description
=> "Search domain for host-name lookup.",
1137 description
=> 'First name server IP address.',
1138 type
=> 'string', format
=> 'ip',
1142 description
=> 'Second name server IP address.',
1143 type
=> 'string', format
=> 'ip',
1147 description
=> 'Third name server IP address.',
1148 type
=> 'string', format
=> 'ip',
1153 returns
=> { type
=> "null" },
1157 PVE
::INotify
::update_file
('resolvconf', $param);
1162 __PACKAGE__-
>register_method({
1167 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1169 description
=> "Read server time and time zone settings.",
1172 additionalProperties
=> 0,
1174 node
=> get_standard_option
('pve-node'),
1179 additionalProperties
=> 0,
1182 description
=> "Time zone",
1186 description
=> "Seconds since 1970-01-01 00:00:00 UTC.",
1188 minimum
=> 1297163644,
1189 renderer
=> 'timestamp',
1192 description
=> "Seconds since 1970-01-01 00:00:00 (local time)",
1194 minimum
=> 1297163644,
1195 renderer
=> 'timestamp_gmt',
1203 my $ltime = timegm_nocheck
(localtime($ctime));
1205 timezone
=> PVE
::INotify
::read_file
('timezone'),
1207 localtime => $ltime,
1213 __PACKAGE__-
>register_method({
1214 name
=> 'set_timezone',
1217 description
=> "Set time zone.",
1219 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1224 additionalProperties
=> 0,
1226 node
=> get_standard_option
('pve-node'),
1228 description
=> "Time zone. The file '/usr/share/zoneinfo/zone.tab' contains the list of valid names.",
1233 returns
=> { type
=> "null" },
1237 PVE
::INotify
::write_file
('timezone', $param->{timezone
});
1242 __PACKAGE__-
>register_method({
1249 description
=> "Get list of appliances.",
1252 additionalProperties
=> 0,
1254 node
=> get_standard_option
('pve-node'),
1269 my $list = PVE
::APLInfo
::load_data
();
1271 foreach my $template (keys %{$list->{all
}}) {
1272 my $pd = $list->{all
}->{$template};
1273 next if $pd->{'package'} eq 'pve-web-news';
1280 __PACKAGE__-
>register_method({
1281 name
=> 'apl_download',
1285 check
=> ['perm', '/storage/{storage}', ['Datastore.AllocateTemplate']],
1287 description
=> "Download appliance templates.",
1291 additionalProperties
=> 0,
1293 node
=> get_standard_option
('pve-node'),
1294 storage
=> get_standard_option
('pve-storage-id', {
1295 description
=> "The storage where the template will be stored",
1296 completion
=> \
&PVE
::Storage
::complete_storage_enabled
,
1298 template
=> { type
=> 'string',
1299 description
=> "The template wich will downloaded",
1301 completion
=> \
&complete_templet_repo
,
1305 returns
=> { type
=> "string" },
1309 my $rpcenv = PVE
::RPCEnvironment
::get
();
1311 my $user = $rpcenv->get_user();
1313 my $node = $param->{node
};
1315 my $list = PVE
::APLInfo
::load_data
();
1317 my $template = $param->{template
};
1318 my $pd = $list->{all
}->{$template};
1320 raise_param_exc
({ template
=> "no such template"}) if !$pd;
1322 my $cfg = PVE
::Storage
::config
();
1323 my $scfg = PVE
::Storage
::storage_check_enabled
($cfg, $param->{storage
}, $node);
1325 die "unknown template type '$pd->{type}'\n"
1326 if !($pd->{type
} eq 'openvz' || $pd->{type
} eq 'lxc');
1328 die "storage '$param->{storage}' does not support templates\n"
1329 if !$scfg->{content
}->{vztmpl
};
1331 my $src = $pd->{location
};
1332 my $tmpldir = PVE
::Storage
::get_vztmpl_dir
($cfg, $param->{storage
});
1333 my $dest = "$tmpldir/$template";
1334 my $tmpdest = "$tmpldir/${template}.tmp.$$";
1339 print "starting template download from: $src\n";
1340 print "target file: $dest\n";
1342 my $check_hash = sub {
1343 my ($template_info, $filename, $noerr) = @_;
1349 open(my $fh, '<', $filename) or die "Can't open '$filename': $!";
1351 if (defined($template_info->{sha512sum
})) {
1352 $expected = $template_info->{sha512sum
};
1353 $digest = Digest
::SHA-
>new(512)->addfile($fh)->hexdigest;
1354 } elsif (defined($template_info->{md5sum
})) {
1356 $expected = $template_info->{md5sum
};
1357 $digest = Digest
::MD5-
>new->addfile($fh)->hexdigest;
1359 die "no expected checksum defined";
1364 die "checking hash failed - $@\n" if $@ && !$noerr;
1366 return ($digest, $digest ?
lc($digest) eq lc($expected) : 0);
1371 my ($hash, $correct) = &$check_hash($pd, $dest, 1);
1373 if ($hash && $correct) {
1374 print "file already exists $hash - no need to download\n";
1380 my $dccfg = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
1381 if ($dccfg->{http_proxy
}) {
1382 $ENV{http_proxy
} = $dccfg->{http_proxy
};
1385 my @cmd = ('/usr/bin/wget', '--progress=dot:mega', '-O', $tmpdest, $src);
1386 if (system (@cmd) != 0) {
1387 die "download failed - $!\n";
1390 my ($hash, $correct) = &$check_hash($pd, $tmpdest);
1392 die "could not calculate checksum\n" if !$hash;
1395 my $expected = $pd->{sha512sum
} // $pd->{md5sum
};
1396 die "wrong checksum: $hash != $expected\n";
1399 if (!rename($tmpdest, $dest)) {
1400 die "unable to save file - $!\n";
1412 print "download finished\n";
1415 return $rpcenv->fork_worker('download', undef, $user, $worker);
1418 __PACKAGE__-
>register_method({
1423 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1426 description
=> "Gather various systems information about a node",
1429 additionalProperties
=> 0,
1431 node
=> get_standard_option
('pve-node'),
1438 return PVE
::Report
::generate
();
1441 # returns a list of VMIDs, those can be filtered by
1442 # * current parent node
1444 # * guest is a template (default: skip)
1445 # * guest is HA manged (default: skip)
1446 my $get_filtered_vmlist = sub {
1447 my ($nodename, $vmfilter, $templates, $ha_managed) = @_;
1449 my $vmlist = PVE
::Cluster
::get_vmlist
();
1451 my $vms_allowed = {};
1452 if (defined($vmfilter)) {
1453 foreach my $vmid (PVE
::Tools
::split_list
($vmfilter)) {
1454 $vms_allowed->{$vmid} = 1;
1459 foreach my $vmid (keys %{$vmlist->{ids
}}) {
1460 next if %$vms_allowed && !$vms_allowed->{$vmid};
1462 my $d = $vmlist->{ids
}->{$vmid};
1463 next if $nodename && $d->{node
} ne $nodename;
1467 if ($d->{type
} eq 'lxc') {
1468 $class = 'PVE::LXC::Config';
1469 } elsif ($d->{type
} eq 'qemu') {
1470 $class = 'PVE::QemuConfig';
1472 die "unknown VM type '$d->{type}'\n";
1475 my $conf = $class->load_config($vmid);
1476 return if !$templates && $class->is_template($conf);
1477 return if !$ha_managed && PVE
::HA
::Config
::vm_is_ha_managed
($vmid);
1479 $res->{$vmid}->{conf
} = $conf;
1480 $res->{$vmid}->{type
} = $d->{type
};
1481 $res->{$vmid}->{class} = $class;
1489 # return all VMs which should get started/stopped on power up/down
1490 my $get_start_stop_list = sub {
1491 my ($nodename, $autostart, $vmfilter) = @_;
1493 # do not skip HA vms on force or if a specific VMID set is wanted
1494 my $include_ha_managed = defined($vmfilter) ?
1 : 0;
1496 my $vmlist = &$get_filtered_vmlist($nodename, $vmfilter, undef, $include_ha_managed);
1499 foreach my $vmid (keys %$vmlist) {
1500 my $conf = $vmlist->{$vmid}->{conf
};
1502 next if $autostart && !$conf->{onboot
};
1505 if ($conf->{startup
}) {
1506 $startup = PVE
::JSONSchema
::pve_parse_startup_order
($conf->{startup
});
1509 $startup->{order
} = LONG_MAX
if !defined($startup->{order
});
1511 $resList->{$startup->{order
}}->{$vmid} = $startup;
1512 $resList->{$startup->{order
}}->{$vmid}->{type
} = $vmlist->{$vmid}->{type
};
1518 my $remove_locks_on_startup = sub {
1519 my ($nodename) = @_;
1521 my $vmlist = &$get_filtered_vmlist($nodename, undef, undef, 1);
1523 foreach my $vmid (keys %$vmlist) {
1524 my $conf = $vmlist->{$vmid}->{conf
};
1525 my $class = $vmlist->{$vmid}->{class};
1528 if ($class->has_lock($conf, 'backup')) {
1529 $class->remove_lock($vmid, 'backup');
1530 my $msg = "removed left over backup lock from '$vmid'!";
1531 warn "$msg\n"; # prints to task log
1532 syslog
('warning', $msg);
1538 __PACKAGE__-
>register_method ({
1544 check
=> ['perm', '/', [ 'VM.PowerMgmt' ]],
1547 description
=> "Start all VMs and containers (when onboot=1).",
1549 additionalProperties
=> 0,
1551 node
=> get_standard_option
('pve-node'),
1555 description
=> "force if onboot=0.",
1558 description
=> "Only consider Guests with these IDs.",
1559 type
=> 'string', format
=> 'pve-vmid-list',
1570 my $rpcenv = PVE
::RPCEnvironment
::get
();
1571 my $authuser = $rpcenv->get_user();
1573 my $nodename = $param->{node
};
1574 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
1576 my $force = $param->{force
};
1580 $rpcenv->{type
} = 'priv'; # to start tasks in background
1582 if (!PVE
::Cluster
::check_cfs_quorum
(1)) {
1583 print "waiting for quorum ...\n";
1586 } while (!PVE
::Cluster
::check_cfs_quorum
(1));
1587 print "got quorum\n";
1590 eval { # remove backup locks, but avoid running into a scheduled backup job
1591 PVE
::Tools
::lock_file
('/var/run/vzdump.lock', 10, $remove_locks_on_startup, $nodename);
1594 my $autostart = $force ?
undef : 1;
1595 my $startList = &$get_start_stop_list($nodename, $autostart, $param->{vms
});
1597 # Note: use numeric sorting with <=>
1598 foreach my $order (sort {$a <=> $b} keys %$startList) {
1599 my $vmlist = $startList->{$order};
1601 foreach my $vmid (sort {$a <=> $b} keys %$vmlist) {
1602 my $d = $vmlist->{$vmid};
1604 PVE
::Cluster
::check_cfs_quorum
(); # abort when we loose quorum
1607 my $default_delay = 0;
1611 if ($d->{type
} eq 'lxc') {
1613 return if PVE
::LXC
::check_running
($vmid);
1614 print STDERR
"Starting CT $vmid\n";
1615 $upid = PVE
::API2
::LXC
::Status-
>vm_start({node
=> $nodename, vmid
=> $vmid });
1616 } elsif ($d->{type
} eq 'qemu') {
1618 $default_delay = 3; # to reduce load
1619 return if PVE
::QemuServer
::check_running
($vmid, 1);
1620 print STDERR
"Starting VM $vmid\n";
1621 $upid = PVE
::API2
::Qemu-
>vm_start({node
=> $nodename, vmid
=> $vmid });
1623 die "unknown VM type '$d->{type}'\n";
1626 my $res = PVE
::Tools
::upid_decode
($upid);
1627 while (PVE
::ProcFSTools
::check_process_running
($res->{pid
})) {
1631 my $status = PVE
::Tools
::upid_read_status
($upid);
1632 if ($status eq 'OK') {
1633 # use default delay to reduce load
1634 my $delay = defined($d->{up
}) ?
int($d->{up
}) : $default_delay;
1636 print STDERR
"Waiting for $delay seconds (startup delay)\n" if $d->{up
};
1637 for (my $i = 0; $i < $delay; $i++) {
1642 print STDERR
"Starting $typeText $vmid failed: $status\n";
1651 return $rpcenv->fork_worker('startall', undef, $authuser, $code);
1654 my $create_stop_worker = sub {
1655 my ($nodename, $type, $vmid, $down_timeout) = @_;
1658 if ($type eq 'lxc') {
1659 return if !PVE
::LXC
::check_running
($vmid);
1660 my $timeout = defined($down_timeout) ?
int($down_timeout) : 60;
1661 print STDERR
"Stopping CT $vmid (timeout = $timeout seconds)\n";
1662 $upid = PVE
::API2
::LXC
::Status-
>vm_shutdown({node
=> $nodename, vmid
=> $vmid,
1663 timeout
=> $timeout, forceStop
=> 1 });
1664 } elsif ($type eq 'qemu') {
1665 return if !PVE
::QemuServer
::check_running
($vmid, 1);
1666 my $timeout = defined($down_timeout) ?
int($down_timeout) : 60*3;
1667 print STDERR
"Stopping VM $vmid (timeout = $timeout seconds)\n";
1668 $upid = PVE
::API2
::Qemu-
>vm_shutdown({node
=> $nodename, vmid
=> $vmid,
1669 timeout
=> $timeout, forceStop
=> 1 });
1671 die "unknown VM type '$type'\n";
1677 __PACKAGE__-
>register_method ({
1683 check
=> ['perm', '/', [ 'VM.PowerMgmt' ]],
1686 description
=> "Stop all VMs and Containers.",
1688 additionalProperties
=> 0,
1690 node
=> get_standard_option
('pve-node'),
1692 description
=> "Only consider Guests with these IDs.",
1693 type
=> 'string', format
=> 'pve-vmid-list',
1704 my $rpcenv = PVE
::RPCEnvironment
::get
();
1705 my $authuser = $rpcenv->get_user();
1707 my $nodename = $param->{node
};
1708 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
1712 $rpcenv->{type
} = 'priv'; # to start tasks in background
1714 my $stopList = &$get_start_stop_list($nodename, undef, $param->{vms
});
1716 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
1717 my $datacenterconfig = cfs_read_file
('datacenter.cfg');
1718 # if not set by user spawn max cpu count number of workers
1719 my $maxWorkers = $datacenterconfig->{max_workers
} || $cpuinfo->{cpus
};
1721 foreach my $order (sort {$b <=> $a} keys %$stopList) {
1722 my $vmlist = $stopList->{$order};
1725 my $finish_worker = sub {
1727 my $d = $workers->{$pid};
1729 delete $workers->{$pid};
1731 syslog
('info', "end task $d->{upid}");
1734 foreach my $vmid (sort {$b <=> $a} keys %$vmlist) {
1735 my $d = $vmlist->{$vmid};
1737 eval { $upid = &$create_stop_worker($nodename, $d->{type
}, $vmid, $d->{down
}); };
1741 my $res = PVE
::Tools
::upid_decode
($upid, 1);
1744 my $pid = $res->{pid
};
1746 $workers->{$pid} = { type
=> $d->{type
}, upid
=> $upid, vmid
=> $vmid };
1747 while (scalar(keys %$workers) >= $maxWorkers) {
1748 foreach my $p (keys %$workers) {
1749 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
1750 &$finish_worker($p);
1756 while (scalar(keys %$workers)) {
1757 foreach my $p (keys %$workers) {
1758 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
1759 &$finish_worker($p);
1766 syslog
('info', "all VMs and CTs stopped");
1771 return $rpcenv->fork_worker('stopall', undef, $authuser, $code);
1774 my $create_migrate_worker = sub {
1775 my ($nodename, $type, $vmid, $target) = @_;
1778 if ($type eq 'lxc') {
1779 my $online = PVE
::LXC
::check_running
($vmid) ?
1 : 0;
1780 print STDERR
"Migrating CT $vmid\n";
1781 $upid = PVE
::API2
::LXC-
>migrate_vm({node
=> $nodename, vmid
=> $vmid, target
=> $target,
1782 online
=> $online });
1783 } elsif ($type eq 'qemu') {
1784 my $online = PVE
::QemuServer
::check_running
($vmid, 1) ?
1 : 0;
1785 print STDERR
"Migrating VM $vmid\n";
1786 $upid = PVE
::API2
::Qemu-
>migrate_vm({node
=> $nodename, vmid
=> $vmid, target
=> $target,
1787 online
=> $online });
1789 die "unknown VM type '$type'\n";
1792 my $res = PVE
::Tools
::upid_decode
($upid);
1797 __PACKAGE__-
>register_method ({
1798 name
=> 'migrateall',
1799 path
=> 'migrateall',
1804 check
=> ['perm', '/', [ 'VM.Migrate' ]],
1806 description
=> "Migrate all VMs and Containers.",
1808 additionalProperties
=> 0,
1810 node
=> get_standard_option
('pve-node'),
1811 target
=> get_standard_option
('pve-node', { description
=> "Target node." }),
1813 description
=> "Maximal number of parallel migration job." .
1814 " If not set use 'max_workers' from datacenter.cfg," .
1815 " one of both must be set!",
1821 description
=> "Only consider Guests with these IDs.",
1822 type
=> 'string', format
=> 'pve-vmid-list',
1833 my $rpcenv = PVE
::RPCEnvironment
::get
();
1834 my $authuser = $rpcenv->get_user();
1836 my $nodename = $param->{node
};
1837 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
1839 my $target = $param->{target
};
1840 raise_param_exc
({ target
=> "target is local node."}) if $target eq $nodename;
1842 PVE
::Cluster
::check_cfs_quorum
();
1844 PVE
::Cluster
::check_node_exists
($target);
1846 my $datacenterconfig = cfs_read_file
('datacenter.cfg');
1847 # prefer parameter over datacenter cfg settings
1848 my $maxWorkers = $param->{maxworkers
} || $datacenterconfig->{max_workers
} ||
1849 die "either 'maxworkers' parameter or max_workers in datacenter.cfg must be set!\n";
1852 $rpcenv->{type
} = 'priv'; # to start tasks in background
1854 my $vmlist = &$get_filtered_vmlist($nodename, $param->{vms
}, 1, 1);
1857 foreach my $vmid (sort keys %$vmlist) {
1858 my $d = $vmlist->{$vmid};
1860 eval { $pid = &$create_migrate_worker($nodename, $d->{type
}, $vmid, $target); };
1864 $workers->{$pid} = 1;
1865 while (scalar(keys %$workers) >= $maxWorkers) {
1866 foreach my $p (keys %$workers) {
1867 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
1868 delete $workers->{$p};
1874 while (scalar(keys %$workers)) {
1875 foreach my $p (keys %$workers) {
1876 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
1877 delete $workers->{$p};
1885 return $rpcenv->fork_worker('migrateall', undef, $authuser, $code);
1889 __PACKAGE__-
>register_method ({
1890 name
=> 'get_etc_hosts',
1896 check
=> ['perm', '/', [ 'Sys.Audit' ]],
1898 description
=> "Get the content of /etc/hosts.",
1900 additionalProperties
=> 0,
1902 node
=> get_standard_option
('pve-node'),
1908 digest
=> get_standard_option
('pve-config-digest'),
1911 description
=> 'The content of /etc/hosts.'
1918 return PVE
::INotify
::read_file
('etchosts');
1922 __PACKAGE__-
>register_method ({
1923 name
=> 'write_etc_hosts',
1929 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1931 description
=> "Write /etc/hosts.",
1933 additionalProperties
=> 0,
1935 node
=> get_standard_option
('pve-node'),
1936 digest
=> get_standard_option
('pve-config-digest'),
1939 description
=> 'The target content of /etc/hosts.'
1949 PVE
::Tools
::lock_file
('/var/lock/pve-etchosts.lck', undef, sub{
1950 if ($param->{digest
}) {
1951 my $hosts = PVE
::INotify
::read_file
('etchosts');
1952 PVE
::Tools
::assert_if_modified
($hosts->{digest
}, $param->{digest
});
1954 PVE
::INotify
::write_file
('etchosts', $param->{data
});
1961 # bash completion helper
1963 sub complete_templet_repo
{
1964 my ($cmdname, $pname, $cvalue) = @_;
1966 my $repo = PVE
::APLInfo
::load_data
();
1968 foreach my $templ (keys %{$repo->{all
}}) {
1969 next if $templ !~ m/^$cvalue/;
1976 package PVE
::API2
::Nodes
;
1981 use PVE
::SafeSyslog
;
1983 use PVE
::RESTHandler
;
1984 use PVE
::RPCEnvironment
;
1986 use PVE
::JSONSchema
qw(get_standard_option);
1988 use base
qw(PVE::RESTHandler);
1990 __PACKAGE__-
>register_method ({
1991 subclass
=> "PVE::API2::Nodes::Nodeinfo",
1995 __PACKAGE__-
>register_method ({
1999 permissions
=> { user
=> 'all' },
2000 description
=> "Cluster node index.",
2002 additionalProperties
=> 0,
2010 node
=> get_standard_option
('pve-node'),
2012 description
=> "Node status.",
2014 enum
=> ['unknown', 'online', 'offline'],
2017 description
=> "CPU utilization.",
2020 renderer
=> 'fraction_as_percentage',
2023 description
=> "Number of available CPUs.",
2028 description
=> "Used memory in bytes.",
2031 renderer
=> 'bytes',
2034 description
=> "Number of available memory in bytes.",
2037 renderer
=> 'bytes',
2040 description
=> "Support level.",
2045 description
=> "Node uptime in seconds.",
2048 renderer
=> 'duration',
2050 ssl_fingerprint
=> {
2051 description
=> "The SSL fingerprint for the node certificate.",
2057 links
=> [ { rel
=> 'child', href
=> "{node}" } ],
2062 my $clinfo = PVE
::Cluster
::get_clinfo
();
2065 my $nodelist = PVE
::Cluster
::get_nodelist
();
2066 my $members = PVE
::Cluster
::get_members
();
2067 my $rrd = PVE
::Cluster
::rrd_dump
();
2069 foreach my $node (@$nodelist) {
2070 my $entry = PVE
::API2Tools
::extract_node_stats
($node, $members, $rrd);
2071 $entry->{ssl_fingerprint
} = PVE
::Cluster
::get_node_fingerprint
($node);