Code

code cleanups, largely resulting from turning on -Wall. mostly
[nagiosplug.git] / plugins / check_swap.c
1 /******************************************************************************
2  *
3  * Program: Swap space plugin for Nagios
4  * License: GPL
5  *
6  * License Information:
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  *
22  * Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net)
23  *
24  * $Id$
25  *
26  *****************************************************************************/
28 const char *progname = "check_swap";
29 const char *revision = "$Revision$";
30 const char *copyright = "2000-2004";
31 const char *email = "nagiosplug-devel@lists.sourceforge.net";
33 #include "common.h"
34 #include "popen.h"
35 #include "utils.h"
37 int check_swap (int usp, float free_swap);
38 int process_arguments (int argc, char **argv);
39 int validate_arguments (void);
40 void print_usage (void);
41 void print_help (void);
43 int warn_percent = 0;
44 int crit_percent = 0;
45 double warn_size = 0;
46 double crit_size = 0;
47 int verbose;
48 int allswaps;
50 int
51 main (int argc, char **argv)
52 {
53         int percent_used, percent;
54         float total_swap = 0, used_swap = 0, free_swap = 0;
55         float dsktotal = 0, dskused = 0, dskfree = 0, tmp = 0;
56         int result = STATE_UNKNOWN;
57         char input_buffer[MAX_INPUT_BUFFER];
58 #ifdef HAVE_PROC_MEMINFO
59         FILE *fp;
60 #else
61         int conv_factor = SWAP_CONVERSION;
62 # ifdef HAVE_SWAP
63         char *temp_buffer;
64         char *swap_command;
65         char *swap_format;
66 # else
67 #  ifdef HAVE_DECL_SWAPCTL
68         int i=0, nswaps=0, swapctl_res=0;
69 #   ifdef CHECK_SWAP_SWAPCTL_SVR4
70         swaptbl_t *tbl=NULL;
71         swapent_t *ent=NULL;
72 #   else
73 #    ifdef CHECK_SWAP_SWAPCTL_BSD
74         struct swapent *ent;
75 #    endif /* CHECK_SWAP_SWAPCTL_BSD */
76 #   endif /* CHECK_SWAP_SWAPCTL_SVR4 */
77 #  endif /* HAVE_DECL_SWAPCTL */
78 # endif
79 #endif
80         char str[32];
81         char *status;
83         setlocale (LC_ALL, "");
84         bindtextdomain (PACKAGE, LOCALEDIR);
85         textdomain (PACKAGE);
87         status = strdup ("");
89         if (process_arguments (argc, argv) == ERROR)
90                 usage4 (_("Could not parse arguments"));
92 #ifdef HAVE_PROC_MEMINFO
93         fp = fopen (PROC_MEMINFO, "r");
94         while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
95                 if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %f %f %f", &dsktotal, &dskused, &dskfree) == 3) {
96                         dsktotal = dsktotal / 1048576;
97                         dskused = dskused / 1048576;
98                         dskfree = dskfree / 1048576;
99                         total_swap += dsktotal;
100                         used_swap += dskused;
101                         free_swap += dskfree;
102                         if (allswaps) {
103                                 if (dsktotal == 0)
104                                         percent=100.0;
105                                 else
106                                         percent = 100 * (((double) dskused) / ((double) dsktotal));
107                                 result = max_state (result, check_swap (percent, dskfree));
108                                 if (verbose)
109                                         asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree, 100 - percent);
110                         }
111                 }
112                 else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFre]%*[:] %f %*[k]%*[B]", str, &tmp)) {
113                         if (strcmp ("Total", str) == 0) {
114                                 dsktotal = tmp / 1024;
115                         }
116                         else if (strcmp ("Free", str) == 0) {
117                                 dskfree = tmp / 1024;
118                         }
119                 }
120         }
121         fclose(fp);
122         dskused = dsktotal - dskfree;
123         total_swap = dsktotal;
124         used_swap = dskused;
125         free_swap = dskfree;
126 #else
127 # ifdef HAVE_SWAP
128         asprintf(&swap_command, "%s", SWAP_COMMAND);
129         asprintf(&swap_format, "%s", SWAP_FORMAT);
131 /* These override the command used if a summary (and thus ! allswaps) is required */
132 /* The summary flag returns more accurate information about swap usage on these OSes */
133 #  ifdef _AIX
134         if (!allswaps) {
135                 asprintf(&swap_command, "%s", "/usr/sbin/lsps -s");
136                 asprintf(&swap_format, "%s", "%f%*s %f");
137                 conv_factor = 1;
138         }
139 #  endif
141         if (verbose >= 2)
142                 printf (_("Command: %s\n"), swap_command);
143         if (verbose >= 3)
144                 printf (_("Format: %s\n"), swap_format);
146         child_process = spopen (swap_command);
147         if (child_process == NULL) {
148                 printf (_("Could not open pipe: %s\n"), swap_command);
149                 return STATE_UNKNOWN;
150         }
152         child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r");
153         if (child_stderr == NULL)
154                 printf (_("Could not open stderr for %s\n"), swap_command);
156         sprintf (str, "%s", "");
157         /* read 1st line */
158         fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process);
159         if (strcmp (swap_format, "") == 0) {
160                 temp_buffer = strtok (input_buffer, " \n");
161                 while (temp_buffer) {
162                         if (strstr (temp_buffer, "blocks"))
163                                 sprintf (str, "%s %s", str, "%f");
164                         else if (strstr (temp_buffer, "dskfree"))
165                                 sprintf (str, "%s %s", str, "%f");
166                         else
167                                 sprintf (str, "%s %s", str, "%*s");
168                         temp_buffer = strtok (NULL, " \n");
169                 }
170         }
172 /* If different swap command is used for summary switch, need to read format differently */
173 #  ifdef _AIX
174         if (!allswaps) {
175                 fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process);       /* Ignore first line */
176                 sscanf (input_buffer, swap_format, &total_swap, &used_swap);
177                 free_swap = total_swap * (100 - used_swap) /100;
178                 used_swap = total_swap - free_swap;
179                 if (verbose >= 3)
180                         printf (_("total=%.0f, used=%.0f, free=%.0f\n"), total_swap, used_swap, free_swap);
181         } else {
182 #  endif
183                 while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
184                         sscanf (input_buffer, swap_format, &dsktotal, &dskfree);
186                         dsktotal = dsktotal / conv_factor;
187                         /* AIX lists percent used, so this converts to dskfree in MBs */
188 #  ifdef _AIX
189                         dskfree = dsktotal * (100 - dskfree) / 100;
190 #  else
191                         dskfree = dskfree / conv_factor;
192 #  endif
193                         if (verbose >= 3)
194                                 printf (_("total=%.0f, free=%.0f\n"), dsktotal, dskfree);
196                         dskused = dsktotal - dskfree;
197                         total_swap += dsktotal;
198                         used_swap += dskused;
199                         free_swap += dskfree;
200                         if (allswaps) {
201                                 percent = 100 * (((double) dskused) / ((double) dsktotal));
202                                 result = max_state (result, check_swap (percent, dskfree));
203                                 if (verbose)
204                                         asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree, 100 - percent);
205                         }
206                 }
207 #  ifdef _AIX
208         }
209 #  endif
211         /* If we get anything on STDERR, at least set warning */
212         while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr))
213                 result = max_state (result, STATE_WARNING);
215         /* close stderr */
216         (void) fclose (child_stderr);
218         /* close the pipe */
219         if (spclose (child_process))
220                 result = max_state (result, STATE_WARNING);
221 # else
222 #  ifdef CHECK_SWAP_SWAPCTL_SVR4
224         /* get the number of active swap devices */
225         nswaps=swapctl(SC_GETNSWP, NULL);
227         /* initialize swap table + entries */
228         tbl=(swaptbl_t*)malloc(sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));
229         memset(tbl, 0, sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));
230         tbl->swt_n=nswaps;
231         for(i=0;i<nswaps;i++){
232                 ent=&tbl->swt_ent[i];
233                 ent->ste_path=(char*)malloc(sizeof(char)*MAXPATHLEN);
234         }
236         /* and now, tally 'em up */
237         swapctl_res=swapctl(SC_LIST, tbl);
238         if(swapctl_res < 0){
239                 perror(_("swapctl failed: "));
240                 result = STATE_WARNING;
241         }
243         for(i=0;i<nswaps;i++){
244                 dsktotal = (float) tbl->swt_ent[i].ste_pages / SWAP_CONVERSION;
245                 dskfree = (float) tbl->swt_ent[i].ste_free /  SWAP_CONVERSION;
246                 dskused = ( dsktotal - dskfree );
248                 if (verbose >= 3)
249                         printf ("dsktotal=%.0f dskfree=%.0f dskused=%.0f\n", dsktotal, dskfree, dskused);
251                 if(allswaps && dsktotal > 0){
252                         percent = 100 * (((double) dskused) / ((double) dsktotal));
253                         result = max_state (result, check_swap (percent, dskfree));
254                         if (verbose) {
255                                 asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree, 100 - percent);
256                         }
257                 }
259                 total_swap += dsktotal;
260                 free_swap += dskfree;
261                 used_swap += dskused;
262         }
264         /* and clean up after ourselves */
265         for(i=0;i<nswaps;i++){
266                 free(tbl->swt_ent[i].ste_path);
267         }
268         free(tbl);
269 #  else
270 #   ifdef CHECK_SWAP_SWAPCTL_BSD
272         /* get the number of active swap devices */
273         nswaps=swapctl(SWAP_NSWAP, NULL, 0);
275         /* initialize swap table + entries */
276         ent=(struct swapent*)malloc(sizeof(struct swapent)*nswaps);
278         /* and now, tally 'em up */
279         swapctl_res=swapctl(SWAP_STATS, ent, nswaps);
280         if(swapctl_res < 0){
281                 perror(_("swapctl failed: "));
282                 result = STATE_WARNING;
283         }
285         for(i=0;i<nswaps;i++){
286                 dsktotal = (float) ent->se_nblks / conv_factor;
287                 dskused = (float) ent->se_inuse / conv_factor;
288                 dskfree = ( dsktotal - dskused );
290                 if(allswaps && dsktotal > 0){
291                         percent = 100 * (((double) dskused) / ((double) dsktotal));
292                         result = max_state (result, check_swap (percent, dskfree));
293                         if (verbose) {
294                                 asprintf (&status, "%s [%.0f (%d%%)]", status, dskfree, 100 - percent);
295                         }
296                 }
298                 total_swap += dsktotal;
299                 free_swap += dskfree;
300                 used_swap += dskused;
301         }
303         /* and clean up after ourselves */
304         free(ent);
306 #   endif /* CHECK_SWAP_SWAPCTL_BSD */
307 #  endif /* CHECK_SWAP_SWAPCTL_SVR4 */
308 # endif /* HAVE_SWAP */
309 #endif /* HAVE_PROC_MEMINFO */
311         /* if total_swap == 0, let's not divide by 0 */
312         if(total_swap) {
313                 percent_used = 100 * ((double) used_swap) / ((double) total_swap);
314         } else {
315                 percent_used = 0;
316         }
318         result = max_state (result, check_swap (percent_used, free_swap));
319         printf (_("SWAP %s - %d%% free (%.0f MB out of %.0f MB) %s|"),
320                         state_text (result),
321                         (100 - percent_used), free_swap, total_swap, status);
323         puts (perfdata ("swap", (long) free_swap, "MB",
324                         TRUE, (long) max (warn_size/1024, warn_percent/100.0*total_swap),
325                         TRUE, (long) max (crit_size/1024, crit_percent/100.0*total_swap),
326                         TRUE, 0,
327                         TRUE, (long) total_swap));
329         return result;
334 int
335 check_swap (int usp, float free_swap)
337         int result = STATE_UNKNOWN;
338         free_swap = free_swap * 1024;           /* Convert back to bytes as warn and crit specified in bytes */
339         if (usp >= 0 && crit_percent != 0 && usp >= (100.0 - crit_percent))
340                 result = STATE_CRITICAL;
341         else if (crit_size > 0 && free_swap <= crit_size)
342                 result = STATE_CRITICAL;
343         else if (usp >= 0 && warn_percent != 0 && usp >= (100.0 - warn_percent))
344                 result = STATE_WARNING;
345         else if (warn_size > 0 && free_swap <= warn_size)
346                 result = STATE_WARNING;
347         else if (usp >= 0.0)
348                 result = STATE_OK;
349         return result;
354 /* process command-line arguments */
355 int
356 process_arguments (int argc, char **argv)
358         int c = 0;  /* option character */
360         int option = 0;
361         static struct option longopts[] = {
362                 {"warning", required_argument, 0, 'w'},
363                 {"critical", required_argument, 0, 'c'},
364                 {"allswaps", no_argument, 0, 'a'},
365                 {"verbose", no_argument, 0, 'v'},
366                 {"version", no_argument, 0, 'V'},
367                 {"help", no_argument, 0, 'h'},
368                 {0, 0, 0, 0}
369         };
371         if (argc < 2)
372                 return ERROR;
374         while (1) {
375                 c = getopt_long (argc, argv, "+?Vvhac:w:", longopts, &option);
377                 if (c == -1 || c == EOF)
378                         break;
380                 switch (c) {
381                 case 'w':                                                                       /* warning size threshold */
382                         if (is_intnonneg (optarg)) {
383                                 warn_size = (double) atoi (optarg);
384                                 break;
385                         }
386                         else if (strstr (optarg, ",") &&
387                                                          strstr (optarg, "%") &&
388                                                          sscanf (optarg, "%lf,%d%%", &warn_size, &warn_percent) == 2) {
389                                 warn_size = floor(warn_size);
390                                 break;
391                         }
392                         else if (strstr (optarg, "%") &&
393                                                          sscanf (optarg, "%d%%", &warn_percent) == 1) {
394                                 break;
395                         }
396                         else {
397                                 usage4 (_("Warning threshold must be integer or percentage!"));
398                         }
399                 case 'c':                                                                       /* critical size threshold */
400                         if (is_intnonneg (optarg)) {
401                                 crit_size = (double) atoi (optarg);
402                                 break;
403                         }
404                         else if (strstr (optarg, ",") &&
405                                                          strstr (optarg, "%") &&
406                                                          sscanf (optarg, "%lf,%d%%", &crit_size, &crit_percent) == 2) {
407                                 crit_size = floor(crit_size);
408                                 break;
409                         }
410                         else if (strstr (optarg, "%") &&
411                                                          sscanf (optarg, "%d%%", &crit_percent) == 1) {
412                                 break;
413                         }
414                         else {
415                                 usage4 (_("Critical threshold must be integer or percentage!"));
416                         }
417                 case 'a':                                                                       /* all swap */
418                         allswaps = TRUE;
419                         break;
420                 case 'v':                                                                       /* verbose */
421                         verbose++;
422                         break;
423                 case 'V':                                                                       /* version */
424                         print_revision (progname, revision);
425                         exit (STATE_OK);
426                 case 'h':                                                                       /* help */
427                         print_help ();
428                         exit (STATE_OK);
429                 case '?':                                                                       /* error */
430                         usage2 (_("Unknown argument"), optarg);
431                 }
432         }
434         c = optind;
435         if (c == argc)
436                 return validate_arguments ();
437         if (warn_percent == 0 && is_intnonneg (argv[c]))
438                 warn_percent = atoi (argv[c++]);
440         if (c == argc)
441                 return validate_arguments ();
442         if (crit_percent == 0 && is_intnonneg (argv[c]))
443                 crit_percent = atoi (argv[c++]);
445         if (c == argc)
446                 return validate_arguments ();
447         if (warn_size == 0 && is_intnonneg (argv[c]))
448                 warn_size = (double) atoi (argv[c++]);
450         if (c == argc)
451                 return validate_arguments ();
452         if (crit_size == 0 && is_intnonneg (argv[c]))
453                 crit_size = (double) atoi (argv[c++]);
455         return validate_arguments ();
460 int
461 validate_arguments (void)
463         if (warn_percent == 0 && crit_percent == 0 && warn_size == 0
464                         && crit_size == 0) {
465                 return ERROR;
466         }
467         else if (warn_percent < crit_percent) {
468                 usage4 
469                         (_("Warning percentage should be more than critical percentage"));
470         }
471         else if (warn_size < crit_size) {
472                 usage4
473                         (_("Warning free space should be more than critical free space"));
474         }
475         return OK;
480 void
481 print_help (void)
483         print_revision (progname, revision);
485         printf (_(COPYRIGHT), copyright, email);
487         printf (_("Check swap space on local machine.\n\n"));
489         print_usage ();
491         printf (_(UT_HELP_VRSN));
493         printf (_("\n\
494  -w, --warning=INTEGER\n\
495    Exit with WARNING status if less than INTEGER bytes of swap space are free\n\
496  -w, --warning=PERCENT%%\n\
497    Exit with WARNING status if less than PERCENT of swap space is free\n\
498  -c, --critical=INTEGER\n\
499    Exit with CRITICAL status if less than INTEGER bytes of swap space are free\n\
500  -c, --critical=PERCENT%%\n\
501    Exit with CRITCAL status if less than PERCENT of swap space is free\n\
502  -a, --allswaps\n\
503     Conduct comparisons for all swap partitions, one by one\n\
504  -v, --verbose\n\
505     Verbose output. Up to 3 levels\n"));
507         printf (_("\n\
508 On AIX, if -a is specified, uses lsps -a, otherwise uses lsps -s.\n"));
510         printf (_(UT_SUPPORT));
515 void
516 print_usage (void)
518         printf ("\
519 Usage: %s [-av] -w <percent_free>%% -c <percent_free>%%\n\
520        %s [-av] -w <bytes_free> -c <bytes_free>\n", progname, progname);