summaryrefslogtreecommitdiffstats
path: root/plugins
diff options
context:
space:
mode:
Diffstat (limited to 'plugins')
-rw-r--r--plugins/Makefile.am21
-rw-r--r--plugins/check_swap.c781
-rw-r--r--plugins/check_swap.d/check_swap.h44
-rw-r--r--plugins/check_swap.d/swap.c412
-rw-r--r--plugins/tests/test_check_swap.c23
-rwxr-xr-xplugins/tests/test_check_swap.t6
-rw-r--r--plugins/tests/var/proc_meminfo55
7 files changed, 811 insertions, 531 deletions
diff --git a/plugins/Makefile.am b/plugins/Makefile.am
index 49086b7a..d43c1971 100644
--- a/plugins/Makefile.am
+++ b/plugins/Makefile.am
@@ -38,19 +38,27 @@ check_tcp_programs = check_ftp check_imap check_nntp check_pop \
38EXTRA_PROGRAMS = check_mysql check_radius check_pgsql check_snmp check_hpjd \ 38EXTRA_PROGRAMS = check_mysql check_radius check_pgsql check_snmp check_hpjd \
39 check_swap check_fping check_ldap check_game check_dig \ 39 check_swap check_fping check_ldap check_game check_dig \
40 check_nagios check_by_ssh check_dns check_nt check_ide_smart \ 40 check_nagios check_by_ssh check_dns check_nt check_ide_smart \
41 check_procs check_mysql_query check_apt check_dbi check_curl 41 check_procs check_mysql_query check_apt check_dbi check_curl \
42 \
43 tests/test_check_swap
42 44
43SUBDIRS = picohttpparser 45SUBDIRS = picohttpparser
44 46
45EXTRA_DIST = t tests 47np_test_scripts = tests/test_check_swap.t
48
49EXTRA_DIST = t tests $(np_test_scripts) check_swap.d
46 50
47PLUGINHDRS = common.h 51PLUGINHDRS = common.h
48 52
49noinst_LIBRARIES = libnpcommon.a 53noinst_LIBRARIES = libnpcommon.a
54noinst_PROGRAMS = @EXTRA_PLUGIN_TESTS@
55# These two lines support "make check", but we use "make test"
56check_PROGRAMS = @EXTRA_PLUGIN_TESTS@
50 57
51libnpcommon_a_SOURCES = utils.c netutils.c sslutils.c runcmd.c \ 58libnpcommon_a_SOURCES = utils.c netutils.c sslutils.c runcmd.c \
52 popen.c utils.h netutils.h popen.h common.h runcmd.c runcmd.h 59 popen.c utils.h netutils.h popen.h common.h runcmd.c runcmd.h
53 60
61
54BASEOBJS = libnpcommon.a ../lib/libmonitoringplug.a ../gl/libgnu.a $(LIB_CRYPTO) 62BASEOBJS = libnpcommon.a ../lib/libmonitoringplug.a ../gl/libgnu.a $(LIB_CRYPTO)
55NETOBJS = $(BASEOBJS) $(EXTRA_NETOBLS) 63NETOBJS = $(BASEOBJS) $(EXTRA_NETOBLS)
56NETLIBS = $(NETOBJS) $(SOCKETLIBS) 64NETLIBS = $(NETOBJS) $(SOCKETLIBS)
@@ -58,7 +66,10 @@ SSLOBJS = $(BASEOBJS) $(NETLIBS) $(SSLLIBS) $(LIB_CRYPTO)
58 66
59TESTS_ENVIRONMENT = perl -I $(top_builddir) -I $(top_srcdir) 67TESTS_ENVIRONMENT = perl -I $(top_builddir) -I $(top_srcdir)
60 68
61TESTS = @PLUGIN_TEST@ 69tap_ldflags = -L$(top_srcdir)/tap
70
71TESTS = @PLUGIN_TEST@ @EXTRA_PLUGIN_TESTS@
72
62 73
63test: 74test:
64 perl -I $(top_builddir) -I $(top_srcdir) ../test.pl 75 perl -I $(top_builddir) -I $(top_srcdir) ../test.pl
@@ -107,6 +118,7 @@ check_real_LDADD = $(NETLIBS)
107check_snmp_LDADD = $(BASEOBJS) 118check_snmp_LDADD = $(BASEOBJS)
108check_smtp_LDADD = $(SSLOBJS) 119check_smtp_LDADD = $(SSLOBJS)
109check_ssh_LDADD = $(NETLIBS) 120check_ssh_LDADD = $(NETLIBS)
121check_swap_SOURCES = check_swap.c check_swap.d/swap.c
110check_swap_LDADD = $(MATHLIBS) $(BASEOBJS) 122check_swap_LDADD = $(MATHLIBS) $(BASEOBJS)
111check_tcp_LDADD = $(SSLOBJS) 123check_tcp_LDADD = $(SSLOBJS)
112check_time_LDADD = $(NETLIBS) 124check_time_LDADD = $(NETLIBS)
@@ -122,6 +134,9 @@ if !HAVE_UTMPX
122check_users_LDADD += popen.o 134check_users_LDADD += popen.o
123endif 135endif
124 136
137tests_test_check_swap_LDADD = $(BASEOBJS) $(tap_ldflags) -ltap
138tests_test_check_swap_SOURCES = tests/test_check_swap.c check_swap.d/swap.c
139
125############################################################################## 140##############################################################################
126# secondary dependencies 141# secondary dependencies
127 142
diff --git a/plugins/check_swap.c b/plugins/check_swap.c
index e7ee785d..4e3471b6 100644
--- a/plugins/check_swap.c
+++ b/plugins/check_swap.c
@@ -1,607 +1,332 @@
1/***************************************************************************** 1/*****************************************************************************
2* 2 *
3* Monitoring check_swap plugin 3 * Monitoring check_swap plugin
4* 4 *
5* License: GPL 5 * License: GPL
6* Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net) 6 * Copyright (c) 2000 Karl DeBisschop (kdebisschop@users.sourceforge.net)
7* Copyright (c) 2000-2024 Monitoring Plugins Development Team 7 * Copyright (c) 2000-2024 Monitoring Plugins Development Team
8* 8 *
9* Description: 9 * Description:
10* 10 *
11* This file contains the check_swap plugin 11 * This file contains the check_swap plugin
12* 12 *
13* 13 *
14* This program is free software: you can redistribute it and/or modify 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 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 16 * the Free Software Foundation, either version 3 of the License, or
17* (at your option) any later version. 17 * (at your option) any later version.
18* 18 *
19* This program is distributed in the hope that it will be useful, 19 * This program is distributed in the hope that it will be useful,
20* but WITHOUT ANY WARRANTY; without even the implied warranty of 20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22* GNU General Public License for more details. 22 * GNU General Public License for more details.
23* 23 *
24* You should have received a copy of the GNU General Public License 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/>. 25 * along with this program. If not, see <http://www.gnu.org/licenses/>.
26* 26 *
27* 27 *
28*****************************************************************************/ 28 *****************************************************************************/
29 29
30#include <stdint.h>
30const char *progname = "check_swap"; 31const char *progname = "check_swap";
31const char *copyright = "2000-2024"; 32const char *copyright = "2000-2024";
32const char *email = "devel@monitoring-plugins.org"; 33const char *email = "devel@monitoring-plugins.org";
33 34
34#include "common.h"
35#include "popen.h"
36#include "utils.h"
37
38#ifdef HAVE_DECL_SWAPCTL 35#ifdef HAVE_DECL_SWAPCTL
39# ifdef HAVE_SYS_PARAM_H 36# ifdef HAVE_SYS_PARAM_H
40# include <sys/param.h> 37# include <sys/param.h>
41# endif 38# endif
42# ifdef HAVE_SYS_SWAP_H 39# ifdef HAVE_SYS_SWAP_H
43# include <sys/swap.h> 40# include <sys/swap.h>
44# endif 41# endif
45# ifdef HAVE_SYS_STAT_H 42# ifdef HAVE_SYS_STAT_H
46# include <sys/stat.h> 43# include <sys/stat.h>
47# endif 44# endif
48#endif 45#endif
49 46
50#ifndef SWAP_CONVERSION 47#include "./check_swap.d/check_swap.h"
51# define SWAP_CONVERSION 1 48#include "./utils.h"
52#endif
53 49
54typedef struct { 50typedef struct {
55 bool is_percentage; 51 int errorcode;
56 uint64_t value; 52 swap_config config;
57} threshold; 53} swap_config_wrapper;
58
59int check_swap (float free_swap_mb, float total_swap_mb);
60int process_arguments (int argc, char **argv);
61int validate_arguments (void);
62void print_usage (void);
63void print_help (void);
64
65threshold warn;
66threshold crit;
67int verbose;
68bool allswaps = false;
69int no_swap_state = STATE_CRITICAL;
70
71int
72main (int argc, char **argv)
73{
74 unsigned int percent_used, percent;
75 uint64_t total_swap_mb = 0, used_swap_mb = 0, free_swap_mb = 0;
76 uint64_t dsktotal_mb = 0, dskused_mb = 0, dskfree_mb = 0;
77 uint64_t tmp_KB = 0;
78 int result = STATE_UNKNOWN;
79 char input_buffer[MAX_INPUT_BUFFER];
80#ifdef HAVE_PROC_MEMINFO
81 FILE *fp;
82#else
83 int conv_factor = SWAP_CONVERSION;
84# ifdef HAVE_SWAP
85 char *temp_buffer;
86 char *swap_command;
87 char *swap_format;
88# else
89# ifdef HAVE_DECL_SWAPCTL
90 int i=0, nswaps=0, swapctl_res=0;
91# ifdef CHECK_SWAP_SWAPCTL_SVR4
92 swaptbl_t *tbl=NULL;
93 swapent_t *ent=NULL;
94# else
95# ifdef CHECK_SWAP_SWAPCTL_BSD
96 struct swapent *ent;
97# endif /* CHECK_SWAP_SWAPCTL_BSD */
98# endif /* CHECK_SWAP_SWAPCTL_SVR4 */
99# endif /* HAVE_DECL_SWAPCTL */
100# endif
101#endif
102 char str[32];
103 char *status;
104 54
105 setlocale (LC_ALL, ""); 55static swap_config_wrapper process_arguments(int argc, char **argv);
106 bindtextdomain (PACKAGE, LOCALEDIR); 56void print_usage(void);
107 textdomain (PACKAGE); 57static void print_help(swap_config /*config*/);
108 58
109 status = strdup (""); 59static int verbose;
110 60
111 /* Parse extra opts if any */ 61#define HUNDRED_PERCENT 100
112 argv=np_extra_opts (&argc, argv, progname);
113 62
114 if (process_arguments (argc, argv) == ERROR) 63int main(int argc, char **argv) {
115 usage4 (_("Could not parse arguments")); 64 setlocale(LC_ALL, "");
116 65 bindtextdomain(PACKAGE, LOCALEDIR);
117#ifdef HAVE_PROC_MEMINFO 66 textdomain(PACKAGE);
118 if (verbose >= 3) {
119 printf("Reading PROC_MEMINFO at %s\n", PROC_MEMINFO);
120 }
121 fp = fopen (PROC_MEMINFO, "r");
122 while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
123 /*
124 * The following sscanf call looks for a line looking like: "Swap: 123 123 123"
125 * On which kind of system this format exists, I can not say, but I wanted to
126 * document this for people who are not adapt with sscanf anymore, like me
127 */
128 if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %lu %lu %lu", &dsktotal_mb, &dskused_mb, &dskfree_mb) == 3) {
129 dsktotal_mb = dsktotal_mb / (1024 * 1024); /* Apply conversion */
130 dskused_mb = dskused_mb / (1024 * 1024);
131 dskfree_mb = dskfree_mb / (1024 * 1024);
132 total_swap_mb += dsktotal_mb;
133 used_swap_mb += dskused_mb;
134 free_swap_mb += dskfree_mb;
135 if (allswaps) {
136 if (dsktotal_mb == 0)
137 percent=100.0;
138 else
139 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
140 result = max_state (result, check_swap (dskfree_mb, dsktotal_mb));
141 if (verbose)
142 xasprintf (&status, "%s [%lu (%d%%)]", status, dskfree_mb, 100 - percent);
143 }
144 }
145 67
146 /* 68 char *status;
147 * The following sscanf call looks for lines looking like: "SwapTotal: 123" and "SwapFree: 123" 69 status = strdup("");
148 * This format exists at least on Debian Linux with a 5.* kernel
149 */
150 else if (sscanf (input_buffer, "%*[S]%*[w]%*[a]%*[p]%[TotalFreCchd]%*[:] %lu %*[k]%*[B]", str, &tmp_KB)) {
151 if (verbose >= 3) {
152 printf("Got %s with %lu\n", str, tmp_KB);
153 }
154 /* I think this part is always in Kb, so convert to mb */
155 if (strcmp ("Total", str) == 0) {
156 dsktotal_mb = tmp_KB / 1024;
157 }
158 else if (strcmp ("Free", str) == 0) {
159 dskfree_mb = dskfree_mb + tmp_KB / 1024;
160 }
161 else if (strcmp ("Cached", str) == 0) {
162 dskfree_mb = dskfree_mb + tmp_KB / 1024;
163 }
164 }
165 }
166 fclose(fp);
167 dskused_mb = dsktotal_mb - dskfree_mb;
168 total_swap_mb = dsktotal_mb;
169 used_swap_mb = dskused_mb;
170 free_swap_mb = dskfree_mb;
171#else
172# ifdef HAVE_SWAP
173 xasprintf(&swap_command, "%s", SWAP_COMMAND);
174 xasprintf(&swap_format, "%s", SWAP_FORMAT);
175
176/* These override the command used if a summary (and thus ! allswaps) is required */
177/* The summary flag returns more accurate information about swap usage on these OSes */
178# ifdef _AIX
179 if (!allswaps) {
180 xasprintf(&swap_command, "%s", "/usr/sbin/lsps -s");
181 xasprintf(&swap_format, "%s", "%lu%*s %lu");
182 conv_factor = 1;
183 }
184# endif
185
186 if (verbose >= 2)
187 printf (_("Command: %s\n"), swap_command);
188 if (verbose >= 3)
189 printf (_("Format: %s\n"), swap_format);
190 70
191 child_process = spopen (swap_command); 71 /* Parse extra opts if any */
192 if (child_process == NULL) { 72 argv = np_extra_opts(&argc, argv, progname);
193 printf (_("Could not open pipe: %s\n"), swap_command);
194 return STATE_UNKNOWN;
195 }
196 73
197 child_stderr = fdopen (child_stderr_array[fileno (child_process)], "r"); 74 swap_config_wrapper tmp = process_arguments(argc, argv);
198 if (child_stderr == NULL)
199 printf (_("Could not open stderr for %s\n"), swap_command);
200
201 sprintf (str, "%s", "");
202 /* read 1st line */
203 fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process);
204 if (strcmp (swap_format, "") == 0) {
205 temp_buffer = strtok (input_buffer, " \n");
206 while (temp_buffer) {
207 if (strstr (temp_buffer, "blocks"))
208 sprintf (str, "%s %s", str, "%lu");
209 else if (strstr (temp_buffer, "dskfree"))
210 sprintf (str, "%s %s", str, "%lu");
211 else
212 sprintf (str, "%s %s", str, "%*s");
213 temp_buffer = strtok (NULL, " \n");
214 }
215 }
216 75
217/* If different swap command is used for summary switch, need to read format differently */ 76 if (tmp.errorcode != OK) {
218# ifdef _AIX 77 usage4(_("Could not parse arguments"));
219 if (!allswaps) {
220 fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process); /* Ignore first line */
221 sscanf (input_buffer, swap_format, &total_swap_mb, &used_swap_mb);
222 free_swap_mb = total_swap_mb * (100 - used_swap_mb) /100;
223 used_swap_mb = total_swap_mb - free_swap_mb;
224 if (verbose >= 3)
225 printf (_("total=%.0f, used=%.0f, free=%.0f\n"), total_swap_mb, used_swap_mb, free_swap_mb);
226 } else {
227# endif
228 while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
229 sscanf (input_buffer, swap_format, &dsktotal_mb, &dskfree_mb);
230
231 dsktotal_mb = dsktotal_mb / conv_factor;
232 /* AIX lists percent used, so this converts to dskfree in MBs */
233# ifdef _AIX
234 dskfree_mb = dsktotal_mb * (100 - dskfree_mb) / 100;
235# else
236 dskfree_mb = dskfree_mb / conv_factor;
237# endif
238 if (verbose >= 3)
239 printf (_("total=%.0f, free=%.0f\n"), dsktotal_mb, dskfree_mb);
240
241 dskused_mb = dsktotal_mb - dskfree_mb;
242 total_swap_mb += dsktotal_mb;
243 used_swap_mb += dskused_mb;
244 free_swap_mb += dskfree_mb;
245 if (allswaps) {
246 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
247 result = max_state (result, check_swap (dskfree_mb, dsktotal_mb));
248 if (verbose)
249 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
250 }
251 }
252# ifdef _AIX
253 } 78 }
254# endif
255
256 /* If we get anything on STDERR, at least set warning */
257 while (fgets (input_buffer, MAX_INPUT_BUFFER - 1, child_stderr))
258 result = max_state (result, STATE_WARNING);
259
260 /* close stderr */
261 (void) fclose (child_stderr);
262
263 /* close the pipe */
264 if (spclose (child_process))
265 result = max_state (result, STATE_WARNING);
266# else
267# ifdef CHECK_SWAP_SWAPCTL_SVR4
268
269 /* get the number of active swap devices */
270 if((nswaps=swapctl(SC_GETNSWP, NULL))== -1)
271 die(STATE_UNKNOWN, _("Error getting swap devices\n") );
272 79
273 if(nswaps == 0) 80 swap_config config = tmp.config;
274 die(STATE_OK, _("SWAP OK: No swap devices defined\n"));
275 81
276 if(verbose >= 3) 82 swap_result data = get_swap_data(config);
277 printf("Found %d swap device(s)\n", nswaps);
278 83
279 /* initialize swap table + entries */ 84 double percent_used;
280 tbl=(swaptbl_t*)malloc(sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps));
281 85
282 if(tbl==NULL) 86 /* if total_swap_mb == 0, let's not divide by 0 */
283 die(STATE_UNKNOWN, _("malloc() failed!\n")); 87 if (data.metrics.total != 0) {
284 88 percent_used = HUNDRED_PERCENT * ((double)data.metrics.used) / ((double)data.metrics.total);
285 memset(tbl, 0, sizeof(swaptbl_t)+(sizeof(swapent_t)*nswaps)); 89 } else {
286 tbl->swt_n=nswaps; 90 printf(_("SWAP %s - Swap is either disabled, not present, or of zero "
287 for(i=0;i<nswaps;i++){ 91 "size."),
288 if((tbl->swt_ent[i].ste_path=(char*)malloc(sizeof(char)*MAXPATHLEN)) == NULL) 92 state_text(data.statusCode));
289 die(STATE_UNKNOWN, _("malloc() failed!\n")); 93 exit(config.no_swap_state);
290 } 94 }
291 95
292 /* and now, tally 'em up */ 96 if (verbose) {
293 swapctl_res=swapctl(SC_LIST, tbl); 97 printf("Computed usage percentage: %g\n", percent_used);
294 if(swapctl_res < 0){
295 perror(_("swapctl failed: "));
296 die(STATE_UNKNOWN, _("Error in swapctl call\n"));
297 } 98 }
298 99
299 for(i=0;i<nswaps;i++){ 100 uint64_t warn_print = config.warn.value;
300 dsktotal_mb = (float) tbl->swt_ent[i].ste_pages / SWAP_CONVERSION; 101 if (config.warn.is_percentage) {
301 dskfree_mb = (float) tbl->swt_ent[i].ste_free / SWAP_CONVERSION; 102 warn_print = config.warn.value * (data.metrics.total / HUNDRED_PERCENT);
302 dskused_mb = ( dsktotal_mb - dskfree_mb ); 103 }
303 104
304 if (verbose >= 3) 105 uint64_t crit_print = config.crit.value;
305 printf ("dsktotal_mb=%.0f dskfree_mb=%.0f dskused_mb=%.0f\n", dsktotal_mb, dskfree_mb, dskused_mb); 106 if (config.crit.is_percentage) {
107 crit_print = config.crit.value * (data.metrics.total / HUNDRED_PERCENT);
108 }
306 109
307 if(allswaps && dsktotal_mb > 0){ 110 char *perfdata = perfdata_uint64("swap", data.metrics.free, "B", true, warn_print, true, crit_print, true, 0, true, data.metrics.total);
308 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb));
309 result = max_state (result, check_swap (dskfree_mb, dsktotal_mb));
310 if (verbose) {
311 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
312 }
313 }
314 111
315 total_swap_mb += dsktotal_mb; 112 if (verbose > 1) {
316 free_swap_mb += dskfree_mb; 113 printf("Warn threshold value: %" PRIu64 "\n", config.warn.value);
317 used_swap_mb += dskused_mb;
318 } 114 }
319 115
320 /* and clean up after ourselves */ 116 if ((config.warn.is_percentage && (percent_used >= (double)(HUNDRED_PERCENT - config.warn.value))) ||
321 for(i=0;i<nswaps;i++){ 117 config.warn.value >= data.metrics.free) {
322 free(tbl->swt_ent[i].ste_path); 118 data.statusCode = max_state(data.statusCode, STATE_WARNING);
323 } 119 }
324 free(tbl);
325# else
326# ifdef CHECK_SWAP_SWAPCTL_BSD
327
328 /* get the number of active swap devices */
329 nswaps=swapctl(SWAP_NSWAP, NULL, 0);
330 120
331 /* initialize swap table + entries */ 121 if (verbose > 1) {
332 ent=(struct swapent*)malloc(sizeof(struct swapent)*nswaps); 122 printf("Crit threshold value: %" PRIu64 "\n", config.crit.value);
123 }
333 124
334 /* and now, tally 'em up */ 125 if ((config.crit.is_percentage && (percent_used >= (double)(HUNDRED_PERCENT - config.crit.value))) ||
335 swapctl_res=swapctl(SWAP_STATS, ent, nswaps); 126 config.crit.value >= data.metrics.free) {
336 if(swapctl_res < 0){ 127 data.statusCode = max_state(data.statusCode, STATE_CRITICAL);
337 perror(_("swapctl failed: "));
338 die(STATE_UNKNOWN, _("Error in swapctl call\n"));
339 } 128 }
340 129
341 for(i=0;i<nswaps;i++){ 130 printf(_("SWAP %s - %g%% free (%lluMB out of %lluMB) %s|%s\n"), state_text(data.statusCode), (HUNDRED_PERCENT - percent_used),
342 dsktotal_mb = (float) ent[i].se_nblks / conv_factor; 131 data.metrics.free, data.metrics.total, status, perfdata);
343 dskused_mb = (float) ent[i].se_inuse / conv_factor;
344 dskfree_mb = ( dsktotal_mb - dskused_mb );
345 132
346 if(allswaps && dsktotal_mb > 0){ 133 exit(data.statusCode);
347 percent = 100 * (((double) dskused_mb) / ((double) dsktotal_mb)); 134}
348 result = max_state (result, check_swap(dskfree_mb, dsktotal_mb));
349 if (verbose) {
350 xasprintf (&status, "%s [%.0f (%d%%)]", status, dskfree_mb, 100 - percent);
351 }
352 }
353 135
354 total_swap_mb += dsktotal_mb; 136int check_swap(float free_swap_mb, float total_swap_mb, swap_config config) {
355 free_swap_mb += dskfree_mb; 137 if (total_swap_mb == 0) {
356 used_swap_mb += dskused_mb; 138 return config.no_swap_state;
357 } 139 }
358 140
359 /* and clean up after ourselves */ 141 uint64_t free_swap = (uint64_t)(free_swap_mb * (1024 * 1024)); /* Convert back to bytes as warn and crit specified in bytes */
360 free(ent);
361
362# endif /* CHECK_SWAP_SWAPCTL_BSD */
363# endif /* CHECK_SWAP_SWAPCTL_SVR4 */
364# endif /* HAVE_SWAP */
365#endif /* HAVE_PROC_MEMINFO */
366 142
367 /* if total_swap_mb == 0, let's not divide by 0 */ 143 if (!config.crit.is_percentage && config.crit.value >= free_swap) {
368 if(total_swap_mb) { 144 return STATE_CRITICAL;
369 percent_used = 100 * ((double) used_swap_mb) / ((double) total_swap_mb); 145 }
370 } else { 146 if (!config.warn.is_percentage && config.warn.value >= free_swap) {
371 percent_used = 100; 147 return STATE_WARNING;
372 status = "- Swap is either disabled, not present, or of zero size. ";
373 } 148 }
374 149
375 result = max_state (result, check_swap(free_swap_mb, total_swap_mb)); 150 uint64_t usage_percentage = (uint64_t)((total_swap_mb - free_swap_mb) / total_swap_mb) * HUNDRED_PERCENT;
376 printf (_("SWAP %s - %d%% free (%dMB out of %dMB) %s|"),
377 state_text (result),
378 (100 - percent_used), (int) free_swap_mb, (int) total_swap_mb, status);
379 151
380 uint64_t warn_print = warn.value; 152 if (config.crit.is_percentage && config.crit.value != 0 && usage_percentage >= (HUNDRED_PERCENT - config.crit.value)) {
381 if (warn.is_percentage) warn_print = warn.value * (total_swap_mb *1024 *1024/100); 153 return STATE_CRITICAL;
382 uint64_t crit_print = crit.value; 154 }
383 if (crit.is_percentage) crit_print = crit.value * (total_swap_mb *1024 *1024/100);
384 155
385 puts (perfdata_uint64 ("swap", free_swap_mb *1024 *1024, "B", 156 if (config.warn.is_percentage && config.warn.value != 0 && usage_percentage >= (HUNDRED_PERCENT - config.warn.value)) {
386 true, warn_print, 157 return STATE_WARNING;
387 true, crit_print, 158 }
388 true, 0,
389 true, (long) total_swap_mb * 1024 * 1024));
390 159
391 return result; 160 return STATE_OK;
392} 161}
393 162
163/* process command-line arguments */
164swap_config_wrapper process_arguments(int argc, char **argv) {
165 swap_config_wrapper conf_wrapper = {.errorcode = OK};
166 conf_wrapper.config = swap_config_init();
394 167
395int 168 if (argc < 2) {
396check_swap(float free_swap_mb, float total_swap_mb) 169 conf_wrapper.errorcode = ERROR;
397{ 170 return conf_wrapper;
398 171 }
399 if (!total_swap_mb) return no_swap_state;
400
401 uint64_t free_swap = free_swap_mb * (1024 * 1024); /* Convert back to bytes as warn and crit specified in bytes */
402 uint64_t usage_percentage = ((total_swap_mb - free_swap_mb) / total_swap_mb) * 100;
403
404 if (warn.value || crit.value) { /* Thresholds defined */
405 if (!crit.is_percentage && crit.value >= free_swap) return STATE_CRITICAL;
406 if (!warn.is_percentage && warn.value >= free_swap) return STATE_WARNING;
407
408 if (crit.is_percentage &&
409 crit.value != 0 &&
410 usage_percentage >= (100 - crit.value))
411 {
412 return STATE_CRITICAL;
413 }
414
415 if (warn.is_percentage &&
416 warn.value != 0 &&
417 usage_percentage >= (100 - warn.value))
418 {
419 return STATE_WARNING;
420 }
421
422 return STATE_OK;
423 } else { /* Without thresholds */
424 return STATE_OK;
425 }
426}
427 172
173 static struct option longopts[] = {{"warning", required_argument, 0, 'w'}, {"critical", required_argument, 0, 'c'},
174 {"allswaps", no_argument, 0, 'a'}, {"no-swap", required_argument, 0, 'n'},
175 {"verbose", no_argument, 0, 'v'}, {"version", no_argument, 0, 'V'},
176 {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}};
428 177
178 while (true) {
179 int option = 0;
180 int option_char = getopt_long(argc, argv, "+?Vvhac:w:n:", longopts, &option);
429 181
430/* process command-line arguments */ 182 if (option_char == -1 || option_char == EOF) {
431int
432process_arguments (int argc, char **argv)
433{
434 int c = 0; /* option character */
435
436 int option = 0;
437 static struct option longopts[] = {
438 {"warning", required_argument, 0, 'w'},
439 {"critical", required_argument, 0, 'c'},
440 {"allswaps", no_argument, 0, 'a'},
441 {"no-swap", required_argument, 0, 'n'},
442 {"verbose", no_argument, 0, 'v'},
443 {"version", no_argument, 0, 'V'},
444 {"help", no_argument, 0, 'h'},
445 {0, 0, 0, 0}
446 };
447
448 while (1) {
449 c = getopt_long (argc, argv, "+?Vvhac:w:n:", longopts, &option);
450
451 if (c == -1 || c == EOF)
452 break; 183 break;
184 }
453 185
454 switch (c) { 186 switch (option_char) {
455 case 'w': /* warning size threshold */ 187 case 'w': /* warning size threshold */
456 { 188 {
457 /* 189 /*
458 * We expect either a positive integer value without a unit, which means 190 * We expect either a positive integer value without a unit, which
459 * the unit is Bytes or a positive integer value and a percentage sign (%), 191 * means the unit is Bytes or a positive integer value and a
460 * which means the value must be with 0 and 100 and is relative to the total swap 192 * percentage sign (%), which means the value must be with 0 and 100
461 */ 193 * and is relative to the total swap
462 size_t length; 194 */
463 length = strlen(optarg); 195 size_t length;
464 196 length = strlen(optarg);
465 if (optarg[length - 1] == '%') { 197
466 /* It's percentage */ 198 if (optarg[length - 1] == '%') {
467 warn.is_percentage = true; 199 /* It's percentage */
468 optarg[length - 1] = '\0'; 200 conf_wrapper.config.warn.is_percentage = true;
469 if (is_uint64(optarg, &warn.value)) { 201 optarg[length - 1] = '\0';
470 if (warn.value > 100) { 202 if (is_uint64(optarg, &conf_wrapper.config.warn.value)) {
471 usage4 (_("Warning threshold percentage must be <= 100!")); 203 if (conf_wrapper.config.warn.value > HUNDRED_PERCENT) {
472 } 204 usage4(_("Warning threshold percentage must be <= 100!"));
473 }
474 break;
475 } else {
476 /* It's Bytes */
477 warn.is_percentage = false;
478 if (is_uint64(optarg, &warn.value)) {
479 break;
480 } else {
481 usage4 (_("Warning threshold be positive integer or percentage!"));
482 } 205 }
483 } 206 }
207 break;
208 } /* It's Bytes */
209 conf_wrapper.config.warn.is_percentage = false;
210 if (is_uint64(optarg, &conf_wrapper.config.warn.value)) {
211 break;
484 } 212 }
213 usage4(_("Warning threshold be positive integer or "
214 "percentage!"));
215 }
485 case 'c': /* critical size threshold */ 216 case 'c': /* critical size threshold */
486 { 217 {
487 /* 218 /*
488 * We expect either a positive integer value without a unit, which means 219 * We expect either a positive integer value without a unit, which
489 * the unit is Bytes or a positive integer value and a percentage sign (%), 220 * means the unit is Bytes or a positive integer value and a
490 * which means the value must be with 0 and 100 and is relative to the total swap 221 * percentage sign (%), which means the value must be with 0 and 100
491 */ 222 * and is relative to the total swap
492 size_t length; 223 */
493 length = strlen(optarg); 224 size_t length;
494 225 length = strlen(optarg);
495 if (optarg[length - 1] == '%') { 226
496 /* It's percentage */ 227 if (optarg[length - 1] == '%') {
497 crit.is_percentage = true; 228 /* It's percentage */
498 optarg[length - 1] = '\0'; 229 conf_wrapper.config.crit.is_percentage = true;
499 if (is_uint64(optarg, &crit.value)) { 230 optarg[length - 1] = '\0';
500 if (crit.value> 100) { 231 if (is_uint64(optarg, &conf_wrapper.config.crit.value)) {
501 usage4 (_("Critical threshold percentage must be <= 100!")); 232 if (conf_wrapper.config.crit.value > HUNDRED_PERCENT) {
502 } 233 usage4(_("Critical threshold percentage must be <= 100!"));
503 }
504 break;
505 } else {
506 /* It's Bytes */
507 crit.is_percentage = false;
508 if (is_uint64(optarg, &crit.value)) {
509 break;
510 } else {
511 usage4 (_("Critical threshold be positive integer or percentage!"));
512 } 234 }
513 } 235 }
514 } 236 break;
515 case 'a': /* all swap */ 237 } /* It's Bytes */
516 allswaps = true; 238 conf_wrapper.config.crit.is_percentage = false;
239 if (is_uint64(optarg, &conf_wrapper.config.crit.value)) {
240 break;
241 }
242 usage4(_("Critical threshold be positive integer or "
243 "percentage!"));
244 }
245 case 'a': /* all swap */
246 conf_wrapper.config.allswaps = true;
517 break; 247 break;
518 case 'n': 248 case 'n':
519 if ((no_swap_state = mp_translate_state(optarg)) == ERROR) { 249 if ((conf_wrapper.config.no_swap_state = mp_translate_state(optarg)) == ERROR) {
520 usage4 (_("no-swap result must be a valid state name (OK, WARNING, CRITICAL, UNKNOWN) or integer (0-3).")); 250 usage4(_("no-swap result must be a valid state name (OK, "
251 "WARNING, CRITICAL, UNKNOWN) or integer (0-3)."));
521 } 252 }
522 break; 253 break;
523 case 'v': /* verbose */ 254 case 'v': /* verbose */
524 verbose++; 255 verbose++;
525 break; 256 break;
526 case 'V': /* version */ 257 case 'V': /* version */
527 print_revision (progname, NP_VERSION); 258 print_revision(progname, NP_VERSION);
528 exit (STATE_UNKNOWN); 259 exit(STATE_UNKNOWN);
529 case 'h': /* help */ 260 case 'h': /* help */
530 print_help (); 261 print_help(conf_wrapper.config);
531 exit (STATE_UNKNOWN); 262 exit(STATE_UNKNOWN);
532 case '?': /* error */ 263 case '?': /* error */
533 usage5 (); 264 usage5();
534 } 265 }
535 } 266 }
536 267
537 c = optind; 268 if (conf_wrapper.config.warn.value == 0 && conf_wrapper.config.crit.value == 0) {
538 if (c == argc) 269 conf_wrapper.errorcode = ERROR;
539 return validate_arguments (); 270 return conf_wrapper;
540 271 }
541 return validate_arguments (); 272 if ((conf_wrapper.config.warn.is_percentage == conf_wrapper.config.crit.is_percentage) &&
542} 273 (conf_wrapper.config.warn.value < conf_wrapper.config.crit.value)) {
543 274 /* This is NOT triggered if warn and crit are different units, e.g warn
544 275 * is percentage and crit is absolute. We cannot determine the condition
545 276 * at this point since we dont know the value of total swap yet
546int
547validate_arguments (void)
548{
549 if ((warn.is_percentage == crit.is_percentage) && (warn.value < crit.value)) {
550 /* This is NOT triggered if warn and crit are different units, e.g warn is percentage
551 * and crit is absolute. We cannot determine the condition at this point since we
552 * dont know the value of total swap yet
553 */ 277 */
554 usage4(_("Warning should be more than critical")); 278 usage4(_("Warning should be more than critical"));
555 } 279 }
556 return OK;
557}
558
559 280
560 281 return conf_wrapper;
561void
562print_help (void)
563{
564 print_revision (progname, NP_VERSION);
565
566 printf (_(COPYRIGHT), copyright, email);
567
568 printf ("%s\n", _("Check swap space on local machine."));
569
570 printf ("\n\n");
571
572 print_usage ();
573
574 printf (UT_HELP_VRSN);
575 printf (UT_EXTRA_OPTS);
576
577 printf (" %s\n", "-w, --warning=INTEGER");
578 printf (" %s\n", _("Exit with WARNING status if less than INTEGER bytes of swap space are free"));
579 printf (" %s\n", "-w, --warning=PERCENT%");
580 printf (" %s\n", _("Exit with WARNING status if less than PERCENT of swap space is free"));
581 printf (" %s\n", "-c, --critical=INTEGER");
582 printf (" %s\n", _("Exit with CRITICAL status if less than INTEGER bytes of swap space are free"));
583 printf (" %s\n", "-c, --critical=PERCENT%");
584 printf (" %s\n", _("Exit with CRITICAL status if less than PERCENT of swap space is free"));
585 printf (" %s\n", "-a, --allswaps");
586 printf (" %s\n", _("Conduct comparisons for all swap partitions, one by one"));
587 printf (" %s\n", "-n, --no-swap=<ok|warning|critical|unknown>");
588 printf (" %s %s\n", _("Resulting state when there is no swap regardless of thresholds. Default:"), state_text(no_swap_state));
589 printf (UT_VERBOSE);
590
591 printf ("\n");
592 printf ("%s\n", _("Notes:"));
593 printf (" %s\n", _("Both INTEGER and PERCENT thresholds can be specified, they are all checked."));
594 printf (" %s\n", _("Without thresholds, the plugin shows free swap space and performance data, but always returns OK."));
595 printf (" %s\n", _("On AIX, if -a is specified, uses lsps -a, otherwise uses lsps -s."));
596
597 printf (UT_SUPPORT);
598} 282}
599 283
284void print_help(swap_config config) {
285 print_revision(progname, NP_VERSION);
286
287 printf(_(COPYRIGHT), copyright, email);
288
289 printf("%s\n", _("Check swap space on local machine."));
290
291 printf("\n\n");
292
293 print_usage();
294
295 printf(UT_HELP_VRSN);
296 printf(UT_EXTRA_OPTS);
297
298 printf(" %s\n", "-w, --warning=INTEGER");
299 printf(" %s\n", _("Exit with WARNING status if less than INTEGER bytes "
300 "of swap space are free"));
301 printf(" %s\n", "-w, --warning=PERCENT%");
302 printf(" %s\n", _("Exit with WARNING status if less than PERCENT of "
303 "swap space is free"));
304 printf(" %s\n", "-c, --critical=INTEGER");
305 printf(" %s\n", _("Exit with CRITICAL status if less than INTEGER bytes "
306 "of swap space are free"));
307 printf(" %s\n", "-c, --critical=PERCENT%");
308 printf(" %s\n", _("Exit with CRITICAL status if less than PERCENT of "
309 "swap space is free"));
310 printf(" %s\n", "-a, --allswaps");
311 printf(" %s\n", _("Conduct comparisons for all swap partitions, one by one"));
312 printf(" %s\n", "-n, --no-swap=<ok|warning|critical|unknown>");
313 printf(" %s %s\n",
314 _("Resulting state when there is no swap regardless of thresholds. "
315 "Default:"),
316 state_text(config.no_swap_state));
317 printf(UT_VERBOSE);
318
319 printf("\n");
320 printf("%s\n", _("Notes:"));
321 printf(" %s\n", _("Both INTEGER and PERCENT thresholds can be specified, "
322 "they are all checked."));
323 printf(" %s\n", _("On AIX, if -a is specified, uses lsps -a, otherwise uses lsps -s."));
324
325 printf(UT_SUPPORT);
326}
600 327
601void 328void print_usage(void) {
602print_usage (void) 329 printf("%s\n", _("Usage:"));
603{ 330 printf(" %s [-av] -w <percent_free>%% -c <percent_free>%%\n", progname);
604 printf ("%s\n", _("Usage:")); 331 printf(" -w <bytes_free> -c <bytes_free> [-n <state>]\n");
605 printf (" %s [-av] [-w <percent_free>%%] [-c <percent_free>%%]\n",progname);
606 printf (" [-w <bytes_free>] [-c <bytes_free>] [-n <state>]\n");
607} 332}
diff --git a/plugins/check_swap.d/check_swap.h b/plugins/check_swap.d/check_swap.h
new file mode 100644
index 00000000..9e8be75f
--- /dev/null
+++ b/plugins/check_swap.d/check_swap.h
@@ -0,0 +1,44 @@
1#ifndef CHECK_SWAP_H
2#define CHECK_SWAP_H
3
4#include "../common.h"
5
6#ifndef SWAP_CONVERSION
7# define SWAP_CONVERSION 1
8#endif
9
10typedef struct {
11 bool is_percentage;
12 uint64_t value;
13} threshold;
14
15typedef struct {
16 unsigned long long free; // Free swap in Bytes!
17 unsigned long long used; // Used swap in Bytes!
18 unsigned long long total; // Total swap size, you guessed it, in Bytes!
19} swap_metrics;
20
21typedef struct {
22 int errorcode;
23 int statusCode;
24 swap_metrics metrics;
25} swap_result;
26
27typedef struct {
28 bool allswaps;
29 int no_swap_state;
30 threshold warn;
31 threshold crit;
32 bool on_aix;
33 int conversion_factor;
34} swap_config;
35
36swap_config swap_config_init(void);
37
38swap_result get_swap_data(swap_config config);
39swap_result getSwapFromProcMeminfo(char path_to_proc_meminfo[]);
40swap_result getSwapFromSwapCommand(swap_config config, const char swap_command[], const char swap_format[]);
41swap_result getSwapFromSwapctl_BSD(swap_config config);
42swap_result getSwapFromSwap_SRV4(swap_config config);
43
44#endif
diff --git a/plugins/check_swap.d/swap.c b/plugins/check_swap.d/swap.c
new file mode 100644
index 00000000..d437ba59
--- /dev/null
+++ b/plugins/check_swap.d/swap.c
@@ -0,0 +1,412 @@
1#include "./check_swap.d/check_swap.h"
2#include "../popen.h"
3#include "../utils.h"
4
5extern int verbose;
6
7swap_config swap_config_init(void) {
8 swap_config tmp = {0};
9 tmp.allswaps = false;
10 tmp.no_swap_state = STATE_CRITICAL;
11 tmp.conversion_factor = SWAP_CONVERSION;
12
13#ifdef _AIX
14 tmp.on_aix = true;
15#else
16 tmp.on_aix = false;
17#endif
18
19 return tmp;
20}
21
22swap_result get_swap_data(swap_config config) {
23#ifdef HAVE_PROC_MEMINFO
24 if (verbose >= 3) {
25 printf("Reading PROC_MEMINFO at %s\n", PROC_MEMINFO);
26 }
27
28 return getSwapFromProcMeminfo(PROC_MEMINFO);
29#else
30# ifdef HAVE_SWAP
31 if (verbose >= 3) {
32 printf("Using swap command %s with format: %s\n", SWAP_COMMAND, SWAP_FORMAT);
33 }
34
35 /* These override the command used if a summary (and thus ! allswaps) is
36 * required
37 * The summary flag returns more accurate information about swap usage on these
38 * OSes */
39 if (config.on_aix && !config.allswaps) {
40
41 config.conversion_factor = 1;
42
43 return getSwapFromSwapCommand(config, "/usr/sbin/lsps -s", "%lu%*s %lu");
44 } else {
45 return getSwapFromSwapCommand(config, SWAP_COMMAND, SWAP_FORMAT);
46 }
47# else
48# ifdef CHECK_SWAP_SWAPCTL_SVR4
49 return getSwapFromSwapctl_SRV4();
50# else
51# ifdef CHECK_SWAP_SWAPCTL_BSD
52 return getSwapFromSwapctl_BSD();
53# else
54# error No way found to retrieve swap
55# endif /* CHECK_SWAP_SWAPCTL_BSD */
56# endif /* CHECK_SWAP_SWAPCTL_SVR4 */
57# endif /* HAVE_SWAP */
58#endif /* HAVE_PROC_MEMINFO */
59}
60
61swap_result getSwapFromProcMeminfo(char proc_meminfo[]) {
62 FILE *fp;
63 fp = fopen(proc_meminfo, "r");
64
65 swap_result result = {0};
66 result.statusCode = STATE_OK;
67
68 uint64_t swap_total = 0, swap_used = 0, swap_free = 0;
69
70 char input_buffer[MAX_INPUT_BUFFER];
71 char str[32];
72
73 while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, fp)) {
74 uint64_t tmp_KB = 0;
75
76 /*
77 * The following sscanf call looks for a line looking like: "Swap: 123
78 * 123 123" On which kind of system this format exists, I can not say,
79 * but I wanted to document this for people who are not adapt with
80 * sscanf anymore, like me
81 * Also the units used here are unclear and probably wrong
82 */
83 if (sscanf(input_buffer, "%*[S]%*[w]%*[a]%*[p]%*[:] %lu %lu %lu", &swap_total, &swap_used, &swap_free) == 3) {
84
85 result.metrics.total += swap_total;
86 result.metrics.used += swap_used;
87 result.metrics.free += swap_free;
88
89 /*
90 * The following sscanf call looks for lines looking like:
91 * "SwapTotal: 123" and "SwapFree: 123" This format exists at least
92 * on Debian Linux with a 5.* kernel
93 */
94 } else if (sscanf(input_buffer,
95 "%*[S]%*[w]%*[a]%*[p]%[TotalFreCchd]%*[:] %lu "
96 "%*[k]%*[B]",
97 str, &tmp_KB)) {
98
99 if (verbose >= 3) {
100 printf("Got %s with %lu\n", str, tmp_KB);
101 }
102
103 /* I think this part is always in Kb, so convert to bytes */
104 if (strcmp("Total", str) == 0) {
105 swap_total = tmp_KB * 1024;
106 } else if (strcmp("Free", str) == 0) {
107 swap_free = swap_free + tmp_KB * 1024;
108 } else if (strcmp("Cached", str) == 0) {
109 swap_free = swap_free + tmp_KB * 1024;
110 }
111 }
112 }
113
114 fclose(fp);
115
116 result.metrics.total = swap_total;
117 result.metrics.used = swap_total - swap_free;
118 result.metrics.free = swap_free;
119
120 return result;
121}
122
123swap_result getSwapFromSwapCommand(swap_config config, const char swap_command[], const char swap_format[]) {
124 swap_result result = {0};
125
126 char *temp_buffer;
127
128 if (verbose >= 2)
129 printf(_("Command: %s\n"), swap_command);
130 if (verbose >= 3)
131 printf(_("Format: %s\n"), swap_format);
132
133 child_process = spopen(swap_command);
134 if (child_process == NULL) {
135 printf(_("Could not open pipe: %s\n"), swap_command);
136 swap_result tmp = {
137 .errorcode = STATE_UNKNOWN,
138 };
139 return tmp;
140 }
141
142 child_stderr = fdopen(child_stderr_array[fileno(child_process)], "r");
143 if (child_stderr == NULL) {
144 printf(_("Could not open stderr for %s\n"), swap_command);
145 }
146
147 char str[32] = {0};
148 char input_buffer[MAX_INPUT_BUFFER];
149
150 /* read 1st line */
151 fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process);
152 if (strcmp(swap_format, "") == 0) {
153 temp_buffer = strtok(input_buffer, " \n");
154 while (temp_buffer) {
155 if (strstr(temp_buffer, "blocks"))
156 sprintf(str, "%s %s", str, "%lu");
157 else if (strstr(temp_buffer, "dskfree"))
158 sprintf(str, "%s %s", str, "%lu");
159 else
160 sprintf(str, "%s %s", str, "%*s");
161 temp_buffer = strtok(NULL, " \n");
162 }
163 }
164
165 double total_swap_mb = 0, free_swap_mb = 0, used_swap_mb = 0;
166 double dsktotal_mb = 0, dskused_mb = 0, dskfree_mb = 0;
167
168 /*
169 * If different swap command is used for summary switch, need to read format
170 * differently
171 */
172 if (config.on_aix && !config.allswaps) {
173 fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process); /* Ignore first line */
174 sscanf(input_buffer, swap_format, &total_swap_mb, &used_swap_mb);
175 free_swap_mb = total_swap_mb * (100 - used_swap_mb) / 100;
176 used_swap_mb = total_swap_mb - free_swap_mb;
177
178 if (verbose >= 3) {
179 printf(_("total=%.0f, used=%.0f, free=%.0f\n"), total_swap_mb, used_swap_mb, free_swap_mb);
180 }
181 } else {
182 while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_process)) {
183 sscanf(input_buffer, swap_format, &dsktotal_mb, &dskfree_mb);
184
185 dsktotal_mb = dsktotal_mb / config.conversion_factor;
186 /* AIX lists percent used, so this converts to dskfree in MBs */
187
188 if (config.on_aix) {
189 dskfree_mb = dsktotal_mb * (100 - dskfree_mb) / 100;
190 } else {
191 dskfree_mb = dskfree_mb / config.conversion_factor;
192 }
193
194 if (verbose >= 3)
195 printf(_("total=%.0f, free=%.0f\n"), dsktotal_mb, dskfree_mb);
196
197 dskused_mb = dsktotal_mb - dskfree_mb;
198 total_swap_mb += dsktotal_mb;
199 used_swap_mb += dskused_mb;
200 free_swap_mb += dskfree_mb;
201 }
202 }
203
204 result.metrics.free = free_swap_mb * 1024 * 1024;
205 result.metrics.used = used_swap_mb * 1024 * 1024;
206 result.metrics.total = free_swap_mb * 1024 * 1024;
207
208 /* If we get anything on STDERR, at least set warning */
209 while (fgets(input_buffer, MAX_INPUT_BUFFER - 1, child_stderr)) {
210 result.statusCode = max_state(result.statusCode, STATE_WARNING);
211 // TODO Set error here
212 }
213
214 /* close stderr */
215 (void)fclose(child_stderr);
216
217 /* close the pipe */
218 if (spclose(child_process)) {
219 result.statusCode = max_state(result.statusCode, STATE_WARNING);
220 // TODO set error here
221 }
222
223 return result;
224}
225
226#ifndef CHECK_SWAP_SWAPCTL_BSD
227# define CHECK_SWAP_SWAPCTL_BSD
228
229// Stub functionality for BSD stuff, so the compiler always sees the following BSD code
230
231# define SWAP_NSWAP 0
232# define SWAP_STATS 1
233
234int bsd_swapctl(int cmd, const void *arg, int misc) {
235 (void)cmd;
236 (void)arg;
237 (void)misc;
238 return 512;
239}
240
241struct swapent {
242 dev_t se_dev; /* device id */
243 int se_flags; /* entry flags */
244 int se_nblks; /* total blocks */
245 int se_inuse; /* blocks in use */
246 int se_priority; /* priority */
247 char se_path[PATH_MAX]; /* path to entry */
248};
249
250#else
251# define bsd_swapctl swapctl
252#endif
253
254swap_result getSwapFromSwapctl_BSD(swap_config config) {
255 /* get the number of active swap devices */
256 int nswaps = bsd_swapctl(SWAP_NSWAP, NULL, 0);
257
258 /* initialize swap table + entries */
259 struct swapent *ent = (struct swapent *)malloc(sizeof(struct swapent) * nswaps);
260
261 /* and now, tally 'em up */
262 int swapctl_res = bsd_swapctl(SWAP_STATS, ent, nswaps);
263 if (swapctl_res < 0) {
264 perror(_("swapctl failed: "));
265 die(STATE_UNKNOWN, _("Error in swapctl call\n"));
266 }
267
268 double dsktotal_mb = 0.0, dskfree_mb = 0.0, dskused_mb = 0.0;
269 unsigned long long total_swap_mb = 0, free_swap_mb = 0, used_swap_mb = 0;
270
271 for (int i = 0; i < nswaps; i++) {
272 dsktotal_mb = (float)ent[i].se_nblks / config.conversion_factor;
273 dskused_mb = (float)ent[i].se_inuse / config.conversion_factor;
274 dskfree_mb = (dsktotal_mb - dskused_mb);
275
276 if (config.allswaps && dsktotal_mb > 0) {
277 double percent = 100 * (((double)dskused_mb) / ((double)dsktotal_mb));
278
279 if (verbose) {
280 printf("[%.0f (%g%%)]", dskfree_mb, 100 - percent);
281 }
282 }
283
284 total_swap_mb += dsktotal_mb;
285 free_swap_mb += dskfree_mb;
286 used_swap_mb += dskused_mb;
287 }
288
289 /* and clean up after ourselves */
290 free(ent);
291
292 swap_result result = {0};
293
294 result.statusCode = OK;
295 result.errorcode = OK;
296
297 result.metrics.total = total_swap_mb * 1024 * 1024;
298 result.metrics.free = free_swap_mb * 1024 * 1024;
299 result.metrics.used = used_swap_mb * 1024 * 1024;
300
301 return result;
302}
303
304#ifndef CHECK_SWAP_SWAPCTL_SVR4
305int srv4_swapctl(int cmd, void *arg) {
306 (void)cmd;
307 (void)arg;
308 return 512;
309}
310
311typedef struct srv4_swapent {
312 char *ste_path; /* name of the swap file */
313 off_t ste_start; /* starting block for swapping */
314 off_t ste_length; /* length of swap area */
315 long ste_pages; /* number of pages for swapping */
316 long ste_free; /* number of ste_pages free */
317 long ste_flags; /* ST_INDEL bit set if swap file */
318 /* is now being deleted */
319} swapent_t;
320
321typedef struct swaptbl {
322 int swt_n; /* number of swapents following */
323 struct srv4_swapent swt_ent[]; /* array of swt_n swapents */
324} swaptbl_t;
325
326# define SC_LIST 2
327# define SC_GETNSWP 3
328
329# ifndef MAXPATHLEN
330# define MAXPATHLEN 2048
331# endif
332
333#else
334# define srv4_swapctl swapctl
335#endif
336
337swap_result getSwapFromSwap_SRV4(swap_config config) {
338 int nswaps = 0;
339
340 /* get the number of active swap devices */
341 if ((nswaps = srv4_swapctl(SC_GETNSWP, NULL)) == -1)
342 die(STATE_UNKNOWN, _("Error getting swap devices\n"));
343
344 if (nswaps == 0)
345 die(STATE_OK, _("SWAP OK: No swap devices defined\n"));
346
347 if (verbose >= 3)
348 printf("Found %d swap device(s)\n", nswaps);
349
350 /* initialize swap table + entries */
351 swaptbl_t *tbl = (swaptbl_t *)malloc(sizeof(swaptbl_t) + (sizeof(swapent_t) * nswaps));
352
353 if (tbl == NULL)
354 die(STATE_UNKNOWN, _("malloc() failed!\n"));
355
356 memset(tbl, 0, sizeof(swaptbl_t) + (sizeof(swapent_t) * nswaps));
357 tbl->swt_n = nswaps;
358
359 for (int i = 0; i < nswaps; i++) {
360 if ((tbl->swt_ent[i].ste_path = (char *)malloc(sizeof(char) * MAXPATHLEN)) == NULL)
361 die(STATE_UNKNOWN, _("malloc() failed!\n"));
362 }
363
364 /* and now, tally 'em up */
365 int swapctl_res = srv4_swapctl(SC_LIST, tbl);
366 if (swapctl_res < 0) {
367 perror(_("swapctl failed: "));
368 die(STATE_UNKNOWN, _("Error in swapctl call\n"));
369 }
370
371 double dsktotal_mb = 0.0;
372 double dskfree_mb = 0.0;
373 double dskused_mb = 0.0;
374 unsigned long long total_swap_mb = 0;
375 unsigned long long free_swap_mb = 0;
376 unsigned long long used_swap_mb = 0;
377
378 for (int i = 0; i < nswaps; i++) {
379 dsktotal_mb = (float)tbl->swt_ent[i].ste_pages / SWAP_CONVERSION;
380 dskfree_mb = (float)tbl->swt_ent[i].ste_free / SWAP_CONVERSION;
381 dskused_mb = (dsktotal_mb - dskfree_mb);
382
383 if (verbose >= 3)
384 printf("dsktotal_mb=%.0f dskfree_mb=%.0f dskused_mb=%.0f\n", dsktotal_mb, dskfree_mb, dskused_mb);
385
386 if (config.allswaps && dsktotal_mb > 0) {
387 double percent = 100 * (((double)dskused_mb) / ((double)dsktotal_mb));
388
389 if (verbose) {
390 printf("[%.0f (%g%%)]", dskfree_mb, 100 - percent);
391 }
392 }
393
394 total_swap_mb += dsktotal_mb;
395 free_swap_mb += dskfree_mb;
396 used_swap_mb += dskused_mb;
397 }
398
399 /* and clean up after ourselves */
400 for (int i = 0; i < nswaps; i++) {
401 free(tbl->swt_ent[i].ste_path);
402 }
403 free(tbl);
404
405 swap_result result = {0};
406 result.errorcode = OK;
407 result.metrics.total = total_swap_mb * 1024 * 1024;
408 result.metrics.free = free_swap_mb * 1024 * 1024;
409 result.metrics.used = used_swap_mb * 1024 * 1024;
410
411 return result;
412}
diff --git a/plugins/tests/test_check_swap.c b/plugins/tests/test_check_swap.c
new file mode 100644
index 00000000..319cadbf
--- /dev/null
+++ b/plugins/tests/test_check_swap.c
@@ -0,0 +1,23 @@
1
2#include "../check_swap.d/check_swap.h"
3#include "../../tap/tap.h"
4
5void print_usage() {};
6void print_help(swap_config config) {
7 (void) config;
8};
9
10const char *progname = "test_check_swap";
11
12int main() {
13 swap_config config = swap_config_init();
14
15 swap_result test_data = getSwapFromProcMeminfo(config, "./var/proc_meminfo");
16
17 plan_tests(4);
18
19 ok(test_data.errorcode == 0, "Test whether we manage to retrieve swap data");
20 ok(test_data.metrics.total == 34233905152, "Is the total Swap correct");
21 ok(test_data.metrics.free == 34233905152, "Is the free Swap correct");
22 ok(test_data.metrics.used == 0, "Is the used Swap correct");
23}
diff --git a/plugins/tests/test_check_swap.t b/plugins/tests/test_check_swap.t
new file mode 100755
index 00000000..826fae01
--- /dev/null
+++ b/plugins/tests/test_check_swap.t
@@ -0,0 +1,6 @@
1#!/usr/bin/perl
2use Test::More;
3if (! -e "./test_check_swap") {
4 plan skip_all => "./test_check_swap not compiled - please enable libtap library to test";
5}
6exec "./test_check_swap";
diff --git a/plugins/tests/var/proc_meminfo b/plugins/tests/var/proc_meminfo
new file mode 100644
index 00000000..6c5a618d
--- /dev/null
+++ b/plugins/tests/var/proc_meminfo
@@ -0,0 +1,55 @@
1MemTotal: 32767776 kB
2MemFree: 1693508 kB
3MemAvailable: 23807480 kB
4Buffers: 438456 kB
5Cached: 19124976 kB
6SwapCached: 0 kB
7Active: 7860680 kB
8Inactive: 18886776 kB
9Active(anon): 6108756 kB
10Inactive(anon): 1364500 kB
11Active(file): 1751924 kB
12Inactive(file): 17522276 kB
13Unevictable: 8548 kB
14Mlocked: 8548 kB
15SwapTotal: 33431548 kB
16SwapFree: 33431548 kB
17Zswap: 0 kB
18Zswapped: 0 kB
19Dirty: 784 kB
20Writeback: 0 kB
21AnonPages: 7139968 kB
22Mapped: 1094916 kB
23Shmem: 284160 kB
24KReclaimable: 3303788 kB
25Slab: 3801908 kB
26SReclaimable: 3303788 kB
27SUnreclaim: 498120 kB
28KernelStack: 32992 kB
29PageTables: 68160 kB
30SecPageTables: 0 kB
31NFS_Unstable: 0 kB
32Bounce: 0 kB
33WritebackTmp: 0 kB
34CommitLimit: 49815436 kB
35Committed_AS: 16888536 kB
36VmallocTotal: 34359738367 kB
37VmallocUsed: 91200 kB
38VmallocChunk: 0 kB
39Percpu: 41472 kB
40HardwareCorrupted: 0 kB
41AnonHugePages: 1708032 kB
42ShmemHugePages: 0 kB
43ShmemPmdMapped: 0 kB
44FileHugePages: 0 kB
45FilePmdMapped: 0 kB
46Unaccepted: 0 kB
47HugePages_Total: 0
48HugePages_Free: 0
49HugePages_Rsvd: 0
50HugePages_Surp: 0
51Hugepagesize: 2048 kB
52Hugetlb: 0 kB
53DirectMap4k: 860468 kB
54DirectMap2M: 20023296 kB
55DirectMap1G: 12582912 kB