Code

Don't try to print `optarg' (which will be a NULL pointer) if an unknown
[nagiosplug.git] / plugins / check_swap.c
1 /******************************************************************************
2 *
3 * Nagios check_disk plugin
4 *
5 * License: GPL
6 * Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net)
7 * Copyright (c) 2000-2006 nagios-plugins team
8 *
9 * Last Modified: $Date$
10 *
11 * Description:
12 *
13 * This file contains the check_disk plugin
14 *
15 * License Information:
16 *
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
21 *
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 * GNU General Public License for more details.
26 *
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
30 *
31 * $Id$
32 *
33 *****************************************************************************/
35 const char *progname = "check_swap";
36 const char *revision = "$Revision$";
37 const char *copyright = "2000-2006";
38 const char *email = "nagiosplug-devel@lists.sourceforge.net";
40 #include "common.h"
41 #include "popen.h"
42 #include "utils.h"
44 #ifdef HAVE_DECL_SWAPCTL
45 # ifdef HAVE_SYS_SWAP_H
46 #  include <sys/swap.h>
47 # endif
48 # ifdef HAVE_SYS_STAT_H
49 #  include <sys/stat.h>
50 # endif
51 # ifdef HAVE_SYS_PARAM_H
52 #  include <sys/param.h>
53 # endif
54 #endif
56 #ifndef SWAP_CONVERSION
57 # define SWAP_CONVERSION 1
58 #endif
60 int check_swap (int usp, float free_swap_mb);
61 int process_arguments (int argc, char **argv);
62 int validate_arguments (void);
63 void print_usage (void);
64 void print_help (void);
66 int warn_percent = 0;
67 int crit_percent = 0;
68 float warn_size_bytes = 0;
69 float crit_size_bytes= 0;
70 int verbose;
71 int allswaps;
73 int
74 main (int argc, char **argv)
75 {
76         int percent_used, percent;
77         float total_swap_mb = 0, used_swap_mb = 0, free_swap_mb = 0;
78         float dsktotal_mb = 0, dskused_mb = 0, dskfree_mb = 0, tmp_mb = 0;
79         int result = STATE_UNKNOWN;
80         char input_buffer[MAX_INPUT_BUFFER];
81 #ifdef HAVE_PROC_MEMINFO
82         FILE *fp;
83 #else
84         int conv_factor = SWAP_CONVERSION;
85 # ifdef HAVE_SWAP
86         char *temp_buffer;
87         char *swap_command;
88         char *swap_format;
89 # else
90 #  ifdef HAVE_DECL_SWAPCTL
91         int i=0, nswaps=0, swapctl_res=0;
92 #   ifdef CHECK_SWAP_SWAPCTL_SVR4
93         swaptbl_t *tbl=NULL;
94         swapent_t *ent=NULL;
95 #   else
96 #    ifdef CHECK_SWAP_SWAPCTL_BSD
97         struct swapent *ent;
98 #    endif /* CHECK_SWAP_SWAPCTL_BSD */
99 #   endif /* CHECK_SWAP_SWAPCTL_SVR4 */
100 #  endif /* HAVE_DECL_SWAPCTL */
101 # endif
102 #endif
103         char str[32];
104         char *status;
106         setlocale (LC_ALL, "");
107         bindtextdomain (PACKAGE, LOCALEDIR);
108         textdomain (PACKAGE);
110         status = strdup ("");
112         if (process_arguments (argc, argv) == ERROR)
113                 usage4 (_("Could not parse arguments"));
115 #ifdef HAVE_PROC_MEMINFO
116         if (verbose >= 3) {
117                 printf("Reading PROC_MEMINFO at %s\n", PROC_MEMINFO);
118         }
119         fp = fopen (PROC_MEMINFO, "r");
120         while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
121                 if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %f %f %f", &dsktotal_mb, &dskused_mb, &dskfree_mb) == 3) {
122                         dsktotal_mb = dsktotal_mb / 1048576;    /* Apply conversion */
123                         dskused_mb = dskused_mb / 1048576;
124                         dskfree_mb = dskfree_mb / 1048576;
125                         total_swap_mb += dsktotal_mb;
126                         used_swap_mb += dskused_mb;
127                         free_swap_mb += dskfree_mb;
128                         if (allswaps) {
129                                 if (dsktotal_mb == 0)
130                                         percent=100.0;
131                                 else
132                                         percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
133                                 result = max_state (result, check_swap (percent, dskfree_mb));
134                                 if (verbose)
135                                         asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
136                         }
137                 }
138                 else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFre]%*[:] %f %*[k]%*[B]", str, &tmp_mb)) {
139                         if (verbose >= 3) {
140                                 printf("Got %s with %f\n", str, tmp_mb);
141                         }
142                         /* I think this part is always in Kb, so convert to mb */
143                         if (strcmp ("Total", str) == 0) {
144                                 dsktotal_mb = tmp_mb / 1024;
145                         }
146                         else if (strcmp ("Free", str) == 0) {
147                                 dskfree_mb = tmp_mb / 1024;
148                         }
149                 }
150         }
151         fclose(fp);
152         dskused_mb = dsktotal_mb - dskfree_mb;
153         total_swap_mb = dsktotal_mb;
154         used_swap_mb = dskused_mb;
155         free_swap_mb = dskfree_mb;
156 #else
157 # ifdef HAVE_SWAP
158         asprintf(&swap_command, "%s", SWAP_COMMAND);
159         asprintf(&swap_format, "%s", SWAP_FORMAT);
161 /* These override the command used if a summary (and thus ! allswaps) is required */
162 /* The summary flag returns more accurate information about swap usage on these OSes */
163 #  ifdef _AIX
164         if (!allswaps) {
165                 asprintf(&swap_command, "%s", "/usr/sbin/lsps -s");
166                 asprintf(&swap_format, "%s", "%f%*s %f");
167                 conv_factor = 1;
168         }
169 #  endif
171         if (verbose >= 2)
172                 printf (_("Command: %s\n"), swap_command);
173         if (verbose >= 3)
174                 printf (_("Format: %s\n"), swap_format);
176         child_process = spopen (swap_command);
177         if (child_process == NULL) {
178                 printf (_("Could not open pipe: %s\n"), swap_command);
179                 return STATE_UNKNOWN;
180         }
182         child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
183         if (child_stderr == NULL)
184                 printf (_("Could not open stderr for %s\n"), swap_command);
186         sprintf (str, "%s", "");
187         /* read 1st line */
188         fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process);
189         if (strcmp (swap_format, "") == 0) {
190                 temp_buffer = strtok (input_buffer, " \n");
191                 while (temp_buffer) {
192                         if (strstr (temp_buffer, "blocks"))
193                                 sprintf (str, "%s %s", str, "%f");
194                         else if (strstr (temp_buffer, "dskfree"))
195                                 sprintf (str, "%s %s", str, "%f");
196                         else
197                                 sprintf (str, "%s %s", str, "%*s");
198                         temp_buffer = strtok (NULL, " \n");
199                 }
200         }
202 /* If different swap command is used for summary switch, need to read format differently */
203 #  ifdef _AIX
204         if (!allswaps) {
205                 fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process);       /* Ignore first line */
206                 sscanf (input_buffer, swap_format, &total_swap_mb, &used_swap_mb);
207                 free_swap_mb = total_swap_mb * (100 - used_swap_mb) /100;
208                 used_swap_mb = total_swap_mb - free_swap_mb;
209                 if (verbose >= 3)
210                         printf (_("total=%.0f, used=%.0f, free=%.0f\n"), total_swap_mb, used_swap_mb, free_swap_mb);
211         } else {
212 #  endif
213                 while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
214                         sscanf (input_buffer, swap_format, &dsktotal_mb, &dskfree_mb);
216                         dsktotal_mb = dsktotal_mb / conv_factor;
217                         /* AIX lists percent used, so this converts to dskfree in MBs */
218 #  ifdef _AIX
219                         dskfree_mb = dsktotal_mb * (100 - dskfree_mb) / 100;
220 #  else
221                         dskfree_mb = dskfree_mb / conv_factor;
222 #  endif
223                         if (verbose >= 3)
224                                 printf (_("total=%.0f, free=%.0f\n"), dsktotal_mb, dskfree_mb);
226                         dskused_mb = dsktotal_mb - dskfree_mb;
227                         total_swap_mb += dsktotal_mb;
228                         used_swap_mb += dskused_mb;
229                         free_swap_mb += dskfree_mb;
230                         if (allswaps) {
231                                 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
232                                 result = max_state (result, check_swap (percent, dskfree_mb));
233                                 if (verbose)
234                                         asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
235                         }
236                 }
237 #  ifdef _AIX
238         }
239 #  endif
241         /* If we get anything on STDERR, at least set warning */
242         while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr))
243                 result = max_state (result, STATE_WARNING);
245         /* close stderr */
246         (void) fclose (child_stderr);
248         /* close the pipe */
249         if (spclose (child_process))
250                 result = max_state (result, STATE_WARNING);
251 # else
252 #  ifdef CHECK_SWAP_SWAPCTL_SVR4
254         /* get the number of active swap devices */
255         if((nswaps=swapctl(SC_GETNSWP, NULL))== -1)
256                 die(STATE_UNKNOWN, _("Error getting swap devices\n") );
258         if(nswaps == 0)
259                 die(STATE_OK, _("SWAP OK: No swap devices defined\n"));
261         if(verbose >= 3)
262                 printf("Found %d swap device(s)\n", nswaps);
264         /* initialize swap table + entries */
265         tbl=(swaptbl_t*)malloc(sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));
267         if(tbl==NULL)
268                 die(STATE_UNKNOWN, _("malloc() failed!\n"));
270         memset(tbl, 0, sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));
271         tbl->swt_n=nswaps;
272         for(i=0;i<nswaps;i++){
273                 if((tbl->swt_ent[i].ste_path=(char*)malloc(sizeof(char)*MAXPATHLEN)) == NULL)
274                         die(STATE_UNKNOWN, _("malloc() failed!\n"));
275         }
277         /* and now, tally 'em up */
278         swapctl_res=swapctl(SC_LIST, tbl);
279         if(swapctl_res < 0){
280                 perror(_("swapctl failed: "));
281                 die(STATE_UNKNOWN, _("Error in swapctl call\n"));
282         }
284         for(i=0;i<nswaps;i++){
285                 dsktotal_mb = (float) tbl->swt_ent[i].ste_pages / SWAP_CONVERSION;
286                 dskfree_mb = (float) tbl->swt_ent[i].ste_free /  SWAP_CONVERSION;
287                 dskused_mb = ( dsktotal_mb - dskfree_mb );
289                 if (verbose >= 3)
290                         printf ("dsktotal_mb=%.0f dskfree_mb=%.0f dskused_mb=%.0f\n", dsktotal_mb, dskfree_mb, dskused_mb);
292                 if(allswaps && dsktotal_mb > 0){
293                         percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
294                         result = max_state (result, check_swap (percent, dskfree_mb));
295                         if (verbose) {
296                                 asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
297                         }
298                 }
300                 total_swap_mb += dsktotal_mb;
301                 free_swap_mb += dskfree_mb;
302                 used_swap_mb += dskused_mb;
303         }
305         /* and clean up after ourselves */
306         for(i=0;i<nswaps;i++){
307                 free(tbl->swt_ent[i].ste_path);
308         }
309         free(tbl);
310 #  else
311 #   ifdef CHECK_SWAP_SWAPCTL_BSD
313         /* get the number of active swap devices */
314         nswaps=swapctl(SWAP_NSWAP, NULL, 0);
316         /* initialize swap table + entries */
317         ent=(struct swapent*)malloc(sizeof(struct swapent)*nswaps);
319         /* and now, tally 'em up */
320         swapctl_res=swapctl(SWAP_STATS, ent, nswaps);
321         if(swapctl_res < 0){
322                 perror(_("swapctl failed: "));
323                 die(STATE_UNKNOWN, _("Error in swapctl call\n"));
324         }
326         for(i=0;i<nswaps;i++){
327                 dsktotal_mb = (float) ent[i].se_nblks / conv_factor;
328                 dskused_mb = (float) ent[i].se_inuse / conv_factor;
329                 dskfree_mb = ( dsktotal_mb - dskused_mb );
331                 if(allswaps && dsktotal_mb > 0){
332                         percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
333                         result = max_state (result, check_swap (percent, dskfree_mb));
334                         if (verbose) {
335                                 asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
336                         }
337                 }
339                 total_swap_mb += dsktotal_mb;
340                 free_swap_mb += dskfree_mb;
341                 used_swap_mb += dskused_mb;
342         }
344         /* and clean up after ourselves */
345         free(ent);
347 #   endif /* CHECK_SWAP_SWAPCTL_BSD */
348 #  endif /* CHECK_SWAP_SWAPCTL_SVR4 */
349 # endif /* HAVE_SWAP */
350 #endif /* HAVE_PROC_MEMINFO */
352         /* if total_swap_mb == 0, let's not divide by 0 */
353         if(total_swap_mb) {
354                 percent_used = 100 * ((double) used_swap_mb) / ((double) total_swap_mb);
355         } else {
356                 percent_used = 0;
357         }
359         result = max_state (result, check_swap (percent_used, free_swap_mb));
360         printf (_("SWAP %s - %d%% free (%d MB out of %d MB) %s|"),
361                         state_text (result),
362                         (100 - percent_used), (int) free_swap_mb, (int) total_swap_mb, status);
364         puts (perfdata ("swap", (long) free_swap_mb, "MB",
365                         TRUE, (long) max (warn_size_bytes/(1024 * 1024), warn_percent/100.0*total_swap_mb),
366                         TRUE, (long) max (crit_size_bytes/(1024 * 1024), crit_percent/100.0*total_swap_mb),
367                         TRUE, 0,
368                         TRUE, (long) total_swap_mb));
370         return result;
375 int
376 check_swap (int usp, float free_swap_mb)
378         int result = STATE_UNKNOWN;
379         float free_swap = free_swap_mb * (1024 * 1024);         /* Convert back to bytes as warn and crit specified in bytes */
380         if (usp >= 0 && crit_percent != 0 && usp >= (100.0 - crit_percent))
381                 result = STATE_CRITICAL;
382         else if (crit_size_bytes > 0 && free_swap <= crit_size_bytes)
383                 result = STATE_CRITICAL;
384         else if (usp >= 0 && warn_percent != 0 && usp >= (100.0 - warn_percent))
385                 result = STATE_WARNING;
386         else if (warn_size_bytes > 0 && free_swap <= warn_size_bytes)
387                 result = STATE_WARNING;
388         else if (usp >= 0.0)
389                 result = STATE_OK;
390         return result;
395 /* process command-line arguments */
396 int
397 process_arguments (int argc, char **argv)
399         int c = 0;  /* option character */
401         int option = 0;
402         static struct option longopts[] = {
403                 {"warning", required_argument, 0, 'w'},
404                 {"critical", required_argument, 0, 'c'},
405                 {"allswaps", no_argument, 0, 'a'},
406                 {"verbose", no_argument, 0, 'v'},
407                 {"version", no_argument, 0, 'V'},
408                 {"help", no_argument, 0, 'h'},
409                 {0, 0, 0, 0}
410         };
412         if (argc < 2)
413                 return ERROR;
415         while (1) {
416                 c = getopt_long (argc, argv, "+?Vvhac:w:", longopts, &option);
418                 if (c == -1 || c == EOF)
419                         break;
421                 switch (c) {
422                 case 'w':                                                                       /* warning size threshold */
423                         if (is_intnonneg (optarg)) {
424                                 warn_size_bytes = (float) atoi (optarg);
425                                 break;
426                         }
427                         else if (strstr (optarg, ",") &&
428                                                          strstr (optarg, "%") &&
429                                                          sscanf (optarg, "%f,%d%%", &warn_size_bytes, &warn_percent) == 2) {
430                                 warn_size_bytes = floorf(warn_size_bytes);
431                                 break;
432                         }
433                         else if (strstr (optarg, "%") &&
434                                                          sscanf (optarg, "%d%%", &warn_percent) == 1) {
435                                 break;
436                         }
437                         else {
438                                 usage4 (_("Warning threshold must be integer or percentage!"));
439                         }
440                 case 'c':                                                                       /* critical size threshold */
441                         if (is_intnonneg (optarg)) {
442                                 crit_size_bytes = (float) atoi (optarg);
443                                 break;
444                         }
445                         else if (strstr (optarg, ",") &&
446                                                          strstr (optarg, "%") &&
447                                                          sscanf (optarg, "%f,%d%%", &crit_size_bytes, &crit_percent) == 2) {
448                                 crit_size_bytes = floorf(crit_size_bytes);
449                                 break;
450                         }
451                         else if (strstr (optarg, "%") &&
452                                                          sscanf (optarg, "%d%%", &crit_percent) == 1) {
453                                 break;
454                         }
455                         else {
456                                 usage4 (_("Critical threshold must be integer or percentage!"));
457                         }
458                 case 'a':                                                                       /* all swap */
459                         allswaps = TRUE;
460                         break;
461                 case 'v':                                                                       /* verbose */
462                         verbose++;
463                         break;
464                 case 'V':                                                                       /* version */
465                         print_revision (progname, revision);
466                         exit (STATE_OK);
467                 case 'h':                                                                       /* help */
468                         print_help ();
469                         exit (STATE_OK);
470                 case '?':                                                                       /* error */
471                         usage5 ();
472                 }
473         }
475         c = optind;
476         if (c == argc)
477                 return validate_arguments ();
478         if (warn_percent == 0 && is_intnonneg (argv[c]))
479                 warn_percent = atoi (argv[c++]);
481         if (c == argc)
482                 return validate_arguments ();
483         if (crit_percent == 0 && is_intnonneg (argv[c]))
484                 crit_percent = atoi (argv[c++]);
486         if (c == argc)
487                 return validate_arguments ();
488         if (warn_size_bytes == 0 && is_intnonneg (argv[c]))
489                 warn_size_bytes = (float) atoi (argv[c++]);
491         if (c == argc)
492                 return validate_arguments ();
493         if (crit_size_bytes == 0 && is_intnonneg (argv[c]))
494                 crit_size_bytes = (float) atoi (argv[c++]);
496         return validate_arguments ();
501 int
502 validate_arguments (void)
504         if (warn_percent == 0 && crit_percent == 0 && warn_size_bytes == 0
505                         && crit_size_bytes == 0) {
506                 return ERROR;
507         }
508         else if (warn_percent < crit_percent) {
509                 usage4 
510                         (_("Warning percentage should be more than critical percentage"));
511         }
512         else if (warn_size_bytes < crit_size_bytes) {
513                 usage4
514                         (_("Warning free space should be more than critical free space"));
515         }
516         return OK;
521 void
522 print_help (void)
524         print_revision (progname, revision);
526         printf (_(COPYRIGHT), copyright, email);
528         printf ("%s\n", _("Check swap space on local machine."));
530   printf ("\n\n");
531   
532         print_usage ();
534         printf (_(UT_HELP_VRSN));
536         printf (" %s\n", "-w, --warning=INTEGER");
537   printf ("    %s\n", _("Exit with WARNING status if less than INTEGER bytes of swap space are free"));
538   printf (" %s\n", "-w, --warning=PERCENT%%");
539   printf ("    %s\n", _("Exit with WARNING status if less than PERCENT of swap space is free"));
540   printf (" %s\n", "-c, --critical=INTEGER");
541   printf ("    %s\n", _("Exit with CRITICAL status if less than INTEGER bytes of swap space are free"));
542   printf (" %s\n", "-c, --critical=PERCENT%%");
543   printf ("    %s\n", _("Exit with CRITCAL status if less than PERCENT of swap space is free"));
544   printf (" %s\n", "-a, --allswaps");
545   printf ("    %s\n", _("Conduct comparisons for all swap partitions, one by one"));
546   printf (" %s\n", "-v, --verbose");
547   printf ("    %s\n", _("Verbose output. Up to 3 levels"));
548         printf ("\n");
549   printf ("%s\n", _("Notes:"));
550   printf (" %s\n", _("On AIX, if -a is specified, uses lsps -a, otherwise uses lsps -s.\n"));
552         printf (_(UT_SUPPORT));
557 void
558 print_usage (void)
560         printf (_("Usage:"));
561   printf ("%s [-av] -w <percent_free>%% -c <percent_free>%%\n",progname);
562   printf ("%s [-av] -w <bytes_free> -c <bytes_free>\n", progname);