guix-daemon.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /* GNU Guix --- Functional package management for GNU
  2. Copyright (C) 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 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. static const struct argp_option options[] =
  74. {
  75. { "system", GUIX_OPT_SYSTEM, n_("SYSTEM"), 0,
  76. n_("assume SYSTEM as the current system type") },
  77. { "cores", 'c', n_("N"), 0,
  78. n_("use N CPU cores to build each derivation; 0 means as many as available")
  79. },
  80. { "max-jobs", 'M', n_("N"), 0,
  81. n_("allow at most N build jobs") },
  82. { "timeout", GUIX_OPT_TIMEOUT, n_("SECONDS"), 0,
  83. n_("mark builds as failed after SECONDS of activity") },
  84. { "max-silent-time", GUIX_OPT_MAX_SILENT_TIME, n_("SECONDS"), 0,
  85. n_("mark builds as failed after SECONDS of silence") },
  86. { "disable-chroot", GUIX_OPT_DISABLE_CHROOT, 0, 0,
  87. n_("disable chroot builds") },
  88. { "chroot-directory", GUIX_OPT_CHROOT_DIR, n_("DIR"), 0,
  89. n_("add DIR to the build chroot") },
  90. { "build-users-group", GUIX_OPT_BUILD_USERS_GROUP, n_("GROUP"), 0,
  91. n_("perform builds as a user of GROUP") },
  92. { "no-substitutes", GUIX_OPT_NO_SUBSTITUTES, 0, 0,
  93. n_("do not use substitutes") },
  94. { "substitute-urls", GUIX_OPT_SUBSTITUTE_URLS, n_("URLS"), 0,
  95. n_("use URLS as the default list of substitute providers") },
  96. { "no-offload", GUIX_OPT_NO_BUILD_HOOK, 0, 0,
  97. n_("do not attempt to offload builds") },
  98. { "no-build-hook", GUIX_OPT_NO_BUILD_HOOK, 0,
  99. OPTION_HIDDEN, // deprecated
  100. n_("do not attempt to offload builds") },
  101. { "cache-failures", GUIX_OPT_CACHE_FAILURES, 0, 0,
  102. n_("cache build failures") },
  103. { "rounds", GUIX_OPT_BUILD_ROUNDS, "N", 0,
  104. n_("build each derivation N times in a row") },
  105. { "lose-logs", GUIX_OPT_LOSE_LOGS, 0, 0,
  106. n_("do not keep build logs") },
  107. { "disable-log-compression", GUIX_OPT_DISABLE_LOG_COMPRESSION, 0,
  108. OPTION_HIDDEN, // deprecated
  109. n_("disable compression of the build logs") },
  110. { "log-compression", GUIX_OPT_LOG_COMPRESSION, "TYPE", 0,
  111. n_("use the specified compression type for build logs") },
  112. /* '--disable-deduplication' was known as '--disable-store-optimization'
  113. up to Guix 0.7 included, so keep the alias around. */
  114. { "disable-deduplication", GUIX_OPT_DISABLE_DEDUPLICATION, 0, 0,
  115. n_("disable automatic file \"deduplication\" in the store") },
  116. { "disable-store-optimization", GUIX_OPT_DISABLE_DEDUPLICATION, 0,
  117. OPTION_ALIAS | OPTION_HIDDEN, NULL },
  118. { "impersonate-linux-2.6", GUIX_OPT_IMPERSONATE_LINUX_26, 0,
  119. #ifdef HAVE_SYS_PERSONALITY_H
  120. 0,
  121. #else
  122. OPTION_HIDDEN,
  123. #endif
  124. n_("impersonate Linux 2.6")
  125. },
  126. { "gc-keep-outputs", GUIX_OPT_GC_KEEP_OUTPUTS,
  127. "yes/no", OPTION_ARG_OPTIONAL,
  128. n_("tell whether the GC must keep outputs of live derivations") },
  129. { "gc-keep-derivations", GUIX_OPT_GC_KEEP_DERIVATIONS,
  130. "yes/no", OPTION_ARG_OPTIONAL,
  131. n_("tell whether the GC must keep derivations corresponding \
  132. to live outputs") },
  133. { "listen", GUIX_OPT_LISTEN, n_("SOCKET"), 0,
  134. n_("listen for connections on SOCKET") },
  135. { "debug", GUIX_OPT_DEBUG, 0, 0,
  136. n_("produce debugging output") },
  137. { 0, 0, 0, 0, 0 }
  138. };
  139. /* Default port for '--listen' on TCP/IP. */
  140. #define DEFAULT_GUIX_PORT "44146"
  141. /* List of '--listen' options. */
  142. static std::list<std::string> listen_options;
  143. /* Convert ARG to a Boolean value, or throw an error if it does not denote a
  144. Boolean. */
  145. static bool
  146. string_to_bool (const char *arg, bool dflt = true)
  147. {
  148. if (arg == NULL)
  149. return dflt;
  150. else if (strcasecmp (arg, "yes") == 0)
  151. return true;
  152. else if (strcasecmp (arg, "no") == 0)
  153. return false;
  154. else
  155. throw nix::Error (format ("'%1%': invalid Boolean value") % arg);
  156. }
  157. /* Parse a single option. */
  158. static error_t
  159. parse_opt (int key, char *arg, struct argp_state *state)
  160. {
  161. switch (key)
  162. {
  163. case GUIX_OPT_DISABLE_CHROOT:
  164. settings.useChroot = false;
  165. break;
  166. case GUIX_OPT_CHROOT_DIR:
  167. {
  168. std::string chroot_dirs;
  169. chroot_dirs = settings.get ("build-extra-chroot-dirs",
  170. (std::string) "");
  171. if (chroot_dirs == "")
  172. chroot_dirs = arg;
  173. else
  174. chroot_dirs = chroot_dirs + " " + arg;
  175. settings.set("build-extra-chroot-dirs", chroot_dirs);
  176. break;
  177. }
  178. case GUIX_OPT_LOG_COMPRESSION:
  179. if (strcmp (arg, "none") == 0)
  180. settings.logCompression = COMPRESSION_NONE;
  181. else if (strcmp (arg, "gzip") == 0)
  182. settings.logCompression = COMPRESSION_GZIP;
  183. #if HAVE_BZLIB_H
  184. else if (strcmp (arg, "bzip2") == 0)
  185. settings.logCompression = COMPRESSION_BZIP2;
  186. #endif
  187. else
  188. {
  189. fprintf (stderr, _("error: %s: unknown compression type\n"), arg);
  190. exit (EXIT_FAILURE);
  191. }
  192. break;
  193. case GUIX_OPT_DISABLE_LOG_COMPRESSION:
  194. settings.logCompression = COMPRESSION_NONE;
  195. break;
  196. case GUIX_OPT_BUILD_USERS_GROUP:
  197. settings.buildUsersGroup = arg;
  198. break;
  199. case GUIX_OPT_DISABLE_DEDUPLICATION:
  200. settings.autoOptimiseStore = false;
  201. break;
  202. case GUIX_OPT_CACHE_FAILURES:
  203. settings.cacheFailure = true;
  204. break;
  205. case GUIX_OPT_BUILD_ROUNDS:
  206. {
  207. char *end;
  208. unsigned long n = strtoul (arg, &end, 10);
  209. if (end != arg + strlen (arg))
  210. {
  211. fprintf (stderr, _("error: %s: invalid number of rounds\n"), arg);
  212. exit (EXIT_FAILURE);
  213. }
  214. settings.set ("build-repeat", std::to_string (std::max (0UL, n - 1)));
  215. break;
  216. }
  217. case GUIX_OPT_IMPERSONATE_LINUX_26:
  218. settings.impersonateLinux26 = true;
  219. break;
  220. case GUIX_OPT_LOSE_LOGS:
  221. settings.keepLog = false;
  222. break;
  223. case GUIX_OPT_LISTEN:
  224. listen_options.push_back (arg);
  225. break;
  226. case GUIX_OPT_SUBSTITUTE_URLS:
  227. settings.set ("substitute-urls", arg);
  228. break;
  229. case GUIX_OPT_NO_SUBSTITUTES:
  230. settings.set ("build-use-substitutes", "false");
  231. break;
  232. case GUIX_OPT_NO_BUILD_HOOK:
  233. settings.useBuildHook = false;
  234. break;
  235. case GUIX_OPT_DEBUG:
  236. verbosity = lvlDebug;
  237. break;
  238. case GUIX_OPT_GC_KEEP_OUTPUTS:
  239. settings.gcKeepOutputs = string_to_bool (arg);
  240. break;
  241. case GUIX_OPT_GC_KEEP_DERIVATIONS:
  242. settings.gcKeepDerivations = string_to_bool (arg);
  243. break;
  244. case 'c':
  245. settings.set ("build-cores", arg);
  246. break;
  247. case 'M':
  248. settings.set ("build-max-jobs", arg);
  249. break;
  250. case GUIX_OPT_TIMEOUT:
  251. settings.set ("build-timeout", arg);
  252. break;
  253. case GUIX_OPT_MAX_SILENT_TIME:
  254. settings.set ("build-max-silent-time", arg);
  255. break;
  256. case GUIX_OPT_SYSTEM:
  257. settings.thisSystem = arg;
  258. break;
  259. default:
  260. return (error_t) ARGP_ERR_UNKNOWN;
  261. }
  262. return (error_t) 0;
  263. }
  264. /* Argument parsing. */
  265. static const struct argp argp =
  266. {
  267. options, parse_opt,
  268. NULL, doc,
  269. NULL, NULL, // children and help_filter
  270. guix_textdomain
  271. };
  272. static int
  273. open_unix_domain_socket (const char *file)
  274. {
  275. /* Create and bind to a Unix domain socket. */
  276. AutoCloseFD fdSocket = socket (PF_UNIX, SOCK_STREAM, 0);
  277. if (fdSocket == -1)
  278. throw SysError (_("cannot create Unix domain socket"));
  279. createDirs (dirOf (file));
  280. /* Urgh, sockaddr_un allows path names of only 108 characters.
  281. So chdir to the socket directory so that we can pass a
  282. relative path name. */
  283. if (chdir (dirOf (file).c_str ()) == -1)
  284. throw SysError (_("cannot change current directory"));
  285. Path fileRel = "./" + baseNameOf (file);
  286. struct sockaddr_un addr;
  287. addr.sun_family = AF_UNIX;
  288. if (fileRel.size () >= sizeof (addr.sun_path))
  289. throw Error (format (_("socket file name '%1%' is too long")) % fileRel);
  290. strcpy (addr.sun_path, fileRel.c_str ());
  291. unlink (file);
  292. /* Make sure that the socket is created with 0666 permission
  293. (everybody can connect --- provided they have access to the
  294. directory containing the socket). */
  295. mode_t oldMode = umask (0111);
  296. int res = bind (fdSocket, (struct sockaddr *) &addr, sizeof addr);
  297. umask (oldMode);
  298. if (res == -1)
  299. throw SysError (format (_("cannot bind to socket '%1%'")) % file);
  300. if (chdir ("/") == -1) /* back to the root */
  301. throw SysError (_("cannot change current directory"));
  302. if (listen (fdSocket, 5) == -1)
  303. throw SysError (format (_("cannot listen on socket '%1%'")) % file);
  304. return fdSocket.borrow ();
  305. }
  306. /* Return a listening socket for ADDRESS, which has the given LENGTH. */
  307. static int
  308. open_inet_socket (const struct sockaddr *address, socklen_t length)
  309. {
  310. AutoCloseFD fd = socket (address->sa_family, SOCK_STREAM, 0);
  311. if (fd == -1)
  312. throw SysError (_("cannot create TCP socket"));
  313. int res = bind (fd, address, length);
  314. if (res == -1)
  315. throw SysError (_("cannot bind TCP socket"));
  316. if (listen (fd, 5) == -1)
  317. throw SysError (format (_("cannot listen on TCP socket")));
  318. return fd.borrow ();
  319. }
  320. /* Return a list of file descriptors of listening sockets. */
  321. static std::vector<int>
  322. listening_sockets (const std::list<std::string> &options)
  323. {
  324. std::vector<int> result;
  325. if (options.empty ())
  326. {
  327. /* Open the default Unix-domain socket. */
  328. auto fd = open_unix_domain_socket (settings.nixDaemonSocketFile.c_str ());
  329. result.push_back (fd);
  330. return result;
  331. }
  332. /* Open the user-specified sockets. */
  333. for (const std::string& option: options)
  334. {
  335. if (option[0] == '/')
  336. {
  337. /* Assume OPTION is the file name of a Unix-domain socket. */
  338. settings.nixDaemonSocketFile = canonPath (option);
  339. int fd =
  340. open_unix_domain_socket (settings.nixDaemonSocketFile.c_str ());
  341. result.push_back (fd);
  342. }
  343. else
  344. {
  345. /* Assume OPTIONS has the form "HOST" or "HOST:PORT". */
  346. auto colon = option.find_last_of (":");
  347. auto host = colon == std::string::npos
  348. ? option : option.substr (0, colon);
  349. auto port = colon == std::string::npos
  350. ? DEFAULT_GUIX_PORT
  351. : option.substr (colon + 1, option.size () - colon - 1);
  352. struct addrinfo *res, hints;
  353. memset (&hints, '\0', sizeof hints);
  354. hints.ai_socktype = SOCK_STREAM;
  355. hints.ai_flags = AI_NUMERICSERV | AI_ADDRCONFIG;
  356. int err = getaddrinfo (host.c_str(), port.c_str (),
  357. &hints, &res);
  358. if (err != 0)
  359. throw Error(format ("failed to look up '%1%': %2%")
  360. % option % gai_strerror (err));
  361. printMsg (lvlDebug, format ("listening on '%1%', port '%2%'")
  362. % host % port);
  363. /* XXX: Pick the first result, RES. */
  364. result.push_back (open_inet_socket (res->ai_addr,
  365. res->ai_addrlen));
  366. freeaddrinfo (res);
  367. }
  368. }
  369. return result;
  370. }
  371. int
  372. main (int argc, char *argv[])
  373. {
  374. setlocale (LC_ALL, "");
  375. bindtextdomain (guix_textdomain, LOCALEDIR);
  376. textdomain (guix_textdomain);
  377. /* Initialize libgcrypt. */
  378. if (!gcry_check_version (GCRYPT_VERSION))
  379. {
  380. fprintf (stderr, _("error: libgcrypt version mismatch\n"));
  381. exit (EXIT_FAILURE);
  382. }
  383. /* Tell Libgcrypt that initialization has completed, as per the Libgcrypt
  384. 1.6.0 manual (although this does not appear to be strictly needed.) */
  385. gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
  386. /* Set the umask so that the daemon does not end up creating group-writable
  387. files, which would lead to "suspicious ownership or permission" errors.
  388. See <http://lists.gnu.org/archive/html/bug-guix/2013-07/msg00033.html>. */
  389. umask (S_IWGRP | S_IWOTH);
  390. #ifndef HAVE_CHROOT
  391. # error chroot is assumed to be available
  392. #endif
  393. /* Always use chroots by default. */
  394. settings.useChroot = true;
  395. /* Turn automatic deduplication on by default. */
  396. settings.autoOptimiseStore = true;
  397. /* Default to using as many cores as possible and one job at a time. */
  398. settings.buildCores = 0;
  399. settings.maxBuildJobs = 1;
  400. argvSaved = argv;
  401. try
  402. {
  403. settings.processEnvironment ();
  404. /* Enable substitutes by default. */
  405. settings.set ("build-use-substitutes", "true");
  406. /* Use our substitute server by default. */
  407. settings.set ("substitute-urls", GUIX_SUBSTITUTE_URLS);
  408. #ifdef HAVE_DAEMON_OFFLOAD_HOOK
  409. /* Use 'guix offload' for distributed builds by default. */
  410. settings.useBuildHook = true;
  411. #else
  412. /* We are not installing any build hook, so disable it. */
  413. settings.useBuildHook = false;
  414. #endif
  415. argp_parse (&argp, argc, argv, 0, 0, 0);
  416. auto sockets = listening_sockets (listen_options);
  417. /* Effect all the changes made via 'settings.set'. */
  418. settings.update ();
  419. printMsg(lvlDebug,
  420. format ("build log compression: %1%") % settings.logCompression);
  421. if (geteuid () == 0 && settings.buildUsersGroup.empty ())
  422. fprintf (stderr, _("warning: daemon is running as root, so \
  423. using `--build-users-group' is highly recommended\n"));
  424. if (settings.useChroot)
  425. {
  426. std::string chroot_dirs;
  427. chroot_dirs = settings.get ("build-extra-chroot-dirs",
  428. (std::string) "");
  429. printMsg (lvlDebug,
  430. format ("extra chroot directories: '%1%'") % chroot_dirs);
  431. }
  432. printMsg (lvlDebug,
  433. format ("automatic deduplication set to %1%")
  434. % settings.autoOptimiseStore);
  435. printMsg (lvlDebug,
  436. format ("listening on `%1%'") % settings.nixDaemonSocketFile);
  437. run (sockets);
  438. }
  439. catch (std::exception &e)
  440. {
  441. fprintf (stderr, _("error: %s\n"), e.what ());
  442. return EXIT_FAILURE;
  443. }
  444. return EXIT_SUCCESS; /* never reached */
  445. }