guix-daemon.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. /* GNU Guix --- Functional package management for GNU
  2. Copyright (C) 2012-2019, 2021-2022 Ludovic Courtès <ludo@gnu.org>
  3. Copyright (C) 2006, 2010, 2012, 2014 Eelco Dolstra <e.dolstra@tudelft.nl>
  4. This file is part of GNU Guix.
  5. GNU Guix is free software; you can redistribute it and/or modify it
  6. under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 3 of the License, or (at
  8. your option) any later version.
  9. GNU Guix is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Guix. If not, see <http://www.gnu.org/licenses/>. */
  15. #include <config.h>
  16. #include <types.hh>
  17. #include "shared.hh"
  18. #include <globals.hh>
  19. #include <util.hh>
  20. #include <gcrypt.h>
  21. #include <stdlib.h>
  22. #include <argp.h>
  23. #include <unistd.h>
  24. #include <sys/types.h>
  25. #include <sys/stat.h>
  26. #include <sys/socket.h>
  27. #include <sys/un.h>
  28. #include <netdb.h>
  29. #include <strings.h>
  30. #include <exception>
  31. #include <iostream>
  32. #include <libintl.h>
  33. #include <locale.h>
  34. /* Variables used by `nix-daemon.cc'. */
  35. volatile ::sig_atomic_t blockInt;
  36. char **argvSaved;
  37. using namespace nix;
  38. /* Entry point in `nix-daemon.cc'. */
  39. extern void run (const std::vector<int> &);
  40. /* Command-line options. */
  41. #define n_(str) str
  42. #define _(str) gettext (str)
  43. static const char guix_textdomain[] = "guix";
  44. const char *argp_program_version =
  45. "guix-daemon (" PACKAGE_NAME ") " PACKAGE_VERSION;
  46. const char *argp_program_bug_address = PACKAGE_BUGREPORT;
  47. static char doc[] =
  48. n_("guix-daemon -- perform derivation builds and store accesses")
  49. "\v\n"
  50. n_("This program is a daemon meant to run in the background. It serves \
  51. requests sent over a Unix-domain socket. It accesses the store, and \
  52. builds derivations on behalf of its clients.");
  53. #define GUIX_OPT_SYSTEM 1
  54. #define GUIX_OPT_DISABLE_CHROOT 2
  55. #define GUIX_OPT_BUILD_USERS_GROUP 3
  56. #define GUIX_OPT_CACHE_FAILURES 4
  57. #define GUIX_OPT_LOSE_LOGS 5
  58. #define GUIX_OPT_DISABLE_LOG_COMPRESSION 6
  59. #define GUIX_OPT_DISABLE_DEDUPLICATION 7
  60. #define GUIX_OPT_IMPERSONATE_LINUX_26 8
  61. #define GUIX_OPT_DEBUG 9
  62. #define GUIX_OPT_CHROOT_DIR 10
  63. #define GUIX_OPT_LISTEN 11
  64. #define GUIX_OPT_NO_SUBSTITUTES 12
  65. #define GUIX_OPT_SUBSTITUTE_URLS 13
  66. #define GUIX_OPT_NO_BUILD_HOOK 14
  67. #define GUIX_OPT_GC_KEEP_OUTPUTS 15
  68. #define GUIX_OPT_GC_KEEP_DERIVATIONS 16
  69. #define GUIX_OPT_BUILD_ROUNDS 17
  70. #define GUIX_OPT_TIMEOUT 18
  71. #define GUIX_OPT_MAX_SILENT_TIME 19
  72. #define GUIX_OPT_LOG_COMPRESSION 20
  73. #define GUIX_OPT_DISCOVER 21
  74. static const struct argp_option options[] =
  75. {
  76. { "system", GUIX_OPT_SYSTEM, n_("SYSTEM"), 0,
  77. n_("assume SYSTEM as the current system type") },
  78. { "cores", 'c', n_("N"), 0,
  79. n_("use N CPU cores to build each derivation; 0 means as many as available")
  80. },
  81. { "max-jobs", 'M', n_("N"), 0,
  82. n_("allow at most N build jobs") },
  83. { "timeout", GUIX_OPT_TIMEOUT, n_("SECONDS"), 0,
  84. n_("mark builds as failed after SECONDS of activity") },
  85. { "max-silent-time", GUIX_OPT_MAX_SILENT_TIME, n_("SECONDS"), 0,
  86. n_("mark builds as failed after SECONDS of silence") },
  87. { "disable-chroot", GUIX_OPT_DISABLE_CHROOT, 0, 0,
  88. n_("disable chroot builds") },
  89. { "chroot-directory", GUIX_OPT_CHROOT_DIR, n_("DIR"), 0,
  90. n_("add DIR to the build chroot") },
  91. { "build-users-group", GUIX_OPT_BUILD_USERS_GROUP, n_("GROUP"), 0,
  92. n_("perform builds as a user of GROUP") },
  93. { "no-substitutes", GUIX_OPT_NO_SUBSTITUTES, 0, 0,
  94. n_("do not use substitutes") },
  95. { "substitute-urls", GUIX_OPT_SUBSTITUTE_URLS, n_("URLS"), 0,
  96. n_("use URLS as the default list of substitute providers") },
  97. { "no-offload", GUIX_OPT_NO_BUILD_HOOK, 0, 0,
  98. n_("do not attempt to offload builds") },
  99. { "no-build-hook", GUIX_OPT_NO_BUILD_HOOK, 0,
  100. OPTION_HIDDEN, // deprecated
  101. n_("do not attempt to offload builds") },
  102. { "cache-failures", GUIX_OPT_CACHE_FAILURES, 0, 0,
  103. n_("cache build failures") },
  104. { "rounds", GUIX_OPT_BUILD_ROUNDS, "N", 0,
  105. n_("build each derivation N times in a row") },
  106. { "lose-logs", GUIX_OPT_LOSE_LOGS, 0, 0,
  107. n_("do not keep build logs") },
  108. { "disable-log-compression", GUIX_OPT_DISABLE_LOG_COMPRESSION, 0,
  109. OPTION_HIDDEN, // deprecated
  110. n_("disable compression of the build logs") },
  111. { "log-compression", GUIX_OPT_LOG_COMPRESSION, "TYPE", 0,
  112. n_("use the specified compression type for build logs") },
  113. { "discover", GUIX_OPT_DISCOVER, "yes/no", OPTION_ARG_OPTIONAL,
  114. n_("use substitute servers discovered on the local network") },
  115. /* '--disable-deduplication' was known as '--disable-store-optimization'
  116. up to Guix 0.7 included, so keep the alias around. */
  117. { "disable-deduplication", GUIX_OPT_DISABLE_DEDUPLICATION, 0, 0,
  118. n_("disable automatic file \"deduplication\" in the store") },
  119. { "disable-store-optimization", GUIX_OPT_DISABLE_DEDUPLICATION, 0,
  120. OPTION_ALIAS | OPTION_HIDDEN, NULL },
  121. { "impersonate-linux-2.6", GUIX_OPT_IMPERSONATE_LINUX_26, 0,
  122. #ifdef HAVE_SYS_PERSONALITY_H
  123. 0,
  124. #else
  125. OPTION_HIDDEN,
  126. #endif
  127. n_("impersonate Linux 2.6")
  128. },
  129. { "gc-keep-outputs", GUIX_OPT_GC_KEEP_OUTPUTS,
  130. "yes/no", OPTION_ARG_OPTIONAL,
  131. n_("tell whether the GC must keep outputs of live derivations") },
  132. { "gc-keep-derivations", GUIX_OPT_GC_KEEP_DERIVATIONS,
  133. "yes/no", OPTION_ARG_OPTIONAL,
  134. n_("tell whether the GC must keep derivations corresponding \
  135. to live outputs") },
  136. { "listen", GUIX_OPT_LISTEN, n_("SOCKET"), 0,
  137. n_("listen for connections on SOCKET") },
  138. { "debug", GUIX_OPT_DEBUG, 0, 0,
  139. n_("produce debugging output") },
  140. { 0, 0, 0, 0, 0 }
  141. };
  142. /* Default port for '--listen' on TCP/IP. */
  143. #define DEFAULT_GUIX_PORT "44146"
  144. /* List of '--listen' options. */
  145. static std::list<std::string> listen_options;
  146. static bool useDiscover = false;
  147. /* Convert ARG to a Boolean value, or throw an error if it does not denote a
  148. Boolean. */
  149. static bool
  150. string_to_bool (const char *arg, bool dflt = true)
  151. {
  152. if (arg == NULL)
  153. return dflt;
  154. else if (strcasecmp (arg, "yes") == 0)
  155. return true;
  156. else if (strcasecmp (arg, "no") == 0)
  157. return false;
  158. else
  159. throw nix::Error (format ("'%1%': invalid Boolean value") % arg);
  160. }
  161. /* Parse a single option. */
  162. static error_t
  163. parse_opt (int key, char *arg, struct argp_state *state)
  164. {
  165. switch (key)
  166. {
  167. case GUIX_OPT_DISABLE_CHROOT:
  168. settings.useChroot = false;
  169. break;
  170. case GUIX_OPT_CHROOT_DIR:
  171. {
  172. std::string chroot_dirs;
  173. chroot_dirs = settings.get ("build-extra-chroot-dirs",
  174. (std::string) "");
  175. if (chroot_dirs == "")
  176. chroot_dirs = arg;
  177. else
  178. chroot_dirs = chroot_dirs + " " + arg;
  179. settings.set("build-extra-chroot-dirs", chroot_dirs);
  180. break;
  181. }
  182. case GUIX_OPT_LOG_COMPRESSION:
  183. if (strcmp (arg, "none") == 0)
  184. settings.logCompression = COMPRESSION_NONE;
  185. else if (strcmp (arg, "gzip") == 0)
  186. settings.logCompression = COMPRESSION_GZIP;
  187. #if HAVE_BZLIB_H
  188. else if (strcmp (arg, "bzip2") == 0)
  189. settings.logCompression = COMPRESSION_BZIP2;
  190. #endif
  191. else
  192. {
  193. fprintf (stderr, _("error: %s: unknown compression type\n"), arg);
  194. exit (EXIT_FAILURE);
  195. }
  196. break;
  197. case GUIX_OPT_DISABLE_LOG_COMPRESSION:
  198. settings.logCompression = COMPRESSION_NONE;
  199. break;
  200. case GUIX_OPT_BUILD_USERS_GROUP:
  201. settings.buildUsersGroup = arg;
  202. break;
  203. case GUIX_OPT_DISABLE_DEDUPLICATION:
  204. settings.autoOptimiseStore = false;
  205. break;
  206. case GUIX_OPT_CACHE_FAILURES:
  207. settings.cacheFailure = true;
  208. break;
  209. case GUIX_OPT_BUILD_ROUNDS:
  210. {
  211. char *end;
  212. unsigned long n = strtoul (arg, &end, 10);
  213. if (end != arg + strlen (arg))
  214. {
  215. fprintf (stderr, _("error: %s: invalid number of rounds\n"), arg);
  216. exit (EXIT_FAILURE);
  217. }
  218. settings.set ("build-repeat", std::to_string (std::max (0UL, n - 1)));
  219. break;
  220. }
  221. case GUIX_OPT_IMPERSONATE_LINUX_26:
  222. settings.impersonateLinux26 = true;
  223. break;
  224. case GUIX_OPT_LOSE_LOGS:
  225. settings.keepLog = false;
  226. break;
  227. case GUIX_OPT_LISTEN:
  228. listen_options.push_back (arg);
  229. break;
  230. case GUIX_OPT_SUBSTITUTE_URLS:
  231. settings.set ("substitute-urls", arg);
  232. break;
  233. case GUIX_OPT_NO_SUBSTITUTES:
  234. settings.set ("build-use-substitutes", "false");
  235. break;
  236. case GUIX_OPT_NO_BUILD_HOOK:
  237. settings.useBuildHook = false;
  238. break;
  239. case GUIX_OPT_DISCOVER:
  240. useDiscover = string_to_bool (arg);
  241. settings.set ("discover", useDiscover ? "true" : "false");
  242. break;
  243. case GUIX_OPT_DEBUG:
  244. verbosity = lvlDebug;
  245. break;
  246. case GUIX_OPT_GC_KEEP_OUTPUTS:
  247. settings.gcKeepOutputs = string_to_bool (arg);
  248. break;
  249. case GUIX_OPT_GC_KEEP_DERIVATIONS:
  250. settings.gcKeepDerivations = string_to_bool (arg);
  251. break;
  252. case 'c':
  253. settings.set ("build-cores", arg);
  254. break;
  255. case 'M':
  256. settings.set ("build-max-jobs", arg);
  257. break;
  258. case GUIX_OPT_TIMEOUT:
  259. settings.set ("build-timeout", arg);
  260. break;
  261. case GUIX_OPT_MAX_SILENT_TIME:
  262. settings.set ("build-max-silent-time", arg);
  263. break;
  264. case GUIX_OPT_SYSTEM:
  265. settings.thisSystem = arg;
  266. break;
  267. default:
  268. return (error_t) ARGP_ERR_UNKNOWN;
  269. }
  270. return (error_t) 0;
  271. }
  272. /* Argument parsing. */
  273. static const struct argp argp =
  274. {
  275. options, parse_opt,
  276. NULL, doc,
  277. NULL, NULL, // children and help_filter
  278. guix_textdomain
  279. };
  280. static int
  281. open_unix_domain_socket (const char *file)
  282. {
  283. /* Create and bind to a Unix domain socket. */
  284. AutoCloseFD fdSocket = socket (PF_UNIX, SOCK_STREAM, 0);
  285. if (fdSocket == -1)
  286. throw SysError (_("cannot create Unix domain socket"));
  287. createDirs (dirOf (file));
  288. /* Urgh, sockaddr_un allows path names of only 108 characters.
  289. So chdir to the socket directory so that we can pass a
  290. relative path name. */
  291. if (chdir (dirOf (file).c_str ()) == -1)
  292. throw SysError (_("cannot change current directory"));
  293. Path fileRel = "./" + baseNameOf (file);
  294. struct sockaddr_un addr;
  295. addr.sun_family = AF_UNIX;
  296. if (fileRel.size () >= sizeof (addr.sun_path))
  297. throw Error (format (_("socket file name '%1%' is too long")) % fileRel);
  298. strcpy (addr.sun_path, fileRel.c_str ());
  299. unlink (file);
  300. /* Make sure that the socket is created with 0666 permission
  301. (everybody can connect --- provided they have access to the
  302. directory containing the socket). */
  303. mode_t oldMode = umask (0111);
  304. int res = bind (fdSocket, (struct sockaddr *) &addr, sizeof addr);
  305. umask (oldMode);
  306. if (res == -1)
  307. throw SysError (format (_("cannot bind to socket '%1%'")) % file);
  308. if (chdir ("/") == -1) /* back to the root */
  309. throw SysError (_("cannot change current directory"));
  310. if (listen (fdSocket, 5) == -1)
  311. throw SysError (format (_("cannot listen on socket '%1%'")) % file);
  312. return fdSocket.borrow ();
  313. }
  314. /* Return a listening socket for ADDRESS, which has the given LENGTH. */
  315. static int
  316. open_inet_socket (const struct sockaddr *address, socklen_t length)
  317. {
  318. AutoCloseFD fd = socket (address->sa_family, SOCK_STREAM, 0);
  319. if (fd == -1)
  320. throw SysError (_("cannot create TCP socket"));
  321. int res = bind (fd, address, length);
  322. if (res == -1)
  323. throw SysError (_("cannot bind TCP socket"));
  324. if (listen (fd, 5) == -1)
  325. throw SysError (format (_("cannot listen on TCP socket")));
  326. return fd.borrow ();
  327. }
  328. /* Return a list of file descriptors of listening sockets. */
  329. static std::vector<int>
  330. listening_sockets (const std::list<std::string> &options)
  331. {
  332. std::vector<int> result;
  333. if (options.empty ())
  334. {
  335. /* Open the default Unix-domain socket. */
  336. auto fd = open_unix_domain_socket (settings.nixDaemonSocketFile.c_str ());
  337. result.push_back (fd);
  338. return result;
  339. }
  340. /* Open the user-specified sockets. */
  341. for (const std::string& option: options)
  342. {
  343. if (option[0] == '/')
  344. {
  345. /* Assume OPTION is the file name of a Unix-domain socket. */
  346. settings.nixDaemonSocketFile = canonPath (option);
  347. int fd =
  348. open_unix_domain_socket (settings.nixDaemonSocketFile.c_str ());
  349. result.push_back (fd);
  350. }
  351. else
  352. {
  353. /* Assume OPTIONS has the form "HOST" or "HOST:PORT". */
  354. auto colon = option.find_last_of (":");
  355. auto host = colon == std::string::npos
  356. ? option : option.substr (0, colon);
  357. auto port = colon == std::string::npos
  358. ? DEFAULT_GUIX_PORT
  359. : option.substr (colon + 1, option.size () - colon - 1);
  360. struct addrinfo *res, hints;
  361. memset (&hints, '\0', sizeof hints);
  362. hints.ai_socktype = SOCK_STREAM;
  363. hints.ai_flags = AI_NUMERICSERV | AI_ADDRCONFIG;
  364. int err = getaddrinfo (host.c_str(), port.c_str (),
  365. &hints, &res);
  366. if (err != 0)
  367. throw Error(format ("failed to look up '%1%': %2%")
  368. % option % gai_strerror (err));
  369. printMsg (lvlDebug, format ("listening on '%1%', port '%2%'")
  370. % host % port);
  371. /* XXX: Pick the first result, RES. */
  372. result.push_back (open_inet_socket (res->ai_addr,
  373. res->ai_addrlen));
  374. freeaddrinfo (res);
  375. }
  376. }
  377. return result;
  378. }
  379. /* First file descriptor provided at startup using systemd-style socket
  380. activation. */
  381. #define SD_LISTEN_FDS_START 3
  382. /* Return a list of file descriptors of listening sockets provided following
  383. the systemd "socket activation" protocol. Return the empty list if we are
  384. not being socket-activated. */
  385. static std::vector<int>
  386. systemd_activation_sockets ()
  387. {
  388. std::vector<int> result;
  389. if (getEnv ("LISTEN_PID") == std::to_string (getpid ()))
  390. {
  391. unsigned int fdCount;
  392. if (string2Int (getEnv ("LISTEN_FDS"), fdCount))
  393. {
  394. for (unsigned int i = 0; i < fdCount; i++)
  395. result.push_back (SD_LISTEN_FDS_START + i);
  396. }
  397. }
  398. return result;
  399. }
  400. int
  401. main (int argc, char *argv[])
  402. {
  403. setlocale (LC_ALL, "");
  404. bindtextdomain (guix_textdomain, LOCALEDIR);
  405. textdomain (guix_textdomain);
  406. /* Initialize libgcrypt. */
  407. if (!gcry_check_version (GCRYPT_VERSION))
  408. {
  409. fprintf (stderr, _("error: libgcrypt version mismatch\n"));
  410. exit (EXIT_FAILURE);
  411. }
  412. /* Tell Libgcrypt that initialization has completed, as per the Libgcrypt
  413. 1.6.0 manual (although this does not appear to be strictly needed.) */
  414. gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
  415. /* Set the umask so that the daemon does not end up creating group-writable
  416. files, which would lead to "suspicious ownership or permission" errors.
  417. See <http://lists.gnu.org/archive/html/bug-guix/2013-07/msg00033.html>. */
  418. umask (S_IWGRP | S_IWOTH);
  419. #ifndef HAVE_CHROOT
  420. # error chroot is assumed to be available
  421. #endif
  422. /* Always use chroots by default. */
  423. settings.useChroot = true;
  424. /* Turn automatic deduplication on by default. */
  425. settings.autoOptimiseStore = true;
  426. /* Default to using as many cores as possible and one job at a time. */
  427. settings.buildCores = 0;
  428. settings.maxBuildJobs = 1;
  429. argvSaved = argv;
  430. try
  431. {
  432. settings.processEnvironment ();
  433. /* Enable substitutes by default. */
  434. settings.set ("build-use-substitutes", "true");
  435. /* Use our substitute server by default. */
  436. settings.set ("substitute-urls", GUIX_SUBSTITUTE_URLS);
  437. #ifdef HAVE_DAEMON_OFFLOAD_HOOK
  438. /* Use 'guix offload' for distributed builds by default. */
  439. settings.useBuildHook = true;
  440. #else
  441. /* We are not installing any build hook, so disable it. */
  442. settings.useBuildHook = false;
  443. #endif
  444. argp_parse (&argp, argc, argv, 0, 0, 0);
  445. auto sockets = systemd_activation_sockets ();
  446. if (sockets.empty ())
  447. /* We were not "socket-activated" so open the sockets specified by
  448. LISTEN_OPTIONS. */
  449. sockets = listening_sockets (listen_options);
  450. else
  451. printMsg (lvlInfo,
  452. format (ngettext ("socket-activated with %1% socket",
  453. "socket-activated with %1% sockets",
  454. sockets.size ()))
  455. % sockets.size ());
  456. /* Effect all the changes made via 'settings.set'. */
  457. settings.update ();
  458. printMsg(lvlDebug,
  459. format ("build log compression: %1%") % settings.logCompression);
  460. if (geteuid () == 0 && settings.buildUsersGroup.empty ())
  461. fprintf (stderr, _("warning: daemon is running as root, so \
  462. using `--build-users-group' is highly recommended\n"));
  463. if (settings.useChroot)
  464. {
  465. std::string chroot_dirs;
  466. chroot_dirs = settings.get ("build-extra-chroot-dirs",
  467. (std::string) "");
  468. printMsg (lvlDebug,
  469. format ("extra chroot directories: '%1%'") % chroot_dirs);
  470. }
  471. if (useDiscover)
  472. {
  473. Strings args;
  474. args.push_back("guix");
  475. args.push_back("discover");
  476. startProcess([&]() {
  477. execv(settings.guixProgram.c_str(), stringsToCharPtrs(args).data());
  478. });
  479. }
  480. printMsg (lvlDebug,
  481. format ("automatic deduplication set to %1%")
  482. % settings.autoOptimiseStore);
  483. run (sockets);
  484. }
  485. catch (std::exception &e)
  486. {
  487. fprintf (stderr, _("error: %s\n"), e.what ());
  488. return EXIT_FAILURE;
  489. }
  490. return EXIT_SUCCESS; /* never reached */
  491. }