daemon.c 17 KB

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