]> git.proxmox.com Git - pve-cluster.git/blobdiff - data/PVE/Cluster.pm
write_datacenter_config: do not overwrite new migration option with old value
[pve-cluster.git] / data / PVE / Cluster.pm
index c142bc8ff06b618d667dad2080b00f3ad29f7515..da8dab48ca8369c43ff3475230e35eb8448a3e33 100644 (file)
@@ -16,9 +16,11 @@ use PVE::INotify;
 use PVE::IPCC;
 use PVE::SafeSyslog;
 use PVE::JSONSchema;
+use PVE::Network;
 use JSON;
 use RRDs;
 use Encode;
+use UUID;
 use base 'Exporter';
 
 our @EXPORT_OK = qw(
@@ -51,6 +53,7 @@ my $ssh_host_rsa_id = "/etc/ssh/ssh_host_rsa_key.pub";
 my $sshglobalknownhosts = "/etc/ssh/ssh_known_hosts";
 my $sshknownhosts = "/etc/pve/priv/known_hosts";
 my $sshauthkeys = "/etc/pve/priv/authorized_keys";
+my $sshd_config_fn = "/etc/ssh/sshd_config";
 my $rootsshauthkeys = "/root/.ssh/authorized_keys";
 my $rootsshauthkeysbackup = "${rootsshauthkeys}.org";
 my $rootsshconfig = "/root/.ssh/config";
@@ -71,6 +74,8 @@ my $observed = {
     'ha/manager_status' => 1,
     'ha/resources.cfg' => 1,
     'ha/groups.cfg' => 1,
+    'ha/fence.cfg' => 1,
+    'status.cfg' => 1,
 };
 
 # only write output if something fails
@@ -150,11 +155,9 @@ sub gen_auth_key {
 
     mkdir $authdir || $! == EEXIST || die "unable to create dir '$authdir' - $!\n";
 
-    my $cmd = "openssl genrsa -out '$authprivkeyfn' 2048";
-    run_silent_cmd($cmd);
+    run_silent_cmd(['openssl', 'genrsa', '-out', $authprivkeyfn, '2048']);
 
-    $cmd = "openssl rsa -in '$authprivkeyfn' -pubout -out '$authpubkeyfn'";
-    run_silent_cmd($cmd)
+    run_silent_cmd(['openssl', 'rsa', '-in', $authprivkeyfn, '-pubout', '-out', $authpubkeyfn]);
 }
 
 sub gen_pveca_key {
@@ -162,7 +165,7 @@ sub gen_pveca_key {
     return if -f $pveca_key_fn;
 
     eval {
-       run_silent_cmd(['openssl', 'genrsa', '-out', $pveca_key_fn, '2048']);
+       run_silent_cmd(['openssl', 'genrsa', '-out', $pveca_key_fn, '4096']);
     };
 
     die "unable to generate pve ca key:\n$@" if $@;
@@ -178,13 +181,17 @@ sub gen_pveca_cert {
 
     # we try to generate an unique 'subject' to avoid browser problems
     # (reused serial numbers, ..)
-    my $nid = (split (/\s/, `md5sum '$pveca_key_fn'`))[0] || time();
+    my $uuid;
+    UUID::generate($uuid);
+    my $uuid_str;
+    UUID::unparse($uuid, $uuid_str);
 
     eval {
-       run_silent_cmd(['openssl', 'req', '-batch', '-days', '3650', '-new',
-                       '-x509', '-nodes', '-key',
+       # wrap openssl with faketime to prevent bug #904
+       run_silent_cmd(['faketime', 'yesterday', 'openssl', 'req', '-batch',
+                       '-days', '3650', '-new', '-x509', '-nodes', '-key',
                        $pveca_key_fn, '-out', $pveca_cert_fn, '-subj',
-                       "/CN=Proxmox Virtual Environment/OU=$nid/O=PVE Cluster Manager CA/"]);
+                       "/CN=Proxmox Virtual Environment/OU=$uuid_str/O=PVE Cluster Manager CA/"]);
     };
 
     die "generating pve root certificate failed:\n$@" if $@;
@@ -268,8 +275,7 @@ commonName = $fqdn
 
 [ v3_req ]
 basicConstraints = CA:FALSE
-nsCertType = server
-keyUsage = nonRepudiation, digitalSignature, keyEncipherment
+extendedKeyUsage = serverAuth
 subjectAltName = $names
 __EOD
 
@@ -296,10 +302,11 @@ __EOD
     update_serial("0000000000000000") if ! -f $pveca_srl_fn;
 
     eval {
-       run_silent_cmd(['openssl', 'x509', '-req', '-in', $reqfn, '-days', '3650',
-                       '-out', $pvessl_cert_fn, '-CAkey', $pveca_key_fn,
-                       '-CA', $pveca_cert_fn, '-CAserial', $pveca_srl_fn,
-                       '-extfile', $cfgfn]);
+       # wrap openssl with faketime to prevent bug #904
+       run_silent_cmd(['faketime', 'yesterday', 'openssl', 'x509', '-req',
+                       '-in', $reqfn, '-days', '3650', '-out', $pvessl_cert_fn,
+                       '-CAkey', $pveca_key_fn, '-CA', $pveca_cert_fn,
+                       '-CAserial', $pveca_srl_fn, '-extfile', $cfgfn]);
     };
 
     if (my $err = $@) {
@@ -654,18 +661,16 @@ sub create_rrd_data {
     for my $line (@$data) {
        my $entry = { 'time' => $start };
        $start += $step;
-       my $found_undefs;
        for (my $i = 0; $i < $fields; $i++) {
            my $name = $names->[$i];
            if (defined(my $val = $line->[$i])) {
                $entry->{$name} = $val;
            } else {
-               # we only add entryies with all data defined
-               # extjs chart has problems with undefined values
-               $found_undefs = 1;
+               # leave empty fields undefined
+               # maybe make this configurable?
            }
        }
-       push @$res, $entry if !$found_undefs;
+       push @$res, $entry;
     }
 
     return $res;
@@ -705,6 +710,7 @@ sub create_rrd_graph {
        "--width" => 800,
        "--start" => - $reso*$count,
        "--end" => 'now' ,
+       "--lower-limit" => 0,
        );
 
     my $socket = "/var/run/rrdcached.sock";
@@ -790,18 +796,12 @@ sub cfs_file_version {
 
     my $version;
     my $infotag;
-    if ($filename =~ m!^nodes/[^/]+/(openvz|qemu-server)/(\d+)\.conf$!) {
+    if ($filename =~ m!^nodes/[^/]+/(openvz|lxc|qemu-server)/(\d+)\.conf$!) {
        my ($type, $vmid) = ($1, $2);
        if ($vmlist && $vmlist->{ids} && $vmlist->{ids}->{$vmid}) {
            $version = $vmlist->{ids}->{$vmid}->{version};
        }
        $infotag = "/$type/";
-    } elsif ($filename =~ m!^nodes/[^/]+/lxc/(\d+)/config$!) {
-       my $vmid = $1;
-       if ($vmlist && $vmlist->{ids} && $vmlist->{ids}->{$vmid}) {
-           $version = $vmlist->{ids}->{$vmid}->{version};
-       }
-       $infotag = "/lxc/";
     } else {
        $infotag = $filename;
        $version = $versions->{$filename};
@@ -931,6 +931,14 @@ sub cfs_lock_storage {
     &$cfs_lock($lockid, $timeout, $code, @param);
 }
 
+sub cfs_lock_domain {
+    my ($domainname, $timeout, $code, @param) = @_;
+
+    my $lockid = "domain-$domainname";
+
+    &$cfs_lock($lockid, $timeout, $code, @param);
+}
+
 my $log_levels = {
     "emerg" => 0,
     "alert" => 1,
@@ -959,12 +967,10 @@ sub log_msg {
    $msg = "empty message" if !$msg;
 
    $ident = "" if !$ident;
-   $ident = encode("ascii", decode_utf8($ident),
+   $ident = encode("ascii", $ident,
                   sub { sprintf "\\u%04x", shift });
 
-   my $utf8 = decode_utf8($msg);
-
-   my $ascii = encode("ascii", $utf8, sub { sprintf "\\u%04x", shift });
+   my $ascii = encode("ascii", $msg, sub { sprintf "\\u%04x", shift });
 
    if ($ident) {
        syslog($priority, "<%s> %s", $ident, $ascii);
@@ -987,9 +993,8 @@ sub check_vmid_unused {
     
     return undef if $noerr;
 
-    die "VM $vmid already exists\n" if $d->{type} eq 'qemu';
-    
-    die "CT $vmid already exists\n";
+    my $vmtypestr =  $d->{type} eq 'qemu' ? 'VM' : 'CT';
+    die "$vmtypestr $vmid already exists on node '$d->{node}'\n";
 }
 
 sub check_node_exists {
@@ -1044,6 +1049,32 @@ sub remote_node_ip {
     return wantarray ? ($ip, $family) : $ip;
 }
 
+sub get_local_migration_ip {
+    my ($migration_network, $noerr) = @_;
+
+    my $cidr = $migration_network;
+
+    if (!defined($cidr)) {
+       my $dc_conf = cfs_read_file('datacenter.cfg');
+       $cidr = $dc_conf->{migration}->{network}
+         if defined($dc_conf->{migration}->{network});
+    }
+
+    if (defined($cidr)) {
+       my $ips = PVE::Network::get_local_ip_from_cidr($cidr);
+
+       die "no IP address configured on local node for network '$cidr'\n" 
+           if !$noerr && (scalar(@$ips) == 0);
+
+       die "multiple IP address configured for network '$cidr'\n" 
+           if !$noerr && (scalar(@$ips) > 1);
+
+       return @$ips[0];
+    }
+
+    return undef;
+};
+
 # ssh related utility functions
 
 sub ssh_merge_keys {
@@ -1089,6 +1120,22 @@ sub ssh_merge_keys {
     }
 }
 
+sub setup_sshd_config {
+
+    my $conf = PVE::Tools::file_get_contents($sshd_config_fn);
+    
+    return if $conf =~ m/^PermitRootLogin\s+yes\s*$/m;
+
+    if ($conf !~ s/^#?PermitRootLogin.*$/PermitRootLogin yes/m) {
+       chomp $conf;
+       $conf .= "\nPermitRootLogin yes\n";
+    } 
+
+    PVE::Tools::file_set_contents($sshd_config_fn, $conf);
+
+    PVE::Tools::run_command(['systemctl', 'reload-or-restart', 'sshd']);
+}
+
 sub setup_rootsshconfig {
 
     # create ssh key if it does not exist
@@ -1179,7 +1226,8 @@ sub ssh_merge_known_hosts {
     }
 
     my $hostkey = PVE::Tools::file_get_contents($ssh_host_rsa_id);
-    die "can't parse $ssh_rsa_id" if $hostkey !~ m/^(ssh-rsa\s\S+)(\s.*)?$/;
+    # Note: file sometimes containe emty lines at start, so we use multiline match
+    die "can't parse $ssh_host_rsa_id" if $hostkey !~ m/^(ssh-rsa\s\S+)(\s.*)?$/m;
     $hostkey = $1;
 
     my $data = '';
@@ -1270,6 +1318,25 @@ sub ssh_merge_known_hosts {
 
 }
 
+my $migration_format = {
+    type => {
+       default_key => 1,
+       type => 'string',
+       enum => ['secure', 'insecure'],
+       description => "Migration traffic is encrypted using an SSH tunnel by " .
+         "default. On secure, completely private networks this can be " .
+         "disabled to increase performance.",
+       default => 'secure',
+       format_description => 'migration type',
+    },
+    network => {
+       optional => 1,
+       type => 'string', format => 'CIDR',
+       format_description => 'CIDR',
+       description => "CIDR of the (sub) network that is used for migration."
+    },
+};
+
 my $datacenter_schema = {
     type => "object",
     additionalProperties => 0,
@@ -1295,7 +1362,14 @@ my $datacenter_schema = {
        migration_unsecure => {
            optional => 1,
            type => 'boolean',
-           description => "Migration is secure using SSH tunnel by default. For secure private networks you can disable it to speed up migration.",
+           description => "Migration is secure using SSH tunnel by default. " .
+             "For secure private networks you can disable it to speed up " .
+             "migration. Deprecated, use the 'migration' property instead!",
+       },
+       migration => {
+           optional => 1,
+           type => 'string', format => $migration_format,
+           description => "For cluster wide migration settings.",
        },
        console => {
            optional => 1,
@@ -1309,6 +1383,29 @@ my $datacenter_schema = {
            format => 'email-opt',
            description => "Specify email address to send notification from (default is root@\$hostname)",
        },
+       max_workers => {
+           optional => 1,
+           type => 'integer',
+           minimum => 1,
+           description => "Defines how many workers (per node) are maximal started ".
+             " on actions like 'stopall VMs' or task from the ha-manager.",
+       },
+       fencing => {
+           optional => 1,
+           type => 'string',
+           default => 'watchdog',
+           enum => [ 'watchdog', 'hardware', 'both' ],
+           description => "Set the fencing mode of the HA cluster. Hardware mode " .
+             "needs a valid configuration of fence devices in /etc/pve/ha/fence.cfg." .
+             " With both all two modes are used." .
+             "\n\nWARNING: 'hardware' and 'both' are EXPERIMENTAL & WIP",
+       },
+       mac_prefix => {
+           optional => 1,
+           type => 'string',
+           pattern => qr/[a-f0-9]{2}(?::[a-f0-9]{2}){0,2}:?/i,
+           description => 'Prefix for autogenerated MAC addresses.',
+       },
     },
 };
 
@@ -1318,12 +1415,34 @@ sub get_datacenter_schema { return $datacenter_schema };
 sub parse_datacenter_config {
     my ($filename, $raw) = @_;
 
-    return PVE::JSONSchema::parse_config($datacenter_schema, $filename, $raw);
+    my $res = PVE::JSONSchema::parse_config($datacenter_schema, $filename, $raw // '');
+
+    if (my $migration = $res->{migration}) {
+       $res->{migration} = PVE::JSONSchema::parse_property_string($migration_format, $migration);
+    }
+
+    # for backwards compatibility only, new migration property has precedence
+    if (defined($res->{migration_unsecure})) {
+       if (defined($res->{migration}->{type})) {
+           warn "deprecated setting 'migration_unsecure' and new 'migration: type' " .
+             "set at same time! Ignore 'migration_unsecure'\n";
+       } else {
+           $res->{migration}->{type} = ($res->{migration_unsecure}) ? 'insecure' : 'secure';
+       }
+    }
+
+    return $res;
 }
 
 sub write_datacenter_config {
     my ($filename, $cfg) = @_;
-    
+
+    # map deprecated setting to new one
+    if (defined($cfg->{migration_unsecure}) && !defined($cfg->{migration})) {
+       my $migration_unsecure = delete $cfg->{migration_unsecure};
+       $cfg->{migration}->{type} = ($migration_unsecure) ? 'insecure' : 'secure';
+    }
+
     return PVE::JSONSchema::dump_config($datacenter_schema, $filename, $cfg);
 }
 
@@ -1463,4 +1582,71 @@ PVE::Cluster::cfs_register_file('corosync.conf', \&parse_corosync_conf);
 PVE::Cluster::cfs_register_file('corosync.conf.new', \&parse_corosync_conf, 
                                \&write_corosync_conf);
 
+sub check_corosync_conf_exists {
+    my ($silent) = @_;
+
+    $silent = $silent // 0;
+
+    my $exists = -f "$basedir/corosync.conf";
+
+    warn "Corosync config '$basedir/corosync.conf' does not exist - is this node part of a cluster?\n"
+       if !$silent && !$exists;
+
+    return $exists;
+}
+
+# bash completion helpers
+
+sub complete_next_vmid {
+
+    my $vmlist = get_vmlist() || {};
+    my $idlist = $vmlist->{ids} || {};
+
+    for (my $i = 100; $i < 10000; $i++) {
+       return [$i] if !defined($idlist->{$i});
+    }
+
+    return [];
+}
+
+sub complete_vmid {
+
+    my $vmlist = get_vmlist();
+    my $ids = $vmlist->{ids} || {};
+
+    return [ keys %$ids ];
+}
+
+sub complete_local_vmid {
+
+    my $vmlist = get_vmlist();
+    my $ids = $vmlist->{ids} || {};
+
+    my $nodename = PVE::INotify::nodename();
+
+    my $res = [];
+    foreach my $vmid (keys %$ids) {
+       my $d = $ids->{$vmid};
+       next if !$d->{node} || $d->{node} ne $nodename;
+       push @$res, $vmid;
+    }
+
+    return $res;
+}
+
+sub complete_migration_target {
+
+    my $res = [];
+
+    my $nodename = PVE::INotify::nodename();
+
+    my $nodelist = get_nodelist();
+    foreach my $node (@$nodelist) {
+       next if $node eq $nodename;
+       push @$res, $node;
+    }
+
+    return $res;
+}
+
 1;