Debian Codegraph @

madrisan-nagios-plugins-linux/nagios-plugins-linux/lib/container.c

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-3.0-or-later
2 /*
3 * License: GPLv3+
4 * Copyright (c) 2018,2024 Davide Madrisan <[email protected]>
5 *
6 * A library for checking for Docker exposed metrics.
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 #ifndef _GNU_SOURCE
22 #define _GNU_SOURCE /* activate extra prototypes for glibc */
23 #endif
24
25 #include <assert.h>
26 #include <ctype.h>
27 #include <errno.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31
32 #if HAVE_LIBCURL
33 #include <curl/curl.h>
34 #endif
35
36 #include "common.h"
37 #include "collection.h"
38 #include "container.h"
39 #include "getenv.h"
40 #include "json_helpers.h"
41 #include "logging.h"
42 #include "messages.h"
43 #include "string-macros.h"
44 #include "system.h"
45 #include "url_encode.h"
46 #include "xalloc.h"
47 #include "xasprintf.h"
48 #include "xstrton.h"
49
50 /* Hide all jsmn API symbols by making them static */
51 #define JSMN_STATIC
52 #include "jsmn.h"
53
54 #define DOCKER_CONTAINERS_JSON 0x01
55 #define DOCKER_STATS_JSON 0x02
56
57 /* returns the last portion of the given container image.
58 example:
59 "prom/prometheus:v2.39.0" --> "prometheus:v2.39.0"
60 note that docker just removes the prefix "docker.io/". */
61 static const char *
62 image_shortname (const char *image)
63 {
64 const char *strip = strrchr (image, '/');
65 if (NULL == strip)
66 strip = image;
67 else
68 strip++;
69 dbg ("shortening of \"%s\" to \"%s\"\n", image, strip);
70
71 return strip;
72 }
73
74 /* parse the json stream returned by the Docker/Podman API and return a pointer
75 to the hashtable containing the values of the discovered 'tokens'.
76 return NULL if the data cannot be parsed.
77 the function 'convert' allows a manipulation of the data before saving it in
78 the hashtable. */
79
80 static hashtable_t *
81 docker_json_parser_search (const char *json, const char *token,
82 const char *(*convert) (const char *),
83 unsigned long increment)
84 {
85 size_t i, ntoken;
86 hashtable_t *hashtable = NULL;
87
88 jsmntok_t *buffer = json_tokenise (json, &ntoken);
89 hashtable = counter_create ();
90
91 for (i = 1; i < ntoken; i++)
92 {
93 if (0 == json_token_streq (json, &buffer[i], token))
94 {
95 size_t strsize = buffer[i + 1].end - buffer[i + 1].start;
96 char *value = xmalloc (strsize + 1);
97 memcpy (value, json + buffer[i + 1].start, strsize);
98
99 dbg ("found token \"%s\" with value \"%s\" at position %d\n",
100 token, value, buffer[i].start);
101 counter_put (hashtable, convert ? convert (value) : value, increment);
102 free (value);
103 }
104 }
105
106 free (buffer);
107 return hashtable;
108 }
109
110 #if !defined NPL_TESTING && defined HAVE_LIBCURL
111
112 static size_t
113 write_memory_callback (void *contents, size_t size, size_t nmemb, void *userp)
114 {
115 size_t realsize = size * nmemb;
116 chunk_t *mem = (chunk_t *) userp;
117
118 mem->memory = realloc (mem->memory, mem->size + realsize + 1);
119 if (NULL == mem->memory)
120 plugin_error (STATE_UNKNOWN, errno, "memory exhausted");
121
122 memcpy (&(mem->memory[mem->size]), contents, realsize);
123 mem->size += realsize;
124 mem->memory[mem->size] = 0;
125
126 return realsize;
127 }
128
129 static void
130 docker_init (CURL **curl_handle, chunk_t *chunk, const char *socket)
131 {
132 chunk->memory = malloc (1); /* will be grown as needed by the realloc above */
133 chunk->size = 0; /* no data at this point */
134
135 if (NULL == socket)
136 {
137 const char *env_docker_host = secure_getenv ("DOCKER_HOST");
138 if (env_docker_host)
139 {
140 dbg ("socket set using DOCKER_HOST (\"%s\")\n", env_docker_host);
141 socket = env_docker_host;
142 }
143 else
144 plugin_error (STATE_UNKNOWN, 0,
145 "the socket path was not set, nor was the environment variable DOCKER_HOST");
146 }
147
148 curl_global_init (CURL_GLOBAL_ALL);
149
150 /* init the curl session */
151 *curl_handle = curl_easy_init ();
152 if (NULL == (*curl_handle))
153 plugin_error (STATE_UNKNOWN, errno,
154 "cannot start a libcurl easy session");
155
156 curl_easy_setopt (*curl_handle, CURLOPT_UNIX_SOCKET_PATH, socket);
157 dbg ("CURLOPT_UNIX_SOCKET_PATH is set to \"%s\"\n", socket);
158
159 /* send all data to this function */
160 curl_easy_setopt (*curl_handle, CURLOPT_WRITEFUNCTION,
161 write_memory_callback);
162 curl_easy_setopt (*curl_handle, CURLOPT_WRITEDATA, (void *) chunk);
163 curl_easy_setopt (*curl_handle, CURLOPT_NOPROGRESS, 1L);
164
165 /* some servers don't like requests that are made without a user-agent
166 field, so we provide one */
167 curl_easy_setopt (*curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
168 }
169
170 static CURLcode
171 docker_get (CURL *curl_handle, const int query, const char *id)
172 {
173 CURLcode res;
174 char *api_version, *class, *url, *filter = NULL;
175
176 api_version = secure_getenv ("DOCKER_API_VERSION");
177 if (NULL == api_version)
178 api_version = "1.24"; /* API versions before v1.24 are deprecated. */
179 else
180 dbg ("setting Docker API version according to DOCKER_API_VERSION: %s\n",
181 api_version);
182
183 switch (query)
184 {
185 default:
186 plugin_error (STATE_UNKNOWN, 0, "unknown docker query");
187 case DOCKER_CONTAINERS_JSON:
188 filter = url_encode ("{\"status\":{\"running\":true}}");
189 class = xasprintf ("containers/json");
190 url = filter ?
191 xasprintf ("http://v%s/%s?filters=%s", api_version, class, filter) :
192 xasprintf ("http://v%s/%s", api_version, class);
193 break;
194 case DOCKER_STATS_JSON:
195 class = xasprintf ("containers/%s/stats", id);
196 url = xasprintf ("http://v%s/%s?stream=false", api_version, class);
197 break;
198 }
199
200 dbg ("docker rest url: %s\n", url);
201
202 curl_easy_setopt (curl_handle, CURLOPT_URL, url);
203 res = curl_easy_perform (curl_handle);
204
205 free (class);
206 free (filter);
207 free (url);
208
209 return res;
210 }
211
212 static void
213 docker_close (CURL *curl_handle, chunk_t *chunk)
214 {
215 /* cleanup curl stuff */
216 curl_easy_cleanup (curl_handle);
217
218 free (chunk->memory);
219
220 /* we're done with libcurl, so clean it up */
221 curl_global_cleanup ();
222 }
223
224 #endif /* NPL_TESTING */
225
226 static int
227 docker_api_call (char *socket, chunk_t *chunk,
228 #ifndef NPL_TESTING
229 CURL *curl_handle,
230 #endif
231 const char *search_key, bool verbose)
232 {
233 #ifndef NPL_TESTING
234
235 CURLcode res;
236
237 curl_handle = NULL;
238 docker_init (&curl_handle, chunk, socket);
239 res = docker_get (curl_handle, DOCKER_CONTAINERS_JSON, NULL);
240 if (CURLE_OK != res)
241 {
242 docker_close (curl_handle, chunk);
243 plugin_error (STATE_UNKNOWN, errno, "%s", curl_easy_strerror (res));
244 }
245
246 #else
247
248 int err;
249 if ((err = docker_get (chunk, DOCKER_CONTAINERS_JSON, NULL)) != 0)
250 return err;
251
252 #endif /* NPL_TESTING */
253
254 assert (chunk->memory);
255 dbg ("%zu bytes retrieved\n", chunk->size);
256 dbg ("json data: %s", chunk->memory);
257
258 #ifdef ENABLE_DEBUG
259 char *dump;
260
261 json_dump_pretty (chunk->memory, &dump, 1);
262 dbg ("json data pretty formatted:%s", dump);
263 free (dump);
264 #endif
265
266 return 0;
267 }
268
269 /* Returns the number of running Docker/Podman containers grouped by images */
270
271 int
272 docker_running_containers (char *socket, unsigned int *count,
273 const char *image, char **perfdata, bool verbose)
274 {
275 chunk_t chunk;
276 #ifndef NPL_TESTING
277 CURL *curl_handle = NULL;
278 #endif
279
280 hashtable_t *hashtable;
281 unsigned int running_containers = 0;
282 char *search_key = "Image";
283
284 #ifndef NPL_TESTING
285 docker_api_call (socket, &chunk, curl_handle, search_key, verbose);
286 #else
287 docker_api_call (socket, &chunk, search_key, verbose);
288 #endif
289
290 hashtable =
291 docker_json_parser_search (chunk.memory, search_key, image_shortname, 1);
292 if (NULL == hashtable)
293 plugin_error (STATE_UNKNOWN, 0,
294 "unable to parse the json data for \"%s\"s", search_key);
295 dbg ("number of docker unique containers (by %s): %u\n", search_key,
296 counter_get_unique_elements (hashtable));
297
298 if (image)
299 {
300 hashable_t *np = counter_lookup (hashtable, image);
301 running_containers = np ? np->count : 0;
302 *perfdata = xasprintf ("containers_%s=%u", image_shortname (image),
303 running_containers);
304 }
305 else
306 {
307 running_containers = counter_get_elements (hashtable);
308 size_t size;
309 FILE *stream = open_memstream (perfdata, &size);
310 for (unsigned int j = 0; j < hashtable->uniq; j++)
311 {
312 hashable_t *np = counter_lookup (hashtable, hashtable->keys[j]);
313 assert (NULL != np);
314 fprintf (stream, "containers_%s=%lu ",
315 image_shortname (hashtable->keys[j]), np->count);
316 }
317 fprintf (stream, "containers_total=%u", hashtable->elements);
318 fclose (stream);
319 }
320
321 *count = running_containers;
322
323 counter_free (hashtable);
324 docker_close (
325 #ifndef NPL_TESTING
326 curl_handle,
327 #endif
328 &chunk);
329
330 return 0;
331 }
332
333 #ifndef NPL_TESTING
334
335 /* Returns the memory usage of a Docker/Podman container */
336 static int
337 docker_container_memory (char *socket, const char *id,
338 long long unsigned int *memory, bool verbose)
339 {
340 chunk_t chunk;
341 CURL *curl_handle = NULL;
342 CURLcode res;
343 char *errmesg = NULL;
344 int ret;
345
346 docker_init (&curl_handle, &chunk, socket);
347 res = docker_get (curl_handle, DOCKER_STATS_JSON, id);
348 if (CURLE_OK != res)
349 {
350 docker_close (curl_handle, &chunk);
351 plugin_error (STATE_UNKNOWN, errno, "%s", curl_easy_strerror (res));
352 }
353
354 assert (chunk.memory);
355 dbg ("%zu bytes retrieved\n", chunk.size);
356 dbg ("json data: %s", chunk.memory);
357
358 #ifdef ENABLE_DEBUG
359 /*
360 char *dump;
361
362 json_dump_pretty (chunk.memory, &dump, 1);
363 dbg ("json data pretty formatted:%s", dump);
364 free (dump);
365 */
366 #endif
367
368 /* get the memory usage */
369 char *value = NULL;
370 json_search (chunk.memory, ".memory_stats.usage", &value);
371
372 /* FIXME: remove cast */
373 ret = sizetollint (value, (long long int *)memory, &errmesg);
374 if (ret < 0)
375 plugin_error (STATE_UNKNOWN, errno
376 , "failed to convert container memory value: %s"
377 , errmesg);
378
379 free (value);
380
381 return 0;
382 }
383
384 /* Returns the memory usage of running Docker/Podman containers */
385
386 int
387 docker_running_containers_memory (char *socket, long long unsigned int *memory,
388 bool verbose)
389 {
390 chunk_t chunk;
391 CURL *curl_handle = NULL;
392 hashtable_t *hashtable;
393 char *search_key = "Id";
394
395 /* get the list of running containers */
396 docker_api_call (socket, &chunk, curl_handle, search_key, verbose);
397
398 hashtable =
399 docker_json_parser_search (chunk.memory, search_key, NULL, 1);
400 if (NULL == hashtable)
401 plugin_error (STATE_UNKNOWN, 0,
402 "unable to parse the json data for \"%s\"s", search_key);
403 dbg ("number of docker containers: %u\n",
404 counter_get_unique_elements (hashtable));
405
406 long long unsigned int memory_usage;
407 *memory = 0;
408
409 /* FIXME: this loop must be threaded and run in parallel */
410 for (unsigned int j = 0; j < hashtable->uniq; j++)
411 {
412 const char *id = hashtable->keys[j];
413 docker_container_memory (socket, id, &memory_usage, verbose);
414 dbg ("memory usage for container id \"%s\": %llu\" bytes\n", id,
415 memory_usage);
416 *memory += (memory_usage >> 10);
417 }
418
419 docker_close (
420 #ifndef NPL_TESTING
421 curl_handle,
422 #endif
423 &chunk);
424
425 return 0;
426 }
427
428 #endif