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 $broadcast_addr = $local_wol_config->{'broadcast-address'} // '255.255.255.255';
705 my $packet = chr(0xff) x
6 . pack('H*', $mac_addr) x
16;
707 my $addr = gethostbyname($broadcast_addr);
708 my $port = getservbyname('discard', 'udp');
709 my $to = Socket
::pack_sockaddr_in
($port, $addr);
711 socket(my $sock, Socket
::AF_INET
, Socket
::SOCK_DGRAM
, Socket
::IPPROTO_UDP
)
712 || die "Unable to open socket: $!\n";
713 setsockopt($sock, Socket
::SOL_SOCKET
, Socket
::SO_BROADCAST
, 1)
714 || die "Unable to set socket option: $!\n";
716 if (defined(my $bind_iface = $local_wol_config->{'bind-interface'})) {
717 my $bind_iface_raw = pack('Z*', $bind_iface); # Null terminated interface name
718 setsockopt($sock, Socket
::SOL_SOCKET
, Socket
::SO_BINDTODEVICE
, $bind_iface_raw)
719 || die "Unable to bind socket to interface '$bind_iface': $!\n";
722 send($sock, $packet, 0, $to)
723 || die "Unable to send packet: $!\n";
727 return $wol_config->{mac
};
730 __PACKAGE__-
>register_method({
734 protected
=> 1, # fixme: can we avoid that?
736 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
738 description
=> "Read node RRD statistics (returns PNG)",
740 additionalProperties
=> 0,
742 node
=> get_standard_option
('pve-node'),
744 description
=> "Specify the time frame you are interested in.",
746 enum
=> [ 'hour', 'day', 'week', 'month', 'year' ],
749 description
=> "The list of datasources you want to display.",
750 type
=> 'string', format
=> 'pve-configid-list',
753 description
=> "The RRD consolidation function",
755 enum
=> [ 'AVERAGE', 'MAX' ],
763 filename
=> { type
=> 'string' },
769 return PVE
::RRD
::create_rrd_graph
(
770 "pve2-node/$param->{node}", $param->{timeframe
},
771 $param->{ds
}, $param->{cf
});
775 __PACKAGE__-
>register_method({
779 protected
=> 1, # fixme: can we avoid that?
781 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
783 description
=> "Read node RRD statistics",
785 additionalProperties
=> 0,
787 node
=> get_standard_option
('pve-node'),
789 description
=> "Specify the time frame you are interested in.",
791 enum
=> [ 'hour', 'day', 'week', 'month', 'year' ],
794 description
=> "The RRD consolidation function",
796 enum
=> [ 'AVERAGE', 'MAX' ],
811 return PVE
::RRD
::create_rrd_data
(
812 "pve2-node/$param->{node}", $param->{timeframe
}, $param->{cf
});
815 __PACKAGE__-
>register_method({
819 description
=> "Read system log",
822 check
=> ['perm', '/nodes/{node}', [ 'Sys.Syslog' ]],
826 additionalProperties
=> 0,
828 node
=> get_standard_option
('pve-node'),
841 pattern
=> '^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}(:\d{2})?)?$',
842 description
=> "Display all log since this date-time string.",
847 pattern
=> '^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}(:\d{2})?)?$',
848 description
=> "Display all log until this date-time string.",
852 description
=> "Service ID",
865 description
=> "Line number",
869 description
=> "Line text",
878 my $rpcenv = PVE
::RPCEnvironment
::get
();
879 my $user = $rpcenv->get_user();
880 my $node = $param->{node
};
883 if ($param->{service
}) {
884 my $service_aliases = {
885 'postfix' => 'postfix@-',
888 $service = $service_aliases->{$param->{service
}} // $param->{service
};
891 my ($count, $lines) = PVE
::Tools
::dump_journal
($param->{start
}, $param->{limit
},
892 $param->{since
}, $param->{until}, $service);
894 $rpcenv->set_result_attrib('total', $count);
899 __PACKAGE__-
>register_method({
903 description
=> "Read Journal",
906 check
=> ['perm', '/nodes/{node}', [ 'Sys.Syslog' ]],
910 additionalProperties
=> 0,
912 node
=> get_standard_option
('pve-node'),
916 description
=> "Display all log since this UNIX epoch. Conflicts with 'startcursor'.",
922 description
=> "Display all log until this UNIX epoch. Conflicts with 'endcursor'.",
926 description
=> "Limit to the last X lines. Conflicts with a range.",
932 description
=> "Start after the given Cursor. Conflicts with 'since'",
937 description
=> "End before the given Cursor. Conflicts with 'until'",
952 my $rpcenv = PVE
::RPCEnvironment
::get
();
953 my $user = $rpcenv->get_user();
955 my $cmd = ["/usr/bin/mini-journalreader", "-j"];
956 push @$cmd, '-n', $param->{lastentries
} if $param->{lastentries
};
957 push @$cmd, '-b', $param->{since
} if $param->{since
};
958 push @$cmd, '-e', $param->{until} if $param->{until};
959 push @$cmd, '-f', PVE
::Tools
::shellquote
($param->{startcursor
}) if $param->{startcursor
};
960 push @$cmd, '-t', PVE
::Tools
::shellquote
($param->{endcursor
}) if $param->{endcursor
};
961 push @$cmd, ' | gzip ';
963 open(my $fh, "-|", join(' ', @$cmd))
964 or die "could not start mini-journalreader";
970 'content-type' => 'application/json',
971 'content-encoding' => 'gzip',
978 my $shell_cmd_map = {
980 cmd
=> [ '/bin/login', '-f', 'root' ],
983 cmd
=> [ '/usr/bin/pveupgrade', '--shell' ],
986 cmd
=> [ '/usr/bin/pveceph', 'install' ],
991 sub get_shell_command
{
992 my ($user, $shellcmd, $args) = @_;
995 if ($user eq 'root@pam') {
996 if (defined($shellcmd) && exists($shell_cmd_map->{$shellcmd})) {
997 my $def = $shell_cmd_map->{$shellcmd};
998 $cmd = [ @{$def->{cmd
}} ]; # clone
999 if (defined($args) && $def->{allow_args
}) {
1000 push @$cmd, split("\0", $args);
1003 $cmd = [ '/bin/login', '-f', 'root' ];
1006 # non-root must always login for now, we do not have a superuser role!
1007 $cmd = [ '/bin/login' ];
1012 my $get_vnc_connection_info = sub {
1015 my $remote_cmd = [];
1017 my ($remip, $family);
1018 if ($node ne 'localhost' && $node ne PVE
::INotify
::nodename
()) {
1019 ($remip, $family) = PVE
::Cluster
::remote_node_ip
($node);
1020 $remote_cmd = ['/usr/bin/ssh', '-e', 'none', '-t', $remip , '--'];
1022 $family = PVE
::Tools
::get_host_address_family
($node);
1024 my $port = PVE
::Tools
::next_vnc_port
($family);
1026 return ($port, $remote_cmd);
1029 __PACKAGE__-
>register_method ({
1035 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
1037 description
=> "Creates a VNC Shell proxy.",
1039 additionalProperties
=> 0,
1041 node
=> get_standard_option
('pve-node'),
1044 description
=> "Run specific command or default to login (requires 'root\@pam')",
1045 enum
=> [keys %$shell_cmd_map],
1051 description
=> "Add parameters to a command. Encoded as null terminated strings.",
1059 description
=> "use websocket instead of standard vnc.",
1063 description
=> "sets the width of the console in pixels.",
1070 description
=> "sets the height of the console in pixels.",
1078 additionalProperties
=> 0,
1080 user
=> { type
=> 'string' },
1081 ticket
=> { type
=> 'string' },
1082 cert
=> { type
=> 'string' },
1083 port
=> { type
=> 'integer' },
1084 upid
=> { type
=> 'string' },
1090 my $rpcenv = PVE
::RPCEnvironment
::get
();
1091 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($rpcenv->get_user());
1094 if (defined($param->{cmd
}) && $param->{cmd
} ne 'login' && $user ne 'root@pam') {
1095 raise_perm_exc
('user != root@pam');
1098 my $node = $param->{node
};
1100 my $authpath = "/nodes/$node";
1101 my $ticket = PVE
::AccessControl
::assemble_vnc_ticket
($user, $authpath);
1103 $sslcert = PVE
::Tools
::file_get_contents
("/etc/pve/pve-root-ca.pem", 8192)
1106 my ($port, $remcmd) = $get_vnc_connection_info->($node);
1108 my $shcmd = get_shell_command
($user, $param->{cmd
}, $param->{'cmd-opts'});
1112 my $cmd = ['/usr/bin/vncterm',
1114 '-timeout', $timeout,
1115 '-authpath', $authpath,
1116 '-perm', 'Sys.Console',
1119 push @$cmd, '-width', $param->{width
} if $param->{width
};
1120 push @$cmd, '-height', $param->{height
} if $param->{height
};
1122 if ($param->{websocket
}) {
1123 $ENV{PVE_VNC_TICKET
} = $ticket; # pass ticket to vncterm
1124 push @$cmd, '-notls', '-listen', 'localhost';
1127 push @$cmd, '-c', @$remcmd, @$shcmd;
1132 syslog
('info', "starting vnc proxy $upid\n");
1134 my $cmdstr = join (' ', @$cmd);
1135 syslog
('info', "launch command: $cmdstr");
1138 foreach my $k (keys %ENV) {
1139 next if $k eq 'PVE_VNC_TICKET';
1140 next if $k eq 'PATH' || $k eq 'TERM' || $k eq 'USER' || $k eq 'HOME' || $k eq 'LANG' || $k eq 'LANGUAGE';
1145 PVE
::Tools
::run_command
($cmd, errmsg
=> "vncterm failed", keeplocale
=> 1);
1148 syslog
('err', $err);
1154 my $upid = $rpcenv->fork_worker('vncshell', "", $user, $realcmd);
1156 PVE
::Tools
::wait_for_vnc_port
($port);
1167 __PACKAGE__-
>register_method ({
1168 name
=> 'termproxy',
1169 path
=> 'termproxy',
1173 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
1175 description
=> "Creates a VNC Shell proxy.",
1177 additionalProperties
=> 0,
1179 node
=> get_standard_option
('pve-node'),
1182 description
=> "Run specific command or default to login (requires 'root\@pam')",
1183 enum
=> [keys %$shell_cmd_map],
1189 description
=> "Add parameters to a command. Encoded as null terminated strings.",
1197 additionalProperties
=> 0,
1199 user
=> { type
=> 'string' },
1200 ticket
=> { type
=> 'string' },
1201 port
=> { type
=> 'integer' },
1202 upid
=> { type
=> 'string' },
1208 my $rpcenv = PVE
::RPCEnvironment
::get
();
1209 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($rpcenv->get_user());
1211 my $node = $param->{node
};
1212 my $authpath = "/nodes/$node";
1213 my $ticket = PVE
::AccessControl
::assemble_vnc_ticket
($user, $authpath);
1215 my ($port, $remcmd) = $get_vnc_connection_info->($node);
1217 my $shcmd = get_shell_command
($user, $param->{cmd
}, $param->{'cmd-opts'});
1222 syslog
('info', "starting termproxy $upid\n");
1225 '/usr/bin/termproxy',
1227 '--path', $authpath,
1228 '--perm', 'Sys.Console',
1231 push @$cmd, @$remcmd, @$shcmd;
1233 PVE
::Tools
::run_command
($cmd);
1235 my $upid = $rpcenv->fork_worker('vncshell', "", $user, $realcmd);
1237 PVE
::Tools
::wait_for_vnc_port
($port);
1247 __PACKAGE__-
>register_method({
1248 name
=> 'vncwebsocket',
1249 path
=> 'vncwebsocket',
1252 description
=> "You also need to pass a valid ticket (vncticket).",
1253 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
1255 description
=> "Opens a websocket for VNC traffic.",
1257 additionalProperties
=> 0,
1259 node
=> get_standard_option
('pve-node'),
1261 description
=> "Ticket from previous call to vncproxy.",
1266 description
=> "Port number returned by previous vncproxy call.",
1276 port
=> { type
=> 'string' },
1282 my $rpcenv = PVE
::RPCEnvironment
::get
();
1284 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($rpcenv->get_user());
1286 my $authpath = "/nodes/$param->{node}";
1288 PVE
::AccessControl
::verify_vnc_ticket
($param->{vncticket
}, $user, $authpath);
1290 my $port = $param->{port
};
1292 return { port
=> $port };
1295 __PACKAGE__-
>register_method ({
1296 name
=> 'spiceshell',
1297 path
=> 'spiceshell',
1302 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
1304 description
=> "Creates a SPICE shell.",
1306 additionalProperties
=> 0,
1308 node
=> get_standard_option
('pve-node'),
1309 proxy
=> get_standard_option
('spice-proxy', { optional
=> 1 }),
1312 description
=> "Run specific command or default to login (requires 'root\@pam')",
1313 enum
=> [keys %$shell_cmd_map],
1319 description
=> "Add parameters to a command. Encoded as null terminated strings.",
1326 returns
=> get_standard_option
('remote-viewer-config'),
1330 my $rpcenv = PVE
::RPCEnvironment
::get
();
1331 my $authuser = $rpcenv->get_user();
1333 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($authuser);
1336 if (defined($param->{cmd
}) && $param->{cmd
} ne 'login' && $user ne 'root@pam') {
1337 raise_perm_exc
('user != root@pam');
1340 my $node = $param->{node
};
1341 my $proxy = $param->{proxy
};
1343 my $authpath = "/nodes/$node";
1344 my $permissions = 'Sys.Console';
1346 my $shcmd = get_shell_command
($user, $param->{cmd
}, $param->{'cmd-opts'});
1348 my $title = "Shell on '$node'";
1350 return PVE
::API2Tools
::run_spiceterm
($authpath, $permissions, 0, $node, $proxy, $title, $shcmd);
1353 __PACKAGE__-
>register_method({
1358 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1360 description
=> "Read DNS settings.",
1363 additionalProperties
=> 0,
1365 node
=> get_standard_option
('pve-node'),
1370 additionalProperties
=> 0,
1373 description
=> "Search domain for host-name lookup.",
1378 description
=> 'First name server IP address.',
1383 description
=> 'Second name server IP address.',
1388 description
=> 'Third name server IP address.',
1397 my $res = PVE
::INotify
::read_file
('resolvconf');
1402 __PACKAGE__-
>register_method({
1403 name
=> 'update_dns',
1406 description
=> "Write DNS settings.",
1408 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1413 additionalProperties
=> 0,
1415 node
=> get_standard_option
('pve-node'),
1417 description
=> "Search domain for host-name lookup.",
1421 description
=> 'First name server IP address.',
1422 type
=> 'string', format
=> 'ip',
1426 description
=> 'Second name server IP address.',
1427 type
=> 'string', format
=> 'ip',
1431 description
=> 'Third name server IP address.',
1432 type
=> 'string', format
=> 'ip',
1437 returns
=> { type
=> "null" },
1441 PVE
::INotify
::update_file
('resolvconf', $param);
1446 __PACKAGE__-
>register_method({
1451 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1453 description
=> "Read server time and time zone settings.",
1456 additionalProperties
=> 0,
1458 node
=> get_standard_option
('pve-node'),
1463 additionalProperties
=> 0,
1466 description
=> "Time zone",
1470 description
=> "Seconds since 1970-01-01 00:00:00 UTC.",
1472 minimum
=> 1297163644,
1473 renderer
=> 'timestamp',
1476 description
=> "Seconds since 1970-01-01 00:00:00 (local time)",
1478 minimum
=> 1297163644,
1479 renderer
=> 'timestamp_gmt',
1487 my $ltime = timegm_nocheck
(localtime($ctime));
1489 timezone
=> PVE
::INotify
::read_file
('timezone'),
1491 localtime => $ltime,
1497 __PACKAGE__-
>register_method({
1498 name
=> 'set_timezone',
1501 description
=> "Set time zone.",
1503 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1508 additionalProperties
=> 0,
1510 node
=> get_standard_option
('pve-node'),
1512 description
=> "Time zone. The file '/usr/share/zoneinfo/zone.tab' contains the list of valid names.",
1517 returns
=> { type
=> "null" },
1521 PVE
::INotify
::write_file
('timezone', $param->{timezone
});
1526 __PACKAGE__-
>register_method({
1533 description
=> "Get list of appliances.",
1536 additionalProperties
=> 0,
1538 node
=> get_standard_option
('pve-node'),
1551 my $list = PVE
::APLInfo
::load_data
();
1554 for my $appliance (values %{$list->{all
}}) {
1555 next if $appliance->{'package'} eq 'pve-web-news';
1556 push @$res, $appliance;
1562 __PACKAGE__-
>register_method({
1563 name
=> 'apl_download',
1567 check
=> ['perm', '/storage/{storage}', ['Datastore.AllocateTemplate']],
1569 description
=> "Download appliance templates.",
1573 additionalProperties
=> 0,
1575 node
=> get_standard_option
('pve-node'),
1576 storage
=> get_standard_option
('pve-storage-id', {
1577 description
=> "The storage where the template will be stored",
1578 completion
=> \
&PVE
::Storage
::complete_storage_enabled
,
1582 description
=> "The template which will downloaded",
1584 completion
=> \
&complete_templet_repo
,
1588 returns
=> { type
=> "string" },
1592 my $rpcenv = PVE
::RPCEnvironment
::get
();
1593 my $user = $rpcenv->get_user();
1595 my $node = $param->{node
};
1596 my $template = $param->{template
};
1598 my $list = PVE
::APLInfo
::load_data
();
1599 my $appliance = $list->{all
}->{$template};
1600 raise_param_exc
({ template
=> "no such template"}) if !$appliance;
1602 my $cfg = PVE
::Storage
::config
();
1603 my $scfg = PVE
::Storage
::storage_check_enabled
($cfg, $param->{storage
}, $node);
1605 die "unknown template type '$appliance->{type}'\n"
1606 if !($appliance->{type
} eq 'openvz' || $appliance->{type
} eq 'lxc');
1608 die "storage '$param->{storage}' does not support templates\n"
1609 if !$scfg->{content
}->{vztmpl
};
1611 my $tmpldir = PVE
::Storage
::get_vztmpl_dir
($cfg, $param->{storage
});
1614 my $dccfg = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
1616 PVE
::Tools
::download_file_from_url
("$tmpldir/$template", $appliance->{location
}, {
1618 sha512sum
=> $appliance->{sha512sum
},
1619 md5sum
=> $appliance->{md5sum
},
1620 http_proxy
=> $dccfg->{http_proxy
},
1624 my $upid = $rpcenv->fork_worker('download', $template, $user, $worker);
1629 __PACKAGE__-
>register_method({
1630 name
=> 'query_url_metadata',
1631 path
=> 'query-url-metadata',
1633 description
=> "Query metadata of an URL: file size, file name and mime type.",
1637 ['perm', '/', [ 'Sys.Audit', 'Sys.Modify' ]],
1638 ['perm', '/nodes/{node}', [ 'Sys.AccessNetwork' ]],
1642 additionalProperties
=> 0,
1644 node
=> get_standard_option
('pve-node'),
1646 description
=> "The URL to query the metadata from.",
1648 pattern
=> 'https?://.*',
1650 'verify-certificates' => {
1651 description
=> "If false, no SSL/TLS certificates will be verified.",
1667 renderer
=> 'bytes',
1679 my $url = $param->{url
};
1681 my $ua = LWP
::UserAgent-
>new();
1682 $ua->agent("Proxmox VE");
1684 my $dccfg = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
1685 if ($dccfg->{http_proxy
}) {
1686 $ua->proxy('http', $dccfg->{http_proxy
});
1689 my $verify = $param->{'verify-certificates'} // 1;
1692 verify_hostname
=> 0,
1693 SSL_verify_mode
=> IO
::Socket
::SSL
::SSL_VERIFY_NONE
,
1697 my $req = HTTP
::Request-
>new(HEAD
=> $url);
1698 my $res = $ua->request($req);
1700 die "invalid server response: '" . $res->status_line() . "'\n" if ($res->code() != 200);
1702 my $size = $res->header("Content-Length");
1703 my $disposition = $res->header("Content-Disposition");
1704 my $type = $res->header("Content-Type");
1708 if ($disposition && ($disposition =~ m/filename="([^"]*)"/ || $disposition =~ m/filename=([^;]*)/)) {
1710 } elsif ($url =~ m!^[^?]+/([^?/]*)(?:\?.*)?$!) {
1714 # Content-Type: text/html; charset=utf-8
1715 if ($type && $type =~ m/^([^;]+);/) {
1720 $ret->{filename
} = $filename if $filename;
1721 $ret->{size
} = $size + 0 if $size;
1722 $ret->{mimetype
} = $type if $type;
1727 __PACKAGE__-
>register_method({
1732 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1735 description
=> "Gather various systems information about a node",
1738 additionalProperties
=> 0,
1740 node
=> get_standard_option
('pve-node'),
1747 return PVE
::Report
::generate
();
1750 # returns a list of VMIDs, those can be filtered by
1751 # * current parent node
1753 # * guest is a template (default: skip)
1754 # * guest is HA manged (default: skip)
1755 my $get_filtered_vmlist = sub {
1756 my ($nodename, $vmfilter, $templates, $ha_managed) = @_;
1758 my $vmlist = PVE
::Cluster
::get_vmlist
();
1761 if (defined($vmfilter)) {
1762 $vms_allowed = { map { $_ => 1 } PVE
::Tools
::split_list
($vmfilter) };
1766 foreach my $vmid (keys %{$vmlist->{ids
}}) {
1767 next if defined($vms_allowed) && !$vms_allowed->{$vmid};
1769 my $d = $vmlist->{ids
}->{$vmid};
1770 next if $nodename && $d->{node
} ne $nodename;
1774 if ($d->{type
} eq 'lxc') {
1775 $class = 'PVE::LXC::Config';
1776 } elsif ($d->{type
} eq 'qemu') {
1777 $class = 'PVE::QemuConfig';
1779 die "unknown virtual guest type '$d->{type}'\n";
1782 my $conf = $class->load_config($vmid);
1783 return if !$templates && $class->is_template($conf);
1784 return if !$ha_managed && PVE
::HA
::Config
::vm_is_ha_managed
($vmid);
1786 $res->{$vmid}->{conf
} = $conf;
1787 $res->{$vmid}->{type
} = $d->{type
};
1788 $res->{$vmid}->{class} = $class;
1796 # return all VMs which should get started/stopped on power up/down
1797 my $get_start_stop_list = sub {
1798 my ($nodename, $autostart, $vmfilter) = @_;
1800 # do not skip HA vms on force or if a specific VMID set is wanted
1801 my $include_ha_managed = defined($vmfilter) ?
1 : 0;
1803 my $vmlist = $get_filtered_vmlist->($nodename, $vmfilter, undef, $include_ha_managed);
1806 foreach my $vmid (keys %$vmlist) {
1807 my $conf = $vmlist->{$vmid}->{conf
};
1808 next if $autostart && !$conf->{onboot
};
1810 my $startup = $conf->{startup
} ? PVE
::JSONSchema
::pve_parse_startup_order
($conf->{startup
}) : {};
1811 my $order = $startup->{order
} = $startup->{order
} // LONG_MAX
;
1813 $resList->{$order}->{$vmid} = $startup;
1814 $resList->{$order}->{$vmid}->{type
} = $vmlist->{$vmid}->{type
};
1820 my $remove_locks_on_startup = sub {
1821 my ($nodename) = @_;
1823 my $vmlist = &$get_filtered_vmlist($nodename, undef, undef, 1);
1825 foreach my $vmid (keys %$vmlist) {
1826 my $conf = $vmlist->{$vmid}->{conf
};
1827 my $class = $vmlist->{$vmid}->{class};
1830 if ($class->has_lock($conf, 'backup')) {
1831 $class->remove_lock($vmid, 'backup');
1832 my $msg = "removed left over backup lock from '$vmid'!";
1833 warn "$msg\n"; # prints to task log
1834 syslog
('warning', $msg);
1840 __PACKAGE__-
>register_method ({
1846 description
=> "The 'VM.PowerMgmt' permission is required on '/' or on '/vms/<ID>' for "
1847 ."each ID passed via the 'vms' parameter.",
1851 description
=> "Start all VMs and containers located on this node (by default only those with onboot=1).",
1853 additionalProperties
=> 0,
1855 node
=> get_standard_option
('pve-node'),
1860 description
=> "Issue start command even if virtual guest have 'onboot' not set or set to off.",
1863 description
=> "Only consider guests from this comma separated list of VMIDs.",
1864 type
=> 'string', format
=> 'pve-vmid-list',
1875 my $rpcenv = PVE
::RPCEnvironment
::get
();
1876 my $authuser = $rpcenv->get_user();
1878 if (!$rpcenv->check($authuser, "/", [ 'VM.PowerMgmt' ], 1)) {
1879 my @vms = PVE
::Tools
::split_list
($param->{vms
});
1880 if (scalar(@vms) > 0) {
1881 $rpcenv->check($authuser, "/vms/$_", [ 'VM.PowerMgmt' ]) for @vms;
1883 raise_perm_exc
("/, VM.PowerMgmt");
1887 my $nodename = $param->{node
};
1888 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
1890 my $force = $param->{force
};
1893 $rpcenv->{type
} = 'priv'; # to start tasks in background
1895 if (!PVE
::Cluster
::check_cfs_quorum
(1)) {
1896 print "waiting for quorum ...\n";
1899 } while (!PVE
::Cluster
::check_cfs_quorum
(1));
1900 print "got quorum\n";
1903 eval { # remove backup locks, but avoid running into a scheduled backup job
1904 PVE
::Tools
::lock_file
('/var/run/vzdump.lock', 10, $remove_locks_on_startup, $nodename);
1908 my $autostart = $force ?
undef : 1;
1909 my $startList = $get_start_stop_list->($nodename, $autostart, $param->{vms
});
1911 # Note: use numeric sorting with <=>
1912 for my $order (sort {$a <=> $b} keys %$startList) {
1913 my $vmlist = $startList->{$order};
1915 for my $vmid (sort {$a <=> $b} keys %$vmlist) {
1916 my $d = $vmlist->{$vmid};
1918 PVE
::Cluster
::check_cfs_quorum
(); # abort when we loose quorum
1921 my $default_delay = 0;
1924 if ($d->{type
} eq 'lxc') {
1925 return if PVE
::LXC
::check_running
($vmid);
1926 print STDERR
"Starting CT $vmid\n";
1927 $upid = PVE
::API2
::LXC
::Status-
>vm_start({node
=> $nodename, vmid
=> $vmid });
1928 } elsif ($d->{type
} eq 'qemu') {
1929 $default_delay = 3; # to reduce load
1930 return if PVE
::QemuServer
::check_running
($vmid, 1);
1931 print STDERR
"Starting VM $vmid\n";
1932 $upid = PVE
::API2
::Qemu-
>vm_start({node
=> $nodename, vmid
=> $vmid });
1934 die "unknown VM type '$d->{type}'\n";
1937 my $task = PVE
::Tools
::upid_decode
($upid);
1938 while (PVE
::ProcFSTools
::check_process_running
($task->{pid
})) {
1942 my $status = PVE
::Tools
::upid_read_status
($upid);
1943 if (!PVE
::Tools
::upid_status_is_error
($status)) {
1944 # use default delay to reduce load
1945 my $delay = defined($d->{up
}) ?
int($d->{up
}) : $default_delay;
1947 print STDERR
"Waiting for $delay seconds (startup delay)\n" if $d->{up
};
1948 for (my $i = 0; $i < $delay; $i++) {
1953 my $rendered_type = $d->{type
} eq 'lxc' ?
'CT' : 'VM';
1954 print STDERR
"Starting $rendered_type $vmid failed: $status\n";
1963 return $rpcenv->fork_worker('startall', undef, $authuser, $code);
1966 my $create_stop_worker = sub {
1967 my ($nodename, $type, $vmid, $timeout, $force_stop) = @_;
1969 if ($type eq 'lxc') {
1970 return if !PVE
::LXC
::check_running
($vmid);
1971 print STDERR
"Stopping CT $vmid (timeout = $timeout seconds)\n";
1972 return PVE
::API2
::LXC
::Status-
>vm_shutdown(
1973 { node
=> $nodename, vmid
=> $vmid, timeout
=> $timeout, forceStop
=> $force_stop }
1975 } elsif ($type eq 'qemu') {
1976 return if !PVE
::QemuServer
::check_running
($vmid, 1);
1977 print STDERR
"Stopping VM $vmid (timeout = $timeout seconds)\n";
1978 return PVE
::API2
::Qemu-
>vm_shutdown(
1979 { node
=> $nodename, vmid
=> $vmid, timeout
=> $timeout, forceStop
=> $force_stop }
1982 die "unknown VM type '$type'\n";
1986 __PACKAGE__-
>register_method ({
1992 description
=> "The 'VM.PowerMgmt' permission is required on '/' or on '/vms/<ID>' for "
1993 ."each ID passed via the 'vms' parameter.",
1997 description
=> "Stop all VMs and Containers.",
1999 additionalProperties
=> 0,
2001 node
=> get_standard_option
('pve-node'),
2003 description
=> "Only consider Guests with these IDs.",
2004 type
=> 'string', format
=> 'pve-vmid-list',
2008 description
=> 'Force a hard-stop after the timeout.',
2014 description
=> 'Timeout for each guest shutdown task. Depending on `force-stop`,'
2015 .' the shutdown gets then simply aborted or a hard-stop is forced.',
2020 maximum
=> 2 * 3600, # mostly arbitrary, but we do not want to high timeouts
2030 my $rpcenv = PVE
::RPCEnvironment
::get
();
2031 my $authuser = $rpcenv->get_user();
2033 if (!$rpcenv->check($authuser, "/", [ 'VM.PowerMgmt' ], 1)) {
2034 my @vms = PVE
::Tools
::split_list
($param->{vms
});
2035 if (scalar(@vms) > 0) {
2036 $rpcenv->check($authuser, "/vms/$_", [ 'VM.PowerMgmt' ]) for @vms;
2038 raise_perm_exc
("/, VM.PowerMgmt");
2042 my $nodename = $param->{node
};
2043 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
2047 $rpcenv->{type
} = 'priv'; # to start tasks in background
2049 my $stopList = $get_start_stop_list->($nodename, undef, $param->{vms
});
2051 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
2052 my $datacenterconfig = cfs_read_file
('datacenter.cfg');
2053 # if not set by user spawn max cpu count number of workers
2054 my $maxWorkers = $datacenterconfig->{max_workers
} || $cpuinfo->{cpus
};
2056 for my $order (sort {$b <=> $a} keys %$stopList) {
2057 my $vmlist = $stopList->{$order};
2060 my $finish_worker = sub {
2062 my $worker = delete $workers->{$pid} || return;
2064 syslog
('info', "end task $worker->{upid}");
2067 for my $vmid (sort {$b <=> $a} keys %$vmlist) {
2068 my $d = $vmlist->{$vmid};
2069 my $timeout = int($d->{down
} // $param->{timeout
} // 180);
2071 $create_stop_worker->(
2072 $nodename, $d->{type
}, $vmid, $timeout, $param->{'force-stop'} // 1)
2077 my $task = PVE
::Tools
::upid_decode
($upid, 1);
2080 my $pid = $task->{pid
};
2082 $workers->{$pid} = { type
=> $d->{type
}, upid
=> $upid, vmid
=> $vmid };
2083 while (scalar(keys %$workers) >= $maxWorkers) {
2084 foreach my $p (keys %$workers) {
2085 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2086 $finish_worker->($p);
2092 while (scalar(keys %$workers)) {
2093 for my $p (keys %$workers) {
2094 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2095 $finish_worker->($p);
2102 syslog
('info', "all VMs and CTs stopped");
2107 return $rpcenv->fork_worker('stopall', undef, $authuser, $code);
2110 my $create_suspend_worker = sub {
2111 my ($nodename, $vmid) = @_;
2112 if (!PVE
::QemuServer
::check_running
($vmid, 1)) {
2113 print "VM $vmid not running, skipping suspension\n";
2116 print STDERR
"Suspending VM $vmid\n";
2117 return PVE
::API2
::Qemu-
>vm_suspend(
2118 { node
=> $nodename, vmid
=> $vmid, todisk
=> 1 }
2122 __PACKAGE__-
>register_method ({
2123 name
=> 'suspendall',
2124 path
=> 'suspendall',
2128 description
=> "The 'VM.PowerMgmt' permission is required on '/' or on '/vms/<ID>' for each"
2129 ." ID passed via the 'vms' parameter. Additionally, you need 'VM.Config.Disk' on the"
2130 ." '/vms/{vmid}' path and 'Datastore.AllocateSpace' for the configured state-storage(s)",
2134 description
=> "Suspend all VMs.",
2136 additionalProperties
=> 0,
2138 node
=> get_standard_option
('pve-node'),
2140 description
=> "Only consider Guests with these IDs.",
2141 type
=> 'string', format
=> 'pve-vmid-list',
2152 my $rpcenv = PVE
::RPCEnvironment
::get
();
2153 my $authuser = $rpcenv->get_user();
2155 # we cannot really check access to the state-storage here, that's happening per worker.
2156 if (!$rpcenv->check($authuser, "/", [ 'VM.PowerMgmt', 'VM.Config.Disk' ], 1)) {
2157 my @vms = PVE
::Tools
::split_list
($param->{vms
});
2158 if (scalar(@vms) > 0) {
2159 $rpcenv->check($authuser, "/vms/$_", [ 'VM.PowerMgmt' ]) for @vms;
2161 raise_perm_exc
("/, VM.PowerMgmt && VM.Config.Disk");
2165 my $nodename = $param->{node
};
2166 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
2170 $rpcenv->{type
} = 'priv'; # to start tasks in background
2172 my $toSuspendList = $get_start_stop_list->($nodename, undef, $param->{vms
});
2174 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
2175 my $datacenterconfig = cfs_read_file
('datacenter.cfg');
2176 # if not set by user spawn max cpu count number of workers
2177 my $maxWorkers = $datacenterconfig->{max_workers
} || $cpuinfo->{cpus
};
2179 for my $order (sort {$b <=> $a} keys %$toSuspendList) {
2180 my $vmlist = $toSuspendList->{$order};
2183 my $finish_worker = sub {
2185 my $worker = delete $workers->{$pid} || return;
2187 syslog
('info', "end task $worker->{upid}");
2190 for my $vmid (sort {$b <=> $a} keys %$vmlist) {
2191 my $d = $vmlist->{$vmid};
2192 if ($d->{type
} ne 'qemu') {
2193 log_warn
("skipping $vmid, only VMs can be suspended");
2197 $create_suspend_worker->($nodename, $vmid)
2202 my $task = PVE
::Tools
::upid_decode
($upid, 1);
2205 my $pid = $task->{pid
};
2206 $workers->{$pid} = { type
=> $d->{type
}, upid
=> $upid, vmid
=> $vmid };
2208 while (scalar(keys %$workers) >= $maxWorkers) {
2209 for my $p (keys %$workers) {
2210 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2211 $finish_worker->($p);
2217 while (scalar(keys %$workers)) {
2218 for my $p (keys %$workers) {
2219 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2220 $finish_worker->($p);
2227 syslog
('info', "all VMs suspended");
2232 return $rpcenv->fork_worker('suspendall', undef, $authuser, $code);
2236 my $create_migrate_worker = sub {
2237 my ($nodename, $type, $vmid, $target, $with_local_disks) = @_;
2240 if ($type eq 'lxc') {
2241 my $online = PVE
::LXC
::check_running
($vmid) ?
1 : 0;
2242 print STDERR
"Migrating CT $vmid\n";
2243 $upid = PVE
::API2
::LXC-
>migrate_vm(
2244 { node
=> $nodename, vmid
=> $vmid, target
=> $target, restart
=> $online });
2245 } elsif ($type eq 'qemu') {
2246 print STDERR
"Check VM $vmid: ";
2248 my $online = PVE
::QemuServer
::check_running
($vmid, 1) ?
1 : 0;
2249 my $preconditions = PVE
::API2
::Qemu-
>migrate_vm_precondition(
2250 {node
=> $nodename, vmid
=> $vmid, target
=> $target});
2251 my $invalidConditions = '';
2252 if ($online && !$with_local_disks && scalar @{$preconditions->{local_disks
}}) {
2253 $invalidConditions .= "\n Has local disks: ";
2254 $invalidConditions .= join(', ', map { $_->{volid
} } @{$preconditions->{local_disks
}});
2257 if (@{$preconditions->{local_resources
}}) {
2258 $invalidConditions .= "\n Has local resources: ";
2259 $invalidConditions .= join(', ', @{$preconditions->{local_resources
}});
2262 if ($invalidConditions && $invalidConditions ne '') {
2263 print STDERR
"skip VM $vmid - precondition check failed:";
2264 die "$invalidConditions\n";
2266 print STDERR
"precondition check passed\n";
2267 print STDERR
"Migrating VM $vmid\n";
2275 $params->{'with-local-disks'} = $with_local_disks if defined($with_local_disks);
2277 $upid = PVE
::API2
::Qemu-
>migrate_vm($params);
2279 die "unknown VM type '$type'\n";
2282 my $task = PVE
::Tools
::upid_decode
($upid);
2284 return $task->{pid
};
2287 __PACKAGE__-
>register_method ({
2288 name
=> 'migrateall',
2289 path
=> 'migrateall',
2294 description
=> "The 'VM.Migrate' permission is required on '/' or on '/vms/<ID>' for each "
2295 ."ID passed via the 'vms' parameter.",
2298 description
=> "Migrate all VMs and Containers.",
2300 additionalProperties
=> 0,
2302 node
=> get_standard_option
('pve-node'),
2303 target
=> get_standard_option
('pve-node', { description
=> "Target node." }),
2305 description
=> "Maximal number of parallel migration job. If not set, uses"
2306 ."'max_workers' from datacenter.cfg. One of both must be set!",
2312 description
=> "Only consider Guests with these IDs.",
2313 type
=> 'string', format
=> 'pve-vmid-list',
2316 "with-local-disks" => {
2318 description
=> "Enable live storage migration for local disk",
2329 my $rpcenv = PVE
::RPCEnvironment
::get
();
2330 my $authuser = $rpcenv->get_user();
2332 if (!$rpcenv->check($authuser, "/", [ 'VM.Migrate' ], 1)) {
2333 my @vms = PVE
::Tools
::split_list
($param->{vms
});
2334 if (scalar(@vms) > 0) {
2335 $rpcenv->check($authuser, "/vms/$_", [ 'VM.Migrate' ]) for @vms;
2337 raise_perm_exc
("/, VM.Migrate");
2341 my $nodename = $param->{node
};
2342 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
2344 my $target = $param->{target
};
2345 my $with_local_disks = $param->{'with-local-disks'};
2346 raise_param_exc
({ target
=> "target is local node."}) if $target eq $nodename;
2348 PVE
::Cluster
::check_cfs_quorum
();
2350 PVE
::Cluster
::check_node_exists
($target);
2352 my $datacenterconfig = cfs_read_file
('datacenter.cfg');
2353 # prefer parameter over datacenter cfg settings
2354 my $maxWorkers = $param->{maxworkers
} || $datacenterconfig->{max_workers
} ||
2355 die "either 'maxworkers' parameter or max_workers in datacenter.cfg must be set!\n";
2358 $rpcenv->{type
} = 'priv'; # to start tasks in background
2360 my $vmlist = &$get_filtered_vmlist($nodename, $param->{vms
}, 1, 1);
2361 if (!scalar(keys %$vmlist)) {
2362 warn "no virtual guests matched, nothing to do..\n";
2367 my $workers_started = 0;
2368 foreach my $vmid (sort keys %$vmlist) {
2369 my $d = $vmlist->{$vmid};
2371 eval { $pid = &$create_migrate_worker($nodename, $d->{type
}, $vmid, $target, $with_local_disks); };
2376 $workers->{$pid} = 1;
2377 while (scalar(keys %$workers) >= $maxWorkers) {
2378 foreach my $p (keys %$workers) {
2379 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2380 delete $workers->{$p};
2386 while (scalar(keys %$workers)) {
2387 foreach my $p (keys %$workers) {
2388 # FIXME: what about PID re-use ?!?!
2389 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2390 delete $workers->{$p};
2395 if ($workers_started <= 0) {
2396 die "no migrations worker started...\n";
2398 print STDERR
"All jobs finished, used $workers_started workers in total.\n";
2402 return $rpcenv->fork_worker('migrateall', undef, $authuser, $code);
2406 __PACKAGE__-
>register_method ({
2407 name
=> 'get_etc_hosts',
2413 check
=> ['perm', '/', [ 'Sys.Audit' ]],
2415 description
=> "Get the content of /etc/hosts.",
2417 additionalProperties
=> 0,
2419 node
=> get_standard_option
('pve-node'),
2425 digest
=> get_standard_option
('pve-config-digest'),
2428 description
=> 'The content of /etc/hosts.'
2435 return PVE
::INotify
::read_file
('etchosts');
2439 __PACKAGE__-
>register_method ({
2440 name
=> 'write_etc_hosts',
2446 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
2448 description
=> "Write /etc/hosts.",
2450 additionalProperties
=> 0,
2452 node
=> get_standard_option
('pve-node'),
2453 digest
=> get_standard_option
('pve-config-digest'),
2456 description
=> 'The target content of /etc/hosts.'
2466 PVE
::Tools
::lock_file
('/var/lock/pve-etchosts.lck', undef, sub {
2467 if ($param->{digest
}) {
2468 my $hosts = PVE
::INotify
::read_file
('etchosts');
2469 PVE
::Tools
::assert_if_modified
($hosts->{digest
}, $param->{digest
});
2471 PVE
::INotify
::write_file
('etchosts', $param->{data
});
2478 # bash completion helper
2480 sub complete_templet_repo
{
2481 my ($cmdname, $pname, $cvalue) = @_;
2483 my $repo = PVE
::APLInfo
::load_data
();
2485 foreach my $templ (keys %{$repo->{all
}}) {
2486 next if $templ !~ m/^$cvalue/;
2493 package PVE
::API2
::Nodes
;
2498 use PVE
::SafeSyslog
;
2500 use PVE
::RESTHandler
;
2501 use PVE
::RPCEnvironment
;
2503 use PVE
::JSONSchema
qw(get_standard_option);
2505 use base
qw(PVE::RESTHandler);
2507 __PACKAGE__-
>register_method ({
2508 subclass
=> "PVE::API2::Nodes::Nodeinfo",
2512 __PACKAGE__-
>register_method ({
2516 permissions
=> { user
=> 'all' },
2517 description
=> "Cluster node index.",
2519 additionalProperties
=> 0,
2527 node
=> get_standard_option
('pve-node'),
2529 description
=> "Node status.",
2531 enum
=> ['unknown', 'online', 'offline'],
2534 description
=> "CPU utilization.",
2537 renderer
=> 'fraction_as_percentage',
2540 description
=> "Number of available CPUs.",
2545 description
=> "Used memory in bytes.",
2548 renderer
=> 'bytes',
2551 description
=> "Number of available memory in bytes.",
2554 renderer
=> 'bytes',
2557 description
=> "Support level.",
2562 description
=> "Node uptime in seconds.",
2565 renderer
=> 'duration',
2567 ssl_fingerprint
=> {
2568 description
=> "The SSL fingerprint for the node certificate.",
2574 links
=> [ { rel
=> 'child', href
=> "{node}" } ],
2579 my $rpcenv = PVE
::RPCEnvironment
::get
();
2580 my $authuser = $rpcenv->get_user();
2582 my $clinfo = PVE
::Cluster
::get_clinfo
();
2585 my $nodelist = PVE
::Cluster
::get_nodelist
();
2586 my $members = PVE
::Cluster
::get_members
();
2587 my $rrd = PVE
::Cluster
::rrd_dump
();
2589 foreach my $node (@$nodelist) {
2590 my $can_audit = $rpcenv->check($authuser, "/nodes/$node", [ 'Sys.Audit' ], 1);
2591 my $entry = PVE
::API2Tools
::extract_node_stats
($node, $members, $rrd, !$can_audit);
2593 $entry->{ssl_fingerprint
} = eval { PVE
::Cluster
::get_node_fingerprint
($node) };