ebpf_apps.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "ebpf.h"
  3. #include "ebpf_socket.h"
  4. #include "ebpf_apps.h"
  5. // ----------------------------------------------------------------------------
  6. // internal flags
  7. // handled in code (automatically set)
  8. static int proc_pid_cmdline_is_needed = 0; // 1 when we need to read /proc/cmdline
  9. /*****************************************************************
  10. *
  11. * FUNCTIONS USED TO READ HASH TABLES
  12. *
  13. *****************************************************************/
  14. /**
  15. * Read statistic hash table.
  16. *
  17. * @param ep the output structure.
  18. * @param fd the file descriptor mapped from kernel ring.
  19. * @param pid the index used to select the data.
  20. * @param bpf_map_lookup_elem a pointer for the function used to read data.
  21. *
  22. * @return It returns 0 when the data was copied and -1 otherwise
  23. */
  24. int ebpf_read_hash_table(void *ep, int fd, uint32_t pid)
  25. {
  26. if (!ep)
  27. return -1;
  28. if (!bpf_map_lookup_elem(fd, &pid, ep))
  29. return 0;
  30. return -1;
  31. }
  32. /**
  33. * Read socket statistic
  34. *
  35. * Read information from kernel ring to user ring.
  36. *
  37. * @param ep the table with all process stats values.
  38. * @param fd the file descriptor mapped from kernel
  39. * @param ef a pointer for the functions mapped from dynamic library
  40. * @param pids the list of pids associated to a target.
  41. *
  42. * @return
  43. */
  44. size_t read_bandwidth_statistic_using_pid_on_target(ebpf_bandwidth_t **ep, int fd, struct pid_on_target *pids)
  45. {
  46. size_t count = 0;
  47. while (pids) {
  48. uint32_t current_pid = pids->pid;
  49. if (!ebpf_read_hash_table(ep[current_pid], fd, current_pid))
  50. count++;
  51. pids = pids->next;
  52. }
  53. return count;
  54. }
  55. /**
  56. * Read bandwidth statistic using hash table
  57. *
  58. * @param out the output tensor that will receive the information.
  59. * @param fd the file descriptor that has the data
  60. * @param bpf_map_lookup_elem a pointer for the function to read the data
  61. * @param bpf_map_get_next_key a pointer fo the function to read the index.
  62. */
  63. size_t read_bandwidth_statistic_using_hash_table(ebpf_bandwidth_t **out, int fd)
  64. {
  65. size_t count = 0;
  66. uint32_t key = 0;
  67. uint32_t next_key = 0;
  68. while (bpf_map_get_next_key(fd, &key, &next_key) == 0) {
  69. ebpf_bandwidth_t *eps = out[next_key];
  70. if (!eps) {
  71. eps = callocz(1, sizeof(ebpf_process_stat_t));
  72. out[next_key] = eps;
  73. }
  74. ebpf_read_hash_table(eps, fd, next_key);
  75. }
  76. return count;
  77. }
  78. /*****************************************************************
  79. *
  80. * FUNCTIONS CALLED FROM COLLECTORS
  81. *
  82. *****************************************************************/
  83. /**
  84. * Am I running as Root
  85. *
  86. * Verify the user that is running the collector.
  87. *
  88. * @return It returns 1 for root and 0 otherwise.
  89. */
  90. int am_i_running_as_root()
  91. {
  92. uid_t uid = getuid(), euid = geteuid();
  93. if (uid == 0 || euid == 0) {
  94. return 1;
  95. }
  96. return 0;
  97. }
  98. /**
  99. * Reset the target values
  100. *
  101. * @param root the pointer to the chain that will be reset.
  102. *
  103. * @return it returns the number of structures that was reset.
  104. */
  105. size_t zero_all_targets(struct target *root)
  106. {
  107. struct target *w;
  108. size_t count = 0;
  109. for (w = root; w; w = w->next) {
  110. count++;
  111. if (unlikely(w->root_pid)) {
  112. struct pid_on_target *pid_on_target = w->root_pid;
  113. while (pid_on_target) {
  114. struct pid_on_target *pid_on_target_to_free = pid_on_target;
  115. pid_on_target = pid_on_target->next;
  116. free(pid_on_target_to_free);
  117. }
  118. w->root_pid = NULL;
  119. }
  120. }
  121. return count;
  122. }
  123. /**
  124. * Clean the allocated structures
  125. *
  126. * @param agrt the pointer to be cleaned.
  127. */
  128. void clean_apps_groups_target(struct target *agrt)
  129. {
  130. struct target *current_target;
  131. while (agrt) {
  132. current_target = agrt;
  133. agrt = current_target->target;
  134. freez(current_target);
  135. }
  136. }
  137. /**
  138. * Find or create a new target
  139. * there are targets that are just aggregated to other target (the second argument)
  140. *
  141. * @param id
  142. * @param target
  143. * @param name
  144. *
  145. * @return It returns the target on success and NULL otherwise
  146. */
  147. struct target *get_apps_groups_target(struct target **agrt, const char *id, struct target *target, const char *name)
  148. {
  149. int tdebug = 0, thidden = target ? target->hidden : 0, ends_with = 0;
  150. const char *nid = id;
  151. // extract the options
  152. while (nid[0] == '-' || nid[0] == '+' || nid[0] == '*') {
  153. if (nid[0] == '-')
  154. thidden = 1;
  155. if (nid[0] == '+')
  156. tdebug = 1;
  157. if (nid[0] == '*')
  158. ends_with = 1;
  159. nid++;
  160. }
  161. uint32_t hash = simple_hash(id);
  162. // find if it already exists
  163. struct target *w, *last = *agrt;
  164. for (w = *agrt; w; w = w->next) {
  165. if (w->idhash == hash && strncmp(nid, w->id, MAX_NAME) == 0)
  166. return w;
  167. last = w;
  168. }
  169. // find an existing target
  170. if (unlikely(!target)) {
  171. while (*name == '-') {
  172. if (*name == '-')
  173. thidden = 1;
  174. name++;
  175. }
  176. for (target = *agrt; target != NULL; target = target->next) {
  177. if (!target->target && strcmp(name, target->name) == 0)
  178. break;
  179. }
  180. }
  181. if (target && target->target)
  182. fatal(
  183. "Internal Error: request to link process '%s' to target '%s' which is linked to target '%s'", id,
  184. target->id, target->target->id);
  185. w = callocz(1, sizeof(struct target));
  186. strncpyz(w->id, nid, MAX_NAME);
  187. w->idhash = simple_hash(w->id);
  188. if (unlikely(!target))
  189. // copy the name
  190. strncpyz(w->name, name, MAX_NAME);
  191. else
  192. // copy the id
  193. strncpyz(w->name, nid, MAX_NAME);
  194. strncpyz(w->compare, nid, MAX_COMPARE_NAME);
  195. size_t len = strlen(w->compare);
  196. if (w->compare[len - 1] == '*') {
  197. w->compare[len - 1] = '\0';
  198. w->starts_with = 1;
  199. }
  200. w->ends_with = ends_with;
  201. if (w->starts_with && w->ends_with)
  202. proc_pid_cmdline_is_needed = 1;
  203. w->comparehash = simple_hash(w->compare);
  204. w->comparelen = strlen(w->compare);
  205. w->hidden = thidden;
  206. #ifdef NETDATA_INTERNAL_CHECKS
  207. w->debug_enabled = tdebug;
  208. #else
  209. if (tdebug)
  210. fprintf(stderr, "apps.plugin has been compiled without debugging\n");
  211. #endif
  212. w->target = target;
  213. // append it, to maintain the order in apps_groups.conf
  214. if (last)
  215. last->next = w;
  216. else
  217. *agrt = w;
  218. return w;
  219. }
  220. /**
  221. * Read the apps_groups.conf file
  222. *
  223. * @param agrt a pointer to apps_group_root_target
  224. * @param path the directory to search apps_%s.conf
  225. * @param file the word to complement the file name.
  226. *
  227. * @return It returns 0 on success and -1 otherwise
  228. */
  229. int ebpf_read_apps_groups_conf(struct target **agdt, struct target **agrt, const char *path, const char *file)
  230. {
  231. char filename[FILENAME_MAX + 1];
  232. snprintfz(filename, FILENAME_MAX, "%s/apps_%s.conf", path, file);
  233. // ----------------------------------------
  234. procfile *ff = procfile_open_no_log(filename, " :\t", PROCFILE_FLAG_DEFAULT);
  235. if (!ff)
  236. return -1;
  237. procfile_set_quotes(ff, "'\"");
  238. ff = procfile_readall(ff);
  239. if (!ff)
  240. return -1;
  241. size_t line, lines = procfile_lines(ff);
  242. for (line = 0; line < lines; line++) {
  243. size_t word, words = procfile_linewords(ff, line);
  244. if (!words)
  245. continue;
  246. char *name = procfile_lineword(ff, line, 0);
  247. if (!name || !*name)
  248. continue;
  249. // find a possibly existing target
  250. struct target *w = NULL;
  251. // loop through all words, skipping the first one (the name)
  252. for (word = 0; word < words; word++) {
  253. char *s = procfile_lineword(ff, line, word);
  254. if (!s || !*s)
  255. continue;
  256. if (*s == '#')
  257. break;
  258. // is this the first word? skip it
  259. if (s == name)
  260. continue;
  261. // add this target
  262. struct target *n = get_apps_groups_target(agrt, s, w, name);
  263. if (!n) {
  264. error("Cannot create target '%s' (line %zu, word %zu)", s, line, word);
  265. continue;
  266. }
  267. // just some optimization
  268. // to avoid searching for a target for each process
  269. if (!w)
  270. w = n->target ? n->target : n;
  271. }
  272. }
  273. procfile_close(ff);
  274. *agdt = get_apps_groups_target(agrt, "p+!o@w#e$i^r&7*5(-i)l-o_", NULL, "other"); // match nothing
  275. if (!*agdt)
  276. fatal("Cannot create default target");
  277. struct target *ptr = *agdt;
  278. if (ptr->target)
  279. *agdt = ptr->target;
  280. return 0;
  281. }
  282. // the minimum PID of the system
  283. // this is also the pid of the init process
  284. #define INIT_PID 1
  285. // ----------------------------------------------------------------------------
  286. // string lengths
  287. #define MAX_COMPARE_NAME 100
  288. #define MAX_NAME 100
  289. #define MAX_CMDLINE 16384
  290. struct pid_stat **all_pids = NULL; // to avoid allocations, we pre-allocate the
  291. // the entire pid space.
  292. struct pid_stat *root_of_pids = NULL; // global list of all processes running
  293. size_t all_pids_count = 0; // the number of processes running
  294. struct target
  295. *apps_groups_default_target = NULL, // the default target
  296. *apps_groups_root_target = NULL, // apps_groups.conf defined
  297. *users_root_target = NULL, // users
  298. *groups_root_target = NULL; // user groups
  299. size_t apps_groups_targets_count = 0; // # of apps_groups.conf targets
  300. // ----------------------------------------------------------------------------
  301. // internal counters
  302. static size_t
  303. // global_iterations_counter = 1,
  304. calls_counter = 0,
  305. // file_counter = 0,
  306. // filenames_allocated_counter = 0,
  307. // inodes_changed_counter = 0,
  308. // links_changed_counter = 0,
  309. targets_assignment_counter = 0;
  310. // ----------------------------------------------------------------------------
  311. // debugging
  312. // log each problem once per process
  313. // log flood protection flags (log_thrown)
  314. #define PID_LOG_IO 0x00000001
  315. #define PID_LOG_STATUS 0x00000002
  316. #define PID_LOG_CMDLINE 0x00000004
  317. #define PID_LOG_FDS 0x00000008
  318. #define PID_LOG_STAT 0x00000010
  319. int debug_enabled = 0;
  320. #ifdef NETDATA_INTERNAL_CHECKS
  321. #define debug_log(fmt, args...) \
  322. do { \
  323. if (unlikely(debug_enabled)) \
  324. debug_log_int(fmt, ##args); \
  325. } while (0)
  326. #else
  327. static inline void debug_log_dummy(void)
  328. {
  329. }
  330. #define debug_log(fmt, args...) debug_log_dummy()
  331. #endif
  332. /**
  333. * Managed log
  334. *
  335. * Store log information if it is necessary.
  336. *
  337. * @param p the pid stat structure
  338. * @param log the log id
  339. * @param status the return from a function.
  340. *
  341. * @return It returns the status value.
  342. */
  343. static inline int managed_log(struct pid_stat *p, uint32_t log, int status)
  344. {
  345. if (unlikely(!status)) {
  346. // error("command failed log %u, errno %d", log, errno);
  347. if (unlikely(debug_enabled || errno != ENOENT)) {
  348. if (unlikely(debug_enabled || !(p->log_thrown & log))) {
  349. p->log_thrown |= log;
  350. switch (log) {
  351. case PID_LOG_IO:
  352. error(
  353. "Cannot process %s/proc/%d/io (command '%s')", netdata_configured_host_prefix, p->pid,
  354. p->comm);
  355. break;
  356. case PID_LOG_STATUS:
  357. error(
  358. "Cannot process %s/proc/%d/status (command '%s')", netdata_configured_host_prefix, p->pid,
  359. p->comm);
  360. break;
  361. case PID_LOG_CMDLINE:
  362. error(
  363. "Cannot process %s/proc/%d/cmdline (command '%s')", netdata_configured_host_prefix, p->pid,
  364. p->comm);
  365. break;
  366. case PID_LOG_FDS:
  367. error(
  368. "Cannot process entries in %s/proc/%d/fd (command '%s')", netdata_configured_host_prefix,
  369. p->pid, p->comm);
  370. break;
  371. case PID_LOG_STAT:
  372. break;
  373. default:
  374. error("unhandled error for pid %d, command '%s'", p->pid, p->comm);
  375. break;
  376. }
  377. }
  378. }
  379. errno = 0;
  380. } else if (unlikely(p->log_thrown & log)) {
  381. // error("unsetting log %u on pid %d", log, p->pid);
  382. p->log_thrown &= ~log;
  383. }
  384. return status;
  385. }
  386. /**
  387. * Get PID entry
  388. *
  389. * Get or allocate the PID entry for the specified pid.
  390. *
  391. * @param pid the pid to search the data.
  392. *
  393. * @return It returns the pid entry structure
  394. */
  395. static inline struct pid_stat *get_pid_entry(pid_t pid)
  396. {
  397. if (unlikely(all_pids[pid]))
  398. return all_pids[pid];
  399. struct pid_stat *p = callocz(1, sizeof(struct pid_stat));
  400. if (likely(root_of_pids))
  401. root_of_pids->prev = p;
  402. p->next = root_of_pids;
  403. root_of_pids = p;
  404. p->pid = pid;
  405. all_pids[pid] = p;
  406. all_pids_count++;
  407. return p;
  408. }
  409. /**
  410. * Assign the PID to a target.
  411. *
  412. * @param p the pid_stat structure to assign for a target.
  413. */
  414. static inline void assign_target_to_pid(struct pid_stat *p)
  415. {
  416. targets_assignment_counter++;
  417. uint32_t hash = simple_hash(p->comm);
  418. size_t pclen = strlen(p->comm);
  419. struct target *w;
  420. for (w = apps_groups_root_target; w; w = w->next) {
  421. // if(debug_enabled || (p->target && p->target->debug_enabled)) debug_log_int("\t\tcomparing '%s' with '%s'", w->compare, p->comm);
  422. // find it - 4 cases:
  423. // 1. the target is not a pattern
  424. // 2. the target has the prefix
  425. // 3. the target has the suffix
  426. // 4. the target is something inside cmdline
  427. if (unlikely(
  428. ((!w->starts_with && !w->ends_with && w->comparehash == hash && !strcmp(w->compare, p->comm)) ||
  429. (w->starts_with && !w->ends_with && !strncmp(w->compare, p->comm, w->comparelen)) ||
  430. (!w->starts_with && w->ends_with && pclen >= w->comparelen && !strcmp(w->compare, &p->comm[pclen - w->comparelen])) ||
  431. (proc_pid_cmdline_is_needed && w->starts_with && w->ends_with && p->cmdline && strstr(p->cmdline, w->compare))))) {
  432. if (w->target)
  433. p->target = w->target;
  434. else
  435. p->target = w;
  436. if (debug_enabled || (p->target && p->target->debug_enabled))
  437. debug_log_int("%s linked to target %s", p->comm, p->target->name);
  438. break;
  439. }
  440. }
  441. }
  442. // ----------------------------------------------------------------------------
  443. // update pids from proc
  444. /**
  445. * Read cmd line from /proc/PID/cmdline
  446. *
  447. * @param p the pid_stat_structure.
  448. *
  449. * @return It returns 1 on success and 0 otherwise.
  450. */
  451. static inline int read_proc_pid_cmdline(struct pid_stat *p)
  452. {
  453. static char cmdline[MAX_CMDLINE + 1];
  454. if (unlikely(!p->cmdline_filename)) {
  455. char filename[FILENAME_MAX + 1];
  456. snprintfz(filename, FILENAME_MAX, "%s/proc/%d/cmdline", netdata_configured_host_prefix, p->pid);
  457. p->cmdline_filename = strdupz(filename);
  458. }
  459. int fd = open(p->cmdline_filename, procfile_open_flags, 0666);
  460. if (unlikely(fd == -1))
  461. goto cleanup;
  462. ssize_t i, bytes = read(fd, cmdline, MAX_CMDLINE);
  463. close(fd);
  464. if (unlikely(bytes < 0))
  465. goto cleanup;
  466. cmdline[bytes] = '\0';
  467. for (i = 0; i < bytes; i++) {
  468. if (unlikely(!cmdline[i]))
  469. cmdline[i] = ' ';
  470. }
  471. if (p->cmdline)
  472. freez(p->cmdline);
  473. p->cmdline = strdupz(cmdline);
  474. debug_log("Read file '%s' contents: %s", p->cmdline_filename, p->cmdline);
  475. return 1;
  476. cleanup:
  477. // copy the command to the command line
  478. if (p->cmdline)
  479. freez(p->cmdline);
  480. p->cmdline = strdupz(p->comm);
  481. return 0;
  482. }
  483. /**
  484. * Read information from /proc/PID/stat and /proc/PID/cmdline
  485. * Assign target to pid
  486. *
  487. * @param p the pid stat structure to store the data.
  488. * @param ptr an useless argument.
  489. */
  490. static inline int read_proc_pid_stat(struct pid_stat *p, void *ptr)
  491. {
  492. UNUSED(ptr);
  493. static procfile *ff = NULL;
  494. if (unlikely(!p->stat_filename)) {
  495. char filename[FILENAME_MAX + 1];
  496. snprintfz(filename, FILENAME_MAX, "%s/proc/%d/stat", netdata_configured_host_prefix, p->pid);
  497. p->stat_filename = strdupz(filename);
  498. }
  499. int set_quotes = (!ff) ? 1 : 0;
  500. struct stat statbuf;
  501. if (stat(p->stat_filename, &statbuf))
  502. return 0;
  503. ff = procfile_reopen(ff, p->stat_filename, NULL, PROCFILE_FLAG_NO_ERROR_ON_FILE_IO);
  504. if (unlikely(!ff))
  505. return 0;
  506. if (unlikely(set_quotes))
  507. procfile_set_open_close(ff, "(", ")");
  508. ff = procfile_readall(ff);
  509. if (unlikely(!ff))
  510. return 0;
  511. p->last_stat_collected_usec = p->stat_collected_usec;
  512. p->stat_collected_usec = now_monotonic_usec();
  513. calls_counter++;
  514. char *comm = procfile_lineword(ff, 0, 1);
  515. p->ppid = (int32_t)str2pid_t(procfile_lineword(ff, 0, 3));
  516. if (strcmp(p->comm, comm) != 0) {
  517. if (unlikely(debug_enabled)) {
  518. if (p->comm[0])
  519. debug_log("\tpid %d (%s) changed name to '%s'", p->pid, p->comm, comm);
  520. else
  521. debug_log("\tJust added %d (%s)", p->pid, comm);
  522. }
  523. strncpyz(p->comm, comm, MAX_COMPARE_NAME);
  524. // /proc/<pid>/cmdline
  525. if (likely(proc_pid_cmdline_is_needed))
  526. managed_log(p, PID_LOG_CMDLINE, read_proc_pid_cmdline(p));
  527. assign_target_to_pid(p);
  528. }
  529. if (unlikely(debug_enabled || (p->target && p->target->debug_enabled)))
  530. debug_log_int(
  531. "READ PROC/PID/STAT: %s/proc/%d/stat, process: '%s' on target '%s' (dt=%llu)",
  532. netdata_configured_host_prefix, p->pid, p->comm, (p->target) ? p->target->name : "UNSET",
  533. p->stat_collected_usec - p->last_stat_collected_usec);
  534. return 1;
  535. }
  536. /**
  537. * Collect data for PID
  538. *
  539. * @param pid the current pid that we are working
  540. * @param ptr a NULL value
  541. *
  542. * @return It returns 1 on success and 0 otherwise
  543. */
  544. static inline int collect_data_for_pid(pid_t pid, void *ptr)
  545. {
  546. if (unlikely(pid < 0 || pid > pid_max)) {
  547. error("Invalid pid %d read (expected %d to %d). Ignoring process.", pid, 0, pid_max);
  548. return 0;
  549. }
  550. struct pid_stat *p = get_pid_entry(pid);
  551. if (unlikely(!p || p->read))
  552. return 0;
  553. p->read = 1;
  554. if (unlikely(!managed_log(p, PID_LOG_STAT, read_proc_pid_stat(p, ptr))))
  555. // there is no reason to proceed if we cannot get its status
  556. return 0;
  557. // check its parent pid
  558. if (unlikely(p->ppid < 0 || p->ppid > pid_max)) {
  559. error("Pid %d (command '%s') states invalid parent pid %d. Using 0.", pid, p->comm, p->ppid);
  560. p->ppid = 0;
  561. }
  562. // mark it as updated
  563. p->updated = 1;
  564. p->keep = 0;
  565. p->keeploops = 0;
  566. return 1;
  567. }
  568. /**
  569. * Fill link list of parents with children PIDs
  570. */
  571. static inline void link_all_processes_to_their_parents(void)
  572. {
  573. struct pid_stat *p, *pp;
  574. // link all children to their parents
  575. // and update children count on parents
  576. for (p = root_of_pids; p; p = p->next) {
  577. // for each process found
  578. p->sortlist = 0;
  579. p->parent = NULL;
  580. if (unlikely(!p->ppid)) {
  581. p->parent = NULL;
  582. continue;
  583. }
  584. pp = all_pids[p->ppid];
  585. if (likely(pp)) {
  586. p->parent = pp;
  587. pp->children_count++;
  588. if (unlikely(debug_enabled || (p->target && p->target->debug_enabled)))
  589. debug_log_int(
  590. "child %d (%s, %s) on target '%s' has parent %d (%s, %s).", p->pid, p->comm,
  591. p->updated ? "running" : "exited", (p->target) ? p->target->name : "UNSET", pp->pid, pp->comm,
  592. pp->updated ? "running" : "exited");
  593. } else {
  594. p->parent = NULL;
  595. debug_log("pid %d %s states parent %d, but the later does not exist.", p->pid, p->comm, p->ppid);
  596. }
  597. }
  598. }
  599. /**
  600. * Aggregate PIDs to targets.
  601. */
  602. static void apply_apps_groups_targets_inheritance(void)
  603. {
  604. struct pid_stat *p = NULL;
  605. // children that do not have a target
  606. // inherit their target from their parent
  607. int found = 1, loops = 0;
  608. while (found) {
  609. if (unlikely(debug_enabled))
  610. loops++;
  611. found = 0;
  612. for (p = root_of_pids; p; p = p->next) {
  613. // if this process does not have a target
  614. // and it has a parent
  615. // and its parent has a target
  616. // then, set the parent's target to this process
  617. if (unlikely(!p->target && p->parent && p->parent->target)) {
  618. p->target = p->parent->target;
  619. found++;
  620. if (debug_enabled || (p->target && p->target->debug_enabled))
  621. debug_log_int(
  622. "TARGET INHERITANCE: %s is inherited by %d (%s) from its parent %d (%s).", p->target->name,
  623. p->pid, p->comm, p->parent->pid, p->parent->comm);
  624. }
  625. }
  626. }
  627. // find all the procs with 0 childs and merge them to their parents
  628. // repeat, until nothing more can be done.
  629. int sortlist = 1;
  630. found = 1;
  631. while (found) {
  632. if (unlikely(debug_enabled))
  633. loops++;
  634. found = 0;
  635. for (p = root_of_pids; p; p = p->next) {
  636. if (unlikely(!p->sortlist && !p->children_count))
  637. p->sortlist = sortlist++;
  638. if (unlikely(
  639. !p->children_count // if this process does not have any children
  640. && !p->merged // and is not already merged
  641. && p->parent // and has a parent
  642. && p->parent->children_count // and its parent has children
  643. // and the target of this process and its parent is the same,
  644. // or the parent does not have a target
  645. && (p->target == p->parent->target || !p->parent->target) &&
  646. p->ppid != INIT_PID // and its parent is not init
  647. )) {
  648. // mark it as merged
  649. p->parent->children_count--;
  650. p->merged = 1;
  651. // the parent inherits the child's target, if it does not have a target itself
  652. if (unlikely(p->target && !p->parent->target)) {
  653. p->parent->target = p->target;
  654. if (debug_enabled || (p->target && p->target->debug_enabled))
  655. debug_log_int(
  656. "TARGET INHERITANCE: %s is inherited by %d (%s) from its child %d (%s).", p->target->name,
  657. p->parent->pid, p->parent->comm, p->pid, p->comm);
  658. }
  659. found++;
  660. }
  661. }
  662. debug_log("TARGET INHERITANCE: merged %d processes", found);
  663. }
  664. // init goes always to default target
  665. if (all_pids[INIT_PID])
  666. all_pids[INIT_PID]->target = apps_groups_default_target;
  667. // pid 0 goes always to default target
  668. if (all_pids[0])
  669. all_pids[0]->target = apps_groups_default_target;
  670. // give a default target on all top level processes
  671. if (unlikely(debug_enabled))
  672. loops++;
  673. for (p = root_of_pids; p; p = p->next) {
  674. // if the process is not merged itself
  675. // then is is a top level process
  676. if (unlikely(!p->merged && !p->target))
  677. p->target = apps_groups_default_target;
  678. // make sure all processes have a sortlist
  679. if (unlikely(!p->sortlist))
  680. p->sortlist = sortlist++;
  681. }
  682. if (all_pids[1])
  683. all_pids[1]->sortlist = sortlist++;
  684. // give a target to all merged child processes
  685. found = 1;
  686. while (found) {
  687. if (unlikely(debug_enabled))
  688. loops++;
  689. found = 0;
  690. for (p = root_of_pids; p; p = p->next) {
  691. if (unlikely(!p->target && p->merged && p->parent && p->parent->target)) {
  692. p->target = p->parent->target;
  693. found++;
  694. if (debug_enabled || (p->target && p->target->debug_enabled))
  695. debug_log_int(
  696. "TARGET INHERITANCE: %s is inherited by %d (%s) from its parent %d (%s) at phase 2.",
  697. p->target->name, p->pid, p->comm, p->parent->pid, p->parent->comm);
  698. }
  699. }
  700. }
  701. debug_log("apply_apps_groups_targets_inheritance() made %d loops on the process tree", loops);
  702. }
  703. /**
  704. * Update target timestamp.
  705. *
  706. * @param root the targets that will be updated.
  707. */
  708. static inline void post_aggregate_targets(struct target *root)
  709. {
  710. struct target *w;
  711. for (w = root; w; w = w->next) {
  712. if (w->collected_starttime) {
  713. if (!w->starttime || w->collected_starttime < w->starttime) {
  714. w->starttime = w->collected_starttime;
  715. }
  716. } else {
  717. w->starttime = 0;
  718. }
  719. }
  720. }
  721. /**
  722. * Remove PID from the link list.
  723. *
  724. * @param pid the PID that will be removed.
  725. */
  726. static inline void del_pid_entry(pid_t pid)
  727. {
  728. struct pid_stat *p = all_pids[pid];
  729. if (unlikely(!p)) {
  730. error("attempted to free pid %d that is not allocated.", pid);
  731. return;
  732. }
  733. debug_log("process %d %s exited, deleting it.", pid, p->comm);
  734. if (root_of_pids == p)
  735. root_of_pids = p->next;
  736. if (p->next)
  737. p->next->prev = p->prev;
  738. if (p->prev)
  739. p->prev->next = p->next;
  740. freez(p->stat_filename);
  741. freez(p->status_filename);
  742. freez(p->io_filename);
  743. freez(p->cmdline_filename);
  744. freez(p->cmdline);
  745. freez(p);
  746. all_pids[pid] = NULL;
  747. all_pids_count--;
  748. }
  749. /**
  750. * Get command string associated with a PID.
  751. * This can only safely be used when holding the `collect_data_mutex` lock.
  752. *
  753. * @param pid the pid to search the data.
  754. * @param n the maximum amount of bytes to copy into dest.
  755. * if this is greater than the size of the command, it is clipped.
  756. * @param dest the target memory buffer to write the command into.
  757. * @return -1 if the PID hasn't been scraped yet, 0 otherwise.
  758. */
  759. int get_pid_comm(pid_t pid, size_t n, char *dest)
  760. {
  761. struct pid_stat *stat;
  762. stat = all_pids[pid];
  763. if (unlikely(stat == NULL)) {
  764. return -1;
  765. }
  766. if (unlikely(n > sizeof(stat->comm))) {
  767. n = sizeof(stat->comm);
  768. }
  769. strncpyz(dest, stat->comm, n);
  770. return 0;
  771. }
  772. /**
  773. * Cleanup variable from other threads
  774. *
  775. * @param pid current pid.
  776. */
  777. void cleanup_variables_from_other_threads(uint32_t pid)
  778. {
  779. // Clean socket structures
  780. if (socket_bandwidth_curr) {
  781. freez(socket_bandwidth_curr[pid]);
  782. socket_bandwidth_curr[pid] = NULL;
  783. }
  784. // Clean cachestat structure
  785. if (cachestat_pid) {
  786. freez(cachestat_pid[pid]);
  787. cachestat_pid[pid] = NULL;
  788. }
  789. // Clean directory cache structure
  790. if (dcstat_pid) {
  791. freez(dcstat_pid[pid]);
  792. dcstat_pid[pid] = NULL;
  793. }
  794. // Clean swap structure
  795. if (swap_pid) {
  796. freez(swap_pid[pid]);
  797. swap_pid[pid] = NULL;
  798. }
  799. // Clean vfs structure
  800. if (vfs_pid) {
  801. freez(vfs_pid[pid]);
  802. vfs_pid[pid] = NULL;
  803. }
  804. // Clean fd structure
  805. if (fd_pid) {
  806. freez(fd_pid[pid]);
  807. fd_pid[pid] = NULL;
  808. }
  809. // Clean shm structure
  810. if (shm_pid) {
  811. freez(shm_pid[pid]);
  812. shm_pid[pid] = NULL;
  813. }
  814. }
  815. /**
  816. * Remove PIDs when they are not running more.
  817. */
  818. void cleanup_exited_pids()
  819. {
  820. struct pid_stat *p = NULL;
  821. for (p = root_of_pids; p;) {
  822. if (!p->updated && (!p->keep || p->keeploops > 0)) {
  823. if (unlikely(debug_enabled && (p->keep || p->keeploops)))
  824. debug_log(" > CLEANUP cannot keep exited process %d (%s) anymore - removing it.", p->pid, p->comm);
  825. pid_t r = p->pid;
  826. p = p->next;
  827. // Clean process structure
  828. freez(global_process_stats[r]);
  829. global_process_stats[r] = NULL;
  830. freez(current_apps_data[r]);
  831. current_apps_data[r] = NULL;
  832. cleanup_variables_from_other_threads(r);
  833. del_pid_entry(r);
  834. } else {
  835. if (unlikely(p->keep))
  836. p->keeploops++;
  837. p->keep = 0;
  838. p = p->next;
  839. }
  840. }
  841. }
  842. /**
  843. * Read proc filesystem for the first time.
  844. *
  845. * @return It returns 0 on success and -1 otherwise.
  846. */
  847. static inline void read_proc_filesystem()
  848. {
  849. char dirname[FILENAME_MAX + 1];
  850. snprintfz(dirname, FILENAME_MAX, "%s/proc", netdata_configured_host_prefix);
  851. DIR *dir = opendir(dirname);
  852. if (!dir)
  853. return;
  854. struct dirent *de = NULL;
  855. while ((de = readdir(dir))) {
  856. char *endptr = de->d_name;
  857. if (unlikely(de->d_type != DT_DIR || de->d_name[0] < '0' || de->d_name[0] > '9'))
  858. continue;
  859. pid_t pid = (pid_t)strtoul(de->d_name, &endptr, 10);
  860. // make sure we read a valid number
  861. if (unlikely(endptr == de->d_name || *endptr != '\0'))
  862. continue;
  863. collect_data_for_pid(pid, NULL);
  864. }
  865. closedir(dir);
  866. }
  867. /**
  868. * Aggregated PID on target
  869. *
  870. * @param w the target output
  871. * @param p the pid with information to update
  872. * @param o never used
  873. */
  874. static inline void aggregate_pid_on_target(struct target *w, struct pid_stat *p, struct target *o)
  875. {
  876. UNUSED(o);
  877. if (unlikely(!p->updated)) {
  878. // the process is not running
  879. return;
  880. }
  881. if (unlikely(!w)) {
  882. error("pid %d %s was left without a target!", p->pid, p->comm);
  883. return;
  884. }
  885. w->processes++;
  886. struct pid_on_target *pid_on_target = mallocz(sizeof(struct pid_on_target));
  887. pid_on_target->pid = p->pid;
  888. pid_on_target->next = w->root_pid;
  889. w->root_pid = pid_on_target;
  890. }
  891. /**
  892. * Collect data for all process
  893. *
  894. * Read data from hash table and store it in appropriate vectors.
  895. * It also creates the link between targets and PIDs.
  896. *
  897. * @param tbl_pid_stats_fd The mapped file descriptor for the hash table.
  898. */
  899. void collect_data_for_all_processes(int tbl_pid_stats_fd)
  900. {
  901. if (unlikely(!all_pids))
  902. return;
  903. struct pid_stat *pids = root_of_pids; // global list of all processes running
  904. while (pids) {
  905. if (pids->updated_twice) {
  906. pids->read = 0; // mark it as not read, so that collect_data_for_pid() will read it
  907. pids->updated = 0;
  908. pids->merged = 0;
  909. pids->children_count = 0;
  910. pids->parent = NULL;
  911. } else {
  912. if (pids->updated)
  913. pids->updated_twice = 1;
  914. }
  915. pids = pids->next;
  916. }
  917. read_proc_filesystem();
  918. uint32_t key;
  919. pids = root_of_pids; // global list of all processes running
  920. // while (bpf_map_get_next_key(tbl_pid_stats_fd, &key, &next_key) == 0) {
  921. while (pids) {
  922. key = pids->pid;
  923. ebpf_process_stat_t *w = global_process_stats[key];
  924. if (!w) {
  925. w = mallocz(sizeof(ebpf_process_stat_t));
  926. global_process_stats[key] = w;
  927. }
  928. if (bpf_map_lookup_elem(tbl_pid_stats_fd, &key, w)) {
  929. // Clean Process structures
  930. freez(w);
  931. global_process_stats[key] = NULL;
  932. freez(current_apps_data[key]);
  933. current_apps_data[key] = NULL;
  934. cleanup_variables_from_other_threads(key);
  935. pids = pids->next;
  936. continue;
  937. }
  938. pids = pids->next;
  939. }
  940. link_all_processes_to_their_parents();
  941. apply_apps_groups_targets_inheritance();
  942. apps_groups_targets_count = zero_all_targets(apps_groups_root_target);
  943. // this has to be done, before the cleanup
  944. // // concentrate everything on the targets
  945. for (pids = root_of_pids; pids; pids = pids->next)
  946. aggregate_pid_on_target(pids->target, pids, NULL);
  947. post_aggregate_targets(apps_groups_root_target);
  948. }