Home Directory

Search Exchange

Search All Sites

Nagios Live Webinars

Let our experts show you how Nagios can help your organization.

Contact Us

Phone: 1-888-NAGIOS-1
Email: sales@nagios.com

Login

Remember Me

Directory

Ozz

Reviews(1)
Hi I have modified the script to enable it to monitor cluster nodes using the Datacenter (vcenter) because it was restricted to access directly to each node.

The new code is:

#!/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
#
# 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 .
#

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);
use Net::SSL;
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.\"



\"Read through the License Agreement\"
\"Do you accept? (yes/no)

yes

\"In which directory do you want to install the executable files? [/usr/bin]\"



\"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 | -H [ -C ] [ -N ] [ -n ]\n"
. " -u -p | -f \n"
. " -l [ -s ] [ -T ] [ -i ]\n"
. " [ -x ] [ -o ]\n"
. " [ -t ] [ -w ] [ -c ]\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):,,...,\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=\n"
. ' ESX or ESXi hostname.',
required => 0,
);

$np->add_arg(
spec => 'cluster|C=s',
help => "-C, --cluster=\n"
. ' ESX or ESXi clustername.',
required => 0,
);

$np->add_arg(
spec => 'datacenter|D=s',
help => "-D, --datacenter=\n"
. ' Datacenter hostname.',
required => 0,
);

$np->add_arg(
spec => 'name|N=s',
help => "-N, --name=\n"
. ' Virtual machine name.',
required => 0,
);

$np->add_arg(
spec => 'node|n=s',
help => "-n, --name=\n"
. ' cluster Node.',
required => 0,
);

$np->add_arg(
spec => 'username|u=s',
help => "-u, --username=\n"
. ' Username to connect with.',
required => 0,
);

$np->add_arg(
spec => 'password|p=s',
help => "-p, --password=\n"
. ' Password to use with the username.',
required => 0,
);

$np->add_arg(
spec => 'authfile|f=s',
help => "-f, --authfile=\n"
. " Authentication file with login and password. File syntax :\n"
. " username=\n"
. ' 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=\n"
. ' Specify black list',
required => 0,
);

$np->add_arg(
spec => 'options|o=s',
help => "-o, --options= \n"
. ' Specify additional command options (quickstats, ...)',
required => 0,
);

$np->add_arg(
spec => 'timestamp|T=i',
help => "-T, --timestamp= \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= \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 - 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= \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= \n"
. ' Set verbosity level of vSphere API request/respond trace',
required => 0,
);

$np->add_arg(
spec => 'generate_test=s',
help => "--generate_test= \n"
. ' Generate a test case script from the executed command/subcommand and write it to .'
. ' If 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 $cnode = $np->opts->node;
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( ) {
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);
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 $cnode} 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($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 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 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 = Monitoring::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));
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');
$value = simplify_number($values->overallCpuUsage) if exists($values->{overallCpuUsage});
}
else
{
$values = return_host_performance_values($host, $defperfargs, 'cpu', ('usagemhz.average'));
$value = simplify_number(convert_number($$values[0][0]->value)) if (defined($values));
}
if (defined($value))
{
$np->add_perfdata(label => "cpu_usagemhz", value => $value, uom => '', threshold => $np->threshold);
$output = "cpu usagemhz=" . $value . " MHz";
$res = $np->check_threshold(check => $value);
}
}
else
{
$res = CRITICAL;
$output = "HOST CPU - unknown subcommand\n" . $np->opts->_help;
}
}
else
{
my $value1;
my $value2;
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');
if (exists($values->{overallCpuUsage}) && defined($hardinfo))
{
$value1 = simplify_number($values->overallCpuUsage);
$value2 = simplify_number($values->overallCpuUsage / ($hardinfo->numCpuCores * $hardinfo->cpuMhz) * 100);
}
}
else
{
$values = return_host_performance_values($host, $defperfargs, 'cpu', ('usagemhz.average', 'usage.average'));
if ($values) {
$value1 = simplify_number(convert_number($$values[0][0]->value));
$value2 = simplify_number(convert_number($$values[0][1]->value) * 0.01);
}
}
if (defined($value1) && defined($value2))
{
$np->add_perfdata(label => "cpu_usagemhz", value => $value1, uom => '', threshold => $np->threshold);
$np->add_perfdata(label => "cpu_usage", value => $value2, uom => '%', threshold => $np->threshold);
$res = OK;
$output = "cpu usage=" . $value1 . " MHz (" . $value2 . "%)";
}
}

return ($res, $output);
}

sub host_mem_info
{
my ($host, $np, $subcommand, $addopts) = @_;

my $res = CRITICAL;
my $output = 'HOST MEM Unknown error';

my $quickStats;
my $outputlist;
$quickStats = $addopts =~ m/(^|\s|\t|,)\Qquickstats\E($|\s|\t|,)/ if (defined($addopts));
$outputlist = $addopts =~ m/(^|\s|\t|,)\Qlistvm\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->overallMemoryUsage / ($hardinfo->memorySize / 1024 / 1024) * 100) if exists($values->{overallMemoryUsage}) && defined($hardinfo);
}
else
{
$values = return_host_performance_values($host, $defperfargs, 'mem', ('usage.average'));
$value = simplify_number(convert_number($$values[0][0]->value) * 0.01) if (defined($values));
}
if (defined($value))
{
$np->add_perfdata(label => "mem_usage", value => $value, uom => '%', threshold => $np->threshold);
$output = "mem usage=" . $value . " %";
$res = $np->check_threshold(check => $value);
}
}
elsif ($subcommand eq "USAGEMB")
{
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));
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');
$value = simplify_number($values->overallMemoryUsage) if exists($values->{overallMemoryUsage});
}
else
{
$values = return_host_performance_values($host, $defperfargs, 'mem', ('consumed.average'));
$value = simplify_number(convert_number($$values[0][0]->value) / 1024) if (defined($values));
}
if (defined($value))
{
$np->add_perfdata(label => "mem_usagemb", value => $value, uom => 'MB', threshold => $np->threshold);
$output = "mem usage=" . $value . " MB";
$res = $np->check_threshold(check => $value);
}
}
elsif ($subcommand eq "SWAP")
{
my $host_view;
($host_view, $values) = return_host_performance_values($host, $defperfargs, 'mem', ('swapused.average'));
if (defined($values))
{
my $value = simplify_number(convert_number($$values[0][0]->value) / 1024);
$np->add_perfdata(label => "mem_swap", value => $value, uom => 'MB', threshold => $np->threshold);
$output = "swap usage=" . $value . " MB: ";
$res = $np->check_threshold(check => $value);
if ($res != OK && $outputlist)
{
my $vm_views = Vim::find_entity_views(view_type => 'VirtualMachine', begin_entity => $$host_view[0], properties => ['name', 'runtime.powerState']);
die "Runtime error\n" if (!defined($vm_views));
die "There are no VMs.\n" if (!@$vm_views);
my @vms = ();
foreach my $vm (@$vm_views)
{
push(@vms, $vm) if ($vm->get_property('runtime.powerState')->val eq "poweredOn");
}
$values = generic_performance_values(\@vms, $defperfargs, 'mem', ('swapped.average'));
if (defined($values))
{
foreach my $index (0..@vms-1) {
my $value = simplify_number(convert_number($$values[$index][0]->value) / 1024);
$output .= $vms[$index]->name . " (" . $value . "MB), " if ($value > 0);
}
}
}
chop($output);
chop($output);
}
}
elsif ($subcommand eq "OVERHEAD")
{
$values = return_host_performance_values($host, $defperfargs, 'mem', ('overhead.average'));
if (defined($values))
{
my $value = simplify_number(convert_number($$values[0][0]->value) / 1024);
$np->add_perfdata(label => "mem_overhead", value => $value, uom => 'MB', threshold => $np->threshold);
$output = "overhead=" . $value . " MB";
$res = $np->check_threshold(check => $value);
}
}
elsif ($subcommand eq "OVERALL")
{
$values = return_host_performance_values($host, $defperfargs, 'mem', ('consumed.average', 'overhead.average'));
if (defined($values))
{
my $value = simplify_number((convert_number($$values[0][0]->value) + convert_number($$values[0][1]->value)) / 1024);
$np->add_perfdata(label => "mem_overhead", value => $value, uom => 'MB', threshold => $np->threshold);
$output = "overall=" . $value . " MB";
$res = $np->check_threshold(check => $value);
}
}
elsif ($subcommand eq "MEMCTL")
{
my $host_view;
($host_view, $values) = return_host_performance_values($host, $defperfargs, 'mem', ('vmmemctl.average'));
if (defined($values))
{
my $value = simplify_number(convert_number($$values[0][0]->value) / 1024);
$np->add_perfdata(label => "mem_memctl", value => $value, uom => 'MB', threshold => $np->threshold);
$output = "memctl=" . $value . " MB: ";
$res = $np->check_threshold(check => $value);
if ($res != OK && $outputlist)
{
my $vm_views = Vim::find_entity_views(view_type => 'VirtualMachine', begin_entity => $$host_view[0], properties => ['name', 'runtime.powerState']);
die "Runtime error\n" if (!defined($vm_views));
die "There are no VMs.\n" if (!@$vm_views);
my @vms = ();
foreach my $vm (@$vm_views)
{
push(@vms, $vm) if ($vm->get_property('runtime.powerState')->val eq "poweredOn");
}
$values = generic_performance_values(\@vms, $defperfargs, 'mem', ('vmmemctl.average'));
if (defined($values))
{
foreach my $index (0..@vms-1) {
my $value = simplify_number(convert_number($$values[$index][0]->value) / 1024);
$output .= $vms[$index]->name . " (" . $value . "MB), " if ($value > 0);
}
}
}
chop($output);
chop($output);
}
}
else
{
$res = CRITICAL;
$output = "HOST MEM - unknown subcommand\n" . $np->opts->_help;
}
}
else
{
$values = return_host_performance_values($host, $defperfargs, 'mem', ('consumed.average', 'usage.average', 'overhead.average', 'swapused.average', 'vmmemctl.average'));
if (defined($values))
{
my $value1 = simplify_number(convert_number($$values[0][0]->value) / 1024);
my $value2 = simplify_number(convert_number($$values[0][1]->value) * 0.01);
my $value3 = simplify_number(convert_number($$values[0][2]->value) / 1024);
my $value4 = simplify_number(convert_number($$values[0][3]->value) / 1024);
my $value5 = simplify_number(convert_number($$values[0][4]->value) / 1024);
$np->add_perfdata(label => "mem_usagemb", value => $value1, uom => 'MB', threshold => $np->threshold);
$np->add_perfdata(label => "mem_usage", value => $value2, uom => '%', threshold => $np->threshold);
$np->add_perfdata(label => "mem_overhead", value => $value3, uom => 'MB', threshold => $np->threshold);
$np->add_perfdata(label => "mem_swap", value => $value4, uom => 'MB', threshold => $np->threshold);
$np->add_perfdata(label => "mem_memctl", value => $value5, uom => 'MB', threshold => $np->threshold);
$res = OK;
$output = "mem usage=" . $value1 . " MB (" . $value2 . "%), overhead=" . $value3 . " MB, swapped=" . $value4 . " MB, memctl=" . $value5 . " MB";
}
}

return ($res, $output);
}

sub host_net_info
{
my ($host, $np, $subcommand) = @_;

my $res = CRITICAL;
my $output = 'HOST NET Unknown error';

if (defined($subcommand))
{
if ($subcommand eq "USAGE")
{
$values = return_host_temporary_vc_4_1_network_performance_values($host, $defperfargs, ('received.average:*', 'transmitted.average:*'));
if ($values)
{
$$values[0][0]{"value"} += $$values[0][1]{"value"};
}
else
{
$values = return_host_performance_values($host, $defperfargs, 'net', ('usage.average'));
}
if (defined($values))
{
my $value = simplify_number(convert_number($$values[0][0]->value));
$np->add_perfdata(label => "net_usage", value => $value, uom => '', threshold => $np->threshold);
$output = "net usage=" . $value . " KBps";
$res = $np->check_threshold(check => $value);
}
}
elsif ($subcommand eq "RECEIVE")
{
$values = return_host_temporary_vc_4_1_network_performance_values($host, $defperfargs, ('received.average:*'));
$values = return_host_performance_values($host, $defperfargs, 'net', ('received.average')) if (!$values);
if (defined($values))
{
my $value = simplify_number(convert_number($$values[0][0]->value));
$np->add_perfdata(label => "net_receive", value => $value, uom => '', threshold => $np->threshold);
$output