Monitor/Backends/Libvirt.pm untested

filter: Statementstmt 0.0% 0 / 187 Branchbran 0.0% 0 / 54 Conditioncond 0.0% 0 / 27 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 291 CC 28 SCAR 62.6
CC
28
Cov
0%
run
702.0
usable
12.0
new
2.0
CRAP 522.9
1 package HV::Monitor::Backends::Libvirt;
2  
3 use 5.006;
4 use strict;
5 use warnings;
6 use JSON;
7 use File::Slurp qw(read_file);
8  
9 =head1 NAME
10  
11 HV::Monitor::Backends::Libvirt - Libvirt support for HV::Monitor
12  
13 =head1 VERSION
14  
15 Version 0.0.4
16  
17 =cut
18  
19 our $VERSION = '0.0.4';
20  
21 =head1 SYNOPSIS
22  
23 use HV::MOnitor::Backend::Libvirt;
24
25 my $backend=HV::MOnitor::Backend::CBSD->new;
26
27 my $usable=$backend->usable;
28 if ( $usable ){
29 $return_hash_ref=$backend->run;
30 }
31  
32 =head1 METHODS
33  
34 =head2 new
35  
36 Initiates the backend object.
37  
38 my $backend=HV::MOnitor::Backend::Libvirt->new;
39  
40 =cut
41  
42 sub new {
43 my $self = { version => 1, };
44 bless $self;
45  
46 return $self;
47 }
48  
49 =head2 run
50  
51 $return_hash_ref=$backend->run;
52  
53 =cut
54  
55 sub run {
56 my $self = $_[0];
57  
58 my $hz = `getconf CLK_TCK`;
59 chomp($hz);
60  
61 my $list_raw = `virsh list --all --name`;
62 if ( $? != 0 ) {
63 return {
64 data => { hv => 'libvirt' },
65 version => $self->{version},
66 error => 2,
67 errorString => '"virsh list --all --name" exited non-zero',
68 };
69 }
70  
71 #
72 # build a indexed mapping of netdev to bridge mappings
73 #
74 my @net_list;
75 foreach my $net_name (
76 grep( !/[\ \t]*Name[\ \t]+State[\ \t]+Autostart[\ \t]+Persistent$/,
77 grep( !/^-+$/, split( /\n/, `virsh net-list --all` ) ) )
78 )
79 {
80 $net_name =~ s/^[\ \t]*//;
81 $net_name =~ s/[\ \t]+.*$//;
82 push( @net_list, $net_name );
83 }
84 my $net_cache = {};
85 foreach my $net_name (@net_list) {
86 my ($bridge_dev) = grep( /^Bridge\:/, `virsh net-info $net_name` );
87 $bridge_dev =~ s/^Bridge\:[\ \t]+//;
88 chomp($bridge_dev);
89 $bridge_dev =~ s/[\ \t].*$//;
90 $net_cache->{$net_name} = $bridge_dev;
91 }
92  
93 my @VMs = grep( !/^[\ \t]*$/, split( /\n/, $list_raw ) );
94  
95 my $ifs_raw = `ifconfig | grep '^[A-Za-z]' | cut -d: -f 1`;
96 my @ifs = split( /\n/, $ifs_raw );
97  
98 my $return_hash = {
99 VMs => {},
100 hv => 'libvirt',
101 totals => {
102 'usertime' => 0,
103 'pmem' => 0,
104 'oublk' => 0,
105 'minflt' => 0,
106 'pcpu' => 0,
107 'mem_alloc' => 0,
108 'nvcsw' => 0,
109 'snaps' => 0,
110 'rss' => 0,
111 'snaps_size' => 0,
112 'cpus' => 0,
113 'cow' => 0,
114 'nivcsw' => 0,
115 'systime' => 0,
116 'vsz' => 0,
117 'etimes' => 0,
118 'majflt' => 0,
119 'inblk' => 0,
120 'nswap' => 0,
121 'on' => 0,
122 'off' => 0,
123 'off_hard' => 0,
124 'off_soft' => 0,
125 'unknown' => 0,
126 'paused' => 0,
127 'crashed' => 0,
128 'blocked' => 0,
129 'nostate' => 0,
130 'pmsuspended' => 0,
131 'freqs' => 0,
132 'ftime' => 0,
133 'ipkts' => 0,
134 'ierrs' => 0,
135 'ibytes' => 0,
136 'idrop' => 0,
137 'opkts' => 0,
138 'oerrs' => 0,
139 'obytes' => 0,
140 'coll' => 0,
141 'odrop' => 0,
142 }
143 };
144  
145 # values that should be totaled
146 my @total = (
147 'usertime', 'pmem', 'oublk', 'minflt', 'pcpu', 'mem_alloc',
148 'nvcsw', 'snaps', 'rss', 'snaps_size', 'cpus', 'cow',
149 'nivcsw', 'systime', 'vsz', 'etimes', 'majflt', 'inblk',
150 'nswap', 'disk_alloc', 'disk_in_use', 'rbytes', 'rtime', 'rreqs',
151 'wbytes', 'wreqs', 'ftime', 'freqs', 'wtime', 'disk_on_disk',
152 'snaps', 'freqs', 'ftime', 'ipkts', 'ierrs', 'ibytes',
153 'idrop', 'opkts', 'oerrs', 'obytes', 'coll', 'odrop'
154 );
155  
156 foreach my $vm (@VMs) {
157  
158 my $domstats_raw = `virsh domstats $vm`;
159 my $domstats = {};
160 my @domstats_split = grep( !/^Domain/, grep( !/^[\ \t]*$/, split( /\n/, $domstats_raw ) ) );
161 foreach my $line (@domstats_split) {
162 chomp($line);
163 $line =~ s/^[\ \t]+//;
164 my ( $stat, $value ) = split( /=/, $line, 2 );
165 $domstats->{$stat} = $value;
166 }
167  
168 # The ones below are linux only, so just zeroing here.
169 # syscw syscw rchar wchar rbytes wbytes cwbytes
170 my $vm_info = {
171 mem_alloc => $domstats->{'balloon.maximum'},
172 cpus => $domstats->{'vcpu.maximum'},
173 pcpu => 0,
174 os_type => 0,
175 ip => '',
176 status_int => $domstats->{'state.state'},
177 console_type => '',
178 console => '',
179 snaps_size => 0,
180 ifs => {},
181 rbytes => 0,
182 wbytes => 0,
183 etimes => 0,
184 pmem => 0,
185 cow => 0,
186 majflt => 0,
187 minflt => 0,
188 nice => 0,
189 nivcsw => 0,
190 nswap => 0,
191 nvcsw => 0,
192 inblk => 0,
193 oublk => 0,
194 pri => 0,
195 rss => 0,
196 systime => 0,
197 usertime => 0,
198 vsz => 0,
199 disk_alloc => 0,
200 disk_in_use => 0,
201 disk_on_disk => 0,
202 disks => {},
203 freqs => 0,
204 ftime => 0,
205 ipkts => 0,
206 ierrs => 0,
207 ibytes => 0,
208 idrop => 0,
209 opkts => 0,
210 oerrs => 0,
211 obytes => 0,
212 coll => 0,
213 odrop => 0,
214 };
215  
216 $vm_info->{mem_alloc} = $vm_info->{mem_alloc} * 1024;
217  
218 # https://libvirt.org/html/libvirt-libvirt-domain.html#virDomainState
219 # VIR_DOMAIN_NOSTATE = 0 (0x0) no state
220 # VIR_DOMAIN_RUNNING = 1 (0x1) the domain is running
221 # VIR_DOMAIN_BLOCKED = 2 (0x2) the domain is blocked on resource
222 # VIR_DOMAIN_PAUSED = 3 (0x3) the domain is paused by user
223 # VIR_DOMAIN_SHUTDOWN = 4 (0x4) the domain is being shut down
224 # VIR_DOMAIN_SHUTOFF = 5 (0x5) the domain is shut off
225 # VIR_DOMAIN_CRASHED = 6 (0x6) the domain is crashed
226 # VIR_DOMAIN_PMSUSPENDED = 7 (0x7) the domain is suspended by guest power management
227 my @hv_args;
228 if ( $domstats->{'state.state'} eq 1
229 || $domstats->{'state.state'} eq 3
230 || $domstats->{'state.state'} eq 4 )
231 {
232 my $pid = `ps ax o pid,args | grep qemu | grep ' -name '| grep 'guest='$vm','`;
233 $pid =~ s/^[\ \t]*//;
234 chomp($pid);
235 $pid =~ s/^[\ \t]*//;
236 my $command = $pid;
237 $pid =~ s/[\ \t]+.*$//;
238 $command =~ s/^[0-9]+[\ \t]+//;
239  
240 @hv_args = split( /\n/, `cat /proc/$pid/cmdline | strings` );
241  
242 my $ps_info = `ps -q $pid --no-headers -o pcpu,pmem,etimes,vsz,pri,nice`;
243 $ps_info =~ s/^[\ \t]*//;
244 chomp($ps_info);
245 $ps_info =~ s/^[\ \t]*//;
246 $ps_info =~ s/[\ \t]*$//;
247 ( $vm_info->{pcpu}, $vm_info->{pmem}, $vm_info->{etimes}, $vm_info->{vsz}, $vm_info->{nice} )
248 = split( /[\ \t]+/, $ps_info );
249  
250 my $console_type = 'unknown';
251 my $console_options = $command;
252 if ( $command =~ s/[\ \t]-vnc[\t\ ]// ) {
253 $console_type = 'vnc';
254 $console_options =~ s/.*\-vnc[\t\ ]+//;
255 }
256 elsif ( $command =~ s/[\ \t]-spice[\t\ ]// ) {
257 $console_type = 'spice';
258 $console_options =~ s/.*\-spice[\t\ ]+//;
259 }
260 $console_options =~ s/[\t\ ].*$//;
261 $vm_info->{console_type} = $console_type;
262 $vm_info->{console} = $console_options;
263  
264 eval {
265 my $proc_stat_raw = read_file( '/proc/' . $pid . '/stat' );
266 my @proc_stat = split( /[\ \t]+/, $proc_stat_raw );
267 $vm_info->{majflt} = $proc_stat[10];
268 $vm_info->{minflt} = $proc_stat[9];
269 $vm_info->{usertime} = $proc_stat[13] / $hz;
270 $vm_info->{systime} = $proc_stat[14] / $hz;
271 };
272  
273 eval {
274 my $proc_status_raw = read_file( '/proc/' . $pid . '/status' );
275 my $proc_status = {};
276 foreach my $line ( split( /\n/, $proc_status_raw ) ) {
277 my ( $status_key, $status_value ) = split( /\:/, $line );
278 $status_value =~ s/^[\ \t]*//;
279 $status_value =~ s/[\ \t]*$//;
280 $proc_status->{$status_key} = $status_value;
281 }
282 $vm_info->{nvcsw} = $proc_status->{voluntary_ctxt_switches};
283 $vm_info->{nivcsw} = $proc_status->{nonvoluntary_ctxt_switches};
284 };
285  
286 $vm_info->{rss} = $domstats->{'balloon.rss'};
287  
288 # convert to bytes for easier display
289 if ( defined( $vm_info->{rss} ) ) {
290 $vm_info->{rss} = $vm_info->{rss} * 1024;
291 }
292 else {
293 $vm_info->{rss} = 0;
294 }
295 $vm_info->{vsz} = $vm_info->{rss} * 1024;
296 }
297  
298 #
299 # process interfaces
300 #
301 my $nic_int = 0;
302 while ( defined( $domstats->{ 'net.' . $nic_int . '.name' } ) ) {
303 my $nic_info = {
304 mac => '',
305 parent => '',
306 if => $domstats->{ 'net.' . $nic_int . '.name' },
307 ipkts => $domstats->{ 'net.' . $nic_int . '.rx.pkts' },
308 ierrs => $domstats->{ 'net.' . $nic_int . '.rx.errs' },
309 ibytes => $domstats->{ 'net.' . $nic_int . '.rx.bytes' },
310 idrop => $domstats->{ 'net.' . $nic_int . '.rx.drop' },
311 opkts => $domstats->{ 'net.' . $nic_int . '.tx.pkts' },
312 oerrs => $domstats->{ 'net.' . $nic_int . '.tx.errs' },
313 obytes => $domstats->{ 'net.' . $nic_int . '.tx.bytes' },
314 odrop => $domstats->{ 'net.' . $nic_int . '.tx.drop' },
315 coll => 0,
316 };
317  
318 $vm_info->{ipkts} = $nic_info->{ipkts};
319 $vm_info->{ierrs} = $nic_info->{ierrs};
320 $vm_info->{ibytes} = $nic_info->{ibytes};
321 $vm_info->{idrop} = $nic_info->{odrop};
322 $vm_info->{opkts} = $nic_info->{opkts};
323 $vm_info->{oerrs} = $nic_info->{oerrs};
324 $vm_info->{obytes} = $nic_info->{obytes};
325 $vm_info->{odrop} = $nic_info->{odrop};
326 $vm_info->{coll} = $nic_info->{coll};
327  
328 # get the mac and parent
329 my $netdev = 'net' . $nic_int;
330 my @net_line
331 = grep( /\"mac\"/, grep( /\"netdev\"/, grep( /^[\ \t]*{.*\"$netdev\".*\}[\ \t]*$/, @hv_args ) ) );
332 if ( defined( $net_line[0] ) ) {
333 eval {
334 my $json = decode_json( $net_line[0] );
335 $nic_info->{mac} = $json->{mac};
336 $json->{netdev} =~ s/^[a-zA-Z]+//;
337 if ( defined( $net_list[ $json->{netdev} ] ) ) {
338 if ( defined( $net_cache->{ $net_list[ $json->{netdev} ] } ) ) {
339 $nic_info->{parent} = $net_cache->{ $net_list[ $json->{netdev} ] };
340 }
341 }
342 }
343 }
344 else {
345 # looks like we did not find one that appears to be a JSON style one, so now try for the CSV style
346 @net_line
347 = grep( /virtio-net-pci/, grep( /mac/, grep( /\=$netdev\,/, @hv_args ) ) );
348  
349 # if we failed, now check for it with $netdev at the end of the arg
350 if ( !defined( $net_line[0] ) ) {
351 @net_line
352 = grep( /virtio-net-pci/, grep( /mac/, grep( /\=$netdev$/, @hv_args ) ) );
353 }
354  
355 if ( defined( $net_line[0] ) ) {
356 my @net_line_split = split( /\,/, $net_line[0] );
357 foreach my $net_line_arg (@net_line_split) {
358 my ( $net_line_key, $net_line_value ) = split( /\=/, $net_line_arg, 2 );
359 if ( defined($net_line_key)
360 && defined($net_line_value)
361 && $net_line_value ne ''
362 && $net_line_key ne '' )
363 {
364 if ( $net_line_key eq 'mac' ) {
365 $nic_info->{mac} = $net_line_value;
366 }
367 }
368 }
369 }
370 }
371  
372 $vm_info->{ifs}{ 'nic' . $nic_int } = $nic_info;
373  
374 $nic_int++;
375 }
376  
377 #
378 # process block devices
379 #
380 my $block_int = 0;
381 while ( defined( $domstats->{ 'block.' . $block_int . '.name' } ) ) {
382 my $disk_info = {
383 in_use => $domstats->{ 'block.' . $block_int . '.allocation' },
384 on_disk => $domstats->{ 'block.' . $block_int . '.physical' },
385 alloc => $domstats->{ 'block.' . $block_int . '.capacity' },
386 rbytes => 0,
387 rtime => 0,
388 rreqs => 0,
389 wbytes => 0,
390 wtime => 0,
391 wreqs => 0,
392 freqs => 0,
393 ftime => 0,
394 };
395  
396 if ( defined( $domstats->{ 'block.' . $block_int . '.rd.bytes' } ) ) {
397 $disk_info->{rbytes} = $domstats->{ 'block.' . $block_int . '.rd.bytes' };
398 $disk_info->{rtime} = $domstats->{ 'block.' . $block_int . '.rd.times' } / 1000000;
399 $disk_info->{rreqs} = $domstats->{ 'block.' . $block_int . '.rd.reqs' };
400 $disk_info->{wbytes} = $domstats->{ 'block.' . $block_int . '.wr.bytes' };
401 $disk_info->{wtime} = $domstats->{ 'block.' . $block_int . '.wr.times' } / 1000000;
402 $disk_info->{wreqs} = $domstats->{ 'block.' . $block_int . '.wr.reqs' };
403 $disk_info->{ftime} = $domstats->{ 'block.' . $block_int . '.fl.times' } / 1000000;
404 $disk_info->{freqs} = $domstats->{ 'block.' . $block_int . '.fl.reqs' };
405  
406 $vm_info->{rbytes} += $domstats->{ 'block.' . $block_int . '.rd.bytes' };
407 $vm_info->{rtime} += $disk_info->{rtime};
408 $vm_info->{rreqs} += $domstats->{ 'block.' . $block_int . '.rd.reqs' };
409 $vm_info->{wbytes} += $domstats->{ 'block.' . $block_int . '.wr.bytes' };
410 $vm_info->{wtime} += $disk_info->{wtime};
411 $vm_info->{wreqs} += $domstats->{ 'block.' . $block_int . '.wr.reqs' };
412 $vm_info->{ftime} += $disk_info->{ftime};
413 $vm_info->{freqs} += $domstats->{ 'block.' . $block_int . '.fl.reqs' };
414 }
415  
416 $vm_info->{disks}{ $domstats->{ 'block.' . $block_int . '.name' } } = $disk_info;
417  
418 # skip adding ISO files to the VM total, these are likely used multiple times
419 if ( defined( $domstats->{ 'block.' . $block_int . '.path' } )
420 && $domstats->{ 'block.' . $block_int . '.path' } !~ /\.[Ii][Ss][Oo]$/
421 && defined( $disk_info->{alloc} )
422 && defined( $disk_info->{in_use} )
423 && defined( $disk_info->{on_disk} ) )
424 {
425 $vm_info->{disk_alloc} += $disk_info->{alloc};
426 $vm_info->{disk_in_use} += $disk_info->{in_use};
427 $vm_info->{disk_on_disk} += $disk_info->{on_disk};
428 }
429  
430 $block_int++;
431 }
432  
433 #
434 # get the snapshot count
435 #
436 my @snaps = split( /\n/, `virsh snapshot-list $vm` );
437 $vm_info->{snaps} = $#snaps - 1;
438  
439 #
440 # total the status totals
441 #
442  
443 if ( $vm_info->{status_int} == 0 ) {
444 $return_hash->{totals}{nostate}++;
445 }
446 elsif ( $vm_info->{status_int} == 1 ) {
447 $return_hash->{totals}{on}++;
448 }
449 elsif ( $vm_info->{status_int} == 2 ) {
450 $return_hash->{totals}{blocked}++;
451 }
452 elsif ( $vm_info->{status_int} == 3 ) {
453 $return_hash->{totals}{paused}++;
454 }
455 elsif ( $vm_info->{status_int} == 4 ) {
456 $return_hash->{totals}{off_soft}++;
457 }
458 elsif ( $vm_info->{status_int} == 5 ) {
459 $return_hash->{totals}{off_hard}++;
460 }
461 elsif ( $vm_info->{status_int} == 6 ) {
462 $return_hash->{totals}{crashed}++;
463 }
464 elsif ( $vm_info->{status_int} == 7 ) {
465 $return_hash->{totals}{pmsuspended}++;
466 }
467  
468 #
469 # compute other totals
470 #
471  
472 foreach my $to_total (@total) {
473 if ( defined( $vm_info->{$to_total} ) ) {
474 if ( defined( $return_hash->{totals}{$to_total} ) ) {
475 $return_hash->{totals}{$to_total} = $return_hash->{totals}{$to_total} + $vm_info->{$to_total};
476 }
477 else {
478 $return_hash->{totals}{$to_total} = $vm_info->{$to_total};
479 }
480 }
481 }
482  
483 # save it and go on
484 $return_hash->{VMs}{$vm} = $vm_info;
485 }
486  
487 return {
488 version => $self->{version},
489 error => 0,
490 errorString => '',
491 data => $return_hash,
492 };
493 }
494  
495 =head2 usable
496  
497 Dies if not usable.
498  
499 eval{ $backend->usable; };
500 if ( $@ ){
501 print 'Not usable because... '.$@."\n";
502 }
503  
504 =cut
505  
506 sub usable {
507 my $self = $_[0];
508  
509 # Make sure we are on a OS on which ZFS is usable on.
510 if ( $^O !~ 'linux' ) {
511 die '$^O is "' . $^O . '" and not "linux"';
512 }
513  
514 # make sure we can locate cbsd
515 # Written like this as which on some Linux distros such as CentOS 7 is broken.
516 my $cmd_bin = `/bin/sh -c 'which virsh 2> /dev/null'`;
517 if ( $? != 0 ) {
518 die 'The command "virsh" is not in the path... ' . $ENV{PATH};
519 }
520  
521 return 1;
522 }
523  
524 =head1 AUTHOR
525  
526 Zane C. Bowers-Hadley, C<< <vvelox at vvelox.net> >>
527  
528 =head1 BUGS
529  
530 Please report any bugs or feature requests to C<bug-hv-monitor at rt.cpan.org>, or through
531 the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=HV-Monitor>. I will be notified, and then you'll
532 automatically be notified of progress on your bug as I make changes.
533  
534  
535  
536  
537 =head1 SUPPORT
538  
539 You can find documentation for this module with the perldoc command.
540  
541 perldoc HV::Monitor
542  
543  
544 You can also look for information at:
545  
546 =over 4
547  
548 =item * RT: CPAN's request tracker (report bugs here)
549  
550 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=HV-Monitor>
551  
552 =item * CPAN Ratings
553  
554 L<https://cpanratings.perl.org/d/HV-Monitor>
555  
556 =item * Search CPAN
557  
558 L<https://metacpan.org/release/HV-Monitor>
559  
560 =back
561  
562  
563 =head1 ACKNOWLEDGEMENTS
564  
565  
566 =head1 LICENSE AND COPYRIGHT
567  
568 This software is Copyright (c) 2022 by Zane C. Bowers-Hadley.
569  
570 This is free software, licensed under:
571  
572 The Artistic License 2.0 (GPL Compatible)
573  
574  
575 =cut
576  
577 1;