Improving output when swap space has zero size
[monitoring-plugins.git] / plugins / check_swap.c
blob25e0bacd81960c092c488d2412ab65bc002fa95e
1 /*****************************************************************************
2 *
3 * Monitoring check_swap plugin
4 *
5 * License: GPL
6 * Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net)
7 * Copyright (c) 2000-2007 Monitoring Plugins Development Team
8 *
9 * Description:
11 * This file contains the check_swap plugin
14 * This program is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <http://www.gnu.org/licenses/>.
28 *****************************************************************************/
30 const char *progname = "check_swap";
31 const char *copyright = "2000-2007";
32 const char *email = "devel@monitoring-plugins.org";
34 #include "common.h"
35 #include "popen.h"
36 #include "utils.h"
38 #ifdef HAVE_DECL_SWAPCTL
39 # ifdef HAVE_SYS_PARAM_H
40 # include <sys/param.h>
41 # endif
42 # ifdef HAVE_SYS_SWAP_H
43 # include <sys/swap.h>
44 # endif
45 # ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
47 # endif
48 #endif
50 #ifndef SWAP_CONVERSION
51 # define SWAP_CONVERSION 1
52 #endif
54 int check_swap (int usp, float free_swap_mb);
55 int process_arguments (int argc, char **argv);
56 int validate_arguments (void);
57 void print_usage (void);
58 void print_help (void);
60 int warn_percent = 0;
61 int crit_percent = 0;
62 float warn_size_bytes = 0;
63 float crit_size_bytes = 0;
64 int verbose;
65 int allswaps;
66 int no_swap_state = STATE_CRITICAL;
68 int
69 main (int argc, char **argv)
71 int percent_used, percent;
72 float total_swap_mb = 0, used_swap_mb = 0, free_swap_mb = 0;
73 float dsktotal_mb = 0, dskused_mb = 0, dskfree_mb = 0, tmp_mb = 0;
74 int result = STATE_UNKNOWN;
75 char input_buffer[MAX_INPUT_BUFFER];
76 #ifdef HAVE_PROC_MEMINFO
77 FILE *fp;
78 #else
79 int conv_factor = SWAP_CONVERSION;
80 # ifdef HAVE_SWAP
81 char *temp_buffer;
82 char *swap_command;
83 char *swap_format;
84 # else
85 # ifdef HAVE_DECL_SWAPCTL
86 int i=0, nswaps=0, swapctl_res=0;
87 # ifdef CHECK_SWAP_SWAPCTL_SVR4
88 swaptbl_t *tbl=NULL;
89 swapent_t *ent=NULL;
90 # else
91 # ifdef CHECK_SWAP_SWAPCTL_BSD
92 struct swapent *ent;
93 # endif /* CHECK_SWAP_SWAPCTL_BSD */
94 # endif /* CHECK_SWAP_SWAPCTL_SVR4 */
95 # endif /* HAVE_DECL_SWAPCTL */
96 # endif
97 #endif
98 char str[32];
99 char *status;
101 setlocale (LC_ALL, "");
102 bindtextdomain (PACKAGE, LOCALEDIR);
103 textdomain (PACKAGE);
105 status = strdup ("");
107 /* Parse extra opts if any */
108 argv=np_extra_opts (&argc, argv, progname);
110 if (process_arguments (argc, argv) == ERROR)
111 usage4 (_("Could not parse arguments"));
113 #ifdef HAVE_PROC_MEMINFO
114 if (verbose >= 3) {
115 printf("Reading PROC_MEMINFO at %s\n", PROC_MEMINFO);
117 fp = fopen (PROC_MEMINFO, "r");
118 while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
119 if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %f %f %f", &dsktotal_mb, &dskused_mb, &dskfree_mb) == 3) {
120 dsktotal_mb = dsktotal_mb / 1048576; /* Apply conversion */
121 dskused_mb = dskused_mb / 1048576;
122 dskfree_mb = dskfree_mb / 1048576;
123 total_swap_mb += dsktotal_mb;
124 used_swap_mb += dskused_mb;
125 free_swap_mb += dskfree_mb;
126 if (allswaps) {
127 if (dsktotal_mb == 0)
128 percent=100.0;
129 else
130 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
131 result = max_state (result, check_swap (percent, dskfree_mb));
132 if (verbose)
133 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
136 else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFre]%*[:] %f %*[k]%*[B]", str, &tmp_mb)) {
137 if (verbose >= 3) {
138 printf("Got %s with %f\n", str, tmp_mb);
140 /* I think this part is always in Kb, so convert to mb */
141 if (strcmp ("Total", str) == 0) {
142 dsktotal_mb = tmp_mb / 1024;
144 else if (strcmp ("Free", str) == 0) {
145 dskfree_mb = tmp_mb / 1024;
149 fclose(fp);
150 dskused_mb = dsktotal_mb - dskfree_mb;
151 total_swap_mb = dsktotal_mb;
152 used_swap_mb = dskused_mb;
153 free_swap_mb = dskfree_mb;
154 #else
155 # ifdef HAVE_SWAP
156 xasprintf(&swap_command, "%s", SWAP_COMMAND);
157 xasprintf(&swap_format, "%s", SWAP_FORMAT);
159 /* These override the command used if a summary (and thus ! allswaps) is required */
160 /* The summary flag returns more accurate information about swap usage on these OSes */
161 # ifdef _AIX
162 if (!allswaps) {
163 xasprintf(&swap_command, "%s", "/usr/sbin/lsps -s");
164 xasprintf(&swap_format, "%s", "%f%*s %f");
165 conv_factor = 1;
167 # endif
169 if (verbose >= 2)
170 printf (_("Command: %s\n"), swap_command);
171 if (verbose >= 3)
172 printf (_("Format: %s\n"), swap_format);
174 child_process = spopen (swap_command);
175 if (child_process == NULL) {
176 printf (_("Could not open pipe: %s\n"), swap_command);
177 return STATE_UNKNOWN;
180 child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
181 if (child_stderr == NULL)
182 printf (_("Could not open stderr for %s\n"), swap_command);
184 sprintf (str, "%s", "");
185 /* read 1st line */
186 fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process);
187 if (strcmp (swap_format, "") == 0) {
188 temp_buffer = strtok (input_buffer, " \n");
189 while (temp_buffer) {
190 if (strstr (temp_buffer, "blocks"))
191 sprintf (str, "%s %s", str, "%f");
192 else if (strstr (temp_buffer, "dskfree"))
193 sprintf (str, "%s %s", str, "%f");
194 else
195 sprintf (str, "%s %s", str, "%*s");
196 temp_buffer = strtok (NULL, " \n");
200 /* If different swap command is used for summary switch, need to read format differently */
201 # ifdef _AIX
202 if (!allswaps) {
203 fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process); /* Ignore first line */
204 sscanf (input_buffer, swap_format, &total_swap_mb, &used_swap_mb);
205 free_swap_mb = total_swap_mb * (100 - used_swap_mb) /100;
206 used_swap_mb = total_swap_mb - free_swap_mb;
207 if (verbose >= 3)
208 printf (_("total=%.0f, used=%.0f, free=%.0f\n"), total_swap_mb, used_swap_mb, free_swap_mb);
209 } else {
210 # endif
211 while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
212 sscanf (input_buffer, swap_format, &dsktotal_mb, &dskfree_mb);
214 dsktotal_mb = dsktotal_mb / conv_factor;
215 /* AIX lists percent used, so this converts to dskfree in MBs */
216 # ifdef _AIX
217 dskfree_mb = dsktotal_mb * (100 - dskfree_mb) / 100;
218 # else
219 dskfree_mb = dskfree_mb / conv_factor;
220 # endif
221 if (verbose >= 3)
222 printf (_("total=%.0f, free=%.0f\n"), dsktotal_mb, dskfree_mb);
224 dskused_mb = dsktotal_mb - dskfree_mb;
225 total_swap_mb += dsktotal_mb;
226 used_swap_mb += dskused_mb;
227 free_swap_mb += dskfree_mb;
228 if (allswaps) {
229 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
230 result = max_state (result, check_swap (percent, dskfree_mb));
231 if (verbose)
232 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
235 # ifdef _AIX
237 # endif
239 /* If we get anything on STDERR, at least set warning */
240 while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr))
241 result = max_state (result, STATE_WARNING);
243 /* close stderr */
244 (void) fclose (child_stderr);
246 /* close the pipe */
247 if (spclose (child_process))
248 result = max_state (result, STATE_WARNING);
249 # else
250 # ifdef CHECK_SWAP_SWAPCTL_SVR4
252 /* get the number of active swap devices */
253 if((nswaps=swapctl(SC_GETNSWP, NULL))== -1)
254 die(STATE_UNKNOWN, _("Error getting swap devices\n") );
256 if(nswaps == 0)
257 die(STATE_OK, _("SWAP OK: No swap devices defined\n"));
259 if(verbose >= 3)
260 printf("Found %d swap device(s)\n", nswaps);
262 /* initialize swap table + entries */
263 tbl=(swaptbl_t*)malloc(sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));
265 if(tbl==NULL)
266 die(STATE_UNKNOWN, _("malloc() failed!\n"));
268 memset(tbl, 0, sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));
269 tbl->swt_n=nswaps;
270 for(i=0;i<nswaps;i++){
271 if((tbl->swt_ent[i].ste_path=(char*)malloc(sizeof(char)*MAXPATHLEN)) == NULL)
272 die(STATE_UNKNOWN, _("malloc() failed!\n"));
275 /* and now, tally 'em up */
276 swapctl_res=swapctl(SC_LIST, tbl);
277 if(swapctl_res < 0){
278 perror(_("swapctl failed: "));
279 die(STATE_UNKNOWN, _("Error in swapctl call\n"));
282 for(i=0;i<nswaps;i++){
283 dsktotal_mb = (float) tbl->swt_ent[i].ste_pages / SWAP_CONVERSION;
284 dskfree_mb = (float) tbl->swt_ent[i].ste_free / SWAP_CONVERSION;
285 dskused_mb = ( dsktotal_mb - dskfree_mb );
287 if (verbose >= 3)
288 printf ("dsktotal_mb=%.0f dskfree_mb=%.0f dskused_mb=%.0f\n", dsktotal_mb, dskfree_mb, dskused_mb);
290 if(allswaps && dsktotal_mb > 0){
291 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
292 result = max_state (result, check_swap (percent, dskfree_mb));
293 if (verbose) {
294 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
298 total_swap_mb += dsktotal_mb;
299 free_swap_mb += dskfree_mb;
300 used_swap_mb += dskused_mb;
303 /* and clean up after ourselves */
304 for(i=0;i<nswaps;i++){
305 free(tbl->swt_ent[i].ste_path);
307 free(tbl);
308 # else
309 # ifdef CHECK_SWAP_SWAPCTL_BSD
311 /* get the number of active swap devices */
312 nswaps=swapctl(SWAP_NSWAP, NULL, 0);
314 /* initialize swap table + entries */
315 ent=(struct swapent*)malloc(sizeof(struct swapent)*nswaps);
317 /* and now, tally 'em up */
318 swapctl_res=swapctl(SWAP_STATS, ent, nswaps);
319 if(swapctl_res < 0){
320 perror(_("swapctl failed: "));
321 die(STATE_UNKNOWN, _("Error in swapctl call\n"));
324 for(i=0;i<nswaps;i++){
325 dsktotal_mb = (float) ent[i].se_nblks / conv_factor;
326 dskused_mb = (float) ent[i].se_inuse / conv_factor;
327 dskfree_mb = ( dsktotal_mb - dskused_mb );
329 if(allswaps && dsktotal_mb > 0){
330 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
331 result = max_state (result, check_swap (percent, dskfree_mb));
332 if (verbose) {
333 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
337 total_swap_mb += dsktotal_mb;
338 free_swap_mb += dskfree_mb;
339 used_swap_mb += dskused_mb;
342 /* and clean up after ourselves */
343 free(ent);
345 # endif /* CHECK_SWAP_SWAPCTL_BSD */
346 # endif /* CHECK_SWAP_SWAPCTL_SVR4 */
347 # endif /* HAVE_SWAP */
348 #endif /* HAVE_PROC_MEMINFO */
350 /* if total_swap_mb == 0, let's not divide by 0 */
351 if(total_swap_mb) {
352 percent_used = 100 * ((double) used_swap_mb) / ((double) total_swap_mb);
353 } else {
354 percent_used = 100;
355 status = "- Swap is either disabled, not present, or of zero size. ";
358 result = max_state (result, check_swap (percent_used, free_swap_mb));
359 printf (_("SWAP %s - %d%% free (%d MB out of %d MB) %s|"),
360 state_text (result),
361 (100 - percent_used), (int) free_swap_mb, (int) total_swap_mb, status);
363 puts (perfdata ("swap", (long) free_swap_mb, "MB",
364 TRUE, (long) max (warn_size_bytes/(1024 * 1024), warn_percent/100.0*total_swap_mb),
365 TRUE, (long) max (crit_size_bytes/(1024 * 1024), crit_percent/100.0*total_swap_mb),
366 TRUE, 0,
367 TRUE, (long) total_swap_mb));
369 return result;
375 check_swap (int usp, float free_swap_mb)
378 if (!free_swap_mb) return no_swap_state;
380 int result = STATE_UNKNOWN;
381 float free_swap = free_swap_mb * (1024 * 1024); /* Convert back to bytes as warn and crit specified in bytes */
382 if (usp >= 0 && crit_percent != 0 && usp >= (100.0 - crit_percent))
383 result = STATE_CRITICAL;
384 else if (crit_size_bytes > 0 && free_swap <= crit_size_bytes)
385 result = STATE_CRITICAL;
386 else if (usp >= 0 && warn_percent != 0 && usp >= (100.0 - warn_percent))
387 result = STATE_WARNING;
388 else if (warn_size_bytes > 0 && free_swap <= warn_size_bytes)
389 result = STATE_WARNING;
390 else if (usp >= 0.0)
391 result = STATE_OK;
392 return result;
397 /* process command-line arguments */
399 process_arguments (int argc, char **argv)
401 int c = 0; /* option character */
403 int option = 0;
404 static struct option longopts[] = {
405 {"warning", required_argument, 0, 'w'},
406 {"critical", required_argument, 0, 'c'},
407 {"allswaps", no_argument, 0, 'a'},
408 {"no-swap", required_argument, 0, 'n'},
409 {"verbose", no_argument, 0, 'v'},
410 {"version", no_argument, 0, 'V'},
411 {"help", no_argument, 0, 'h'},
412 {0, 0, 0, 0}
415 if (argc < 2)
416 return ERROR;
418 while (1) {
419 c = getopt_long (argc, argv, "+?Vvhac:w:n:", longopts, &option);
421 if (c == -1 || c == EOF)
422 break;
424 switch (c) {
425 case 'w': /* warning size threshold */
426 if (is_intnonneg (optarg)) {
427 warn_size_bytes = (float) atoi (optarg);
428 break;
430 else if (strstr (optarg, ",") &&
431 strstr (optarg, "%") &&
432 sscanf (optarg, "%f,%d%%", &warn_size_bytes, &warn_percent) == 2) {
433 warn_size_bytes = floorf(warn_size_bytes);
434 break;
436 else if (strstr (optarg, "%") &&
437 sscanf (optarg, "%d%%", &warn_percent) == 1) {
438 break;
440 else {
441 usage4 (_("Warning threshold must be integer or percentage!"));
443 case 'c': /* critical size threshold */
444 if (is_intnonneg (optarg)) {
445 crit_size_bytes = (float) atoi (optarg);
446 break;
448 else if (strstr (optarg, ",") &&
449 strstr (optarg, "%") &&
450 sscanf (optarg, "%f,%d%%", &crit_size_bytes, &crit_percent) == 2) {
451 crit_size_bytes = floorf(crit_size_bytes);
452 break;
454 else if (strstr (optarg, "%") &&
455 sscanf (optarg, "%d%%", &crit_percent) == 1) {
456 break;
458 else {
459 usage4 (_("Critical threshold must be integer or percentage!"));
461 case 'a': /* all swap */
462 allswaps = TRUE;
463 break;
464 case 'n':
465 if ((no_swap_state = mp_translate_state(optarg)) == ERROR) {
466 usage4 (_("no-swap result must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3)."));
468 case 'v': /* verbose */
469 verbose++;
470 break;
471 case 'V': /* version */
472 print_revision (progname, NP_VERSION);
473 exit (STATE_OK);
474 case 'h': /* help */
475 print_help ();
476 exit (STATE_OK);
477 case '?': /* error */
478 usage5 ();
482 c = optind;
483 if (c == argc)
484 return validate_arguments ();
485 if (warn_percent == 0 && is_intnonneg (argv[c]))
486 warn_percent = atoi (argv[c++]);
488 if (c == argc)
489 return validate_arguments ();
490 if (crit_percent == 0 && is_intnonneg (argv[c]))
491 crit_percent = atoi (argv[c++]);
493 if (c == argc)
494 return validate_arguments ();
495 if (warn_size_bytes == 0 && is_intnonneg (argv[c]))
496 warn_size_bytes = (float) atoi (argv[c++]);
498 if (c == argc)
499 return validate_arguments ();
500 if (crit_size_bytes == 0 && is_intnonneg (argv[c]))
501 crit_size_bytes = (float) atoi (argv[c++]);
503 return validate_arguments ();
509 validate_arguments (void)
511 if (warn_percent == 0 && crit_percent == 0 && warn_size_bytes == 0
512 && crit_size_bytes == 0) {
513 return ERROR;
515 else if (warn_percent < crit_percent) {
516 usage4
517 (_("Warning percentage should be more than critical percentage"));
519 else if (warn_size_bytes < crit_size_bytes) {
520 usage4
521 (_("Warning free space should be more than critical free space"));
523 return OK;
528 void
529 print_help (void)
531 print_revision (progname, NP_VERSION);
533 printf (_(COPYRIGHT), copyright, email);
535 printf ("%s\n", _("Check swap space on local machine."));
537 printf ("\n\n");
539 print_usage ();
541 printf (UT_HELP_VRSN);
542 printf (UT_EXTRA_OPTS);
544 printf (" %s\n", "-w, --warning=INTEGER");
545 printf (" %s\n", _("Exit with WARNING status if less than INTEGER bytes of swap space are free"));
546 printf (" %s\n", "-w, --warning=PERCENT%%");
547 printf (" %s\n", _("Exit with WARNING status if less than PERCENT of swap space is free"));
548 printf (" %s\n", "-c, --critical=INTEGER");
549 printf (" %s\n", _("Exit with CRITICAL status if less than INTEGER bytes of swap space are free"));
550 printf (" %s\n", "-c, --critical=PERCENT%%");
551 printf (" %s\n", _("Exit with CRITICAL status if less than PERCENT of swap space is free"));
552 printf (" %s\n", "-a, --allswaps");
553 printf (" %s\n", _("Conduct comparisons for all swap partitions, one by one"));
554 printf (" %s\n", "-n, --no-swap=<ok|warning|critical|unknown>");
555 printf (" %s %s\n", _("Resulting state when there is no swap regardless of thresholds. Default:"), state_text(no_swap_state));
556 printf (UT_VERBOSE);
558 printf ("\n");
559 printf ("%s\n", _("Notes:"));
560 printf (" %s\n", _("Both INTEGER and PERCENT thresholds can be specified, they are all checked."));
561 printf (" %s\n", _("On AIX, if -a is specified, uses lsps -a, otherwise uses lsps -s."));
563 printf (UT_SUPPORT);
568 void
569 print_usage (void)
571 printf ("%s\n", _("Usage:"));
572 printf (" %s [-av] -w <percent_free>%% -c <percent_free>%%\n",progname);
573 printf (" -w <bytes_free> -c <bytes_free> [-n <state>]\n");