offload.scm 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2014, 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2017 Ricardo Wurmus <rekado@elephly.net>
  4. ;;; Copyright © 2020 Maxim Cournoyer <maxim.cournoyer@gmail.com>
  5. ;;;
  6. ;;; This file is part of GNU Guix.
  7. ;;;
  8. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  9. ;;; under the terms of the GNU General Public License as published by
  10. ;;; the Free Software Foundation; either version 3 of the License, or (at
  11. ;;; your option) any later version.
  12. ;;;
  13. ;;; GNU Guix is distributed in the hope that it will be useful, but
  14. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;;; GNU General Public License for more details.
  17. ;;;
  18. ;;; You should have received a copy of the GNU General Public License
  19. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  20. (define-module (guix scripts offload)
  21. #:use-module (ssh key)
  22. #:use-module (ssh auth)
  23. #:use-module (ssh session)
  24. #:use-module (ssh channel)
  25. #:use-module (ssh popen)
  26. #:use-module (ssh version)
  27. #:use-module (guix config)
  28. #:use-module (guix records)
  29. #:use-module (guix ssh)
  30. #:use-module (guix store)
  31. #:use-module (guix inferior)
  32. #:use-module (guix derivations)
  33. #:use-module ((guix serialization)
  34. #:select (nar-error? nar-error-file))
  35. #:use-module (guix nar)
  36. #:use-module ((guix utils) #:select (%current-system))
  37. #:use-module ((guix build syscalls)
  38. #:select (fcntl-flock set-thread-name))
  39. #:use-module ((guix build utils) #:select (which mkdir-p))
  40. #:use-module (guix ui)
  41. #:use-module (guix scripts)
  42. #:use-module (guix diagnostics)
  43. #:use-module (srfi srfi-1)
  44. #:use-module (srfi srfi-11)
  45. #:use-module (srfi srfi-26)
  46. #:use-module (srfi srfi-34)
  47. #:use-module (srfi srfi-35)
  48. #:use-module (ice-9 popen)
  49. #:use-module (ice-9 rdelim)
  50. #:use-module (ice-9 match)
  51. #:use-module (ice-9 regex)
  52. #:use-module (ice-9 format)
  53. #:use-module (ice-9 binary-ports)
  54. #:export (build-machine
  55. build-requirements
  56. guix-offload))
  57. ;;; Commentary:
  58. ;;;
  59. ;;; Attempt to offload builds to the machines listed in
  60. ;;; /etc/guix/machines.scm, transferring missing dependencies over SSH, and
  61. ;;; retrieving the build output(s) over SSH upon success.
  62. ;;;
  63. ;;; This command should not be used directly; instead, it is called on-demand
  64. ;;; by the daemon, unless it was started with '--no-offload' or a client
  65. ;;; inhibited build hooks.
  66. ;;;
  67. ;;; Code:
  68. (define-record-type* <build-machine>
  69. build-machine make-build-machine
  70. build-machine?
  71. (name build-machine-name) ; string
  72. (port build-machine-port ; number
  73. (default 22))
  74. (systems %build-machine-systems ; list of strings
  75. (default #f)) ; drop default after system is removed
  76. (system %build-machine-system ; deprecated
  77. (default #f))
  78. (user build-machine-user) ; string
  79. (private-key build-machine-private-key ; file name
  80. (default (user-openssh-private-key)))
  81. (host-key build-machine-host-key) ; string
  82. (compression build-machine-compression ; string
  83. (default "zlib@openssh.com,zlib"))
  84. (compression-level build-machine-compression-level ;integer
  85. (default 3))
  86. (daemon-socket build-machine-daemon-socket ; string
  87. (default "/var/guix/daemon-socket/socket"))
  88. ;; A #f value tells the offload scheduler to disregard the load of the build
  89. ;; machine when selecting the best offload machine.
  90. (overload-threshold build-machine-overload-threshold ; inexact real between
  91. (default 0.6)) ; 0.0 and 1.0 | #f
  92. (parallel-builds build-machine-parallel-builds ; number
  93. (default 1))
  94. (speed build-machine-speed ; inexact real
  95. (default 1.0))
  96. (features build-machine-features ; list of strings
  97. (default '())))
  98. ;;; Deprecated.
  99. (define (build-machine-system machine)
  100. (warning (G_ "The 'system' field is deprecated, \
  101. please use 'systems' instead.~%"))
  102. (%build-machine-system machine))
  103. ;;; TODO: Remove after the deprecated 'system' field is removed.
  104. (define (build-machine-systems machine)
  105. (or (%build-machine-systems machine)
  106. (list (build-machine-system machine))
  107. (leave (G_ "The build-machine object lacks a value for its 'systems'
  108. field."))))
  109. (define-record-type* <build-requirements>
  110. build-requirements make-build-requirements
  111. build-requirements?
  112. (system build-requirements-system) ; string
  113. (features build-requirements-features ; list of strings
  114. (default '())))
  115. (define %machine-file
  116. ;; File that lists machines available as build slaves.
  117. (string-append %config-directory "/machines.scm"))
  118. (define (user-openssh-private-key)
  119. "Return the user's default SSH private key, or #f if it could not be
  120. determined."
  121. (and=> (getenv "HOME")
  122. (cut string-append <> "/.ssh/id_rsa")))
  123. (define %user-module
  124. ;; Module in which the machine description file is loaded.
  125. (let ((module (make-fresh-user-module)))
  126. (module-use! module (resolve-interface '(guix scripts offload)))
  127. module))
  128. (define* (build-machines #:optional (file %machine-file))
  129. "Read the list of build machines from FILE and return it."
  130. (catch #t
  131. (lambda ()
  132. ;; Avoid ABI incompatibility with the <build-machine> record.
  133. ;; (set! %fresh-auto-compile #t)
  134. (save-module-excursion
  135. (lambda ()
  136. (set-current-module %user-module)
  137. (match (primitive-load file)
  138. (((? build-machine? machines) ...)
  139. machines)
  140. (_
  141. ;; Instead of crashing, assume the empty list.
  142. (warning (G_ "'~a' did not return a list of build machines; \
  143. ignoring it~%")
  144. file)
  145. '())))))
  146. (lambda args
  147. (match args
  148. (('system-error . rest)
  149. (let ((err (system-error-errno args)))
  150. ;; Silently ignore missing file since this is a common case.
  151. (if (= ENOENT err)
  152. '()
  153. (leave (G_ "failed to open machine file '~a': ~a~%")
  154. file (strerror err)))))
  155. (('syntax-error proc message properties form . rest)
  156. (let ((loc (source-properties->location properties)))
  157. (leave (G_ "~a: ~a~%")
  158. (location->string loc) message)))
  159. (x
  160. (leave (G_ "failed to load machine file '~a': ~s~%")
  161. file args))))))
  162. (define (private-key-from-file* file)
  163. "Like 'private-key-from-file', but raise an error that 'with-error-handling'
  164. can interpret meaningfully."
  165. (catch 'guile-ssh-error
  166. (lambda ()
  167. (private-key-from-file file))
  168. (lambda (key proc str . rest)
  169. (raise (formatted-message (G_ "failed to load SSH \
  170. private key from '~a': ~a")
  171. file str)))))
  172. (define* (open-ssh-session machine #:optional (max-silent-time -1))
  173. "Open an SSH session for MACHINE and return it. Throw an error on failure."
  174. (let ((private (private-key-from-file* (build-machine-private-key machine)))
  175. (public (public-key-from-file
  176. (string-append (build-machine-private-key machine)
  177. ".pub")))
  178. (session (make-session #:user (build-machine-user machine)
  179. #:host (build-machine-name machine)
  180. #:port (build-machine-port machine)
  181. #:timeout 10 ;initial timeout (seconds)
  182. ;; #:log-verbosity 'protocol
  183. #:identity (build-machine-private-key machine)
  184. ;; By default libssh reads ~/.ssh/known_hosts
  185. ;; and uses that to adjust its choice of cipher
  186. ;; suites, which changes the type of host key
  187. ;; that the server sends (RSA vs. Ed25519,
  188. ;; etc.). Opt for something reproducible and
  189. ;; stateless instead.
  190. #:knownhosts "/dev/null"
  191. ;; We need lightweight compression when
  192. ;; exchanging full archives.
  193. #:compression
  194. (build-machine-compression machine)
  195. #:compression-level
  196. (build-machine-compression-level machine))))
  197. (match (connect! session)
  198. ('ok
  199. ;; Make sure the server's key is what we expect.
  200. (authenticate-server* session (build-machine-host-key machine))
  201. (let ((auth (userauth-public-key! session private)))
  202. (unless (eq? 'success auth)
  203. (disconnect! session)
  204. (leave (G_ "SSH public key authentication failed for '~a': ~a~%")
  205. (build-machine-name machine) (get-error session))))
  206. ;; From then on use MAX-SILENT-TIME as the absolute timeout when
  207. ;; reading from or write to a channel for this session.
  208. (session-set! session 'timeout max-silent-time)
  209. session)
  210. (x
  211. ;; Connection failed or timeout expired.
  212. (leave (G_ "failed to connect to '~a': ~a~%")
  213. (build-machine-name machine) (get-error session))))))
  214. ;;;
  215. ;;; Synchronization.
  216. ;;;
  217. (define (machine-slot-file machine slot)
  218. "Return the file name of MACHINE's file for SLOT."
  219. ;; For each machine we have a bunch of files representing each build slot.
  220. ;; When choosing a build machine, we attempt to get an exclusive lock on one
  221. ;; of these; if we fail, that means all the build slots are already taken.
  222. ;; Inspired by Nix's build-remote.pl.
  223. (string-append (string-append %state-directory "/offload/"
  224. (build-machine-name machine) ":"
  225. (number->string (build-machine-port machine))
  226. "/" (number->string slot))))
  227. (define (acquire-build-slot machine)
  228. "Attempt to acquire a build slot on MACHINE. Return the port representing
  229. the slot, or #f if none is available.
  230. This mechanism allows us to set a hard limit on the number of simultaneous
  231. connections allowed to MACHINE."
  232. (mkdir-p (dirname (machine-slot-file machine 0)))
  233. ;; When several 'guix offload' processes run in parallel, there's a race
  234. ;; among them, but since they try the slots in the same order, we're fine.
  235. (any (lambda (slot)
  236. (let ((port (open-file (machine-slot-file machine slot)
  237. "w0")))
  238. (catch 'flock-error
  239. (lambda ()
  240. (fcntl-flock port 'write-lock #:wait? #f)
  241. ;; Got it!
  242. (format (current-error-port)
  243. "process ~a acquired build slot '~a'~%"
  244. (getpid) (port-filename port))
  245. port)
  246. (lambda args
  247. ;; PORT is already locked by another process.
  248. (close-port port)
  249. #f))))
  250. (iota (build-machine-parallel-builds machine))))
  251. (define (release-build-slot slot)
  252. "Release SLOT, a build slot as returned as by 'acquire-build-slot'."
  253. (close-port slot))
  254. ;;;
  255. ;;; Offloading.
  256. ;;;
  257. (define (build-log-port)
  258. "Return the default port where build logs should be sent. The default is
  259. file descriptor 4, which is open by the daemon before running the offload
  260. hook."
  261. (let ((port (fdopen 4 "w0")))
  262. ;; Make sure file descriptor 4 isn't closed when PORT is GC'd.
  263. (set-port-revealed! port 1)
  264. port))
  265. (define (node-guile-version node)
  266. (inferior-eval '(version) node))
  267. (define (node-free-disk-space node)
  268. "Return the free disk space, in bytes, in NODE's store."
  269. (inferior-eval `(begin
  270. (use-modules (guix build syscalls))
  271. (free-disk-space ,(%store-prefix)))
  272. node))
  273. (define* (transfer-and-offload drv machine
  274. #:key
  275. (inputs '())
  276. (outputs '())
  277. (max-silent-time 3600)
  278. build-timeout
  279. print-build-trace?)
  280. "Offload DRV to MACHINE. Prior to the actual offloading, transfer all of
  281. INPUTS to MACHINE; if building DRV succeeds, retrieve all of OUTPUTS from
  282. MACHINE."
  283. (define session
  284. (open-ssh-session machine max-silent-time))
  285. (define store
  286. (connect-to-remote-daemon session
  287. (build-machine-daemon-socket machine)))
  288. (set-build-options store
  289. #:print-build-trace print-build-trace?
  290. #:max-silent-time max-silent-time
  291. #:timeout build-timeout)
  292. ;; Protect DRV from garbage collection.
  293. (add-temp-root store (derivation-file-name drv))
  294. (with-store local
  295. (send-files local (cons (derivation-file-name drv) inputs) store
  296. #:log-port (current-output-port)))
  297. (format (current-error-port) "offloading '~a' to '~a'...~%"
  298. (derivation-file-name drv) (build-machine-name machine))
  299. (format (current-error-port) "@ build-remote ~a ~a~%"
  300. (derivation-file-name drv) (build-machine-name machine))
  301. (guard (c ((store-protocol-error? c)
  302. (format (current-error-port)
  303. (G_ "derivation '~a' offloaded to '~a' failed: ~a~%")
  304. (derivation-file-name drv)
  305. (build-machine-name machine)
  306. (store-protocol-error-message c))
  307. (let* ((inferior (false-if-exception (remote-inferior session)))
  308. (space (false-if-exception
  309. (node-free-disk-space inferior))))
  310. (when inferior
  311. (close-inferior inferior))
  312. ;; Use exit code 100 for a permanent build failure. The daemon
  313. ;; interprets other non-zero codes as transient build failures.
  314. (if (and space (< space (* 10 (expt 2 20))))
  315. (begin
  316. (format (current-error-port)
  317. (G_ "build failure may have been caused by lack \
  318. of free disk space on '~a'~%")
  319. (build-machine-name machine))
  320. (primitive-exit 1))
  321. (primitive-exit 100)))))
  322. (parameterize ((current-build-output-port (build-log-port)))
  323. (build-derivations store (list drv))))
  324. (retrieve-files* outputs store
  325. ;; We cannot use the 'import-paths' RPC here because we
  326. ;; already hold the locks for FILES.
  327. #:import
  328. (lambda (port)
  329. (restore-file-set port
  330. #:log-port (current-error-port)
  331. #:lock? #f)))
  332. (close-connection store)
  333. (disconnect! session)
  334. (format (current-error-port) "done with offloaded '~a'~%"
  335. (derivation-file-name drv)))
  336. ;;;
  337. ;;; Scheduling.
  338. ;;;
  339. (define (machine-matches? machine requirements)
  340. "Return #t if MACHINE matches REQUIREMENTS."
  341. (and (member (build-requirements-system requirements)
  342. (build-machine-systems machine))
  343. (lset<= string=?
  344. (build-requirements-features requirements)
  345. (build-machine-features machine))))
  346. (define %minimum-disk-space
  347. ;; Minimum disk space required on the build machine for a build to be
  348. ;; offloaded. This keeps us from offloading to machines that are bound to
  349. ;; run out of disk space.
  350. (* 100 (expt 2 20))) ;100 MiB
  351. (define (node-load node)
  352. "Return the load on NODE, a normalized value between 0.0 and 1.0. The value
  353. is derived from /proc/loadavg and normalized according to the number of
  354. logical cores available, to give a rough estimation of CPU usage. Return
  355. 1.0 (fully loaded) if NODE is misbehaving."
  356. (let ((line (inferior-eval '(begin
  357. (use-modules (ice-9 rdelim))
  358. (call-with-input-file "/proc/loadavg"
  359. read-string))
  360. node))
  361. (ncores (inferior-eval '(begin
  362. (use-modules (ice-9 threads))
  363. (current-processor-count))
  364. node)))
  365. (if (or (eof-object? line) (eof-object? ncores))
  366. 1.0 ;MACHINE does not respond, so assume it is fully loaded
  367. (match (string-tokenize line)
  368. ((one five fifteen . x)
  369. (let ((load (/ (string->number one) ncores)))
  370. (if (> load 1.0)
  371. 1.0
  372. load)))
  373. (x
  374. 1.0)))))
  375. (define (report-load machine load)
  376. (format (current-error-port)
  377. "normalized load on machine '~a' is ~,2f~%"
  378. (build-machine-name machine) load))
  379. (define (random-seed)
  380. (logxor (getpid) (car (gettimeofday))))
  381. (define shuffle
  382. (let ((state (seed->random-state (random-seed))))
  383. (lambda (lst)
  384. "Return LST shuffled (using the Fisher-Yates algorithm.)"
  385. (define vec (list->vector lst))
  386. (let loop ((result '())
  387. (i (vector-length vec)))
  388. (if (zero? i)
  389. result
  390. (let* ((j (random i state))
  391. (val (vector-ref vec j)))
  392. (vector-set! vec j (vector-ref vec (- i 1)))
  393. (loop (cons val result) (- i 1))))))))
  394. (define (choose-build-machine machines)
  395. "Return two values: the best machine among MACHINES and its build
  396. slot (which must later be released with 'release-build-slot'), or #f and #f."
  397. ;; Proceed like this:
  398. ;; 1. For all MACHINES, attempt to acquire a build slot, and filter out
  399. ;; those machines for which we failed.
  400. ;; 2. Choose the best machine among those that are left.
  401. ;; 3. Release the previously-acquired build slots of the other machines.
  402. (define machines+slots
  403. (filter-map (lambda (machine)
  404. (let ((slot (acquire-build-slot machine)))
  405. (and slot (list machine slot))))
  406. (shuffle machines)))
  407. (define (undecorate pred)
  408. (lambda (a b)
  409. (match a
  410. ((machine1 slot1)
  411. (match b
  412. ((machine2 slot2)
  413. (pred machine1 machine2)))))))
  414. (define (machine-faster? m1 m2)
  415. ;; Return #t if M1 is faster than M2.
  416. (> (build-machine-speed m1)
  417. (build-machine-speed m2)))
  418. (let loop ((machines+slots
  419. (sort machines+slots (undecorate machine-faster?))))
  420. (match machines+slots
  421. (((best slot) others ...)
  422. ;; Return the best machine unless it's already overloaded.
  423. ;; Note: We call 'node-load' only as a last resort because it is
  424. ;; too costly to call it once for every machine.
  425. (let* ((session (false-if-exception (open-ssh-session best
  426. %short-timeout)))
  427. (node (and session (remote-inferior session)))
  428. (load (and node (node-load node)))
  429. (threshold (build-machine-overload-threshold best))
  430. (space (and node (node-free-disk-space node))))
  431. (when load (report-load best load))
  432. (when node (close-inferior node))
  433. (when session (disconnect! session))
  434. (if (and node
  435. (or (not threshold) (< load threshold))
  436. (>= space %minimum-disk-space))
  437. (match others
  438. (((machines slots) ...)
  439. ;; Release slots from the uninteresting machines.
  440. (for-each release-build-slot slots)
  441. ;; The caller must keep SLOT to protect it from GC and to
  442. ;; eventually release it.
  443. (values best slot)))
  444. (begin
  445. ;; BEST is unsuitable, so try the next one.
  446. (when (and space (< space %minimum-disk-space))
  447. (format (current-error-port)
  448. "skipping machine '~a' because it is low \
  449. on disk space (~,2f MiB free)~%"
  450. (build-machine-name best)
  451. (/ space (expt 2 20) 1.)))
  452. (release-build-slot slot)
  453. (loop others)))))
  454. (()
  455. (values #f #f)))))
  456. (define (call-with-timeout timeout drv thunk)
  457. "Call THUNK and leave after TIMEOUT seconds. If TIMEOUT is #f, simply call
  458. THUNK. Use DRV as an indication of what we were building when the timeout
  459. expired."
  460. (if (number? timeout)
  461. (dynamic-wind
  462. (lambda ()
  463. (sigaction SIGALRM
  464. (lambda _
  465. ;; The exit code here will be 1, which guix-daemon will
  466. ;; interpret as a transient failure.
  467. (leave (G_ "timeout expired while offloading '~a'~%")
  468. (derivation-file-name drv))))
  469. (alarm timeout))
  470. thunk
  471. (lambda ()
  472. (alarm 0)))
  473. (thunk)))
  474. (define-syntax-rule (with-timeout timeout drv exp ...)
  475. "Evaluate EXP... and leave after TIMEOUT seconds if EXP hasn't completed.
  476. If TIMEOUT is #f, simply evaluate EXP..."
  477. (call-with-timeout timeout drv (lambda () exp ...)))
  478. (define* (process-request wants-local? system drv features
  479. #:key
  480. print-build-trace? (max-silent-time 3600)
  481. build-timeout)
  482. "Process a request to build DRV."
  483. (let* ((local? (and wants-local? (string=? system (%current-system))))
  484. (reqs (build-requirements
  485. (system system)
  486. (features features)))
  487. (candidates (filter (cut machine-matches? <> reqs)
  488. (build-machines))))
  489. (match candidates
  490. (()
  491. ;; We'll never be able to match REQS.
  492. (display "# decline\n"))
  493. ((x ...)
  494. (let-values (((machine slot)
  495. (choose-build-machine candidates)))
  496. (if machine
  497. (dynamic-wind
  498. (const #f)
  499. (lambda ()
  500. ;; Offload DRV to MACHINE.
  501. (display "# accept\n")
  502. (let ((inputs (string-tokenize (read-line)))
  503. (outputs (string-tokenize (read-line))))
  504. ;; Even if BUILD-TIMEOUT is honored by MACHINE, there can
  505. ;; be issues with the connection or deadlocks that could
  506. ;; lead the 'guix offload' process to remain stuck forever.
  507. ;; To avoid that, install a timeout here as well.
  508. (with-timeout build-timeout drv
  509. (transfer-and-offload drv machine
  510. #:inputs inputs
  511. #:outputs outputs
  512. #:max-silent-time max-silent-time
  513. #:build-timeout build-timeout
  514. #:print-build-trace?
  515. print-build-trace?))))
  516. (lambda ()
  517. (release-build-slot slot)))
  518. ;; Not now, all the machines are busy.
  519. (display "# postpone\n")))))))
  520. ;;;
  521. ;;; Installation tests.
  522. ;;;
  523. (define %short-timeout
  524. ;; Timeout in seconds used on SSH connections where reads and writes
  525. ;; shouldn't take long.
  526. 15)
  527. (define (assert-node-repl node name)
  528. "Bail out if NODE is not running Guile."
  529. (match (node-guile-version node)
  530. (#f
  531. (report-guile-error name))
  532. ((? string? version)
  533. (info (G_ "'~a' is running GNU Guile ~a~%")
  534. name (node-guile-version node)))))
  535. (define (assert-node-has-guix node name)
  536. "Bail out if NODE if #f or if we fail to use the (guix) module, or if its
  537. daemon is not running."
  538. (unless (inferior? node)
  539. (leave (G_ "failed to run 'guix repl' on '~a'~%") name))
  540. (match (inferior-eval '(begin
  541. (use-modules (guix))
  542. (and add-text-to-store 'alright))
  543. node)
  544. ('alright #t)
  545. (_ (report-module-error name)))
  546. (match (inferior-eval '(begin
  547. (use-modules (guix))
  548. (with-store store
  549. (add-text-to-store store "test"
  550. "Hello, build machine!")))
  551. node)
  552. ((? string? str)
  553. (info (G_ "Guix is usable on '~a' (test returned ~s)~%")
  554. name str))
  555. (x
  556. (leave (G_ "failed to talk to guix-daemon on '~a' (test returned ~s)~%")
  557. name x))))
  558. (define %random-state
  559. (delay
  560. (seed->random-state (logxor (getpid) (car (gettimeofday))))))
  561. (define* (nonce #:optional (name (gethostname)))
  562. (string-append name "-"
  563. (number->string (random 1000000 (force %random-state)))))
  564. (define (assert-node-can-import session node name daemon-socket)
  565. "Bail out if NODE refuses to import our archives."
  566. (with-store store
  567. (let* ((item (add-text-to-store store "export-test" (nonce)))
  568. (remote (connect-to-remote-daemon session daemon-socket)))
  569. (with-store local
  570. (send-files local (list item) remote))
  571. (if (valid-path? remote item)
  572. (info (G_ "'~a' successfully imported '~a'~%")
  573. name item)
  574. (leave (G_ "'~a' was not properly imported on '~a'~%")
  575. item name)))))
  576. (define (assert-node-can-export session node name daemon-socket)
  577. "Bail out if we cannot import signed archives from NODE."
  578. (let* ((remote (connect-to-remote-daemon session daemon-socket))
  579. (item (add-text-to-store remote "import-test" (nonce name))))
  580. (with-store store
  581. (if (and (retrieve-files store (list item) remote)
  582. (valid-path? store item))
  583. (info (G_ "successfully imported '~a' from '~a'~%")
  584. item name)
  585. (leave (G_ "failed to import '~a' from '~a'~%")
  586. item name)))))
  587. (define (check-machine-availability machine-file pred)
  588. "Check that each machine matching PRED in MACHINE-FILE is usable as a build
  589. machine."
  590. (define (build-machine=? m1 m2)
  591. (and (string=? (build-machine-name m1) (build-machine-name m2))
  592. (= (build-machine-port m1) (build-machine-port m2))))
  593. ;; A given build machine may appear several times (e.g., once for
  594. ;; "x86_64-linux" and a second time for "i686-linux"); test them only once.
  595. (let ((machines (filter pred
  596. (delete-duplicates (build-machines machine-file)
  597. build-machine=?))))
  598. (info (G_ "testing ~a build machines defined in '~a'...~%")
  599. (length machines) machine-file)
  600. (let* ((names (map build-machine-name machines))
  601. (sockets (map build-machine-daemon-socket machines))
  602. (sessions (map (cut open-ssh-session <> %short-timeout) machines))
  603. (nodes (map remote-inferior sessions)))
  604. (for-each assert-node-has-guix nodes names)
  605. (for-each assert-node-repl nodes names)
  606. (for-each assert-node-can-import sessions nodes names sockets)
  607. (for-each assert-node-can-export sessions nodes names sockets)
  608. (for-each close-inferior nodes)
  609. (for-each disconnect! sessions))))
  610. (define (check-machine-status machine-file pred)
  611. "Print the load of each machine matching PRED in MACHINE-FILE."
  612. (define (build-machine=? m1 m2)
  613. (and (string=? (build-machine-name m1) (build-machine-name m2))
  614. (= (build-machine-port m1) (build-machine-port m2))))
  615. ;; A given build machine may appear several times (e.g., once for
  616. ;; "x86_64-linux" and a second time for "i686-linux"); test them only once.
  617. (let ((machines (filter pred
  618. (delete-duplicates (build-machines machine-file)
  619. build-machine=?))))
  620. (info (G_ "getting status of ~a build machines defined in '~a'...~%")
  621. (length machines) machine-file)
  622. (for-each (lambda (machine)
  623. (define session
  624. (open-ssh-session machine %short-timeout))
  625. (match (remote-inferior session)
  626. (#f
  627. (warning (G_ "failed to run 'guix repl' on machine '~a'~%")
  628. (build-machine-name machine)))
  629. ((? inferior? inferior)
  630. (let ((now (car (gettimeofday))))
  631. (match (inferior-eval '(list (uname)
  632. (car (gettimeofday)))
  633. inferior)
  634. ((uts time)
  635. (when (< time now)
  636. ;; Build machine clocks must not be behind as this
  637. ;; could cause timestamp issues.
  638. (warning (G_ "machine '~a' is ~a seconds behind~%")
  639. (build-machine-name machine)
  640. (- now time)))
  641. (let ((load (node-load inferior))
  642. (free (node-free-disk-space inferior)))
  643. (close-inferior inferior)
  644. (format #t "~a~% kernel: ~a ~a~% architecture: ~a~%\
  645. host name: ~a~% normalized load: ~,2f~% free disk space: ~,2f MiB~%\
  646. time difference: ~a s~%"
  647. (build-machine-name machine)
  648. (utsname:sysname uts) (utsname:release uts)
  649. (utsname:machine uts)
  650. (utsname:nodename uts)
  651. load
  652. (/ free (expt 2 20) 1.)
  653. (- time now))))))))
  654. (disconnect! session))
  655. machines)))
  656. ;;;
  657. ;;; Entry point.
  658. ;;;
  659. (define-command (guix-offload . args)
  660. (category plumbing)
  661. (synopsis "set up and operate build offloading")
  662. (define request-line-rx
  663. ;; The request format. See 'tryBuildHook' method in build.cc.
  664. (make-regexp "([01]) ([a-z0-9_-]+) (/[[:graph:]]+.drv) ([[:graph:]]*)"))
  665. (define not-coma
  666. (char-set-complement (char-set #\,)))
  667. ;; Make sure $HOME really corresponds to the current user. This is
  668. ;; necessary since lsh uses that to determine the location of the yarrow
  669. ;; seed file, and fails if it's owned by someone else.
  670. (and=> (passwd:dir (getpw (getuid)))
  671. (cut setenv "HOME" <>))
  672. ;; We rely on protocol-level compression from libssh to optimize large data
  673. ;; transfers. Warn if it's missing.
  674. (unless (zlib-support?)
  675. (warning (G_ "Guile-SSH lacks zlib support"))
  676. (warning (G_ "data transfers will *not* be compressed!")))
  677. (match args
  678. ((system max-silent-time print-build-trace? build-timeout)
  679. (let ((max-silent-time (string->number max-silent-time))
  680. (build-timeout (string->number build-timeout))
  681. (print-build-trace? (string=? print-build-trace? "1")))
  682. (set-thread-name "guix offload")
  683. (parameterize ((%current-system system))
  684. (let loop ((line (read-line)))
  685. (unless (eof-object? line)
  686. (cond ((regexp-exec request-line-rx line)
  687. =>
  688. (lambda (match)
  689. (with-error-handling
  690. (process-request (equal? (match:substring match 1) "1")
  691. (match:substring match 2) ; system
  692. (read-derivation-from-file
  693. (match:substring match 3))
  694. (string-tokenize
  695. (match:substring match 4) not-coma)
  696. #:print-build-trace? print-build-trace?
  697. #:max-silent-time max-silent-time
  698. #:build-timeout build-timeout))))
  699. (else
  700. (leave (G_ "invalid request line: ~s~%") line)))
  701. (loop (read-line)))))))
  702. (("test" rest ...)
  703. (with-error-handling
  704. (let-values (((file pred)
  705. (match rest
  706. ((file regexp)
  707. (values file
  708. (compose (cut string-match regexp <>)
  709. build-machine-name)))
  710. ((file) (values file (const #t)))
  711. (() (values %machine-file (const #t)))
  712. (x (leave (G_ "wrong number of arguments~%"))))))
  713. (check-machine-availability (or file %machine-file) pred))))
  714. (("status" rest ...)
  715. (with-error-handling
  716. (let-values (((file pred)
  717. (match rest
  718. ((file regexp)
  719. (values file
  720. (compose (cut string-match regexp <>)
  721. build-machine-name)))
  722. ((file) (values file (const #t)))
  723. (() (values %machine-file (const #t)))
  724. (x (leave (G_ "wrong number of arguments~%"))))))
  725. (check-machine-status (or file %machine-file) pred))))
  726. (("--version")
  727. (show-version-and-exit "guix offload"))
  728. (("--help")
  729. (format #t (G_ "Usage: guix offload SYSTEM MAX-SILENT-TIME \
  730. PRINT-BUILD-TRACE? BUILD-TIMEOUT
  731. Process build offload requests written on the standard input, possibly
  732. offloading builds to the machines listed in '~a'.~%")
  733. %machine-file)
  734. (display (G_ "
  735. This tool is meant to be used internally by 'guix-daemon'.\n"))
  736. (show-bug-report-information))
  737. (x
  738. (leave (G_ "invalid arguments: ~{~s ~}~%") x))))
  739. ;;; Local Variables:
  740. ;;; eval: (put 'with-error-to-port 'scheme-indent-function 1)
  741. ;;; eval: (put 'with-timeout 'scheme-indent-function 2)
  742. ;;; End:
  743. ;;; offload.scm ends here