offload.scm 35 KB

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