Merge branch 'master' into core-updates
[jackhill/guix/guix.git] / guix / ssh.scm
1 ;;; GNU Guix --- Functional package management for GNU
2 ;;; Copyright © 2016, 2017, 2018 Ludovic Courtès <ludo@gnu.org>
3 ;;;
4 ;;; This file is part of GNU Guix.
5 ;;;
6 ;;; GNU Guix is free software; you can redistribute it and/or modify it
7 ;;; under the terms of the GNU General Public License as published by
8 ;;; the Free Software Foundation; either version 3 of the License, or (at
9 ;;; your option) any later version.
10 ;;;
11 ;;; GNU Guix is distributed in the hope that it will be useful, but
12 ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ;;; GNU General Public License for more details.
15 ;;;
16 ;;; You should have received a copy of the GNU General Public License
17 ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
18
19 (define-module (guix ssh)
20 #:use-module (guix store)
21 #:use-module (guix i18n)
22 #:use-module ((guix utils) #:select (&fix-hint))
23 #:use-module (ssh session)
24 #:use-module (ssh auth)
25 #:use-module (ssh key)
26 #:use-module (ssh channel)
27 #:use-module (ssh popen)
28 #:use-module (ssh session)
29 #:use-module (ssh dist)
30 #:use-module (ssh dist node)
31 #:use-module (srfi srfi-1)
32 #:use-module (srfi srfi-11)
33 #:use-module (srfi srfi-26)
34 #:use-module (srfi srfi-34)
35 #:use-module (srfi srfi-35)
36 #:use-module (ice-9 match)
37 #:use-module (ice-9 binary-ports)
38 #:export (open-ssh-session
39 remote-daemon-channel
40 connect-to-remote-daemon
41 send-files
42 retrieve-files
43 retrieve-files*
44 remote-store-host
45
46 report-guile-error
47 report-module-error))
48
49 ;;; Commentary:
50 ;;;
51 ;;; This module provides tools to support communication with remote stores
52 ;;; over SSH, using Guile-SSH.
53 ;;;
54 ;;; Code:
55
56 (define %compression
57 "zlib@openssh.com,zlib")
58
59 (define* (open-ssh-session host #:key user port
60 (compression %compression))
61 "Open an SSH session for HOST and return it. When USER and PORT are #f, use
62 default values or whatever '~/.ssh/config' specifies; otherwise use them.
63 Throw an error on failure."
64 (let ((session (make-session #:user user
65 #:host host
66 #:port port
67 #:timeout 10 ;seconds
68 ;; #:log-verbosity 'protocol
69
70 ;; We need lightweight compression when
71 ;; exchanging full archives.
72 #:compression compression
73 #:compression-level 3)))
74
75 ;; Honor ~/.ssh/config.
76 (session-parse-config! session)
77
78 (match (connect! session)
79 ('ok
80 ;; Use public key authentication, via the SSH agent if it's available.
81 (match (userauth-public-key/auto! session)
82 ('success
83 session)
84 (x
85 (disconnect! session)
86 (raise (condition
87 (&message
88 (message (format #f (G_ "SSH authentication failed for '~a': ~a~%")
89 host (get-error session)))))))))
90 (x
91 ;; Connection failed or timeout expired.
92 (raise (condition
93 (&message
94 (message (format #f (G_ "SSH connection to '~a' failed: ~a~%")
95 host (get-error session))))))))))
96
97 (define* (remote-daemon-channel session
98 #:optional
99 (socket-name
100 "/var/guix/daemon-socket/socket"))
101 "Return an input/output port (an SSH channel) to the daemon at SESSION."
102 (define redirect
103 ;; Code run in SESSION to redirect the remote process' stdin/stdout to the
104 ;; daemon's socket, à la socat. The SSH protocol supports forwarding to
105 ;; Unix-domain sockets but libssh doesn't have an API for that, hence this
106 ;; hack.
107 `(begin
108 (use-modules (ice-9 match) (rnrs io ports)
109 (rnrs bytevectors))
110
111 (let ((sock (socket AF_UNIX SOCK_STREAM 0))
112 (stdin (current-input-port))
113 (stdout (current-output-port)))
114 (setvbuf stdout _IONBF)
115
116 ;; Use buffered ports so that 'get-bytevector-some' returns up to the
117 ;; whole buffer like read(2) would--see <https://bugs.gnu.org/30066>.
118 (setvbuf stdin _IOFBF 65536)
119 (setvbuf sock _IOFBF 65536)
120
121 (connect sock AF_UNIX ,socket-name)
122
123 (let loop ()
124 (match (select (list stdin sock) '() '())
125 ((reads () ())
126 (when (memq stdin reads)
127 (match (get-bytevector-some stdin)
128 ((? eof-object?)
129 (primitive-exit 0))
130 (bv
131 (put-bytevector sock bv)
132 (force-output sock))))
133 (when (memq sock reads)
134 (match (get-bytevector-some sock)
135 ((? eof-object?)
136 (primitive-exit 0))
137 (bv
138 (put-bytevector stdout bv))))
139 (loop))
140 (_
141 (primitive-exit 1)))))))
142
143 (open-remote-pipe* session OPEN_BOTH
144 ;; Sort-of shell-quote REDIRECT.
145 "guile" "-c"
146 (object->string
147 (object->string redirect))))
148
149 (define* (connect-to-remote-daemon session
150 #:optional
151 (socket-name
152 "/var/guix/daemon-socket/socket"))
153 "Connect to the remote build daemon listening on SOCKET-NAME over SESSION,
154 an SSH session. Return a <nix-server> object."
155 (open-connection #:port (remote-daemon-channel session)))
156
157
158 (define (store-import-channel session)
159 "Return an output port to which archives to be exported to SESSION's store
160 can be written."
161 ;; Using the 'import-paths' RPC on a remote store would be slow because it
162 ;; makes a round trip every time 32 KiB have been transferred. This
163 ;; procedure instead opens a separate channel to use the remote
164 ;; 'import-paths' procedure, which consumes all the data in a single round
165 ;; trip. This optimizes the successful case at the expense of error
166 ;; conditions: errors can only be reported once all the input has been
167 ;; consumed.
168 (define import
169 `(begin
170 (use-modules (guix) (srfi srfi-34)
171 (rnrs io ports) (rnrs bytevectors))
172
173 (define (consume-input port)
174 (let ((bv (make-bytevector 32768)))
175 (let loop ()
176 (let ((n (get-bytevector-n! port bv 0
177 (bytevector-length bv))))
178 (unless (eof-object? n)
179 (loop))))))
180
181 ;; Upon completion, write an sexp that denotes the status.
182 (write
183 (catch #t
184 (lambda ()
185 (guard (c ((nix-protocol-error? c)
186 ;; Consume all the input since the only time we can
187 ;; report the error is after everything has been
188 ;; consumed.
189 (consume-input (current-input-port))
190 (list 'protocol-error (nix-protocol-error-message c))))
191 (with-store store
192 (setvbuf (current-input-port) _IONBF)
193 (import-paths store (current-input-port))
194 '(success))))
195 (lambda args
196 (cons 'error args))))))
197
198 (open-remote-pipe session
199 (string-join
200 `("guile" "-c"
201 ,(object->string (object->string import))))
202 OPEN_BOTH))
203
204 (define* (store-export-channel session files
205 #:key recursive?)
206 "Return an input port from which an export of FILES from SESSION's store can
207 be read. When RECURSIVE? is true, the closure of FILES is exported."
208 ;; Same as above: this is more efficient than calling 'export-paths' on a
209 ;; remote store.
210 (define export
211 `(begin
212 (eval-when (load expand eval)
213 (unless (resolve-module '(guix) #:ensure #f)
214 (write `(module-error))
215 (exit 7)))
216
217 (use-modules (guix) (srfi srfi-1)
218 (srfi srfi-26) (srfi srfi-34))
219
220 (guard (c ((nix-connection-error? c)
221 (write `(connection-error ,(nix-connection-error-file c)
222 ,(nix-connection-error-code c))))
223 ((nix-protocol-error? c)
224 (write `(protocol-error ,(nix-protocol-error-status c)
225 ,(nix-protocol-error-message c))))
226 (else
227 (write `(exception))))
228 (with-store store
229 (let* ((files ',files)
230 (invalid (remove (cut valid-path? store <>)
231 files)))
232 (unless (null? invalid)
233 (write `(invalid-items ,invalid))
234 (exit 1))
235
236 ;; TODO: When RECURSIVE? is true, we could send the list of store
237 ;; items in the closure so that the other end can filter out
238 ;; those it already has.
239
240 (write '(exporting)) ;we're ready
241 (force-output)
242
243 (setvbuf (current-output-port) _IONBF)
244 (export-paths store files (current-output-port)
245 #:recursive? ,recursive?))))))
246
247 (open-remote-input-pipe session
248 (string-join
249 `("guile" "-c"
250 ,(object->string
251 (object->string export))))))
252
253 (define* (send-files local files remote
254 #:key
255 recursive?
256 (log-port (current-error-port)))
257 "Send the subset of FILES from LOCAL (a local store) that's missing to
258 REMOTE, a remote store. When RECURSIVE? is true, send the closure of FILES.
259 Return the list of store items actually sent."
260 ;; Compute the subset of FILES missing on SESSION and send them.
261 (let* ((files (if recursive? (requisites local files) files))
262 (session (channel-get-session (nix-server-socket remote)))
263 (node (make-node session))
264 (missing (node-eval node
265 `(begin
266 (use-modules (guix)
267 (srfi srfi-1) (srfi srfi-26))
268
269 (with-store store
270 (remove (cut valid-path? store <>)
271 ',files)))))
272 (count (length missing))
273 (port (store-import-channel session)))
274 (format log-port (N_ "sending ~a store item to '~a'...~%"
275 "sending ~a store items to '~a'...~%" count)
276 count (session-get session 'host))
277
278 ;; Send MISSING in topological order.
279 (export-paths local missing port)
280
281 ;; Tell the remote process that we're done. (In theory the end-of-archive
282 ;; mark of 'export-paths' would be enough, but in practice it's not.)
283 (channel-send-eof port)
284
285 ;; Wait for completion of the remote process and read the status sexp from
286 ;; PORT.
287 (let* ((result (false-if-exception (read port)))
288 (status (zero? (channel-get-exit-status port))))
289 (close-port port)
290 (match result
291 (('success . _)
292 missing)
293 (('protocol-error message)
294 (raise (condition
295 (&nix-protocol-error (message message) (status 42)))))
296 (('error key args ...)
297 (raise (condition
298 (&nix-protocol-error
299 (message (call-with-output-string
300 (lambda (port)
301 (print-exception port #f key args))))
302 (status 43)))))
303 (_
304 (raise (condition
305 (&nix-protocol-error
306 (message "unknown error while sending files over SSH")
307 (status 44)))))))))
308
309 (define (remote-store-session remote)
310 "Return the SSH channel beneath REMOTE, a remote store as returned by
311 'connect-to-remote-daemon', or #f."
312 (channel-get-session (nix-server-socket remote)))
313
314 (define (remote-store-host remote)
315 "Return the name of the host REMOTE is connected to, where REMOTE is a
316 remote store as returned by 'connect-to-remote-daemon'."
317 (match (remote-store-session remote)
318 (#f #f)
319 ((? session? session)
320 (session-get session 'host))))
321
322 (define* (file-retrieval-port files remote
323 #:key recursive?)
324 "Return an input port from which to retrieve FILES (a list of store items)
325 from REMOTE, along with the number of items to retrieve (lower than or equal
326 to the length of FILES.)"
327 (values (store-export-channel (remote-store-session remote) files
328 #:recursive? recursive?)
329 (length files))) ;XXX: inaccurate when RECURSIVE? is true
330
331 (define-syntax raise-error
332 (syntax-rules (=>)
333 ((_ fmt args ... (=> hint-fmt hint-args ...))
334 (raise (condition
335 (&message
336 (message (format #f fmt args ...)))
337 (&fix-hint
338 (hint (format #f hint-fmt hint-args ...))))))
339 ((_ fmt args ...)
340 (raise (condition
341 (&message
342 (message (format #f fmt args ...))))))))
343
344 (define* (retrieve-files* files remote
345 #:key recursive? (log-port (current-error-port))
346 (import (const #f)))
347 "Pass IMPORT an input port from which to read the sequence of FILES coming
348 from REMOTE. When RECURSIVE? is true, retrieve the closure of FILES."
349 (let-values (((port count)
350 (file-retrieval-port files remote
351 #:recursive? recursive?)))
352 (match (read port) ;read the initial status
353 (('exporting)
354 (format #t (N_ "retrieving ~a store item from '~a'...~%"
355 "retrieving ~a store items from '~a'...~%" count)
356 count (remote-store-host remote))
357
358 (dynamic-wind
359 (const #t)
360 (lambda ()
361 (import port))
362 (lambda ()
363 (close-port port))))
364 ((? eof-object?)
365 (report-guile-error (remote-store-host remote)))
366 (('module-error . _)
367 (report-module-error (remote-store-host remote)))
368 (('connection-error file code . _)
369 (raise-error (G_ "failed to connect to '~A' on remote host '~A': ~a")
370 file (remote-store-host remote) (strerror code)))
371 (('invalid-items items . _)
372 (raise-error (N_ "no such item on remote host '~A':~{ ~a~}"
373 "no such items on remote host '~A':~{ ~a~}"
374 (length items))
375 (remote-store-host remote) items))
376 (('protocol-error status message . _)
377 (raise-error (G_ "protocol error on remote host '~A': ~a")
378 (remote-store-host remote) message))
379 (_
380 (raise-error (G_ "failed to retrieve store items from '~a'")
381 (remote-store-host remote))))))
382
383 (define* (retrieve-files local files remote
384 #:key recursive? (log-port (current-error-port)))
385 "Retrieve FILES from REMOTE and import them using the 'import-paths' RPC on
386 LOCAL. When RECURSIVE? is true, retrieve the closure of FILES."
387 (retrieve-files* (remove (cut valid-path? local <>) files)
388 remote
389 #:recursive? recursive?
390 #:log-port log-port
391 #:import (lambda (port)
392 (import-paths local port))))
393
394 \f
395 ;;;
396 ;;; Error reporting.
397 ;;;
398
399 (define (report-guile-error host)
400 (raise-error (G_ "failed to start Guile on remote host '~A'") host
401 (=> (G_ "Make sure @command{guile} can be found in
402 @code{$PATH} on the remote host. Run @command{ssh ~A guile --version} to
403 check.")
404 host)))
405
406 (define (report-module-error host)
407 "Report an error about missing Guix modules on HOST."
408 ;; TRANSLATORS: Leave "Guile" untranslated.
409 (raise-error (G_ "Guile modules not found on remote host '~A'") host
410 (=> (G_ "Make sure @code{GUILE_LOAD_PATH} includes Guix'
411 own module directory. Run @command{ssh ~A env | grep GUILE_LOAD_PATH} to
412 check.")
413 host)))
414
415 ;;; ssh.scm ends here