]> git.proxmox.com Git - pve-cluster.git/blame - data/PVE/Cluster.pm
cluster: add get_guest_config_properties
[pve-cluster.git] / data / PVE / Cluster.pm
CommitLineData
fe000966
DM
1package PVE::Cluster;
2
3use strict;
7181f622 4use warnings;
57d8355e 5
57d8355e 6use Encode;
fe000966 7use File::stat qw();
462c16b7 8use File::Path qw(make_path);
57d8355e 9use JSON;
26784563 10use Net::SSLeay;
c5204e14 11use POSIX qw(ENOENT);
57d8355e
TL
12use Socket;
13use Storable qw(dclone);
57d8355e 14
c92b7716 15use PVE::Certificate;
fe000966
DM
16use PVE::INotify;
17use PVE::IPCC;
d0ad18e8 18use PVE::JSONSchema;
54d487bf 19use PVE::Network;
57d8355e
TL
20use PVE::SafeSyslog;
21use PVE::Tools qw(run_command);
22
95c44445 23use PVE::Cluster::IPCConst;
57d8355e 24
fe000966
DM
25use base 'Exporter';
26
27our @EXPORT_OK = qw(
28cfs_read_file
29cfs_write_file
30cfs_register_file
31cfs_lock_file);
32
fe000966
DM
33# x509 certificate utils
34
35my $basedir = "/etc/pve";
36my $authdir = "$basedir/priv";
37my $lockdir = "/etc/pve/priv/lock";
38
68491de3 39# cfs and corosync files
e02bdaae
TL
40my $dbfile = "/var/lib/pve-cluster/config.db";
41my $dbbackupdir = "/var/lib/pve-cluster/backup";
fe000966 42
34180e03
TL
43# this is just a readonly copy, the relevant one is in status.c from pmxcfs
44# observed files are the one we can get directly through IPCC, they are cached
45# using a computed version and only those can be used by the cfs_*_file methods
fe000966 46my $observed = {
e1735a61 47 'vzdump.cron' => 1,
1fdf150e 48 'jobs.cfg' => 1,
fe000966
DM
49 'storage.cfg' => 1,
50 'datacenter.cfg' => 1,
f6de131a 51 'replication.cfg' => 1,
cafc7309
DM
52 'corosync.conf' => 1,
53 'corosync.conf.new' => 1,
fe000966
DM
54 'user.cfg' => 1,
55 'domains.cfg' => 1,
56 'priv/shadow.cfg' => 1,
454c3a2c 57 'priv/tfa.cfg' => 1,
7dac5e0e 58 'priv/token.cfg' => 1,
8b84a18a 59 'priv/acme/plugins.cfg' => 1,
fc28c2f8 60 'priv/ipam.db' => 1,
fe000966 61 '/qemu-server/' => 1,
f71eee41 62 '/openvz/' => 1,
7f66b436 63 '/lxc/' => 1,
5a5417e6
DM
64 'ha/crm_commands' => 1,
65 'ha/manager_status' => 1,
66 'ha/resources.cfg' => 1,
67 'ha/groups.cfg' => 1,
e9af3eb7 68 'ha/fence.cfg' => 1,
9d4f69ff 69 'status.cfg' => 1,
22e2ed76 70 'ceph.conf' => 1,
1bb7107a 71 'sdn/vnets.cfg' => 1,
1bb7107a 72 'sdn/zones.cfg' => 1,
1bb7107a 73 'sdn/controllers.cfg' => 1,
c20823f8 74 'sdn/subnets.cfg' => 1,
be1aa34b 75 'sdn/ipams.cfg' => 1,
9d3ea5ef 76 'sdn/dns.cfg' => 1,
a3d44df8 77 'sdn/.running-config' => 1,
9bb0fbe9 78 'virtual-guest/cpu-models.conf' => 1,
fe000966
DM
79};
80
462c16b7
TL
81sub prepare_observed_file_basedirs {
82
393742f6 83 if (!check_cfs_is_mounted(1)) {
462c16b7
TL
84 warn "pmxcfs isn't mounted (/etc/pve), chickening out..\n";
85 return;
86 }
87
88 for my $f (sort keys %$observed) {
89 next if $f !~ m!^(.*)/[^/]+$!;
90 my $dir = "$basedir/$1";
91 next if -e $dir; # can also be a link, so just use -e xist check
92 print "creating directory '$dir' for observerd files\n";
93 make_path($dir);
94 }
95}
96
c5204e14
FG
97sub base_dir {
98 return $basedir;
99}
fe000966 100
c5204e14
FG
101sub auth_dir {
102 return $authdir;
fe000966
DM
103}
104
105sub check_cfs_quorum {
01dddfb9
DM
106 my ($noerr) = @_;
107
fe000966
DM
108 # note: -w filename always return 1 for root, so wee need
109 # to use File::lstat here
110 my $st = File::stat::lstat("$basedir/local");
01dddfb9
DM
111 my $quorate = ($st && (($st->mode & 0200) != 0));
112
113 die "cluster not ready - no quorum?\n" if !$quorate && !$noerr;
114
115 return $quorate;
fe000966
DM
116}
117
118sub check_cfs_is_mounted {
119 my ($noerr) = @_;
120
121 my $res = -l "$basedir/local";
122
4f26cc86 123 die "pve configuration filesystem (pmxcfs) not mounted\n" if !$res && !$noerr;
fe000966
DM
124
125 return $res;
126}
127
fe000966
DM
128my $versions = {};
129my $vmlist = {};
130my $clinfo = {};
131
132my $ipcc_send_rec = sub {
133 my ($msgid, $data) = @_;
134
135 my $res = PVE::IPCC::ipcc_send_rec($msgid, $data);
136
dd856b4d 137 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
fe000966
DM
138
139 return $res;
140};
141
142my $ipcc_send_rec_json = sub {
143 my ($msgid, $data) = @_;
144
145 my $res = PVE::IPCC::ipcc_send_rec($msgid, $data);
146
dd856b4d 147 die "ipcc_send_rec[$msgid] failed: $!\n" if !defined($res) && ($! != 0);
fe000966
DM
148
149 return decode_json($res);
150};
151
152my $ipcc_get_config = sub {
153 my ($path) = @_;
154
155 my $bindata = pack "Z*", $path;
95c44445 156 my $res = PVE::IPCC::ipcc_send_rec(CFS_IPC_GET_CONFIG, $bindata);
2db32d95 157 if (!defined($res)) {
7bac9ca5
WB
158 if ($! != 0) {
159 return undef if $! == ENOENT;
160 die "$!\n";
161 }
2db32d95
DM
162 return '';
163 }
164
165 return $res;
fe000966
DM
166};
167
168my $ipcc_get_status = sub {
169 my ($name, $nodename) = @_;
170
171 my $bindata = pack "Z[256]Z[256]", $name, ($nodename || "");
95c44445 172 return PVE::IPCC::ipcc_send_rec(CFS_IPC_GET_STATUS, $bindata);
fe000966
DM
173};
174
71cc17bc
DC
175my $ipcc_remove_status = sub {
176 my ($name) = @_;
0adf0c5a
TL
177 # we just omit the data payload, pmxcfs takes this as hint and removes this
178 # key from the status hashtable
71cc17bc
DC
179 my $bindata = pack "Z[256]", $name;
180 return &$ipcc_send_rec(CFS_IPC_SET_STATUS, $bindata);
181};
182
fe000966
DM
183my $ipcc_update_status = sub {
184 my ($name, $data) = @_;
185
186 my $raw = ref($data) ? encode_json($data) : $data;
187 # update status
188 my $bindata = pack "Z[256]Z*", $name, $raw;
189
95c44445 190 return &$ipcc_send_rec(CFS_IPC_SET_STATUS, $bindata);
fe000966
DM
191};
192
193my $ipcc_log = sub {
194 my ($priority, $ident, $tag, $msg) = @_;
195
196 my $bindata = pack "CCCZ*Z*Z*", $priority, bytes::length($ident) + 1,
197 bytes::length($tag) + 1, $ident, $tag, $msg;
198
95c44445 199 return &$ipcc_send_rec(CFS_IPC_LOG_CLUSTER_MSG, $bindata);
fe000966
DM
200};
201
202my $ipcc_get_cluster_log = sub {
203 my ($user, $max) = @_;
204
205 $max = 0 if !defined($max);
206
207 my $bindata = pack "VVVVZ*", $max, 0, 0, 0, ($user || "");
95c44445 208 return &$ipcc_send_rec(CFS_IPC_GET_CLUSTER_LOG, $bindata);
fe000966
DM
209};
210
7dac5e0e
FG
211my $ipcc_verify_token = sub {
212 my ($full_token) = @_;
213
214 my $bindata = pack "Z*", $full_token;
215 my $res = PVE::IPCC::ipcc_send_rec(CFS_IPC_VERIFY_TOKEN, $bindata);
216
217 return 1 if $! == 0;
218 return 0 if $! == ENOENT;
219
220 die "$!\n";
221};
222
fe000966
DM
223my $ccache = {};
224
225sub cfs_update {
686801e4 226 my ($fail) = @_;
fe000966 227 eval {
95c44445 228 my $res = &$ipcc_send_rec_json(CFS_IPC_GET_FS_VERSION);
fe000966
DM
229 die "no starttime\n" if !$res->{starttime};
230
231 if (!$res->{starttime} || !$versions->{starttime} ||
232 $res->{starttime} != $versions->{starttime}) {
233 #print "detected changed starttime\n";
234 $vmlist = {};
235 $clinfo = {};
236 $ccache = {};
237 }
238
239 $versions = $res;
240 };
241 my $err = $@;
242 if ($err) {
243 $versions = {};
244 $vmlist = {};
245 $clinfo = {};
246 $ccache = {};
686801e4 247 die $err if $fail;
fe000966
DM
248 warn $err;
249 }
250
251 eval {
252 if (!$clinfo->{version} || $clinfo->{version} != $versions->{clinfo}) {
253 #warn "detected new clinfo\n";
95c44445 254 $clinfo = &$ipcc_send_rec_json(CFS_IPC_GET_CLUSTER_INFO);
fe000966
DM
255 }
256 };
257 $err = $@;
258 if ($err) {
259 $clinfo = {};
686801e4 260 die $err if $fail;
fe000966
DM
261 warn $err;
262 }
263
264 eval {
265 if (!$vmlist->{version} || $vmlist->{version} != $versions->{vmlist}) {
266 #warn "detected new vmlist1\n";
95c44445 267 $vmlist = &$ipcc_send_rec_json(CFS_IPC_GET_GUEST_LIST);
fe000966
DM
268 }
269 };
270 $err = $@;
271 if ($err) {
272 $vmlist = {};
686801e4 273 die $err if $fail;
fe000966
DM
274 warn $err;
275 }
276}
277
278sub get_vmlist {
279 return $vmlist;
280}
281
282sub get_clinfo {
283 return $clinfo;
284}
285
9ddd4ae9
DM
286sub get_members {
287 return $clinfo->{nodelist};
288}
289
fe000966 290sub get_nodelist {
fe000966
DM
291 my $nodelist = $clinfo->{nodelist};
292
fe000966
DM
293 my $nodename = PVE::INotify::nodename();
294
295 if (!$nodelist || !$nodelist->{$nodename}) {
296 return [ $nodename ];
297 }
298
299 return [ keys %$nodelist ];
300}
301
0adf0c5a
TL
302# only stored in a in-memory hashtable inside pmxcfs, local data is gone after
303# a restart (of pmxcfs or the node), peer data is still available then
304# best used for status data, like running (ceph) services, package versions, ...
a26b18e1
DC
305sub broadcast_node_kv {
306 my ($key, $data) = @_;
307
308 if (!defined($data)) {
4d04cad0 309 eval { $ipcc_remove_status->("kv/$key") };
a26b18e1
DC
310 } else {
311 die "cannot send a reference\n" if ref($data);
312 my $size = length($data);
0adf0c5a 313 die "data for '$key' too big\n" if $size >= (32 * 1024); # limit from pmxfs
a26b18e1 314
4d04cad0 315 eval { $ipcc_update_status->("kv/$key", $data) };
a26b18e1 316 }
a26b18e1
DC
317 warn $@ if $@;
318}
319
0adf0c5a 320# nodename is optional
a26b18e1
DC
321sub get_node_kv {
322 my ($key, $nodename) = @_;
323
324 my $res = {};
325 my $get_node_data = sub {
326 my ($node) = @_;
327 my $raw = $ipcc_get_status->("kv/$key", $node);
14000cd7 328 $res->{$node} = unpack("Z*", $raw) if $raw;
a26b18e1
DC
329 };
330
331 if ($nodename) {
332 $get_node_data->($nodename);
333 } else {
4d04cad0 334 for my $node (get_nodelist()->@*) {
a26b18e1
DC
335 $get_node_data->($node);
336 }
337 }
338
339 return $res;
340}
341
3e9a2ecb
DC
342# properties: an array-ref of config properties you want to get, e.g., this
343# is perfect to get multiple properties of a guest _fast_
344# (>100 faster than manual parsing here)
345# vmid: optional, if a valid is passed we only check that one, else return all
346# NOTE: does *not* searches snapshot and PENDING entries sections!
347# NOTE: returns the guest config lines (excluding trailing whitespace) as is,
348# so for non-trivial properties, checking the validity must be done
349# NOTE: no permission check is done, that is the responsibilty of the caller
350sub get_guest_config_properties {
351 my ($properties, $vmid) = @_;
352
353 die "properties required" if !defined($properties);
354
355 my $num_props = scalar(@$properties);
356 die "only up to 255 properties supported" if $num_props > 255;
357 my $bindata = pack "VC", $vmid // 0, $num_props;
358 for my $property (@$properties) {
359 $bindata .= pack "Z*", $property;
360 }
361 my $res = $ipcc_send_rec_json->(CFS_IPC_GET_GUEST_CONFIG_PROPERTIES, $bindata);
362
363 return $res;
364}
365
cf1b19d9
TL
366# property: a config property you want to get, e.g., this is perfect to get
367# the 'lock' entry of a guest _fast_ (>100 faster than manual parsing here)
8a93eeae 368# vmid: optional, if a valid is passed we only check that one, else return all
cf1b19d9 369# NOTE: does *not* searches snapshot and PENDING entries sections!
3e9a2ecb
DC
370# NOTE: returns the guest config lines (excluding trailing whitespace) as is,
371# so for non-trivial properties, checking the validity must be done
372# NOTE: no permission check is done, that is the responsibilty of the caller
cf1b19d9
TL
373sub get_guest_config_property {
374 my ($property, $vmid) = @_;
375
376 die "property is required" if !defined($property);
377
378 my $bindata = pack "VZ*", $vmid // 0, $property;
379 my $res = $ipcc_send_rec_json->(CFS_IPC_GET_GUEST_CONFIG_PROPERTY, $bindata);
380
381 return $res;
382}
383
1b36b6b1 384# $data must be a chronological descending ordered array of tasks
fe000966
DM
385sub broadcast_tasklist {
386 my ($data) = @_;
387
4f26cc86
TL
388 # the serialized list may not get bigger than 128 KiB (CFS_MAX_STATUS_SIZE from pmxcfs)
389 # drop older items until we satisfy this constraint
1b36b6b1 390 my $size = length(encode_json($data));
4f26cc86 391 while ($size >= (32 * 1024)) { # TODO: update to 128 KiB in PVE 8.x
1b36b6b1
TL
392 pop @$data;
393 $size = length(encode_json($data));
394 }
395
4f26cc86 396 eval { $ipcc_update_status->("tasklist", $data) };
fe000966
DM
397 warn $@ if $@;
398}
399
400my $tasklistcache = {};
401
402sub get_tasklist {
403 my ($nodename) = @_;
404
405 my $kvstore = $versions->{kvstore} || {};
406
407 my $nodelist = get_nodelist();
408
409 my $res = [];
410 foreach my $node (@$nodelist) {
411 next if $nodename && ($nodename ne $node);
412 eval {
413 my $ver = $kvstore->{$node}->{tasklist} if $kvstore->{$node};
1f1c5c43
TL
414 my $cache = $tasklistcache->{$node};
415 if (!$cache || !$ver || !$cache->{version} || ($cache->{version} != $ver)) {
416 my $tasks = [];
417 if (my $raw = $ipcc_get_status->("tasklist", $node)) {
aea0f5a6
TL
418 my $json_str = unpack("Z*", $raw);
419 $tasks = decode_json($json_str);
1f1c5c43
TL
420 }
421 push @$res, @$tasks;
422 $tasklistcache->{$node} = {
423 data => $tasks,
fe000966
DM
424 version => $ver,
425 };
1f1c5c43
TL
426 } elsif ($cache && $cache->{data}) {
427 push @$res, $cache->{data}->@*;
fe000966
DM
428 }
429 };
430 my $err = $@;
431 syslog('err', $err) if $err;
432 }
433
434 return $res;
435}
436
437sub broadcast_rrd {
438 my ($rrdid, $data) = @_;
439
440 eval {
441 &$ipcc_update_status("rrd/$rrdid", $data);
442 };
443 my $err = $@;
444
445 warn $err if $err;
446}
447
448my $last_rrd_dump = 0;
449my $last_rrd_data = "";
450
451sub rrd_dump {
452
453 my $ctime = time();
454
455 my $diff = $ctime - $last_rrd_dump;
456 if ($diff < 2) {
457 return $last_rrd_data;
458 }
459
460 my $raw;
461 eval {
95c44445 462 $raw = &$ipcc_send_rec(CFS_IPC_GET_RRD_DUMP);
fe000966
DM
463 };
464 my $err = $@;
465
466 if ($err) {
467 warn $err;
468 return {};
469 }
470
471 my $res = {};
472
c3fabca7
DM
473 if ($raw) {
474 while ($raw =~ s/^(.*)\n//) {
475 my ($key, @ela) = split(/:/, $1);
476 next if !$key;
477 next if !(scalar(@ela) > 1);
d2aae33e 478 $res->{$key} = [ map { $_ eq 'U' ? undef : $_ } @ela ];
c3fabca7 479 }
fe000966
DM
480 }
481
482 $last_rrd_dump = $ctime;
483 $last_rrd_data = $res;
484
485 return $res;
486}
487
fe000966
DM
488
489# a fast way to read files (avoid fuse overhead)
490sub get_config {
491 my ($path) = @_;
492
d3a92ba7 493 return &$ipcc_get_config($path);
fe000966
DM
494}
495
496sub get_cluster_log {
497 my ($user, $max) = @_;
498
499 return &$ipcc_get_cluster_log($user, $max);
500}
501
7dac5e0e
FG
502sub verify_token {
503 my ($userid, $token) = @_;
504
505 return &$ipcc_verify_token("$userid $token");
506}
507
fe000966
DM
508my $file_info = {};
509
510sub cfs_register_file {
511 my ($filename, $parser, $writer) = @_;
512
513 $observed->{$filename} || die "unknown file '$filename'";
514
515 die "file '$filename' already registered" if $file_info->{$filename};
516
517 $file_info->{$filename} = {
518 parser => $parser,
519 writer => $writer,
520 };
521}
522
523my $ccache_read = sub {
524 my ($filename, $parser, $version) = @_;
525
526 $ccache->{$filename} = {} if !$ccache->{$filename};
527
528 my $ci = $ccache->{$filename};
529
d3a92ba7 530 if (!$ci->{version} || !$version || $ci->{version} != $version) {
a79c7743 531 # we always call the parser, even when the file does not exist
d3a92ba7 532 # (in that case $data is undef)
fe000966 533 my $data = get_config($filename);
fe000966
DM
534 $ci->{data} = &$parser("/etc/pve/$filename", $data);
535 $ci->{version} = $version;
536 }
537
538 my $res = ref($ci->{data}) ? dclone($ci->{data}) : $ci->{data};
539
540 return $res;
541};
542
543sub cfs_file_version {
544 my ($filename) = @_;
545
546 my $version;
547 my $infotag;
6e73d5c2 548 if ($filename =~ m!^nodes/[^/]+/(openvz|lxc|qemu-server)/(\d+)\.conf$!) {
f71eee41 549 my ($type, $vmid) = ($1, $2);
fe000966
DM
550 if ($vmlist && $vmlist->{ids} && $vmlist->{ids}->{$vmid}) {
551 $version = $vmlist->{ids}->{$vmid}->{version};
552 }
f71eee41 553 $infotag = "/$type/";
fe000966
DM
554 } else {
555 $infotag = $filename;
556 $version = $versions->{$filename};
557 }
558
559 my $info = $file_info->{$infotag} ||
560 die "unknown file type '$filename'\n";
561
562 return wantarray ? ($version, $info) : $version;
563}
564
565sub cfs_read_file {
566 my ($filename) = @_;
567
c53b111f 568 my ($version, $info) = cfs_file_version($filename);
fe000966
DM
569 my $parser = $info->{parser};
570
571 return &$ccache_read($filename, $parser, $version);
572}
573
574sub cfs_write_file {
575 my ($filename, $data) = @_;
576
c53b111f 577 my ($version, $info) = cfs_file_version($filename);
fe000966
DM
578
579 my $writer = $info->{writer} || die "no writer defined";
580
581 my $fsname = "/etc/pve/$filename";
582
583 my $raw = &$writer($fsname, $data);
584
585 if (my $ci = $ccache->{$filename}) {
586 $ci->{version} = undef;
587 }
588
589 PVE::Tools::file_set_contents($fsname, $raw);
590}
591
592my $cfs_lock = sub {
593 my ($lockid, $timeout, $code, @param) = @_;
594
00ea8428
TL
595 my $prev_alarm = alarm(0); # suspend outer alarm early
596
fe000966 597 my $res;
bcdb1b3a 598 my $got_lock = 0;
fe000966 599
e8c6be91 600 # this timeout is for acquire the lock
fe000966
DM
601 $timeout = 10 if !$timeout;
602
603 my $filename = "$lockdir/$lockid";
604
e085fe6f 605 my $is_code_err = 0;
fe000966
DM
606 eval {
607
608 mkdir $lockdir;
609
610 if (! -d $lockdir) {
6e13e20a 611 die "pve cluster filesystem not online.\n";
fe000966
DM
612 }
613
6e13e20a 614 my $timeout_err = sub { die "got lock request timeout\n"; };
bcdb1b3a 615 local $SIG{ALRM} = $timeout_err;
fe000966 616
bcdb1b3a
TL
617 while (1) {
618 alarm ($timeout);
619 $got_lock = mkdir($filename);
3fb23b5b 620 $timeout = alarm(0) - 1; # we'll sleep for 1s, see down below
bcdb1b3a
TL
621
622 last if $got_lock;
623
3fb23b5b 624 $timeout_err->() if $timeout <= 0;
fe000966 625
e8c6be91 626 print STDERR "trying to acquire cfs lock '$lockid' ...\n";
bcdb1b3a
TL
627 utime (0, 0, $filename); # cfs unlock request
628 sleep(1);
fe000966
DM
629 }
630
631 # fixed command timeout: cfs locks have a timeout of 120
632 # using 60 gives us another 60 seconds to abort the task
e085fe6f 633 local $SIG{ALRM} = sub { die "'$lockid'-locked command timed out - aborting\n"; };
00ea8428 634 alarm(60);
fe000966 635
9c206b2b
DM
636 cfs_update(); # make sure we read latest versions inside code()
637
e085fe6f
TL
638 $is_code_err = 1; # allows to differ between locking and actual-work errors
639
fe000966
DM
640 $res = &$code(@param);
641
642 alarm(0);
643 };
644
645 my $err = $@;
646
6e13e20a 647 $err = "no quorum!\n" if !$got_lock && !check_cfs_quorum(1);
fe000966 648
96857ee4 649 rmdir $filename if $got_lock; # if we held the lock always unlock again
fe000966 650
00ea8428
TL
651 alarm($prev_alarm);
652
fe000966 653 if ($err) {
e085fe6f 654 if (ref($err) eq 'PVE::Exception' || $is_code_err) {
c09b0af5
FG
655 # re-raise defined exceptions
656 $@ = $err;
657 } else {
e085fe6f
TL
658 # add lock info for plain errors comming from the locking itself
659 $@ = "cfs-lock '$lockid' error: $err";
c09b0af5 660 }
fe000966
DM
661 return undef;
662 }
663
664 $@ = undef;
665
666 return $res;
667};
668
669sub cfs_lock_file {
670 my ($filename, $timeout, $code, @param) = @_;
671
672 my $info = $observed->{$filename} || die "unknown file '$filename'";
673
674 my $lockid = "file-$filename";
675 $lockid =~ s/[.\/]/_/g;
676
677 &$cfs_lock($lockid, $timeout, $code, @param);
678}
679
680sub cfs_lock_storage {
681 my ($storeid, $timeout, $code, @param) = @_;
682
683 my $lockid = "storage-$storeid";
684
685 &$cfs_lock($lockid, $timeout, $code, @param);
686}
687
78897707
TL
688sub cfs_lock_domain {
689 my ($domainname, $timeout, $code, @param) = @_;
690
691 my $lockid = "domain-$domainname";
692
693 &$cfs_lock($lockid, $timeout, $code, @param);
694}
695
4790f9f4
FG
696sub cfs_lock_acme {
697 my ($account, $timeout, $code, @param) = @_;
698
699 my $lockid = "acme-$account";
700
701 &$cfs_lock($lockid, $timeout, $code, @param);
702}
703
900b50d9
FG
704sub cfs_lock_authkey {
705 my ($timeout, $code, @param) = @_;
706
707 $cfs_lock->('authkey', $timeout, $code, @param);
31c78985
FG
708}
709
710sub cfs_lock_firewall {
711 my ($scope, $timeout, $code, @param) = @_;
712
713 my $lockid = "firewall-$scope";
714
715 $cfs_lock->($lockid, $timeout, $code, @param);
900b50d9
FG
716}
717
fe000966
DM
718my $log_levels = {
719 "emerg" => 0,
720 "alert" => 1,
721 "crit" => 2,
722 "critical" => 2,
723 "err" => 3,
724 "error" => 3,
725 "warn" => 4,
726 "warning" => 4,
727 "notice" => 5,
728 "info" => 6,
729 "debug" => 7,
730};
731
732sub log_msg {
733 my ($priority, $ident, $msg) = @_;
734
735 if (my $tmp = $log_levels->{$priority}) {
736 $priority = $tmp;
737 }
738
739 die "need numeric log priority" if $priority !~ /^\d+$/;
740
741 my $tag = PVE::SafeSyslog::tag();
742
743 $msg = "empty message" if !$msg;
744
745 $ident = "" if !$ident;
8f2d54ff 746 $ident = encode("ascii", $ident,
fe000966
DM
747 sub { sprintf "\\u%04x", shift });
748
8f2d54ff 749 my $ascii = encode("ascii", $msg, sub { sprintf "\\u%04x", shift });
fe000966
DM
750
751 if ($ident) {
752 syslog($priority, "<%s> %s", $ident, $ascii);
753 } else {
754 syslog($priority, "%s", $ascii);
755 }
756
757 eval { &$ipcc_log($priority, $ident, $tag, $ascii); };
758
759 syslog("err", "writing cluster log failed: $@") if $@;
760}
761
9d76a1bb
DM
762sub check_vmid_unused {
763 my ($vmid, $noerr) = @_;
c53b111f 764
9d76a1bb
DM
765 my $vmlist = get_vmlist();
766
767 my $d = $vmlist->{ids}->{$vmid};
768 return 1 if !defined($d);
c53b111f 769
9d76a1bb
DM
770 return undef if $noerr;
771
4f66b109 772 my $vmtypestr = $d->{type} eq 'qemu' ? 'VM' : 'CT';
e75ccbee 773 die "$vmtypestr $vmid already exists on node '$d->{node}'\n";
9d76a1bb
DM
774}
775
65ff467f
DM
776sub check_node_exists {
777 my ($nodename, $noerr) = @_;
778
779 my $nodelist = $clinfo->{nodelist};
780 return 1 if $nodelist && $nodelist->{$nodename};
781
782 return undef if $noerr;
783
784 die "no such cluster node '$nodename'\n";
785}
786
fe000966
DM
787# this is also used to get the IP of the local node
788sub remote_node_ip {
789 my ($nodename, $noerr) = @_;
790
791 my $nodelist = $clinfo->{nodelist};
792 if ($nodelist && $nodelist->{$nodename}) {
793 if (my $ip = $nodelist->{$nodename}->{ip}) {
fc31f517
WB
794 return $ip if !wantarray;
795 my $family = $nodelist->{$nodename}->{address_family};
796 if (!$family) {
797 $nodelist->{$nodename}->{address_family} =
798 $family =
799 PVE::Tools::get_host_address_family($ip);
800 }
14830160 801 return wantarray ? ($ip, $family) : $ip;
fe000966
DM
802 }
803 }
804
805 # fallback: try to get IP by other means
e064c9b0 806 return PVE::Network::get_ip_from_hostname($nodename, $noerr);
fe000966
DM
807}
808
1904862a
TL
809sub get_node_fingerprint {
810 my ($node) = @_;
811
812 my $cert_path = "/etc/pve/nodes/$node/pve-ssl.pem";
813 my $custom_cert_path = "/etc/pve/nodes/$node/pveproxy-ssl.pem";
814
815 $cert_path = $custom_cert_path if -f $custom_cert_path;
816
c92b7716 817 return PVE::Certificate::get_certificate_fingerprint($cert_path);
1904862a
TL
818}
819
15df58e6
DM
820# bash completion helpers
821
822sub complete_next_vmid {
823
824 my $vmlist = get_vmlist() || {};
825 my $idlist = $vmlist->{ids} || {};
826
827 for (my $i = 100; $i < 10000; $i++) {
828 return [$i] if !defined($idlist->{$i});
829 }
830
831 return [];
832}
833
87515b25
DM
834sub complete_vmid {
835
836 my $vmlist = get_vmlist();
837 my $ids = $vmlist->{ids} || {};
838
839 return [ keys %$ids ];
840}
841
15df58e6
DM
842sub complete_local_vmid {
843
844 my $vmlist = get_vmlist();
845 my $ids = $vmlist->{ids} || {};
846
847 my $nodename = PVE::INotify::nodename();
848
849 my $res = [];
850 foreach my $vmid (keys %$ids) {
851 my $d = $ids->{$vmid};
852 next if !$d->{node} || $d->{node} ne $nodename;
853 push @$res, $vmid;
854 }
855
856 return $res;
857}
858
4dd189df
DM
859sub complete_migration_target {
860
861 my $res = [];
862
863 my $nodename = PVE::INotify::nodename();
864
865 my $nodelist = get_nodelist();
866 foreach my $node (@$nodelist) {
867 next if $node eq $nodename;
868 push @$res, $node;
869 }
870
871 return $res;
872}
873
1f1aef8b 874
a9965358 875# NOTE: filesystem must be offline here, no DB changes allowed
c5204e14 876sub cfs_backup_database {
e02bdaae
TL
877 mkdir $dbbackupdir;
878
e02bdaae 879 my $ctime = time();
a9965358 880 my $backup_fn = "$dbbackupdir/config-$ctime.sql.gz";
e02bdaae 881
a9965358 882 print "backup old database to '$backup_fn'\n";
e02bdaae 883
a9965358
TL
884 my $cmd = [ ['sqlite3', $dbfile, '.dump'], ['gzip', '-', \ ">${backup_fn}"] ];
885 run_command($cmd, 'errmsg' => "cannot backup old database\n");
e02bdaae 886
a9965358
TL
887 my $maxfiles = 10; # purge older backup
888 my $backups = [ sort { $b cmp $a } <$dbbackupdir/config-*.sql.gz> ];
889
890 if ((my $count = scalar(@$backups)) > $maxfiles) {
891 foreach my $f (@$backups[$maxfiles..$count-1]) {
ee0daa88 892 next if $f !~ m/^(\S+)$/; # untaint
a9965358
TL
893 print "delete old backup '$1'\n";
894 unlink $1;
895 }
e02bdaae 896 }
8f64504c 897
c5204e14 898 return $dbfile;
8f64504c 899}
e02bdaae 900
ac68281b 9011;