1 package PVE
::API2
::Nodes
::Nodeinfo
;
9 use HTTP
::Status
qw(:constants);
11 use POSIX
qw(LONG_MAX);
12 use Time
::Local
qw(timegm_nocheck);
18 use PVE
::AccessControl
;
19 use PVE
::Cluster
qw(cfs_read_file);
20 use PVE
::DataCenterConfig
;
21 use PVE
::Exception
qw(raise raise_perm_exc raise_param_exc);
24 use PVE
::HA
::Env
::PVE2
;
26 use PVE
::JSONSchema
qw(get_standard_option);
32 use PVE
::RESTEnvironment
qw(log_warn);
34 use PVE
::RPCEnvironment
;
39 use PVE
::Tools
qw(file_get_contents);
43 use PVE
::API2
::Capabilities
;
45 use PVE
::API2
::Certificates
;
47 use PVE
::API2
::Firewall
::Host
;
48 use PVE
::API2
::Hardware
;
49 use PVE
::API2
::LXC
::Status
;
51 use PVE
::API2
::Network
;
52 use PVE
::API2
::NodeConfig
;
53 use PVE
::API2
::Qemu
::CPU
;
55 use PVE
::API2
::Replication
;
56 use PVE
::API2
::Services
;
57 use PVE
::API2
::Storage
::Scan
;
58 use PVE
::API2
::Storage
::Status
;
59 use PVE
::API2
::Subscription
;
61 use PVE
::API2
::VZDump
;
65 require PVE
::API2
::Network
::SDN
::Zones
::Status
;
69 use base
qw(PVE::RESTHandler);
71 my $verify_command_item_desc = {
72 description
=> "An array of objects describing endpoints, methods and arguments.",
78 description
=> "A relative path to an API endpoint on this node.",
83 description
=> "A method related to the API endpoint (GET, POST etc.).",
85 pattern
=> "(GET|POST|PUT|DELETE)",
89 description
=> "A set of parameter names and their values.",
97 PVE
::JSONSchema
::register_format
('pve-command-batch', \
&verify_command_batch
);
98 sub verify_command_batch
{
99 my ($value, $noerr) = @_;
100 my $commands = eval { decode_json
($value); };
102 return if $noerr && $@;
103 die "commands param did not contain valid JSON: $@" if $@;
105 eval { PVE
::JSONSchema
::validate
($commands, $verify_command_item_desc) };
107 return $commands if !$@;
110 die "commands is not a valid array of commands: $@";
113 __PACKAGE__-
>register_method ({
114 subclass
=> "PVE::API2::Qemu",
118 __PACKAGE__-
>register_method ({
119 subclass
=> "PVE::API2::LXC",
123 __PACKAGE__-
>register_method ({
124 subclass
=> "PVE::API2::Ceph",
128 __PACKAGE__-
>register_method ({
129 subclass
=> "PVE::API2::VZDump",
133 __PACKAGE__-
>register_method ({
134 subclass
=> "PVE::API2::Services",
138 __PACKAGE__-
>register_method ({
139 subclass
=> "PVE::API2::Subscription",
140 path
=> 'subscription',
143 __PACKAGE__-
>register_method ({
144 subclass
=> "PVE::API2::Network",
148 __PACKAGE__-
>register_method ({
149 subclass
=> "PVE::API2::Tasks",
153 __PACKAGE__-
>register_method ({
154 subclass
=> "PVE::API2::Storage::Scan",
158 __PACKAGE__-
>register_method ({
159 subclass
=> "PVE::API2::Hardware",
163 __PACKAGE__-
>register_method ({
164 subclass
=> "PVE::API2::Capabilities",
165 path
=> 'capabilities',
168 __PACKAGE__-
>register_method ({
169 subclass
=> "PVE::API2::Storage::Status",
173 __PACKAGE__-
>register_method ({
174 subclass
=> "PVE::API2::Disks",
178 __PACKAGE__-
>register_method ({
179 subclass
=> "PVE::API2::APT",
183 __PACKAGE__-
>register_method ({
184 subclass
=> "PVE::API2::Firewall::Host",
188 __PACKAGE__-
>register_method ({
189 subclass
=> "PVE::API2::Replication",
190 path
=> 'replication',
193 __PACKAGE__-
>register_method ({
194 subclass
=> "PVE::API2::Certificates",
195 path
=> 'certificates',
199 __PACKAGE__-
>register_method ({
200 subclass
=> "PVE::API2::NodeConfig",
205 __PACKAGE__-
>register_method ({
206 subclass
=> "PVE::API2::Network::SDN::Zones::Status",
210 __PACKAGE__-
>register_method ({
214 permissions
=> { user
=> 'all' },
215 description
=> "SDN index.",
217 additionalProperties
=> 0,
219 node
=> get_standard_option
('pve-node'),
228 links
=> [ { rel
=> 'child', href
=> "{name}" } ],
240 __PACKAGE__-
>register_method ({
244 permissions
=> { user
=> 'all' },
245 description
=> "Node index.",
247 additionalProperties
=> 0,
249 node
=> get_standard_option
('pve-node'),
258 links
=> [ { rel
=> 'child', href
=> "{name}" } ],
264 { name
=> 'aplinfo' },
266 { name
=> 'capabilities' },
268 { name
=> 'certificates' },
269 { name
=> 'config' },
272 { name
=> 'firewall' },
273 { name
=> 'hardware' },
275 { name
=> 'journal' },
277 { name
=> 'migrateall' },
278 { name
=> 'netstat' },
279 { name
=> 'network' },
281 { name
=> 'query-url-metadata' },
282 { name
=> 'replication' },
283 { name
=> 'report' },
284 { name
=> 'rrd' }, # fixme: remove?
285 { name
=> 'rrddata' },# fixme: remove?
287 { name
=> 'services' },
288 { name
=> 'spiceshell' },
289 { name
=> 'startall' },
290 { name
=> 'status' },
291 { name
=> 'stopall' },
292 { name
=> 'storage' },
293 { name
=> 'subscription' },
294 { name
=> 'suspendall' },
295 { name
=> 'syslog' },
297 { name
=> 'termproxy' },
299 { name
=> 'version' },
300 { name
=> 'vncshell' },
301 { name
=> 'vzdump' },
302 { name
=> 'wakeonlan' },
305 push @$result, { name
=> 'sdn' } if $have_sdn;
310 __PACKAGE__-
>register_method ({
315 permissions
=> { user
=> 'all' },
316 description
=> "API version details",
318 additionalProperties
=> 0,
320 node
=> get_standard_option
('pve-node'),
328 description
=> 'The current installed pve-manager package version',
332 description
=> 'The current installed Proxmox VE Release',
336 description
=> 'The short git commit hash ID from which this version was build',
341 my ($resp, $param) = @_;
343 return PVE
::pvecfg
::version_info
();
346 my sub get_current_kernel_info
{
347 my ($sysname, $nodename, $release, $version, $machine) = POSIX
::uname
();
349 my $kernel_version_string = "$sysname $release $version"; # for legacy compat
350 my $current_kernel = {
356 return ($current_kernel, $kernel_version_string);
359 my $boot_mode_info_cache;
360 my sub get_boot_mode_info
{
361 return $boot_mode_info_cache if defined($boot_mode_info_cache);
363 my $is_efi_booted = -d
"/sys/firmware/efi";
365 $boot_mode_info_cache = {
366 mode
=> $is_efi_booted ?
'efi' : 'legacy-bios',
369 my $efi_var = "/sys/firmware/efi/efivars/SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c";
371 if ($is_efi_booted && -e
$efi_var) {
372 my $efi_var_sec_boot_entry = eval { file_get_contents
($efi_var) };
374 warn "Failed to read secure boot state: $@\n";
376 my @secureboot = unpack("CCCCC", $efi_var_sec_boot_entry);
377 $boot_mode_info_cache->{secureboot
} = $secureboot[4] == 1 ?
1 : 0;
380 return $boot_mode_info_cache;
383 __PACKAGE__-
>register_method({
388 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
390 description
=> "Read node status",
393 additionalProperties
=> 0,
395 node
=> get_standard_option
('pve-node'),
400 additionalProperties
=> 1,
402 # TODO: document remaing ones
404 description
=> "Meta-information about the boot mode.",
408 description
=> 'Through which firmware the system got booted.',
410 enum
=> [qw(efi legacy-bios)],
413 description
=> 'System is booted in secure mode, only applicable for the "efi" mode.',
419 'current-kernel' => {
420 description
=> "The uptime of the system in seconds.",
424 description
=> 'OS kernel name (e.g., "Linux")',
428 description
=> 'OS kernel release (e.g., "6.8.0")',
432 description
=> 'OS kernel version with build info',
436 description
=> 'Hardware (architecture) type',
451 my ($uptime, $idle) = PVE
::ProcFSTools
::read_proc_uptime
();
452 $res->{uptime
} = $uptime;
454 my ($avg1, $avg5, $avg15) = PVE
::ProcFSTools
::read_loadavg
();
455 $res->{loadavg
} = [ $avg1, $avg5, $avg15];
457 my ($current_kernel_info, $kversion_string) = get_current_kernel_info
();
458 $res->{kversion
} = $kversion_string;
459 $res->{'current-kernel'} = $current_kernel_info;
461 $res->{'boot-info'} = get_boot_mode_info
();
463 $res->{cpuinfo
} = PVE
::ProcFSTools
::read_cpuinfo
();
465 my $stat = PVE
::ProcFSTools
::read_proc_stat
();
466 $res->{cpu
} = $stat->{cpu
};
467 $res->{wait} = $stat->{wait};
469 my $meminfo = PVE
::ProcFSTools
::read_meminfo
();
471 free
=> $meminfo->{memfree
},
472 total
=> $meminfo->{memtotal
},
473 used
=> $meminfo->{memused
},
477 shared
=> $meminfo->{memshared
},
481 free
=> $meminfo->{swapfree
},
482 total
=> $meminfo->{swaptotal
},
483 used
=> $meminfo->{swapused
},
486 $res->{pveversion
} = PVE
::pvecfg
::package() . "/" .
487 PVE
::pvecfg
::version_text
();
489 my $dinfo = df
('/', 1); # output is bytes
492 total
=> $dinfo->{blocks
},
493 avail
=> $dinfo->{bavail
},
494 used
=> $dinfo->{used
},
495 free
=> $dinfo->{blocks
} - $dinfo->{used
},
501 __PACKAGE__-
>register_method({
506 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
508 description
=> "Read tap/vm network device interface counters",
511 additionalProperties
=> 0,
513 node
=> get_standard_option
('pve-node'),
528 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
529 foreach my $dev (sort keys %$netdev) {
530 next if $dev !~ m/^(?:tap|veth)([1-9]\d*)i(\d+)$/;
531 my ($vmid, $netid) = ($1, $2);
536 in => $netdev->{$dev}->{transmit
},
537 out
=> $netdev->{$dev}->{receive
},
544 __PACKAGE__-
>register_method({
548 description
=> "Execute multiple commands in order, root only.",
550 protected
=> 1, # avoid problems with proxy code
552 additionalProperties
=> 0,
554 node
=> get_standard_option
('pve-node'),
556 description
=> "JSON encoded array of commands.",
558 verbose_description
=> "JSON encoded array of commands, where each command is an object with the following properties:\n"
559 . PVE
::RESTHandler
::dump_properties
($verify_command_item_desc->{items
}->{properties
}, 'full'),
560 format
=> "pve-command-batch",
575 my $rpcenv = PVE
::RPCEnvironment
::get
();
576 my $user = $rpcenv->get_user();
577 # just parse the json again, it should already be validated
578 my $commands = eval { decode_json
($param->{commands
}); };
580 foreach my $cmd (@$commands) {
584 my $path = "nodes/$param->{node}/$cmd->{path}";
587 my ($handler, $info) = PVE
::API2-
>find_handler($cmd->{method}, $path, $uri_param);
588 if (!$handler || !$info) {
589 die "no handler for '$path'\n";
592 foreach my $p (keys %{$cmd->{args
}}) {
593 raise_param_exc
({ $p => "duplicate parameter" }) if defined($uri_param->{$p});
594 $uri_param->{$p} = $cmd->{args
}->{$p};
597 # check access permissions
598 $rpcenv->check_api2_permissions($info->{permissions
}, $user, $uri_param);
602 data
=> $handler->handle($info, $uri_param),
606 my $resp = { status
=> HTTP_INTERNAL_SERVER_ERROR
};
607 if (ref($err) eq "PVE::Exception") {
608 $resp->{status
} = $err->{code
} if $err->{code
};
609 $resp->{errors
} = $err->{errors
} if $err->{errors
};
610 $resp->{message
} = $err->{msg
};
612 $resp->{message
} = $err;
622 __PACKAGE__-
>register_method({
627 check
=> ['perm', '/nodes/{node}', [ 'Sys.PowerMgmt' ]],
630 description
=> "Reboot or shutdown a node.",
633 additionalProperties
=> 0,
635 node
=> get_standard_option
('pve-node'),
637 description
=> "Specify the command.",
639 enum
=> [qw(reboot shutdown)],
643 returns
=> { type
=> "null" },
647 if ($param->{command
} eq 'reboot') {
648 system ("(sleep 2;/sbin/reboot)&");
649 } elsif ($param->{command
} eq 'shutdown') {
650 system ("(sleep 2;/sbin/poweroff)&");
656 __PACKAGE__-
>register_method({
661 check
=> ['perm', '/nodes/{node}', [ 'Sys.PowerMgmt' ]],
664 description
=> "Try to wake a node via 'wake on LAN' network packet.",
666 additionalProperties
=> 0,
668 node
=> get_standard_option
('pve-node', {
669 description
=> 'target node for wake on LAN packet',
671 my $members = PVE
::Cluster
::get_members
();
672 return [ grep { !$members->{$_}->{online
} } keys %$members ];
679 format
=> 'mac-addr',
680 description
=> 'MAC address used to assemble the WoL magic packet.',
685 my $node = $param->{node
};
686 my $local_node = PVE
::INotify
::nodename
();
688 die "'$node' is local node, cannot wake my self!\n"
689 if $node eq 'localhost' || $node eq $local_node;
691 PVE
::Cluster
::check_node_exists
($node);
693 my $config = PVE
::NodeConfig
::load_config
($node);
694 my $wol_config = PVE
::NodeConfig
::get_wakeonlan_config
($config);
695 my $mac_addr = $wol_config->{mac
};
696 if (!defined($mac_addr)) {
697 die "No wake on LAN MAC address defined for '$node'!\n";
700 my $local_config = PVE
::NodeConfig
::load_config
($local_node);
701 my $local_wol_config = PVE
::NodeConfig
::get_wakeonlan_config
($local_config);
702 my $bind_iface = $local_wol_config->{'bind-interface'};
703 my $broadcast_addr = $local_wol_config->{'broadcast-address'} // '255.255.255.255';
706 my $packet = chr(0xff) x
6 . pack('H*', $mac_addr) x
16;
708 my $addr = gethostbyname($broadcast_addr);
709 my $port = getservbyname('discard', 'udp');
710 my $to = Socket
::pack_sockaddr_in
($port, $addr);
712 socket(my $sock, Socket
::AF_INET
, Socket
::SOCK_DGRAM
, Socket
::IPPROTO_UDP
)
713 || die "Unable to open socket: $!\n";
714 setsockopt($sock, Socket
::SOL_SOCKET
, Socket
::SO_BROADCAST
, 1)
715 || die "Unable to set socket option: $!\n";
717 if (defined($bind_iface)) {
718 # Null terminated interface name
719 my $bind_iface_raw = pack('Z*', $bind_iface);
720 setsockopt($sock, Socket
::SOL_SOCKET
, Socket
::SO_BINDTODEVICE
, $bind_iface_raw)
721 || die "Unable to bind socket to interface '$bind_iface': $!\n";
724 send($sock, $packet, 0, $to)
725 || die "Unable to send packet: $!\n";
729 return $wol_config->{mac
};
732 __PACKAGE__-
>register_method({
736 protected
=> 1, # fixme: can we avoid that?
738 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
740 description
=> "Read node RRD statistics (returns PNG)",
742 additionalProperties
=> 0,
744 node
=> get_standard_option
('pve-node'),
746 description
=> "Specify the time frame you are interested in.",
748 enum
=> [ 'hour', 'day', 'week', 'month', 'year' ],
751 description
=> "The list of datasources you want to display.",
752 type
=> 'string', format
=> 'pve-configid-list',
755 description
=> "The RRD consolidation function",
757 enum
=> [ 'AVERAGE', 'MAX' ],
765 filename
=> { type
=> 'string' },
771 return PVE
::RRD
::create_rrd_graph
(
772 "pve2-node/$param->{node}", $param->{timeframe
},
773 $param->{ds
}, $param->{cf
});
777 __PACKAGE__-
>register_method({
781 protected
=> 1, # fixme: can we avoid that?
783 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
785 description
=> "Read node RRD statistics",
787 additionalProperties
=> 0,
789 node
=> get_standard_option
('pve-node'),
791 description
=> "Specify the time frame you are interested in.",
793 enum
=> [ 'hour', 'day', 'week', 'month', 'year' ],
796 description
=> "The RRD consolidation function",
798 enum
=> [ 'AVERAGE', 'MAX' ],
813 return PVE
::RRD
::create_rrd_data
(
814 "pve2-node/$param->{node}", $param->{timeframe
}, $param->{cf
});
817 __PACKAGE__-
>register_method({
821 description
=> "Read system log",
824 check
=> ['perm', '/nodes/{node}', [ 'Sys.Syslog' ]],
828 additionalProperties
=> 0,
830 node
=> get_standard_option
('pve-node'),
843 pattern
=> '^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}(:\d{2})?)?$',
844 description
=> "Display all log since this date-time string.",
849 pattern
=> '^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}(:\d{2})?)?$',
850 description
=> "Display all log until this date-time string.",
854 description
=> "Service ID",
867 description
=> "Line number",
871 description
=> "Line text",
880 my $rpcenv = PVE
::RPCEnvironment
::get
();
881 my $user = $rpcenv->get_user();
882 my $node = $param->{node
};
885 if ($param->{service
}) {
886 my $service_aliases = {
887 'postfix' => 'postfix@-',
890 $service = $service_aliases->{$param->{service
}} // $param->{service
};
893 my ($count, $lines) = PVE
::Tools
::dump_journal
($param->{start
}, $param->{limit
},
894 $param->{since
}, $param->{until}, $service);
896 $rpcenv->set_result_attrib('total', $count);
901 __PACKAGE__-
>register_method({
905 description
=> "Read Journal",
908 check
=> ['perm', '/nodes/{node}', [ 'Sys.Syslog' ]],
912 additionalProperties
=> 0,
914 node
=> get_standard_option
('pve-node'),
918 description
=> "Display all log since this UNIX epoch. Conflicts with 'startcursor'.",
924 description
=> "Display all log until this UNIX epoch. Conflicts with 'endcursor'.",
928 description
=> "Limit to the last X lines. Conflicts with a range.",
934 description
=> "Start after the given Cursor. Conflicts with 'since'",
939 description
=> "End before the given Cursor. Conflicts with 'until'",
954 my $rpcenv = PVE
::RPCEnvironment
::get
();
955 my $user = $rpcenv->get_user();
957 my $cmd = ["/usr/bin/mini-journalreader", "-j"];
958 push @$cmd, '-n', $param->{lastentries
} if $param->{lastentries
};
959 push @$cmd, '-b', $param->{since
} if $param->{since
};
960 push @$cmd, '-e', $param->{until} if $param->{until};
961 push @$cmd, '-f', PVE
::Tools
::shellquote
($param->{startcursor
}) if $param->{startcursor
};
962 push @$cmd, '-t', PVE
::Tools
::shellquote
($param->{endcursor
}) if $param->{endcursor
};
963 push @$cmd, ' | gzip ';
965 open(my $fh, "-|", join(' ', @$cmd))
966 or die "could not start mini-journalreader";
972 'content-type' => 'application/json',
973 'content-encoding' => 'gzip',
980 my $shell_cmd_map = {
982 cmd
=> [ '/bin/login', '-f', 'root' ],
985 cmd
=> [ '/usr/bin/pveupgrade', '--shell' ],
988 cmd
=> [ '/usr/bin/pveceph', 'install' ],
993 sub get_shell_command
{
994 my ($user, $shellcmd, $args) = @_;
997 if ($user eq 'root@pam') {
998 if (defined($shellcmd) && exists($shell_cmd_map->{$shellcmd})) {
999 my $def = $shell_cmd_map->{$shellcmd};
1000 $cmd = [ @{$def->{cmd
}} ]; # clone
1001 if (defined($args) && $def->{allow_args
}) {
1002 push @$cmd, split("\0", $args);
1005 $cmd = [ '/bin/login', '-f', 'root' ];
1008 # non-root must always login for now, we do not have a superuser role!
1009 $cmd = [ '/bin/login' ];
1014 my $get_vnc_connection_info = sub {
1017 my $remote_cmd = [];
1019 my ($remip, $family);
1020 if ($node ne 'localhost' && $node ne PVE
::INotify
::nodename
()) {
1021 ($remip, $family) = PVE
::Cluster
::remote_node_ip
($node);
1022 $remote_cmd = ['/usr/bin/ssh', '-e', 'none', '-t', $remip , '--'];
1024 $family = PVE
::Tools
::get_host_address_family
($node);
1026 my $port = PVE
::Tools
::next_vnc_port
($family);
1028 return ($port, $remote_cmd);
1031 __PACKAGE__-
>register_method ({
1037 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
1039 description
=> "Creates a VNC Shell proxy.",
1041 additionalProperties
=> 0,
1043 node
=> get_standard_option
('pve-node'),
1046 description
=> "Run specific command or default to login (requires 'root\@pam')",
1047 enum
=> [keys %$shell_cmd_map],
1053 description
=> "Add parameters to a command. Encoded as null terminated strings.",
1061 description
=> "use websocket instead of standard vnc.",
1065 description
=> "sets the width of the console in pixels.",
1072 description
=> "sets the height of the console in pixels.",
1080 additionalProperties
=> 0,
1082 user
=> { type
=> 'string' },
1083 ticket
=> { type
=> 'string' },
1084 cert
=> { type
=> 'string' },
1085 port
=> { type
=> 'integer' },
1086 upid
=> { type
=> 'string' },
1092 my $rpcenv = PVE
::RPCEnvironment
::get
();
1093 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($rpcenv->get_user());
1096 if (defined($param->{cmd
}) && $param->{cmd
} ne 'login' && $user ne 'root@pam') {
1097 raise_perm_exc
('user != root@pam');
1100 my $node = $param->{node
};
1102 my $authpath = "/nodes/$node";
1103 my $ticket = PVE
::AccessControl
::assemble_vnc_ticket
($user, $authpath);
1105 $sslcert = PVE
::Tools
::file_get_contents
("/etc/pve/pve-root-ca.pem", 8192)
1108 my ($port, $remcmd) = $get_vnc_connection_info->($node);
1110 my $shcmd = get_shell_command
($user, $param->{cmd
}, $param->{'cmd-opts'});
1114 my $cmd = ['/usr/bin/vncterm',
1116 '-timeout', $timeout,
1117 '-authpath', $authpath,
1118 '-perm', 'Sys.Console',
1121 push @$cmd, '-width', $param->{width
} if $param->{width
};
1122 push @$cmd, '-height', $param->{height
} if $param->{height
};
1124 if ($param->{websocket
}) {
1125 $ENV{PVE_VNC_TICKET
} = $ticket; # pass ticket to vncterm
1126 push @$cmd, '-notls', '-listen', 'localhost';
1129 push @$cmd, '-c', @$remcmd, @$shcmd;
1134 syslog
('info', "starting vnc proxy $upid\n");
1136 my $cmdstr = join (' ', @$cmd);
1137 syslog
('info', "launch command: $cmdstr");
1140 foreach my $k (keys %ENV) {
1141 next if $k eq 'PVE_VNC_TICKET';
1142 next if $k eq 'PATH' || $k eq 'TERM' || $k eq 'USER' || $k eq 'HOME' || $k eq 'LANG' || $k eq 'LANGUAGE';
1147 PVE
::Tools
::run_command
($cmd, errmsg
=> "vncterm failed", keeplocale
=> 1);
1150 syslog
('err', $err);
1156 my $upid = $rpcenv->fork_worker('vncshell', "", $user, $realcmd);
1158 PVE
::Tools
::wait_for_vnc_port
($port);
1169 __PACKAGE__-
>register_method ({
1170 name
=> 'termproxy',
1171 path
=> 'termproxy',
1175 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
1177 description
=> "Creates a VNC Shell proxy.",
1179 additionalProperties
=> 0,
1181 node
=> get_standard_option
('pve-node'),
1184 description
=> "Run specific command or default to login (requires 'root\@pam')",
1185 enum
=> [keys %$shell_cmd_map],
1191 description
=> "Add parameters to a command. Encoded as null terminated strings.",
1199 additionalProperties
=> 0,
1201 user
=> { type
=> 'string' },
1202 ticket
=> { type
=> 'string' },
1203 port
=> { type
=> 'integer' },
1204 upid
=> { type
=> 'string' },
1210 my $rpcenv = PVE
::RPCEnvironment
::get
();
1211 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($rpcenv->get_user());
1213 my $node = $param->{node
};
1214 my $authpath = "/nodes/$node";
1215 my $ticket = PVE
::AccessControl
::assemble_vnc_ticket
($user, $authpath);
1217 my ($port, $remcmd) = $get_vnc_connection_info->($node);
1219 my $shcmd = get_shell_command
($user, $param->{cmd
}, $param->{'cmd-opts'});
1224 syslog
('info', "starting termproxy $upid\n");
1227 '/usr/bin/termproxy',
1229 '--path', $authpath,
1230 '--perm', 'Sys.Console',
1233 push @$cmd, @$remcmd, @$shcmd;
1235 PVE
::Tools
::run_command
($cmd);
1237 my $upid = $rpcenv->fork_worker('vncshell', "", $user, $realcmd);
1239 PVE
::Tools
::wait_for_vnc_port
($port);
1249 __PACKAGE__-
>register_method({
1250 name
=> 'vncwebsocket',
1251 path
=> 'vncwebsocket',
1254 description
=> "You also need to pass a valid ticket (vncticket).",
1255 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
1257 description
=> "Opens a websocket for VNC traffic.",
1259 additionalProperties
=> 0,
1261 node
=> get_standard_option
('pve-node'),
1263 description
=> "Ticket from previous call to vncproxy.",
1268 description
=> "Port number returned by previous vncproxy call.",
1278 port
=> { type
=> 'string' },
1284 my $rpcenv = PVE
::RPCEnvironment
::get
();
1286 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($rpcenv->get_user());
1288 my $authpath = "/nodes/$param->{node}";
1290 PVE
::AccessControl
::verify_vnc_ticket
($param->{vncticket
}, $user, $authpath);
1292 my $port = $param->{port
};
1294 return { port
=> $port };
1297 __PACKAGE__-
>register_method ({
1298 name
=> 'spiceshell',
1299 path
=> 'spiceshell',
1304 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
1306 description
=> "Creates a SPICE shell.",
1308 additionalProperties
=> 0,
1310 node
=> get_standard_option
('pve-node'),
1311 proxy
=> get_standard_option
('spice-proxy', { optional
=> 1 }),
1314 description
=> "Run specific command or default to login (requires 'root\@pam')",
1315 enum
=> [keys %$shell_cmd_map],
1321 description
=> "Add parameters to a command. Encoded as null terminated strings.",
1328 returns
=> get_standard_option
('remote-viewer-config'),
1332 my $rpcenv = PVE
::RPCEnvironment
::get
();
1333 my $authuser = $rpcenv->get_user();
1335 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($authuser);
1338 if (defined($param->{cmd
}) && $param->{cmd
} ne 'login' && $user ne 'root@pam') {
1339 raise_perm_exc
('user != root@pam');
1342 my $node = $param->{node
};
1343 my $proxy = $param->{proxy
};
1345 my $authpath = "/nodes/$node";
1346 my $permissions = 'Sys.Console';
1348 my $shcmd = get_shell_command
($user, $param->{cmd
}, $param->{'cmd-opts'});
1350 my $title = "Shell on '$node'";
1352 return PVE
::API2Tools
::run_spiceterm
($authpath, $permissions, 0, $node, $proxy, $title, $shcmd);
1355 __PACKAGE__-
>register_method({
1360 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1362 description
=> "Read DNS settings.",
1365 additionalProperties
=> 0,
1367 node
=> get_standard_option
('pve-node'),
1372 additionalProperties
=> 0,
1375 description
=> "Search domain for host-name lookup.",
1380 description
=> 'First name server IP address.',
1385 description
=> 'Second name server IP address.',
1390 description
=> 'Third name server IP address.',
1399 my $res = PVE
::INotify
::read_file
('resolvconf');
1404 __PACKAGE__-
>register_method({
1405 name
=> 'update_dns',
1408 description
=> "Write DNS settings.",
1410 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1415 additionalProperties
=> 0,
1417 node
=> get_standard_option
('pve-node'),
1419 description
=> "Search domain for host-name lookup.",
1423 description
=> 'First name server IP address.',
1424 type
=> 'string', format
=> 'ip',
1428 description
=> 'Second name server IP address.',
1429 type
=> 'string', format
=> 'ip',
1433 description
=> 'Third name server IP address.',
1434 type
=> 'string', format
=> 'ip',
1439 returns
=> { type
=> "null" },
1443 PVE
::INotify
::update_file
('resolvconf', $param);
1448 __PACKAGE__-
>register_method({
1453 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1455 description
=> "Read server time and time zone settings.",
1458 additionalProperties
=> 0,
1460 node
=> get_standard_option
('pve-node'),
1465 additionalProperties
=> 0,
1468 description
=> "Time zone",
1472 description
=> "Seconds since 1970-01-01 00:00:00 UTC.",
1474 minimum
=> 1297163644,
1475 renderer
=> 'timestamp',
1478 description
=> "Seconds since 1970-01-01 00:00:00 (local time)",
1480 minimum
=> 1297163644,
1481 renderer
=> 'timestamp_gmt',
1489 my $ltime = timegm_nocheck
(localtime($ctime));
1491 timezone
=> PVE
::INotify
::read_file
('timezone'),
1493 localtime => $ltime,
1499 __PACKAGE__-
>register_method({
1500 name
=> 'set_timezone',
1503 description
=> "Set time zone.",
1505 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1510 additionalProperties
=> 0,
1512 node
=> get_standard_option
('pve-node'),
1514 description
=> "Time zone. The file '/usr/share/zoneinfo/zone.tab' contains the list of valid names.",
1519 returns
=> { type
=> "null" },
1523 PVE
::INotify
::write_file
('timezone', $param->{timezone
});
1528 __PACKAGE__-
>register_method({
1535 description
=> "Get list of appliances.",
1538 additionalProperties
=> 0,
1540 node
=> get_standard_option
('pve-node'),
1553 my $list = PVE
::APLInfo
::load_data
();
1556 for my $appliance (values %{$list->{all
}}) {
1557 next if $appliance->{'package'} eq 'pve-web-news';
1558 push @$res, $appliance;
1564 __PACKAGE__-
>register_method({
1565 name
=> 'apl_download',
1569 check
=> ['perm', '/storage/{storage}', ['Datastore.AllocateTemplate']],
1571 description
=> "Download appliance templates.",
1575 additionalProperties
=> 0,
1577 node
=> get_standard_option
('pve-node'),
1578 storage
=> get_standard_option
('pve-storage-id', {
1579 description
=> "The storage where the template will be stored",
1580 completion
=> \
&PVE
::Storage
::complete_storage_enabled
,
1584 description
=> "The template which will downloaded",
1586 completion
=> \
&complete_templet_repo
,
1590 returns
=> { type
=> "string" },
1594 my $rpcenv = PVE
::RPCEnvironment
::get
();
1595 my $user = $rpcenv->get_user();
1597 my $node = $param->{node
};
1598 my $template = $param->{template
};
1600 my $list = PVE
::APLInfo
::load_data
();
1601 my $appliance = $list->{all
}->{$template};
1602 raise_param_exc
({ template
=> "no such template"}) if !$appliance;
1604 my $cfg = PVE
::Storage
::config
();
1605 my $scfg = PVE
::Storage
::storage_check_enabled
($cfg, $param->{storage
}, $node);
1607 die "unknown template type '$appliance->{type}'\n"
1608 if !($appliance->{type
} eq 'openvz' || $appliance->{type
} eq 'lxc');
1610 die "storage '$param->{storage}' does not support templates\n"
1611 if !$scfg->{content
}->{vztmpl
};
1613 my $tmpldir = PVE
::Storage
::get_vztmpl_dir
($cfg, $param->{storage
});
1616 my $dccfg = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
1618 PVE
::Tools
::download_file_from_url
("$tmpldir/$template", $appliance->{location
}, {
1620 sha512sum
=> $appliance->{sha512sum
},
1621 md5sum
=> $appliance->{md5sum
},
1622 http_proxy
=> $dccfg->{http_proxy
},
1626 my $upid = $rpcenv->fork_worker('download', $template, $user, $worker);
1631 __PACKAGE__-
>register_method({
1632 name
=> 'query_url_metadata',
1633 path
=> 'query-url-metadata',
1635 description
=> "Query metadata of an URL: file size, file name and mime type.",
1639 ['perm', '/', [ 'Sys.Audit', 'Sys.Modify' ]],
1640 ['perm', '/nodes/{node}', [ 'Sys.AccessNetwork' ]],
1644 additionalProperties
=> 0,
1646 node
=> get_standard_option
('pve-node'),
1648 description
=> "The URL to query the metadata from.",
1650 pattern
=> 'https?://.*',
1652 'verify-certificates' => {
1653 description
=> "If false, no SSL/TLS certificates will be verified.",
1669 renderer
=> 'bytes',
1681 my $url = $param->{url
};
1683 my $ua = LWP
::UserAgent-
>new();
1684 $ua->agent("Proxmox VE");
1686 my $dccfg = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
1687 if ($dccfg->{http_proxy
}) {
1688 $ua->proxy('http', $dccfg->{http_proxy
});
1691 my $verify = $param->{'verify-certificates'} // 1;
1694 verify_hostname
=> 0,
1695 SSL_verify_mode
=> IO
::Socket
::SSL
::SSL_VERIFY_NONE
,
1699 my $req = HTTP
::Request-
>new(HEAD
=> $url);
1700 my $res = $ua->request($req);
1702 die "invalid server response: '" . $res->status_line() . "'\n" if ($res->code() != 200);
1704 my $size = $res->header("Content-Length");
1705 my $disposition = $res->header("Content-Disposition");
1706 my $type = $res->header("Content-Type");
1710 if ($disposition && ($disposition =~ m/filename="([^"]*)"/ || $disposition =~ m/filename=([^;]*)/)) {
1712 } elsif ($url =~ m!^[^?]+/([^?/]*)(?:\?.*)?$!) {
1716 # Content-Type: text/html; charset=utf-8
1717 if ($type && $type =~ m/^([^;]+);/) {
1722 $ret->{filename
} = $filename if $filename;
1723 $ret->{size
} = $size + 0 if $size;
1724 $ret->{mimetype
} = $type if $type;
1729 __PACKAGE__-
>register_method({
1734 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1737 description
=> "Gather various systems information about a node",
1740 additionalProperties
=> 0,
1742 node
=> get_standard_option
('pve-node'),
1749 return PVE
::Report
::generate
();
1752 # returns a list of VMIDs, those can be filtered by
1753 # * current parent node
1755 # * guest is a template (default: skip)
1756 # * guest is HA manged (default: skip)
1757 my $get_filtered_vmlist = sub {
1758 my ($nodename, $vmfilter, $templates, $ha_managed) = @_;
1760 my $vmlist = PVE
::Cluster
::get_vmlist
();
1763 if (defined($vmfilter)) {
1764 $vms_allowed = { map { $_ => 1 } PVE
::Tools
::split_list
($vmfilter) };
1768 foreach my $vmid (keys %{$vmlist->{ids
}}) {
1769 next if defined($vms_allowed) && !$vms_allowed->{$vmid};
1771 my $d = $vmlist->{ids
}->{$vmid};
1772 next if $nodename && $d->{node
} ne $nodename;
1776 if ($d->{type
} eq 'lxc') {
1777 $class = 'PVE::LXC::Config';
1778 } elsif ($d->{type
} eq 'qemu') {
1779 $class = 'PVE::QemuConfig';
1781 die "unknown virtual guest type '$d->{type}'\n";
1784 my $conf = $class->load_config($vmid);
1785 return if !$templates && $class->is_template($conf);
1786 return if !$ha_managed && PVE
::HA
::Config
::vm_is_ha_managed
($vmid);
1788 $res->{$vmid}->{conf
} = $conf;
1789 $res->{$vmid}->{type
} = $d->{type
};
1790 $res->{$vmid}->{class} = $class;
1798 # return all VMs which should get started/stopped on power up/down
1799 my $get_start_stop_list = sub {
1800 my ($nodename, $autostart, $vmfilter) = @_;
1802 # do not skip HA vms on force or if a specific VMID set is wanted
1803 my $include_ha_managed = defined($vmfilter) ?
1 : 0;
1805 my $vmlist = $get_filtered_vmlist->($nodename, $vmfilter, undef, $include_ha_managed);
1808 foreach my $vmid (keys %$vmlist) {
1809 my $conf = $vmlist->{$vmid}->{conf
};
1810 next if $autostart && !$conf->{onboot
};
1812 my $startup = $conf->{startup
} ? PVE
::JSONSchema
::pve_parse_startup_order
($conf->{startup
}) : {};
1813 my $order = $startup->{order
} = $startup->{order
} // LONG_MAX
;
1815 $resList->{$order}->{$vmid} = $startup;
1816 $resList->{$order}->{$vmid}->{type
} = $vmlist->{$vmid}->{type
};
1822 my $remove_locks_on_startup = sub {
1823 my ($nodename) = @_;
1825 my $vmlist = &$get_filtered_vmlist($nodename, undef, undef, 1);
1827 foreach my $vmid (keys %$vmlist) {
1828 my $conf = $vmlist->{$vmid}->{conf
};
1829 my $class = $vmlist->{$vmid}->{class};
1832 if ($class->has_lock($conf, 'backup')) {
1833 $class->remove_lock($vmid, 'backup');
1834 my $msg = "removed left over backup lock from '$vmid'!";
1835 warn "$msg\n"; # prints to task log
1836 syslog
('warning', $msg);
1842 __PACKAGE__-
>register_method ({
1848 description
=> "The 'VM.PowerMgmt' permission is required on '/' or on '/vms/<ID>' for "
1849 ."each ID passed via the 'vms' parameter.",
1853 description
=> "Start all VMs and containers located on this node (by default only those with onboot=1).",
1855 additionalProperties
=> 0,
1857 node
=> get_standard_option
('pve-node'),
1862 description
=> "Issue start command even if virtual guest have 'onboot' not set or set to off.",
1865 description
=> "Only consider guests from this comma separated list of VMIDs.",
1866 type
=> 'string', format
=> 'pve-vmid-list',
1877 my $rpcenv = PVE
::RPCEnvironment
::get
();
1878 my $authuser = $rpcenv->get_user();
1880 if (!$rpcenv->check($authuser, "/", [ 'VM.PowerMgmt' ], 1)) {
1881 my @vms = PVE
::Tools
::split_list
($param->{vms
});
1882 if (scalar(@vms) > 0) {
1883 $rpcenv->check($authuser, "/vms/$_", [ 'VM.PowerMgmt' ]) for @vms;
1885 raise_perm_exc
("/, VM.PowerMgmt");
1889 my $nodename = $param->{node
};
1890 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
1892 my $force = $param->{force
};
1895 $rpcenv->{type
} = 'priv'; # to start tasks in background
1897 if (!PVE
::Cluster
::check_cfs_quorum
(1)) {
1898 print "waiting for quorum ...\n";
1901 } while (!PVE
::Cluster
::check_cfs_quorum
(1));
1902 print "got quorum\n";
1905 eval { # remove backup locks, but avoid running into a scheduled backup job
1906 PVE
::Tools
::lock_file
('/var/run/vzdump.lock', 10, $remove_locks_on_startup, $nodename);
1910 my $autostart = $force ?
undef : 1;
1911 my $startList = $get_start_stop_list->($nodename, $autostart, $param->{vms
});
1913 # Note: use numeric sorting with <=>
1914 for my $order (sort {$a <=> $b} keys %$startList) {
1915 my $vmlist = $startList->{$order};
1917 for my $vmid (sort {$a <=> $b} keys %$vmlist) {
1918 my $d = $vmlist->{$vmid};
1920 PVE
::Cluster
::check_cfs_quorum
(); # abort when we loose quorum
1923 my $default_delay = 0;
1926 if ($d->{type
} eq 'lxc') {
1927 return if PVE
::LXC
::check_running
($vmid);
1928 print STDERR
"Starting CT $vmid\n";
1929 $upid = PVE
::API2
::LXC
::Status-
>vm_start({node
=> $nodename, vmid
=> $vmid });
1930 } elsif ($d->{type
} eq 'qemu') {
1931 $default_delay = 3; # to reduce load
1932 return if PVE
::QemuServer
::check_running
($vmid, 1);
1933 print STDERR
"Starting VM $vmid\n";
1934 $upid = PVE
::API2
::Qemu-
>vm_start({node
=> $nodename, vmid
=> $vmid });
1936 die "unknown VM type '$d->{type}'\n";
1939 my $task = PVE
::Tools
::upid_decode
($upid);
1940 while (PVE
::ProcFSTools
::check_process_running
($task->{pid
})) {
1944 my $status = PVE
::Tools
::upid_read_status
($upid);
1945 if (!PVE
::Tools
::upid_status_is_error
($status)) {
1946 # use default delay to reduce load
1947 my $delay = defined($d->{up
}) ?
int($d->{up
}) : $default_delay;
1949 print STDERR
"Waiting for $delay seconds (startup delay)\n" if $d->{up
};
1950 for (my $i = 0; $i < $delay; $i++) {
1955 my $rendered_type = $d->{type
} eq 'lxc' ?
'CT' : 'VM';
1956 print STDERR
"Starting $rendered_type $vmid failed: $status\n";
1965 return $rpcenv->fork_worker('startall', undef, $authuser, $code);
1968 my $create_stop_worker = sub {
1969 my ($nodename, $type, $vmid, $timeout, $force_stop) = @_;
1971 if ($type eq 'lxc') {
1972 return if !PVE
::LXC
::check_running
($vmid);
1973 print STDERR
"Stopping CT $vmid (timeout = $timeout seconds)\n";
1974 return PVE
::API2
::LXC
::Status-
>vm_shutdown(
1975 { node
=> $nodename, vmid
=> $vmid, timeout
=> $timeout, forceStop
=> $force_stop }
1977 } elsif ($type eq 'qemu') {
1978 return if !PVE
::QemuServer
::check_running
($vmid, 1);
1979 print STDERR
"Stopping VM $vmid (timeout = $timeout seconds)\n";
1980 return PVE
::API2
::Qemu-
>vm_shutdown(
1981 { node
=> $nodename, vmid
=> $vmid, timeout
=> $timeout, forceStop
=> $force_stop }
1984 die "unknown VM type '$type'\n";
1988 __PACKAGE__-
>register_method ({
1994 description
=> "The 'VM.PowerMgmt' permission is required on '/' or on '/vms/<ID>' for "
1995 ."each ID passed via the 'vms' parameter.",
1999 description
=> "Stop all VMs and Containers.",
2001 additionalProperties
=> 0,
2003 node
=> get_standard_option
('pve-node'),
2005 description
=> "Only consider Guests with these IDs.",
2006 type
=> 'string', format
=> 'pve-vmid-list',
2010 description
=> 'Force a hard-stop after the timeout.',
2016 description
=> 'Timeout for each guest shutdown task. Depending on `force-stop`,'
2017 .' the shutdown gets then simply aborted or a hard-stop is forced.',
2022 maximum
=> 2 * 3600, # mostly arbitrary, but we do not want to high timeouts
2032 my $rpcenv = PVE
::RPCEnvironment
::get
();
2033 my $authuser = $rpcenv->get_user();
2035 if (!$rpcenv->check($authuser, "/", [ 'VM.PowerMgmt' ], 1)) {
2036 my @vms = PVE
::Tools
::split_list
($param->{vms
});
2037 if (scalar(@vms) > 0) {
2038 $rpcenv->check($authuser, "/vms/$_", [ 'VM.PowerMgmt' ]) for @vms;
2040 raise_perm_exc
("/, VM.PowerMgmt");
2044 my $nodename = $param->{node
};
2045 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
2049 $rpcenv->{type
} = 'priv'; # to start tasks in background
2051 my $stopList = $get_start_stop_list->($nodename, undef, $param->{vms
});
2053 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
2054 my $datacenterconfig = cfs_read_file
('datacenter.cfg');
2055 # if not set by user spawn max cpu count number of workers
2056 my $maxWorkers = $datacenterconfig->{max_workers
} || $cpuinfo->{cpus
};
2058 for my $order (sort {$b <=> $a} keys %$stopList) {
2059 my $vmlist = $stopList->{$order};
2062 my $finish_worker = sub {
2064 my $worker = delete $workers->{$pid} || return;
2066 syslog
('info', "end task $worker->{upid}");
2069 for my $vmid (sort {$b <=> $a} keys %$vmlist) {
2070 my $d = $vmlist->{$vmid};
2071 my $timeout = int($d->{down
} // $param->{timeout
} // 180);
2073 $create_stop_worker->(
2074 $nodename, $d->{type
}, $vmid, $timeout, $param->{'force-stop'} // 1)
2079 my $task = PVE
::Tools
::upid_decode
($upid, 1);
2082 my $pid = $task->{pid
};
2084 $workers->{$pid} = { type
=> $d->{type
}, upid
=> $upid, vmid
=> $vmid };
2085 while (scalar(keys %$workers) >= $maxWorkers) {
2086 foreach my $p (keys %$workers) {
2087 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2088 $finish_worker->($p);
2094 while (scalar(keys %$workers)) {
2095 for my $p (keys %$workers) {
2096 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2097 $finish_worker->($p);
2104 syslog
('info', "all VMs and CTs stopped");
2109 return $rpcenv->fork_worker('stopall', undef, $authuser, $code);
2112 my $create_suspend_worker = sub {
2113 my ($nodename, $vmid) = @_;
2114 if (!PVE
::QemuServer
::check_running
($vmid, 1)) {
2115 print "VM $vmid not running, skipping suspension\n";
2118 print STDERR
"Suspending VM $vmid\n";
2119 return PVE
::API2
::Qemu-
>vm_suspend(
2120 { node
=> $nodename, vmid
=> $vmid, todisk
=> 1 }
2124 __PACKAGE__-
>register_method ({
2125 name
=> 'suspendall',
2126 path
=> 'suspendall',
2130 description
=> "The 'VM.PowerMgmt' permission is required on '/' or on '/vms/<ID>' for each"
2131 ." ID passed via the 'vms' parameter. Additionally, you need 'VM.Config.Disk' on the"
2132 ." '/vms/{vmid}' path and 'Datastore.AllocateSpace' for the configured state-storage(s)",
2136 description
=> "Suspend all VMs.",
2138 additionalProperties
=> 0,
2140 node
=> get_standard_option
('pve-node'),
2142 description
=> "Only consider Guests with these IDs.",
2143 type
=> 'string', format
=> 'pve-vmid-list',
2154 my $rpcenv = PVE
::RPCEnvironment
::get
();
2155 my $authuser = $rpcenv->get_user();
2157 # we cannot really check access to the state-storage here, that's happening per worker.
2158 if (!$rpcenv->check($authuser, "/", [ 'VM.PowerMgmt', 'VM.Config.Disk' ], 1)) {
2159 my @vms = PVE
::Tools
::split_list
($param->{vms
});
2160 if (scalar(@vms) > 0) {
2161 $rpcenv->check($authuser, "/vms/$_", [ 'VM.PowerMgmt' ]) for @vms;
2163 raise_perm_exc
("/, VM.PowerMgmt && VM.Config.Disk");
2167 my $nodename = $param->{node
};
2168 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
2172 $rpcenv->{type
} = 'priv'; # to start tasks in background
2174 my $toSuspendList = $get_start_stop_list->($nodename, undef, $param->{vms
});
2176 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
2177 my $datacenterconfig = cfs_read_file
('datacenter.cfg');
2178 # if not set by user spawn max cpu count number of workers
2179 my $maxWorkers = $datacenterconfig->{max_workers
} || $cpuinfo->{cpus
};
2181 for my $order (sort {$b <=> $a} keys %$toSuspendList) {
2182 my $vmlist = $toSuspendList->{$order};
2185 my $finish_worker = sub {
2187 my $worker = delete $workers->{$pid} || return;
2189 syslog
('info', "end task $worker->{upid}");
2192 for my $vmid (sort {$b <=> $a} keys %$vmlist) {
2193 my $d = $vmlist->{$vmid};
2194 if ($d->{type
} ne 'qemu') {
2195 log_warn
("skipping $vmid, only VMs can be suspended");
2199 $create_suspend_worker->($nodename, $vmid)
2204 my $task = PVE
::Tools
::upid_decode
($upid, 1);
2207 my $pid = $task->{pid
};
2208 $workers->{$pid} = { type
=> $d->{type
}, upid
=> $upid, vmid
=> $vmid };
2210 while (scalar(keys %$workers) >= $maxWorkers) {
2211 for my $p (keys %$workers) {
2212 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2213 $finish_worker->($p);
2219 while (scalar(keys %$workers)) {
2220 for my $p (keys %$workers) {
2221 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2222 $finish_worker->($p);
2229 syslog
('info', "all VMs suspended");
2234 return $rpcenv->fork_worker('suspendall', undef, $authuser, $code);
2238 my $create_migrate_worker = sub {
2239 my ($nodename, $type, $vmid, $target, $with_local_disks) = @_;
2242 if ($type eq 'lxc') {
2243 my $online = PVE
::LXC
::check_running
($vmid) ?
1 : 0;
2244 print STDERR
"Migrating CT $vmid\n";
2245 $upid = PVE
::API2
::LXC-
>migrate_vm(
2246 { node
=> $nodename, vmid
=> $vmid, target
=> $target, restart
=> $online });
2247 } elsif ($type eq 'qemu') {
2248 print STDERR
"Check VM $vmid: ";
2250 my $online = PVE
::QemuServer
::check_running
($vmid, 1) ?
1 : 0;
2251 my $preconditions = PVE
::API2
::Qemu-
>migrate_vm_precondition(
2252 {node
=> $nodename, vmid
=> $vmid, target
=> $target});
2253 my $invalidConditions = '';
2254 if ($online && !$with_local_disks && scalar @{$preconditions->{local_disks
}}) {
2255 $invalidConditions .= "\n Has local disks: ";
2256 $invalidConditions .= join(', ', map { $_->{volid
} } @{$preconditions->{local_disks
}});
2259 if (@{$preconditions->{local_resources
}}) {
2260 $invalidConditions .= "\n Has local resources: ";
2261 $invalidConditions .= join(', ', @{$preconditions->{local_resources
}});
2264 if ($invalidConditions && $invalidConditions ne '') {
2265 print STDERR
"skip VM $vmid - precondition check failed:";
2266 die "$invalidConditions\n";
2268 print STDERR
"precondition check passed\n";
2269 print STDERR
"Migrating VM $vmid\n";
2277 $params->{'with-local-disks'} = $with_local_disks if defined($with_local_disks);
2279 $upid = PVE
::API2
::Qemu-
>migrate_vm($params);
2281 die "unknown VM type '$type'\n";
2284 my $task = PVE
::Tools
::upid_decode
($upid);
2286 return $task->{pid
};
2289 __PACKAGE__-
>register_method ({
2290 name
=> 'migrateall',
2291 path
=> 'migrateall',
2296 description
=> "The 'VM.Migrate' permission is required on '/' or on '/vms/<ID>' for each "
2297 ."ID passed via the 'vms' parameter.",
2300 description
=> "Migrate all VMs and Containers.",
2302 additionalProperties
=> 0,
2304 node
=> get_standard_option
('pve-node'),
2305 target
=> get_standard_option
('pve-node', { description
=> "Target node." }),
2307 description
=> "Maximal number of parallel migration job. If not set, uses"
2308 ."'max_workers' from datacenter.cfg. One of both must be set!",
2314 description
=> "Only consider Guests with these IDs.",
2315 type
=> 'string', format
=> 'pve-vmid-list',
2318 "with-local-disks" => {
2320 description
=> "Enable live storage migration for local disk",
2331 my $rpcenv = PVE
::RPCEnvironment
::get
();
2332 my $authuser = $rpcenv->get_user();
2334 if (!$rpcenv->check($authuser, "/", [ 'VM.Migrate' ], 1)) {
2335 my @vms = PVE
::Tools
::split_list
($param->{vms
});
2336 if (scalar(@vms) > 0) {
2337 $rpcenv->check($authuser, "/vms/$_", [ 'VM.Migrate' ]) for @vms;
2339 raise_perm_exc
("/, VM.Migrate");
2343 my $nodename = $param->{node
};
2344 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
2346 my $target = $param->{target
};
2347 my $with_local_disks = $param->{'with-local-disks'};
2348 raise_param_exc
({ target
=> "target is local node."}) if $target eq $nodename;
2350 PVE
::Cluster
::check_cfs_quorum
();
2352 PVE
::Cluster
::check_node_exists
($target);
2354 my $datacenterconfig = cfs_read_file
('datacenter.cfg');
2355 # prefer parameter over datacenter cfg settings
2356 my $maxWorkers = $param->{maxworkers
} || $datacenterconfig->{max_workers
} ||
2357 die "either 'maxworkers' parameter or max_workers in datacenter.cfg must be set!\n";
2360 $rpcenv->{type
} = 'priv'; # to start tasks in background
2362 my $vmlist = &$get_filtered_vmlist($nodename, $param->{vms
}, 1, 1);
2363 if (!scalar(keys %$vmlist)) {
2364 warn "no virtual guests matched, nothing to do..\n";
2369 my $workers_started = 0;
2370 foreach my $vmid (sort keys %$vmlist) {
2371 my $d = $vmlist->{$vmid};
2373 eval { $pid = &$create_migrate_worker($nodename, $d->{type
}, $vmid, $target, $with_local_disks); };
2378 $workers->{$pid} = 1;
2379 while (scalar(keys %$workers) >= $maxWorkers) {
2380 foreach my $p (keys %$workers) {
2381 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2382 delete $workers->{$p};
2388 while (scalar(keys %$workers)) {
2389 foreach my $p (keys %$workers) {
2390 # FIXME: what about PID re-use ?!?!
2391 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2392 delete $workers->{$p};
2397 if ($workers_started <= 0) {
2398 die "no migrations worker started...\n";
2400 print STDERR
"All jobs finished, used $workers_started workers in total.\n";
2404 return $rpcenv->fork_worker('migrateall', undef, $authuser, $code);
2408 __PACKAGE__-
>register_method ({
2409 name
=> 'get_etc_hosts',
2415 check
=> ['perm', '/', [ 'Sys.Audit' ]],
2417 description
=> "Get the content of /etc/hosts.",
2419 additionalProperties
=> 0,
2421 node
=> get_standard_option
('pve-node'),
2427 digest
=> get_standard_option
('pve-config-digest'),
2430 description
=> 'The content of /etc/hosts.'
2437 return PVE
::INotify
::read_file
('etchosts');
2441 __PACKAGE__-
>register_method ({
2442 name
=> 'write_etc_hosts',
2448 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
2450 description
=> "Write /etc/hosts.",
2452 additionalProperties
=> 0,
2454 node
=> get_standard_option
('pve-node'),
2455 digest
=> get_standard_option
('pve-config-digest'),
2458 description
=> 'The target content of /etc/hosts.'
2468 PVE
::Tools
::lock_file
('/var/lock/pve-etchosts.lck', undef, sub {
2469 if ($param->{digest
}) {
2470 my $hosts = PVE
::INotify
::read_file
('etchosts');
2471 PVE
::Tools
::assert_if_modified
($hosts->{digest
}, $param->{digest
});
2473 PVE
::INotify
::write_file
('etchosts', $param->{data
});
2480 # bash completion helper
2482 sub complete_templet_repo
{
2483 my ($cmdname, $pname, $cvalue) = @_;
2485 my $repo = PVE
::APLInfo
::load_data
();
2487 foreach my $templ (keys %{$repo->{all
}}) {
2488 next if $templ !~ m/^$cvalue/;
2495 package PVE
::API2
::Nodes
;
2500 use PVE
::SafeSyslog
;
2502 use PVE
::RESTHandler
;
2503 use PVE
::RPCEnvironment
;
2505 use PVE
::JSONSchema
qw(get_standard_option);
2507 use base
qw(PVE::RESTHandler);
2509 __PACKAGE__-
>register_method ({
2510 subclass
=> "PVE::API2::Nodes::Nodeinfo",
2514 __PACKAGE__-
>register_method ({
2518 permissions
=> { user
=> 'all' },
2519 description
=> "Cluster node index.",
2521 additionalProperties
=> 0,
2529 node
=> get_standard_option
('pve-node'),
2531 description
=> "Node status.",
2533 enum
=> ['unknown', 'online', 'offline'],
2536 description
=> "CPU utilization.",
2539 renderer
=> 'fraction_as_percentage',
2542 description
=> "Number of available CPUs.",
2547 description
=> "Used memory in bytes.",
2550 renderer
=> 'bytes',
2553 description
=> "Number of available memory in bytes.",
2556 renderer
=> 'bytes',
2559 description
=> "Support level.",
2564 description
=> "Node uptime in seconds.",
2567 renderer
=> 'duration',
2569 ssl_fingerprint
=> {
2570 description
=> "The SSL fingerprint for the node certificate.",
2576 links
=> [ { rel
=> 'child', href
=> "{node}" } ],
2581 my $rpcenv = PVE
::RPCEnvironment
::get
();
2582 my $authuser = $rpcenv->get_user();
2584 my $clinfo = PVE
::Cluster
::get_clinfo
();
2587 my $nodelist = PVE
::Cluster
::get_nodelist
();
2588 my $members = PVE
::Cluster
::get_members
();
2589 my $rrd = PVE
::Cluster
::rrd_dump
();
2591 foreach my $node (@$nodelist) {
2592 my $can_audit = $rpcenv->check($authuser, "/nodes/$node", [ 'Sys.Audit' ], 1);
2593 my $entry = PVE
::API2Tools
::extract_node_stats
($node, $members, $rrd, !$can_audit);
2595 $entry->{ssl_fingerprint
} = eval { PVE
::Cluster
::get_node_fingerprint
($node) };