Debian Codegraph @

madrisan-nagios-plugins-linux/nagios-plugins-linux/plugins/check_cpu.c

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-3.0-or-later
2 /*
3 * License: GPLv3+
4 * Copyright (c) 2014,2015,2020,2022 Davide Madrisan <[email protected]>
5 *
6 * A Nagios plugin to check the CPU utilization.
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 3 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, see <http://www.gnu.org/licenses/>.
20 *
21 * This software is based on the source code of the tool "vmstat".
22 */
23
24 /* Definition of I/O wait time:
25 * The I/O wait time is the time during which a CPU was idle and
26 * there was at least one outstanding (disk or network) I/O operation
27 * requested by a task scheduled on that CPU. */
28
29 #include <ctype.h>
30 #include <getopt.h>
31 #include <limits.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36
37 #include "common.h"
38 #include "cpudesc.h"
39 #include "cpufreq.h"
40 #include "cpustats.h"
41 #include "cputopology.h"
42 #include "logging.h"
43 #include "messages.h"
44 #include "progname.h"
45 #include "progversion.h"
46 #include "thresholds.h"
47 #include "string-macros.h"
48 #include "sysfsparser.h"
49 #include "system.h"
50 #include "xalloc.h"
51 #include "xasprintf.h"
52 #include "xstrton.h"
53
54 static const char *program_copyright =
55 "Copyright (C) 2014,2015,2020,2022 Davide Madrisan <" PACKAGE_BUGREPORT ">\n";
56
57 static const char *program_shorthelp = NULL;
58
59 static struct option const longopts[] = {
60 {(char *) "cpuinfo", no_argument, NULL, 'i'},
61 {(char *) "no-cpu-model", no_argument, NULL, 'm'},
62 {(char *) "per-cpu", no_argument, NULL, 'p'},
63 {(char *) "critical", required_argument, NULL, 'c'},
64 {(char *) "warning", required_argument, NULL, 'w'},
65 {(char *) "verbose", no_argument, NULL, 'v'},
66 {(char *) "help", no_argument, NULL, GETOPT_HELP_CHAR},
67 {(char *) "version", no_argument, NULL, GETOPT_VERSION_CHAR},
68 {NULL, 0, NULL, 0}
69 };
70
71 static _Noreturn void
72 usage (FILE * out)
73 {
74 fprintf (out, "%s (" PACKAGE_NAME ") v%s\n", program_name, program_version);
75 fputs (program_shorthelp, out);
76 fputs (program_copyright, out);
77 fputs (USAGE_HEADER, out);
78 fprintf (out, " %s [-v] [-m] [-p] [-w PERC] [-c PERC] [delay [count]]\n",
79 program_name);
80 fprintf (out, " %s --cpuinfo\n", program_name);
81 fputs (USAGE_OPTIONS, out);
82 fputs (" -m, --no-cpu-model "
83 "do not display the CPU model in the output message\n", out);
84 fputs (" -p, --per-cpu display the utilization of each CPU\n", out);
85 fputs (" -w, --warning PERCENT warning threshold\n", out);
86 fputs (" -c, --critical PERCENT critical threshold\n", out);
87 fputs (" -v, --verbose show details for command-line debugging "
88 "(Nagios may truncate output)\n", out);
89 fputs (" -i, --cpuinfo show the CPU characteristics (for debugging)\n",
90 out);
91 fputs (USAGE_HELP, out);
92 fputs (USAGE_VERSION, out);
93 fprintf (out, " delay is the delay between updates in seconds "
94 "(default: %dsec)\n", DELAY_DEFAULT);
95 fprintf (out, " count is the number of updates "
96 "(default: %d)\n", COUNT_DEFAULT);
97 fputs ("\t1 means the percentages of total CPU time from boottime.\n", out);
98 fputs (USAGE_EXAMPLES, out);
99 fprintf (out, " %s -m -p -w 85%% -c 95%%\n", program_name);
100 fprintf (out, " %s -w 85%% -c 95%% 1 2\n", program_name);
101 fprintf (out, " %s --cpuinfo\n", program_name);
102
103 exit (out == stderr ? STATE_UNKNOWN : STATE_OK);
104 }
105
106 static _Noreturn void
107 print_version (void)
108 {
109 printf ("%s (" PACKAGE_NAME ") v%s\n", program_name, program_version);
110 fputs (program_copyright, stdout);
111 fputs (GPLv3_DISCLAIMER, stdout);
112
113 exit (STATE_OK);
114 }
115
116 /* output formats "<key>: <value>" */
117 #define print_d(_key, _val) printf ("%-30s%d\n", _key, _val)
118 #define print_u(_key, _val) printf ("%-30s%u\n", _key, _val)
119 #define print_s(_key, _val) printf ("%-30s%s\n", _key, _val)
120 #define print_key_s(_key) printf ("%-30s", _key)
121 #define print_range_s(_key, _val1, _val2) \
122 printf ("%-30s%s - %s\n", _key, _val1, _val2)
123
124 static void cpu_desc_summary (struct cpu_desc *cpudesc)
125 {
126 printf ("-= CPU Characteristics =-\n");
127
128 print_s("Architecture:", cpu_desc_get_architecture (cpudesc));
129
130 int cpu_mode = cpu_desc_get_mode (cpudesc);
131 if (cpu_mode)
132 {
133 char mbuf[32], *p = mbuf;
134 if (cpu_mode & MODE_32BIT)
135 {
136 strcpy (p, "32-bit, ");
137 p += 8;
138 }
139 if (cpu_mode & MODE_64BIT)
140 {
141 strcpy (p, "64-bit, ");
142 p += 8;
143 }
144 *(p - 2) = '\0';
145
146 print_s("CPU op-mode(s):", mbuf);
147 }
148
149 #if !defined(WORDS_BIGENDIAN)
150 print_s("Byte Order:", "Little Endian");
151 #else
152 print_s("Byte Order:", "Big Endian");
153 #endif
154
155 int cpu, ncpus = cpu_desc_get_ncpus (cpudesc);
156
157 print_d("CPU(s):", ncpus);
158
159 unsigned int nsockets, ncores, nthreads;
160 get_cputopology_read (&nsockets, &ncores, &nthreads);
161
162 print_u("Thread(s) per core:", nthreads);
163 print_u("Core(s) per socket:", ncores);
164 print_u("Socket(s):", nsockets);
165
166 print_s("Vendor ID:", cpu_desc_get_vendor (cpudesc));
167 print_s("CPU Family:", cpu_desc_get_family (cpudesc));
168 print_s("Model:", cpu_desc_get_model (cpudesc));
169 print_s("Model name:", cpu_desc_get_model_name (cpudesc));
170
171 for (cpu = 0; cpu < ncpus; cpu++)
172 {
173 printf ("-CPU%d-\n", cpu);
174
175 bool cpu_hot_pluggable = get_processor_is_hot_pluggable (cpu);
176 int cpu_online = get_processor_is_online (cpu);
177
178 print_s ("CPU is Hot Pluggable:", cpu_hot_pluggable ?
179 (cpu_online ? "yes (online)" : "yes (offline)") : "no");
180
181 unsigned long latency = cpufreq_get_transition_latency (cpu);
182 if (latency)
183 print_s("Maximum Transition Latency:",
184 cpufreq_duration_to_string (latency));
185
186 unsigned long freq_kernel = cpufreq_get_freq_kernel (cpu);
187 if (freq_kernel > 0)
188 print_s("Current CPU Frequency:", cpufreq_freq_to_string (freq_kernel));
189
190 struct cpufreq_available_frequencies *cpufreqs, *curr;
191 cpufreqs = curr = cpufreq_get_available_freqs (cpu);
192 if (curr)
193 {
194 print_key_s("Available CPU Frequencies:");
195 while (curr)
196 {
197 printf ("%s ",
198 cpufreq_freq_to_string
199 (cpufreq_get_available_freqs_value (curr)));
200 curr = cpufreq_get_available_freqs_next (curr);
201 }
202 printf ("\n");
203 cpufreq_available_frequencies_unref(cpufreqs);
204 }
205
206 unsigned long freq_min, freq_max;
207 if (0 == cpufreq_get_hardware_limits (cpu, &freq_min, &freq_max))
208 {
209 char *min_s = cpufreq_freq_to_string (freq_min),
210 *max_s = cpufreq_freq_to_string (freq_max);
211 print_range_s("Hardware Limits:", min_s, max_s);
212 free (min_s);
213 free (max_s);
214 }
215
216 char *freq_governor = cpufreq_get_governor (cpu);
217 if (freq_governor)
218 {
219 print_s ("CPU Freq Current Governor:", freq_governor);
220 free (freq_governor);
221 }
222
223 char *freq_governors = cpufreq_get_available_governors (cpu);
224 if (freq_governors)
225 {
226 print_s ("CPU Freq Available Governors:", freq_governors);
227 free (freq_governors);
228 }
229
230 char *freq_driver = cpufreq_get_driver (cpu);
231 if (freq_driver)
232 {
233 print_s ("CPU Freq Driver:", freq_driver);
234 free (freq_driver);
235 }
236 }
237
238 char *cpu_virtflag = cpu_desc_get_virtualization_flag (cpudesc);
239 if (cpu_virtflag)
240 print_s("Virtualization:", cpu_virtflag);
241 }
242
243 int
244 main (int argc, char **argv)
245 {
246 int c, err;
247 bool verbose, cpu_model, per_cpu_stats;
248 unsigned long len, i, count, delay;
249 char *critical = NULL, *warning = NULL;
250 char *p = NULL, *cpu_progname;
251 nagstatus currstatus, status;
252 thresholds *my_threshold = NULL;
253
254 float cpu_perc = 0.0;
255 unsigned int tog = 0; /* toggle switch for cleaner code */
256 struct cpu_desc *cpudesc = NULL;
257
258 set_program_name (argv[0]);
259
260 len = strlen (program_name);
261 if (len > 6 && STRPREFIX (program_name, "check_"))
262 p = (char *) program_name + 6;
263 else
264 plugin_error (STATE_UNKNOWN, 0,
265 "bug: the plugin does not have a standard name");
266
267 if (STRPREFIX (p, "iowait")) /* check_iowait --> cpu_iowait */
268 {
269 cpu_progname = xstrdup ("iowait");
270 program_shorthelp =
271 xstrdup ("This plugin checks I/O wait bottlenecks\n");
272 }
273 else /* check_cpu --> cpu_user (the default) */
274 {
275 cpu_progname = xstrdup ("user");;
276 program_shorthelp =
277 xstrdup ("This plugin checks the CPU (user mode) utilization\n");
278 }
279
280 sysfsparser_check_for_sysfs ();
281
282 err = cpu_desc_new (&cpudesc);
283 if (err < 0)
284 plugin_error (STATE_UNKNOWN, err, "memory exhausted");
285
286 /* default values */
287 verbose = per_cpu_stats = false;
288 cpu_model = true;
289
290 while ((c = getopt_long (
291 argc, argv, "c:w:vifmp"
292 GETOPT_HELP_VERSION_STRING, longopts, NULL)) != -1)
293 {
294 switch (c)
295 {
296 default:
297 usage (stderr);
298 case 'i':
299 cpu_desc_read (cpudesc);
300 cpu_desc_summary (cpudesc);
301 return STATE_UNKNOWN;
302 case 'm':
303 cpu_model = false;
304 break;
305 case 'p':
306 per_cpu_stats = true;
307 break;
308 case 'c':
309 critical = optarg;
310 break;
311 case 'w':
312 warning = optarg;
313 break;
314 case 'v':
315 verbose = true;
316 break;
317
318 case_GETOPT_HELP_CHAR
319 case_GETOPT_VERSION_CHAR
320
321 }
322 }
323
324 if (!thresholds_expressed_as_percentages (warning, critical))
325 usage (stderr);
326
327 delay = DELAY_DEFAULT, count = COUNT_DEFAULT;
328 if (optind < argc)
329 {
330 delay = strtol_or_err (argv[optind++], "failed to parse argument");
331
332 if (delay < 1)
333 plugin_error (STATE_UNKNOWN, 0, "delay must be positive integer");
334 else if (DELAY_MAX < delay)
335 plugin_error (STATE_UNKNOWN, 0,
336 "too large delay value (greater than %d)", DELAY_MAX);
337 }
338
339 if (optind < argc)
340 {
341 count = strtol_or_err (argv[optind++], "failed to parse argument");
342 if (COUNT_MAX < count)
343 plugin_error (STATE_UNKNOWN, 0,
344 "too large count value (greater than %d)", COUNT_MAX);
345 }
346
347 status = set_thresholds (&my_threshold, warning, critical);
348 if (status == NP_RANGE_UNPARSEABLE)
349 usage (stderr);
350
351 int ncpus = per_cpu_stats ? get_processor_number_total () + 1 : 1;
352
353 jiff duser[ncpus], dsystem[ncpus], didle[ncpus],
354 diowait[ncpus], dsteal[ncpus], ratio[ncpus];
355 int debt[ncpus]; /* handle idle ticks running backwards */
356 struct cpu_time cpuv[2][ncpus];
357 jiff *cpu_value = strncmp (p, "iowait", 6) ? duser : diowait;
358 const char *cpuname;
359
360 cpu_stats_get_time (cpuv[0], ncpus);
361
362 for (c = 0; c < ncpus; c++)
363 {
364 duser[c] = cpuv[0][c].user + cpuv[0][c].nice;
365 dsystem[c] = cpuv[0][c].system + cpuv[0][c].irq + cpuv[0][c].softirq;
366 didle[c] = cpuv[0][c].idle;
367 diowait[c] = cpuv[0][c].iowait;
368 dsteal[c] = cpuv[0][c].steal;
369
370 debt[c] = 0;
371 ratio[c] = duser[c] + dsystem[c] + didle[c] + diowait[c] + dsteal[c];
372 if (!ratio[c])
373 ratio[c] = 1, didle[c] = 1;
374 }
375
376 for (i = 1; i < count; i++)
377 {
378 sleep (delay);
379 tog = !tog;
380 cpu_stats_get_time (cpuv[tog], ncpus);
381
382 for (c = 0; c < ncpus; c++)
383 {
384 duser[c] =
385 cpuv[tog][c].user - cpuv[!tog][c].user +
386 cpuv[tog][c].nice - cpuv[!tog][c].nice;
387 dsystem[c] =
388 cpuv[tog][c].system - cpuv[!tog][c].system +
389 cpuv[tog][c].irq - cpuv[!tog][c].irq +
390 cpuv[tog][c].softirq - cpuv[!tog][c].softirq;
391 didle[c] = cpuv[tog][c].idle - cpuv[!tog][c].idle;
392 diowait[c] = cpuv[tog][c].iowait - cpuv[!tog][c].iowait;
393 dsteal[c] = cpuv[tog][c].steal - cpuv[!tog][c].steal;
394
395 /* idle can run backwards for a moment -- kernel "feature" */
396 if (debt[c])
397 {
398 didle[c] = (int) didle[c] + debt[c];
399 debt[c] = 0;
400 }
401 if ((int) didle[c] < 0)
402 {
403 debt[c] = (int) didle[c];
404 didle[c] = 0;
405 }
406
407 ratio[c] = duser[c] + dsystem[c] + didle[c] + diowait[c] + dsteal[c];
408 if (!ratio[c])
409 ratio[c] = 1, didle[c] = 1;
410
411 if (NULL == (cpuname = cpuv[0][c].cpuname))
412 cpuname = "n/a";
413
414 if (verbose)
415 printf
416 ("%s_user=%.1f%%, %s_system=%.1f%%, %s_idle=%.1f%%, "
417 "%s_iowait=%.1f%%, %s_steal=%.1f%%\n"
418 , cpuname, 100.0 * duser[c] / ratio[c]
419 , cpuname, 100.0 * dsystem[c] / ratio[c]
420 , cpuname, 100.0 * didle[c] / ratio[c]
421 , cpuname, 100.0 * diowait[c] / ratio[c]
422 , cpuname, 100.0 * dsteal[c] / ratio[c]);
423
424 dbg ("sum (%s_*) = %.1f%%\n", cpuname, (100.0 * duser[c] / ratio[c]) +
425 (100.0 * dsystem[c] / ratio[c]) + (100.0 * didle[c] / ratio[c]) +
426 (100.0 * diowait[c] / ratio[c]) + (100.0 * dsteal[c] / ratio[c]));
427 }
428 }
429
430 for (c = 0, status = STATE_OK; c < ncpus; c++)
431 {
432 cpu_perc = (100.0 * (cpu_value[c]) / ratio[c]);
433 currstatus = get_status (cpu_perc, my_threshold);
434 if (currstatus > status)
435 status = currstatus;
436 }
437
438 cpu_desc_read (cpudesc);
439 char *cpu_model_str =
440 cpu_model ? xasprintf ("(%s) ",
441 cpu_desc_get_model_name (cpudesc)) : NULL;
442
443 printf ("%s %s%s - cpu %s %.1f%% |"
444 , program_name_short, cpu_model ? cpu_model_str : ""
445 , state_text (status), cpu_progname, cpu_perc);
446 for (c = 0; c < ncpus; c++)
447 {
448 if ((cpuname = cpuv[0][c].cpuname))
449 printf (" %s_user=%.1f%% %s_system=%.1f%% %s_idle=%.1f%%"
450 " %s_iowait=%.1f%% %s_steal=%.1f%%"
451 , cpuname, 100.0 * duser[c] / ratio[c]
452 , cpuname, 100.0 * dsystem[c] / ratio[c]
453 , cpuname, 100.0 * didle[c] / ratio[c]
454 , cpuname, 100.0 * diowait[c] / ratio[c]
455 , cpuname, 100.0 * dsteal[c] / ratio[c]);
456 }
457 putchar ('\n');
458
459 cpu_desc_unref (cpudesc);
460 return status;
461 }