-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_vmware_api.pl
executable file
·4743 lines (4401 loc) · 166 KB
/
check_vmware_api.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl -w
#
# Nagios plugin to monitor VMware ESX and vSphere servers
#
# License: GPL
# Copyright (c) 2008-2013 op5 AB
# Author: Kostyantyn Hushchyn and op5 <[email protected]>
#
# Contributors:
#
# Patrick Müller, Jeremy Martin, Eric Jonsson, stumpr,
# John Cavanaugh, Libor Klepac, maikmayers, Steffen Poulsen,
# Mark Elliott, simeg, sebastien.prudhomme, Raphael Schitz,
# Mattias Bergsten
#
# For direct contact with any of the op5 developers, send an email to
#
# Discussions are directed to the mailing list [email protected],
# see http://lists.op5.com/mailman/listinfo/op5-users
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
package CheckVMwareAPI;
use strict;
use warnings;
use vars qw($PROGNAME $VERSION $output $values $result $defperfargs);
use Monitoring::Plugin::Functions qw(%STATUS_TEXT);
use Monitoring::Plugin;
use File::Basename;
use HTTP::Date;
use Data::Dumper qw(Dumper);
my $perl_module_instructions="
Download the latest version of the vSphere SDK for Perl from VMware.
In this example we use VMware-vSphere-Perl-SDK-5.1.0-780721.x86_64.tar.gz,
but the instructions should apply to other versions as well.
You may need to install additional packages and Perl modules on your server,
see https://kb.op5.com/x/pYEK for
more information and package names for op5 APS / CentOS 6 / RHEL 6.
Upload the .tar.gz file to your op5 Monitor server's /root dir and execute:
cd /root
tar xvzf VMware-vSphere-Perl-SDK-5.1.0-780721.x86_64.tar.gz
cd vmware-vsphere-cli-distrib/
./vmware-install.pl
Follow the on screen instructions, described below:
\"Creating a new vSphere CLI installer database using the tar4 format.
Installing vSphere CLI 5.1.0 build-780721 for Linux.
You must read and accept the vSphere CLI End User License Agreement to
continue.
Press enter to display it.\"
<ENTER>
\"Read through the License Agreement\"
\"Do you accept? (yes/no)
yes
\"In which directory do you want to install the executable files? [/usr/bin]\"
<ENTER>
\"Please wait while copying vSphere CLI files...
The installation of vSphere CLI 5.1.0 build-780721 for Linux completed
successfully. You can decide to remove this software from your system at any
time by invoking the following command:
\"/usr/bin/vmware-uninstall-vSphere-CLI.pl\".
This installer has successfully installed both vSphere CLI and the vSphere SDK
for Perl.
The following Perl modules were found on the system but may be too old to work
with vSphere CLI:
Compress::Zlib 2.037 or newer
Compress::Raw::Zlib 2.037 or newer
version 0.78 or newer
IO::Compress::Base 2.037 or newer
IO::Compress::Zlib::Constants 2.037 or newer
LWP::Protocol::https 5.805 or newer
Enjoy,
--the VMware team\"
Note: None of the Perl modules mentioned as \"may be too old\" are needed for check_vmware_api to work.
";
sub main {
$PROGNAME = basename($0);
$VERSION = '0.7.1';
my $np = Monitoring::Plugin->new(
usage => "Usage: %s -D <data_center> | -H <host_name> [ -C <cluster_name> ] [ -N <vm_name> ]\n"
. " -u <user> -p <pass> | -f <authfile>\n"
. " -l <command> [ -s <subcommand> ] [ -T <timeshift> ] [ -i <interval> ]\n"
. " [ -x <black_list> ] [ -o <additional_options> ]\n"
. " [ -t <timeout> ] [ -w <warn_range> ] [ -c <crit_range> ]\n"
. ' [ -V ] [ -h ]',
version => $VERSION,
plugin => $PROGNAME,
shortname => uc($PROGNAME),
blurb => 'VMware ESX/vSphere plugin',
extra => "Supported commands(^ - blank or not specified parameter, o - options, T - timeshift value, b - blacklist) :\n"
. " VM specific :\n"
. " * cpu - shows cpu info\n"
. " + usage - CPU usage in percentage\n"
. " + usagemhz - CPU usage in MHz\n"
. " + wait - CPU wait time in ms\n"
. " + ready - CPU ready time in ms\n"
. " ^ all cpu info(no thresholds)\n"
. " * mem - shows mem info\n"
. " + usage - mem usage in percentage\n"
. " + usagemb - mem usage in MB\n"
. " + swap - swap mem usage in MB\n"
. " + swapin - swapin mem usage in MB\n"
. " + swapout - swapout mem usage in MB\n"
. " + overhead - additional mem used by VM Server in MB\n"
. " + overall - overall mem used by VM Server in MB\n"
. " + active - active mem usage in MB\n"
. " + memctl - mem used by VM memory control driver(vmmemctl) that controls ballooning\n"
. " ^ all mem info(except overall and no thresholds)\n"
. " * net - shows net info\n"
. " + usage - overall network usage in KBps(Kilobytes per Second)\n"
. " + receive - receive in KBps(Kilobytes per Second)\n"
. " + send - send in KBps(Kilobytes per Second)\n"
. " ^ all net info(except usage and no thresholds)\n"
. " * io - shows disk I/O info\n"
. " + usage - overall disk usage in MB/s\n"
. " + read - read disk usage in MB/s\n"
. " + write - write disk usage in MB/s\n"
. " ^ all disk io info(no thresholds)\n"
. " * runtime - shows runtime info\n"
. " + con - connection state\n"
. " + cpu - allocated CPU in MHz\n"
. " + mem - allocated mem in MB\n"
. " + state - virtual machine state (UP, DOWN, SUSPENDED)\n"
. " + status - overall object status (gray/green/red/yellow)\n"
. " + consoleconnections - console connections to VM\n"
. " + guest - guest OS status, needs VMware Tools\n"
. " + tools - VMware Tools status\n"
. " + issues - all issues for the host\n"
. " ^ all runtime info(except con and no thresholds)\n"
. " Host specific :\n"
. " * cpu - shows cpu info\n"
. " + usage - CPU usage in percentage\n"
. " o quickstats - switch for query either PerfCounter values or Runtime info\n"
. " + usagemhz - CPU usage in MHz\n"
. " o quickstats - switch for query either PerfCounter values or Runtime info\n"
. " ^ all cpu info\n"
. " o quickstats - switch for query either PerfCounter values or Runtime info\n"
. " * mem - shows mem info\n"
. " + usage - mem usage in percentage\n"
. " o quickstats - switch for query either PerfCounter values or Runtime info\n"
. " + usagemb - mem usage in MB\n"
. " o quickstats - switch for query either PerfCounter values or Runtime info\n"
. " + swap - swap mem usage in MB\n"
. " o listvm - turn on/off output list of swapping VM's\n"
. " + overhead - additional mem used by VM Server in MB\n"
. " + overall - overall mem used by VM Server in MB\n"
. " + memctl - mem used by VM memory control driver(vmmemctl) that controls ballooning\n"
. " o listvm - turn on/off output list of ballooning VM's\n"
. " ^ all mem info(except overall and no thresholds)\n"
. " * net - shows net info\n"
. " + usage - overall network usage in KBps(Kilobytes per Second)\n"
. " + receive - receive in KBps(Kilobytes per Second)\n"
. " + send - send in KBps(Kilobytes per Second)\n"
. " + nic - makes sure all active NICs are plugged in\n"
. " ^ all net info(except usage and no thresholds)\n"
. " * io - shows disk io info\n"
. " + aborted - aborted commands count\n"
. " + resets - bus resets count\n"
. " + read - read latency in ms (totalReadLatency.average)\n"
. " + write - write latency in ms (totalWriteLatency.average)\n"
. " + kernel - kernel latency in ms\n"
. " + device - device latency in ms\n"
. " + queue - queue latency in ms\n"
. " ^ all disk io info\n"
. " * vmfs - shows Datastore info\n"
. " + (name) - free space info for datastore with name (name)\n"
. " o used - output used space instead of free\n"
. " o brief - list only alerting volumes\n"
. " o regexp - whether to treat name as regexp\n"
. " o blacklistregexp - whether to treat blacklist as regexp\n"
. " b - blacklist VMFS's\n"
. " T (value) - timeshift to detemine if we need to refresh\n"
. " ^ all datastore info\n"
. " o used - output used space instead of free\n"
. " o brief - list only alerting volumes\n"
. " o blacklistregexp - whether to treat blacklist as regexp\n"
. " b - blacklist VMFS's\n"
. " T (value) - timeshift to detemine if we need to refresh\n"
. " * runtime - shows runtime info\n"
. " + con - connection state\n"
. " + health - checks cpu/storage/memory/sensor status and propagates worst state\n"
. " o listitems - list all available sensors(use for listing purpose only)\n"
. " o blackregexpflag - whether to treat blacklist as regexp\n"
. " b - blacklist status objects\n"
. " + storagehealth - storage status check\n"
. " o blackregexpflag - whether to treat blacklist as regexp\n"
. " b - blacklist status objects\n"
. " + temperature - temperature sensors\n"
. " o blackregexpflag - whether to treat blacklist as regexp\n"
. " b - blacklist status objects\n"
. " + sensor - threshold specified sensor\n"
. " + maintenance - shows whether host is in maintenance mode\n"
. " o maintwarn - sets warning state when host is in maintenance mode\n"
. " o maintcrit - sets critical state when host is in maintenance mode\n"
. " + list(vm) - list of VMware machines and their statuses\n"
. " + status - overall object status (gray/green/red/yellow)\n"
. " + issues - all issues for the host\n"
. " b - blacklist issues\n"
. " ^ all runtime info(health, storagehealth, temperature and sensor are represented as one value and no thresholds)\n"
. " * service - shows Host service info\n"
. " + (names) - check the state of one or several services specified by (names), syntax for (names):<service1>,<service2>,...,<serviceN>\n"
. " ^ show all services\n"
. " * storage - shows Host storage info\n"
. " + adapter - list bus adapters\n"
. " b - blacklist adapters\n"
. " + lun - list SCSI logical units\n"
. " b - blacklist LUN's\n"
. " + path - list logical unit paths\n"
. " b - blacklist paths\n"
. " ^ show all storage info\n"
. " * uptime - shows Host uptime\n"
. " o quickstats - switch for query either PerfCounter values or Runtime info\n"
. " * device - shows Host specific device info\n"
. " + cd/dvd - list vm's with attached cd/dvd drives\n"
. " o listall - list all available devices(use for listing purpose only)\n"
. " DC specific :\n"
. " * cpu - shows cpu info\n"
. " + usage - CPU usage in percentage\n"
. " o quickstats - switch for query either PerfCounter values or Runtime info\n"
. " + usagemhz - CPU usage in MHz\n"
. " o quickstats - switch for query either PerfCounter values or Runtime info\n"
. " ^ all cpu info\n"
. " o quickstats - switch for query either PerfCounter values or Runtime info\n"
. " * mem - shows mem info\n"
. " + usage - mem usage in percentage\n"
. " o quickstats - switch for query either PerfCounter values or Runtime info\n"
. " + usagemb - mem usage in MB\n"
. " o quickstats - switch for query either PerfCounter values or Runtime info\n"
. " + swap - swap mem usage in MB\n"
. " + overhead - additional mem used by VM Server in MB\n"
. " + overall - overall mem used by VM Server in MB\n"
. " + memctl - mem used by VM memory control driver(vmmemctl) that controls ballooning\n"
. " ^ all mem info(except overall and no thresholds)\n"
. " * net - shows net info\n"
. " + usage - overall network usage in KBps(Kilobytes per Second)\n"
. " + receive - receive in KBps(Kilobytes per Second)\n"
. " + send - send in KBps(Kilobytes per Second)\n"
. " ^ all net info(except usage and no thresholds)\n"
. " * io - shows disk io info\n"
. " + aborted - aborted commands count\n"
. " + resets - bus resets count\n"
. " + read - read latency in ms (totalReadLatency.average)\n"
. " + write - write latency in ms (totalWriteLatency.average)\n"
. " + kernel - kernel latency in ms\n"
. " + device - device latency in ms\n"
. " + queue - queue latency in ms\n"
. " ^ all disk io info\n"
. " * vmfs - shows Datastore info\n"
. " + (name) - free space info for datastore with name (name)\n"
. " o used - output used space instead of free\n"
. " o brief - list only alerting volumes\n"
. " o regexp - whether to treat name as regexp\n"
. " o blacklistregexp - whether to treat blacklist as regexp\n"
. " b - blacklist VMFS's\n"
. " T (value) - timeshift to detemine if we need to refresh\n"
. " ^ all datastore info\n"
. " o used - output used space instead of free\n"
. " o brief - list only alerting volumes\n"
. " o blacklistregexp - whether to treat blacklist as regexp\n"
. " b - blacklist VMFS's\n"
. " T (value) - timeshift to detemine if we need to refresh\n"
. " * runtime - shows runtime info\n"
. " + list(vm) - list of VMware machines and their statuses\n"
. " + listhost - list of VMware esx host servers and their statuses\n"
. " + listcluster - list of VMware clusters and their statuses\n"
. " + tools - VMware Tools status\n"
. " b - blacklist VM's\n"
. " + status - overall object status (gray/green/red/yellow)\n"
. " + issues - all issues for the host\n"
. " b - blacklist issues\n"
. " ^ all runtime info(except cluster and tools and no thresholds)\n"
. " * recommendations - shows recommendations for cluster\n"
. " + (name) - recommendations for cluster with name (name)\n"
. " ^ all clusters recommendations\n"
. " Cluster specific :\n"
. " * cpu - shows cpu info\n"
. " + usage - CPU usage in percentage\n"
. " + usagemhz - CPU usage in MHz\n"
. " ^ all cpu info\n"
. " * mem - shows mem info\n"
. " + usage - mem usage in percentage\n"
. " + usagemb - mem usage in MB\n"
. " + swap - swap mem usage in MB\n"
. " o listvm - turn on/off output list of swapping VM's\n"
. " + memctl - mem used by VM memory control driver(vmmemctl) that controls ballooning\n"
. " o listvm - turn on/off output list of ballooning VM's\n"
. " ^ all mem info(plus overhead and no thresholds)\n"
. " * cluster - shows cluster services info\n"
. " + effectivecpu - total available cpu resources of all hosts within cluster\n"
. " + effectivemem - total amount of machine memory of all hosts in the cluster\n"
. " + failover - VMware HA number of failures that can be tolerated\n"
. " + cpufairness - fairness of distributed cpu resource allocation\n"
. " + memfairness - fairness of distributed mem resource allocation\n"
. " ^ only effectivecpu and effectivemem values for cluster services\n"
. " * runtime - shows runtime info\n"
. " + list(vm) - list of VMware machines in cluster and their statuses\n"
. " + listhost - list of VMware esx host servers in cluster and their statuses\n"
. " + status - overall cluster status (gray/green/red/yellow)\n"
. " + issues - all issues for the cluster\n"
. " b - blacklist issues\n"
. " ^ all cluster runtime info\n"
. " * vmfs - shows Datastore info\n"
. " + (name) - free space info for datastore with name (name)\n"
. " o used - output used space instead of free\n"
. " o brief - list only alerting volumes\n"
. " o regexp - whether to treat name as regexp\n"
. " o blacklistregexp - whether to treat blacklist as regexp\n"
. " b - blacklist VMFS's\n"
. " T (value) - timeshift to detemine if we need to refresh\n"
. " ^ all datastore info\n"
. " o used - output used space instead of free\n"
. " o brief - list only alerting volumes\n"
. " o blacklistregexp - whether to treat blacklist as regexp\n"
. " b - blacklist VMFS's\n"
. " T (value) - timeshift to detemine if we need to refresh\n"
. "\n\nCopyright (c) 2008-2013 op5",
timeout => 30,
);
$np->add_arg(
spec => 'host|H=s',
help => "-H, --host=<hostname>\n"
. ' ESX or ESXi hostname.',
required => 0,
);
$np->add_arg(
spec => 'cluster|C=s',
help => "-C, --cluster=<clustername>\n"
. ' ESX or ESXi clustername.',
required => 0,
);
$np->add_arg(
spec => 'datacenter|D=s',
help => "-D, --datacenter=<DCname>\n"
. ' Datacenter hostname.',
required => 0,
);
$np->add_arg(
spec => 'name|N=s',
help => "-N, --name=<vmname>\n"
. ' Virtual machine name.',
required => 0,
);
$np->add_arg(
spec => 'username|u=s',
help => "-u, --username=<username>\n"
. ' Username to connect with.',
required => 0,
);
$np->add_arg(
spec => 'password|p=s',
help => "-p, --password=<password>\n"
. ' Password to use with the username.',
required => 0,
);
$np->add_arg(
spec => 'authfile|f=s',
help => "-f, --authfile=<path>\n"
. " Authentication file with login and password. File syntax :\n"
. " username=<login>\n"
. ' password=<password>',
required => 0,
);
$np->add_arg(
spec => 'warning|w=s',
help => "-w, --warning=THRESHOLD\n"
. " Warning threshold. See\n"
. " http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT\n"
. ' for the threshold format. By default, no threshold is set.',
required => 0,
);
$np->add_arg(
spec => 'critical|c=s',
help => "-c, --critical=THRESHOLD\n"
. " Critical threshold. See\n"
. " http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT\n"
. ' for the threshold format. By default, no threshold is set.',
required => 0,
);
$np->add_arg(
spec => 'command|l=s',
help => "-l, --command=COMMAND\n"
. ' Specify command type (CPU, MEM, NET, IO, VMFS, RUNTIME, ...)',
required => 1,
);
$np->add_arg(
spec => 'subcommand|s=s',
help => "-s, --subcommand=SUBCOMMAND\n"
. ' Specify subcommand',
required => 0,
);
$np->add_arg(
spec => 'sessionfile|S=s',
help => "-S, --sessionfile=SESSIONFILE\n"
. ' Specify a filename to store sessions for faster authentication',
required => 0,
);
$np->add_arg(
spec => 'exclude|x=s',
help => "-x, --exclude=<black_list>\n"
. ' Specify black list',
required => 0,
);
$np->add_arg(
spec => 'options|o=s',
help => "-o, --options=<additional_options> \n"
. ' Specify additional command options (quickstats, ...)',
required => 0,
);
$np->add_arg(
spec => 'timestamp|T=i',
help => "-T, --timestamp=<timeshift> \n"
. ' Timeshift in seconds that could fix issues with "Unknown error". Use values like 5, 10, 20, etc',
required => 0,
);
$np->add_arg(
spec => 'interval|i=s',
help => "-i, --interval=<sampling period> \n"
. " Sampling Period in seconds. Basic historic intervals: 300, 1800, 7200 or 86400. See config for any changes.\n"
. " Supports literval values to autonegotiate interval value: r - realtime interval, h<number> - historical interval specified by position.\n"
. ' Default value is 20 (realtime). Since cluster does not have realtime stats interval other than 20(default realtime) is mandatory.',
required => 0,
);
$np->add_arg(
spec => 'maxsamples|M=s',
help => "-M, --maxsamples=<max sample count> \n"
. " Maximum number of samples to retrieve. Max sample number is ignored for historic intervals.\n"
. ' Default value is 1 (latest available sample). ',
required => 0,
);
$np->add_arg(
spec => 'trace=s',
help => "--trace=<level> \n"
. ' Set verbosity level of vSphere API request/respond trace',
required => 0,
);
$np->add_arg(
spec => 'generate_test=s',
help => "--generate_test=<file> \n"
. ' Generate a test case script from the executed command/subcommand and write it to <file>.'
. ' If <file> is "stdout", the test case script is written to stdout instead.',
default => 0,
required => 0,
);
$np->getopts;
my $host = $np->opts->host;
my $cluster = $np->opts->cluster;
my $datacenter = $np->opts->datacenter;
my $vmname = $np->opts->name;
my $username = $np->opts->username;
my $password = $np->opts->password;
my $authfile = $np->opts->authfile;
my $warning = $np->opts->warning;
my $critical = $np->opts->critical;
my $command = $np->opts->command;
my $subcommand = $np->opts->subcommand;
my $sessionfile = $np->opts->sessionfile;
my $blacklist = $np->opts->exclude;
my $addopts = $np->opts->options;
my $trace = $np->opts->trace;
my $generate_test = $np->opts->generate_test;
my $timeshift = $np->opts->timestamp;
my $interval = $np->opts->interval;
my $maxsamples = $np->opts->maxsamples;
my $timeout = $np->opts->timeout;
my $percw;
my $percc;
if ($generate_test) {
if (uc($generate_test) ne "STDOUT") {
-e $generate_test and die("cowardly refusing to write test case script to existing file ${generate_test}");
}
use LWP::UserAgent;
my $cref = *LWP::UserAgent::request{CODE};
{
no warnings 'redefine';
*LWP::UserAgent::request = sub {
my $r = &{$cref}(@_); #$r is (hopefully) a SOAP response as returned by the VMware WS
if (uc($generate_test) ne "STDOUT") {
open TEST_SCRIPT, ">>", $generate_test;
print TEST_SCRIPT $r->content . "\n!\n"; #print the response content to the target script. separate messages by '!' for easy parsing
} else {
print $r->content . "\n";
}
$r #pass it on
};
}
}
eval {
require VMware::VIRuntime;
} or Monitoring::Plugin::Functions::plugin_exit(UNKNOWN, "Missing perl module VMware::VIRuntime. Download and install \'VMware vSphere SDK for Perl\', available at https://my.vmware.com/group/vmware/downloads\n $perl_module_instructions"); #This is, potentially, a lie. This might just as well fail if a dependency of VMware::VIRuntime is missing (i.e VIRuntime itself requires something which in turn fails).
alarm($timeout) if $timeout;
$output = "Unknown ERROR!";
$result = CRITICAL;
if (defined($subcommand))
{
$subcommand = undef if ($subcommand eq '');
}
if (defined($critical))
{
($percc, $critical) = check_percantage($critical);
$critical = undef if ($critical eq '');
}
if (defined($warning))
{
($percw, $warning) = check_percantage($warning);
$warning = undef if ($warning eq '');
}
$np->set_thresholds(critical => $critical, warning => $warning);
$defperfargs = {};
$defperfargs->{timeshift} = $timeshift if (defined($timeshift));
$defperfargs->{interval} = $interval if (defined($interval));
$defperfargs->{maxsamples} = $maxsamples if (defined($maxsamples));
eval
{
die "Provide either Password/Username or Auth file or Session file\n" if ((!defined($password) || !defined($username) || defined($authfile)) && (defined($password) || defined($username) || !defined($authfile)) && (defined($password) || defined($username) || defined($authfile) || !defined($sessionfile)));
die "Both threshold values must be the same units\n" if (($percw && !$percc && defined($critical)) || (!$percw && $percc && defined($warning)));
if (defined($authfile))
{
open (AUTH_FILE, $authfile) || die "Unable to open auth file \"$authfile\"\n";
while( <AUTH_FILE> ) {
if(s/^[ \t]*username[ \t]*=//){
s/^\s+//;s/\s+$//;
$username = $_;
}
if(s/^[ \t]*password[ \t]*=//){
s/^\s+//;s/\s+$//;
$password = $_;
}
}
die "Auth file must contain both username and password\n" if (!(defined($username) && defined($password)));
}
my $host_address;
if (defined($datacenter))
{
$host_address = $datacenter;
}
elsif (defined($host))
{
$host_address = $host;
}
else
{
$np->plugin_exit(CRITICAL, "No Host or Datacenter specified");
}
$host_address .= ":443" if (index($host_address, ":") == -1);
if (not $host_address =~ '^.*://.*$') {
$host_address = "https://" . $host_address . "/sdk/webService";
}
if (defined($sessionfile) and -e $sessionfile)
{
Opts::set_option("sessionfile", $sessionfile);
Vim::load_session(service_url => $host_address, session_file => $sessionfile);
eval {
Util::connect();
die "Connected host doesn't match reqested once\n" if (Opts::get_option("url") ne $host_address);
};
if ($@) {
Opts::set_option("sessionfile", undef);
Util::connect();
}
}
else
{
Util::connect($host_address, $username, $password);
}
if (defined($sessionfile))
{
Vim::save_session(session_file => $sessionfile);
}
if (defined($trace))
{
$Util::tracelevel = $Util::tracelevel;
$Util::tracelevel = $trace if (($trace =~ m/^\d$/) && ($trace >= 0) && ($trace <= 4));
}
$command = uc($command);
if (defined($vmname))
{
if ($command eq "CPU")
{
($result, $output) = vm_cpu_info($vmname, $np, local_uc($subcommand));
}
elsif ($command eq "MEM")
{
($result, $output) = vm_mem_info($vmname, $np, local_uc($subcommand));
}
elsif ($command eq "NET")
{
($result, $output) = vm_net_info($vmname, $np, local_uc($subcommand));
}
elsif ($command eq "IO")
{
($result, $output) = vm_disk_io_info($vmname, $np, local_uc($subcommand));
}
elsif ($command eq "RUNTIME")
{
($result, $output) = vm_runtime_info($vmname, $np, local_uc($subcommand));
}
else
{
$output = "Unknown HOST-VM command\n" . $np->opts->_help;
$result = CRITICAL;
}
}
elsif (defined($host))
{
my $esx;
$esx = {name => $host} if (defined($datacenter));
if ($command eq "CPU")
{
($result, $output) = host_cpu_info($esx, $np, local_uc($subcommand), $addopts);
}
elsif ($command eq "MEM")
{
($result, $output) = host_mem_info($esx, $np, local_uc($subcommand), $addopts);
}
elsif ($command eq "NET")
{
($result, $output) = host_net_info($esx, $np, local_uc($subcommand));
}
elsif ($command eq "IO")
{
($result, $output) = host_disk_io_info($esx, $np, local_uc($subcommand));
}
elsif ($command eq "VMFS")
{
($result, $output) = host_list_vm_volumes_info($esx, $np, $subcommand, $blacklist, $percc || $percw, $addopts);
}
elsif ($command eq "RUNTIME")
{
($result, $output) = host_runtime_info($esx, $np, local_uc($subcommand), $blacklist, $addopts);
}
elsif ($command eq "SERVICE")
{
($result, $output) = host_service_info($esx, $np, $subcommand);
}
elsif ($command eq "STORAGE")
{
($result, $output) = host_storage_info($esx, $np, local_uc($subcommand), $blacklist);
}
elsif ($command eq "UPTIME")
{
($result, $output) = host_uptime_info($esx, $np, $addopts);
}
elsif ($command eq "DEVICE")
{
($result, $output) = host_device_info($esx, $np, $subcommand, $addopts);
}
else
{
$output = "Unknown HOST command\n" . $np->opts->_help;
$result = CRITICAL;
}
}
elsif (defined($cluster))
{
if ($command eq "CPU")
{
($result, $output) = cluster_cpu_info($cluster, $np, local_uc($subcommand));
}
elsif ($command eq "MEM")
{
($result, $output) = cluster_mem_info($cluster, $np, local_uc($subcommand), $addopts);
}
elsif ($command eq "CLUSTER")
{
($result, $output) = cluster_cluster_info($cluster, $np, local_uc($subcommand));
}
elsif ($command eq "VMFS")
{
($result, $output) = cluster_list_vm_volumes_info($cluster, $np, $subcommand, $blacklist, $percc || $percw, $addopts);
}
elsif ($command eq "RUNTIME")
{
($result, $output) = cluster_runtime_info($cluster, $np, local_uc($subcommand), $blacklist);
}
else
{
$output = "Unknown CLUSTER command\n" . $np->opts->_help;
$result = CRITICAL;
}
}
else
{
if ($command eq "RECOMMENDATIONS")
{
my $cluster_name;
$cluster_name = {name => $subcommand} if (defined($subcommand));
($result, $output) = return_cluster_DRS_recommendations($np, $cluster_name);
}
elsif ($command eq "CPU")
{
($result, $output) = dc_cpu_info($np, local_uc($subcommand), $addopts);
}
elsif ($command eq "MEM")
{
($result, $output) = dc_mem_info($np, local_uc($subcommand), $addopts);
}
elsif ($command eq "NET")
{
($result, $output) = dc_net_info($np, local_uc($subcommand));
}
elsif ($command eq "IO")
{
($result, $output) = dc_disk_io_info($np, local_uc($subcommand));
}
elsif ($command eq "VMFS")
{
($result, $output) = dc_list_vm_volumes_info($np, $subcommand, $blacklist, $percc || $percw, $addopts);
}
elsif ($command eq "RUNTIME")
{
($result, $output) = dc_runtime_info($np, local_uc($subcommand), $blacklist);
}
else
{
$output = "Unknown HOST command\n" . $np->opts->_help;
$result = CRITICAL;
}
}
};
if ($@)
{
if (uc(ref($@)) eq "HASH")
{
$output = $@->{msg};
$result = $@->{code};
}
elsif ($@ =~ /^Error connecting to server at/) {
$output = $@ . "";
$result = UNKNOWN;
}
elsif ($@ =~ /^Error: Cannot complete login/) {
$output = $@ . "";
$result = UNKNOWN;
}
elsif ($@ =~ /^Error: Permission to perform/) {
$output = $@ . "";
$result = UNKNOWN;
}
else
{
$output = $@ . "";
$result = CRITICAL;
}
}
Util::disconnect();
if ($generate_test && uc($generate_test) ne 'STDOUT') {
open TEST_SCRIPT, ">>", $generate_test;
print TEST_SCRIPT "#" . $output . "\n";
print TEST_SCRIPT "-" . $result;
}
$np->plugin_exit($result, $output);
}
main unless defined caller;
#######################################################################################################################################################################
sub get_key_metrices {
my ($perfmgr_view, $group, @names) = @_;
my $perfCounterInfo = $perfmgr_view->perfCounter;
my @counters;
die "Insufficient rights to access perfcounters\n" if (!defined($perfCounterInfo));
foreach (@$perfCounterInfo) {
if ($_->groupInfo->key eq $group) {
my $cur_name = $_->nameInfo->key . "." . $_->rollupType->val;
foreach my $index (0..@names-1)
{
if ($names[$index] =~ /$cur_name/)
{
$names[$index] =~ /(\w+).(\w+):*(.*)/;
$counters[$index] = PerfMetricId->new(counterId => $_->key, instance => $3);
}
}
}
}
return \@counters;
}
sub generic_performance_values {
my ($views, $perfargs, $group, @list) = @_;
my $counter = 0;
my @values = ();
my $amount = @list;
my $perfMgr = $perfargs->{perfCounter};
if (!defined($perfMgr)) {
$perfMgr = Vim::get_view(mo_ref => Vim::get_service_content()->perfManager, properties => [ 'perfCounter' ]);
$perfargs->{perfCounter} = $perfMgr;
}
my $metrices = get_key_metrices($perfMgr, $group, @list);
my $maxsamples = $perfargs->{maxsamples};
my $interval = defined($perfargs->{interval}) ? $perfargs->{interval} : 20;
my $timestamp = $perfargs->{timestamp};
my @perf_query_spec = ();
if (defined($timestamp)) {
my $timeshift = $perfargs->{timeshift};
my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($timestamp - $timeshift);
my $startTime = sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", $year + 1900, $mon + 1, $mday, $hour, $min, $sec);
($sec,$min,$hour,$mday,$mon,$year) = gmtime($timestamp);
my $endTime = sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", $year + 1900, $mon + 1, $mday, $hour, $min, $sec);
if ($interval and $interval eq "r") {
foreach (@$views) {
my $summary = $perfMgr->QueryPerfProviderSummary(entity => $_);
die "Realtime interval is not supported or not enabled\n" unless ($summary && $summary->currentSupported);
$interval = $summary->refreshRate;
push(@perf_query_spec, PerfQuerySpec->new(entity => $_, metricId => $metrices, format => 'csv', intervalId => $interval, maxSample => $maxsamples, startTime => $startTime, endTime => $endTime));
}
} elsif ($interval and substr($interval, 0, 1) eq "h") {
my $index = substr($interval, 1, -1);
foreach (@$views) {
my $summary = $perfMgr->QueryPerfProviderSummary(entity => $_);
die "Historical intervals are not supported\n" unless ($summary && $summary->summarySupported);
my $historic_intervals = $perfMgr->historicalInterval;
die "Historical interval [$index] is not present (max value " . @{$historic_intervals} . ")\n" unless (($index >= 0) && ($index < @{$historic_intervals}));
my $perf_interval = $$historic_intervals[$index];
die "Historical interval [$index] is disabled\n" unless ($perf_interval->enabled);
$interval = $perf_interval->key;
push(@perf_query_spec, PerfQuerySpec->new(entity => $_, metricId => $metrices, format => 'csv', intervalId => $interval, maxSample => $maxsamples, startTime => $startTime, endTime => $endTime));
}
} else {
push(@perf_query_spec, PerfQuerySpec->new(entity => $_, metricId => $metrices, format => 'csv', intervalId => $interval, maxSample => $maxsamples, startTime => $startTime, endTime => $endTime)) foreach (@$views);
}
} else {
if ($interval and $interval eq "r") {
foreach (@$views) {
my $summary = $perfMgr->QueryPerfProviderSummary(entity => $_);
die "Realtime interval is not supported or not enabled\n" unless ($summary && $summary->currentSupported);
$interval = $summary->refreshRate;
push(@perf_query_spec, PerfQuerySpec->new(entity => $_, metricId => $metrices, format => 'csv', intervalId => $interval, maxSample => $maxsamples));
}
} elsif ($interval and substr($interval, 0, 1) eq "h") {
my $index = substr($interval, 1, -1);
foreach (@$views) {
my $summary = $perfMgr->QueryPerfProviderSummary(entity => $_);
die "Historical intervals are not supported\n" unless ($summary && $summary->summarySupported);
my $historic_intervals = $perfMgr->historicalInterval;
die "Historical interval [$index] is not present (max value " . @{$historic_intervals} . ")\n" unless (($index >= 0) && ($index < @{$historic_intervals}));
my $perf_interval = $$historic_intervals[$index];
die "Historical interval [$index] is disabled\n" unless ($perf_interval->enabled);
$interval = $perf_interval->key;
push(@perf_query_spec, PerfQuerySpec->new(entity => $_, metricId => $metrices, format => 'csv', intervalId => $interval, maxSample => $maxsamples));
}
} else {
push(@perf_query_spec, PerfQuerySpec->new(entity => $_, metricId => $metrices, format => 'csv', intervalId => $interval, maxSample => $maxsamples)) foreach (@$views);
}
}
my $perf_data = $perfMgr->QueryPerf(querySpec => \@perf_query_spec);
$amount *= @$perf_data;
while (@$perf_data)
{
my $unsorted = shift(@$perf_data)->value;
my @host_values = ();
foreach my $id (@$unsorted)
{
foreach my $index (0..@$metrices-1)
{
if ($id->id->counterId == $$metrices[$index]->counterId)
{
$counter++ if (!defined($host_values[$index]));
$host_values[$index] = $id;
}
}
}
push(@values, \@host_values);
}
return undef if ($counter != $amount || $counter == 0);
return \@values;
}
sub return_host_performance_values {
my $values;
my $host_name = shift(@_);
my $perfargs = shift(@_);
my $timeshift = $perfargs->{timeshift};
my $host_view = Vim::find_entity_views(view_type => 'HostSystem', filter => $host_name, properties => (defined($timeshift) ? [ 'name', 'runtime.inMaintenanceMode', 'configManager.dateTimeSystem' ] : [ 'name', 'runtime.inMaintenanceMode']) ); # Added properties named argument.
die "Runtime error\n" if (!defined($host_view));
die "Host \"" . $$host_name{"name"} . "\" does not exist\n" if (!@$host_view);
die {msg => ("NOTICE: \"" . $$host_view[0]->name . "\" is in maintenance mode, check skipped\n"), code => OK} if (uc($$host_view[0]->get_property('runtime.inMaintenanceMode')) eq "TRUE");
# Timestamp is required for some Hosts in vCenter(Datacenter), this could fix 'Unknown error' type of issues
$perfargs->{timestamp} = str2time(Vim::get_view(mo_ref => $$host_view[0]->get_property('configManager.dateTimeSystem'))->QueryDateTime()) if (defined($timeshift));
$values = generic_performance_values($host_view, $perfargs, @_);
return undef if ($@);
return ($host_view, $values);
}
sub return_host_vmware_performance_values {
my $values;
my $vmname = shift(@_);
my $vm_view = Vim::find_entity_views(view_type => 'VirtualMachine', filter => {name => "$vmname"}, properties => [ 'name', 'runtime.powerState' ]);
die "Runtime error\n" if (!defined($vm_view));
die "VMware machine \"" . $vmname . "\" does not exist\n" if (!@$vm_view);
die "VMware machine \"" . $vmname . "\" is not running. Current state is \"" . $$vm_view[0]->get_property('runtime.powerState')->val . "\"\n" if ($$vm_view[0]->get_property('runtime.powerState')->val ne "poweredOn");
my $perfargs = shift(@_);
$perfargs->{timestamp} = time() if (exists($perfargs->{timeshift}));
$values = generic_performance_values($vm_view, $perfargs, @_);
return $@ if ($@);
return ($vm_view, $values);
}
sub return_dc_performance_values {
my $values;
my $host_views = Vim::find_entity_views(view_type => 'HostSystem', properties => [ 'name' ]);
die "Runtime error\n" if (!defined($host_views));
die "Datacenter does not contain any hosts\n" if (!@$host_views);
my $perfargs = shift(@_);
$perfargs->{timestamp} = time() if (exists($perfargs->{timeshift}));
$values = generic_performance_values($host_views, $perfargs, @_);
return undef if ($@);
return ($host_views, $values);
}
sub return_cluster_performance_values {
my $values;