336a9964410584682eb8417c15c77ce2912f7425
[collectd.git] / src / utils / proc_pids / proc_pids.c
1 /**
2  * collectd - src/utils/proc_pids/proc_pids.c
3  *
4  * Copyright(c) 2018-2019 Intel Corporation. All rights reserved.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22  * SOFTWARE.
23  *
24  * Authors:
25  *   Starzyk, Mateusz <mateuszx.starzyk@intel.com>
26  *   Wojciech Andralojc <wojciechx.andralojc@intel.com>
27  *   Michał Aleksiński <michalx.aleksinski@intel.com>
28  **/
29
30 #include "collectd.h"
31 #include "utils/common/common.h"
32 #include "utils/proc_pids/proc_pids.h"
33
34 #define UTIL_NAME "utils_proc_pids"
35
36 void pids_list_free(pids_list_t *list) {
37   assert(list);
38
39   sfree(list->pids);
40   sfree(list);
41 }
42
43 int proc_pids_is_name_valid(const char *name) {
44
45   if (name != NULL) {
46     unsigned len = strlen(name);
47     if (len > 0 && len <= MAX_PROC_NAME_LEN)
48       return 1;
49     else {
50       DEBUG(UTIL_NAME
51             ": Process name \'%s\' is too long. Max supported len is %d chars.",
52             name, MAX_PROC_NAME_LEN);
53     }
54   }
55
56   return 0;
57 }
58
59 int pids_list_add_pid(pids_list_t *list, const pid_t pid) {
60   assert(list);
61
62   if (list->allocated == list->size) {
63     size_t new_allocated = list->allocated + 1 + list->allocated / 10;
64     pid_t *new_pids = realloc(list->pids, sizeof(pid_t) * new_allocated);
65
66     if (NULL == new_pids) {
67       ERROR(UTIL_NAME ": Alloc error\n");
68       return -1;
69     }
70
71     list->pids = new_pids;
72     list->allocated = new_allocated;
73   }
74
75   list->pids[list->size] = pid;
76   list->size++;
77
78   return 0;
79 }
80
81 int pids_list_add_list(pids_list_t *dst, pids_list_t *src) {
82   assert(dst);
83   assert(src);
84
85   if (dst->allocated < dst->size + src->size) {
86     pid_t *new_pids =
87         realloc(dst->pids, sizeof(pid_t) * (dst->size + src->size));
88
89     if (NULL == new_pids) {
90       ERROR(UTIL_NAME ": Alloc error\n");
91       return -1;
92     }
93
94     dst->allocated = dst->size + src->size;
95     dst->pids = new_pids;
96   }
97
98   memcpy(dst->pids + dst->size, src->pids, src->size * sizeof(*(src->pids)));
99   dst->size += src->size;
100
101   return 0;
102 }
103
104 int pids_list_clear(pids_list_t *list) {
105   assert(list);
106
107   if (list->pids != NULL)
108     sfree(list->pids);
109
110   list->size = 0;
111   list->allocated = 0;
112
113   return 0;
114 }
115
116 int pids_list_contains_pid(pids_list_t *list, const pid_t pid) {
117   assert(list);
118
119   for (int i = 0; i < list->size; i++)
120     if (list->pids[i] == pid)
121       return 1;
122
123   return 0;
124 }
125
126 /*
127  * NAME
128  *   read_proc_name
129  *
130  * DESCRIPTION
131  *   Reads process name from given pid directory.
132  *   Strips new-line character (\n).
133  *
134  * PARAMETERS
135  *   `procfs_path' Path to systems proc directory (e.g. /proc)
136  *   `pid_entry'   Dirent for PID directory
137  *   `name'        Output buffer for process name, recommended proc_comm.
138  *   `out_size'    Output buffer size, recommended sizeof(proc_comm)
139  *
140  * RETURN VALUE
141  *   On success, the number of read bytes (includes stripped \n).
142  *   -1 on file open error
143 */
144 static int read_proc_name(const char *procfs_path,
145                           const struct dirent *pid_entry, char *name,
146                           const size_t out_size) {
147   assert(pid_entry);
148   assert(name);
149   assert(out_size);
150   memset(name, 0, out_size);
151
152   const char *comm_file_name = "comm";
153
154   char *path = ssnprintf_alloc("%s/%s/%s", procfs_path, pid_entry->d_name,
155                                comm_file_name);
156   if (path == NULL)
157     return -1;
158   FILE *f = fopen(path, "r");
159   if (f == NULL) {
160     ERROR(UTIL_NAME ": Failed to open comm file, error: %d\n", errno);
161     sfree(path);
162     return -1;
163   }
164   size_t read_length = fread(name, sizeof(char), out_size, f);
165   name[out_size - 1] = '\0';
166   fclose(f);
167   sfree(path);
168   /* strip new line ending */
169   char *newline = strchr(name, '\n');
170   if (newline) {
171     *newline = '\0';
172   }
173
174   return read_length;
175 }
176
177 /*
178  * NAME
179  *   get_pid_number
180  *
181  * DESCRIPTION
182  *   Gets pid number for given /proc/pid directory entry or
183  *   returns error if input directory does not hold PID information.
184  *
185  * PARAMETERS
186  *   `entry'    Dirent for PID directory
187  *   `pid'      PID number to be filled
188  *
189  * RETURN VALUE
190  *   0 on success. -1 on error.
191  */
192 static int get_pid_number(struct dirent *entry, pid_t *pid) {
193   char *tmp_end; /* used for strtoul error check*/
194
195   if (pid == NULL || entry == NULL)
196     return -1;
197
198   if (entry->d_type != DT_DIR)
199     return -1;
200
201   /* trying to get pid number from directory name*/
202   *pid = strtoul(entry->d_name, &tmp_end, 10);
203   if (*tmp_end != '\0') {
204     return -1; /* conversion failed, not proc-pid */
205   }
206   /* all checks passed, marking as success */
207   return 0;
208 }
209
210 int proc_pids_init(const char **procs_names_array,
211                    const size_t procs_names_array_size,
212                    proc_pids_t **proc_pids[]) {
213
214   proc_pids_t **proc_pids_array;
215   assert(proc_pids);
216   assert(NULL == *proc_pids);
217
218   /* Copy procs names to output array. Initialize pids list with NULL value. */
219   proc_pids_array = calloc(procs_names_array_size, sizeof(*proc_pids_array));
220
221   if (NULL == proc_pids_array)
222     return -1;
223
224   for (size_t i = 0; i < procs_names_array_size; ++i) {
225     proc_pids_array[i] = calloc(1, sizeof(**proc_pids_array));
226     if (NULL == proc_pids_array[i])
227       goto proc_pids_init_error;
228
229     sstrncpy(proc_pids_array[i]->process_name, procs_names_array[i],
230              STATIC_ARRAY_SIZE(proc_pids_array[i]->process_name));
231     proc_pids_array[i]->prev = NULL;
232     proc_pids_array[i]->curr = NULL;
233   }
234
235   *proc_pids = proc_pids_array;
236
237   return 0;
238 proc_pids_init_error:
239   if (NULL != proc_pids_array) {
240     for (size_t i = 0; i < procs_names_array_size; ++i) {
241       free(proc_pids_array[i]);
242     }
243     free(proc_pids_array);
244   }
245   return -1;
246 }
247
248 static void swap_proc_pids(proc_pids_t **proc_pids, size_t proc_pids_num) {
249   for (size_t i = 0; i < proc_pids_num; i++) {
250     pids_list_t *swap = proc_pids[i]->prev;
251     proc_pids[i]->prev = proc_pids[i]->curr;
252     proc_pids[i]->curr = swap;
253   }
254 }
255
256 int proc_pids_update(const char *procfs_path, proc_pids_t **proc_pids,
257                      size_t proc_pids_num) {
258   assert(procfs_path);
259   assert(proc_pids);
260
261   DIR *proc_dir = opendir(procfs_path);
262   if (proc_dir == NULL) {
263     ERROR(UTIL_NAME ": Could not open %s directory, error: %d", procfs_path,
264           errno);
265     return -1;
266   }
267
268   swap_proc_pids(proc_pids, proc_pids_num);
269
270   for (size_t i = 0; i < proc_pids_num; i++) {
271     if (NULL == proc_pids[i]->curr)
272       proc_pids[i]->curr = calloc(1, sizeof(*(proc_pids[i]->curr)));
273
274     if (NULL == proc_pids[i]->curr) {
275       ERROR(UTIL_NAME ": Alloc error\n");
276       goto update_error;
277     }
278
279     proc_pids[i]->curr->size = 0;
280   }
281
282   /* Go through procfs and find PIDS and their comms */
283   struct dirent *entry;
284   while ((entry = readdir(proc_dir)) != NULL) {
285     pid_t pid;
286     int pid_conversion = get_pid_number(entry, &pid);
287     if (pid_conversion < 0)
288       continue;
289
290     proc_comm_t comm;
291     int read_result =
292         read_proc_name(procfs_path, entry, comm, sizeof(proc_comm_t));
293     if (read_result <= 0)
294       continue;
295
296     /* Try to find comm in input procs array */
297     for (size_t i = 0; i < proc_pids_num; ++i) {
298       if (0 ==
299           strncmp(comm, proc_pids[i]->process_name, STATIC_ARRAY_SIZE(comm)))
300         pids_list_add_pid(proc_pids[i]->curr, pid);
301     }
302   }
303
304   int close_result = closedir(proc_dir);
305   if (0 != close_result) {
306     ERROR(UTIL_NAME ": failed to close /proc directory, error: %d", errno);
307     goto update_error;
308   }
309   return 0;
310
311 update_error:
312   swap_proc_pids(proc_pids, proc_pids_num);
313   return -1;
314 }
315
316 int pids_list_diff(proc_pids_t *proc, pids_list_t *added,
317                    pids_list_t *removed) {
318   assert(proc);
319   assert(added);
320   assert(removed);
321
322   added->size = 0;
323   removed->size = 0;
324
325   if (NULL == proc->prev || 0 == proc->prev->size) {
326     /* append all PIDs from curr to added*/
327     return pids_list_add_list(added, proc->curr);
328   } else if (NULL == proc->curr || 0 == proc->curr->size) {
329     /* append all PIDs from prev to removed*/
330     return pids_list_add_list(removed, proc->prev);
331   }
332
333   for (int i = 0; i < proc->prev->size; i++)
334     if (0 == pids_list_contains_pid(proc->curr, proc->prev->pids[i])) {
335       int add_result = pids_list_add_pid(removed, proc->prev->pids[i]);
336       if (add_result < 0)
337         return add_result;
338     }
339
340   for (int i = 0; i < proc->curr->size; i++)
341     if (0 == pids_list_contains_pid(proc->prev, proc->curr->pids[i])) {
342       int add_result = pids_list_add_pid(added, proc->curr->pids[i]);
343       if (add_result < 0)
344         return add_result;
345     }
346
347   return 0;
348 }
349
350 int proc_pids_free(proc_pids_t *proc_pids[], size_t proc_pids_num) {
351   for (size_t i = 0; i < proc_pids_num; i++) {
352     if (NULL != proc_pids[i]->curr)
353       pids_list_free(proc_pids[i]->curr);
354     if (NULL != proc_pids[i]->prev)
355       pids_list_free(proc_pids[i]->prev);
356     sfree(proc_pids[i]);
357   }
358   sfree(proc_pids);
359
360   return 0;
361 }