daemon.c 15 KB

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