/opsview/files/default/server_plugins/check_vmware_api.pl
https://github.com/masamiya/chef-cookbooks · Perl · 4718 lines · 4337 code · 323 blank · 58 comment · 684 complexity · 35bada396d7dcd8e110ba0ede39fdb40 MD5 · raw file
Large files are truncated click here to view the full file
- #!/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 <op5-users@lists.op5.com>
- #
- # 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
- # op5-users@lists.op5.com
- #
- # Discussions are directed to the mailing list op5-users@lists.op5.com,
- # 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/>.
- #
- # Prevent SSL certificate validation
- $ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;
- package CheckVMwareAPI;
- use strict;
- use warnings;
- use vars qw($PROGNAME $VERSION $output $values $result $defperfargs);
- use Nagios::Plugin::Functions qw(%STATUS_TEXT);
- use Nagios::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 http://www.op5.com/how-to/how-to-install-vmware-vsphere-sdk-perl-5-1/ 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 = Nagios::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 latency in ms (totalReadLatency.average)\n"
- . " + write - write latency in ms (totalWriteLatency.average)\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 breif - 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 breif - 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"
- . " + 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 breif - 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 breif - 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"
- . " + cpufainess - fairness of distributed cpu resource allocation\n"
- . " + memfainess - 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 breif - 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 breif - 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 Nagios::Plugin::Functions::nagios_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->nagios_exit(CRITICAL, "No Host or Datacenter specified");
- }
- $host_address .= ":443" if (index($host_address, ":") == -1);
- $host_address = "https://" . $host_address . "/sdk/webService";
- if (defined($sessionfile) and -e $sessionfile)
- {
- Opts::set_option("sessionfile", $sessionfile);
- eval {
- Util::connect($host_address, $username, $password);
- 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($host_address, $username, $password);
- }
- }
- 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};
- }
- 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->nagios_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 = defined($perfargs->{maxsamples}) ? $perfargs->{maxsamples} : 1; #default 1 sample
- my $interval = defined($perfargs->{interval}) ? $perfargs->{interval} : 20; #retrive RefreshRate as default value
- 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 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 (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 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 (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;
- my $cluster_name = shift(@_);
- my $cluster_view = Vim::find_entity_views(view_type => 'ClusterComputeResource', filter => { name => "$cluster_name" }, properties => [ 'name' ]); # Added properties named argument.
- die "Runtime error\n" if (!defined($cluster_view));
- die "Cluster \"" . $cluster_name . "\" does not exist\n" if (!@$cluster_view);
- my $perfargs = shift(@_);
- die "Since cluster does not have realtime stats interval other than 20(default value) is mandatory\n" if (!exists($perfargs->{interval}));
- $perfargs->{timestamp} = time() if (exists($perfargs->{timeshift}));
- $values = generic_performance_values($cluster_view, $perfargs, @_);
- return undef if ($@);
- return $values;
- }
- # Temporary solution to overcome zeros in network output
- sub return_host_temporary_vc_4_1_network_performance_values {
- my @values;
- my ($host_name, $perfargs, @list) = @_;
- my $host_view = Vim::find_entity_views(view_type => 'HostSystem', filter => $host_name, properties => [ 'name', 'runtime.inMaintenanceMode', 'summary.config.product.version', 'configManager.dateTimeSystem' ]); # 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");
- my $software_version = $$host_view[0]->get_property('summary.config.product.version');
- return undef if (substr($software_version, 0, 4) ne '4.1.');
- my $timeshift = $perfargs->{timeshift};
- my $interval = $perfargs->{interval};
- my $maxsamples = $perfargs->{maxsamples};
- my $timestamp = defined($timeshift) ? str2time(Vim::get_view(mo_ref => $$host_view[0]->get_property('configManager.dateTimeSystem'))->QueryDateTime()) : undef;
- my $perfMgr = Vim::get_view(mo_ref => Vim::get_service_content()->perfManager, properties => [ 'perfCounter' ]);
- my $metrices = get_key_metrices($perfMgr, 'net', @list);
- my $amount = @list;
- my @perf_query_spec = ();
- if (defined($timestamp)) {
- my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($timestamp - $timeshift);
- my $endTime = sprintf("%04d-%02d-%02dT%02d:%02d:%02dZ", $year + 1900, $mon + 1, $mday, $hour, $min, $sec);
- ($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);
- push(@perf_query_spec, PerfQuerySpec->new(entity => $_, metricId => $metrices, format => 'csv', intervalId => $interval, startTime => $startTime, endtime => $endTime)) foreach (@$host_view);
- } else {
- push(@perf_query_spec, PerfQuerySpec->new(entity => $_, metricId => $metrices, format => 'csv', intervalId => $interval, maxSample => $maxsamples)) foreach (@$host_view);
- }
- my $perf_data = $perfMgr->QueryPerf(querySpec => \@perf_query_spec);
- $amount *= @$perf_data;
- my $counter = 0;
- 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)
- {
- if (!defined($host_values[$index]))
- {
- $counter++;
- $host_values[$index] = bless({ 'value' => '0' }, "PerfMetricSeriesCSV");
- }
- $host_values[$index]{"value"} += convert_number($id->value) if ($id->id->instance ne '');
- }
- }
- }
- push(@values, \@host_values);
- }
- return undef if ($counter != $amount || $counter == 0 || $@);
- return ($host_view, \@values);
- }
- # Remove as soon as possible
- sub local_uc
- {
- my ($val) = shift(@_);
- return defined($val)?uc($val):undef;
- }
- sub simplify_number
- {
- my ($number, $cnt) = @_;
- $cnt = 2 if (!defined($cnt));
- return sprintf("%.${cnt}f", "$number");
- }
- sub convert_number
- {
- my @vals = split(/,/, shift(@_));
- my $res = 0;
- while (@vals) {
- my $value = pop(@vals);
- $value =~ s/^\s+//;
- $value =~ s/\s+$//;
- if (defined($value) && $value ne '') {
- return $value if ($value >= 0);
- $res = $value if ($res == 0);
- }
- }
- return $res;
- }
- sub check_percantage
- {
- my ($number) = shift(@_);
- my $perc = $number =~ s/\%//;
- return ($perc, $number);
- }
- sub check_health_state
- {
- my ($state) = shift(@_);
- my $res = UNKNOWN;
- if (uc($state) eq "GREEN") {
- $res = OK
- } elsif (uc($state) eq "YELLOW") {
- $res = WARNING;
- } elsif (uc($state) eq "RED") {
- $res = CRITICAL;
- }
- return $res;
- }
- sub format_issue {
- my ($issue) = shift(@_);
- my $output = '';
- if (defined($issue->datacenter))
- {
- $output .= 'Datacenter "' . $issue->datacenter->name . '", ';
- }
- if (defined($issue->host))
- {
- $output .= 'Host "' . $issue->host->name . '", ';
- }
- if (defined($issue->vm))
- {
- $output .= 'VM "' . $issue->vm->name . '", ';
- }
- if (defined($issue->computeResource))
- {
- $output .= 'Compute Resource "' . $issue->computeResource->name . '", ';
- }
- if (exists($issue->{dvs}) && defined($issue->dvs))
- {
- # Since vSphere API 4.0
- $output .= 'Virtual Switch "' . $issue->dvs->name . '", ';
- }
- if (exists($issue->{ds}) && defined($issue->ds))
- {
- # Since vSphere API 4.0
- $output .= 'Datastore "' . $issue->ds->name . '", ';
- }
- if (exists($issue->{net}) && defined($issue->net))
- {
- # Since vSphere API 4.0
- $output .= 'Network "' . $issue->net->name . '" ';
- }
- $output =~ s/, $/ /;
- $output .= ": " . $issue->fullFormattedMessage;
- $output .= "(caused by " . $issue->userName . ")" if ($issue->userName ne "");
- return $output;
- }
- sub datastore_volumes_info
- {
- my ($datastore, $np, $subcommand, $blacklist, $perc, $addopts) = @_;
- my $res = OK;
- my $output = '';
- my $usedflag;
- my $briefflag;
- my $regexpflag;
- my $blackregexpflag;
- $usedflag = $addopts =~ m/(^|\s|\t|,)\Qused\E($|\s|\t|,)/ if (defined($addopts));
- $briefflag = $addopts =~ m/(^|\s|\t|,)\Qbrief\E($|\s|\t|,)/ if (defined($addopts));
- $regexpflag = $addopts =~ m/(^|\s|\t|,)\Qregexp\E($|\s|\t|,)/ if (defined($addopts));
- $blackregexpflag = $addopts =~ m/(^|\s|\t|,)\Qblacklistregexp\E($|\s|\t|,)/ if (defined($addopts));
- die "Blacklist is supported only in generic check or regexp subcheck\n" if (defined($subcommand) && defined($blacklist) && !defined($regexpflag));
- if (defined($regexpflag) && defined($subcommand))
- {
- eval
- {
- qr{$subcommand};
- };
- if ($@)
- {
- $@ =~ s/ at.*line.*\.//;
- die $@;
- }
- }
- my $state;
- foreach my $ref_store (@{$datastore})
- {
- my $store = Vim::get_view(mo_ref => $ref_store, properties => ['summary', 'info']);
- my $name = $store->summary->name;
- if (!defined($subcommand) || ($name eq $subcommand) || (defined($regexpflag) && $name =~ /$subcommand/))
- {
- if (defined($blacklist))
- {
- next if ($blackregexpflag?$name =~ /$blacklist/:$blacklist =~ m/(^|\s|\t|,)\Q$name\E($|\s|\t|,)/);
- }
- if ($store->summary->accessible)
- {
- $store->RefreshDatastoreStorageInfo() if ($store->can("RefreshDatastoreStorageInfo") && exists($store->info->{timestamp}) && $defperfargs->{timeshift} && (time() - str2time($store->info->timestamp) > $defperfargs->{timeshift}));
- my $value1 = simplify_number(convert_number($store->summary->freeSpace) / 1024 / 1024);
- my $value2 = convert_number($store->summary->capacity);
- $value2 = simplify_number(convert_number($store->info->freeSpace) / $value2 * 100) if ($value2 > 0);
- if ($usedflag)
- {
- $value1 = simplify_number(convert_number($store->summary->capacity) / 1024 / 1024) - $value1;
- $value2 = 100 - $value2;
- }
- $state = $np->check_threshold(check => $perc?$value2:$value1);
- $res = Nagios::Plugin::Functions::max_state($res, $state);
- $np->add_perfdata(label => $name, value => $perc?$value2:$value1, uom => $perc?'%':'MB', threshold => $np->threshold);
- $output .= "'$name'" . ($usedflag ? "(used)" : "(free)") . "=". $value1 . " MB (" . $value2 . "%), " if (!$briefflag || $state != OK);
- }
- else
- {
- $res = CRITICAL;
- $output .= "'$name' is not accessible, ";
- }
- last if (!$regexpflag && defined($subcommand) && ($name eq $subcommand));
- $blacklist .= $blackregexpflag?"|^$name\$":",$name";
- }
- }
- if ($output)
- {
- chop($output);
- chop($output);
- $output = "Storages : " . $output;
- }
- else
- {
- if ($briefflag)
- {
- $output = "There are no alerts";
- }
- else
- {
- $res = WARNING;
- $output = defined($subcommand)?$regexpflag? "No matching volumes for regexp \"$subcommand\" found":"No volume named \"$subcommand\" found":"There are no volumes";
- }
- }
- return ($res, $output);
- }
- #=====================================================================| HOST |============================================================================#
- sub host_cpu_info
- {
- my ($host, $np, $subcommand, $addopts) = @_;
- my $res = CRITICAL;
- my $output = 'HOST CPU Unknown error';
- my $quickStats;
- $quickStats = $addopts =~ m/(^|\s|\t|,)\Qquickstats\E($|\s|\t|,)/ if (defined($addopts));
- if (defined($subcommand))
- {
- if ($subcommand eq "USAGE")
- {
- my $value;
- if (defined($quickStats))
- {
- my $host_view = Vim::find_entity_view(view_type => 'HostSystem', filter => $host, properties => ['name', 'runtime.inMaintenanceMode', 'summary.hardware', 'summary.quickStats']);
- die "Host \"" . $$host{"name"} . "\" does not exist\n" if (!defined($host_view));
- die {msg => ("NOTICE: \"" . $host_view->name . "\" is in maintenance mode, check skipped\n"), code => OK} if (uc($host_view->get_property('runtime.inMaintenanceMode')) eq "TRUE");
- $values = $host_view->get_property('summary.quickStats');
- my $hardinfo = $host_view->get_property('summary.hardware');
- $value = simplify_number($values->overallCpuUsage / ($hardinfo->numCpuCores * $hardinfo->cpuMhz) * 100) if exists($values->{overallCpuUsage}) && defined($hardinfo);
- }
- else
- {
- $values = return_host_performance_values($host, $defperfargs, 'cpu', ('usage.average'));
- $value = simplify_number(convert_number($$values[0][0]->value) * 0.01) if (defined($values));
- }
- if (defined($value))
- {
- $np->add_perfdata(label => "cpu_usage", value => $value, uom => '%', threshold => $np->threshold);
- $output = "cpu usage=" . $value . " %";
- $res = $np->check_threshold(check => $value);
- }
- }
- elsif ($subcommand eq "USAGEMHZ")
- {
- my $value;
- if (defined($quickStats))
- {
- my $host_view = Vim::find_entity_view(view_type => 'HostSystem', filter => $host, properties => ['name', 'runtime.inMaintenanceMode', 'summary.quickStats']);
- die "Host \"" . $$host{"name"} . "\" does not exist\n" if (!defined($host_view));…