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
::RPCEnvironment
;
41 use PVE
::API2
::Capabilities
;
43 use PVE
::API2
::Certificates
;
45 use PVE
::API2
::Firewall
::Host
;
46 use PVE
::API2
::Hardware
;
47 use PVE
::API2
::LXC
::Status
;
49 use PVE
::API2
::Network
;
50 use PVE
::API2
::NodeConfig
;
51 use PVE
::API2
::Qemu
::CPU
;
53 use PVE
::API2
::Replication
;
54 use PVE
::API2
::Services
;
55 use PVE
::API2
::Storage
::Scan
;
56 use PVE
::API2
::Storage
::Status
;
57 use PVE
::API2
::Subscription
;
59 use PVE
::API2
::VZDump
;
63 require PVE
::API2
::Network
::SDN
::Zones
::Status
;
67 use base
qw(PVE::RESTHandler);
69 my $verify_command_item_desc = {
70 description
=> "An array of objects describing endpoints, methods and arguments.",
76 description
=> "A relative path to an API endpoint on this node.",
81 description
=> "A method related to the API endpoint (GET, POST etc.).",
83 pattern
=> "(GET|POST|PUT|DELETE)",
87 description
=> "A set of parameter names and their values.",
95 PVE
::JSONSchema
::register_format
('pve-command-batch', \
&verify_command_batch
);
96 sub verify_command_batch
{
97 my ($value, $noerr) = @_;
98 my $commands = eval { decode_json
($value); };
100 return if $noerr && $@;
101 die "commands param did not contain valid JSON: $@" if $@;
103 eval { PVE
::JSONSchema
::validate
($commands, $verify_command_item_desc) };
105 return $commands if !$@;
108 die "commands is not a valid array of commands: $@";
111 __PACKAGE__-
>register_method ({
112 subclass
=> "PVE::API2::Qemu",
116 __PACKAGE__-
>register_method ({
117 subclass
=> "PVE::API2::LXC",
121 __PACKAGE__-
>register_method ({
122 subclass
=> "PVE::API2::Ceph",
126 __PACKAGE__-
>register_method ({
127 subclass
=> "PVE::API2::VZDump",
131 __PACKAGE__-
>register_method ({
132 subclass
=> "PVE::API2::Services",
136 __PACKAGE__-
>register_method ({
137 subclass
=> "PVE::API2::Subscription",
138 path
=> 'subscription',
141 __PACKAGE__-
>register_method ({
142 subclass
=> "PVE::API2::Network",
146 __PACKAGE__-
>register_method ({
147 subclass
=> "PVE::API2::Tasks",
151 __PACKAGE__-
>register_method ({
152 subclass
=> "PVE::API2::Storage::Scan",
156 __PACKAGE__-
>register_method ({
157 subclass
=> "PVE::API2::Hardware",
161 __PACKAGE__-
>register_method ({
162 subclass
=> "PVE::API2::Capabilities",
163 path
=> 'capabilities',
166 __PACKAGE__-
>register_method ({
167 subclass
=> "PVE::API2::Storage::Status",
171 __PACKAGE__-
>register_method ({
172 subclass
=> "PVE::API2::Disks",
176 __PACKAGE__-
>register_method ({
177 subclass
=> "PVE::API2::APT",
181 __PACKAGE__-
>register_method ({
182 subclass
=> "PVE::API2::Firewall::Host",
186 __PACKAGE__-
>register_method ({
187 subclass
=> "PVE::API2::Replication",
188 path
=> 'replication',
191 __PACKAGE__-
>register_method ({
192 subclass
=> "PVE::API2::Certificates",
193 path
=> 'certificates',
197 __PACKAGE__-
>register_method ({
198 subclass
=> "PVE::API2::NodeConfig",
203 __PACKAGE__-
>register_method ({
204 subclass
=> "PVE::API2::Network::SDN::Zones::Status",
208 __PACKAGE__-
>register_method ({
212 permissions
=> { user
=> 'all' },
213 description
=> "SDN index.",
215 additionalProperties
=> 0,
217 node
=> get_standard_option
('pve-node'),
226 links
=> [ { rel
=> 'child', href
=> "{name}" } ],
238 __PACKAGE__-
>register_method ({
242 permissions
=> { user
=> 'all' },
243 description
=> "Node index.",
245 additionalProperties
=> 0,
247 node
=> get_standard_option
('pve-node'),
256 links
=> [ { rel
=> 'child', href
=> "{name}" } ],
262 { name
=> 'aplinfo' },
264 { name
=> 'capabilities' },
266 { name
=> 'certificates' },
267 { name
=> 'config' },
270 { name
=> 'firewall' },
271 { name
=> 'hardware' },
273 { name
=> 'journal' },
275 { name
=> 'migrateall' },
276 { name
=> 'netstat' },
277 { name
=> 'network' },
279 { name
=> 'query-url-metadata' },
280 { name
=> 'replication' },
281 { name
=> 'report' },
282 { name
=> 'rrd' }, # fixme: remove?
283 { name
=> 'rrddata' },# fixme: remove?
285 { name
=> 'services' },
286 { name
=> 'spiceshell' },
287 { name
=> 'startall' },
288 { name
=> 'status' },
289 { name
=> 'stopall' },
290 { name
=> 'storage' },
291 { name
=> 'subscription' },
292 { name
=> 'suspendall' },
293 { name
=> 'syslog' },
295 { name
=> 'termproxy' },
297 { name
=> 'version' },
298 { name
=> 'vncshell' },
299 { name
=> 'vzdump' },
300 { name
=> 'wakeonlan' },
303 push @$result, { name
=> 'sdn' } if $have_sdn;
308 __PACKAGE__-
>register_method ({
313 permissions
=> { user
=> 'all' },
314 description
=> "API version details",
316 additionalProperties
=> 0,
318 node
=> get_standard_option
('pve-node'),
326 description
=> 'The current installed pve-manager package version',
330 description
=> 'The current installed Proxmox VE Release',
334 description
=> 'The short git commit hash ID from which this version was build',
339 my ($resp, $param) = @_;
341 return PVE
::pvecfg
::version_info
();
344 __PACKAGE__-
>register_method({
349 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
351 description
=> "Read node status",
354 additionalProperties
=> 0,
356 node
=> get_standard_option
('pve-node'),
373 my ($uptime, $idle) = PVE
::ProcFSTools
::read_proc_uptime
();
374 $res->{uptime
} = $uptime;
376 my ($avg1, $avg5, $avg15) = PVE
::ProcFSTools
::read_loadavg
();
377 $res->{loadavg
} = [ $avg1, $avg5, $avg15];
379 my ($sysname, $nodename, $release, $version, $machine) = POSIX
::uname
();
381 $res->{kversion
} = "$sysname $release $version";
383 $res->{cpuinfo
} = PVE
::ProcFSTools
::read_cpuinfo
();
385 my $stat = PVE
::ProcFSTools
::read_proc_stat
();
386 $res->{cpu
} = $stat->{cpu
};
387 $res->{wait} = $stat->{wait};
389 my $meminfo = PVE
::ProcFSTools
::read_meminfo
();
391 free
=> $meminfo->{memfree
},
392 total
=> $meminfo->{memtotal
},
393 used
=> $meminfo->{memused
},
397 shared
=> $meminfo->{memshared
},
401 free
=> $meminfo->{swapfree
},
402 total
=> $meminfo->{swaptotal
},
403 used
=> $meminfo->{swapused
},
406 $res->{pveversion
} = PVE
::pvecfg
::package() . "/" .
407 PVE
::pvecfg
::version_text
();
409 my $dinfo = df
('/', 1); # output is bytes
412 total
=> $dinfo->{blocks
},
413 avail
=> $dinfo->{bavail
},
414 used
=> $dinfo->{used
},
415 free
=> $dinfo->{blocks
} - $dinfo->{used
},
421 __PACKAGE__-
>register_method({
426 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
428 description
=> "Read tap/vm network device interface counters",
431 additionalProperties
=> 0,
433 node
=> get_standard_option
('pve-node'),
448 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
449 foreach my $dev (sort keys %$netdev) {
450 next if $dev !~ m/^(?:tap|veth)([1-9]\d*)i(\d+)$/;
451 my ($vmid, $netid) = ($1, $2);
456 in => $netdev->{$dev}->{transmit
},
457 out
=> $netdev->{$dev}->{receive
},
464 __PACKAGE__-
>register_method({
468 description
=> "Execute multiple commands in order, root only.",
470 protected
=> 1, # avoid problems with proxy code
472 additionalProperties
=> 0,
474 node
=> get_standard_option
('pve-node'),
476 description
=> "JSON encoded array of commands.",
478 verbose_description
=> "JSON encoded array of commands, where each command is an object with the following properties:\n"
479 . PVE
::RESTHandler
::dump_properties
($verify_command_item_desc->{items
}->{properties
}, 'full'),
480 format
=> "pve-command-batch",
495 my $rpcenv = PVE
::RPCEnvironment
::get
();
496 my $user = $rpcenv->get_user();
497 # just parse the json again, it should already be validated
498 my $commands = eval { decode_json
($param->{commands
}); };
500 foreach my $cmd (@$commands) {
504 my $path = "nodes/$param->{node}/$cmd->{path}";
507 my ($handler, $info) = PVE
::API2-
>find_handler($cmd->{method}, $path, $uri_param);
508 if (!$handler || !$info) {
509 die "no handler for '$path'\n";
512 foreach my $p (keys %{$cmd->{args
}}) {
513 raise_param_exc
({ $p => "duplicate parameter" }) if defined($uri_param->{$p});
514 $uri_param->{$p} = $cmd->{args
}->{$p};
517 # check access permissions
518 $rpcenv->check_api2_permissions($info->{permissions
}, $user, $uri_param);
522 data
=> $handler->handle($info, $uri_param),
526 my $resp = { status
=> HTTP_INTERNAL_SERVER_ERROR
};
527 if (ref($err) eq "PVE::Exception") {
528 $resp->{status
} = $err->{code
} if $err->{code
};
529 $resp->{errors
} = $err->{errors
} if $err->{errors
};
530 $resp->{message
} = $err->{msg
};
532 $resp->{message
} = $err;
542 __PACKAGE__-
>register_method({
547 check
=> ['perm', '/nodes/{node}', [ 'Sys.PowerMgmt' ]],
550 description
=> "Reboot or shutdown a node.",
553 additionalProperties
=> 0,
555 node
=> get_standard_option
('pve-node'),
557 description
=> "Specify the command.",
559 enum
=> [qw(reboot shutdown)],
563 returns
=> { type
=> "null" },
567 if ($param->{command
} eq 'reboot') {
568 system ("(sleep 2;/sbin/reboot)&");
569 } elsif ($param->{command
} eq 'shutdown') {
570 system ("(sleep 2;/sbin/poweroff)&");
576 __PACKAGE__-
>register_method({
581 check
=> ['perm', '/nodes/{node}', [ 'Sys.PowerMgmt' ]],
584 description
=> "Try to wake a node via 'wake on LAN' network packet.",
586 additionalProperties
=> 0,
588 node
=> get_standard_option
('pve-node', {
589 description
=> 'target node for wake on LAN packet',
591 my $members = PVE
::Cluster
::get_members
();
592 return [ grep { !$members->{$_}->{online
} } keys %$members ];
599 format
=> 'mac-addr',
600 description
=> 'MAC address used to assemble the WoL magic packet.',
605 my $node = $param->{node
};
607 die "'$node' is local node, cannot wake my self!\n"
608 if $node eq 'localhost' || $node eq PVE
::INotify
::nodename
();
610 PVE
::Cluster
::check_node_exists
($node);
612 my $config = PVE
::NodeConfig
::load_config
($node);
613 my $mac_addr = $config->{wakeonlan
};
614 if (!defined($mac_addr)) {
615 die "No wake on LAN MAC address defined for '$node'!\n";
619 my $packet = chr(0xff) x
6 . pack('H*', $mac_addr) x
16;
621 my $addr = gethostbyname('255.255.255.255');
622 my $port = getservbyname('discard', 'udp');
623 my $to = Socket
::pack_sockaddr_in
($port, $addr);
625 socket(my $sock, Socket
::AF_INET
, Socket
::SOCK_DGRAM
, Socket
::IPPROTO_UDP
)
626 || die "Unable to open socket: $!\n";
627 setsockopt($sock, Socket
::SOL_SOCKET
, Socket
::SO_BROADCAST
, 1)
628 || die "Unable to set socket option: $!\n";
630 send($sock, $packet, 0, $to)
631 || die "Unable to send packet: $!\n";
635 return $config->{wakeonlan
};
638 __PACKAGE__-
>register_method({
642 protected
=> 1, # fixme: can we avoid that?
644 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
646 description
=> "Read node RRD statistics (returns PNG)",
648 additionalProperties
=> 0,
650 node
=> get_standard_option
('pve-node'),
652 description
=> "Specify the time frame you are interested in.",
654 enum
=> [ 'hour', 'day', 'week', 'month', 'year' ],
657 description
=> "The list of datasources you want to display.",
658 type
=> 'string', format
=> 'pve-configid-list',
661 description
=> "The RRD consolidation function",
663 enum
=> [ 'AVERAGE', 'MAX' ],
671 filename
=> { type
=> 'string' },
677 return PVE
::RRD
::create_rrd_graph
(
678 "pve2-node/$param->{node}", $param->{timeframe
},
679 $param->{ds
}, $param->{cf
});
683 __PACKAGE__-
>register_method({
687 protected
=> 1, # fixme: can we avoid that?
689 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
691 description
=> "Read node RRD statistics",
693 additionalProperties
=> 0,
695 node
=> get_standard_option
('pve-node'),
697 description
=> "Specify the time frame you are interested in.",
699 enum
=> [ 'hour', 'day', 'week', 'month', 'year' ],
702 description
=> "The RRD consolidation function",
704 enum
=> [ 'AVERAGE', 'MAX' ],
719 return PVE
::RRD
::create_rrd_data
(
720 "pve2-node/$param->{node}", $param->{timeframe
}, $param->{cf
});
723 __PACKAGE__-
>register_method({
727 description
=> "Read system log",
730 check
=> ['perm', '/nodes/{node}', [ 'Sys.Syslog' ]],
734 additionalProperties
=> 0,
736 node
=> get_standard_option
('pve-node'),
749 pattern
=> '^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}(:\d{2})?)?$',
750 description
=> "Display all log since this date-time string.",
755 pattern
=> '^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}(:\d{2})?)?$',
756 description
=> "Display all log until this date-time string.",
760 description
=> "Service ID",
773 description
=> "Line number",
777 description
=> "Line text",
786 my $rpcenv = PVE
::RPCEnvironment
::get
();
787 my $user = $rpcenv->get_user();
788 my $node = $param->{node
};
791 if ($param->{service
}) {
792 my $service_aliases = {
793 'postfix' => 'postfix@-',
796 $service = $service_aliases->{$param->{service
}} // $param->{service
};
799 my ($count, $lines) = PVE
::Tools
::dump_journal
($param->{start
}, $param->{limit
},
800 $param->{since
}, $param->{until}, $service);
802 $rpcenv->set_result_attrib('total', $count);
807 __PACKAGE__-
>register_method({
811 description
=> "Read Journal",
814 check
=> ['perm', '/nodes/{node}', [ 'Sys.Syslog' ]],
818 additionalProperties
=> 0,
820 node
=> get_standard_option
('pve-node'),
824 description
=> "Display all log since this UNIX epoch. Conflicts with 'startcursor'.",
830 description
=> "Display all log until this UNIX epoch. Conflicts with 'endcursor'.",
834 description
=> "Limit to the last X lines. Conflicts with a range.",
840 description
=> "Start after the given Cursor. Conflicts with 'since'",
845 description
=> "End before the given Cursor. Conflicts with 'until'",
860 my $rpcenv = PVE
::RPCEnvironment
::get
();
861 my $user = $rpcenv->get_user();
863 my $cmd = ["/usr/bin/mini-journalreader", "-j"];
864 push @$cmd, '-n', $param->{lastentries
} if $param->{lastentries
};
865 push @$cmd, '-b', $param->{since
} if $param->{since
};
866 push @$cmd, '-e', $param->{until} if $param->{until};
867 push @$cmd, '-f', PVE
::Tools
::shellquote
($param->{startcursor
}) if $param->{startcursor
};
868 push @$cmd, '-t', PVE
::Tools
::shellquote
($param->{endcursor
}) if $param->{endcursor
};
869 push @$cmd, ' | gzip ';
871 open(my $fh, "-|", join(' ', @$cmd))
872 or die "could not start mini-journalreader";
878 'content-type' => 'application/json',
879 'content-encoding' => 'gzip',
886 my $shell_cmd_map = {
888 cmd
=> [ '/bin/login', '-f', 'root' ],
891 cmd
=> [ '/usr/bin/pveupgrade', '--shell' ],
894 cmd
=> [ '/usr/bin/pveceph', 'install' ],
899 sub get_shell_command
{
900 my ($user, $shellcmd, $args) = @_;
903 if ($user eq 'root@pam') {
904 if (defined($shellcmd) && exists($shell_cmd_map->{$shellcmd})) {
905 my $def = $shell_cmd_map->{$shellcmd};
906 $cmd = [ @{$def->{cmd
}} ]; # clone
907 if (defined($args) && $def->{allow_args
}) {
908 push @$cmd, split("\0", $args);
911 $cmd = [ '/bin/login', '-f', 'root' ];
914 # non-root must always login for now, we do not have a superuser role!
915 $cmd = [ '/bin/login' ];
920 my $get_vnc_connection_info = sub {
925 my ($remip, $family);
926 if ($node ne 'localhost' && $node ne PVE
::INotify
::nodename
()) {
927 ($remip, $family) = PVE
::Cluster
::remote_node_ip
($node);
928 $remote_cmd = ['/usr/bin/ssh', '-e', 'none', '-t', $remip , '--'];
930 $family = PVE
::Tools
::get_host_address_family
($node);
932 my $port = PVE
::Tools
::next_vnc_port
($family);
934 return ($port, $remote_cmd);
937 __PACKAGE__-
>register_method ({
943 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
945 description
=> "Creates a VNC Shell proxy.",
947 additionalProperties
=> 0,
949 node
=> get_standard_option
('pve-node'),
952 description
=> "Run specific command or default to login (requires 'root\@pam')",
953 enum
=> [keys %$shell_cmd_map],
959 description
=> "Add parameters to a command. Encoded as null terminated strings.",
967 description
=> "use websocket instead of standard vnc.",
971 description
=> "sets the width of the console in pixels.",
978 description
=> "sets the height of the console in pixels.",
986 additionalProperties
=> 0,
988 user
=> { type
=> 'string' },
989 ticket
=> { type
=> 'string' },
990 cert
=> { type
=> 'string' },
991 port
=> { type
=> 'integer' },
992 upid
=> { type
=> 'string' },
998 my $rpcenv = PVE
::RPCEnvironment
::get
();
999 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($rpcenv->get_user());
1002 if (defined($param->{cmd
}) && $param->{cmd
} ne 'login' && $user ne 'root@pam') {
1003 raise_perm_exc
('user != root@pam');
1006 my $node = $param->{node
};
1008 my $authpath = "/nodes/$node";
1009 my $ticket = PVE
::AccessControl
::assemble_vnc_ticket
($user, $authpath);
1011 $sslcert = PVE
::Tools
::file_get_contents
("/etc/pve/pve-root-ca.pem", 8192)
1014 my ($port, $remcmd) = $get_vnc_connection_info->($node);
1016 my $shcmd = get_shell_command
($user, $param->{cmd
}, $param->{'cmd-opts'});
1020 my $cmd = ['/usr/bin/vncterm',
1022 '-timeout', $timeout,
1023 '-authpath', $authpath,
1024 '-perm', 'Sys.Console',
1027 push @$cmd, '-width', $param->{width
} if $param->{width
};
1028 push @$cmd, '-height', $param->{height
} if $param->{height
};
1030 if ($param->{websocket
}) {
1031 $ENV{PVE_VNC_TICKET
} = $ticket; # pass ticket to vncterm
1032 push @$cmd, '-notls', '-listen', 'localhost';
1035 push @$cmd, '-c', @$remcmd, @$shcmd;
1040 syslog
('info', "starting vnc proxy $upid\n");
1042 my $cmdstr = join (' ', @$cmd);
1043 syslog
('info', "launch command: $cmdstr");
1046 foreach my $k (keys %ENV) {
1047 next if $k eq 'PVE_VNC_TICKET';
1048 next if $k eq 'PATH' || $k eq 'TERM' || $k eq 'USER' || $k eq 'HOME' || $k eq 'LANG' || $k eq 'LANGUAGE';
1053 PVE
::Tools
::run_command
($cmd, errmsg
=> "vncterm failed", keeplocale
=> 1);
1056 syslog
('err', $err);
1062 my $upid = $rpcenv->fork_worker('vncshell', "", $user, $realcmd);
1064 PVE
::Tools
::wait_for_vnc_port
($port);
1075 __PACKAGE__-
>register_method ({
1076 name
=> 'termproxy',
1077 path
=> 'termproxy',
1081 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
1083 description
=> "Creates a VNC Shell proxy.",
1085 additionalProperties
=> 0,
1087 node
=> get_standard_option
('pve-node'),
1090 description
=> "Run specific command or default to login (requires 'root\@pam')",
1091 enum
=> [keys %$shell_cmd_map],
1097 description
=> "Add parameters to a command. Encoded as null terminated strings.",
1105 additionalProperties
=> 0,
1107 user
=> { type
=> 'string' },
1108 ticket
=> { type
=> 'string' },
1109 port
=> { type
=> 'integer' },
1110 upid
=> { type
=> 'string' },
1116 my $rpcenv = PVE
::RPCEnvironment
::get
();
1117 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($rpcenv->get_user());
1119 my $node = $param->{node
};
1120 my $authpath = "/nodes/$node";
1121 my $ticket = PVE
::AccessControl
::assemble_vnc_ticket
($user, $authpath);
1123 my ($port, $remcmd) = $get_vnc_connection_info->($node);
1125 my $shcmd = get_shell_command
($user, $param->{cmd
}, $param->{'cmd-opts'});
1130 syslog
('info', "starting termproxy $upid\n");
1133 '/usr/bin/termproxy',
1135 '--path', $authpath,
1136 '--perm', 'Sys.Console',
1139 push @$cmd, @$remcmd, @$shcmd;
1141 PVE
::Tools
::run_command
($cmd);
1143 my $upid = $rpcenv->fork_worker('vncshell', "", $user, $realcmd);
1145 PVE
::Tools
::wait_for_vnc_port
($port);
1155 __PACKAGE__-
>register_method({
1156 name
=> 'vncwebsocket',
1157 path
=> 'vncwebsocket',
1160 description
=> "You also need to pass a valid ticket (vncticket).",
1161 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
1163 description
=> "Opens a websocket for VNC traffic.",
1165 additionalProperties
=> 0,
1167 node
=> get_standard_option
('pve-node'),
1169 description
=> "Ticket from previous call to vncproxy.",
1174 description
=> "Port number returned by previous vncproxy call.",
1184 port
=> { type
=> 'string' },
1190 my $rpcenv = PVE
::RPCEnvironment
::get
();
1192 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($rpcenv->get_user());
1194 my $authpath = "/nodes/$param->{node}";
1196 PVE
::AccessControl
::verify_vnc_ticket
($param->{vncticket
}, $user, $authpath);
1198 my $port = $param->{port
};
1200 return { port
=> $port };
1203 __PACKAGE__-
>register_method ({
1204 name
=> 'spiceshell',
1205 path
=> 'spiceshell',
1210 check
=> ['perm', '/nodes/{node}', [ 'Sys.Console' ]],
1212 description
=> "Creates a SPICE shell.",
1214 additionalProperties
=> 0,
1216 node
=> get_standard_option
('pve-node'),
1217 proxy
=> get_standard_option
('spice-proxy', { optional
=> 1 }),
1220 description
=> "Run specific command or default to login (requires 'root\@pam')",
1221 enum
=> [keys %$shell_cmd_map],
1227 description
=> "Add parameters to a command. Encoded as null terminated strings.",
1234 returns
=> get_standard_option
('remote-viewer-config'),
1238 my $rpcenv = PVE
::RPCEnvironment
::get
();
1239 my $authuser = $rpcenv->get_user();
1241 my ($user, undef, $realm) = PVE
::AccessControl
::verify_username
($authuser);
1244 if (defined($param->{cmd
}) && $param->{cmd
} ne 'login' && $user ne 'root@pam') {
1245 raise_perm_exc
('user != root@pam');
1248 my $node = $param->{node
};
1249 my $proxy = $param->{proxy
};
1251 my $authpath = "/nodes/$node";
1252 my $permissions = 'Sys.Console';
1254 my $shcmd = get_shell_command
($user, $param->{cmd
}, $param->{'cmd-opts'});
1256 my $title = "Shell on '$node'";
1258 return PVE
::API2Tools
::run_spiceterm
($authpath, $permissions, 0, $node, $proxy, $title, $shcmd);
1261 __PACKAGE__-
>register_method({
1266 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1268 description
=> "Read DNS settings.",
1271 additionalProperties
=> 0,
1273 node
=> get_standard_option
('pve-node'),
1278 additionalProperties
=> 0,
1281 description
=> "Search domain for host-name lookup.",
1286 description
=> 'First name server IP address.',
1291 description
=> 'Second name server IP address.',
1296 description
=> 'Third name server IP address.',
1305 my $res = PVE
::INotify
::read_file
('resolvconf');
1310 __PACKAGE__-
>register_method({
1311 name
=> 'update_dns',
1314 description
=> "Write DNS settings.",
1316 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1321 additionalProperties
=> 0,
1323 node
=> get_standard_option
('pve-node'),
1325 description
=> "Search domain for host-name lookup.",
1329 description
=> 'First name server IP address.',
1330 type
=> 'string', format
=> 'ip',
1334 description
=> 'Second name server IP address.',
1335 type
=> 'string', format
=> 'ip',
1339 description
=> 'Third name server IP address.',
1340 type
=> 'string', format
=> 'ip',
1345 returns
=> { type
=> "null" },
1349 PVE
::INotify
::update_file
('resolvconf', $param);
1354 __PACKAGE__-
>register_method({
1359 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1361 description
=> "Read server time and time zone settings.",
1364 additionalProperties
=> 0,
1366 node
=> get_standard_option
('pve-node'),
1371 additionalProperties
=> 0,
1374 description
=> "Time zone",
1378 description
=> "Seconds since 1970-01-01 00:00:00 UTC.",
1380 minimum
=> 1297163644,
1381 renderer
=> 'timestamp',
1384 description
=> "Seconds since 1970-01-01 00:00:00 (local time)",
1386 minimum
=> 1297163644,
1387 renderer
=> 'timestamp_gmt',
1395 my $ltime = timegm_nocheck
(localtime($ctime));
1397 timezone
=> PVE
::INotify
::read_file
('timezone'),
1399 localtime => $ltime,
1405 __PACKAGE__-
>register_method({
1406 name
=> 'set_timezone',
1409 description
=> "Set time zone.",
1411 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
1416 additionalProperties
=> 0,
1418 node
=> get_standard_option
('pve-node'),
1420 description
=> "Time zone. The file '/usr/share/zoneinfo/zone.tab' contains the list of valid names.",
1425 returns
=> { type
=> "null" },
1429 PVE
::INotify
::write_file
('timezone', $param->{timezone
});
1434 __PACKAGE__-
>register_method({
1441 description
=> "Get list of appliances.",
1444 additionalProperties
=> 0,
1446 node
=> get_standard_option
('pve-node'),
1459 my $list = PVE
::APLInfo
::load_data
();
1462 for my $appliance (values %{$list->{all
}}) {
1463 next if $appliance->{'package'} eq 'pve-web-news';
1464 push @$res, $appliance;
1470 __PACKAGE__-
>register_method({
1471 name
=> 'apl_download',
1475 check
=> ['perm', '/storage/{storage}', ['Datastore.AllocateTemplate']],
1477 description
=> "Download appliance templates.",
1481 additionalProperties
=> 0,
1483 node
=> get_standard_option
('pve-node'),
1484 storage
=> get_standard_option
('pve-storage-id', {
1485 description
=> "The storage where the template will be stored",
1486 completion
=> \
&PVE
::Storage
::complete_storage_enabled
,
1490 description
=> "The template which will downloaded",
1492 completion
=> \
&complete_templet_repo
,
1496 returns
=> { type
=> "string" },
1500 my $rpcenv = PVE
::RPCEnvironment
::get
();
1501 my $user = $rpcenv->get_user();
1503 my $node = $param->{node
};
1504 my $template = $param->{template
};
1506 my $list = PVE
::APLInfo
::load_data
();
1507 my $appliance = $list->{all
}->{$template};
1508 raise_param_exc
({ template
=> "no such template"}) if !$appliance;
1510 my $cfg = PVE
::Storage
::config
();
1511 my $scfg = PVE
::Storage
::storage_check_enabled
($cfg, $param->{storage
}, $node);
1513 die "unknown template type '$appliance->{type}'\n"
1514 if !($appliance->{type
} eq 'openvz' || $appliance->{type
} eq 'lxc');
1516 die "storage '$param->{storage}' does not support templates\n"
1517 if !$scfg->{content
}->{vztmpl
};
1519 my $tmpldir = PVE
::Storage
::get_vztmpl_dir
($cfg, $param->{storage
});
1522 my $dccfg = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
1524 PVE
::Tools
::download_file_from_url
("$tmpldir/$template", $appliance->{location
}, {
1526 sha512sum
=> $appliance->{sha512sum
},
1527 md5sum
=> $appliance->{md5sum
},
1528 http_proxy
=> $dccfg->{http_proxy
},
1532 my $upid = $rpcenv->fork_worker('download', $template, $user, $worker);
1537 __PACKAGE__-
>register_method({
1538 name
=> 'query_url_metadata',
1539 path
=> 'query-url-metadata',
1541 description
=> "Query metadata of an URL: file size, file name and mime type.",
1544 check
=> ['perm', '/', [ 'Sys.Audit', 'Sys.Modify' ]],
1547 additionalProperties
=> 0,
1549 node
=> get_standard_option
('pve-node'),
1551 description
=> "The URL to query the metadata from.",
1553 pattern
=> 'https?://.*',
1555 'verify-certificates' => {
1556 description
=> "If false, no SSL/TLS certificates will be verified.",
1572 renderer
=> 'bytes',
1584 my $url = $param->{url
};
1586 my $ua = LWP
::UserAgent-
>new();
1587 $ua->agent("Proxmox VE");
1589 my $dccfg = PVE
::Cluster
::cfs_read_file
('datacenter.cfg');
1590 if ($dccfg->{http_proxy
}) {
1591 $ua->proxy('http', $dccfg->{http_proxy
});
1594 my $verify = $param->{'verify-certificates'} // 1;
1597 verify_hostname
=> 0,
1598 SSL_verify_mode
=> IO
::Socket
::SSL
::SSL_VERIFY_NONE
,
1602 my $req = HTTP
::Request-
>new(HEAD
=> $url);
1603 my $res = $ua->request($req);
1605 die "invalid server response: '" . $res->status_line() . "'\n" if ($res->code() != 200);
1607 my $size = $res->header("Content-Length");
1608 my $disposition = $res->header("Content-Disposition");
1609 my $type = $res->header("Content-Type");
1613 if ($disposition && ($disposition =~ m/filename="([^"]*)"/ || $disposition =~ m/filename=([^;]*)/)) {
1615 } elsif ($url =~ m!^[^?]+/([^?/]*)(?:\?.*)?$!) {
1619 # Content-Type: text/html; charset=utf-8
1620 if ($type && $type =~ m/^([^;]+);/) {
1625 $ret->{filename
} = $filename if $filename;
1626 $ret->{size
} = $size + 0 if $size;
1627 $ret->{mimetype
} = $type if $type;
1632 __PACKAGE__-
>register_method({
1637 check
=> ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
1640 description
=> "Gather various systems information about a node",
1643 additionalProperties
=> 0,
1645 node
=> get_standard_option
('pve-node'),
1652 return PVE
::Report
::generate
();
1655 # returns a list of VMIDs, those can be filtered by
1656 # * current parent node
1658 # * guest is a template (default: skip)
1659 # * guest is HA manged (default: skip)
1660 my $get_filtered_vmlist = sub {
1661 my ($nodename, $vmfilter, $templates, $ha_managed) = @_;
1663 my $vmlist = PVE
::Cluster
::get_vmlist
();
1666 if (defined($vmfilter)) {
1667 $vms_allowed = { map { $_ => 1 } PVE
::Tools
::split_list
($vmfilter) };
1671 foreach my $vmid (keys %{$vmlist->{ids
}}) {
1672 next if defined($vms_allowed) && !$vms_allowed->{$vmid};
1674 my $d = $vmlist->{ids
}->{$vmid};
1675 next if $nodename && $d->{node
} ne $nodename;
1679 if ($d->{type
} eq 'lxc') {
1680 $class = 'PVE::LXC::Config';
1681 } elsif ($d->{type
} eq 'qemu') {
1682 $class = 'PVE::QemuConfig';
1684 die "unknown virtual guest type '$d->{type}'\n";
1687 my $conf = $class->load_config($vmid);
1688 return if !$templates && $class->is_template($conf);
1689 return if !$ha_managed && PVE
::HA
::Config
::vm_is_ha_managed
($vmid);
1691 $res->{$vmid}->{conf
} = $conf;
1692 $res->{$vmid}->{type
} = $d->{type
};
1693 $res->{$vmid}->{class} = $class;
1701 # return all VMs which should get started/stopped on power up/down
1702 my $get_start_stop_list = sub {
1703 my ($nodename, $autostart, $vmfilter) = @_;
1705 # do not skip HA vms on force or if a specific VMID set is wanted
1706 my $include_ha_managed = defined($vmfilter) ?
1 : 0;
1708 my $vmlist = $get_filtered_vmlist->($nodename, $vmfilter, undef, $include_ha_managed);
1711 foreach my $vmid (keys %$vmlist) {
1712 my $conf = $vmlist->{$vmid}->{conf
};
1713 next if $autostart && !$conf->{onboot
};
1715 my $startup = $conf->{startup
} ? PVE
::JSONSchema
::pve_parse_startup_order
($conf->{startup
}) : {};
1716 my $order = $startup->{order
} = $startup->{order
} // LONG_MAX
;
1718 $resList->{$order}->{$vmid} = $startup;
1719 $resList->{$order}->{$vmid}->{type
} = $vmlist->{$vmid}->{type
};
1725 my $remove_locks_on_startup = sub {
1726 my ($nodename) = @_;
1728 my $vmlist = &$get_filtered_vmlist($nodename, undef, undef, 1);
1730 foreach my $vmid (keys %$vmlist) {
1731 my $conf = $vmlist->{$vmid}->{conf
};
1732 my $class = $vmlist->{$vmid}->{class};
1735 if ($class->has_lock($conf, 'backup')) {
1736 $class->remove_lock($vmid, 'backup');
1737 my $msg = "removed left over backup lock from '$vmid'!";
1738 warn "$msg\n"; # prints to task log
1739 syslog
('warning', $msg);
1745 __PACKAGE__-
>register_method ({
1751 description
=> "The 'VM.PowerMgmt' permission is required on '/' or on '/vms/<ID>' for "
1752 ."each ID passed via the 'vms' parameter.",
1756 description
=> "Start all VMs and containers located on this node (by default only those with onboot=1).",
1758 additionalProperties
=> 0,
1760 node
=> get_standard_option
('pve-node'),
1765 description
=> "Issue start command even if virtual guest have 'onboot' not set or set to off.",
1768 description
=> "Only consider guests from this comma separated list of VMIDs.",
1769 type
=> 'string', format
=> 'pve-vmid-list',
1780 my $rpcenv = PVE
::RPCEnvironment
::get
();
1781 my $authuser = $rpcenv->get_user();
1783 if (!$rpcenv->check($authuser, "/", [ 'VM.PowerMgmt' ], 1)) {
1784 my @vms = PVE
::Tools
::split_list
($param->{vms
});
1785 if (scalar(@vms) > 0) {
1786 $rpcenv->check($authuser, "/vms/$_", [ 'VM.PowerMgmt' ]) for @vms;
1788 raise_perm_exc
("/, VM.PowerMgmt");
1792 my $nodename = $param->{node
};
1793 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
1795 my $force = $param->{force
};
1798 $rpcenv->{type
} = 'priv'; # to start tasks in background
1800 if (!PVE
::Cluster
::check_cfs_quorum
(1)) {
1801 print "waiting for quorum ...\n";
1804 } while (!PVE
::Cluster
::check_cfs_quorum
(1));
1805 print "got quorum\n";
1808 eval { # remove backup locks, but avoid running into a scheduled backup job
1809 PVE
::Tools
::lock_file
('/var/run/vzdump.lock', 10, $remove_locks_on_startup, $nodename);
1813 my $autostart = $force ?
undef : 1;
1814 my $startList = $get_start_stop_list->($nodename, $autostart, $param->{vms
});
1816 # Note: use numeric sorting with <=>
1817 for my $order (sort {$a <=> $b} keys %$startList) {
1818 my $vmlist = $startList->{$order};
1820 for my $vmid (sort {$a <=> $b} keys %$vmlist) {
1821 my $d = $vmlist->{$vmid};
1823 PVE
::Cluster
::check_cfs_quorum
(); # abort when we loose quorum
1826 my $default_delay = 0;
1829 if ($d->{type
} eq 'lxc') {
1830 return if PVE
::LXC
::check_running
($vmid);
1831 print STDERR
"Starting CT $vmid\n";
1832 $upid = PVE
::API2
::LXC
::Status-
>vm_start({node
=> $nodename, vmid
=> $vmid });
1833 } elsif ($d->{type
} eq 'qemu') {
1834 $default_delay = 3; # to reduce load
1835 return if PVE
::QemuServer
::check_running
($vmid, 1);
1836 print STDERR
"Starting VM $vmid\n";
1837 $upid = PVE
::API2
::Qemu-
>vm_start({node
=> $nodename, vmid
=> $vmid });
1839 die "unknown VM type '$d->{type}'\n";
1842 my $task = PVE
::Tools
::upid_decode
($upid);
1843 while (PVE
::ProcFSTools
::check_process_running
($task->{pid
})) {
1847 my $status = PVE
::Tools
::upid_read_status
($upid);
1848 if (!PVE
::Tools
::upid_status_is_error
($status)) {
1849 # use default delay to reduce load
1850 my $delay = defined($d->{up
}) ?
int($d->{up
}) : $default_delay;
1852 print STDERR
"Waiting for $delay seconds (startup delay)\n" if $d->{up
};
1853 for (my $i = 0; $i < $delay; $i++) {
1858 my $rendered_type = $d->{type
} eq 'lxc' ?
'CT' : 'VM';
1859 print STDERR
"Starting $rendered_type $vmid failed: $status\n";
1868 return $rpcenv->fork_worker('startall', undef, $authuser, $code);
1871 my $create_stop_worker = sub {
1872 my ($nodename, $type, $vmid, $timeout, $force_stop) = @_;
1874 if ($type eq 'lxc') {
1875 return if !PVE
::LXC
::check_running
($vmid);
1876 print STDERR
"Stopping CT $vmid (timeout = $timeout seconds)\n";
1877 return PVE
::API2
::LXC
::Status-
>vm_shutdown(
1878 { node
=> $nodename, vmid
=> $vmid, timeout
=> $timeout, forceStop
=> $force_stop }
1880 } elsif ($type eq 'qemu') {
1881 return if !PVE
::QemuServer
::check_running
($vmid, 1);
1882 print STDERR
"Stopping VM $vmid (timeout = $timeout seconds)\n";
1883 return PVE
::API2
::Qemu-
>vm_shutdown(
1884 { node
=> $nodename, vmid
=> $vmid, timeout
=> $timeout, forceStop
=> $force_stop }
1887 die "unknown VM type '$type'\n";
1891 __PACKAGE__-
>register_method ({
1897 description
=> "The 'VM.PowerMgmt' permission is required on '/' or on '/vms/<ID>' for "
1898 ."each ID passed via the 'vms' parameter.",
1902 description
=> "Stop all VMs and Containers.",
1904 additionalProperties
=> 0,
1906 node
=> get_standard_option
('pve-node'),
1908 description
=> "Only consider Guests with these IDs.",
1909 type
=> 'string', format
=> 'pve-vmid-list',
1913 description
=> 'Force a hard-stop after the timeout.',
1919 description
=> 'Timeout for each guest shutdown task. Depending on `force-stop`,'
1920 .' the shutdown gets then simply aborted or a hard-stop is forced.',
1925 maximum
=> 2 * 3600, # mostly arbitrary, but we do not want to high timeouts
1935 my $rpcenv = PVE
::RPCEnvironment
::get
();
1936 my $authuser = $rpcenv->get_user();
1938 if (!$rpcenv->check($authuser, "/", [ 'VM.PowerMgmt' ], 1)) {
1939 my @vms = PVE
::Tools
::split_list
($param->{vms
});
1940 if (scalar(@vms) > 0) {
1941 $rpcenv->check($authuser, "/vms/$_", [ 'VM.PowerMgmt' ]) for @vms;
1943 raise_perm_exc
("/, VM.PowerMgmt");
1947 my $nodename = $param->{node
};
1948 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
1952 $rpcenv->{type
} = 'priv'; # to start tasks in background
1954 my $stopList = $get_start_stop_list->($nodename, undef, $param->{vms
});
1956 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
1957 my $datacenterconfig = cfs_read_file
('datacenter.cfg');
1958 # if not set by user spawn max cpu count number of workers
1959 my $maxWorkers = $datacenterconfig->{max_workers
} || $cpuinfo->{cpus
};
1961 for my $order (sort {$b <=> $a} keys %$stopList) {
1962 my $vmlist = $stopList->{$order};
1965 my $finish_worker = sub {
1967 my $worker = delete $workers->{$pid} || return;
1969 syslog
('info', "end task $worker->{upid}");
1972 for my $vmid (sort {$b <=> $a} keys %$vmlist) {
1973 my $d = $vmlist->{$vmid};
1974 my $timeout = int($d->{down
} // $param->{timeout
} // 180);
1976 $create_stop_worker->(
1977 $nodename, $d->{type
}, $vmid, $timeout, $param->{'force-stop'} // 1)
1982 my $task = PVE
::Tools
::upid_decode
($upid, 1);
1985 my $pid = $task->{pid
};
1987 $workers->{$pid} = { type
=> $d->{type
}, upid
=> $upid, vmid
=> $vmid };
1988 while (scalar(keys %$workers) >= $maxWorkers) {
1989 foreach my $p (keys %$workers) {
1990 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
1991 $finish_worker->($p);
1997 while (scalar(keys %$workers)) {
1998 for my $p (keys %$workers) {
1999 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2000 $finish_worker->($p);
2007 syslog
('info', "all VMs and CTs stopped");
2012 return $rpcenv->fork_worker('stopall', undef, $authuser, $code);
2015 my $create_suspend_worker = sub {
2016 my ($nodename, $vmid) = @_;
2017 return if !PVE
::QemuServer
::check_running
($vmid, 1);
2018 print STDERR
"Suspending VM $vmid\n";
2019 return PVE
::API2
::Qemu-
>vm_suspend(
2020 { node
=> $nodename, vmid
=> $vmid, todisk
=> 1 }
2024 __PACKAGE__-
>register_method ({
2025 name
=> 'suspendall',
2026 path
=> 'suspendall',
2030 description
=> "The 'VM.PowerMgmt' permission is required on '/' or on '/vms/<ID>' for each"
2031 ." ID passed via the 'vms' parameter. Additionally, you need 'VM.Config.Disk' on the"
2032 ." '/vms/{vmid}' path and 'Datastore.AllocateSpace' for the configured state-storage(s)",
2036 description
=> "Suspend all VMs.",
2038 additionalProperties
=> 0,
2040 node
=> get_standard_option
('pve-node'),
2042 description
=> "Only consider Guests with these IDs.",
2043 type
=> 'string', format
=> 'pve-vmid-list',
2054 my $rpcenv = PVE
::RPCEnvironment
::get
();
2055 my $authuser = $rpcenv->get_user();
2057 # we cannot really check access to the state-storage here, that's happening per worker.
2058 if (!$rpcenv->check($authuser, "/", [ 'VM.PowerMgmt', 'VM.Config.Disk' ], 1)) {
2059 my @vms = PVE
::Tools
::split_list
($param->{vms
});
2060 if (scalar(@vms) > 0) {
2061 $rpcenv->check($authuser, "/vms/$_", [ 'VM.PowerMgmt' ]) for @vms;
2063 raise_perm_exc
("/, VM.PowerMgmt && VM.Config.Disk");
2067 my $nodename = $param->{node
};
2068 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
2072 $rpcenv->{type
} = 'priv'; # to start tasks in background
2074 my $stopList = $get_start_stop_list->($nodename, undef, $param->{vms
});
2076 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
2077 my $datacenterconfig = cfs_read_file
('datacenter.cfg');
2078 # if not set by user spawn max cpu count number of workers
2079 my $maxWorkers = $datacenterconfig->{max_workers
} || $cpuinfo->{cpus
};
2081 for my $order (sort {$b <=> $a} keys %$stopList) {
2082 my $vmlist = $stopList->{$order};
2085 my $finish_worker = sub {
2087 my $worker = delete $workers->{$pid} || return;
2089 syslog
('info', "end task $worker->{upid}");
2092 for my $vmid (sort {$b <=> $a} keys %$vmlist) {
2093 my $d = $vmlist->{$vmid};
2094 if ($d->{type
} eq 'lxc') {
2095 print STDERR
"Skipping $vmid, only VMs can be suspended\n";
2099 $create_suspend_worker->($nodename, $vmid)
2104 my $task = PVE
::Tools
::upid_decode
($upid, 1);
2107 my $pid = $task->{pid
};
2109 $workers->{$pid} = { type
=> $d->{type
}, upid
=> $upid, vmid
=> $vmid };
2110 while (scalar(keys %$workers) >= $maxWorkers) {
2111 foreach my $p (keys %$workers) {
2112 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2113 $finish_worker->($p);
2119 while (scalar(keys %$workers)) {
2120 for my $p (keys %$workers) {
2121 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2122 $finish_worker->($p);
2129 syslog
('info', "all VMs suspended");
2134 return $rpcenv->fork_worker('suspendall', undef, $authuser, $code);
2138 my $create_migrate_worker = sub {
2139 my ($nodename, $type, $vmid, $target, $with_local_disks) = @_;
2142 if ($type eq 'lxc') {
2143 my $online = PVE
::LXC
::check_running
($vmid) ?
1 : 0;
2144 print STDERR
"Migrating CT $vmid\n";
2145 $upid = PVE
::API2
::LXC-
>migrate_vm(
2146 { node
=> $nodename, vmid
=> $vmid, target
=> $target, restart
=> $online });
2147 } elsif ($type eq 'qemu') {
2148 print STDERR
"Check VM $vmid: ";
2150 my $online = PVE
::QemuServer
::check_running
($vmid, 1) ?
1 : 0;
2151 my $preconditions = PVE
::API2
::Qemu-
>migrate_vm_precondition(
2152 {node
=> $nodename, vmid
=> $vmid, target
=> $target});
2153 my $invalidConditions = '';
2154 if ($online && !$with_local_disks && scalar @{$preconditions->{local_disks
}}) {
2155 $invalidConditions .= "\n Has local disks: ";
2156 $invalidConditions .= join(', ', map { $_->{volid
} } @{$preconditions->{local_disks
}});
2159 if (@{$preconditions->{local_resources
}}) {
2160 $invalidConditions .= "\n Has local resources: ";
2161 $invalidConditions .= join(', ', @{$preconditions->{local_resources
}});
2164 if ($invalidConditions && $invalidConditions ne '') {
2165 print STDERR
"skip VM $vmid - precondition check failed:";
2166 die "$invalidConditions\n";
2168 print STDERR
"precondition check passed\n";
2169 print STDERR
"Migrating VM $vmid\n";
2177 $params->{'with-local-disks'} = $with_local_disks if defined($with_local_disks);
2179 $upid = PVE
::API2
::Qemu-
>migrate_vm($params);
2181 die "unknown VM type '$type'\n";
2184 my $task = PVE
::Tools
::upid_decode
($upid);
2186 return $task->{pid
};
2189 __PACKAGE__-
>register_method ({
2190 name
=> 'migrateall',
2191 path
=> 'migrateall',
2196 description
=> "The 'VM.Migrate' permission is required on '/' or on '/vms/<ID>' for each "
2197 ."ID passed via the 'vms' parameter.",
2200 description
=> "Migrate all VMs and Containers.",
2202 additionalProperties
=> 0,
2204 node
=> get_standard_option
('pve-node'),
2205 target
=> get_standard_option
('pve-node', { description
=> "Target node." }),
2207 description
=> "Maximal number of parallel migration job. If not set, uses"
2208 ."'max_workers' from datacenter.cfg. One of both must be set!",
2214 description
=> "Only consider Guests with these IDs.",
2215 type
=> 'string', format
=> 'pve-vmid-list',
2218 "with-local-disks" => {
2220 description
=> "Enable live storage migration for local disk",
2231 my $rpcenv = PVE
::RPCEnvironment
::get
();
2232 my $authuser = $rpcenv->get_user();
2234 if (!$rpcenv->check($authuser, "/", [ 'VM.Migrate' ], 1)) {
2235 my @vms = PVE
::Tools
::split_list
($param->{vms
});
2236 if (scalar(@vms) > 0) {
2237 $rpcenv->check($authuser, "/vms/$_", [ 'VM.Migrate' ]) for @vms;
2239 raise_perm_exc
("/, VM.Migrate");
2243 my $nodename = $param->{node
};
2244 $nodename = PVE
::INotify
::nodename
() if $nodename eq 'localhost';
2246 my $target = $param->{target
};
2247 my $with_local_disks = $param->{'with-local-disks'};
2248 raise_param_exc
({ target
=> "target is local node."}) if $target eq $nodename;
2250 PVE
::Cluster
::check_cfs_quorum
();
2252 PVE
::Cluster
::check_node_exists
($target);
2254 my $datacenterconfig = cfs_read_file
('datacenter.cfg');
2255 # prefer parameter over datacenter cfg settings
2256 my $maxWorkers = $param->{maxworkers
} || $datacenterconfig->{max_workers
} ||
2257 die "either 'maxworkers' parameter or max_workers in datacenter.cfg must be set!\n";
2260 $rpcenv->{type
} = 'priv'; # to start tasks in background
2262 my $vmlist = &$get_filtered_vmlist($nodename, $param->{vms
}, 1, 1);
2263 if (!scalar(keys %$vmlist)) {
2264 warn "no virtual guests matched, nothing to do..\n";
2269 my $workers_started = 0;
2270 foreach my $vmid (sort keys %$vmlist) {
2271 my $d = $vmlist->{$vmid};
2273 eval { $pid = &$create_migrate_worker($nodename, $d->{type
}, $vmid, $target, $with_local_disks); };
2278 $workers->{$pid} = 1;
2279 while (scalar(keys %$workers) >= $maxWorkers) {
2280 foreach my $p (keys %$workers) {
2281 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2282 delete $workers->{$p};
2288 while (scalar(keys %$workers)) {
2289 foreach my $p (keys %$workers) {
2290 # FIXME: what about PID re-use ?!?!
2291 if (!PVE
::ProcFSTools
::check_process_running
($p)) {
2292 delete $workers->{$p};
2297 if ($workers_started <= 0) {
2298 die "no migrations worker started...\n";
2300 print STDERR
"All jobs finished, used $workers_started workers in total.\n";
2304 return $rpcenv->fork_worker('migrateall', undef, $authuser, $code);
2308 __PACKAGE__-
>register_method ({
2309 name
=> 'get_etc_hosts',
2315 check
=> ['perm', '/', [ 'Sys.Audit' ]],
2317 description
=> "Get the content of /etc/hosts.",
2319 additionalProperties
=> 0,
2321 node
=> get_standard_option
('pve-node'),
2327 digest
=> get_standard_option
('pve-config-digest'),
2330 description
=> 'The content of /etc/hosts.'
2337 return PVE
::INotify
::read_file
('etchosts');
2341 __PACKAGE__-
>register_method ({
2342 name
=> 'write_etc_hosts',
2348 check
=> ['perm', '/nodes/{node}', [ 'Sys.Modify' ]],
2350 description
=> "Write /etc/hosts.",
2352 additionalProperties
=> 0,
2354 node
=> get_standard_option
('pve-node'),
2355 digest
=> get_standard_option
('pve-config-digest'),
2358 description
=> 'The target content of /etc/hosts.'
2368 PVE
::Tools
::lock_file
('/var/lock/pve-etchosts.lck', undef, sub {
2369 if ($param->{digest
}) {
2370 my $hosts = PVE
::INotify
::read_file
('etchosts');
2371 PVE
::Tools
::assert_if_modified
($hosts->{digest
}, $param->{digest
});
2373 PVE
::INotify
::write_file
('etchosts', $param->{data
});
2380 # bash completion helper
2382 sub complete_templet_repo
{
2383 my ($cmdname, $pname, $cvalue) = @_;
2385 my $repo = PVE
::APLInfo
::load_data
();
2387 foreach my $templ (keys %{$repo->{all
}}) {
2388 next if $templ !~ m/^$cvalue/;
2395 package PVE
::API2
::Nodes
;
2400 use PVE
::SafeSyslog
;
2402 use PVE
::RESTHandler
;
2403 use PVE
::RPCEnvironment
;
2405 use PVE
::JSONSchema
qw(get_standard_option);
2407 use base
qw(PVE::RESTHandler);
2409 __PACKAGE__-
>register_method ({
2410 subclass
=> "PVE::API2::Nodes::Nodeinfo",
2414 __PACKAGE__-
>register_method ({
2418 permissions
=> { user
=> 'all' },
2419 description
=> "Cluster node index.",
2421 additionalProperties
=> 0,
2429 node
=> get_standard_option
('pve-node'),
2431 description
=> "Node status.",
2433 enum
=> ['unknown', 'online', 'offline'],
2436 description
=> "CPU utilization.",
2439 renderer
=> 'fraction_as_percentage',
2442 description
=> "Number of available CPUs.",
2447 description
=> "Used memory in bytes.",
2450 renderer
=> 'bytes',
2453 description
=> "Number of available memory in bytes.",
2456 renderer
=> 'bytes',
2459 description
=> "Support level.",
2464 description
=> "Node uptime in seconds.",
2467 renderer
=> 'duration',
2469 ssl_fingerprint
=> {
2470 description
=> "The SSL fingerprint for the node certificate.",
2476 links
=> [ { rel
=> 'child', href
=> "{node}" } ],
2481 my $rpcenv = PVE
::RPCEnvironment
::get
();
2482 my $authuser = $rpcenv->get_user();
2484 my $clinfo = PVE
::Cluster
::get_clinfo
();
2487 my $nodelist = PVE
::Cluster
::get_nodelist
();
2488 my $members = PVE
::Cluster
::get_members
();
2489 my $rrd = PVE
::Cluster
::rrd_dump
();
2491 foreach my $node (@$nodelist) {
2492 my $can_audit = $rpcenv->check($authuser, "/nodes/$node", [ 'Sys.Audit' ], 1);
2493 my $entry = PVE
::API2Tools
::extract_node_stats
($node, $members, $rrd, !$can_audit);
2495 $entry->{ssl_fingerprint
} = eval { PVE
::Cluster
::get_node_fingerprint
($node) };