]>
git.proxmox.com Git - pve-cluster.git/blob - data/PVE/CLI/pvecm.pm
48c110bef77a03f0fb25d6ded41c31d5978b2092
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 die "Node not in a cluster. Aborting.\n"
113 if !PVE
::Corosync
::check_conf_exists
(1);
115 my $members = PVE
::Cluster
::get_members
();
116 foreach my $node (sort keys %$members) {
117 die "All nodes must be online! Node $node is offline, aborting.\n"
118 if !$members->{$node}->{online
};
121 my $conf = PVE
::Cluster
::cfs_read_file
("corosync.conf");
123 die "QDevice already configured!\n"
124 if defined($conf->{main
}->{quorum
}->{device
}) && !$param->{force
};
126 my $network = $param->{network
};
129 my $algorithm = 'ffsplit';
130 if (scalar($members) & 1) {
131 if ($param->{force
}) {
134 die "Clusters with an odd node count are not officially supported!\n";
138 my $qnetd_addr = $param->{address
};
139 my $base_dir = "/etc/corosync/qdevice/net";
140 my $db_dir_qnetd = "/etc/corosync/qnetd/nssdb";
141 my $db_dir_node = "$base_dir/nssdb";
142 my $ca_export_base = "qnetd-cacert.crt";
143 my $ca_export_file = "$db_dir_qnetd/$ca_export_base";
144 my $crq_file_base = "qdevice-net-node.crq";
145 my $p12_file_base = "qdevice-net-node.p12";
146 my $qdevice_certutil = "corosync-qdevice-net-certutil";
147 my $qnetd_certutil= "corosync-qnetd-certutil";
148 my $clustername = $conf->{main
}->{totem
}->{cluster_name
};
150 run_command
(['ssh-copy-id', '-i', '/root/.ssh/id_rsa', "root\@$qnetd_addr"]);
152 if (-d
$db_dir_node) {
153 # FIXME: check on all nodes?!
154 if ($param->{force
}) {
157 die "QDevice certificate store already initialised, set force to delete!\n";
161 my $ssh_cmd = ['ssh', '-o', 'BatchMode=yes', '-lroot'];
162 my $scp_cmd = ['scp', '-o', 'BatchMode=yes'];
164 print "\nINFO: initializing qnetd server\n";
166 [@$ssh_cmd, $qnetd_addr, $qnetd_certutil, "-i"],
170 print "\nINFO: copying CA cert and initializing on all nodes\n";
171 run_command
([@$scp_cmd, "root\@\[$qnetd_addr\]:$ca_export_file", "/etc/pve/$ca_export_base"]);
172 $foreach_member->(sub {
173 my ($node, $ip) = @_;
174 my $outsub = sub { print "\nnode '$node': " . shift };
176 [@$ssh_cmd, $ip, $qdevice_certutil, "-i", "-c", "/etc/pve/$ca_export_base"],
177 noerr
=> 1, outfunc
=> \
&$outsub
180 unlink "/etc/pve/$ca_export_base";
182 print "\nINFO: generating cert request\n";
183 run_command
([$qdevice_certutil, "-r", "-n", $clustername]);
185 print "\nINFO: copying exported cert request to qnetd server\n";
186 run_command
([@$scp_cmd, "$db_dir_node/$crq_file_base", "root\@\[$qnetd_addr\]:/tmp"]);
188 print "\nINFO: sign and export cluster cert\n";
190 @$ssh_cmd, $qnetd_addr, $qnetd_certutil, "-s", "-c",
191 "/tmp/$crq_file_base", "-n", "$clustername"
194 print "\nINFO: copy exported CRT\n";
196 @$scp_cmd, "root\@\[$qnetd_addr\]:$db_dir_qnetd/cluster-$clustername.crt",
200 print "\nINFO: import certificate\n";
201 run_command
(["$qdevice_certutil", "-M", "-c", "$db_dir_node/cluster-$clustername.crt"]);
203 print "\nINFO: copy and import pk12 cert to all nodes\n";
204 run_command
([@$scp_cmd, "$db_dir_node/$p12_file_base", "/etc/pve/"]);
205 $foreach_member->(sub {
206 my ($node, $ip) = @_;
207 my $outsub = sub { print "\nnode '$node': " . shift };
209 @$ssh_cmd, $ip, "$qdevice_certutil", "-m", "-c",
210 "/etc/pve/$p12_file_base"], outfunc
=> \
&$outsub
213 unlink "/etc/pve/$p12_file_base";
217 my $conf = PVE
::Cluster
::cfs_read_file
("corosync.conf");
218 my $quorum_section = $conf->{main
}->{quorum
};
220 die "Qdevice already configured, must be removed before setting up new one!\n"
221 if defined($quorum_section->{device
}); # must not be forced!
228 algorithm
=> $algorithm,
231 $qdev_section->{votes
} = 1 if $algorithm eq 'ffsplit';
233 $quorum_section->{device
} = $qdev_section;
235 PVE
::Corosync
::atomic_write_conf
($conf);
238 print "\nINFO: add QDevice to cluster configuration\n";
239 PVE
::Cluster
::cfs_lock_file
('corosync.conf', 10, $code);
242 $foreach_member->(sub {
243 my ($node, $ip) = @_;
244 my $outsub = sub { print "\nnode '$node': " . shift };
245 print "\nINFO: start and enable corosync qdevice daemon on node '$node'...\n";
246 run_command
([@$ssh_cmd, $ip, 'systemctl', 'start', 'corosync-qdevice'], outfunc
=> \
&$outsub);
247 run_command
([@$ssh_cmd, $ip, 'systemctl', 'enable', 'corosync-qdevice'], outfunc
=> \
&$outsub);
250 run_command
(['corosync-cfgtool', '-R']); # do cluster wide config reload
255 __PACKAGE__-
>register_method ({
256 name
=> 'remove_qdevice',
257 path
=> 'remove_qdevice',
259 description
=> "Remove a configured QDevice",
261 additionalProperties
=> 0,
264 returns
=> { type
=> 'null' },
269 die "Node not in a cluster. Aborting.\n"
270 if !PVE
::Corosync
::check_conf_exists
(1);
272 my $members = PVE
::Cluster
::get_members
();
273 foreach my $node (sort keys %$members) {
274 die "All nodes must be online! Node $node is offline, aborting.\n"
275 if !$members->{$node}->{online
};
278 my $ssh_cmd = ['ssh', '-o', 'BatchMode=yes', '-lroot'];
281 my $conf = PVE
::Cluster
::cfs_read_file
("corosync.conf");
282 my $quorum_section = $conf->{main
}->{quorum
};
284 die "No QDevice configured!\n" if !defined($quorum_section->{device
});
286 delete $quorum_section->{device
};
288 PVE
::Corosync
::atomic_write_conf
($conf);
290 # cleanup qdev state (cert storage)
291 my $qdev_state_dir = "/etc/corosync/qdevice";
292 $foreach_member->(sub {
293 my (undef, $ip) = @_;
294 run_command
([@$ssh_cmd, $ip, '--', 'rm', '-rf', $qdev_state_dir]);
298 PVE
::Cluster
::cfs_lock_file
('corosync.conf', 10, $code);
301 $foreach_member->(sub {
302 my (undef, $ip) = @_;
303 run_command
([@$ssh_cmd, $ip, 'systemctl', 'stop', 'corosync-qdevice']);
304 run_command
([@$ssh_cmd, $ip, 'systemctl', 'disable', 'corosync-qdevice']);
307 run_command
(['corosync-cfgtool', '-R']);
309 print "\nRemoved Qdevice.\n";
314 __PACKAGE__-
>register_method ({
318 description
=> "Adds the current node to an existing cluster.",
320 additionalProperties
=> 0,
324 description
=> "Hostname (or IP) of an existing cluster member."
326 nodeid
=> get_standard_option
('corosync-nodeid'),
329 description
=> "Number of votes for this node",
335 description
=> "Do not throw error if node already exists.",
338 link0
=> get_standard_option
('corosync-link'),
339 link1
=> get_standard_option
('corosync-link'),
340 fingerprint
=> get_standard_option
('fingerprint-sha256', {
345 description
=> "Always use SSH to join, even if peer may do it over API.",
350 returns
=> { type
=> 'null' },
355 my $nodename = PVE
::INotify
::nodename
();
357 my $host = $param->{hostname
};
358 my $local_ip_address = PVE
::Cluster
::remote_node_ip
($nodename);
360 my $link0 = PVE
::Cluster
::parse_corosync_link
($param->{link0
});
361 my $link1 = PVE
::Cluster
::parse_corosync_link
($param->{link1
});
363 PVE
::Cluster
::Setup
::assert_joinable
($local_ip_address, $link0, $link1, $param->{force
});
367 if (!$param->{use_ssh
}) {
368 print "Please enter superuser (root) password for '$host':\n";
369 my $password = PVE
::PTY
::read_password
("Password for root\@$host: ");
371 delete $param->{use_ssh
};
372 $param->{password
} = $password;
374 my $local_cluster_lock = "/var/lock/pvecm.lock";
375 PVE
::Tools
::lock_file
($local_cluster_lock, 10, \
&PVE
::Cluster
::Setup
::join, $param);
378 if (ref($err) eq 'PVE::APIClient::Exception' && defined($err->{code
}) && $err->{code
} == 501) {
379 $err = "Remote side is not able to use API for Cluster join!\n" .
380 "Pass the 'use_ssh' switch or update the remote side.\n";
384 return; # all OK, the API join endpoint successfully set us up
387 # allow fallback to old ssh only join if wished or needed
389 PVE
::Cluster
::Setup
::setup_sshd_config
();
390 PVE
::Cluster
::Setup
::setup_rootsshconfig
();
391 PVE
::Cluster
::Setup
::setup_ssh_keys
();
393 # make sure known_hosts is on local filesystem
394 PVE
::Cluster
::Setup
::ssh_unmerge_known_hosts
();
396 my $cmd = ['ssh-copy-id', '-i', '/root/.ssh/id_rsa', "root\@$host"];
397 run_command
($cmd, 'outfunc' => sub {}, 'errfunc' => sub {},
398 'errmsg' => "unable to copy ssh ID");
400 $cmd = ['ssh', $host, '-o', 'BatchMode=yes',
401 'pvecm', 'addnode', $nodename, '--force', 1];
403 push @$cmd, '--nodeid', $param->{nodeid
} if $param->{nodeid
};
404 push @$cmd, '--votes', $param->{votes
} if defined($param->{votes
});
405 # just pass the un-parsed string through, or as we've address as
406 # the default_key, we can just pass the fallback directly too
407 push @$cmd, '--link0', $param->{link0
} // $local_ip_address;
408 push @$cmd, '--link1', $param->{link1
} if defined($param->{link1
});
410 if (system (@$cmd) != 0) {
411 my $cmdtxt = join (' ', @$cmd);
412 die "unable to add node: command failed ($cmdtxt)\n";
415 my $tmpdir = "$libdir/.pvecm_add.tmp.$$";
419 print "copy corosync auth key\n";
420 $cmd = ['rsync', '--rsh=ssh -l root -o BatchMode=yes', '-lpgoq',
421 "[$host]:$authfile $clusterconf", $tmpdir];
423 system(@$cmd) == 0 || die "can't rsync data from host '$host'\n";
425 my $corosync_conf = PVE
::Tools
::file_get_contents
("$tmpdir/corosync.conf");
426 my $corosync_authkey = PVE
::Tools
::file_get_contents
("$tmpdir/authkey");
428 PVE
::Cluster
::Setup
::finish_join
($host, $corosync_conf, $corosync_authkey);
437 # use a synced worker so we get a nice task log when joining through CLI
438 my $rpcenv = PVE
::RPCEnvironment
::get
();
439 my $authuser = $rpcenv->get_user();
441 $rpcenv->fork_worker('clusterjoin', '', $authuser, $worker);
446 __PACKAGE__-
>register_method ({
450 description
=> "Displays the local view of the cluster status.",
452 additionalProperties
=> 0,
455 returns
=> { type
=> 'null' },
460 PVE
::Corosync
::check_conf_exists
();
461 my $conf = eval { PVE
::Cluster
::cfs_read_file
("corosync.conf") } // {};
463 my $totem = PVE
::Corosync
::totem_config
($conf);
465 if (scalar(%$totem)) {
466 my $print_info = sub {
467 my ($label, $key, $default) = @_;
468 my $val = $totem->{$key} // $default;
469 printf "%-17s %s\n", "$label:", "$val";
472 printf "Cluster information\n";
473 printf "-------------------\n";
474 $print_info->('Name', 'cluster_name', 'UNKOWN?');
475 $print_info->('Config Version', 'config_version', -1);
476 $print_info->('Transport', 'transport', 'knet');
477 $print_info->('Secure auth', 'secauth', 'off');
481 my $cmd = ['corosync-quorumtool', '-siH'];
485 exit (-1); # should not be reached
488 __PACKAGE__-
>register_method ({
492 description
=> "Displays the local view of the cluster nodes.",
494 additionalProperties
=> 0,
497 returns
=> { type
=> 'null' },
502 PVE
::Corosync
::check_conf_exists
();
504 my $cmd = ['corosync-quorumtool', '-l'];
508 exit (-1); # should not be reached
511 __PACKAGE__-
>register_method ({
515 description
=> "Tells corosync a new value of expected votes.",
517 additionalProperties
=> 0,
521 description
=> "Expected votes",
526 returns
=> { type
=> 'null' },
531 PVE
::Corosync
::check_conf_exists
();
533 my $cmd = ['corosync-quorumtool', '-e', $param->{expected
}];
537 exit (-1); # should not be reached
541 __PACKAGE__-
>register_method ({
542 name
=> 'updatecerts',
543 path
=> 'updatecerts',
545 description
=> "Update node certificates (and generate all needed files/directories).",
547 additionalProperties
=> 0,
550 description
=> "Force generation of new SSL certifate.",
555 description
=> "Ignore errors (i.e. when cluster has no quorum).",
561 returns
=> { type
=> 'null' },
565 # we get called by the pve-cluster.service ExecStartPost and as we do
566 # IO (on /etc/pve) which can hang (uninterruptedly D state). That'd be
567 # no-good for ExecStartPost as it fails the whole service in this case
568 PVE
::Tools
::run_fork_with_timeout
(30, sub {
569 PVE
::Cluster
::Setup
::updatecerts_and_ssh
($param->@{qw(force silent)});
575 __PACKAGE__-
>register_method ({
579 description
=> "Used by VM/CT migration - do not use manually.",
581 additionalProperties
=> 0,
583 get_migration_ip
=> {
586 description
=> 'return the migration IP, if configured',
589 migration_network
=> {
592 description
=> 'the migration network used to detect the local migration IP',
597 description
=> 'Run a command with a tcp socket as standard input.'
598 .' The IP address and port are printed via this'
599 ." command's stdandard output first, each on a separate line.",
602 'extra-args' => PVE
::JSONSchema
::get_standard_option
('extra-args'),
605 returns
=> { type
=> 'null'},
609 if (!PVE
::Cluster
::check_cfs_quorum
(1)) {
614 my $network = $param->{migration_network
};
615 if ($param->{get_migration_ip
}) {
616 die "cannot use --run-command with --get_migration_ip\n"
617 if $param->{'run-command'};
618 if (my $ip = PVE
::Cluster
::get_local_migration_ip
($network)) {
623 # do not keep tunnel open when asked for migration ip
627 if ($param->{'run-command'}) {
628 my $cmd = $param->{'extra-args'};
629 die "missing command\n"
630 if !$cmd || !scalar(@$cmd);
632 # Get an ip address to listen on, and find a free migration port
634 if (defined($network)) {
635 $ip = PVE
::Cluster
::get_local_migration_ip
($network)
636 or die "failed to get migration IP address to listen on\n";
637 $family = PVE
::Tools
::get_host_address_family
($ip);
639 my $nodename = PVE
::INotify
::nodename
();
640 ($ip, $family) = PVE
::Network
::get_ip_from_hostname
($nodename, 0);
642 my $port = PVE
::Tools
::next_migrate_port
($family, $ip);
644 PVE
::Tools
::pipe_socket_to_command
($cmd, $ip, $port);
648 print "tunnel online\n";
651 while (my $line = <STDIN
>) {
653 last if $line =~ m/^quit$/;
661 keygen
=> [ __PACKAGE__
, 'keygen', ['filename']],
662 create
=> [ 'PVE::API2::ClusterConfig', 'create', ['clustername']],
663 add
=> [ __PACKAGE__
, 'add', ['hostname']],
664 addnode
=> [ 'PVE::API2::ClusterConfig', 'addnode', ['node']],
665 delnode
=> [ 'PVE::API2::ClusterConfig', 'delnode', ['node']],
666 status
=> [ __PACKAGE__
, 'status' ],
667 nodes
=> [ __PACKAGE__
, 'nodes' ],
668 expected
=> [ __PACKAGE__
, 'expected', ['expected']],
669 updatecerts
=> [ __PACKAGE__
, 'updatecerts', []],
670 mtunnel
=> [ __PACKAGE__
, 'mtunnel', ['extra-args']],
672 setup
=> [ __PACKAGE__
, 'setup_qdevice', ['address']],
673 remove
=> [ __PACKAGE__
, 'remove_qdevice', []],