daemon.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #include "common.h"
  3. #include <sched.h>
  4. char pidfile[FILENAME_MAX + 1] = "";
  5. char claiming_directory[FILENAME_MAX + 1];
  6. char netdata_exe_path[FILENAME_MAX + 1];
  7. char netdata_exe_file[FILENAME_MAX + 1];
  8. void get_netdata_execution_path(void) {
  9. int ret;
  10. size_t exepath_size = 0;
  11. struct passwd *passwd = NULL;
  12. char *user = NULL;
  13. passwd = getpwuid(getuid());
  14. user = (passwd && passwd->pw_name) ? passwd->pw_name : "";
  15. exepath_size = sizeof(netdata_exe_file) - 1;
  16. ret = uv_exepath(netdata_exe_file, &exepath_size);
  17. if (0 != ret) {
  18. netdata_log_error("uv_exepath(\"%s\", %u) (user: %s) failed (%s).", netdata_exe_file, (unsigned)exepath_size, user,
  19. uv_strerror(ret));
  20. fatal("Cannot start netdata without getting execution path.");
  21. }
  22. netdata_exe_file[exepath_size] = '\0';
  23. strcpy(netdata_exe_path, netdata_exe_file);
  24. dirname(netdata_exe_path);
  25. }
  26. static void chown_open_file(int fd, uid_t uid, gid_t gid) {
  27. if(fd == -1) return;
  28. struct stat buf;
  29. if(fstat(fd, &buf) == -1) {
  30. netdata_log_error("Cannot fstat() fd %d", fd);
  31. return;
  32. }
  33. if((buf.st_uid != uid || buf.st_gid != gid) && S_ISREG(buf.st_mode)) {
  34. if(fchown(fd, uid, gid) == -1)
  35. netdata_log_error("Cannot fchown() fd %d.", fd);
  36. }
  37. }
  38. static void fix_directory_file_permissions(const char *dirname, uid_t uid, gid_t gid, bool recursive)
  39. {
  40. char filename[FILENAME_MAX + 1];
  41. DIR *dir = opendir(dirname);
  42. if (!dir)
  43. return;
  44. struct dirent *de = NULL;
  45. while ((de = readdir(dir))) {
  46. if (de->d_type == DT_DIR && (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")))
  47. continue;
  48. (void) snprintfz(filename, FILENAME_MAX, "%s/%s", dirname, de->d_name);
  49. if (de->d_type == DT_REG || recursive) {
  50. if (chown(filename, uid, gid) == -1)
  51. netdata_log_error("Cannot chown %s '%s' to %u:%u", de->d_type == DT_DIR ? "directory" : "file", filename, (unsigned int)uid, (unsigned int)gid);
  52. }
  53. if (de->d_type == DT_DIR && recursive)
  54. fix_directory_file_permissions(filename, uid, gid, recursive);
  55. }
  56. closedir(dir);
  57. }
  58. void change_dir_ownership(const char *dir, uid_t uid, gid_t gid, bool recursive)
  59. {
  60. if (chown(dir, uid, gid) == -1)
  61. netdata_log_error("Cannot chown directory '%s' to %u:%u", dir, (unsigned int)uid, (unsigned int)gid);
  62. fix_directory_file_permissions(dir, uid, gid, recursive);
  63. }
  64. void clean_directory(char *dirname)
  65. {
  66. DIR *dir = opendir(dirname);
  67. if(!dir) return;
  68. int dir_fd = dirfd(dir);
  69. struct dirent *de = NULL;
  70. while((de = readdir(dir)))
  71. if(de->d_type == DT_REG)
  72. if (unlinkat(dir_fd, de->d_name, 0))
  73. netdata_log_error("Cannot delete %s/%s", dirname, de->d_name);
  74. closedir(dir);
  75. }
  76. void prepare_required_directories(uid_t uid, gid_t gid) {
  77. change_dir_ownership(netdata_configured_cache_dir, uid, gid, true);
  78. change_dir_ownership(netdata_configured_varlib_dir, uid, gid, false);
  79. change_dir_ownership(netdata_configured_lock_dir, uid, gid, false);
  80. change_dir_ownership(netdata_configured_log_dir, uid, gid, false);
  81. change_dir_ownership(claiming_directory, uid, gid, false);
  82. char filename[FILENAME_MAX + 1];
  83. snprintfz(filename, FILENAME_MAX, "%s/registry", netdata_configured_varlib_dir);
  84. change_dir_ownership(filename, uid, gid, false);
  85. clean_directory(netdata_configured_lock_dir);
  86. }
  87. int become_user(const char *username, int pid_fd) {
  88. int am_i_root = (getuid() == 0)?1:0;
  89. struct passwd *pw = getpwnam(username);
  90. if(!pw) {
  91. netdata_log_error("User %s is not present.", username);
  92. return -1;
  93. }
  94. uid_t uid = pw->pw_uid;
  95. gid_t gid = pw->pw_gid;
  96. if (am_i_root)
  97. netdata_log_info("I am root, so checking permissions");
  98. prepare_required_directories(uid, gid);
  99. if(pidfile[0]) {
  100. if(chown(pidfile, uid, gid) == -1)
  101. netdata_log_error("Cannot chown '%s' to %u:%u", pidfile, (unsigned int)uid, (unsigned int)gid);
  102. }
  103. int ngroups = (int)sysconf(_SC_NGROUPS_MAX);
  104. gid_t *supplementary_groups = NULL;
  105. if(ngroups > 0) {
  106. supplementary_groups = mallocz(sizeof(gid_t) * ngroups);
  107. #ifdef __APPLE__
  108. if(getgrouplist(username, gid, (int *)supplementary_groups, &ngroups) == -1) {
  109. #else
  110. if(getgrouplist(username, gid, supplementary_groups, &ngroups) == -1) {
  111. #endif /* __APPLE__ */
  112. if(am_i_root)
  113. netdata_log_error("Cannot get supplementary groups of user '%s'.", username);
  114. ngroups = 0;
  115. }
  116. }
  117. chown_open_file(STDOUT_FILENO, uid, gid);
  118. chown_open_file(STDERR_FILENO, uid, gid);
  119. chown_open_file(stdaccess_fd, uid, gid);
  120. chown_open_file(pid_fd, uid, gid);
  121. if(supplementary_groups && ngroups > 0) {
  122. if(setgroups((size_t)ngroups, supplementary_groups) == -1) {
  123. if(am_i_root)
  124. netdata_log_error("Cannot set supplementary groups for user '%s'", username);
  125. }
  126. ngroups = 0;
  127. }
  128. if(supplementary_groups)
  129. freez(supplementary_groups);
  130. #ifdef __APPLE__
  131. if(setregid(gid, gid) != 0) {
  132. #else
  133. if(setresgid(gid, gid, gid) != 0) {
  134. #endif /* __APPLE__ */
  135. netdata_log_error("Cannot switch to user's %s group (gid: %u).", username, gid);
  136. return -1;
  137. }
  138. #ifdef __APPLE__
  139. if(setreuid(uid, uid) != 0) {
  140. #else
  141. if(setresuid(uid, uid, uid) != 0) {
  142. #endif /* __APPLE__ */
  143. netdata_log_error("Cannot switch to user %s (uid: %u).", username, uid);
  144. return -1;
  145. }
  146. if(setgid(gid) != 0) {
  147. netdata_log_error("Cannot switch to user's %s group (gid: %u).", username, gid);
  148. return -1;
  149. }
  150. if(setegid(gid) != 0) {
  151. netdata_log_error("Cannot effectively switch to user's %s group (gid: %u).", username, gid);
  152. return -1;
  153. }
  154. if(setuid(uid) != 0) {
  155. netdata_log_error("Cannot switch to user %s (uid: %u).", username, uid);
  156. return -1;
  157. }
  158. if(seteuid(uid) != 0) {
  159. netdata_log_error("Cannot effectively switch to user %s (uid: %u).", username, uid);
  160. return -1;
  161. }
  162. return(0);
  163. }
  164. #ifndef OOM_SCORE_ADJ_MAX
  165. #define OOM_SCORE_ADJ_MAX (1000)
  166. #endif
  167. #ifndef OOM_SCORE_ADJ_MIN
  168. #define OOM_SCORE_ADJ_MIN (-1000)
  169. #endif
  170. static void oom_score_adj(void) {
  171. char buf[30 + 1];
  172. long long int old_score, wanted_score = 0, final_score = 0;
  173. // read the existing score
  174. if(read_single_signed_number_file("/proc/self/oom_score_adj", &old_score)) {
  175. netdata_log_error("Out-Of-Memory (OOM) score setting is not supported on this system.");
  176. return;
  177. }
  178. if (old_score != 0) {
  179. wanted_score = old_score;
  180. analytics_report_oom_score(old_score);
  181. }
  182. // check the environment
  183. char *s = getenv("OOMScoreAdjust");
  184. if(!s || !*s) {
  185. snprintfz(buf, 30, "%d", (int)wanted_score);
  186. s = buf;
  187. }
  188. // check netdata.conf configuration
  189. s = config_get(CONFIG_SECTION_GLOBAL, "OOM score", s);
  190. if(s && *s && (isdigit(*s) || *s == '-' || *s == '+'))
  191. wanted_score = atoll(s);
  192. else if(s && !strcmp(s, "keep")) {
  193. netdata_log_info("Out-Of-Memory (OOM) kept as-is (running with %d)", (int) old_score);
  194. return;
  195. }
  196. else {
  197. netdata_log_info("Out-Of-Memory (OOM) score not changed due to non-numeric setting: '%s' (running with %d)", s, (int)old_score);
  198. return;
  199. }
  200. if(wanted_score < OOM_SCORE_ADJ_MIN) {
  201. netdata_log_error("Wanted Out-Of-Memory (OOM) score %d is too small. Using %d", (int)wanted_score, (int)OOM_SCORE_ADJ_MIN);
  202. wanted_score = OOM_SCORE_ADJ_MIN;
  203. }
  204. if(wanted_score > OOM_SCORE_ADJ_MAX) {
  205. netdata_log_error("Wanted Out-Of-Memory (OOM) score %d is too big. Using %d", (int)wanted_score, (int)OOM_SCORE_ADJ_MAX);
  206. wanted_score = OOM_SCORE_ADJ_MAX;
  207. }
  208. if(old_score == wanted_score) {
  209. netdata_log_info("Out-Of-Memory (OOM) score is already set to the wanted value %d", (int)old_score);
  210. return;
  211. }
  212. int written = 0;
  213. int fd = open("/proc/self/oom_score_adj", O_WRONLY);
  214. if(fd != -1) {
  215. snprintfz(buf, 30, "%d", (int)wanted_score);
  216. ssize_t len = strlen(buf);
  217. if(len > 0 && write(fd, buf, (size_t)len) == len) written = 1;
  218. close(fd);
  219. if(written) {
  220. if(read_single_signed_number_file("/proc/self/oom_score_adj", &final_score))
  221. netdata_log_error("Adjusted my Out-Of-Memory (OOM) score to %d, but cannot verify it.", (int)wanted_score);
  222. else if(final_score == wanted_score)
  223. netdata_log_info("Adjusted my Out-Of-Memory (OOM) score from %d to %d.", (int)old_score, (int)final_score);
  224. else
  225. netdata_log_error("Adjusted my Out-Of-Memory (OOM) score from %d to %d, but it has been set to %d.", (int)old_score, (int)wanted_score, (int)final_score);
  226. analytics_report_oom_score(final_score);
  227. }
  228. else
  229. netdata_log_error("Failed to adjust my Out-Of-Memory (OOM) score to %d. Running with %d. (systemd systems may change it via netdata.service)", (int)wanted_score, (int)old_score);
  230. }
  231. else
  232. netdata_log_error("Failed to adjust my Out-Of-Memory (OOM) score. Cannot open /proc/self/oom_score_adj for writing.");
  233. }
  234. static void process_nice_level(void) {
  235. #ifdef HAVE_NICE
  236. int nice_level = (int)config_get_number(CONFIG_SECTION_GLOBAL, "process nice level", 19);
  237. if(nice(nice_level) == -1)
  238. netdata_log_error("Cannot set netdata CPU nice level to %d.", nice_level);
  239. else
  240. netdata_log_debug(D_SYSTEM, "Set netdata nice level to %d.", nice_level);
  241. #endif // HAVE_NICE
  242. };
  243. #define SCHED_FLAG_NONE 0x00
  244. #define SCHED_FLAG_PRIORITY_CONFIGURABLE 0x01 // the priority is user configurable
  245. #define SCHED_FLAG_KEEP_AS_IS 0x04 // do not attempt to set policy, priority or nice()
  246. #define SCHED_FLAG_USE_NICE 0x08 // use nice() after setting this policy
  247. struct sched_def {
  248. char *name;
  249. int policy;
  250. int priority;
  251. uint8_t flags;
  252. } scheduler_defaults[] = {
  253. // the order of array members is important!
  254. // the first defined is the default used by netdata
  255. // the available members are important too!
  256. // these are all the possible scheduling policies supported by netdata
  257. #ifdef SCHED_BATCH
  258. { "batch", SCHED_BATCH, 0, SCHED_FLAG_USE_NICE },
  259. #endif
  260. #ifdef SCHED_OTHER
  261. { "other", SCHED_OTHER, 0, SCHED_FLAG_USE_NICE },
  262. { "nice", SCHED_OTHER, 0, SCHED_FLAG_USE_NICE },
  263. #endif
  264. #ifdef SCHED_IDLE
  265. { "idle", SCHED_IDLE, 0, SCHED_FLAG_NONE },
  266. #endif
  267. #ifdef SCHED_RR
  268. { "rr", SCHED_RR, 0, SCHED_FLAG_PRIORITY_CONFIGURABLE },
  269. #endif
  270. #ifdef SCHED_FIFO
  271. { "fifo", SCHED_FIFO, 0, SCHED_FLAG_PRIORITY_CONFIGURABLE },
  272. #endif
  273. // do not change the scheduling priority
  274. { "keep", 0, 0, SCHED_FLAG_KEEP_AS_IS },
  275. { "none", 0, 0, SCHED_FLAG_KEEP_AS_IS },
  276. // array termination
  277. { NULL, 0, 0, 0 }
  278. };
  279. #ifdef HAVE_SCHED_GETSCHEDULER
  280. static void sched_getscheduler_report(void) {
  281. int sched = sched_getscheduler(0);
  282. if(sched == -1) {
  283. netdata_log_error("Cannot get my current process scheduling policy.");
  284. return;
  285. }
  286. else {
  287. int i;
  288. for(i = 0 ; scheduler_defaults[i].name ; i++) {
  289. if(scheduler_defaults[i].policy == sched) {
  290. if(scheduler_defaults[i].flags & SCHED_FLAG_PRIORITY_CONFIGURABLE) {
  291. struct sched_param param;
  292. if(sched_getparam(0, &param) == -1) {
  293. netdata_log_error("Cannot get the process scheduling priority for my policy '%s'", scheduler_defaults[i].name);
  294. return;
  295. }
  296. else {
  297. netdata_log_info("Running with process scheduling policy '%s', priority %d", scheduler_defaults[i].name, param.sched_priority);
  298. }
  299. }
  300. else if(scheduler_defaults[i].flags & SCHED_FLAG_USE_NICE) {
  301. #ifdef HAVE_GETPRIORITY
  302. int n = getpriority(PRIO_PROCESS, 0);
  303. netdata_log_info("Running with process scheduling policy '%s', nice level %d", scheduler_defaults[i].name, n);
  304. #else // !HAVE_GETPRIORITY
  305. netdata_log_info("Running with process scheduling policy '%s'", scheduler_defaults[i].name);
  306. #endif // !HAVE_GETPRIORITY
  307. }
  308. else {
  309. netdata_log_info("Running with process scheduling policy '%s'", scheduler_defaults[i].name);
  310. }
  311. return;
  312. }
  313. }
  314. }
  315. }
  316. #endif /* HAVE_SCHED_GETSCHEDULER */
  317. #ifdef HAVE_SCHED_SETSCHEDULER
  318. static void sched_setscheduler_set(void) {
  319. if(scheduler_defaults[0].name) {
  320. const char *name = scheduler_defaults[0].name;
  321. int policy = scheduler_defaults[0].policy, priority = scheduler_defaults[0].priority;
  322. uint8_t flags = scheduler_defaults[0].flags;
  323. int found = 0;
  324. // read the configuration
  325. name = config_get(CONFIG_SECTION_GLOBAL, "process scheduling policy", name);
  326. int i;
  327. for(i = 0 ; scheduler_defaults[i].name ; i++) {
  328. if(!strcmp(name, scheduler_defaults[i].name)) {
  329. found = 1;
  330. policy = scheduler_defaults[i].policy;
  331. priority = scheduler_defaults[i].priority;
  332. flags = scheduler_defaults[i].flags;
  333. if(flags & SCHED_FLAG_KEEP_AS_IS)
  334. goto report;
  335. if(flags & SCHED_FLAG_PRIORITY_CONFIGURABLE)
  336. priority = (int)config_get_number(CONFIG_SECTION_GLOBAL, "process scheduling priority", priority);
  337. #ifdef HAVE_SCHED_GET_PRIORITY_MIN
  338. errno = 0;
  339. if(priority < sched_get_priority_min(policy)) {
  340. netdata_log_error("scheduler %s (%d) priority %d is below the minimum %d. Using the minimum.", name, policy, priority, sched_get_priority_min(policy));
  341. priority = sched_get_priority_min(policy);
  342. }
  343. #endif
  344. #ifdef HAVE_SCHED_GET_PRIORITY_MAX
  345. errno = 0;
  346. if(priority > sched_get_priority_max(policy)) {
  347. netdata_log_error("scheduler %s (%d) priority %d is above the maximum %d. Using the maximum.", name, policy, priority, sched_get_priority_max(policy));
  348. priority = sched_get_priority_max(policy);
  349. }
  350. #endif
  351. break;
  352. }
  353. }
  354. if(!found) {
  355. netdata_log_error("Unknown scheduling policy '%s' - falling back to nice", name);
  356. goto fallback;
  357. }
  358. const struct sched_param param = {
  359. .sched_priority = priority
  360. };
  361. errno = 0;
  362. i = sched_setscheduler(0, policy, &param);
  363. if(i != 0) {
  364. netdata_log_error("Cannot adjust netdata scheduling policy to %s (%d), with priority %d. Falling back to nice.",
  365. name,
  366. policy,
  367. priority);
  368. }
  369. else {
  370. netdata_log_info("Adjusted netdata scheduling policy to %s (%d), with priority %d.", name, policy, priority);
  371. if(!(flags & SCHED_FLAG_USE_NICE))
  372. goto report;
  373. }
  374. }
  375. fallback:
  376. process_nice_level();
  377. report:
  378. sched_getscheduler_report();
  379. }
  380. #else /* HAVE_SCHED_SETSCHEDULER */
  381. static void sched_setscheduler_set(void) {
  382. process_nice_level();
  383. }
  384. #endif /* HAVE_SCHED_SETSCHEDULER */
  385. int become_daemon(int dont_fork, const char *user)
  386. {
  387. if(!dont_fork) {
  388. int i = fork();
  389. if(i == -1) {
  390. perror("cannot fork");
  391. exit(1);
  392. }
  393. if(i != 0) {
  394. exit(0); // the parent
  395. }
  396. // become session leader
  397. if (setsid() < 0) {
  398. perror("Cannot become session leader.");
  399. exit(2);
  400. }
  401. // fork() again
  402. i = fork();
  403. if(i == -1) {
  404. perror("cannot fork");
  405. exit(1);
  406. }
  407. if(i != 0) {
  408. exit(0); // the parent
  409. }
  410. }
  411. // generate our pid file
  412. int pidfd = -1;
  413. if(pidfile[0]) {
  414. pidfd = open(pidfile, O_WRONLY | O_CREAT, 0644);
  415. if(pidfd >= 0) {
  416. if(ftruncate(pidfd, 0) != 0)
  417. netdata_log_error("Cannot truncate pidfile '%s'.", pidfile);
  418. char b[100];
  419. sprintf(b, "%d\n", getpid());
  420. ssize_t i = write(pidfd, b, strlen(b));
  421. if(i <= 0)
  422. netdata_log_error("Cannot write pidfile '%s'.", pidfile);
  423. }
  424. else
  425. netdata_log_error("Failed to open pidfile '%s'.", pidfile);
  426. }
  427. // Set new file permissions
  428. umask(0007);
  429. // adjust my Out-Of-Memory score
  430. oom_score_adj();
  431. // never become a problem
  432. sched_setscheduler_set();
  433. // Set claiming directory based on user config directory with correct ownership
  434. snprintfz(claiming_directory, FILENAME_MAX, "%s/cloud.d", netdata_configured_varlib_dir);
  435. if(user && *user) {
  436. if(become_user(user, pidfd) != 0) {
  437. netdata_log_error("Cannot become user '%s'. Continuing as we are.", user);
  438. }
  439. else
  440. netdata_log_debug(D_SYSTEM, "Successfully became user '%s'.", user);
  441. }
  442. else {
  443. prepare_required_directories(getuid(), getgid());
  444. }
  445. if(pidfd != -1)
  446. close(pidfd);
  447. return(0);
  448. }