intel_rdt: refactored proc utils to increase efficiency
[collectd.git] / src / utils_proc_pids.c
1 /**
2  * collectd - src/utils_config_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.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 is_proc_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 int read_proc_name(const char *procfs_path, const struct dirent *pid_entry,
127                    char *name, const size_t out_size) {
128   assert(pid_entry);
129   assert(name);
130   assert(out_size);
131   memset(name, 0, out_size);
132
133   const char *comm_file_name = "comm";
134
135   char *path = ssnprintf_alloc("%s/%s/%s", procfs_path, pid_entry->d_name,
136                                comm_file_name);
137   if (path == NULL)
138     return -1;
139   FILE *f = fopen(path, "r");
140   if (f == NULL) {
141     ERROR(UTIL_NAME ": Failed to open comm file, error: %d\n", errno);
142     sfree(path);
143     return -1;
144   }
145   size_t read_length = fread(name, sizeof(char), out_size, f);
146   name[out_size - 1] = '\0';
147   fclose(f);
148   sfree(path);
149   /* strip new line ending */
150   char *newline = strchr(name, '\n');
151   if (newline) {
152     *newline = '\0';
153   }
154
155   return read_length;
156 }
157
158 int get_pid_number(struct dirent *entry, pid_t *pid) {
159   char *tmp_end; /* used for strtoul error check*/
160
161   if (pid == NULL || entry == NULL)
162     return -1;
163
164   if (entry->d_type != DT_DIR)
165     return -1;
166
167   /* trying to get pid number from directory name*/
168   *pid = strtoul(entry->d_name, &tmp_end, 10);
169   if (*tmp_end != '\0') {
170     return -1; /* conversion failed, not proc-pid */
171   }
172   /* all checks passed, marking as success */
173   return 0;
174 }
175
176 int initialize_proc_pids(const char **procs_names_array,
177                          const size_t procs_names_array_size,
178                          proc_pids_t **proc_pids[]) {
179
180   proc_pids_t **proc_pids_array;
181   assert(proc_pids);
182   assert(NULL == *proc_pids);
183
184   /* Copy procs names to output array. Initialize pids list with NULL value. */
185   proc_pids_array = calloc(procs_names_array_size, sizeof(*proc_pids_array));
186
187   if (NULL == proc_pids_array)
188     return -1;
189
190   for (size_t i = 0; i < procs_names_array_size; ++i) {
191     proc_pids_array[i] = calloc(1, sizeof(**proc_pids_array));
192     if (NULL == proc_pids_array[i])
193       goto initialize_proc_pids_error;
194
195     sstrncpy(proc_pids_array[i]->process_name, procs_names_array[i],
196              STATIC_ARRAY_SIZE(proc_pids_array[i]->process_name));
197     proc_pids_array[i]->prev = NULL;
198     proc_pids_array[i]->curr = NULL;
199   }
200
201   *proc_pids = proc_pids_array;
202
203   return 0;
204 initialize_proc_pids_error:
205   if (NULL != proc_pids_array) {
206     for (size_t i = 0; i < procs_names_array_size; ++i) {
207       free(proc_pids_array[i]);
208     }
209     free(proc_pids_array);
210   }
211   return -1;
212 }
213
214 static void swap_proc_pids(proc_pids_t **proc_pids, size_t proc_pids_num) {
215   for (size_t i = 0; i < proc_pids_num; i++) {
216     pids_list_t *swap = proc_pids[i]->prev;
217     proc_pids[i]->prev = proc_pids[i]->curr;
218     proc_pids[i]->curr = swap;
219   }
220 }
221
222 int update_proc_pids(const char *procfs_path, proc_pids_t **proc_pids,
223                      size_t proc_pids_num) {
224   assert(procfs_path);
225   assert(proc_pids);
226
227   DIR *proc_dir = opendir(procfs_path);
228   if (proc_dir == NULL) {
229     ERROR(UTIL_NAME ": Could not open %s directory, error: %d", procfs_path,
230           errno);
231     return -1;
232   }
233
234   swap_proc_pids(proc_pids, proc_pids_num);
235
236   for (size_t i = 0; i < proc_pids_num; i++) {
237     if (NULL == proc_pids[i]->curr)
238       proc_pids[i]->curr = calloc(1, sizeof(*(proc_pids[i]->curr)));
239
240     if (NULL == proc_pids[i]->curr) {
241       ERROR(UTIL_NAME ": Alloc error\n");
242       goto update_error;
243     }
244
245     proc_pids[i]->curr->size = 0;
246   }
247
248   /* Go through procfs and find PIDS and their comms */
249   struct dirent *entry;
250   while ((entry = readdir(proc_dir)) != NULL) {
251     pid_t pid;
252     int pid_conversion = get_pid_number(entry, &pid);
253     if (pid_conversion < 0)
254       continue;
255
256     proc_comm_t comm;
257     int read_result =
258         read_proc_name(procfs_path, entry, comm, sizeof(proc_comm_t));
259     if (read_result <= 0)
260       continue;
261
262     /* Try to find comm in input procs array */
263     for (size_t i = 0; i < proc_pids_num; ++i) {
264       if (0 ==
265           strncmp(comm, proc_pids[i]->process_name, STATIC_ARRAY_SIZE(comm)))
266         pids_list_add_pid(proc_pids[i]->curr, pid);
267     }
268   }
269
270   int close_result = closedir(proc_dir);
271   if (0 != close_result) {
272     ERROR(UTIL_NAME ": failed to close /proc directory, error: %d", errno);
273     goto update_error;
274   }
275   return 0;
276
277 update_error:
278   swap_proc_pids(proc_pids, proc_pids_num);
279   return -1;
280 }
281
282 int pids_list_diff(proc_pids_t *proc, pids_list_t *added,
283                    pids_list_t *removed) {
284   assert(proc);
285   assert(added);
286   assert(removed);
287
288   added->size = 0;
289   removed->size = 0;
290
291   if (NULL == proc->prev || 0 == proc->prev->size) {
292     /* append all PIDs from curr to added*/
293     return pids_list_add_list(added, proc->curr);
294   } else if (NULL == proc->curr || 0 == proc->curr->size) {
295     /* append all PIDs from prev to removed*/
296     return pids_list_add_list(removed, proc->prev);
297   }
298
299   for (int i = 0; i < proc->prev->size; i++)
300     if (0 == pids_list_contains_pid(proc->curr, proc->prev->pids[i])) {
301       int add_result = pids_list_add_pid(removed, proc->prev->pids[i]);
302       if (add_result < 0)
303         return add_result;
304     }
305
306   for (int i = 0; i < proc->curr->size; i++)
307     if (0 == pids_list_contains_pid(proc->prev, proc->curr->pids[i])) {
308       int add_result = pids_list_add_pid(added, proc->curr->pids[i]);
309       if (add_result < 0)
310         return add_result;
311     }
312
313   return 0;
314 }
315
316 int proc_pids_free(proc_pids_t *proc_pids[], size_t proc_pids_num) {
317   for (size_t i = 0; i < proc_pids_num; i++) {
318     if (NULL != proc_pids[i]->curr)
319       pids_list_free(proc_pids[i]->curr);
320     if (NULL != proc_pids[i]->prev)
321       pids_list_free(proc_pids[i]->prev);
322     sfree(proc_pids[i]);
323   }
324   sfree(proc_pids);
325
326   return 0;
327 }