Debian Codegraph @

check_redis/check_redis.pl

raw ◀ ▶
1 Debian patch touch this file
1 #!/usr/bin/perl -w
2 #
3 # ============================== SUMMARY =====================================
4 #
5 # Program : check_redis.pl
6 # Version : 0.73
7 # Date : Mar 23, 2013
8 # Author : William Leibzon - [email protected]
9 # Licence : GPL - summary below, full text at http://www.fsf.org/licenses/gpl.txt
10 #
11 # =========================== PROGRAM LICENSE =================================
12 #
13 # This program is free software; you can redistribute it and/or modify
14 # it under the terms of the GNU General Public License as published by
15 # the Free Software Foundation; either version 2 of the License, or
16 # (at your option) any later version.
17 #
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 #
27 # ===================== INFORMATION ABOUT THIS PLUGIN =========================
28 #
29 # This is Redis Server Check plugin. It gets stats variables and allows to set
30 # thresholds on their value or their rate of change. It can measure response time,
31 # hitrate, memory utilization, check replication sync and more. It can also test
32 # data in a specified key (if necessary doing average or sum on range).
33 #
34 # Plugin returns stats variables as performance data for further nagios 2.0
35 # post-processing, you can find graph templates for PNP4Nagios at:
36 # http://william.leibzon.org/nagios/
37 #
38 # This program is written and maintained by:
39 # William Leibzon - william(at)leibzon.org
40 #
41 # ============================= SETUP NOTES ====================================
42 #
43 # Make sure to install Redis perl library from CPAN first.
44 #
45 # Next for help and to see what parameters this plugin accepts do:
46 # ./check_redis.pl --help
47 #
48 # This plugin checks Redis NoSQL database status variables, measures its response
49 # time and if specified allows to set thresholds on one or more key data. You can
50 # set thresholds for data in stats variables and some of them are also conveniently
51 # available as long options with special threshold syntax. Plugin also calculates
52 # statistics such as Hitrate (calculated as rate of change of hits/misses) and
53 # memory use and can check replication delay.
54 #
55 # All variables can be returned as performance data for graphing and pnp4nagios
56 # template should be available with this plugin on the site you downloaded it from.
57
58 # 1. Connection Parameters
59 #
60 # The connection parameters are "-H hostname", "-p port", "-D database" and
61 # "-C password_file" or "-x password". Specifying hostname is required, if you
62 # run locally specify it as -H 127.0.0.1. Everything else is optional and rarely
63 # needed. Default port is 6337. Database name (usually a numeric id) is probably
64 # only needed if you use --query option. Password can be passed on a command
65 # line with -x but its safer to read read it from a file or change in the code
66 # itself if you do use authentication.
67 #
68 # 2. Response Time, HitRate, Memory Utilization, Replication Delay
69 #
70 # To get response time you use "-T" or "--response_time=" option. By itself
71 # it will cause output of response time at the status line. You can also use
72 # it as "-T warn,crit" to specify warning and critical thresholds.
73 #
74 # To get hitrate the option is "-R" or "--hitrate=". If previous performance
75 # data is not feed to plugin (-P option, see below) the plugin calculates
76 # it as total hitrate over life of redis process. If -P is specified and
77 # previous performance data is fed back, the data is based on real hitrate
78 # (which can show spikes and downs) with lifelong info also given in paranthesis
79 # The data is based on keyspace_hits and keyspace_misses stats variables.
80 # As with -T you can specify -R by itself or with thresholds as -R warn,crit
81 #
82 # Memory utilization is percent of real memory used by Redis out of total
83 # memory on the system. To be able to calculate it plugin needs to known
84 # amount of memory your system has which you specify with "-M" or "--total_memory="
85 # option. Memory utilization option itself is lower "-m" or "--memory_utilization="
86 # and you can specify threshold for it as "-m warn,crit"
87 #
88 # Replication delay threshold option "-R" or "--replication_delay=" is used
89 # to check replication with data from "master_last_io_seconds_ago" stats and
90 # valid only on slave servers. Other variables maybe checked for this later
91 # with more complex functionality, so it was chosen to do this as separate
92 # option rather than directing people to check that variable.
93 #
94 # 3. Checks on Redis Status Variables
95 #
96 # All status variables from redis can be checked with the plugin. For some
97 # status variables separate long option is provided to specify threshold.
98 # i.e. --connected_clients=<thresholds>
99 #
100 # This is a new alternative to specifying all variables together with -a
101 # (--variables) option. For example:
102 # -a connected_clients,blocked_clients
103 # When you do above results are included in status output line and you
104 # are required to specify thresholds with -w or --warn and -c or --crit
105 # with exactly number of thresholds as a number of variables specified
106 # in -a. If you simply want variable values on status line without specifying
107 # any threshold, use ~ in place of threshold value or skip value but specify
108 # all appropriate commas. For example:
109 # -a connected_clients,blocked_clients -w ~,~ -c ~,~
110 # OR -a connected_clients,blocked_clients -w , -c ,
111 #
112 # If you use new syntax with a long option for specific stats variables, you
113 # can specify list of one or more threshold specifiers which can be any of:
114 # NAME:<string> - Overrides name for this variable for use in status and PERF output
115 # PATTERN:<regex> - Regular Expression that allows to match multiple data results
116 # WARN:threshold - warning alert threshold
117 # CRIT:threshold - critical alert threshold
118 # Threshold is a value (usually numeric) which may have the following prefix:
119 # > - warn if data is above this value (default for numeric values)
120 # < - warn if data is below this value (must be followed by number)
121 # = - warn if data is equal to this value (default for non-numeric values)
122 # ! - warn if data is not equal to this value
123 # Threshold can also be specified as a range in two forms:
124 # num1:num2 - warn if data is outside range i.e. if data<num1 or data>num2
125 # \@num1:num2 - warn if data is in range i.e. data>=num1 && data<=num2
126 # ABSENT:OK|WARNING|CRITICAL|UNKNOWN - Nagios alert (or lock of thereof) if data is absent
127 # ZERO:OK|WARNING|CRITICAL|UNKNOWN - Nagios alert (or lock of thereof) if result is 0
128 # DISPLAY:YES|NO - Specifies if data should be included in nagios status line output
129 # PERF:YES|NO - Output in performance data or not (always YES if -F option is used)
130 # UOM:<string> - Unit Of Measurement symbol to add to perf data - 'c','%','s','B'
131 # This is used by programs that graph perf data such as PNP
132 #
133 # These can be specified in any order separated by ",". For example:
134 # --connected_clients=CRIT:>100,WARN:>50,ABSENT:CRITICAL,ZERO:OK,DISPLAY:YES,PERF:YES
135 #
136 # Variables that are not known to plugin and don't have specific long option (or even if
137 # they do) can be specified using general long option --check or --option or -o
138 # (all are aliases for same option):
139 # --check=NAME:connected_clients,CRIT:>100,WARN:>50,ABSENT:CRITICAL,DISPLAY:YES,PERF:YES
140 #
141 # Then NAME is used to specify what to match and multiple data vars maybe matched
142 # with PATTERN regex option (and please only use PATTERN with --check and not confuse
143 # plugin by using it in a named long option). Either NAME or PATTERN are required.
144 #
145 # 4. Calculating and using Rate of Change for Variables
146 #
147 # If you want to check rate of change rather than actual value you can do this
148 # by specifying it as '&variable' such as "&total_connections_received" or
149 # as "variable_rate" which is "total_connections_received_rate" and is similar
150 # to 'connected_clients' variable. By default it would be reported in the output
151 # as 'variable_rate' though '&variable' is a format used internally by plugin.
152 #
153 # As an alternative you can specify how to label these with --rate_label
154 # option where you can specify prefix and/or suffix. For example '--rate_label=dt_'
155 # would have the output being "dt_total_connections_received' where as
156 # '--rate_label=,_rate' is plugin default giving 'total_connections_received_rate'.
157 # You can use these names with -a and -A such as:
158 # --rate_label=,_rate -a total_connections_received_rate -w 1000 -c ~
159 # Note that --rate_label will not work with new variable-named options, the
160 # only way to change default if you use that is to modify code and change
161 # $o_rprefix and $o_rsuffix variables default values.
162 #
163 # Now in order to be able to calculate rate of change, the plugin needs to
164 # know values of the variables from when it was run the last time. This
165 # is done by feeding it previous performance data with a -P option.
166 # In commands.cfg this would be specified as:
167 # -P "$SERVICEPERFDATA$"
168 # And don't forget the quotes, in this case they are not just for documentation.
169 #
170 # 5. Threshold Specification
171 #
172 # The plugin fully supports Nagios plug-in specification for specifying thresholds:
173 # http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT
174 #
175 # And it supports an easier format with the following one-letter prefix modifiers:
176 # >value : issue alert if data is above this value (default for numeric value)
177 # <value : issue alert if data is below this value (must be followed by number)
178 # =value : issue alert if data is equal to this value (default for non-numeric)
179 # !value : issue alert if data is NOT equal to this value
180 # (because > and < are interpreted by shell you may need to specify this in quotes)
181 # There are also two specifications of range formats as with other nagios plugins:
182 # number1:number2 issue alert if data is OUTSIDE of range [number1..number2]
183 # i.e. alert if data<$number1 or data>$number2
184 # @number1:number2 issue alert if data is WITHIN range [number1..number2]
185 # i.e. alert if data>=$number and $data<=$number2
186 #
187 # The plugin will attempt to check that WARNING value is less than CRITICAL
188 # (or greater for <). A special prefix modifier '^' can be used to disable these
189 # checks. A quick example of such special use is '--warn=^<100 --crit=>200' which
190 # means warning alert if value is < 100 and critical alert if its greater than 200.
191 #
192 # 6. Performance Data
193 #
194 # With '-f' option values of all variables you specified in -a as well as
195 # response time from -T (response time),
196 # hitrate from -R,
197 # memory utilization from -m
198 # and other data are reported back out as performance data for Nagios graphing programs.
199 #
200 # You may also directly specify which variables are to be return as performance data
201 # with '-A' option. If you use '-A' by itself and not specify any variables or use
202 # special value of '*' (as in '-A *') the plugin will output all variables which is useful
203 # for finding what data you can check with this plugin.
204 #
205 # The plugin will output threshold values as part of performance data as specified at
206 # http://nagiosplug.sourceforge.net/developer-guidelines.html#AEN201
207 # And don't worry about using non-standard >,<,=,~ prefixes, all of that would get
208 # converted into nagios threshold format for performance output
209 #
210 # The plugin is smart enough to add 'c' suffix for known COUNTER variables to
211 # values in performance data. Known variables are specified in an array you can
212 # find at the top of the code (further below) and plugin author does not claim
213 # to have identified all variables correctly. Please email if you find an error
214 # or want to add more variables.
215 #
216 # As noted above performance data is also used to calculate rate of change
217 # by feeding it back with -P option. In that regard even if you did not specify
218 # -f or -A but you have specified &variable, its actual data would be sent out
219 # in performance output. Additionally last time plugin was run is also in
220 # performance data as special _ptime variable.
221 #
222 # 7. Query Option and setting thresholds for data in Redis Database
223 #
224 # With -q (--query) option the plugin can retrieve data from Redis database
225 # which become new variables you can then check thresholds on. Currently it
226 # supports getting single key values with GET and getting range or values (or
227 # everything in list) with LRANGE and finding their Average or Min or Max or Sum.
228 # The option maybe repeated more than once. The format for this option is:
229 #
230 # -q, --query=query_type,key[:varname]<,list of threshold specifiers>
231 #
232 # query_type is one of:
233 # GET - get one string value
234 # LLEN - returns number of items in a list
235 # LRANGE:AVG:start:end - retrieve list and average results
236 # LRANGE:SUM:start:end - retrieve list and sum results
237 # LRANGE:MIN:start:end - retrieve list and return minimum
238 # LRANGE:MAX:start:end - retrieve list and return maximum
239 # HLEN - returns number of items in a hash [TODO]
240 # HGET:name - get specific hash key 'name' [TODO]
241 # HEXISTS:name - returns 0 or 1 depending on if specified hash key 'name' exists [TODO]
242 # SLEN - returns number of items in a set [TODO, SCARD redis opp]
243 # SEXISTS:name - returns 0 or 1 depending on if set member 'name' exists [SISMEMBER, TODO]
244 # ZLEN - returns number of items in a sorted set [TODO, ZCARD redis opp]
245 # ZCOUNT:min:max - counts number of items in sorted set with scores within the given values
246 # ZRANGE:AVG:min:max - retrieve sorted set members from min to max and average results
247 # ZRANGE:SUM:min:max - retrieve sorted set members from min to max and sum results
248 # ZRANGE:MIN:min:max - retrieve sorted set members from min to max list and return minimum
249 # ZRANGE:MAX:min:max- retrieve sorted set members from min to max and return maximum
250 # For LRANGE if you do not specify start and end, then start will be 0 and end
251 # is last value in the list pointed to by this key (found by using llen).
252 #
253 # Key is the Redis key name to be retrieved and optionally you can add ":varname"
254 # after it which specifies what to name plugin variable based on this data -
255 # based on what you specify here is how it will be displayed in the status
256 # line and performance data, default is same as Redis key name.
257 #
258 # After these key name you specify list of thresholds in the same format as
259 # variable-based long options described in section 3. Again the list of the
260 # possible specifiers are:
261 # WARN:threshold
262 # CRIT:threshold
263 # ABSENT:OK|WARNING|CRITICAL|UNKNOWN - what to do if data is not available
264 # ZERO:OK|WARNING|CRIICAL|UNKNOWN - what to do if data is 0 (rarely needed)
265 # DISPLAY:YES|NO - display on status line or not (default YES)
266 # PERF:YES|NO - output in perf data or not
267 #
268 # You can also optionally use -a, -w and -c to check data from the query instead
269 # of specifying thresholds as part of query option itself And remember that you if
270 # you need to check multiple keys you just repeat --query option more than once.
271 #
272 # 8. Example of Nagios Config Definitions
273 #
274 # Sample command and service definitions are below:
275 #
276 # define command {
277 # command_name check_redis_new
278 # command_line $USER1$/check_redis.pl -H $HOSTADDRESS$ -p $ARG1$ -T $ARG2$ -R -A -M $_HOSTSYSTEM_MEMORY$ -m $ARG3$ -a $ARG4$ -w $ARG5$ -c $ARG6$ -f -P "$SERVICEPERFDATA$"
279 # }
280 #
281 # Arguments and thresholds are:
282 # $ARG1 : Port
283 # $ARG2 : response time thresholds
284 # $ARG3 : memory utilization thresholds
285 # $ARG4 : additional variables to be checked
286 # $ARG5 : warning thresholds for those variables
287 # $ARG6 : critical thresholds for those variables
288 #
289 # define service {
290 # use prod-service
291 # hostgroups redishosts
292 # service_description Redis
293 # check_command check_redis_new!6379!"1,2"!"80,90"!blocked_clients,connected_clients!50,~!100,~
294 # }
295 #
296 # define host {
297 # use prod-server
298 # host_name redis.mynetwork
299 # address redis.mynetwork
300 # alias Redis Stat Server
301 # hostgroups linux,redishosts
302 # _SYSTEM_MEMORY '8G'
303 # }
304 #
305 # Example of command-line use:
306 # /usr/lib/nagios/plugins/check_redis.pl -H localhost -a 'connected_clients,blocked_clients' -w ~,~ -c ~,~ -m -M 4G -A -R -T -f -v
307 #
308 # In above the -v option means "verbose" and with it plugin will output some debugging information
309 # about what it is doing. The option is not intended to be used when plugin is called from nagios itself.
310 #
311 # Example of using query and variable-based long options with debug enabled as well (-v):
312 #
313 # ./check_redis.pl -H localhost -p 6379 -D 1 --query LRANGE:AVG:0:,MyColumn1:Q1,ABSENT:WARNING,WARN:300,CRIT:500,DISPLAY:YES,PERF:NO
314 # --query GET,MyKey:K1,ABSENT:CRITICAL "--connected_clients=WARN:<2,CRIT:>100,ZERO:OK,ABSENT:WARNING,DISPLAY:YES,PERF:YES"
315 #
316 # ======================= VERSION HISTORY and TODO ================================
317 #
318 # The plugins is written by reusing code my check_memcached.pl which itself is based
319 # on check_mysqld.pl. check_mysqld.pl has history going back to 2004.
320 #
321 # [0.4 - Mar 2012] First version of the code based on check_mysqld.pl 0.93
322 # and check_memcached.pl 0.6. Internal work, not released.
323 # Version 0.4 because its based on a well developed code base
324 # [0.41 - Apr 15, 2012] Added list of variables array and perf_ok regex.
325 # Still testing internally and not released yet.
326 # [0.42 - Apr 28, 2012] Added total_keys, total_expires, nice uptime_info
327 # and memory utilization
328 # [0.43 - May 31, 2012] Release candidate. More documentation added
329 # replacing check_memcached examples. Bugs fixed.
330 # Made "_rate" as default rate variables suffix in
331 # place of &delta. Changed -D option to -r.
332 #
333 # [0.5 - Jun 01, 2012] First official release will start with version 0.5
334 # Documentation changes, but no code updates.
335 # [0.51 - Jun 16, 2012] Added support to specify filename to '-v' option
336 # for debug output and '--debug' as alias to '--verbose'
337 # [0.52 - Jul 10, 2012] Patch by Jon Schulz to support credentials with -C
338 # (credentials file) and addition by me to support
339 # password as command argument.
340 # [0.53 - Jul 15, 2012] Adding special option to do query on one redis key and
341 # and do threshold checking of results if its numeric
342 #
343 # [0.6 - Jul 17, 2012] Rewrote parts of thresholds checking code and moved code
344 # that checks and parses thresholds from main into separate
345 # functions that are to become part of plugin library.
346 # Added support for variable thresholds specified as:
347 # option=WARN:threshold,CRIT:threshold,ABSENT:OK|WARNING|CRITICAL,ZERO:..
348 # which are to be used for stats-variable based long options such as
349 # --connected_clients=WARN:threshold,CRIT:threshold
350 # and added DISPLAY:YES|NO and PERF specifiers for above too.
351 # Added -D option to specify database needed for --query
352 # [0.61 - Aug 03, 2012] Added more types of key query for lists, sets, hashes
353 # and options to find number of elements in a list/set/hash.
354 # New options added are:
355 # LLEN,HLEN,SLEN,ZLEN,HGET,HEXISTS,SEXISTS,ZRANGE
356 #
357 # [0.7 - Aug 28, 2012] A lot of internal rewrites in the library. Its now not just a
358 # a set of functions, but a proper object library with internal
359 # variables hidden from outside. Support has also been added for
360 # regex matching with PATTERN specifier and for generalized
361 # --check option that can be used where specific long option is
362 # not available. For use with that option also added UOM specifier.
363 # Also added checkin 'master_last_io_seconds_ago' (when link is down)
364 # for when replication_delay info is requested.
365 # [0.71 - Sep 03, 2012] Fixed bug in a new library related to when data is missing
366 # [0.72 - Oct 05, 2012] Fixed bug reported by Matt McMillan in specified memory size
367 # when KB are used. Fixed bugs in adding performance data that
368 # results in keyspace_hits, keyspace_misses, memory_utilization
369 # having double 'c' or '%' in perfdata. Added contributors section.
370 # [0.73 - Mar 23, 2013] Fixed bug in parse_threshold function of embedded library
371 #
372 # TODO or consider for future:
373 #
374 # 1. Library Enhancements (will apply to multiple plugins that share common code)
375 # (a) Add '--extra-opts' to allow to read options from a file as specified
376 # at http://nagiosplugins.org/extra-opts. This is TODO for all my plugins
377 # (b) [DONE]
378 # In plans are to allow long options to specify thresholds for known variables.
379 # These would mean you specify '--connected_clients' in similar way to '--hitrate'
380 # Internally these would be converged into -A, -w, -c as appropriate and used
381 # together with these options. So in practice it will now allow to get any data
382 # just a different way to specify options for this plugin.
383 # (c) Allow regex when selecting variable name(s) with -a, this will be enabled with
384 # a special option and not be default
385 # [DONE]
386 #
387 # 2. REDIS Specific
388 # (a) Add option to check from master that slave is connected and working.
389 # (b) Look into replication delay from master and how it can be done. Look
390 # for into on replication_delay from slave as well
391 # (c) How to better calculate memory utilization and get max memory available
392 # without directly specifying it
393 # (d) Maybe special options to measure cpu use and set thresholds
394 #
395 # Others are welcome recommend a new feature to be added here. If so please email to
396 # [email protected].
397 # And don't worry, I'm not a company with some hidden agenda to use your idea
398 # but an actual person who you can easily get hold of by email, find on forums
399 # and on Nagios conferences. More info on my nagios work is at:
400 # http://william.leibzon.org/nagios/
401 # Above site should also have PNP4Nagios template for this and other plugins.
402 #
403 # ============================ LIST OF CONTRIBUTORS ===============================
404 #
405 # The following individuals have contributed code, patches, bug fixes and ideas to
406 # this plugin (listed in last-name alphabetical order):
407 #
408 # William Leibzon
409 # Matthew Litwin
410 # Matt McMillan
411 # Jon Schulz
412 # M Spiegle
413 #
414 # ============================ START OF PROGRAM CODE =============================
415
416 use strict;
417 use IO::Socket;
418 use Time::HiRes;
419 use Text::ParseWords;
420 use Getopt::Long qw(:config no_ignore_case);
421 use Redis;
422
423 # default hostname, port, database, user and password, see NOTES above
424 my $HOSTNAME= 'localhost';
425 my $PORT= 6379;
426 my $PASSWORD= undef;
427 my $DATABASE= undef;
428
429 # Add path to additional libraries if necessary
430 use lib '/usr/lib/nagios/plugins';
431 our $TIMEOUT;
432 our %ERRORS;
433 eval 'use utils qw(%ERRORS $TIMEOUT)';
434 if ($@) {
435 $TIMEOUT = 20;
436 %ERRORS = ('OK'=>0,'WARNING'=>1,'CRITICAL'=>2,'UNKNOWN'=>3,'DEPENDENT'=>4);
437 }
438
439 my $Version='0.73';
440
441 # This is a list of known stat and info variables including variables added by plugin,
442 # used in order to designate COUNTER variables with 'c' in perfout for graphing programs
443 # The format is:
444 # VAR_NAME => [ TYPE, PerfSuffix, DESCRIPTION]
445 # If option has description, the variable will also become available as a long option so for example
446 # you can specify "--connected_clients=WARN,CRIT" instead of specifying "-a connected_clients -w WARN -c CRIT'
447 my %KNOWN_STATUS_VARS = (
448 'memory_utilization' => [ 'status', 'GAUGE', '%' ], # calculated by plugin
449 'redis_version' => [ 'status', 'VERSION', '' ], # version string variable
450 'response_time' => [ 'status','GAUGE', 's' ], # measured by plugin
451 'hitrate' => [ 'status', 'GAUGE', '%' ], # calculated by plugin
452 'total_keys' => [ 'status','GAUGE', '', 'Total Number of Keys on the Server' ],
453 'total_expires' => [ 'status','GAUGE', '', 'Number of Expired Keys for All DBs' ],
454 'last_save_time' => [ 'status', 'GAUGE', 's' ],
455 'bgsave_in_progress' => [ 'status', 'BOOLEAN', '' ],
456 'vm_enabled' => [ 'status', 'BOOLEAN', '' ],
457 'uptime_in_seconds' => [ 'status', 'COUNTER', 'c' ],
458 'total_connections_received' => [ 'status', 'COUNTER', 'c', 'Total Connections Received' ],
459 'used_memory_rss' => [ 'status', 'GAUGE', 'B', 'Resident Set Size, Used Memory in Bytes' ], # RSS - Resident Set Size
460 'used_cpu_sys' => [ 'status', 'GAUGE', '', 'Main Process Used System CPU' ],
461 'redis_git_dirty' => [ 'status', 'BOOLEAN', '', 'Git Dirty Set Bit' ],
462 'loading' => [ 'status', 'BOOLEAN', '' ],
463 'latest_fork_usec' => [ 'status', 'GAUGE', '' ],
464 'connected_clients' => [ 'status', 'GAUGE', '', 'Total Number of Connected Clients' ],
465 'used_memory_peak_human' => [ 'status', 'GAUGE', '' ],
466 'mem_allocator' => [ 'status', 'TEXTINFO', '' ],
467 'uptime_in_days' => [ 'status', 'COUNTER', 'c', 'Total Uptime in Days' ],
468 'keyspace_hits' => [ 'status', 'COUNTER', 'c', 'Total Keyspace Hits' ],
469 'client_biggest_input_buf' => [ 'status', 'GAUGE', '' ],
470 'gcc_version' => [ 'status', 'TEXTINFO', '' ],
471 'changes_since_last_save' => [ 'status', 'COUNTER', 'c' ],
472 'arch_bits' => [ 'status', 'TEXTINFO', '' ],
473 'lru_clock' => [ 'status', 'GAUGE', '' ], # LRU is page replacement algorithm (least recently used), I'm unsure what this represents though
474 'role' => [ 'status', 'SETTING', '' ],
475 'multiplexing_api' => [ 'status', 'SETTING' , '' ],
476 'slave' => [ 'status', 'TEXTDATA', '' ],
477 'pubsub_channels' => [ 'status', 'GAUGE', '', 'Number of Pubsub Channels' ],
478 'redis_git_sha1' => [ 'status', 'TEXTDATA', '' ],
479 'used_cpu_user_children' => [ 'status', 'GAUGE', '', 'Child Processes Used User CPU' ],
480 'process_id' => [ 'status', 'GAUGE', '' ],
481 'used_memory_human' => [ 'status', 'GAUGE', '' ],
482 'keyspace_misses' => [ 'status', 'COUNTER', 'c', 'Keyspace Misses' ],
483 'used_cpu_user' => [ 'status', 'GAUGE', '', 'Main Process Used User CPU' ],
484 'total_commands_processed' => [ 'status', 'COUNTER', 'c', 'Total Number of Commands Processed from Start' ],
485 'mem_fragmentation_ratio' => [ 'status', 'GAUGE', '', 'Memory Fragmentation Ratio' ],
486 'client_longest_output_list' => [ 'status', 'GAUGE', '' ],
487 'blocked_clients' => [ 'status', 'GAUGE', '', 'Number of Currently Blocked Clients' ],
488 'aof_enabled' => [ 'status', 'BOOLEAN', '' ],
489 'evicted_keys' => [ 'status', 'COUNTER', 'c', 'Total Number of Evicted Keys' ],
490 'bgrewriteaof_in_progress' => [ 'status','BOOLEAN', '' ],
491 'expired_keys' => [ 'status', 'COUNTER', 'c', 'Total Number of Expired Keys' ],
492 'used_memory_peak' => [ 'status', 'GAUGE', 'B' ],
493 'connected_slaves' => [ 'status', 'GAUGE', '', 'Number of Connected Slaves' ],
494 'used_cpu_sys_children' => [ 'status', 'GAUGE', '', 'Child Processed Used System CPU' ],
495 'master_host' => [ 'status', 'TEXTINFO', '' ],
496 'master_port' => [ 'status', 'TEXTINFO', '' ],
497 'master_link_status' => [ 'status', 'TEXTINFO', '' ],
498 'slave0' => [ 'status', 'TEXTINFO', '' ],
499 'slave1' => [ 'status', 'TEXTINFO', '' ],
500 'slave2' => [ 'status', 'TEXTINFO', '' ],
501 'slave3' => [ 'status', 'TEXTINFO', '' ],
502 );
503
504 # Here you can also specify which variables should go into perf data,
505 # For right now it is 'GAUGE', 'COUNTER', 'DATA' (but not 'TEXTDATA'), and 'BOOLEAN'
506 # you may want to remove BOOLEAN if you don't want too much data
507 my $PERF_OK_STATUS_REGEX = 'GAUGE|COUNTER|^DATA$|BOOLEAN';
508
509 # ============= MAIN PROGRAM CODE - DO NOT MODIFY BELOW THIS LINE ==============
510
511 my $o_host= undef; # hostname
512 my $o_port= undef; # port
513 my $o_pwfile= undef; # password file
514 my $o_password= undef; # password as parameter
515 my $o_database= undef; # database name (usually a number)
516 my $o_help= undef; # help option
517 my $o_verb= undef; # verbose mode
518 my $o_version= undef; # version info option
519 my $o_variables=undef; # list of variables for warn and critical
520 my $o_perfvars= undef; # list of variables to include in performance data
521 my $o_warn= undef; # warning level option
522 my $o_crit= undef; # Critical level option
523 my $o_perf= undef; # Performance data option
524 my @o_check= (); # General check option that maybe repeated more than once
525 my $o_timeout= undef; # Timeout to use - note that normally timeout is from nagios
526 my $o_timecheck=undef; # threshold spec for connection time
527 my $o_memutilization=undef; # threshold spec for memory utilization%
528 my $o_totalmemory=undef; # total memory on a system
529 my $o_hitrate= undef; # threshold spec for hitrate%
530 my $o_repdelay=undef; # replication delay time
531 my @o_querykey=(); # query this key, this option maybe repeated so its an array
532 my $o_prevperf= undef; # performance data given with $SERVICEPERFDATA$ macro
533 my $o_prevtime= undef; # previous time plugin was run $LASTSERVICECHECK$ macro
534 my $o_ratelabel=undef; # prefix and suffix for creating rate variables
535 my $o_rsuffix='_rate'; # default suffix
536 my $o_rprefix='';
537
538 ## Additional global variables
539 my $redis= undef; # DB connection object
540 my @query=(); # array of queries with each entry being keyed hash of processedoption data on howto query
541
542
543 sub p_version { print "check_redis.pl version : $Version\n"; }
544
545 sub print_usage_line {
546 print "Usage: $0 [-v [debugfilename]] -H <host> [-p <port>] [-x password | -C credentials_file] [-D <database>] [-a <statistics variables> -w <variables warning thresholds> -c <variables critical thresholds>] [-A <performance output variables>] [-T [conntime_warn,conntime_crit]] [-R [hitrate_warn,hitrate_crit]] [-m [mem_utilization_warn,mem_utilization_crit] [-M <maxmemory>[B|K|M|G]]] [-r replication_delay_time_warn,replication_delay_time_crit] [-f] [-T <timeout>] [-V] [-P <previous performance data in quoted string>] [-q (GET|LLEN|HLEN|SLEN|ZLEN|HGET:name|HEXISTS:name|SEXISTS:name|LRANGE:(AVG|SUM|MIN|MAX):start:end|ZRANGE:(AVG|SUM|MIN|MAX):start:end),query_type,query_key_name[:data_name][,ABSENT:WARNING|CRITICAL][,WARN:threshold,CRIT:threshold]] [-o <threshold specification with name or pattern>]\n";
547 }
548
549 sub print_usage {
550 print_usage_line();
551 print "For more details on options do: $0 --help\n";
552 }
553
554 sub help {
555 my $nlib = shift;
556
557 print "Redis Check for Nagios version ",$Version,"\n";
558 print " by William Leibzon - william(at)leibzon.org\n\n";
559 print "This is redis monitoring plugin to check its stats variables, replication, response time\n";
560 print "hitrate, memory utilization and other info. The plugin can also query and test key data\n";
561 print "against specified thresholds. All data is available as performance output for graphing.\n\n";
562 print_usage_line();
563 print "\n";
564 print <<EOT;
565 General and Server Connection Options:
566 -v, --verbose[=FILENAME], --debug[=FILENAME]
567 Print extra debugging information.
568 If filename is specified instead of STDOUT the debug data is written to that file.
569 -h, --help
570 Print this detailed help screen
571 -H, --hostname=ADDRESS
572 Hostname or IP Address to check
573 -p, --port=INTEGER
574 port number (default: 6379)
575 -D, --database=NAME
576 optional database name (usually a number), needed for --query but otherwise not needed
577 -x, --password=STRING
578 Password for Redis authentication. Safer alternative is to put them in a file and use -C
579 -C, --credentials=FILENAME
580 Credentials file to read for Redis authentication
581 -t, --timeout=NUMBER
582 Allows to set timeout for execution of this plugin. This overrides nagios default.
583 -V, --version
584 Prints version number
585
586 Variables and Thresholds Set as List:
587 -a, --variables=STRING[,STRING[,STRING...]]
588 List of variables from info data to do threshold checks on.
589 The default (if option is not used) is not to monitor any variable.
590 The variable name should be prefixed with '&' to chec its rate of
591 change over time rather than actual value.
592 -w, --warn=STR[,STR[,STR[..]]]
593 This option can only be used if '--variables' (or '-a') option above
594 is used and number of values listed here must exactly match number
595 of variables specified with '-a'. The values specify warning threshold
596 for when Nagios should send WARNING alert. These values are usually
597 numbers and can have the following prefix modifiers:
598 > - warn if data is above this value (default for numeric values)
599 < - warn if data is below this value (must be followed by number)
600 = - warn if data is equal to this value (default for non-numeric values)
601 ! - warn if data is not equal to this value
602 ~ - do not check this data (must not be followed by number or ':')
603 ^ - for numeric values this disables check that warning < critical
604 Threshold values can also be specified as range in two forms:
605 num1:num2 - warn if data is outside range i.e. if data<num1 or data>num2
606 \@num1:num2 - warn if data is in range i.e. data>=num1 && data<=num2
607 -c, --crit=STR[,STR[,STR[..]]]
608 This option can only be used if '--variables' (or '-a') option above
609 is used and number of values listed here must exactly match number of
610 variables specified with '-a'. The values specify critical threshold
611 for when Nagios should send CRITICAL alert. The format is exactly same
612 as with -w option except no '^' prefix.
613
614 Performance Data Processing Options:
615 -f, --perfparse
616 This should only be used with '-a' and causes variable data not only as part of
617 main status line but also as perfparse compatible output (for graphing, etc).
618 -A, --perfvars=[STRING[,STRING[,STRING...]]]
619 This allows to list variables which values will go only into perfparse
620 output (and not for threshold checking). The option by itself (emply value)
621 is same as a special value '*' and specify to output all variables.
622 -P, --prev_perfdata
623 Previous performance data (normally put '-P \$SERVICEPERFDATA\$' in nagios
624 command definition). This is used to calculate rate of change for counter
625 statistics variables and for proper calculation of hitrate.
626 --rate_label=[PREFIX_STRING[,SUFFIX_STRING]]
627 Prefix or Suffix label used to create a new variable which has rate of change
628 of another base variable. You can specify PREFIX or SUFFIX or both. Default
629 if not specified is suffix '_rate' i.e. --rate_label=,_rate
630
631 Key Data Query Option (maybe repeated more than once):
632 -q, --query=query_type,key[:varname][,ABSENT:OK|WARNING|CRITICAL,WARN:threshold,CRIT:threshold]
633 query_type is one of:
634 GET - get one data value
635 LLEN - number of items in a list
636 LRANGE:AVG:start:end - retrieve list and average results
637 LRANGE:SUM:start:end - retrieve list and sum results
638 LRANGE:MIN:start:end - retrieve list and return minimum
639 LRANGE:MAX:start:end - retrieve list and return maximum
640 HLEN - returns number of items in a hash
641 HGET:name - get specific hash key 'name'
642 HEXISTS:name - returns 0 or 1 depending on if specified hash key 'name' exists
643 SLEN - returns number of items in a set
644 SEXISTS:name - returns 0 or 1 depending on if set member 'name' exists
645 ZLEN - returns number of items in a sorted set
646 ZCOUNT:min:max - counts items in sorted set with scores within the given values
647 ZRANGE:AVG:min:max - retrieve sorted set members from min to max and average results
648 ZRANGE:SUM:min:max - retrieve sorted set members from min to max and sum results
649 ZRANGE:MIN:min:max - retrieve sorted set members from min to max list and return minimum
650 ZRANGE:MAX:min:max - retrieve sorted set memers from min to max and return maximum
651
652 Option specifies key to query and optional variable name to assign the results to after :
653 (if not specified it would be same as key). If key is not available the plugin can issue
654 either warning or critical alert depending on what you specified after ABSENT.
655 Numeric results are calculated for ranges and can be checked with specified thresholds
656 or you can do it together with standard with redis stats variables and -a option.
657
658 General Check Option (all 3 forms equivalent, can be repated more than once):
659 -o <list of specifiers>, --option=<list of specifiers>, --check=<list of specifiers>
660 where specifiers are separated by , and must include NAME or PATTERN:
661 NAME:<string> - Default name for this variable as you'd have specified with -v
662 PATTERN:<regex> - Regular Expression that allows to match multiple data results
663 WARN:threshold - warning alert threshold
664 CRIT:threshold - critical alert threshold
665 Threshold is a value (usually numeric) which may have the following prefix:
666 > - warn if data is above this value (default for numeric values)
667 < - warn if data is below this value (must be followed by number)
668 = - warn if data is equal to this value (default for non-numeric values)
669 ! - warn if data is not equal to this value
670 Threshold can also be specified as a range in two forms:
671 num1:num2 - warn if data is outside range i.e. if data<num1 or data>num2
672 \@num1:num2 - warn if data is in range i.e. data>=num1 && data<=num2
673 ABSENT:OK|WARNING|CRITICAL|UNKNOWN - Nagios alert (or lock of thereof) if data is absent
674 ZERO:OK|WARNING|CRITICAL|UNKNOWN - Nagios alert (or lock of thereof) if result is 0
675 DISPLAY:YES|NO - Specifies if data should be included in nagios status line output
676 PERF:YES|NO - Output results as performance data or not (always YES if asked for rate)
677 UOM:<string> - Unit Of Measurement symbol to add to perf data - 'c','%','s','B'
678
679 Measured/Calculated Data:
680 -T, --response_time=[WARN,CRIT]
681 If this is used as just -T the plugin will measure and output connection
682 response time in seconds. With -f this would also be provided on perf variables.
683 You can also specify values for this parameter, these are interprted as
684 WARNING and CRITICAL thresholds (separated by ',').
685 -R, --hitrate=[WARN,CRIT]
686 Calculates Hitrate %: cache_miss/(cache_hits+cache_miss). If this is used
687 as just -R then this info just goes to output line. With '-R -f' these
688 go as performance data. You can also specify values for this parameter,
689 these are interprted as WARNING and CRITICAL thresholds (separated by ',').
690 The format for WARN and CRIT is same as what you would use in -w and -c.
691 -m, --memory_utilization=[WARN,CRIT]
692 This calculates percent of total memory on system used by redis, which is
693 utilization=redis_memory_rss/total_memory*100.
694 Total_memory on server must be specified with -M since Redis does not report
695 it and can use maximum memory unless you enabled virtual memory and set a limit
696 (I plan to test this case and see if it gets reported then).
697 If you specify -m by itself, the plugin will just output this info,
698 with '-f' it will also include this in performance data. You can also specify
699 parameter values which are interpreted as WARNING and CRITICAL thresholds.
700 -M, --total_memory=NUM[B|K|M|G]
701 Amount of memory on a system for memory utilization calculations above.
702 If it does not end with K,M,G then its assumed to be B (bytes)
703 -r, --replication_delay=WARN,CRIT
704 Allows to set threshold on replication delay info. Only valid if this is a slave!
705 The threshold value is in seconds and fractions are acceptable.
706
707 EOT
708
709 if (defined($nlib) && $nlib->{'enable_long_options'} == 1) {
710 my $long_opt_help = $nlib->additional_options_help();
711 if ($long_opt_help) {
712 print "Stats Variable Options (this is alternative to specifying them as list with -a):\n";
713 print $long_opt_help;
714 print "\n";
715 }
716 }
717 }
718
719 ############################ START OF THE LIBRARY FUNCTIONS #####################################
720 #
721 # THIS IS WORK IN PROGRESS, THE LIBRARY HAS NOT BEEN RELEASED YET AND INTERFACES MAY CHANGE
722 #
723 # ====================================== SUMMARY ================================================
724 #
725 # Name : Naglio Perl Library For Developing Nagios Plugins
726 # Version : 0.2
727 # Date : Aug 28, 2012
728 # Author : William Leibzon - [email protected]
729 # Licence : LGPL - full text at http://www.fsf.org/licenses/lgpl.txt
730 #
731 # ============================= LIBRARY HISTORY AND VERSIONS ====================================
732 #
733 # Note: you may safely skip this section if you're looking at documentation about this library or plugin
734 #
735 # [2006-2008] The history of this library goes back to plugins such as check_snmp_temperature.pl,
736 # check_mysqld,pl and others released as early as 2006 with common functions to
737 # support prefixes "<,>,=,!" for specifying thresholds and checking data against
738 # these thresholds. Several of my plugins had common architecture supporting multiple
739 # variables or attributes to be checked using -a/--attributes/--variables option and
740 # --warn and --crit options with list of thresholds for these attributes and --perfvars
741 # specifying variables whose data would only go as PERFOUT for graphing.
742 #
743 # [2008-2011] Threshold parsing and check code had been rewritten and support added for specifying
744 # range per plugin guidelines: http://nagiosplug.sourceforge.net/developer-guidelines.html
745 # Internal structures had been changing and becoming more complex to various cases.
746 # In 2010-2012 plugins started to get support for ;warn;crit output of thresholds in perf,
747 # as specified in the guidelines.
748 #
749 # [Early 2012] Code from check_memcached had been used as a base for check_memcached and then
750 # check_redis plugins with some of the latest threshold code from check_netstat
751 # with more updates. Starting with check_redis the code from check_options() and
752 # from main part of plugin that was very similar across my plugins were separated
753 # into their own functions. KNOWN_STATS_VARS array was introduced as well to be
754 # able to properly add UOM symbol ('c', '%', 's', 'ms', 'B', 'KB') to perfout.
755 # check_memcached and check_redis also included support for calculating rate of
756 # variables in a similar way to how its been done in check_snmp_netint
757 #
758 # [0.1 - July 17, 2012] In 0.6 release of check_redis.pl support had been added for long options
759 # with special threshold line syntax:
760 # --option=WARN:threshold,CRIT:threshold,ABSENT:OK|WARNING|CRITICAL|UNKNOWN,DISPLAY:YES|NO,PERF:YES|NO
761 # This was extension from just doing --option=WARN,CRIT to have a more universal
762 # and extendable way to specify and alike parameters for checking. check_redis 0.6
763 # also introduced support automatically adding long options with above syntax based
764 # on description in KNOWN_STATS_VARS. The functions for the library were all separated
765 # into their own section of the code. When inported to check_memcached global variables
766 # were added to that section and accessor functions written for some of them.
767 # This is considered 0.1 version of the library
768 #
769 # [0.2 - Aug 28, 2012] In August the library code in check_memcached had been re-written from
770 # just functions to object-oriented perl interface. All variables were hidden from
771 # direct access with accessor functions written. Documentation header had been added
772 # to each library function and the header for the library itself. This was major work
773 # taking over a week to do although functions and mainly sllllame as in 0.1. They are
774 # not stabilized and so library is only to be included within plugins. Support was
775 # also added for regex matching with PATTERN option spec. Also added NAME spec.
776 # License changed to LGPL from GPL for this code.
777 # [0.21 - Sep 3, 2012] Fix bug in handling absent data
778 # [0.22 - Mar 23, 2013] Fix bug in parse_threshold functon
779 #
780 # ================================== LIBRARY TODO =================================================
781 #
782 # (a) Add library function to support '--extra-opts' to read plugin options from a file
783 # This is being to be compatible with http://nagiosplugins.org/extra-opts
784 # (b) Support regex matching and allowing multiple data for same threshold definition.
785 # [DONE]
786 # (c) Support for expressions in places of numeric values for thresholds. The idea is to allow
787 # to refer to another variable or to special macro. I know at least one person has extended
788 # my check_mysqld to support using mysql variables (not same as status data) for thresholds.
789 # I also previouslyhad planned such support with experimental check_snmp_attributes plugin
790 # library/base. The idea was also floated around on nagios-devel list.
791 # (d) Support specifying variables as expressions. This is straight out of check_snmp_atributes
792 # and maybe part of it can be reused for this
793 # (e) Add common SNMP functions into library as so many of my plugins use it#
794 # (f) Add more functions to make this library easier to use and stabilize its interfaces.
795 # Port my plugins to this library.
796 # (f) Add support for functions in Nagios-Plugins perl library. While its interfaces are
797 # different, I believe, it'd be possible to add "shim" code to support them too.
798 # (h) Write proper Perl-style documentation as well as web documentation (much of above maybe
799 # moved to web documentation) and move library to separate GITHUB project. Release it.
800 # (i) Port this library to Python and write one or two example plugins
801 #
802 # ================================================================================================
803 {
804 package Naglio;
805 use fields qw();
806 use Text::ParseWords;
807
808 my %ERRORS = ('OK'=>0,'WARNING'=>1,'CRITICAL'=>2,'UNKNOWN'=>3,'DEPENDENT'=>4);
809 my $DEFAULT_PERF_OK_STATUS_REGEX = 'GAUGE|COUNTER|^DATA$|BOOLEAN';
810
811 # @DESCRIPTION : Library object constructor
812 # @LAST CHANGED : 08-27-12 by WL
813 # @INPUT : Hash array of named config settings. All parameters are optiona. Currently supported are:
814 # plugin_name => string - short name of the plugin
815 # plugin_description => string - plugin longer description
816 # plugin_authors => string - list of plugin authors
817 # knownStatsVars => reference to hash - hash array defining known variables, what type they are, their description
818 # usage_function => &ref - function that would display helpful text in case of error with options for this plugin
819 # verbose => 1 or "" or "filename" - set to 1 or "" if verbose/debug or to filename to send data to (may not be called "0" or "1")
820 # output_comparison_symbols => 0 or 1 - 1 means library output in case threshold is met can use "<", ">", "="
821 # 0 means output is something like "less than or equal", "more than", etc.
822 # all_variables_perf => 0 or 1 - 1 means data for all variables would go to PERF. This is what '-A *' or just -A do
823 # enable_long_options => 0 or 1 - 1 enables long options generated based on knownStatsVars. This is automatically enabled (from 0
824 # to 1) when plugin references additional_options_list() unless this is set to -1 at library init
825 # enable_rate_of_change => 0 or 1 - enables support for calculating rate of change based on previously saved data, default is 1
826 # enable_regex_match => 0 or 1 - when set to 1 each threshold-specified var name is treated as regex and can match
827 # to multiple collected data. this can also be enabled per-variable with PATTERN spec
828 # @RETURNS : Reference representing object instance of this library
829 # @PRIVACY & USE : PUBLIC, To be used when initializing the library
830 sub lib_init {
831 my $invocant = shift;
832 my $class = ref($invocant) || $invocant;
833 my %other_args = @_;
834
835 # These used to be global variables, now these are object local variables in self with accessor
836 my @allVars = (); # all variables after options processing
837 my @perfVars = (); # performance variables list [renamed from @o_perfVarsL in earlier code]
838 my %thresholds=(); # hash array of thresholds for above variables, [this replaced @o_warnL and @o_critL in earlier code]
839 my %dataresults= (); # This is where data is loaded. It is a hash with variable names as keys and array array for value:
840 # $dataresults{$var}[0] - undef of value of this variable
841 # $dataresults{$var}[1] - 0 if variable not printed out to status line yet, 1 or more otherwise
842 # $dataresults{$var}[2] - 0 if variable data not yet put into PERF output, -1 if PERF output is preset, 1 after output
843 # $dataresults{$var}[3] - string, '' to start with, holds ready performance data output for this variable
844 # $dataresults{$var}[4] - only for regex matches. name of match var (which should be key in thresholds), otherwise undef
845 my %dataVars = (); # keys are variables from allVars and perfVars, values is array of data that matched i.e. keys in dataresults
846 my @ar_warnLv = (); # used during options processing
847 my @ar_critLv = (); # used during options processing
848 my @ar_varsL= (); # used during options processing
849 my @prev_time= (); # timestamps if more then one set of previois performance data
850
851 my $self = { # library and nagios versions
852 _NaglioLibraryVersion => 0.2, # this library's version
853 _NagiosVersion => 3, # assume nagios core 3.x unless known otherwise
854 # library internal data structures
855 _allVars => \@allVars,
856 _perfVars => \@perfVars,
857 _thresholds => \%thresholds,
858 _dataresults => \%dataresults,
859 _datavars => \%dataVars,
860 _ar_warnLv => \@ar_warnLv,
861 _ar_critLv => \@ar_critLv,
862 _ar_varsL => \@ar_varsL,
863 _prevTime => \@prev_time,
864 _prevPerf => {}, # array that is populated with previous performance data
865 _checkTime => undef, # time when data was last checked
866 _statuscode => "OK", # final status code
867 _statusinfo => "", # if there is an error, this has human info about what it is
868 _statusdata => "", # if there is no error but we want some data in status line, this var gets it
869 _perfdata => "", # this variable collects performance data line
870 _saveddata => "", # collects saved data (for next plugin re-run, not implimented yet)
871 _init_args => \%other_args,
872 # copy of data from plugin option variables
873 o_variables => undef, # List of variables for warn and critical checks
874 o_crit => undef, # Comma-separated list of critical thresholds for each checked variable
875 o_warn => undef, # Comma-separated list of warning thresholds for each checked variable
876 o_perf => undef, # defined or undef. perf option means all data from variables also goes as PERFDATA
877 o_perfvars => undef, # List of variables only for PERFDATA
878 o_prevperf => undef, # previously saved performance data coming from $SERVICEPERFDATA$ macro
879 # library special input variables (similar to options)
880 o_rprefix => '', # prefix used to distinguish rate variables
881 o_rsuffix => '_rate', # suffix used to distinguish rate variables
882 knownStatusVars => {}, # Special HASH ARRAY with names and description of known variables
883 perfOKStatusRegex => $DEFAULT_PERF_OK_STATUS_REGEX,
884 verbose => 0, # verbose, same as debug, same as o_verb
885 plugin_name => '', # next 3 parameters are variables are currently not used
886 plugin_description => '', # but its still better if these are provided
887 plugin_authors => '', # in the future these maybe used for help & usage functions
888 # library setting variables
889 debug_file => "", # instead of setting file name in verbose, can also set it here
890 output_comparison_symbols => 1, # should plugin output >,<.=,! for threshold match
891 # if 0, it will say it in human form, i.e. "less"
892 all_variables_perf => 0, # should we all variables go to PERF (even those not listed in o_variables and o_perfvars)
893 # this is the option set to 1 when --perfvars '*' is used
894 enable_long_options => 0, # enable support for long options generated based on knownStatusVars description
895 enable_rate_of_change => 1, # enables support for calculatin rate of chane and for rate of change long options
896 enable_regex_match => 0, # 0 is not enabled, 1 means variables in o_variables and o_perfvars are considered regex to match actual data
897 # a value of 2 means its enabled, but for options with PATTERN specifier (this is not configurale value)
898 };
899
900 # bless to create an object
901 bless $self, $class;
902
903 # deal with arguments that maybe passed to library when initalizing
904 if (exists($other_args{'KNOWN_STATUS_VARS'})) {
905 $self->{'knownStatusVars'} = $other_args{'KNOWN_STATUS_VARS'};
906 }
907 $self->{'plugin_name'} = $other_args{'plugin_name'} if exists($other_args{'plugin_name'});
908 $self->{'plugin_description'} = $other_args{'plugin_description'} if exists($other_args{'plugin_description'});
909 $self->{'plugin_authors'} = $other_args{'plugin_authors'} if exists($other_args{'plugin_authors'});
910 $self->{'usage_function'} = $other_args{'usage_gunction'} if exists($other_args{'usage_function'});
911 $self->configure(%other_args);
912
913 # return self object
914 return $self;
915 }
916
917 # This is just an alias for object constructor lib_init function
918 sub new {
919 return lib_init(@_);
920 }
921
922 # @DESCRIPTION : Allows to confiure some settings after initialization (all these can also be done as part of lib_init)
923 # @LAST CHANGED : 08-27-12 by WL
924 # @INPUT : Hash array of named config settings. All parameters are optiona. Currently supported are:
925 # verbose => 1 or "" or "filename" - set to 1 or "" if verbose/debug or to filename to send data to (may not be called "0" or "1")
926 # output_comparison_symbols => 0 or 1 - 1 means library output in case threshold is met can use "<", ">", "="
927 # 0 means output is something like "less than or equal", "more than", etc.
928 # all_variables_perf => 0 or 1 - 1 means data for all variables would go to PERF. This is what '-A *' or just -A do
929 # enable_long_options => 0 or 1 - 1 enables long options generated based on knownStatsVars. This is automatically enabled (from 0
930 # to 1) when plugin references additional_options_list() unless this is set to -1 at library init
931 # enable_rate_of_change => 0 or 1 - enables support for calculating rate of change based on previously saved data, default is 1
932 # enable_regex_match => 0 or 1 - when set to 1 each threshold-specified var name is treated as regex and can match
933 # to multiple collected data. this can also be enabled per-variable with PATTERN spec
934 # @RETURNS : nothing (future: 1 on success, 0 on error)
935 # @PRIVACY & USE : PUBLIC, Must be used as an object instance function.
936 sub configure {
937 my $self = shift;
938 my %args = @_;
939
940 if (exists($args{'verbose'}) || exists($args{'debug'})) {
941 $self->{'verbose'} = 1;
942 if (exists($args{'verbose'}) && $args{'verbose'}) {
943 $self->{'debug_file'} = $args{'verbose'};
944 }
945 if (exists($args{'debug_log_filename'})) {
946 $self->{'debug_file'} = $args{'debug_log_filename'};
947 }
948 }
949 $self->{'all_variables_perf'} = $args{'all_variables_perf'} if exists($args{'all_variables_perf'});
950 $self->{'enable_long_options'} = $args{'enable_long_options'} if exists($args{'enable_long_options'});
951 $self->{'enable_rate_of_change'} = $args{'enable_rate_of_change'} if exists($args{'enable_rate_of_change'});
952 $self->{'enable_regex_match'} = 1 if exists($args{'enable_regex_match'}) && $args{'enable_regex_match'}!=0;
953 $self->{'output_comparison_symbols'} = $args{'output_comparison_symbols'} if exists($args{'output_comparison_symbols'});
954 }
955
956 # @DESCRIPTION : Allows functions to take be used both directly and as object referenced functions
957 # In the 2nd case they get $self as 1st argument, in 1st they don't. this just adds
958 # $self if its if its not there so their argument list is known.
959 # Functions that allow both should still check if $self is defined
960 # @LAST CHANGED : 08-20-12 by WL
961 # @INPUT : arbitrary list of arguments
962 # @RETURNS : arbitrary list of arguments with 1st being object hash or undef
963 # @PRIVACY & USE : PRIVATE
964 sub _self_args {
965 return @_ if ref($_[0]) && exists($_[0]->{'_NaglioLibraryVersion'});
966 unshift @_,undef;
967 return @_;
968 }
969
970 # @DESCRIPTION : Sets function to be called to display help text on using plugin in case of error
971 # @LAST CHANGED : 08-22-12 by WL
972 # @INPUT : reference to usage function
973 # @RETURNS : nothing
974 # @PRIVACY & USE : PUBLIC, Must be used as an object instance function :
975 sub set_usage_function {
976 my ($self, $usage_function) = @_;
977 $self->{'usage_function'} = $usage_function;
978 }
979
980 # @DESCRIPTION : Usage function. For right now it just calls usage function given as a parameter
981 # In the future if it is not available, it'll print something standard.
982 # @LAST CHANGED : 08-22-12 by WL
983 # @INPUT : none
984 # @RETURNS : nothing
985 # @PRIVACY & USE : PUBLIC, But primary for internal use. Must be used as an object instance function.
986 sub usage {
987 my $self = shift;
988 if (defined($self) && defined($self->{'usage_function'})) { &{$self->{'usage_function'}}(); }
989 }
990
991 # @DESCRIPTION : This function converts uptime in seconds to nice & short output format
992 # @LAST_CHANGED : 08-20-12 by WL
993 # @INPUT : ARG1 - uptime in seconds
994 # @RETURNS : string of uptime for human consumption
995 # @PRIVACY & USE : PUBLIC, Maybe used directly or as object instance function :
996 sub uptime_info {
997 my ($self,$uptime_seconds) = _self_args(@_);
998 my $upinfo = "";
999 my ($secs,$mins,$hrs,$days) = (undef,undef,undef,undef);
1000
1001 sub div_mod { return int( $_[0]/$_[1]) , ($_[0] % $_[1]); }
1002
1003 ($mins,$secs) = div_mod($uptime_seconds,60);
1004 ($hrs,$mins) = div_mod($mins,60);
1005 ($days,$hrs) = div_mod($hrs,24);
1006 $upinfo .= "$days days" if $days>0;
1007 $upinfo .= (($upinfo ne '')?' ':'').$hrs." hours" if $hrs>0;
1008 $upinfo .= (($upinfo ne '')?' ':'').$mins." minutes" if $mins>0 && ($days==0 || $hrs==0);
1009 $upinfo .= (($upinfo ne '')?' ':'').$secs." seconds" if $secs>0 && $days==0 && $hrs==0;
1010 return $upinfo;
1011 }
1012
1013 # @DESCRIPTION : If debug / verbose option is set, function prints its input out or to debug file
1014 # @LAST_CHANGED : 08-20-12 by WL
1015 # @INPUT : ARG1 - string of debug text
1016 # @RETURNS : nothing
1017 # @PRIVACY & USE : PUBLIC, Maybe used directly or as object instance function
1018 sub verb {
1019 my ($self,$in) = _self_args(@_);
1020 my $debug_file_name = "";
1021
1022 if (defined($o_verb) || (defined($self) && defined($self->{'verbose'}) && $self->{'verbose'} ne 0)) {
1023 $debug_file_name = $self->{'debug_file'} if defined($self) && $self->{'debug_file'} ne "";
1024 $debug_file_name = $self->{'verbose'} if $debug_file_name ne "" && defined($self) &&
1025 ($self->{'verbose'} ne 0 && $self->{'verbose'} ne 1 && $self->{'verbose'} ne '');
1026 $debug_file_name = $o_verb if $debug_file_name ne "" && defined($o_verb) && $o_verb ne "";
1027 if ($debug_file_name ne "") {
1028 if (!open (DEBUGFILE, ">>$debug_file_name")) {
1029 print $in, "\n";
1030 }
1031 else {
1032 print DEBUGFILE $in,"\n";
1033 close DEBUGFILE;
1034 }
1035 }
1036 else {
1037 print $in, "\n";
1038 }
1039 }
1040 }
1041
1042 # @DESCRIPTION : Check of string is a a number supporting integers, negative, decimal floats
1043 # @LAST CHANGED : 08-20-12 by WL
1044 # @INPUT : ARG1 - string of text to be checked
1045 # @RETURNS : 1 if its a number, 0 if its not a number
1046 # @PRIVACY & USE : PUBLIC, To be used statically and not as an object instance reference
1047 sub isnum {
1048 my $num = shift;
1049 if (defined($num) && $num =~ /^[-|+]?((\d+\.?\d*)|(^\.\d+))$/ ) { return 1 ;}
1050 return 0;
1051 }
1052
1053 # @DESCRIPTION : Check of string is a a number supporting integers, negative, decimal floats
1054 # @LAST CHANGED : 08-20-12 by WL
1055 # @INPUT : ARG1 - string of text to be checked
1056 # @RETURNS : 1 if its a number, 0 if its not a number
1057 # @PRIVACY & USE : PUBLIC, To be used statically and not as an object instance function
1058 sub trim {
1059 my $string = shift;
1060 $string =~ s/^\s+//;
1061 $string =~ s/\s+$//;
1062 return $string;
1063 }
1064
1065 # @DESCRIPTION : Takes as input string from PERF or SAVED data from previous plugin invocation
1066 # which should contain space-separated list of var=data pairs. The string is
1067 # parsed and it returns back hash array of var=>data pairs.
1068 # - Function written in 2007 for check_snmp_netint, first release 06/01/07
1069 # - Modified to use quotewords as suggested by Nicholas Scott, release of 05/20/12
1070 # @LAST CHANGED : 08-27-12 by WL
1071 # @INPUT : ARG1 - string of text passed from SERVICEPERFDATA OR SERVICESAVEDDATA MACRO
1072 # @RETURNS : hash array (see description)
1073 # @PRIVACY & USE : PUBLIC, Maybe used directly or as object instance function
1074 # TODO: double-check this works when there are no single quotes as check_snmp_netint always did quotes
1075 sub process_perf {
1076 my ($self,$in) = _self_args(@_);
1077 my %pdh;
1078 my ($nm,$dt);
1079 use Text::ParseWords;
1080 foreach (quotewords('\s+',1,$in)) {
1081 if (/(.*)=(.*)/) {
1082 ($nm,$dt)=($1,$2);
1083 if (defined($self)) { $self->verb("prev_perf: $nm = $dt"); }
1084 else { verb("prev_perf: $nm = $dt"); }
1085 # in some of my plugins time_ is to profile execution time for part of plugin
1086 # $pdh{$nm}=$dt if $nm !~ /^time_/;
1087 $pdh{$nm}=$dt;
1088 $pdh{$nm}=$1 if $dt =~ /(\d+)[csB%]/; # 'c' or 's' or B or % maybe have been added
1089 # support for more than one set of previously cached performance data
1090 # push @prev_time,$1 if $nm =~ /.*\.(\d+)/ && (!defined($prev_time[0]) || $prev_time[0] ne $1);
1091 }
1092 }
1093 return %pdh;
1094 }
1095
1096 # @DESCRIPTION : Converts variables with white-spaces with per-name enclosed with ''
1097 # @LAST CHANGED : 08-24-12 by WL
1098 # @INPUT : ARG1 - varible name
1099 # @RETURNS : name for perf-out output
1100 # @PRIVACY & USE : PUBLIC, but its use should be limited. To be used statically and not as an object instance function
1101 sub perf_name {
1102 my $in = shift;
1103 my $out = $in;
1104 $out =~ s/'\/\(\)/_/g; #' get rid of special characters in performance description name
1105 if ($in !~ /\s/ && $in eq $out) {
1106 return $in;
1107 }
1108 return "'".$out."'";
1109 }
1110
1111 # @DESCRIPTION : Determines appropriate output name (for STATUS and PERF) taking into account
1112 # rate variales prefix/suffix and 'NAME' override in long thresholds line specification
1113 # @LAST CHANGED : 08-26-12 by WL
1114 # @INPUT : ARG1 - variable name (variable as found in dataresults)
1115 # @RETURNS : name for output
1116 # @PRIVACY & USE : PUBLIC, but its use should be limited. To be as an object instance function,
1117 sub out_name {
1118 my ($self,$dname) = @_;
1119 my $thresholds = $self->{'_thresholds'};
1120 my $dataresults = $self-> {'_dataresults'};
1121 my $vr = $self->data2varname($dname,1);
1122 my $name_out;
1123
1124 if (defined($vr) && exists($thresholds->{$vr}{'NAME'})) {
1125 if (exists($thresholds->{$vr}{'PATTERN'}) || $self->{'enable_regex_match'} == 1) {
1126 $thresholds->{$vr}{'NAMES_INDEX'} = {} if !exists($thresholds->{$vr}{'NAMES_INDEX'});
1127 if (!exists($thresholds->{$vr}{'NAMES_INDEX'}{$dname})) {
1128 my $ncount = scalar(keys %{$thresholds->{$vr}{'NAMES_INDEX'}});
1129 $ncount++;
1130 $thresholds->{$vr}{'NAMES_INDEX'}{$dname} = $ncount;
1131 }
1132 $name_out = $thresholds->{$vr}{'NAME'} .'_'. $thresholds->{$vr}{'NAMES_INDEX'}{$dname};
1133 }
1134 else {
1135 $name_out = $thresholds->{$vr}{'NAME'};
1136 }
1137 }
1138 else {
1139 # this is for output of rate variables which name internally start with &
1140 if ($dname =~ /^&(.*)/) {
1141 $name_out = $self->{'o_rprefix'}.$1.$self->{'o_rsuffix'};
1142 }
1143 else {
1144 $name_out = $dname;
1145 }
1146 }
1147 return $name_out;
1148 }
1149
1150 # @DESCRIPTION : Builds statusline. Adds info on error conditions that would preceed status data.
1151 # @LAST CHANGED : 08-20-12 by WL
1152 # @INPUT : ARG1 - variable name
1153 # ARG2 - string argument for status info
1154 # @RETURNS : nothing (future: 1 on success, 0 on error)
1155 # @PRIVACY & USE : PUBLIC, but its direct use is discouraged. Must be used as an object instance function
1156 sub addto_statusinfo_output {
1157 my ($self, $var, $sline) = @_;
1158 $self->{'_statusinfo'} .= ", " if $self->{'_statusinfo'};
1159 $self->{'_statusinfo'} .= trim($sline);
1160 $self->{'_dataresults'}{$var}[1]++;
1161 }
1162
1163 # @DESCRIPTION : Accessor function for statusinfo
1164 # @LAST CHANGED : 08-22-12 by WL
1165 # @INPUT : none
1166 # @RETURNS : statusinfo (error conditions and messages) string
1167 # @PRIVACY & USE : PUBLIC. Must be used as an object instance function
1168 sub statusinfo {
1169 my $self = shift;
1170 if (defined($self) && defined($self->{'_statusinfo'})) {
1171 return $self->{'_statusinfo'};
1172 }
1173 return undef;
1174 }
1175
1176 # @DESCRIPTION : Builds Statuline. Adds variable data for status line output in non-error condition.
1177 # @LAST CHANGED : 08-26-12 by WL
1178 # @INPUT : ARG1 - variable name
1179 # ARG2 - formatted for human consumption text of collected data for this variable
1180 # @RETURNS : nothing (future: 1 on success, 0 on error)
1181 # @PRIVACY & USE : PUBLIC, but its direct use is discouraged. Must be used as an object instance function
1182 sub addto_statusdata_output {
1183 my ($self,$dvar,$data) = @_;
1184 my $thresholds = $self->{'_thresholds'};
1185 my $dataresults = $self -> {'_dataresults'};
1186 my $avar = $self->data2varname($dvar,1);
1187
1188 # $self->verb("debug: addto_statusdata_output - dvar is $dvar and avar is $avar");
1189 if ((!exists($thresholds->{$avar}{'DISPLAY'}) || $thresholds->{$avar}{'DISPLAY'} eq 'YES') &&
1190 (!exists($dataresults->{$dvar}[1]) || $dataresults->{$dvar}[1] == 0)) {
1191 $self->{'_statusdata'} .= ", " if $self->{'_statusdata'};
1192 if (defined($data)) {
1193 $self->{'_statusdata'} .= trim($data);
1194 }
1195 elsif (exists($dataresults->{$dvar}[0])) {
1196 $self->{'_statusdata'} .= $self->out_name($dvar) ." is ".$dataresults->{$dvar}[0];
1197 }
1198 $dataresults->{$dvar}[1]++;
1199 }
1200 }
1201
1202 # @DESCRIPTION : Accessor function for statusdata
1203 # @LAST CHANGED : 08-22-12 by WL
1204 # @INPUT : none
1205 # @RETURNS : statusdata string (non-error data from some variables)
1206 # @PRIVACY & USE : PUBLIC. Must be used as an object instance function
1207 sub statusdata {
1208 my $self = shift;
1209 if (defined($self) && defined($self->{'_statusdata'})) {
1210 return $self->{'_statusdata'};
1211 }
1212 return undef;
1213 }
1214
1215 # @DESCRIPTION : This function sets text or data for data variable PERFORMANCE output
1216 # (;warn;crit would be added to it later if thresholds were set for this variable)
1217 # @LAST CHANGED : 08-26-12 by WL
1218 # @INPUT : ARG1 - variable name
1219 # ARG2 - either "var=data" text or just "data" (in which case var= is prepended to it)
1220 # ARG3 - UOM symol ('c' for continous, '%' for percent, 's' for seconds) to added after data
1221 # if undef then it is looked up in known variables and if one is present there, its used
1222 # ARG4 - one of: "REPLACE" - if existing preset perfdata is present, it would be replaced with ARG2
1223 # "ADD" - if existing preset perfdata is there, ARG2 string would be added to it (DEFAULT)
1224 # "IFNOTSET - only set perfdata to ARG2 if it is empty, otherwise keep existing
1225 # @RETURNS : nothing (future: 0 on success, -1 on error)
1226 # @PRIVACY & USE : PUBLIC, but its use should be limited to custom variables added by plugins to data
1227 # Must be used as an object instance function
1228 sub set_perfdata {
1229 my ($self,$avar,$adata,$unit,$opt) = @_;
1230 my $dataresults = $self->{'_dataresults'};
1231 my $thresholds = $self->{'_thresholds'};
1232 my $known_vars = $self->{'knownStatusVars'};
1233 my $bdata = $adata;
1234 my $vr = undef;
1235
1236 # default operation is ADD
1237 if (!defined($opt)) {
1238 $opt = "ADD";
1239 }
1240 else {
1241 $opt = uc $opt;
1242 }
1243 if (defined($adata)) {
1244 # if only data wthout "var=" create proper perf line
1245 $bdata = perf_name($self->out_name($avar)).'='.$adata if $adata !~ /=/;
1246 if (defined($unit)) {
1247 $bdata .= $unit;
1248 }
1249 else {
1250 # appending UOM is done here
1251 $vr = $self->data2varname($avar,1);
1252 if (defined($vr)) {
1253 if (exists($thresholds->{$vr}{'UOM'})) {
1254 $bdata .= $thresholds->{$vr}{'UOM'};
1255 }
1256 elsif (exists($known_vars->{$vr}[2])) {
1257 $bdata .= $known_vars->{$vr}[2];
1258 }
1259 }
1260 }
1261 # preset perfdata in dataresults array
1262 $dataresults->{$avar}=[undef,0,0,''] if !defined($dataresults->{$avar});
1263 $dataresults->{$avar}[2]=-1;
1264 if ($opt eq "REPLACE" || !exists($dataresults->{$avar}[3]) || $dataresults->{$avar}[3] eq '') {
1265 $dataresults->{$avar}[3]=$bdata;
1266 }
1267 elsif (exists($dataresults->{$avar}[3]) && $dataresults->{$avar}[3] ne '' && $opt eq "ADD") {
1268 $dataresults->{$avar}[3].=$adata;
1269 }
1270 }
1271 }
1272
1273 # @DESCRIPTION : This function is used when building performance output
1274 # @LAST CHANGED : 08-26-12 by WL
1275 # @INPUT : ARG1 - variable name
1276 # ARG2 - optional data argument, if not present variable's dataresults are used
1277 # ARG3 - one of: "REPLACE" - if existing preset perfdata is present, it would be replaced with ARG2
1278 # "ADD" - if existing preset perfdata is there, ARG2 string would be added to it
1279 # "IFNOTSET - only set perfdata to ARG2 if it is empty, otherwise keep existing (DEFAULT)
1280 # @RETURNS : nothing (future: 1 on success, 0 on error)
1281 # @PRIVACY & USE : PUBLIC, but its direct use is discouraged. Must be used as an object instance function
1282 sub addto_perfdata_output {
1283 my ($self,$avar,$adata, $opt) = @_;
1284 my $thresholds = $self->{'_thresholds'};
1285 my $dataresults = $self-> {'_dataresults'};
1286 my $vr = undef;
1287
1288 if (!defined($opt)) {
1289 $opt = "IFNOTSET";
1290 }
1291 else {
1292 $opt = uc $opt;
1293 }
1294 $vr = $self->data2varname($avar,1);
1295 if (defined($avar) && defined($vr) &&
1296 (!exists($thresholds->{$vr}{'PERF'}) || $thresholds->{$vr}{'PERF'} eq 'YES') &&
1297 (!defined($dataresults->{$avar}[2]) || $dataresults->{$avar}[2] < 1)) {
1298 my $bdata = '';
1299 if (defined($adata)) {
1300 $bdata .= trim($adata);
1301 }
1302 # this is how most perfdata gets added
1303 elsif (defined($dataresults->{$avar}[0])) {
1304 $bdata .= perf_name($self->out_name($avar)) .'='. $dataresults->{$avar}[0];
1305 }
1306 # this would use existing preset data now if it was present due to default
1307 # setting UOM from KNOWN_STATUS_VARS array is now in set_perfdata if 3rd arg is undef
1308 $self->set_perfdata($avar,$bdata,undef,$opt);
1309 # now we actually add to perfdata from [3] of dataresults
1310 if (exists($dataresults->{$avar}[3]) && $dataresults->{$avar}[3] ne '') {
1311 $bdata = trim($dataresults->{$avar}[3]);
1312 $self->{'_perfdata'} .= " " if $self->{'_perfdata'};
1313 $self->{'_perfdata'} .= $bdata;
1314 $dataresults->{$avar}[2]=0 if $dataresults->{$avar}[2] < 0;
1315 $dataresults->{$avar}[2]++;
1316 }
1317 }
1318 }
1319
1320 # @DESCRIPTION : Accessor function for map from data collected to variable names specified in options and thresholds
1321 # @LAST CHANGED : 08-22-13 by WL
1322 # @INPUT : ARG1 - data variable name
1323 # ARG2 - if undef or 0 return undef if no match for ARG1 found, if 1 return ARG1
1324 # @RETURNS : string of variable name as was specified with --variables or --thresholds
1325 # @PRIVACY & USE : PUBLIC. Must be used as an object instance function
1326 sub data2varname {
1327 my ($self,$dname,$ropt) = @_;
1328 my $dataresults = $self->{'_dataresults'};
1329
1330 return $dataresults->{$dname}[4] if defined($self) && defined($dataresults->{$dname}[4]);
1331 return $dname if defined($ropt) && $ropt eq 1;
1332 return undef;
1333 }
1334
1335 # @DESCRIPTION : Sets list and info on known variables and regex for acceptable data types.
1336 # This function maybe called more than once. If called again, new vars in subsequent
1337 # calls are added to existing ones and existing vars are replaced if they are there again.
1338 # @LAST CHANGED : 08-22-12 by WL
1339 # @INPUT : ARG1 - ref to hash array of known vars. Keys are variable names. Data is an array. Example is:
1340 # 'version' => [ 'misc', 'VERSION', '' ],
1341 # 'utilization' => [ 'misc', 'GAUGE', '%' ],
1342 # 'cmd_get' => [ 'misc', 'COUNTER', 'c', "Total Number of Get Commands from Start" ],
1343 # The array elements are:
1344 # 1st - string of source for this variable. not used by the library at all, but maybe used by code getting the data
1345 # 2nd - type of data in a variable. May be "GAUGE", "VERSION", "COUNTER", "BOOLEAN", "TEXTINFO", "TEXTDATA", "SETTING"
1346 # 3rd - either empty or one-character UOM to be added to perforance data - 'c' for continous, '%' percent, 's' seconds
1347 # 4th - either empty or a description of this variable. If not empty, the variable becomes long-option and this is help text
1348 # ARG2 - regex of acceptable types of data for performance output. Anything else is ignored (i.e. no no output to perf), but
1349 # is still available for threshold checks. if this is undef, then default of 'GAUGE|COUNTER|^DATA$|BOOLEAN' is used
1350 # @RETURNS : nothing (future: 1 on success, 0 on error)
1351 # @PRIVACY & USE : PUBLIC, Must be used as object instance function
1352 sub set_knownvars {
1353 my ($self, $known_vars_in, $vartypes_regex_in) = @_;
1354 my $known_vars = $self->{'knownStatusVars'};
1355
1356 if (defined($known_vars_in)) {
1357 foreach (keys %{$known_vars_in}) {
1358 $known_vars->{$_} = $known_vars_in->{$_};
1359 }
1360 }
1361 if (defined($vartypes_regex_in)) {
1362 $self->{'perfOKStatusRegex'} = $vartypes_regex_in;
1363 }
1364 else {
1365 $self->{'perfOKStatusRegex'} = $DEFAULT_PERF_OK_STATUS_REGEX;
1366 }
1367 }
1368
1369 # @DESCRIPTION : Adds known variables definition one at a time
1370 # @LAST CHANGED : 08-22-12 by WL
1371 # @INPUT : ARG1 - variable name
1372 # ARG2 - string of source for this variable. not used by the library at all, but maybe used by code getting the data
1373 # ARG3 - type of data in a variable. May be "GAUGE", "VERSION", "COUNTER", "BOOLEAN", "TEXTINFO", "TEXTDATA", "SETTING"
1374 # ARG4 - either empty or one-character UOM symbol to be added to perforance data - 'c' for continous, '%' percent, 's' seconds
1375 # ARG5 - either empty or a description of this variable. If not empty, the variable becomes long-option and this is help text
1376 # @RETURNS : nothing (future: 1 on success, 0 on error)
1377 # @PRIVACY & USE : PUBLIC, Must be used as object instance function
1378 sub add_knownvar {
1379 my ($self, $varname, $source, $type, $unit, $description) = @_;
1380 my $temp = { $varname => [ $source, $type, $unit, $description] };
1381 $self->set_knownvars($temp,undef);
1382 }
1383
1384 # @DESCRIPTION : This function is used for checking data values against critical and warning thresholds
1385 # @LAST CHANGED : 08-20-12 by WL
1386 # @INPUT : ARG1 - variable name (used for text output in case it falls within threshold)
1387 # ARG2 - data to be checked
1388 # ARG3 - threshold to be checked, internal structure returned by parse_threshold()
1389 # @RETURNS : Returns "" (empty string) if data is not within threshold range
1390 # and text message for status line out about how data is within range otherwise
1391 # @PRIVACY & USE : PUBLIC. Maybe used directly or as an object instance function
1392 sub check_threshold {
1393 my ($self,$attrib,$data,$th_array) = _self_args(@_);
1394 my $mod = $th_array->[0];
1395 my $lv1 = $th_array->[1];
1396 my $lv2 = $th_array->[2];
1397 my $issymb = 1;
1398 $issymb = 0 if defined($self) && $self->{'output_comparison_symbols'} eq 0;
1399
1400 # verb("debug check_threshold: $mod : ".(defined($lv1)?$lv1:'')." : ".(defined($lv2)?$lv2:''));
1401 return "" if !defined($lv1) || ($mod eq '' && $lv1 eq '');
1402 return " " . $attrib . " is " . $data . ( ($issymb==1)?' = ':' equal to ' ). $lv1 if $mod eq '=' && $data eq $lv1;
1403 return " " . $attrib . " is " . $data . ( ($issymb==1)?' != ':' not equal to ' ). $lv1 if $mod eq '!' && $data ne $lv1;
1404 return " " . $attrib . " is " . $data . ( ($issymb==1)?' > ':' more than ' ) . $lv1 if $mod eq '>' && $data>$lv1;
1405 return " " . $attrib . " is " . $data . ( ($issymb==1)?' > ':' more than ' ) . $lv2 if $mod eq ':' && $data>$lv2;
1406 return " " . $attrib . " is " . $data . ( ($issymb==1)?' >= ':' more than or equal to ' ) . $lv1 if $mod eq '>=' && $data>=$lv1;
1407 return " " . $attrib . " is " . $data . ( ($issymb==1)?' < ':' less than ' ). $lv1 if ($mod eq '<' || $mod eq ':') && $data<$lv1;
1408 return " " . $attrib . " is " . $data . ( ($issymb==1)?' <= ':' less than or equal to ' ) . $lv1 if $mod eq '<=' && $data<=$lv1;
1409 return " " . $attrib . " is " . $data . " in range $lv1..$lv2" if $mod eq '@' && $data>=$lv1 && $data<=$lv2;
1410 return "";
1411 }
1412
1413 # @DESCRIPTION : This function is called to parse threshold string
1414 # @LAST CHANGED : 03-23-13 by WL
1415 # (the code in this function can be traced back to late 2006. It has not much changed from 2008)
1416 # @INPUT : ARG1 - String for one variable WARN or CRIT threshold which can be as follows:
1417 # data - warn if data is above this value if numeric data, or equal for non-numeric
1418 # >data - warn if data is above this value (default for numeric values)
1419 # <data - warn if data is below this value (must be followed by number)
1420 # =data - warn if data is equal to this value (default for non-numeric values)
1421 # !data - warn if data is not equal to this value
1422 # Threshold can also be specified as range in two forms:
1423 # num1:num2 - warn if data is outside range i.e. if data<num1 or data>num2
1424 # \@num1:num2 - warn if data is in range i.e. data>=num1 && data<=num2
1425 # @RETURNS : Returns reference to a hash array, this library's structure for holding processed threshold spec
1426 # @PRIVACY & USE : PUBLIC. Maybe used directly or as an object instance function
1427 sub parse_threshold {
1428 my ($self,$thin) = _self_args(@_);
1429
1430 # link to an array that holds processed threshold data
1431 # array: 1st is type of check, 2nd is threshold value or value1 in range, 3rd is value2 in range,
1432 # 4th is extra options such as ^, 5th is nagios spec string representation for perf out
1433 my $th_array = [ '', undef, undef, '', '' ];
1434 my $th = $thin;
1435 my $at = '';
1436
1437 $at = $1 if $th =~ s/^(\^?[@|>|<|=|!]?~?)//; # check mostly for my own threshold format
1438 $th_array->[3]='^' if $at =~ s/\^//; # deal with ^ option
1439 $at =~ s/~//; # ignore ~ if it was entered
1440 if ($th =~ /^\:([-|+]?\d+\.?\d*)/) { # :number format per nagios spec
1441 $th_array->[1]=$1;
1442 $th_array->[0]=($at !~ /@/)?'>':'<=';
1443 $th_array->[5]=($at !~ /@/)?('~:'.$th_array->[1]):($th_array->[1].':');
1444 }
1445 elsif ($th =~ /([-|+]?\d+\.?\d*)\:$/) { # number: format per nagios spec
1446 $th_array->[1]=$1;
1447 $th_array->[0]=($at !~ /@/)?'<':'>=';
1448 $th_array->[5]=($at !~ /@/)?'':'@';
1449 $th_array->[5].=$th_array->[1].':';
1450 }
1451 elsif ($th =~ /([-|+]?\d+\.?\d*)\:([-|+]?\d+\.?\d*)/) { # nagios range format
1452 $th_array->[1]=$1;
1453 $th_array->[2]=$2;
1454 if ($th_array->[1] > $th_array->[2]) {
1455 print "Incorrect format in '$thin' - in range specification first number must be smaller then 2nd\n";
1456 if (defined($self)) { $self->usage(); }
1457 exit $ERRORS{"UNKNOWN"};
1458 }
1459 $th_array->[0]=($at !~ /@/)?':':'@';
1460 $th_array->[5]=($at !~ /@/)?'':'@';
1461 $th_array->[5].=$th_array->[1].':'.$th_array->[2];
1462 }
1463 if (!defined($th_array->[1])) { # my own format (<,>,=,!)
1464 $th_array->[0] = ($at eq '@')?'<=':$at;
1465 $th_array->[1] = $th;
1466 $th_array->[5] = '~:'.$th_array->[1] if ($th_array->[0] eq '>' || $th_array->[0] eq '>=');
1467 $th_array->[5] = $th_array->[1].':' if ($th_array->[0] eq '<' || $th_array->[0] eq '<=');
1468 $th_array->[5] = '@'.$th_array->[1].':'.$th_array->[1] if $th_array->[0] eq '=';
1469 $th_array->[5] = $th_array->[1].':'.$th_array->[1] if $th_array->[0] eq '!';
1470 }
1471 if ($th_array->[0] =~ /[>|<]/ && !isnum($th_array->[1])) {
1472 print "Numeric value required when '>' or '<' are used !\n";
1473 if (defined($self)) { $self->usage(); }
1474 exit $ERRORS{"UNKNOWN"};
1475 }
1476 # verb("debug parse_threshold: $th_array->[0] and $th_array->[1]");
1477 $th_array->[0] = '=' if !$th_array->[0] && !isnum($th_array->[1]) && $th_array->[1] ne '';
1478 if (!$th_array->[0] && isnum($th_array->[1])) { # this is just the number by itself, becomes 0:number check per nagios guidelines
1479 $th_array->[2]=$th_array->[1];
1480 $th_array->[1]=0;
1481 $th_array->[0]=':';
1482 $th_array->[5]=$th_array->[2];
1483 }
1484 return $th_array;
1485 }
1486
1487 # @DESCRIPTION : this function checks that for numeric data warn threshold is within range of critical
1488 # @LAST CHANGED : 08-20-12 by WL
1489 # @INPUT : ARG1 - warhing threshold structure (reference to hash array)
1490 # ARG2 - critical threshold structure (reference to hash array)
1491 # @RETURNS : Returns 1 if warning does not fall within critical (there is an error)
1492 # Returns 0 if everything is ok and warning is within critical
1493 # @PRIVACY & USE : PUBLIC, but its use is discouraged. Maybe used directly or as an object instance function.
1494 sub threshold_specok {
1495 my ($self, $warn_thar,$crit_thar) = _self_args(@_);
1496
1497 return 1 if defined($warn_thar) && defined($warn_thar->[1]) &&
1498 defined($crit_thar) && defined($crit_thar->[1]) &&
1499 isnum($warn_thar->[1]) && isnum($crit_thar->[1]) &&
1500 $warn_thar->[0] eq $crit_thar->[0] &&
1501 (!defined($warn_thar->[3]) || $warn_thar->[3] !~ /\^/) &&
1502 (!defined($crit_thar->[3]) || $crit_thar->[3] !~ /\^/) &&
1503 (($warn_thar->[1]>$crit_thar->[1] && ($warn_thar->[0] =~ />/ || $warn_thar->[0] eq '@')) ||
1504 ($warn_thar->[1]<$crit_thar->[1] && ($warn_thar->[0] =~ /</ || $warn_thar->[0] eq ':')) ||
1505 ($warn_thar->[0] eq ':' && $warn_thar->[2]>=$crit_thar->[2]) ||
1506 ($warn_thar->[0] eq '@' && $warn_thar->[2]<=$crit_thar->[2]));
1507 return 0; # return with 0 means specs check out and are ok
1508 }
1509
1510 # @DESCRIPTION : this compares var names from data to names given as plugin options treating them regex
1511 # @LAST CHANGED : 08-26-12 by WL
1512 # @INPUT : ARG1 - the name to search for
1513 # @RETURNS : Keyname for what first one that matched from _thresholds
1514 # Undef if nothing matched
1515 # @PRIVACY & USE : PUBLIC, but its direct use should be rare. Must be used as an object instance function.
1516 sub var_pattern_match {
1517 my ($self, $name) = @_;
1518 my $thresholds = $self->{'_thresholds'};
1519 my $allvars = $self->{'_allVars'};
1520 my $is_regex_match = $self->{'enable_regex_match'};
1521 my $v;
1522 my $pattern;
1523
1524 foreach $v (@{$allvars}) {
1525 $pattern='';
1526 if ($is_regex_match eq 1 && !defined($thresholds->{$v}{'PATTERN'})) {
1527 $pattern=$v;
1528 }
1529 elsif ($is_regex_match ne 0 && defined($thresholds->{$v}{'PATTERN'})) {
1530 $pattern = $thresholds->{$v}{'PATTERN'};
1531 }
1532 if ($pattern ne '' && $name =~ /$pattern/) {
1533 $self->verb("Data name '".$name."' matches pattern '".$pattern."'");
1534 return $v;
1535 }
1536 }
1537 return undef;
1538 }
1539
1540 # @DESCRIPTION : This function adds data results
1541 # @LAST CHANGED : 08-27-12 by WL
1542 # @INPUT : ARG1 - name of data variable
1543 # ARG2 - data for this variable
1544 # ARG3 - name of checked variable/parameter corresponding to this data variable
1545 # default undef, assumed to be same as ARG1
1546 # @RETURNS : nothing (future: 1 on success, 0 on error)
1547 # @PRIVACY & USE : PUBLIC, Must be used as an object instance function
1548 sub add_data {
1549 my ($self, $dnam, $dval, $anam) = @_;
1550 my $thresholds = $self->{'_thresholds'};
1551 my $dataresults = $self-> {'_dataresults'};
1552 my $datavars = $self -> {'_datavars'};
1553 my $perfVars = $self->{'_perfVars'};
1554
1555 # determine what plugin options-specified var & threshold this data corresponds to
1556 if (!defined($anam)) {
1557 if ($self->{'enable_regex_match'} == 0) {
1558 $anam = $dnam;
1559 }
1560 else {
1561 $anam = $self->var_pattern_match($dnam);
1562 $anam = $dnam if !defined($anam);
1563 }
1564 }
1565 # set dataresults
1566 if (exists($dataresults->{$dnam})) {
1567 $dataresults->{$dnam}[0] = $dval;
1568 $dataresults->{$dnam}[4] = $anam if defined($anam);
1569 }
1570 else {
1571 $dataresults->{$dnam} = [$dval, 0, 0, '', $anam];
1572 }
1573 # reverse map array
1574 $datavars->{$anam} = [] if !exists($datavars->{$anam});
1575 push @{$datavars->{$anam}}, $dnam;
1576 # setperf if all variables go to perf
1577 if ($self->{'all_variables_perf'} == 1) {
1578 $thresholds->{$anam}={} if !exists($thresholds->{$anam});
1579 $thresholds->{$anam}{'PERF_DATALIST'} = [] if !exists($thresholds->{$anam}{'PERF_DATALIST'});
1580 push @{$thresholds->{$anam}{'PERF_DATALIST'}}, $dnam;
1581 if (!defined($thresholds->{$anam}{'PERF'})) {
1582 push @{$perfVars}, $anam;
1583 $thresholds->{$anam}{'PERF'} = 'YES';
1584 }
1585 }
1586 }
1587
1588 # @DESCRIPTION : Accessor function that gets variable data
1589 # @LAST CHANGED : 08-20-12 by WL
1590 # @INPUT : ARG1 - name of data variable
1591 # @RETURNS : undef if variable does not exist and data otherwise
1592 # @PRIVACY & USE : PUBLIC, Must be used as an object instance function
1593 sub vardata {
1594 my ($self,$dnam) = @_;
1595 my $dataresults = $self->{'_dataresults'};
1596 return undef if !exists($dataresults->{$dnam});
1597 return $dataresults->{$dnam}[0];
1598 }
1599
1600 # @DESCRIPTION : This function parses "WARN:threshold,CRIT:threshold,ABSENT:OK|WARNING|CRITICAL|UNKNOWN" combined threshold string
1601 # Parsing of actual threshold i.e. what is after WARN, CRIT is done by parse_threshold() function
1602 # @LAST CHANGED : 08-27-12 by WL
1603 # @INPUT : ARG1 - String containing threshold line like "WARN:threshold,CRIT:threshold,ABSENT:OK|WARNING|CRITICAL|UNKNOWN"
1604 # Acceptable comma-separated parts threshold specifiers are:
1605 # WARN:<threshold> - warning threshold
1606 # CRIT:<treshold> - critical threshold
1607 # ABSENT:OK|WARNING|CRITICAL|UNKNOWN - nagios exit code if data for this variable is not found
1608 # ZERO:OK|WARNING|CRITICAL|UNKNOWN - nagios exit code if data is 0
1609 # DISPLAY:YES|NO - output data in plugin status line
1610 # PERF:YES|NO - output data as plugin performance data
1611 # SAVED:YES|NO - put results in saved data (this really should not be set manually)
1612 # PATTERN:<regex> - enables regex match allowing more than one real data name to match this threshold
1613 # NAME:<string> - overrides output status and perf name for this variable
1614 # UOM:<string> - unit of measurement symbol to add to perf
1615 # @RETURNS : Returns reference to a hash array, a library's structure for holding processed MULTI-THRESHOLD spec
1616 # Note that this is MULTI-THRESHOLD hash structure, it itself contains threshold hashes returned by parse_threshold()
1617 # @PRIVACY & USE : PUBLIC, but its use is discouraged. Maybe used directly or as an object instance function.
1618 sub parse_thresholds_list {
1619 my ($self,$in) = _self_args(@_);
1620 my $thres = {};
1621 my @tin = undef;
1622 my $t = undef;
1623 my $t2 = undef;
1624
1625 @tin = split(',', $in);
1626 $t = uc $tin[0] if exists($tin[0]);
1627 # old format with =warn,crit thresolds without specifying which one
1628 if (defined($t) && $t !~ /^WARN/ && $t !~ /^CRIT/ && $t !~ /^ABSENT/ && $t !~ /^ZERO/ &&
1629 $t !~ /^DISPLAY/ && $t !~ /^PERF/ && $t !~ /^SAVED/ &&
1630 $t !~ /^PATTERN/ && $t !~ /^NAME/ && $t !~ /^UOM/) {
1631 if (scalar(@tin)==2) {
1632 if (defined($self)) {
1633 $thres->{'WARN'} = $self->parse_threshold($tin[0]);
1634 $thres->{'CRIT'} = $self->parse_threshold($tin[1]);
1635 }
1636 else {
1637 $thres->{'WARN'} = parse_threshold($tin[0]);
1638 $thres->{'CRIT'} = parse_threshold($tin[1]);
1639 }
1640 }
1641 else {
1642 print "Can not parse. Unknown threshold specification: $in\n";
1643 print "Threshold line should be either both warning and critical thresholds separated by ',' or \n";
1644 print "new format of: WARN:threshold,CRIT:threshold,ABSENT:OK|WARNING|CRITICAL|UNKNOWN\n";
1645 print "which allows to specify all 3 (CRIT,WARN,ABSENT) or any one of them in any order\n";
1646 if (defined($self)) { $self->usage(); }
1647 exit $ERRORS{"UNKNOWN"};
1648 }
1649 }
1650 # new format with prefix specifying if its WARN or CRIT and support of ABSENT
1651 else {
1652 foreach $t (@tin) {
1653 $t2 = uc $t;
1654 if ($t2 =~ /^WARN\:(.*)/) {
1655 if (defined($self)) {
1656 $thres->{'WARN'} = $self->parse_threshold($1);
1657 }
1658 else {
1659 $thres->{'WARN'} = parse_threshold($1);
1660 }
1661 }
1662 elsif ($t2 =~ /^CRIT\:(.*)/) {
1663 if (defined($self)) {
1664 $thres->{'CRIT'} = $self->parse_threshold($1);
1665 }
1666 else {
1667 $thres->{'CRIT'} = parse_threshold($1);
1668 }
1669 }
1670 elsif ($t2 =~ /^ABSENT\:(.*)/) {
1671 my $val = $1;
1672 if (defined($ERRORS{$val})) {
1673 $thres->{'ABSENT'} = $val;
1674 }
1675 else {
1676 print "Invalid value $val after ABSENT. Acceptable values are: OK, WARNING, CRITICAL, UNKNOWN\n";
1677 if (defined($self)) { $self->usage(); }
1678 exit $ERRORS{"UNKNOWN"};
1679 }
1680 }
1681 elsif ($t2 =~ /^ZERO\:(.*)/) {
1682 my $val = $1;
1683 if (exists($ERRORS{$val})) {
1684 $thres->{'ZERO'} = $val;
1685 }
1686 else {
1687 print "Invalid value $val after ZERO. Acceptable values are: OK, WARNING, CRITICAL, UNKNOWN\n";
1688 if (defined($self)) { $self->usage(); }
1689 exit $ERRORS{"UNKNOWN"};
1690 }
1691 }
1692 elsif ($t2 =~ /^DISPLAY\:(.*)/) {
1693 if ($1 eq 'YES' || $1 eq 'NO') {
1694 $thres->{'DISPLAY'} = $1;
1695 }
1696 else {
1697 print "Invalid value $1 after DISPLAY. Specify this as YES or NO.\n";
1698 if (defined($self)) { $self->usage(); }
1699 exit $ERRORS{"UNKNOWN"};
1700 }
1701 }
1702 elsif ($t2 =~ /^PERF\:(.*)/) {
1703 if ($1 eq 'YES' || $1 eq 'NO') {
1704 $thres->{'PERF'} = $1;
1705 }
1706 else {
1707 print "Invalid value $1 after PERF. Specify this as YES or NO.\n";
1708 if (defined($self)) { $self->usage(); }
1709 exit $ERRORS{"UNKNOWN"};
1710 }
1711 }
1712 elsif ($t =~ /^PATTERN\:(.*)/i) {
1713 $thres->{'PATTERN'} = $1;
1714 $self->{'enable_regex_match'} = 2 if defined($self) && $self->{'enable_regex_match'} eq 0;
1715 }
1716 elsif ($t =~ /^NAME\:(.*)/i) {
1717 $thres->{'NAME'} = $1;
1718 }
1719 elsif ($t =~ /^UOM\:(.*)/i) {
1720 $thres->{'UOM'} = $1;
1721 }
1722 else {
1723 print "Can not parse. Unknown threshold specification: $_\n";
1724 print "Threshold line should be WARN:threshold,CRIT:threshold,ABSENT:OK|WARNING|CRITICAL|UNKNOWN,ZERO:OK|WARNING|CRITICAL|UNKNOWN\n";
1725 if (defined($self)) { $self->usage(); }
1726 exit $ERRORS{"UNKNOWN"};
1727 }
1728 }
1729 }
1730 if (exists($thres->{'WARN'}) && exists($thres->{'CRIT'})) {
1731 my $check_warncrit = 0;
1732 if (defined($self)) {
1733 $check_warncrit = $self->threshold_specok($thres->{'WARN'},$thres->{'CRIT'});
1734 }
1735 else {
1736 $check_warncrit = threshold_specok($thres->{'WARN'},$thres->{'CRIT'});
1737 }
1738 if ($check_warncrit) {
1739 print "All numeric warning values must be less then critical (or greater then when '<' is used)\n";
1740 print "Note: to override this check prefix warning value with ^\n";
1741 if (defined($self)) { $self->usage(); }
1742 exit $ERRORS{"UNKNOWN"};
1743 }
1744 }
1745 return $thres;
1746 }
1747
1748 # @DESCRIPTION : Adds variable to those whose thresholds would be checked
1749 # @LAST CHANGED : 08-27-12 by WL
1750 # @INPUT : ARG1 - name of the data variable
1751 # ARG2 - either:
1752 # 1) ref to combined thresholds hash array i.e. { 'WARN' => threshold array, 'CRIT' => threshold array, ABSENT => ... }
1753 # such hash array is returned by by parse_thresholds_list function
1754 # -- OR --
1755 # 2) a tet string with a list of thresholds in the format
1756 # WARN:threshold,CRIT:thresholod,ABSENT:OK|WARNING|CRITICAL|UNKNOWN,ZERO:WARNING|CRITICAL|UNKNOWN,PATTERN:pattern,NAME:name
1757 # which would get parsed y parse_thresholds_list function into ref array
1758 # @RETURNS : nothing (future: 1 on success, 0 on error)
1759 # @PRIVACY & USE : PUBLIC, Recommend function for adding thresholds. Must be used as an object instance function
1760 sub add_thresholds {
1761 my ($self,$var,$th_in) = @_;
1762 my $th;
1763 if (ref($th_in) && (exists($th_in->{'WARN'}) || exists($th_in->{'CRIT'}) || exists($th_in->{'DISPLAY'}) ||
1764 exists($th_in->{'PERF'}) || exists($th_in->{'SAVED'}) || exists($th_in->{'ABSENT'}) ||
1765 exists($th_in->{'ZERO'}) || exists($th_in->{'PATTERN'}))) {
1766 $th = $th_in;
1767 }
1768 else {
1769 $th = $self->parse_thresholds_list($th_in);
1770 }
1771 if (!defined($var)) {
1772 if (defined($th->{'NAME'})) {
1773 $var = $th->{'NAME'};
1774 }
1775 elsif (defined($th->{'PATTERN'})) {
1776 $var = $th->{'PATTERN'};
1777 }
1778 else {
1779 print "Can not parse. No name or pattern in threshold: $th_in\n";
1780 print "Specify threshold line as: NAME:name,PATTERN:regex,WARN:threshold,CRIT:threshold,ABSENT:OK|WARNING|CRITICAL|UNKNOWN,ZERO:OK|WARNING|CRITICAL|UNKNOWN\n";
1781 $self->usage();
1782 exit $ERRORS{"UNKNOWN"};
1783 }
1784 }
1785 push @{$self->{'_allVars'}}, $var if !exists($self->{'_thresholds'}{$var});
1786 $self->{'_thresholds'}{$var}=$th;
1787 }
1788
1789 # @DESCRIPTION : Accessor function for thresholds and related variable settings on what and how to check
1790 # @LAST CHANGED : 08-20-12 by WL
1791 # @INPUT : ARG1 - name of data variable
1792 # ARG2 - name of the threshold or related data setting to return
1793 # This can be: "WARN", "CRIT", "ABSENT", "ZERO", "DISPLAY", "PERF"
1794 # @RETURNS : undef if variable does not exist
1795 # if variable exists and "WARN" or "CRIT" thresholds are requested, it returns asociated
1796 # threshold hash array structure for named threshold of the type returned by parse_threshold()
1797 # for ABSENT, ZERO, DISPLAY, PERF and other, it returns a string for this check setting
1798 # @PRIVACY & USE : PUBLIC, Must be used as an object instance function
1799 sub get_threshold {
1800 my ($self,$var,$thname) = @_;
1801 return undef if !exists($self->{'_thresholds'}{$var}) || !exists($self->{'_thresholds'}{$var}{$thname});
1802 return $self->{'_thresholds'}{$var}{$thname};
1803 }
1804
1805 # @DESCRIPTION : Modifier function for thresholds and related variable settings on how to check and display results
1806 # @LAST CHANGED : 08-20-12 by WL
1807 # @INPUT : ARG1 - name of data variable
1808 # ARG2 - type of the threshold or related data setting
1809 # This can be: "WARN", "CRIT", "ABSENT", "ZERO", "DISPLAY", "PERF"
1810 # ARG3 - what to set this to, for "WARN" and "CRIT" this must be hash array returned by parse_threshold()
1811 # @RETURNS : 0 if type you want to set is not one of "WARN", "CRIT", "ZERO" or other acceptable settings
1812 # 1 on success
1813 # @PRIVACY & USE : PUBLIC, Must be used as an object instance function
1814 sub set_threshold {
1815 my ($self,$var,$thname,$thdata) = @_;
1816 if ($thname ne 'WARN' && $thname ne 'CRIT' && $thname ne 'ZERO' && $thname ne 'PATTERN' && $thname ne 'NAME' &&
1817 $thname ne 'ABSENT' && $thname ne 'PERF' && $thname ne 'DISPLAY' && $thname ne 'SAVED' && $thname ne 'UOM') {
1818 return 0;
1819 }
1820 $self->{'_thresholds'}{$var}={} if !exists($self->{'_thresholds'}{$var});
1821 $self->{'_thresholds'}{$var}{$thname}=$thdata;
1822 return 1;
1823 }
1824
1825 # @DESCRIPTION : Returns list variables for GetOptions(..) that are long-options based on known/defined variable
1826 # @LAST CHANGED : 08-20-12 by WL
1827 # @INPUT : none
1828 # @RETURNS : Array of additional options based on KNOWN_STATS_VARS
1829 # @PRIVACY & USE : PUBLIC, Special use case with GetOpt::Long. Must be used as an object instance function
1830 sub additional_options_list {
1831 my $self = shift;
1832
1833 my $known_vars = $self->{'knownStatusVars'};
1834 my ($o_rprefix, $o_rsuffix, $v, $v2) = ('','','','');
1835 $o_rprefix = $self->{'o_rprefix'} if defined($self->{'o_rprefix'});
1836 $o_rsuffix = $self->{'o_rsuffix'} if defined($self->{'o_rsuffix'});
1837 my @VarOptions = ();
1838
1839 if ($self->{'enable_long_options'} != -1) {
1840 if (defined($self) && defined($known_vars)) {
1841 foreach $v (keys %{$known_vars}) {
1842 if (exists($known_vars->{$v}[3]) && $known_vars->{$v}[3] ne '') {
1843 push @VarOptions,$v."=s";
1844 if ($self->{'enable_rate_of_change'} eq 1 && $known_vars->{$v}[1] eq 'COUNTER' && ($o_rprefix ne '' || $o_rsuffix ne '')) {
1845 $v2 = $o_rprefix.$v.$o_rsuffix;
1846 push @VarOptions,$v2."=s"
1847 }
1848 }
1849 }
1850 }
1851 }
1852 if (scalar(@VarOptions)>0) {
1853 $self->{'enable_long_options'} = 1;
1854 }
1855 return @VarOptions;
1856 }
1857
1858 # @DESCRIPTION : Prints out help for generated long options
1859 # @LAST CHANGED : 08-20-12 by WL
1860 # @INPUT : none
1861 # @RETURNS : a string of text for help output
1862 # @PRIVACY & USE : PUBLIC, Special use case with GetOpt::Long. Must be used as an object instance function
1863 sub additional_options_help {
1864 my $self = shift;
1865 my $vname;
1866 my $vname2;
1867 my $counter = 0;
1868 my $known_vars = $self->{'knownStatusVars'};
1869
1870 if ($self->{'enable_long_options'} != 1) { return ''; }
1871
1872 my $out=" These options are all --long_name=<list of specifiers separated by ,>
1873 where specifiers are one or more of:
1874 WARN:threshold - warning alert threshold
1875 CRIT:threshold - critical alert threshold
1876 Threshold is a value (usually numeric) which may have the following prefix:
1877 > - warn if data is above this value (default for numeric values)
1878 < - warn if data is below this value (must be followed by number)
1879 = - warn if data is equal to this value (default for non-numeric values)
1880 ! - warn if data is not equal to this value
1881 Threshold can also be specified as a range in two forms:
1882 num1:num2 - warn if data is outside range i.e. if data<num1 or data>num2
1883 \@num1:num2 - warn if data is in range i.e. data>=num1 && data<=num2
1884 ABSENT:OK|WARNING|CRITICAL|UNKNOWN - Nagios alert (or lock of thereof) if data is absent
1885 ZERO:OK|WARNING|CRITICAL|UNKNOWN - Nagios alert (or lock of thereof) if result is 0
1886 DISPLAY:YES|NO - Specifies if data should be included in nagios status line output
1887 PERF:YES|NO - Output results as performance data or not (always YES if asked for rate)
1888 NAME:<string> - Change the name to <string> in status and PERF output\n\n";
1889
1890 # add more options based on KNOWN_STATUS_VARS array
1891 foreach $vname (keys(%{$known_vars})) {
1892 if (exists($known_vars->{$vname}[3])) {
1893 $counter++;
1894 $out .= ' --'.$vname."=WARN:threshold,CRIT:threshold,<other specifiers>\n";
1895 $out .= " ".$known_vars->{$vname}[3]."\n";
1896 if ($known_vars->{$vname}[1] eq 'COUNTER' && $self->{'enable_rate_of_change'} eq 1) {
1897 $vname2=$o_rprefix.$vname.$o_rsuffix;
1898 $out .= ' --'.$vname2."=WARN:threshold,CRIT:threshold,<other specifiers>\n";
1899 $out .= " Rate of Change of ".$known_vars->{$vname}[3]."\n";
1900 }
1901 }
1902 }
1903 if ($counter>0) { return $out; }
1904 return "";
1905 }
1906
1907 # @DESCRIPTION : Processes standard options parsing out of them variables to be checked
1908 # @LAST CHANGED : 08-20-12 by WL
1909 # @INPUT : ARG1 - Options data hash from GetOpt::Long
1910 # ARG2 - option --verbose or -v or --debug : undef normally and "" or filename if debug enabled
1911 # ARG3 - option --variables or -a in WL's plugins : comma-separated list of variables to check
1912 # ARG4 - option --warn or -w : comma-separated warning thresholds for variables in ARG3
1913 # ARG5 - option --crit or -c : comma-separated critical thresholds for variables in ARG3
1914 # ARG6 - option --perf or -f in WL's plugin: all regular variables should also go to perf data
1915 # ARG7 - option --perfvars or -A in WL's plugins: command-separated list of variables whose data goes to PERF output
1916 # ARG8 - prefix to distinguish rate variables, maybe "" but usually this is "rate_"
1917 # ARG9 - suffix to distinguish rate variables, only if ARG7 is "", otherwise optional and absent
1918 # @RETURNS : nothing (future: 1 on success, 0 on error)
1919 # @PRIVACY & USE : PUBLIC, To be used shortly after GetOptions. Must be used as an object instance function
1920 sub options_startprocessing {
1921 my ($self, $Options, $o_verb, $o_variables, $o_warn, $o_crit, $o_perf, $o_perfvars, $o_rprefix, $o_rsuffix) = @_;
1922
1923 # Copy input parameters to object hash array, set them if not present
1924 $o_rprefix="" if !defined($o_rprefix);
1925 $o_rsuffix="" if !defined($o_rsuffix);
1926 $o_crit="" if !defined($o_crit);
1927 $o_warn="" if !defined($o_warn);
1928 $o_variables="" if !defined($o_variables);
1929 $self->{'o_variables'} = $o_variables;
1930 $self->{'o_perfvars'} = $o_perfvars;
1931 $self->{'o_crit'} = $o_crit;
1932 $self->{'o_warn'} = $o_warn;
1933 $self->{'o_perf'} = $o_perf;
1934 $self->{'o_rprefix'} = $o_rprefix;
1935 $self->{'o_rsuffix'} = $o_rsuffix;
1936 $self->{'verbose'} = $o_verb if defined($o_verb);
1937 # start processing
1938 my $perfVars = $self->{'_perfVars'};
1939 my $ar_varsL = $self->{'_ar_varsL'};
1940 my $ar_critLv = $self->{'_ar_critLv'};
1941 my $ar_warnLv = $self->{'_ar_warnLv'};
1942 my $known_vars = $self->{'knownStatusVars'};
1943 $o_rprefix = lc $o_rprefix;
1944 $o_rsuffix = lc $o_rsuffix;
1945 # process o_perfvars option
1946 if (defined($o_perfvars)) {
1947 @{$perfVars} = split( /,/ , lc $o_perfvars );
1948 if (scalar(@{$perfVars})==0) {
1949 $o_perfvars='*';
1950 $self->{'o_perfvars'}='*';
1951 }
1952 if ($o_perfvars eq '*') {
1953 $self->{'all_variables_perf'} = 1;
1954 }
1955 else {
1956 # below loop converts rate variables to internal representation
1957 for (my $i=0; $i<scalar(@{$perfVars}); $i++) {
1958 $perfVars->[$i] = '&'.$1 if $perfVars->[$i] =~ /^$o_rprefix(.*)$o_rsuffix$/;
1959 }
1960 }
1961 }
1962 if (defined($o_warn) || defined($o_crit) || defined($o_variables)) {
1963 if (defined($o_variables)) {
1964 @{$ar_varsL}=split( /,/ , lc $o_variables );
1965 if (defined($o_warn)) {
1966 $o_warn.="~" if $o_warn =~ /,$/;
1967 @{$ar_warnLv}=split( /,/ , lc $o_warn );
1968 }
1969 if (defined($o_crit)) {
1970 $o_crit.="~" if $o_crit =~ /,$/;
1971 @{$ar_critLv}=split( /,/ , lc $o_crit );
1972 }
1973 }
1974 else {
1975 print "Specifying warning or critical thresholds requires specifying list of variables to be checked\n";
1976 if (defined($self)) { $self->usage(); }
1977 exit $ERRORS{"UNKNOWN"};
1978 }
1979 }
1980 # this is a special loop to check stats-variables options such as "connected_clients=WARN:warning,CRIT:critical"
1981 # which are specified as long options (new extended threshold line spec introduced in check_redis and check_memcached)
1982 my ($vname,$vname2) = (undef,undef);
1983 foreach $vname (keys(%{$known_vars})) {
1984 $vname2=$o_rprefix.$vname.$o_rsuffix;
1985 if (exists($known_vars->{$vname}[3])) {
1986 if (exists($Options->{$vname})) {
1987 $self->verb("Option $vname found with spec parameter: ".$Options->{$vname});
1988 $self->add_thresholds($vname,$Options->{$vname});
1989 }
1990 if (exists($Options->{$vname2})) {
1991 $self->verb("Rate option $vname2 found with spec parameter: ".$Options->{$vname2});
1992 $self->add_thresholds('&'.$vname,$Options->{$vname2});
1993 }
1994 }
1995 }
1996 $self->{'_called_options_startprocessing'}=1;
1997 }
1998
1999 # @DESCRIPTION : Internal function. Parses and sets thresholds for given list of variables after all options have been processed
2000 # @LAST CHANGED : 08-20-12 by WL
2001 # @INPUT : none
2002 # @RETURNS : nothing (future: 1 on success, 0 on error)
2003 # @PRIVACY & USE : PRIVATE, Must be used as an object instance function
2004 sub _options_setthresholds {
2005 my $self = shift;
2006
2007 my $perfVars = $self->{'_perfVars'};
2008 my $ar_varsL = $self->{'_ar_varsL'};
2009 my $ar_critLv = $self->{'_ar_critLv'};
2010 my $ar_warnLv = $self->{'_ar_warnLv'};
2011 my $known_vars = $self->{'knownStatusVars'};
2012 my $thresholds = $self->{'_thresholds'};
2013 my ($o_rprefix, $o_rsuffix) = ("", "");
2014 $o_rprefix = $self->{'o_rprefix'} if exists($self->{'o_rprefix'});
2015 $o_rsuffix = $self->{'o_rsuffix'} if exists($self->{'o_rsuffix'});
2016
2017 if (scalar(@{$ar_warnLv})!=scalar(@{$ar_varsL}) || scalar(@{$ar_critLv})!=scalar(@{$ar_varsL})) {
2018 printf "Number of specified warning levels (%d) and critical levels (%d) must be equal to the number of attributes specified at '-a' (%d). If you need to ignore some attribute do it as ',,'\n", scalar(@{$ar_warnLv}), scalar(@{$ar_critLv}), scalar(@{$ar_varsL});
2019 $self->verb("Warning Levels: ".join(",",@{$ar_warnLv}));
2020 $self->verb("Critical Levels: ".join(",",@{$ar_critLv}));
2021 if (defined($self)) { $self->usage(); }
2022 exit $ERRORS{"UNKNOWN"};
2023 }
2024 for (my $i=0; $i<scalar(@{$ar_varsL}); $i++) {
2025 $ar_varsL->[$i] = '&'.$1 if $ar_varsL->[$i] =~ /^$o_rprefix(.*)$o_rsuffix$/;
2026 if ($ar_varsL->[$i] =~ /^&(.*)/) {
2027 if (!defined($self->{'o_prevperf'})) {
2028 print "Calculating rate variable such as ".$ar_varsL->[$i]." requires previous performance data. Please add '-P \$SERVICEPERFDATA\$' to your nagios command line.\n";
2029 if (defined($self)) { $self->usage(); }
2030 exit $ERRORS{"UNKNOWN"};
2031 }
2032 if (defined($known_vars->{$1}) && $known_vars->{$1}[0] ne 'COUNTER') {
2033 print "$1 is not a COUNTER variable for which rate of change should be calculated\n";
2034 if (defined($self)) { $self->usage(); }
2035 exit $ERRORS{"UNKNOWN"};
2036 }
2037 }
2038 if (!exists($thresholds->{$ar_varsL->[$i]})) {
2039 my $warn = $self->parse_threshold($ar_warnLv->[$i]);
2040 my $crit = $self->parse_threshold($ar_critLv->[$i]);
2041 if ($self->threshold_specok($warn,$crit)) {
2042 print "All numeric warning values must be less then critical (or greater then when '<' is used)\n";
2043 print "Note: to override this check prefix warning value with ^\n";
2044 if (defined($self)) { $self->usage(); }
2045 exit $ERRORS{"UNKNOWN"};
2046 }
2047 $self->add_thresholds($ar_varsL->[$i], {'WARN'=>$warn,'CRIT'=>$crit} );
2048 }
2049 }
2050 }
2051
2052 # @DESCRIPTION : Internal helper function. Finds time when previous performance data was calculated/saved at
2053 # @DEVNOTE : Right now this library and function only supports one previous performance data set,
2054 # but check_snmp_netint plugin supports multiple sets and there the code is more complex,
2055 # As this function originated there, that code is commented out right now.
2056 # @LAST CHANGED : 08-21-12 by WL
2057 # @INPUT : ARG1 - reference to previous performance data hash array. It looks for _ptime variable there.
2058 # ARG2 - string with previous performance time in unix seconds. This may come from separate plugin option.
2059 # @RETURNS : Time in unix seconds frm 1970 or undef if it was not located
2060 # @PRIVACY & USE : PRIVATE, Maybe used directly or as an object instance function.
2061 sub _set_prevtime {
2062 my ($self,$prevperf,$o_prevtime) = _self_args(@_);
2063 my $perfcheck_time;
2064
2065 if (defined($o_prevtime)) {
2066 # push @prev_time, $o_prevtime;
2067 # $prev_perf{ptime}=$o_prevtime;
2068 $perfcheck_time=$o_prevtime;
2069 }
2070 elsif (defined($prevperf) && defined($prevperf->{'_ptime'})) {
2071 # push @prev_time, $prev_perf{ptime};
2072 $perfcheck_time=$prevperf->{'_ptime'};
2073 }
2074 else {
2075 # @prev_time=();
2076 $perfcheck_time=undef;
2077 }
2078 # numeric sort for timestamp array (this is from lowest time to highiest, i.e. to latest)
2079 # my %ptimes=();
2080 # $ptimes{$_}=$_ foreach @prev_time;
2081 # @prev_time = sort { $a <=> $b } keys(%ptimes);
2082 return $perfcheck_time;
2083 }
2084
2085 # @DESCRIPTION : Processes standard options, setting up thresholds based on options that are to be checked
2086 # @LAST CHANGED : 08-22-12 by WL
2087 # @INPUT : none
2088 # @RETURNS : nothing (future: 1 on success, 0 on error)
2089 # @PRIVACY & USE : PUBLIC, To be called after plugin finished processing its own custom options. Must be used as an object instance function
2090 sub options_finishprocessing {
2091 my $self = shift;
2092
2093 if (!exists($self->{'_called_options_finishprocessing'})) {
2094 # process previous performance data
2095 my $prevperf = $self->{'_prevPerf'};
2096 if (defined($self->{'o_prevperf'})) {
2097 if (defined($self->{'o_perf'}) || defined($self->{'o_perfvars'})) {
2098 %{$prevperf}=$self->process_perf($self->{'o_prevperf'});
2099 $self->{'_perfcheck_time'} = $self->_set_prevtime($prevperf,$self->{'o_prevtime'});
2100 }
2101 else {
2102 print "--prevperf can only be used with --perf or --perfvars options\n";
2103 if (defined($self)) { $self->usage(); }
2104 exit $ERRORS{"UNKNOWN"};
2105 }
2106 }
2107 # set thresholds
2108 $self->_options_setthresholds();
2109 # prepare data results arrays
2110 my $dataresults = $self->{'_dataresults'};
2111 my $thresholds = $self->{'_thresholds'};
2112 $dataresults->{$_} = [undef, 0, 0] foreach(@{$self->{'_allVars'}});
2113 if (defined($self->{'_perfVars'})) {
2114 foreach(@{$self->{'_perfVars'}}) {
2115 $dataresults->{$_} = [undef, 0, 0] if !exists($dataresults->{$_});
2116 $thresholds->{$_} = {} if !exists($thresholds->{$_});
2117 $thresholds->{$_}{'PERF'} = 'YES';
2118 }
2119 }
2120 # mark as having finished
2121 $self->{'_called_options_finishprocessing'}=1;
2122 }
2123 }
2124
2125 # @DESCRIPTION : Accessor function for previously saved perfdata
2126 # @LAST CHANGED : 08-22-12 by WL
2127 # @INPUT : ARG1 - varname
2128 # @RETURNS : value of that variable on previous plugin run, undef if not known
2129 # @PRIVACY & USE : PUBLIC, Must be used as an object instance function
2130 sub prev_perf {
2131 my ($self,$var) = @_;
2132 if (defined($self) && defined($self->{'_prevPerf'}{$var})) {
2133 return $self->{'_prevPerf'}{$var};
2134 }
2135 return undef;
2136 }
2137
2138 # @DESCRIPTION : Accessor function for exit status code
2139 # @LAST CHANGED : 08-21-12 by WL
2140 # @INPUT : none
2141 # @RETURNS : current expected exit status code
2142 # @PRIVACY & USE : PUBLIC, Must be used as an object instance function
2143 sub statuscode {
2144 my $self = shift;
2145 return $self->{'_statuscode'};
2146 }
2147
2148 # @DESCRIPTION : Sets plugin exist status
2149 # @LAST CHANGED : 08-21-12 by WL
2150 # @INPUT : status code string - one of "WARNING", "CRITICAL", "UNKNOWN".
2151 # @RETURNS : 0 on success, 1 if this status code is below level that plugin would exit with and as such it was not set
2152 # @PRIVACY & USE : PUBLIC, Must be used as an object instance function
2153 sub set_statuscode {
2154 my ($self,$newcode) = @_;
2155
2156 if ($newcode eq 'UNKNOWN') {
2157 $self->{'_statuscode'} = 'UNKNOWN';
2158 return 0;
2159 }
2160 if ($self->{'_statuscode'} eq 'UNKNOWN') { return 1; }
2161 elsif ($self->{'_statuscode'} eq 'CRITICAL') {
2162 if ($newcode eq 'CRITICAL') { return 0;}
2163 else { return 1; }
2164 }
2165 elsif ($self->{'_statuscode'} eq 'WARNING') {
2166 if ($newcode eq 'CRITICAL') {
2167 $self->{'_statuscode'} ='CRITICAL';
2168 return 0;
2169 }
2170 elsif ($newcode eq 'WARNING') { return 0; }
2171 else { return 1; }
2172 }
2173 elsif ($self->{'_statuscode'} eq 'OK') {
2174 if ($newcode eq 'CRITICAL' || $newcode eq 'WARNING') {
2175 $self->{'_statuscode'} = $newcode;
2176 return 0;
2177 }
2178 else { return 1; }
2179 }
2180 else {
2181 printf "SYSTEM ERROR: status code $newcode not supported";
2182 exit $ERRORS{'UNKNOWN'};
2183 }
2184 return 1; # should never get here
2185 }
2186
2187 # @DESCRIPTION : This function is called closer to end of the code after plugin retrieved data and
2188 # assigned values to variables. This function checks variables against all thresholds.
2189 # It prepares statusdata and statusinfo and exitcode.
2190 # @LAST CHANGED : 09-03-12 by WL
2191 # @INPUT : none
2192 # @RETURNS : nothing (future: 1 on success, 0 on error)
2193 # @PRIVACY & USE : PUBLIC, To be called after variables have values. Must be used as an object instance function
2194 sub main_checkvars {
2195 my $self = shift;
2196
2197 $self->options_finishprocessing() if !exists($self->{'_called_options_finshprocessing'});
2198 if (exists($self->{'_called_main_checkvars'})) { return; }
2199
2200 my $thresholds = $self->{'_thresholds'};
2201 my $dataresults = $self->{'_dataresults'};
2202 my $allVars = $self->{'_allVars'};
2203 my $datavars = $self->{'_datavars'};
2204
2205 my ($dvar,$avar,$aname,$perf_str,$chk)=(undef,undef,undef,undef,undef);
2206
2207 # main loop to check for warning & critical thresholds
2208 for (my $i=0;$i<scalar(@{$allVars});$i++) {
2209 $avar = $allVars->[$i];
2210 if (!defined($datavars->{$avar}) || scalar(@{$datavars->{$avar}})==0) {
2211 if (defined($thresholds->{$avar}{'ABSENT'})) {
2212 $self->set_statuscode($thresholds->{$avar}{'ABSENT'});
2213 }
2214 else {
2215 $self->set_statuscode("CRITICAL");
2216 }
2217 $aname = $self->out_name($avar);
2218 $self->addto_statusinfo_output($avar, "$aname data is missing");
2219 }
2220 foreach $dvar (@{$datavars->{$avar}}) {
2221 $aname = $self->out_name($dvar);
2222 if (defined($dataresults->{$dvar}[0])) {
2223 # main check
2224 if (defined($avar)) {
2225 if ($dataresults->{$dvar}[0] eq 0 && exists($thresholds->{$avar}{'ZERO'})) {
2226 $self->set_statuscode($thresholds->{$avar}{'ZERO'});
2227 $self->addto_statusinfo_output($dvar, "$aname is zero") if $self->statuscode() ne 'OK';
2228 }
2229 else {
2230 $chk=undef;
2231 if (exists($thresholds->{$avar}{'CRIT'})) {
2232 $chk = $self->check_threshold($aname,lc $dataresults->{$dvar}[0], $thresholds->{$avar}{'CRIT'});
2233 if ($chk) {
2234 $self->set_statuscode("CRITICAL");
2235 $self->addto_statusinfo_output($dvar,$chk);
2236 }
2237 }
2238 if (exists($thresholds->{$avar}{'WARN'}) && (!defined($chk) || !$chk)) {
2239 $chk = $self->check_threshold($aname,lc $dataresults->{$dvar}[0], $thresholds->{$avar}{'WARN'});
2240 if ($chk) {
2241 $self->set_statuscode("WARNING");
2242 $self->addto_statusinfo_output($dvar,$chk);
2243 }
2244 }
2245 }
2246 }
2247 # if we did not output to status line yet, do so
2248 $self->addto_statusdata_output($dvar,$aname." is ".$dataresults->{$dvar}[0]);
2249
2250 # if we were asked to output performance, prepare it but do not output until later
2251 if ((defined($self->{'o_perf'}) && defined($avar) && !exists($thresholds->{$avar}{'PERF'})) ||
2252 (exists($thresholds->{$avar}{'PERF'}) && $thresholds->{$avar}{'PERF'} eq 'YES')) {
2253 $perf_str = perf_name($aname).'='.$dataresults->{$dvar}[0];
2254 $self->set_perfdata($dvar, $perf_str, undef, "IFNOTSET"); # with undef UOM would get added
2255 $dataresults->{$dvar}[2]=0; # this would clear -1 from preset perf data, making it ready for output
2256 # below is where threshold info gets added to perfdata
2257 if ((exists($thresholds->{$avar}{'WARN'}[5]) && $thresholds->{$avar}{'WARN'}[5] ne '') ||
2258 (exists($thresholds->{$avar}{'CRIT'}[5]) && $thresholds->{$avar}{'CRIT'}[5] ne '')) {
2259 $perf_str = ';';
2260 $perf_str .= $thresholds->{$avar}{'WARN'}[5] if exists($thresholds->{$avar}{'WARN'}[5]) && $thresholds->{$avar}{'WARN'}[5] ne '';
2261 $perf_str .= ';'.$thresholds->{$avar}{'CRIT'}[5] if exists($thresholds->{$avar}{'CRIT'}[5]) && $thresholds->{$avar}{'CRIT'}[5] ne '';
2262 $self->set_perfdata($dvar, $perf_str, '', "ADD");
2263 }
2264 }
2265 }
2266 }
2267 }
2268 $self->{'_called_main_checkvars'}=1;
2269 # $statusinfo=trim($statusinfo);
2270 # $statusdata=trim($statusdata);
2271 }
2272
2273 # @DESCRIPTION : This function is at the end. It prepares PERFOUT for output collecting all perf variables data
2274 # @LAST CHANGED : 08-26-12 by WL
2275 # @INPUT : none
2276 # @RETURNS : nothing (future: 1 on success, 0 on error)
2277 # @PRIVACY & USE : PUBLIC, To be called after variables have values. Must be used as an object instance function
2278 # Calling this function direcly is optional, its automatically called on 1st call to perfdata()
2279 sub main_perfvars {
2280 my $self = shift;
2281
2282 my $dataresults = $self->{'_dataresults'};
2283 my $PERF_OK_STATUS_REGEX = $self->{'perfOKStatusRegex'};
2284 my $perfVars = $self->{'_perfVars'};
2285 my $known_vars = $self->{'knownStatusVars'};
2286 my $datavars = $self->{'_datavars'};
2287 my $avar;
2288 my $dvar;
2289
2290 $self->main_checkvars() if !exists($self->{'_called_main_checkvars'});
2291 if (exists($self->{'_called_main_perfvars'})) { return; }
2292
2293 for (my $i=0;$i<scalar(@{$perfVars});$i++) {
2294 $avar=$perfVars->[$i];
2295 if (!defined($datavars->{$avar}) || scalar(@{$datavars->{$avar}})==0) {
2296 $self->verb("Perfvar: $avar selected for PERFOUT but data not available");
2297 }
2298 else {
2299 foreach $dvar (@{$datavars->{$avar}}) {
2300 if (defined($dataresults->{$dvar}[0])) {
2301 $self->verb("Perfvar: $dvar ($avar) = ".$dataresults->{$dvar}[0]);
2302 if (!defined($known_vars->{$avar}[1]) || $known_vars->{$avar}[1] =~ /$PERF_OK_STATUS_REGEX/ ) {
2303 $self->addto_perfdata_output($dvar);
2304 }
2305 else {
2306 $self->verb(" -- not adding to perfdata because of it is '".$known_vars->{$avar}[1]."' type variable --");
2307 }
2308 }
2309 else {
2310 $self->verb("Perfvar: $avar selected for PERFOUT but data not defined");
2311 }
2312 }
2313 }
2314 }
2315 if (defined($self->{'o_prevperf'})) {
2316 $self->addto_perfdata_output('_ptime', "_ptime=".time(), "REPLACE");
2317 }
2318 foreach $dvar (keys %{$dataresults}) {
2319 if (defined($dataresults->{$dvar}[3]) && $dataresults->{$dvar}[3] ne '') {
2320 $self->verb("Perfvar (Dataresults Loop): $dvar => ".$dataresults->{$dvar}[3]);
2321 $self->addto_perfdata_output($dvar);
2322 }
2323 }
2324
2325 $self->{'_called_main_perfvars'}=1;
2326 # $perfdata = trim($perfdata);
2327 }
2328
2329 # @DESCRIPTION : This function should be called at the very very end, it returns perf data output
2330 # @LAST CHANGED : 08-22-12 by WL
2331 # @INPUT : none
2332 # @RETURNS : string of perfdata starting with "|"
2333 # @PRIVACY & USE : PUBLIC, To be called during plugin output. Must be used as an object instance function
2334 sub perfdata {
2335 my $self=shift;
2336
2337 $self->main_perfvars() if !exists($self->{'_called_main_perfvars'});
2338 my $perfdata = trim($self->{'_perfdata'});
2339 if ($perfdata ne '') {
2340 return " | " . $perfdata;
2341 }
2342 return "";
2343 }
2344
2345 # @DESCRIPTION : This function is called after data is available and calculates rate variables
2346 # based on current and previous (saved in perfdata) values.
2347 # @LAST CHANGED : 08-27-12 by WL
2348 # @INPUT : none
2349 # @RETURNS : nothing (future: 1 on success, 0 on error)
2350 # @PRIVACY & USE : PUBLIC, To be called after variables have values. Must be used as an object instance function
2351 sub calculate_ratevars {
2352 my $self = shift;
2353
2354 my $prev_perf = $self->{'_prevPerf'};
2355 my $ptime = $self->{'_perfcheck_time'};
2356 my $thresholds = $self->{'_thresholds'};
2357 my $dataresults = $self->{'_dataresults'};
2358 my $datavars = $self->{'_datavars'};
2359 my $allVars = $self->{'_allVars'};
2360
2361 my ($avar,$dvar,$nvar) = (undef,undef,undef);
2362 my $timenow=time();
2363 if (defined($self->{'o_prevperf'}) && (defined($self->{'o_perf'}) || defined($self->{'o_perfvars'}))) {
2364 for (my $i=0;$i<scalar(@{$allVars});$i++) {
2365 if ($allVars->[$i] =~ /^&(.*)/) {
2366 $avar = $1;
2367 if (defined($datavars->{$avar}) && scalar(@{$datavars->{$avar}})>0) {
2368 foreach $dvar (@{$datavars->{$avar}}) {
2369 $nvar = '&'.$dvar;
2370 # this forces perfdata output if it was not already
2371 if (defined($dataresults->{$dvar}) && $dataresults->{$dvar}[2]<1 &&
2372 (!defined($dataresults->{$dvar}[3]) || $dataresults->{$dvar}[3] eq '')) {
2373 $self->set_perfdata($dvar, perf_name($self->out_name($dvar)).'='.$dataresults->{$dvar}[0], undef, "IFNOTSET");
2374 $self->set_threshold($dvar,'PERF','YES');
2375 $self->set_threshold($dvar,'SAVED','YES'); # will replace PERF in the future
2376 }
2377 if (defined($prev_perf->{$dvar}) && defined($ptime)) {
2378 $self->add_data($nvar,
2379 sprintf("%.2f",($dataresults->{$dvar}[0]-$prev_perf->{$dvar})/($timenow-$ptime)));
2380 $self->verb("Calculating Rate of Change for $dvar ($avar) : ".$nvar."=". $self->vardata($nvar));
2381 }
2382 }
2383 }
2384 }
2385 }
2386 }
2387 }
2388
2389 }
2390 ##################################### END OF THE LIBRARY FUNCTIONS #########################################
2391
2392 # process --query options (which maybe repeated, that's why loop)
2393 sub option_query {
2394 my $nlib = shift;
2395
2396 for(my $i=0;$i<scalar(@o_querykey);$i++) {
2397 $nlib->verb("Processing query key option: $o_querykey[$i]");
2398 my @ar=split(/,/, $o_querykey[$i]);
2399 # how to query
2400 my @key_querytype = split(':', uc shift @ar);
2401 $nlib->verb("- processing query type specification: ".join(':',@key_querytype));
2402 $query[$i] = { 'query_type' => $key_querytype[0] };
2403 if ($key_querytype[0] eq 'GET' || $key_querytype[0] eq 'LLEN' ||
2404 $key_querytype[0] eq 'SLEN' || $key_querytype[0] eq 'HLEN' ||
2405 $key_querytype[0] eq 'ZLEN') {
2406 if (scalar(@key_querytype)!=1) {
2407 print "Incorrect specification. GET, LLEN, SLEN, HLEN, ZLEN do not have any arguments\n";
2408 print_usage();
2409 exit $ERRORS{"UNKNOWN"};
2410 }
2411 }
2412 elsif ($key_querytype[0] eq 'HGET' || $key_querytype[0] eq 'HEXISTS' ||
2413 $key_querytype[0] eq 'SEXISTS') {
2414 if (scalar(@key_querytype)!=2) {
2415 print "Incorrect specification of HGET, HEXISTS or SEXIST. Must include hash or set member name as an argument.\n";
2416 print_usage();
2417 exit $ERRORS{"UNKNOWN"};
2418 }
2419 $query[$i]{'element_name'} = $key_querytype[1];
2420 }
2421 elsif ($key_querytype[0] eq 'LRANGE' || $key_querytype[0] eq 'ZRANGE') {
2422 if ($key_querytype[0] eq 'ZRANGE' && scalar(@key_querytype)!=4) {
2423 print "Incorrect specification of ZRANGE. Must include type and start and end (min and max scores).\n";
2424 print_usage();
2425 exit $ERRORS{"UNKNOWN"};
2426 }
2427 elsif ($key_querytype[0] eq 'LRANGE' && (scalar(@key_querytype)<2 || scalar(@key_querytype)>4)) {
2428 print "Incorrect specification of LRANGE. Must include type and start and end range.\n";
2429 print_usage();
2430 exit $ERRORS{"UNKNOWN"};
2431 }
2432 elsif ($key_querytype[1] ne 'MAX' && $key_querytype[1] ne 'MIN' &&
2433 $key_querytype[1] ne 'AVG' && $key_querytype[1] ne 'SUM') {
2434 print "Invalid LRANGE/ZRANGE type $key_querytype[1]. This must be either MAX or MIN or AVG or SUM\n";
2435 print_usage();
2436 exit $ERRORS{"UNKNOWN"};
2437 }
2438 $query[$i]{'query_subtype'} = $key_querytype[1];
2439 $query[$i]{'query_range_start'} = $key_querytype[2] if defined($key_querytype[2]);
2440 $query[$i]{'query_range_end'} = $key_querytype[3] if defined($key_querytype[3]);
2441 }
2442 else {
2443 print "Invalid key query $key_querytype[0]. Currently supported are GET, LLEN, SLEN, HLEN, ZLEN, HGET, HEXISTS, SEXISTS, LRANGE and ZRANGE.\n";
2444 print_usage();
2445 exit $ERRORS{"UNKNOWN"};
2446 }
2447 # key to query and how to name it
2448 if (scalar(@ar)==0) {
2449 print "Invalid query specification. Missing query key name\n";
2450 print_usage();
2451 exit $ERRORS{"UNKNOWN"};
2452 }
2453 my ($key_query,$key_name) = split(':', shift @ar);
2454 $key_name = $key_query if !defined($key_name) || ! $key_name;
2455 $nlib->verb("- variable $key_name will receive data from $key_query");
2456 $query[$i]{'key_query'} = $key_query;
2457 $query[$i]{'key_name'} = $key_name;
2458 # parse thresholds and finish processing assigning values to arrays
2459 my $th = $nlib->parse_thresholds_list(join(',',@ar));
2460 if (exists($th->{'ABSENT'})) {
2461 $nlib->verb("- ".$th->{'ABSENT'}." alert will be issued if $key_query is not present");
2462 $query[$i]{'alert'} = $th->{'ABSENT'};
2463 }
2464 if (exists($th->{'WARN'})) {
2465 $nlib->verb("- warning threshold ".$th->{'WARN'}." set");
2466 $query[$i]{'warn'} = $th->{'WARN'};
2467 }
2468 if (exists($th->{'CRIT'})) {
2469 $nlib->verb("- critical threshold ".$th->{'CRIT'}." set");
2470 $query[$i]{'crit'} = $th->{'CRIT'};
2471 }
2472 $nlib->add_thresholds($key_name,$th);
2473 }
2474 }
2475
2476 # sets password, host, port and other data based on options entered
2477 sub options_setaccess {
2478 if (!defined($o_host)) { print "Please specify hostname (-H)\n"; print_usage(); exit $ERRORS{"UNKNOWN"}; }
2479 if (defined($o_pwfile) && $o_pwfile) {
2480 if ($o_password) {
2481 print "use either -x or -C to enter credentials\n"; print_usage(); exit $ERRORS{"UNKNOWN"};
2482 }
2483 open my $file, '<', $o_pwfile or die $!;
2484 while (<$file>) {
2485 # Match first non-blank line that doesn't start with a comment
2486 if (!($_ =~ /^\s*#/) && $_ =~ /\S+/) {
2487 chomp($PASSWORD = $_);
2488 last;
2489 }
2490 }
2491 close $file;
2492 print 'Password file is empty' and exit $ERRORS{"UNKNOWN"} if !$PASSWORD;
2493 }
2494 if (defined($o_password) && $o_password) {
2495 $PASSWORD = $o_password;
2496 }
2497 $HOSTNAME = $o_host if defined($o_host);
2498 $PORT = $o_port if defined($o_port);
2499 $TIMEOUT = $o_timeout if defined($o_timeout);
2500 $DATABASE = $o_database if defined($o_database);
2501 }
2502
2503 # parse command line options
2504 sub check_options {
2505 my $opt;
2506 my $nlib = shift;
2507 my %Options = ();
2508 Getopt::Long::Configure("bundling");
2509 GetOptions(\%Options,
2510 'v:s' => \$o_verb, 'verbose:s' => \$o_verb, "debug:s" => \$o_verb,
2511 'h' => \$o_help, 'help' => \$o_help,
2512 'H:s' => \$o_host, 'hostname:s' => \$o_host,
2513 'p:i' => \$o_port, 'port:i' => \$o_port,
2514 'C:s' => \$o_pwfile, 'credentials:s' => \$o_pwfile,
2515 'x:s' => \$o_password, 'password:s' => \$o_password,
2516 'D:s' => \$o_database, 'database:s' => \$o_database,
2517 't:i' => \$o_timeout, 'timeout:i' => \$o_timeout,
2518 'V' => \$o_version, 'version' => \$o_version,
2519 'a:s' => \$o_variables, 'variables:s' => \$o_variables,
2520 'c:s' => \$o_crit, 'critical:s' => \$o_crit,
2521 'w:s' => \$o_warn, 'warn:s' => \$o_warn,
2522 'f:s' => \$o_perf, 'perfparse:s' => \$o_perf,
2523 'A:s' => \$o_perfvars, 'perfvars:s' => \$o_perfvars,
2524 'T:s' => \$o_timecheck, 'response_time:s' => \$o_timecheck,
2525 'R:s' => \$o_hitrate, 'hitrate:s' => \$o_hitrate,
2526 'r:s' => \$o_repdelay, 'replication_delay:s' => \$o_repdelay,
2527 'P:s' => \$o_prevperf, 'prev_perfdata:s' => \$o_prevperf,
2528 'E:s' => \$o_prevtime, 'prev_checktime:s'=> \$o_prevtime,
2529 'm:s' => \$o_memutilization, 'memory_utilization:s' => \$o_memutilization,
2530 'M:s' => \$o_totalmemory, 'total_memory:s' => \$o_totalmemory,
2531 'q=s' => \@o_querykey, 'query=s' => \@o_querykey,
2532 'o=s' => \@o_check, 'check|option=s' => \@o_check,
2533 'rate_label:s' => \$o_ratelabel,
2534 map { ($_) } $nlib->additional_options_list()
2535 );
2536
2537 ($o_rprefix,$o_rsuffix)=split(/,/,$o_ratelabel) if defined($o_ratelabel) && $o_ratelabel ne '';
2538
2539 # Standard nagios plugin required options
2540 if (defined($o_help)) { help($nlib); exit $ERRORS{"UNKNOWN"} };
2541 if (defined($o_version)) { p_version(); exit $ERRORS{"UNKNOWN"} };
2542
2543 # now start options processing in the library
2544 $nlib->options_startprocessing(\%Options, $o_verb, $o_variables, $o_warn, $o_crit, $o_perf, $o_perfvars, $o_rprefix, $o_rsuffix);
2545
2546 # additional variables/options calculated and added by this plugin
2547 if (defined($o_timecheck) && $o_timecheck ne '') {
2548 $nlib->verb("Processing timecheck thresholds: $o_timecheck");
2549 $nlib->add_thresholds('response_time',$o_timecheck);
2550 }
2551 if (defined($o_hitrate) && $o_hitrate ne '') {
2552 $nlib->verb("Processing hitrate thresholds: $o_hitrate");
2553 $nlib->add_thresholds('hitrate',$o_hitrate);
2554 $nlib->set_threshold('hitrate','ZERO','OK') if !defined($nlib->get_threshold('hitrate','ZERO')); # except case of hitrate=0, don't remember why I added it
2555 }
2556 if (defined($o_memutilization) && $o_memutilization ne '') {
2557 $nlib->verb("Processing memory utilization thresholds: $o_memutilization");
2558 $nlib->add_thresholds('memory_utilization',$o_memutilization);
2559 }
2560 if (defined($o_totalmemory)) {
2561 if ($o_totalmemory =~ /^(\d+)B/) {
2562 $o_totalmemory = $1;
2563 }
2564 elsif ($o_totalmemory =~ /^(\d+)K/) {
2565 $o_totalmemory = $1*1024;
2566 }
2567 elsif ($o_totalmemory =~ /^(\d+)M/) {
2568 $o_totalmemory = $1*1024*1024;
2569 }
2570 elsif ($o_totalmemory =~ /^(\d+)G/) {
2571 $o_totalmemory = $1*1024*1024*1024;
2572 }
2573 elsif ($o_totalmemory !~ /^(\d+)$/) {
2574 print "Total memory value $o_totalmemory can not be interpreted\n";
2575 print_usage();
2576 exit $ERRORS{"UNKNOWN"};
2577 }
2578 }
2579 if (defined($o_repdelay) && $o_repdelay ne '') {
2580 $nlib->verb("Processing replication delay thresholds: $o_repdelay");
2581 $nlib->add_thresholds('replication_delay',$o_repdelay);
2582 }
2583
2584 # general check option, allows to specify everything, can be repeated more than once
2585 foreach $opt (@o_check) {
2586 $nlib->verb("Processing general check option: ".$opt);
2587 $nlib->add_thresholds(undef,$opt);
2588 }
2589
2590 # query option processing
2591 option_query($nlib);
2592
2593 # finish it up
2594 $nlib->options_finishprocessing();
2595 options_setaccess();
2596 }
2597
2598 # Get the alarm signal (just in case nagios screws up)
2599 $SIG{'ALRM'} = sub {
2600 $redis->quit if defined($redis);
2601 print ("ERROR: Alarm signal (Nagios time-out)\n");
2602 exit $ERRORS{"UNKNOWN"};
2603 };
2604
2605 ########## MAIN #######
2606
2607 my $nlib = Naglio->lib_init('plugin_name' => 'check_redis.pl',
2608 'plugins_authors' => 'William Leibzon',
2609 'plugin_description' => 'Redis Monitoring Plugin for Nagios',
2610 'usage_function' => \&print_usage,
2611 'enable_long_options' => 1,
2612 'enable_rate_of_change' => 1);
2613 $nlib->set_knownvars(\%KNOWN_STATUS_VARS, $PERF_OK_STATUS_REGEX);
2614
2615 check_options($nlib);
2616 $nlib->verb("check_redis.pl plugin version ".$Version);
2617
2618 # Check global timeout if plugin screws up
2619 if (defined($TIMEOUT)) {
2620 $nlib->verb("Alarm at $TIMEOUT");
2621 alarm($TIMEOUT);
2622 }
2623 else {
2624 $nlib->verb("no timeout defined : $o_timeout + 10");
2625 alarm ($o_timeout+10);
2626 }
2627
2628 # some more variables for processing of the results
2629 my $dbversion = "";
2630 my $vnam;
2631 my $vval;
2632 my %dbs=(); # database-specific info, this is almost unused right now
2633 my %slaves=();
2634 my $avar;
2635
2636 # connect using tcp and verify the port is working
2637 my $sock = new IO::Socket::INET(
2638 PeerAddr => $HOSTNAME,
2639 PeerPort => $PORT,
2640 Proto => 'tcp',
2641 );
2642 if (!$sock) {
2643 print "CRITICAL ERROR - Can not connect to '$HOSTNAME' on port $PORT\n";
2644 exit $ERRORS{'CRITICAL'};
2645 }
2646 close($sock);
2647
2648 # now do connection using Redis library
2649 my $start_time;
2650 my $dsn = $HOSTNAME.":".$PORT;
2651 $nlib->verb("connecting to $dsn");
2652 $start_time = [ Time::HiRes::gettimeofday() ] if defined($o_timecheck);
2653
2654 $redis = Redis-> new ( server => $dsn, 'debug' => (defined($o_verb))?1:0 );
2655
2656 if ($PASSWORD) {
•2657 $redis->auth($PASSWORD);
2658 }
2659 if ($DATABASE) {
2660 $redis->select($DATABASE);
2661 }
2662
2663 if (!$redis) {
2664 print "CRITICAL ERROR - Redis Library - can not connect to '$HOSTNAME' on port $PORT\n";
2665 exit $ERRORS{'CRITICAL'};
2666 }
2667
2668 if (!$redis->ping) {
2669 print "CRITICAL ERROR - Redis Library - can not ping '$HOSTNAME' on port $PORT\n";
2670 exit $ERRORS{'CRITICAL'};
2671 }
2672
2673 # This returns hashref of various statistics/info data
2674 my $stats = $redis->info();
2675
2676 # Check specified key if option -q was used
2677 for (my $i=0; $i<scalar(@query);$i++) {
2678 my $result=undef;
2679 if ($query[$i]{'query_type'} eq 'GET') {
2680 $nlib->verb("Getting redis key: ".$query[$i]{'key_query'});
2681 $result = $redis->get($query[$i]{'key_query'});
2682 }
2683 elsif ($query[$i]{'query_type'} eq 'LLEN') {
2684 $nlib->verb("Getting number of items for list with redis key: ".$query[$i]{'key_query'});
2685 $result = $redis->llen($query[$i]{'key_query'});
2686 }
2687 elsif ($query[$i]{'query_type'} eq 'HLEN') {
2688 $nlib->verb("Getting number of items for hash with redis key: ".$query[$i]{'key_query'});
2689 $result = $redis->hlen($query[$i]{'key_query'});
2690 }
2691 elsif ($query[$i]{'query_type'} eq 'SLEN') {
2692 $nlib->verb("Getting number of items for set with redis key: ".$query[$i]{'key_query'});
2693 $result = $redis->scard($query[$i]{'key_query'});
2694 }
2695 elsif ($query[$i]{'query_type'} eq 'ZLEN') {
2696 $nlib->verb("Getting number of items for sorted set with redis key: ".$query[$i]{'key_query'});
2697 $result = $redis->zcard($query[$i]{'key_query'});
2698 }
2699 elsif ($query[$i]{'query_type'} eq 'HGET') {
2700 $nlib->verb("Getting hash member ".$query[$i]{'element_name'}." with redis key: ".$query[$i]{'key_query'});
2701 $result = $redis->hget($query[$i]{'key_query'},$query[$i]{'element_name'});
2702 }
2703 elsif ($query[$i]{'query_type'} eq 'HEXISTS') {
2704 $nlib->verb("Checking if there exists hash member ".$query[$i]{'element_name'}." with redis key: ".$query[$i]{'key_query'});
2705 $result = $redis->hexists($query[$i]{'key_query'},$query[$i]{'element_name'});
2706 }
2707 elsif ($query[$i]{'query_type'} eq 'SEXISTS') {
2708 $nlib->verb("Checking if there exists set member ".$query[$i]{'element_name'}." with redis key: ".$query[$i]{'key_query'});
2709 $result = $redis->sismember($query[$i]{'key_query'},$query[$i]{'element_name'});
2710 }
2711 elsif ($query[$i]{'query_type'} eq 'LRANGE' || $query[$i]{'query_type'} eq 'ZRANGE') {
2712 my $range_start;
2713 my $range_end;
2714 if (defined($query[$i]{'query_range_start'}) && $query[$i]{'query_range_start'} ne '') {
2715 $range_start=$query[$i]{'query_range_start'};
2716 }
2717 else {
2718 $range_start=0;
2719 }
2720 if (defined($query[$i]{'query_range_end'}) && $query[$i]{'query_range_end'} ne '') {
2721 $range_end= $query[$i]{'query_range_end'};
2722 }
2723 elsif ($query[$i]{'query_type'} eq 'LRANGE') {
2724 $nlib->verb("Getting (lrange) redis key: ".$query[$i]{'key_query'});
2725 $range_end = $redis->llen($query[$i]{'key_query'})-1;
2726 }
2727 else {
2728 print "ERROR - can not do ZRANGE if you do not specify mix and max score.";
2729 exit $ERRORS{"UNKNOWN"};
2730 }
2731 my @list;
2732 if ($query[$i]{'query_type'} eq 'LRANGE') {
2733 @list = $redis->lrange($query[$i]{'key_query'}, $range_start, $range_end);
2734 }
2735 else {
2736 @list = $redis->zrange($query[$i]{'key_query'}, $range_start, $range_end);
2737 }
2738 if (scalar(@list)>0) {
2739 $result=shift @list;
2740 foreach(@list) {
2741 $result+=$_ if $query[$i]{'query_subtype'} eq 'SUM' || $query[$i]{'query_subtype'} eq 'AVG';
2742 $result=$_ if ($query[$i]{'query_subtype'} eq 'MIN' && $_ < $result) ||
2743 ($query[$i]{'query_subtype'} eq 'MAX' && $_ > $result);
2744 }
2745 $result = $result / (scalar(@list)+1) if $query[$i]{'query_subtype'} eq 'AVG';
2746 }
2747 }
2748 if (defined($result)) {
2749 $query[$i]{'result'} = $result;
2750 $nlib->add_data($query[$i]{'key_name'}, $result);
2751 $nlib->verb("Result of querying ".$query[$i]{'key_query'}." is: $result");
2752 }
2753 else {
2754 $nlib->verb("could not get results for ".$query[$i]{'key_query'});
2755 }
2756 # else {
2757 # if (exists($query[$i]{'alert'}) && $query[$i]{'alert'} ne 'OK') {
2758 # $statuscode=$query[$i]{'alert'} if $statuscode ne 'CRITICAL';
2759 # $statusinfo.=", " if $statusinfo;
2760 # $statusinfo.= "Query on ".$query[$i]{'key_query'}." did not succeed";
2761 # }
2762 # }
2763 }
2764
2765 # end redis session
2766 $redis->quit;
2767
2768 # load stats data into internal hash array
2769 my $total_keys=0;
2770 my $total_expires=0;
2771 foreach $vnam (keys %{$stats}) {
2772 $vval = $stats->{$vnam};
2773 if (defined($vval)) {
2774 $nlib->verb("Stats Line: $vnam = $vval");
2775 if (exists($KNOWN_STATUS_VARS{$vnam}) && $KNOWN_STATUS_VARS{$vnam}[1] eq 'VERSION') {
2776 $dbversion .= $vval;
2777 }
2778 elsif ($vnam =~ /^db\d+$/) {
2779 $dbs{$vnam}= {'name'=>$vnam};
2780 foreach (split(/,/,$vval)) {
2781 my ($k,$d) = split(/=/,$_);
2782 $nlib->add_data($vnam.'_'.$k,$d);
2783 $dbs{$vnam}{$k}=$d;
2784 $nlib->verb(" - stats data added: ".$vnam.'_'.$k.' = '.$d);
2785 $total_keys+=$d if $k eq 'keys' && Naglio::isnum($d);
2786 $total_expires+=$d if $k eq 'expires' && Naglio::isnum($d);
2787 }
2788 }
2789 elsif ($vnam =~ /~slave/) {
2790 # TODO TODO TODO TODO
2791 }
2792 else {
2793 $nlib->add_data($vnam, $vval);
2794 }
2795 }
2796 else {
2797 $nlib->verb("Stats Data: $vnam = NULL");
2798 }
2799 }
2800 $nlib->verb("Calculated Data: total_keys=".$total_keys);
2801 $nlib->verb("Calculated Data: total_expires=".$total_expires);
2802 $nlib->add_data('total_keys',$total_keys);
2803 $nlib->add_data('total_expires',$total_expires);
2804
2805 # Response Time
2806 if (defined($o_timecheck)) {
2807 $nlib->add_data('response_time',Time::HiRes::tv_interval($start_time));
2808 $nlib->addto_statusdata_output('response_time',sprintf("response in %.3fs",$nlib->vardata('response_time')));
2809 if (defined($o_perf)) {
2810 $nlib->set_perfdata('response_time','response_time='.$nlib->vardata('response_time'),'s');
2811 }
2812 }
2813
2814 # calculate rate variables
2815 $nlib->calculate_ratevars();
2816
2817 # Hitrate
2818 my $hitrate=0;
2819 my $hits_total=0;
2820 my $hits_hits=undef;
2821 my $hitrate_all=0;
2822 if (defined($o_hitrate) && defined($nlib->vardata('keyspace_hits')) && defined($nlib->vardata('keyspace_misses'))) {
2823 for $avar ('keyspace_hits', 'keyspace_misses') {
2824 if (defined($o_prevperf) && defined($o_perf)) {
2825 $nlib->set_perfdata($avar,$avar."=".$nlib->vardata($avar),'c');
2826 }
2827 $hits_hits = $nlib->vardata('keyspace_hits') if $avar eq 'keyspace_hits';
2828 $hits_total += $nlib->vardata($avar);
2829 }
2830 $nlib->verb("Calculating Hitrate : total=".$hits_total." hits=".$hits_hits);
2831 if (defined($hits_hits) && defined($nlib->prev_perf('keyspace_hits')) && defined($nlib->prev_perf('keyspace_misses')) && $hits_hits > $nlib->prev_perf('keyspace_hits')) {
2832 $hitrate_all = $hits_hits/$hits_total*100 if $hits_total!=0;
2833 $hits_hits -= $nlib->prev_perf('keyspace_hits');
2834 $hits_total -= $nlib->prev_perf('keyspace_misses');
2835 $hits_total -= $nlib->prev_perf('keyspace_hits');
2836 verb("Calculating Hitrate. Adjusted based on previous values. total=".$hits_total." hits=".$hits_hits);
2837 }
2838 if (defined($hits_hits)) {
2839 if ($hits_total!=0) {
2840 $hitrate= sprintf("%.4f", $hits_hits/$hits_total*100);
2841 }
2842 $nlib->add_data('hitrate',$hitrate);
2843 my $sdata .= sprintf(" hitrate is %.2f%%", $hitrate);
2844 $sdata .= sprintf(" (%.2f%% from launch)", $hitrate_all) if ($hitrate_all!=0);
2845 $nlib->addto_statusdata_output('hitrate',$sdata);
2846 if (defined($o_perf)) {
2847 $nlib->set_perfdata('hitrate',"hitrate=$hitrate",'%');
2848 }
2849 }
2850 }
2851
2852 # Replication Delay
2853 my $repl_delay=0;
2854 if (defined($o_repdelay) && defined($nlib->vardata('master_last_io_seconds_ago')) && defined($nlib->vardata('role'))) {
2855 if ($nlib->vardata('role') eq 'slave') {
2856 $repl_delay = $nlib->vardata('master_link_down_since_seconds');
2857 if (!defined($repl_delay) || $repl_delay < $nlib->vardata('master_last_io_seconds_ago')) {
2858 $repl_delay = $nlib->vardata('master_last_io_seconds_ago','s');
2859 }
2860 if (defined($repl_delay) && $repl_delay>=0) {
2861 $nlib->add_data('replication_delay',$repl_delay);
2862 $nlib->addto_statusdata_output('replication_delay',sprintf("replication_delay is %d", $nlib->vardata('replication_delay')));
2863 if (defined($o_perf)) {
2864 $nlib->set_perfdata('replication_delay',sprintf("replication_delay=%d", $nlib->vardata('replication_delay')));
2865 }
2866 }
2867 }
2868 }
2869
2870 # Memory Use Utilization
2871 if (defined($o_memutilization) && defined($nlib->vardata('used_memory_rss'))) {
2872 if (defined($o_totalmemory)) {
2873 $nlib->add_data('memory_utilization',$nlib->vardata('used_memory_rss')/$o_totalmemory*100);
2874 $nlib->verb('memory utilization % : '.$nlib->vardata('memory_utilization').' = '.$nlib->vardata('used_memory_rss').' (used_memory_rss) / '.$o_totalmemory.' * 100');
2875 }
2876 elsif ($o_memutilization ne '') {
2877 print "ERROR: Can not calculate memory utilization if you do not specify total memory on a system (-M option)\n";
2878 print_usage();
2879 exit $ERRORS{"UNKNOWN"};
2880 }
2881 if (defined($o_perf) && defined($nlib->vardata('memory_utilization'))) {
2882 $nlib->set_perfdata('memory_utilization',sprintf(" memory_utilization=%.4f", $nlib->vardata('memory_utilization')),'%');
2883 }
2884 if (defined($nlib->vardata('used_memory_human')) && defined($nlib->vardata('used_memory_peak_human'))) {
2885 my $sdata="memory use is ".$nlib->vardata('used_memory_human')." (";
2886 $sdata.='peak '.$nlib->vardata('used_memory_peak_human');
2887 if (defined($nlib->vardata('memory_utilization'))) {
2888 $sdata.= sprintf(", %.2f%% of max", $nlib->vardata('memory_utilization'));
2889 }
2890 if (defined($nlib->vardata('mem_fragmentation_ratio'))) {
2891 $sdata.=", fragmentation ".$nlib->vardata('mem_fragmentation_ratio').'%';
2892 }
2893 $sdata.=")";
2894 $nlib->addto_statusdata_output('memory_utilization',$sdata);
2895 }
2896 }
2897
2898 # Check thresholds in all variables and prepare status and performance data for output
2899 $nlib->main_checkvars();
2900 $nlib->main_perfvars();
2901
2902 # now output the results
2903 print $nlib->statuscode() . ': '.$nlib->statusinfo();
2904 print " - " if $nlib->statusinfo();
2905 print "REDIS " . $dbversion . ' on ' . $HOSTNAME. ':'. $PORT;
2906 print ' has '.scalar(keys %dbs).' databases ('.join(',',keys(%dbs)).')';
2907 print " with $total_keys keys" if $total_keys > 0;
2908 print ', up '.$nlib->uptime_info($nlib->vardata('uptime_in_seconds')) if defined($nlib->vardata('uptime_in_seconds'));
2909 print " - " . $nlib->statusdata() if $nlib->statusdata();
2910 print $nlib->perfdata();
2911 print "\n";
2912
2913 # end exit
2914 exit $ERRORS{$nlib->statuscode()};