]>
git.proxmox.com Git - pve-cluster.git/blob - data/PVE/CLI/pvecm.pm
1 package PVE
::CLI
::pvecm
;
8 use PVE
::Tools
qw(run_command);
11 use PVE
::JSONSchema
qw(get_standard_option);
12 use PVE
::RPCEnvironment
;
15 use PVE
::API2
::ClusterConfig
;
17 use PVE
::Cluster
::Setup
;
19 use base
qw(PVE::CLIHandler);
21 $ENV{HOME
} = '/root'; # for ssh-copy-id
23 my $basedir = "/etc/pve";
24 my $clusterconf = "$basedir/corosync.conf";
25 my $libdir = "/var/lib/pve-cluster";
26 my $authfile = "/etc/corosync/authkey";
29 sub setup_environment
{
30 PVE
::RPCEnvironment-
>setup_default_cli_env();
33 __PACKAGE__-
>register_method ({
37 description
=> "Generate new cryptographic key for corosync.",
39 additionalProperties
=> 0,
43 description
=> "Output file name"
47 returns
=> { type
=> 'null' },
52 my $filename = $param->{filename
};
55 $> == 0 || die "Error: Authorization key must be generated as root user.\n";
56 my $dirname = dirname
($filename);
58 die "key file '$filename' already exists\n" if -e
$filename;
60 File
::Path
::make_path
($dirname) if $dirname;
62 run_command
(['corosync-keygen', '-l', '-k', $filename]);
67 my $foreach_member = sub {
68 my ($code, $noerr) = @_;
70 my $members = PVE
::Cluster
::get_members
();
71 foreach my $node (sort keys %$members) {
72 if (my $ip = $members->{$node}->{ip
}) {
75 die "cannot get the cluster IP for node '$node'.\n" if !$noerr;
76 warn "cannot get the cluster IP for node '$node'.\n";
82 __PACKAGE__-
>register_method ({
83 name
=> 'setup_qdevice',
84 path
=> 'setup_qdevice',
86 description
=> "Setup the use of a QDevice",
88 additionalProperties
=> 0,
91 type
=> 'string', format
=> 'ip',
92 description
=> "Specifies the network address of an external corosync QDevice" ,
97 description
=> 'The network which should be used to connect to the external qdevice',
102 description
=> "Do not throw error on possible dangerous operations.",
107 returns
=> { type
=> 'null' },
112 PVE
::Corosync
::check_conf_exists
();
114 my $members = PVE
::Cluster
::get_members
();
115 foreach my $node (sort keys %$members) {
116 die "All nodes must be online! Node $node is offline, aborting.\n"
117 if !$members->{$node}->{online
};
120 my $conf = PVE
::Cluster
::cfs_read_file
("corosync.conf");
122 die "QDevice already configured!\n"
123 if defined($conf->{main
}->{quorum
}->{device
}) && !$param->{force
};
125 my $network = $param->{network
};
128 my $algorithm = 'ffsplit';
129 if (scalar($members) & 1) {
130 if ($param->{force
}) {
133 die "Clusters with an odd node count are not officially supported!\n";
137 my $qnetd_addr = $param->{address
};
138 my $base_dir = "/etc/corosync/qdevice/net";
139 my $db_dir_qnetd = "/etc/corosync/qnetd/nssdb";
140 my $db_dir_node = "$base_dir/nssdb";
141 my $ca_export_base = "qnetd-cacert.crt";
142 my $ca_export_file = "$db_dir_qnetd/$ca_export_base";
143 my $crq_file_base = "qdevice-net-node.crq";
144 my $p12_file_base = "qdevice-net-node.p12";
145 my $qdevice_certutil = "corosync-qdevice-net-certutil";
146 my $qnetd_certutil= "corosync-qnetd-certutil";
147 my $clustername = $conf->{main
}->{totem
}->{cluster_name
};
149 run_command
(['ssh-copy-id', '-i', '/root/.ssh/id_rsa', "root\@$qnetd_addr"]);
151 if (-d
$db_dir_node) {
152 # FIXME: check on all nodes?!
153 if ($param->{force
}) {
156 die "QDevice certificate store already initialised, set force to delete!\n";
160 my $ssh_cmd = ['ssh', '-o', 'BatchMode=yes', '-lroot'];
161 my $scp_cmd = ['scp', '-o', 'BatchMode=yes'];
163 print "\nINFO: initializing qnetd server\n";
165 [@$ssh_cmd, $qnetd_addr, $qnetd_certutil, "-i"],
169 print "\nINFO: copying CA cert and initializing on all nodes\n";
170 run_command
([@$scp_cmd, "root\@\[$qnetd_addr\]:$ca_export_file", "/etc/pve/$ca_export_base"]);
171 $foreach_member->(sub {
172 my ($node, $ip) = @_;
173 my $outsub = sub { print "\nnode '$node': " . shift };
175 [@$ssh_cmd, $ip, $qdevice_certutil, "-i", "-c", "/etc/pve/$ca_export_base"],
176 noerr
=> 1, outfunc
=> \
&$outsub
179 unlink "/etc/pve/$ca_export_base";
181 print "\nINFO: generating cert request\n";
182 run_command
([$qdevice_certutil, "-r", "-n", $clustername]);
184 print "\nINFO: copying exported cert request to qnetd server\n";
185 run_command
([@$scp_cmd, "$db_dir_node/$crq_file_base", "root\@\[$qnetd_addr\]:/tmp"]);
187 print "\nINFO: sign and export cluster cert\n";
189 @$ssh_cmd, $qnetd_addr, $qnetd_certutil, "-s", "-c",
190 "/tmp/$crq_file_base", "-n", "$clustername"
193 print "\nINFO: copy exported CRT\n";
195 @$scp_cmd, "root\@\[$qnetd_addr\]:$db_dir_qnetd/cluster-$clustername.crt",
199 print "\nINFO: import certificate\n";
200 run_command
(["$qdevice_certutil", "-M", "-c", "$db_dir_node/cluster-$clustername.crt"]);
202 print "\nINFO: copy and import pk12 cert to all nodes\n";
203 run_command
([@$scp_cmd, "$db_dir_node/$p12_file_base", "/etc/pve/"]);
204 $foreach_member->(sub {
205 my ($node, $ip) = @_;
206 my $outsub = sub { print "\nnode '$node': " . shift };
208 @$ssh_cmd, $ip, "$qdevice_certutil", "-m", "-c",
209 "/etc/pve/$p12_file_base"], outfunc
=> \
&$outsub
212 unlink "/etc/pve/$p12_file_base";
216 my $conf = PVE
::Cluster
::cfs_read_file
("corosync.conf");
217 my $quorum_section = $conf->{main
}->{quorum
};
219 die "Qdevice already configured, must be removed before setting up new one!\n"
220 if defined($quorum_section->{device
}); # must not be forced!
227 algorithm
=> $algorithm,
230 $qdev_section->{votes
} = 1 if $algorithm eq 'ffsplit';
232 $quorum_section->{device
} = $qdev_section;
234 PVE
::Corosync
::atomic_write_conf
($conf);
237 print "\nINFO: add QDevice to cluster configuration\n";
238 PVE
::Cluster
::cfs_lock_file
('corosync.conf', 10, $code);
241 $foreach_member->(sub {
242 my ($node, $ip) = @_;
243 my $outsub = sub { print "\nnode '$node': " . shift };
244 print "\nINFO: start and enable corosync qdevice daemon on node '$node'...\n";
245 run_command
([@$ssh_cmd, $ip, 'systemctl', 'start', 'corosync-qdevice'], outfunc
=> \
&$outsub);
246 run_command
([@$ssh_cmd, $ip, 'systemctl', 'enable', 'corosync-qdevice'], outfunc
=> \
&$outsub);
249 run_command
(['corosync-cfgtool', '-R']); # do cluster wide config reload
254 __PACKAGE__-
>register_method ({
255 name
=> 'remove_qdevice',
256 path
=> 'remove_qdevice',
258 description
=> "Remove a configured QDevice",
260 additionalProperties
=> 0,
263 returns
=> { type
=> 'null' },
268 PVE
::Corosync
::check_conf_exists
();
270 my $members = PVE
::Cluster
::get_members
();
271 foreach my $node (sort keys %$members) {
272 die "All nodes must be online! Node $node is offline, aborting.\n"
273 if !$members->{$node}->{online
};
276 my $ssh_cmd = ['ssh', '-o', 'BatchMode=yes', '-lroot'];
279 my $conf = PVE
::Cluster
::cfs_read_file
("corosync.conf");
280 my $quorum_section = $conf->{main
}->{quorum
};
282 die "No QDevice configured!\n" if !defined($quorum_section->{device
});
284 delete $quorum_section->{device
};
286 PVE
::Corosync
::atomic_write_conf
($conf);
288 # cleanup qdev state (cert storage)
289 my $qdev_state_dir = "/etc/corosync/qdevice";
290 $foreach_member->(sub {
291 my (undef, $ip) = @_;
292 run_command
([@$ssh_cmd, $ip, '--', 'rm', '-rf', $qdev_state_dir]);
296 PVE
::Cluster
::cfs_lock_file
('corosync.conf', 10, $code);
299 $foreach_member->(sub {
300 my (undef, $ip) = @_;
301 run_command
([@$ssh_cmd, $ip, 'systemctl', 'stop', 'corosync-qdevice']);
302 run_command
([@$ssh_cmd, $ip, 'systemctl', 'disable', 'corosync-qdevice']);
305 run_command
(['corosync-cfgtool', '-R']);
307 print "\nRemoved Qdevice.\n";
312 __PACKAGE__-
>register_method ({
316 description
=> "Adds the current node to an existing cluster.",
318 additionalProperties
=> 0,
322 description
=> "Hostname (or IP) of an existing cluster member."
324 nodeid
=> get_standard_option
('corosync-nodeid'),
327 description
=> "Number of votes for this node",
333 description
=> "Do not throw error if node already exists.",
336 link0
=> get_standard_option
('corosync-link'),
337 link1
=> get_standard_option
('corosync-link'),
338 fingerprint
=> get_standard_option
('fingerprint-sha256', {
343 description
=> "Always use SSH to join, even if peer may do it over API.",
348 returns
=> { type
=> 'null' },
353 my $nodename = PVE
::INotify
::nodename
();
354 my $host = $param->{hostname
};
358 if (!$param->{use_ssh
}) {
359 my $password = PVE
::PTY
::read_password
("Please enter superuser (root) password for '$host': ");
361 delete $param->{use_ssh
};
362 $param->{password
} = $password;
364 my $local_cluster_lock = "/var/lock/pvecm.lock";
365 PVE
::Tools
::lock_file
($local_cluster_lock, 10, \
&PVE
::Cluster
::Setup
::join, $param);
368 if (ref($err) eq 'PVE::APIClient::Exception' && defined($err->{code
}) && $err->{code
} == 501) {
369 $err = "Remote side is not able to use API for Cluster join!\n" .
370 "Pass the 'use_ssh' switch or update the remote side.\n";
374 return; # all OK, the API join endpoint successfully set us up
377 # allow fallback to old ssh only join if wished or needed
379 my $local_ip_address = PVE
::Cluster
::remote_node_ip
($nodename);
381 my $link0 = PVE
::Corosync
::parse_corosync_link
($param->{link0
});
382 my $link1 = PVE
::Corosync
::parse_corosync_link
($param->{link1
});
384 PVE
::Cluster
::Setup
::assert_joinable
($local_ip_address, $link0, $link1, $param->{force
});
386 PVE
::Cluster
::Setup
::setup_sshd_config
();
387 PVE
::Cluster
::Setup
::setup_rootsshconfig
();
388 PVE
::Cluster
::Setup
::setup_ssh_keys
();
390 # make sure known_hosts is on local filesystem
391 PVE
::Cluster
::Setup
::ssh_unmerge_known_hosts
();
393 my $cmd = ['ssh-copy-id', '-i', '/root/.ssh/id_rsa', "root\@$host"];
394 run_command
($cmd, 'outfunc' => sub {}, 'errfunc' => sub {},
395 'errmsg' => "unable to copy ssh ID");
397 $cmd = ['ssh', $host, '-o', 'BatchMode=yes',
398 'pvecm', 'addnode', $nodename, '--force', 1];
400 push @$cmd, '--nodeid', $param->{nodeid
} if $param->{nodeid
};
401 push @$cmd, '--votes', $param->{votes
} if defined($param->{votes
});
402 # just pass the un-parsed string through, or as we've address as
403 # the default_key, we can just pass the fallback directly too
404 push @$cmd, '--link0', $param->{link0
} // $local_ip_address;
405 push @$cmd, '--link1', $param->{link1
} if defined($param->{link1
});
407 if (system (@$cmd) != 0) {
408 my $cmdtxt = join (' ', @$cmd);
409 die "unable to add node: command failed ($cmdtxt)\n";
412 my $tmpdir = "$libdir/.pvecm_add.tmp.$$";
416 print "copy corosync auth key\n";
417 $cmd = ['rsync', '--rsh=ssh -l root -o BatchMode=yes', '-lpgoq',
418 "[$host]:$authfile $clusterconf", $tmpdir];
420 system(@$cmd) == 0 || die "can't rsync data from host '$host'\n";
422 my $corosync_conf = PVE
::Tools
::file_get_contents
("$tmpdir/corosync.conf");
423 my $corosync_authkey = PVE
::Tools
::file_get_contents
("$tmpdir/authkey");
425 PVE
::Cluster
::Setup
::finish_join
($host, $corosync_conf, $corosync_authkey);
434 # use a synced worker so we get a nice task log when joining through CLI
435 my $rpcenv = PVE
::RPCEnvironment
::get
();
436 my $authuser = $rpcenv->get_user();
438 $rpcenv->fork_worker('clusterjoin', '', $authuser, $worker);
443 __PACKAGE__-
>register_method ({
447 description
=> "Displays the local view of the cluster status.",
449 additionalProperties
=> 0,
452 returns
=> { type
=> 'null' },
457 PVE
::Corosync
::check_conf_exists
();
458 my $conf = eval { PVE
::Cluster
::cfs_read_file
("corosync.conf") } // {};
460 my $totem = PVE
::Corosync
::totem_config
($conf);
462 if (scalar(%$totem)) {
463 my $print_info = sub {
464 my ($label, $key, $default) = @_;
465 my $val = $totem->{$key} // $default;
466 printf "%-17s %s\n", "$label:", "$val";
469 printf "Cluster information\n";
470 printf "-------------------\n";
471 $print_info->('Name', 'cluster_name', 'UNKOWN?');
472 $print_info->('Config Version', 'config_version', -1);
473 $print_info->('Transport', 'transport', 'knet');
474 $print_info->('Secure auth', 'secauth', 'off');
478 my $cmd = ['corosync-quorumtool', '-siH'];
482 exit (-1); # should not be reached
485 __PACKAGE__-
>register_method ({
489 description
=> "Displays the local view of the cluster nodes.",
491 additionalProperties
=> 0,
494 returns
=> { type
=> 'null' },
499 PVE
::Corosync
::check_conf_exists
();
501 my $cmd = ['corosync-quorumtool', '-l'];
505 exit (-1); # should not be reached
508 __PACKAGE__-
>register_method ({
512 description
=> "Tells corosync a new value of expected votes.",
514 additionalProperties
=> 0,
518 description
=> "Expected votes",
523 returns
=> { type
=> 'null' },
528 PVE
::Corosync
::check_conf_exists
();
530 my $cmd = ['corosync-quorumtool', '-e', $param->{expected
}];
534 exit (-1); # should not be reached
538 __PACKAGE__-
>register_method ({
539 name
=> 'updatecerts',
540 path
=> 'updatecerts',
542 description
=> "Update node certificates (and generate all needed files/directories).",
544 additionalProperties
=> 0,
547 description
=> "Force generation of new SSL certifate.",
552 description
=> "Ignore errors (i.e. when cluster has no quorum).",
558 returns
=> { type
=> 'null' },
562 # we get called by the pve-cluster.service ExecStartPost and as we do
563 # IO (on /etc/pve) which can hang (uninterruptedly D state). That'd be
564 # no-good for ExecStartPost as it fails the whole service in this case
565 PVE
::Tools
::run_fork_with_timeout
(30, sub {
566 PVE
::Cluster
::Setup
::updatecerts_and_ssh
($param->@{qw(force silent)});
572 __PACKAGE__-
>register_method ({
576 description
=> "Used by VM/CT migration - do not use manually.",
578 additionalProperties
=> 0,
580 get_migration_ip
=> {
583 description
=> 'return the migration IP, if configured',
586 migration_network
=> {
589 description
=> 'the migration network used to detect the local migration IP',
594 description
=> 'Run a command with a tcp socket as standard input.'
595 .' The IP address and port are printed via this'
596 ." command's stdandard output first, each on a separate line.",
599 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args'),
602 returns
=> { type
=> 'null'},
606 if (!PVE
::Cluster
::check_cfs_quorum
(1)) {
611 my $get_local_migration_ip = sub {
614 if (!defined($cidr)) {
615 my $dc_conf = cfs_read_file
('datacenter.cfg');
616 $cidr = $dc_conf->{migration
}->{network
}
617 if defined($dc_conf->{migration
}->{network
});
620 if (defined($cidr)) {
621 my $ips = PVE
::Network
::get_local_ip_from_cidr
($cidr);
623 die "could not get migration ip: no IP address configured on local " .
624 "node for network '$cidr'\n" if scalar(@$ips) == 0;
626 die "could not get migration ip: multiple, different, IP address configured for " .
627 "network '$cidr'\n" if scalar(@$ips) > 1 && grep { @$ips[0] ne $_ } @$ips;
635 my $network = $param->{migration_network
};
636 if ($param->{get_migration_ip
}) {
637 die "cannot use --run-command with --get_migration_ip\n"
638 if $param->{'run-command'};
640 if (my $ip = $get_local_migration_ip->($network)) {
645 # do not keep tunnel open when asked for migration ip
649 if ($param->{'run-command'}) {
650 my $cmd = $param->{'extra-args'};
651 die "missing command\n"
652 if !$cmd || !scalar(@$cmd);
654 # Get an ip address to listen on, and find a free migration port
656 if (defined($network)) {
657 $ip = $get_local_migration_ip->($network)
658 or die "failed to get migration IP address to listen on\n";
659 $family = PVE
::Tools
::get_host_address_family
($ip);
661 my $nodename = PVE
::INotify
::nodename
();
662 ($ip, $family) = PVE
::Network
::get_ip_from_hostname
($nodename, 0);
664 my $port = PVE
::Tools
::next_migrate_port
($family, $ip);
666 PVE
::Tools
::pipe_socket_to_command
($cmd, $ip, $port);
670 print "tunnel online\n";
673 while (my $line = <STDIN
>) {
675 last if $line =~ m/^quit$/;
683 keygen
=> [ __PACKAGE__
, 'keygen', ['filename']],
684 create
=> [ 'PVE::API2::ClusterConfig', 'create', ['clustername']],
685 add
=> [ __PACKAGE__
, 'add', ['hostname']],
686 addnode
=> [ 'PVE::API2::ClusterConfig', 'addnode', ['node']],
687 delnode
=> [ 'PVE::API2::ClusterConfig', 'delnode', ['node']],
688 status
=> [ __PACKAGE__
, 'status' ],
689 nodes
=> [ __PACKAGE__
, 'nodes' ],
690 expected
=> [ __PACKAGE__
, 'expected', ['expected']],
691 updatecerts
=> [ __PACKAGE__
, 'updatecerts', []],
692 mtunnel
=> [ __PACKAGE__
, 'mtunnel', ['extra-args']],
694 setup
=> [ __PACKAGE__
, 'setup_qdevice', ['address']],
695 remove
=> [ __PACKAGE__
, 'remove_qdevice', []],