offload.scm 35 KB

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