1 package PVE
::Service
::pvestatd
;
11 use Time
::HiRes qw
(gettimeofday
);
12 use PVE
::Tools
qw(dir_glob_foreach file_read_firstline);
18 use PVE
::Cluster
qw(cfs_read_file);
21 use PVE
::QemuServer
::Monitor
;
25 use PVE
::RPCEnvironment
;
26 use PVE
::API2
::Subscription
;
28 use PVE
::AccessControl
;
29 use PVE
::Ceph
::Services
;
34 use PVE
::Status
::Plugin
;
36 use base
qw(PVE::Daemon);
40 require PVE
::Network
::SDN
;
47 my $nodename = PVE
::INotify
::nodename
();
49 my $cmdline = [$0, @ARGV];
51 my %daemon_options = (restart_on_error
=> 5, stop_wait_time
=> 5);
52 my $daemon = __PACKAGE__-
>new('pvestatd', $cmdline, %daemon_options);
57 $opt_debug = $self->{debug
};
59 PVE
::Cluster
::cfs_update
();
65 syslog
('info' , "server closing");
68 1 while (waitpid(-1, POSIX
::WNOHANG
()) > 0);
70 $self->exit_daemon(0);
79 my $cached_kvm_version = '';
80 my $next_flag_update_time;
81 my $failed_flag_update_delay_sec = 120;
83 sub update_supported_cpuflags
{
84 my $kvm_version = PVE
::QemuServer
::kvm_user_version
();
86 # only update when QEMU/KVM version has changed, as that is the only reason
87 # why flags could change without restarting pvestatd
88 return if $cached_kvm_version && $cached_kvm_version eq $kvm_version;
90 if ($next_flag_update_time && $next_flag_update_time > time()) {
93 $next_flag_update_time = 0;
95 my $supported_cpuflags = eval { PVE
::QemuServer
::query_supported_cpu_flags
() };
98 if (!$supported_cpuflags ||
99 (!$supported_cpuflags->{tcg
} && !$supported_cpuflags->{kvm
})) {
100 # something went wrong, clear broadcast flags and set try-again delay
101 warn "CPU flag detection failed, will try again after delay\n";
102 $next_flag_update_time = time() + $failed_flag_update_delay_sec;
104 $supported_cpuflags = {};
106 # only set cached version if there's actually something to braodcast
107 $cached_kvm_version = $kvm_version;
110 for my $accel ("tcg", "kvm") {
111 if ($supported_cpuflags->{$accel}) {
112 PVE
::Cluster
::broadcast_node_kv
("cpuflags-$accel", join(' ', @{$supported_cpuflags->{$accel}}));
114 # clear potentially invalid data
115 PVE
::Cluster
::broadcast_node_kv
("cpuflags-$accel", '');
120 my $generate_rrd_string = sub {
123 return join(':', map { $_ // 'U' } @$data);
126 sub update_node_status
{
127 my ($status_cfg) = @_;
129 my ($uptime) = PVE
::ProcFSTools
::read_proc_uptime
();
131 my ($avg1, $avg5, $avg15) = PVE
::ProcFSTools
::read_loadavg
();
132 my $stat = PVE
::ProcFSTools
::read_proc_stat
();
133 my $cpuinfo = PVE
::ProcFSTools
::read_cpuinfo
();
134 my $maxcpu = $cpuinfo->{cpus
};
136 update_supported_cpuflags
();
138 my $subinfo = PVE
::INotify
::read_file
('subscription');
139 my $sublevel = $subinfo->{level
} || '';
141 my $netdev = PVE
::ProcFSTools
::read_proc_net_dev
();
142 # traffic from/to physical interface cards
143 my ($netin, $netout) = (0, 0);
144 for my $dev (grep { /^$PVE::Network::PHYSICAL_NIC_RE$/ } keys %$netdev) {
145 $netin += $netdev->{$dev}->{receive
};
146 $netout += $netdev->{$dev}->{transmit
};
149 my $meminfo = PVE
::ProcFSTools
::read_meminfo
();
151 my $dinfo = df
('/', 1); # output is bytes
152 # everything not free is considered to be used
153 my $dused = $dinfo->{blocks
} - $dinfo->{bfree
};
157 my $data = $generate_rrd_string->(
158 [$uptime, $sublevel, $ctime, $avg1, $maxcpu, $stat->{cpu
}, $stat->{wait},
159 $meminfo->{memtotal
}, $meminfo->{memused
},
160 $meminfo->{swaptotal
}, $meminfo->{swapused
},
161 $dinfo->{blocks
}, $dused, $netin, $netout]
163 PVE
::Cluster
::broadcast_rrd
("pve2-node/$nodename", $data);
172 $node_metric->{cpustat
}->@{qw(avg1 avg5 avg15)} = ($avg1, $avg5, $avg15);
173 $node_metric->{cpustat
}->{cpus
} = $maxcpu;
175 my $transactions = PVE
::ExtMetric
::transactions_start
($status_cfg);
176 PVE
::ExtMetric
::update_all
($transactions, 'node', $nodename, $node_metric, $ctime);
177 PVE
::ExtMetric
::transactions_finish
($transactions);
183 my $log = sub { $opt_debug and printf @_ };
185 my $hostmeminfo = PVE
::ProcFSTools
::read_meminfo
();
186 # NOTE: to debug, run 'pvestatd -d' and set memtotal here
187 #$hostmeminfo->{memtotal} = int(2*1024*1024*1024/0.8); # you can set this to test
188 my $hostfreemem = $hostmeminfo->{memtotal
} - $hostmeminfo->{memused
};
190 # try to use ~80% host memory; goal is the change amount required to achieve that
191 my $goal = int($hostmeminfo->{memtotal
} * 0.8 - $hostmeminfo->{memused
});
192 $log->("host goal: $goal free: $hostfreemem total: $hostmeminfo->{memtotal}\n");
194 my $maxchange = 100*1024*1024;
195 my $res = PVE
::AutoBalloon
::compute_alg1
($vmstatus, $goal, $maxchange);
197 for my $vmid (sort keys %$res) {
198 my $target = int($res->{$vmid});
199 my $current = int($vmstatus->{$vmid}->{balloon
});
200 next if $target == $current; # no need to change
202 $log->("BALLOON $vmid to $target (%d)\n", $target - $current);
203 eval { PVE
::QemuServer
::Monitor
::mon_cmd
($vmid, "balloon", value
=> int($target)) };
208 sub update_qemu_status
{
209 my ($status_cfg) = @_;
212 my $vmstatus = PVE
::QemuServer
::vmstatus
(undef, 1);
214 eval { auto_balloning
($vmstatus); };
215 syslog
('err', "auto ballooning error: $@") if $@;
217 my $transactions = PVE
::ExtMetric
::transactions_start
($status_cfg);
218 foreach my $vmid (keys %$vmstatus) {
219 my $d = $vmstatus->{$vmid};
221 my $status = $d->{qmpstatus
} || $d->{status
} || 'stopped';
222 my $template = $d->{template
} ?
$d->{template
} : "0";
223 if ($d->{pid
}) { # running
224 $data = $generate_rrd_string->(
225 [$d->{uptime
}, $d->{name
}, $status, $template, $ctime, $d->{cpus
}, $d->{cpu
},
226 $d->{maxmem
}, $d->{mem
}, $d->{maxdisk
}, $d->{disk
},
227 $d->{netin
}, $d->{netout
}, $d->{diskread
}, $d->{diskwrite
}]);
229 $data = $generate_rrd_string->(
230 [0, $d->{name
}, $status, $template, $ctime, $d->{cpus
}, undef,
231 $d->{maxmem
}, undef, $d->{maxdisk
}, $d->{disk
}, undef, undef, undef, undef]);
233 PVE
::Cluster
::broadcast_rrd
("pve2.3-vm/$vmid", $data);
235 PVE
::ExtMetric
::update_all
($transactions, 'qemu', $vmid, $d, $ctime, $nodename);
238 PVE
::ExtMetric
::transactions_finish
($transactions);
241 sub remove_stale_lxc_consoles
{
243 my $vmstatus = PVE
::LXC
::vmstatus
();
244 my $pidhash = PVE
::LXC
::find_lxc_console_pids
();
246 foreach my $vmid (keys %$pidhash) {
247 next if defined($vmstatus->{$vmid});
248 syslog
('info', "remove stale lxc-console for CT $vmid");
249 foreach my $pid (@{$pidhash->{$vmid}}) {
255 my $rebalance_error_count = {};
258 sub rebalance_lxc_containers
{
259 # Make sure we can find the cpuset controller path:
260 return if $NO_REBALANCE;
261 my $cpuset_base = eval { PVE
::CGroup
::cpuset_controller_path
() };
263 syslog
('info', "could not get cpuset controller path: $err");
266 if (!defined($cpuset_base)) {
271 # Figure out the cpu count & highest ID
272 my $all_cpus = PVE
::CpuSet-
>new_from_path($cpuset_base, 1);
273 my @allowed_cpus = $all_cpus->members();
274 my $cpucount = scalar(@allowed_cpus);
275 my $max_cpuid = $allowed_cpus[-1];
277 my @cpu_ctcount = (0) x
($max_cpuid+1);
280 # A mapping { vmid => cgroup_payload_path } for containers where namespace
281 # separation is active and recognized.
284 my $modify_cpuset = sub {
285 my ($vmid, $cpuset, $newset) = @_;
287 if (!$rebalance_error_count->{$vmid}) {
288 syslog
('info', "modified cpu set for lxc/$vmid: " . $newset->short_string());
292 my $cgbase = $ctinfo->{$vmid};
294 if (defined($cgbase)) {
295 # allow all, so that we can set new cpuset in /ns
296 $all_cpus->write_to_path($cgbase);
298 $newset->write_to_path("$cgbase/ns");
301 warn $err if !$rebalance_error_count->{$vmid}++;
303 $cpuset->write_to_path($cgbase);
305 # also apply to container root cgroup
306 $newset->write_to_path($cgbase);
307 $rebalance_error_count->{$vmid} = 0;
310 # old style container
311 $newset->write_to_path($cgbase);
312 $rebalance_error_count->{$vmid} = 0;
316 warn $err if !$rebalance_error_count->{$vmid}++;
320 my $ctlist = PVE
::LXC
::config_list
();
322 foreach my $vmid (sort keys %$ctlist) {
323 my $cgpath = "$cpuset_base/lxc/$vmid";
324 if (-d
"$cgpath/ns") {
325 $ctinfo->{$vmid} = $cgpath;
327 next; # old style container
330 my ($conf, $cpuset) = eval {(
331 PVE
::LXC
::Config-
>load_config($vmid),
332 PVE
::CpuSet-
>new_from_path($cgpath),
339 my @cpuset_members = $cpuset->members();
341 if (!PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.cgroup.cpuset.cpus')
342 && !PVE
::LXC
::Config-
>has_lxc_entry($conf, 'lxc.cgroup2.cpuset.cpus')
344 my $cores = $conf->{cores
} || $cpucount;
345 $cores = $cpucount if $cores > $cpucount;
347 # see if the number of cores was hot-reduced or hasn't been enacted at all yet
348 my $newset = PVE
::CpuSet-
>new();
349 if ($cores < scalar(@cpuset_members)) {
350 for (my $i = 0; $i < $cores; $i++) {
351 $newset->insert($cpuset_members[$i]);
353 } elsif ($cores > scalar(@cpuset_members)) {
354 my $count = $newset->insert(@cpuset_members);
355 foreach my $cpu (@allowed_cpus) {
356 $count += $newset->insert($cpu);
357 last if $count >= $cores;
360 $newset->insert(@cpuset_members);
363 # Apply hot-plugged changes if any:
364 if (!$newset->is_equal($cpuset)) {
365 @cpuset_members = $newset->members();
366 $modify_cpuset->($vmid, $cpuset, $newset);
369 # Note: no need to rebalance if we already use all cores
370 push @balanced_cts, [$vmid, $cores, $newset]
371 if defined($conf->{cores
}) && ($cores != $cpucount);
374 foreach my $cpu (@cpuset_members) {
375 $cpu_ctcount[$cpu]++ if $cpu <= $max_cpuid;
379 my $find_best_cpu = sub {
380 my ($cpulist, $cpu) = @_;
382 my $cur_cost = $cpu_ctcount[$cpu];
385 foreach my $candidate (@$cpulist) {
386 my $cost = $cpu_ctcount[$candidate];
387 if ($cost < ($cur_cost - 1)) {
389 $cur_cpu = $candidate;
396 foreach my $bct (@balanced_cts) {
397 my ($vmid, $cores, $cpuset) = @$bct;
399 my $rest = [ grep { !$cpuset->has($_) } @allowed_cpus ];
401 my $newset = PVE
::CpuSet-
>new();
402 for my $cpu ($cpuset->members()) {
403 my $best = $find_best_cpu->($rest, $cpu);
405 $cpu_ctcount[$best]++;
406 $cpu_ctcount[$cpu]--;
408 $newset->insert($best);
411 if (!$newset->is_equal($cpuset)) {
412 $modify_cpuset->($vmid, $cpuset, $newset);
417 sub update_lxc_status
{
418 my ($status_cfg) = @_;
421 my $vmstatus = PVE
::LXC
::vmstatus
();
423 my $transactions = PVE
::ExtMetric
::transactions_start
($status_cfg);
425 foreach my $vmid (keys %$vmstatus) {
426 my $d = $vmstatus->{$vmid};
427 my $template = $d->{template
} ?
$d->{template
} : "0";
429 if ($d->{status
} eq 'running') { # running
430 $data = $generate_rrd_string->(
431 [$d->{uptime
}, $d->{name
}, $d->{status
}, $template,
432 $ctime, $d->{cpus
}, $d->{cpu
},
433 $d->{maxmem
}, $d->{mem
},
434 $d->{maxdisk
}, $d->{disk
},
435 $d->{netin
}, $d->{netout
},
436 $d->{diskread
}, $d->{diskwrite
}]);
438 $data = $generate_rrd_string->(
439 [0, $d->{name
}, $d->{status
}, $template, $ctime, $d->{cpus
}, undef,
440 $d->{maxmem
}, undef, $d->{maxdisk
}, $d->{disk
}, undef, undef, undef, undef]);
442 PVE
::Cluster
::broadcast_rrd
("pve2.3-vm/$vmid", $data);
444 PVE
::ExtMetric
::update_all
($transactions, 'lxc', $vmid, $d, $ctime, $nodename);
446 PVE
::ExtMetric
::transactions_finish
($transactions);
449 sub update_storage_status
{
450 my ($status_cfg) = @_;
452 my $cfg = PVE
::Storage
::config
();
454 my $info = PVE
::Storage
::storage_info
($cfg);
456 my $transactions = PVE
::ExtMetric
::transactions_start
($status_cfg);
458 foreach my $storeid (keys %$info) {
459 my $d = $info->{$storeid};
460 next if !$d->{active
};
462 my $data = $generate_rrd_string->([$ctime, $d->{total
}, $d->{used
}]);
464 my $key = "pve2-storage/${nodename}/$storeid";
465 PVE
::Cluster
::broadcast_rrd
($key, $data);
467 PVE
::ExtMetric
::update_all
($transactions, 'storage', $nodename, $storeid, $d, $ctime);
469 PVE
::ExtMetric
::transactions_finish
($transactions);
472 sub rotate_authkeys
{
473 PVE
::AccessControl
::rotate_authkey
() if !PVE
::AccessControl
::check_authkey
(1);
476 sub update_ceph_metadata
{
477 return if !PVE
::Ceph
::Tools
::check_ceph_inited
(1); # nothing to do
479 PVE
::Ceph
::Services
::broadcast_ceph_services
();
481 PVE
::Ceph
::Services
::broadcast_ceph_versions
();
484 sub update_sdn_status
{
487 my ($transport_status, $vnet_status) = PVE
::Network
::SDN
::status
();
489 my $status = $transport_status ? encode_json
($transport_status) : undef;
490 PVE
::Cluster
::broadcast_node_kv
("sdn", $status);
494 my $broadcast_version_info_done = 0;
495 my sub broadcast_version_info
: prototype() {
496 if (!$broadcast_version_info_done) {
497 PVE
::Cluster
::broadcast_node_kv
(
499 encode_json
(PVE
::pvecfg
::version_info
()),
501 $broadcast_version_info_done = 1;
506 # update worker list. This is not really required, but we want to make sure that we also have a
507 # correct list in case of an unexpected crash.
508 my $rpcenv = PVE
::RPCEnvironment
::get
();
511 my $tlist = $rpcenv->active_workers();
512 PVE
::Cluster
::broadcast_tasklist
($tlist);
515 syslog
('err', $err) if $err;
517 my $status_cfg = PVE
::Cluster
::cfs_read_file
('status.cfg');
520 update_node_status
($status_cfg);
523 syslog
('err', "node status update error: $err") if $err;
526 update_qemu_status
($status_cfg);
529 syslog
('err', "qemu status update error: $err") if $err;
532 update_lxc_status
($status_cfg);
535 syslog
('err', "lxc status update error: $err") if $err;
538 rebalance_lxc_containers
();
541 syslog
('err', "lxc cpuset rebalance error: $err") if $err;
544 update_storage_status
($status_cfg);
547 syslog
('err', "storage status update error: $err") if $err;
550 remove_stale_lxc_consoles
();
553 syslog
('err', "lxc console cleanup error: $err") if $err;
559 syslog
('err', "authkey rotation error: $err") if $err;
562 update_ceph_metadata
();
565 syslog
('err', "ceph metadata update error: $err") if $err;
571 syslog
('err', "sdn status update error: $err") if $err;
574 broadcast_version_info
();
577 syslog
('err', "version info update error: $err") if $err;
582 # do not update directly after startup, because install scripts
583 # have a problem with that
587 my $initial_memory_usage;
594 $next_update = time() + $updatetime;
597 my ($ccsec, $cusec) = gettimeofday
();
599 # syslog('info', "start status update");
600 PVE
::Cluster
::cfs_update
();
606 syslog
('err', "status update error: $err");
609 my ($ccsec_end, $cusec_end) = gettimeofday
();
610 my $cptime = ($ccsec_end-$ccsec) + ($cusec_end - $cusec)/1000000;
612 syslog
('info', sprintf("status update time (%.3f seconds)", $cptime))
618 my $mem = PVE
::ProcFSTools
::read_memory_usage
();
619 my $resident_kb = $mem->{resident
} / 1024;
621 if (!defined($initial_memory_usage) || ($cycle < 10)) {
622 $initial_memory_usage = $resident_kb;
624 my $diff = $resident_kb - $initial_memory_usage;
625 if ($diff > 15 * 1024) {
626 syslog
('info', "restarting server after $cycle cycles to " .
627 "reduce memory usage (free $resident_kb ($diff) KB)");
628 $self->restart_daemon();
633 while ((time() < $next_update) &&
634 ($wcount < $updatetime) && # protect against time wrap
635 !$restart_request) { $wcount++; sleep (1); };
637 $self->restart_daemon() if $restart_request;
641 $daemon->register_start_command();
642 $daemon->register_restart_command(1);
643 $daemon->register_stop_command();
644 $daemon->register_status_command();
647 start
=> [ __PACKAGE__
, 'start', []],
648 restart
=> [ __PACKAGE__
, 'restart', []],
649 stop
=> [ __PACKAGE__
, 'stop', []],
650 status
=> [ __PACKAGE__
, 'status', [], undef, sub { print shift . "\n";} ],