/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

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