digital-ocean.scm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2019 Jakob L. Kreuze <zerodaysfordays@sdf.org>
  3. ;;; Copyright © 2020 Brice Waegeneire <brice@waegenei.re>
  4. ;;; Copyright © 2022 Matthew James Kraai <kraai@ftbfs.org>
  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 (gnu machine digital-ocean)
  21. #:use-module (gnu machine ssh)
  22. #:use-module (gnu machine)
  23. #:use-module (gnu services)
  24. #:use-module (gnu services networking)
  25. #:use-module (gnu system)
  26. #:use-module (gnu system pam)
  27. #:use-module (guix base32)
  28. #:use-module (guix derivations)
  29. #:use-module (guix i18n)
  30. #:use-module ((guix diagnostics) #:select (formatted-message))
  31. #:use-module (guix import json)
  32. #:use-module (guix monads)
  33. #:use-module (guix records)
  34. #:use-module (guix ssh)
  35. #:use-module (guix store)
  36. #:use-module (ice-9 iconv)
  37. #:use-module (json)
  38. #:use-module (rnrs bytevectors)
  39. #:use-module (srfi srfi-1)
  40. #:use-module (srfi srfi-2)
  41. #:use-module (srfi srfi-34)
  42. #:use-module (srfi srfi-35)
  43. #:use-module (ssh key)
  44. #:use-module (ssh sftp)
  45. #:use-module (ssh shell)
  46. #:use-module (web client)
  47. #:use-module (web request)
  48. #:use-module (web response)
  49. #:use-module (web uri)
  50. #:export (digital-ocean-configuration
  51. digital-ocean-configuration?
  52. digital-ocean-configuration-ssh-key
  53. digital-ocean-configuration-tags
  54. digital-ocean-configuration-region
  55. digital-ocean-configuration-size
  56. digital-ocean-configuration-enable-ipv6?
  57. digital-ocean-environment-type))
  58. ;;; Commentary:
  59. ;;;
  60. ;;; This module implements a high-level interface for provisioning "droplets"
  61. ;;; from the Digital Ocean virtual private server (VPS) service.
  62. ;;;
  63. ;;; Code:
  64. (define %api-base "https://api.digitalocean.com")
  65. (define %digital-ocean-token
  66. (make-parameter (getenv "GUIX_DIGITAL_OCEAN_TOKEN")))
  67. (define* (post-endpoint endpoint body)
  68. "Encode BODY as JSON and send it to the Digital Ocean API endpoint
  69. ENDPOINT. This procedure is quite a bit more specialized than 'http-post', as
  70. it takes care to set headers such as 'Content-Type', 'Content-Length', and
  71. 'Authorization' appropriately."
  72. (let* ((uri (string->uri (string-append %api-base endpoint)))
  73. (body (string->bytevector (scm->json-string body) "UTF-8"))
  74. (headers `((User-Agent . "Guix Deploy")
  75. (Accept . "application/json")
  76. (Content-Type . "application/json")
  77. (Authorization . ,(format #f "Bearer ~a"
  78. (%digital-ocean-token)))
  79. (Content-Length . ,(number->string
  80. (bytevector-length body)))))
  81. (port (open-socket-for-uri uri))
  82. (request (build-request uri
  83. #:method 'POST
  84. #:version '(1 . 1)
  85. #:headers headers
  86. #:port port))
  87. (request (write-request request port)))
  88. (write-request-body request body)
  89. (force-output (request-port request))
  90. (let* ((response (read-response port))
  91. (body (read-response-body response)))
  92. (unless (= 2 (floor/ (response-code response) 100))
  93. (raise
  94. (condition (&message
  95. (message (format
  96. #f
  97. (G_ "~a: HTTP post failed: ~a (~s)")
  98. (uri->string uri)
  99. (response-code response)
  100. (response-reason-phrase response)))))))
  101. (close-port port)
  102. (bytevector->string body "UTF-8"))))
  103. (define (fetch-endpoint endpoint)
  104. "Return the contents of the Digital Ocean API endpoint ENDPOINT as an
  105. alist. This procedure is quite a bit more specialized than 'json-fetch', as it
  106. takes care to set headers such as 'Accept' and 'Authorization' appropriately."
  107. (define headers
  108. `((user-agent . "Guix Deploy")
  109. (Accept . "application/json")
  110. (Authorization . ,(format #f "Bearer ~a" (%digital-ocean-token)))))
  111. (json-fetch (string-append %api-base endpoint) #:headers headers))
  112. ;;;
  113. ;;; Parameters for droplet creation.
  114. ;;;
  115. (define-record-type* <digital-ocean-configuration> digital-ocean-configuration
  116. make-digital-ocean-configuration
  117. digital-ocean-configuration?
  118. this-digital-ocean-configuration
  119. (ssh-key digital-ocean-configuration-ssh-key) ; string
  120. (tags digital-ocean-configuration-tags) ; list of strings
  121. (region digital-ocean-configuration-region) ; string
  122. (size digital-ocean-configuration-size) ; string
  123. (enable-ipv6? digital-ocean-configuration-enable-ipv6?)) ; boolean
  124. (define (read-key-fingerprint file-name)
  125. "Read the private key at FILE-NAME and return the key's fingerprint as a hex
  126. string."
  127. (let* ((privkey (private-key-from-file file-name))
  128. (pubkey (private-key->public-key privkey))
  129. (hash (get-public-key-hash pubkey 'md5)))
  130. (bytevector->hex-string hash)))
  131. (define (machine-droplet machine)
  132. "Return an alist describing the droplet allocated to MACHINE."
  133. (let ((tags (digital-ocean-configuration-tags
  134. (machine-configuration machine))))
  135. (find (lambda (droplet)
  136. (equal? (assoc-ref droplet "tags") (list->vector tags)))
  137. (vector->list
  138. (assoc-ref (fetch-endpoint "/v2/droplets") "droplets")))))
  139. (define (machine-public-ipv4-network machine)
  140. "Return the public IPv4 network interface of the droplet allocated to
  141. MACHINE as an alist. The expected fields are 'ip_address', 'netmask', and
  142. 'gateway'."
  143. (and-let* ((droplet (machine-droplet machine))
  144. (networks (assoc-ref droplet "networks"))
  145. (network (find (lambda (network)
  146. (string= "public" (assoc-ref network "type")))
  147. (vector->list (assoc-ref networks "v4")))))
  148. network))
  149. ;;;
  150. ;;; Remote evaluation.
  151. ;;;
  152. (define (digital-ocean-remote-eval target exp)
  153. "Internal implementation of 'machine-remote-eval' for MACHINE instances with
  154. an environment type of 'digital-ocean-environment-type'."
  155. (let* ((network (machine-public-ipv4-network target))
  156. (address (assoc-ref network "ip_address"))
  157. (ssh-key (digital-ocean-configuration-ssh-key
  158. (machine-configuration target)))
  159. (delegate (machine
  160. (inherit target)
  161. (environment managed-host-environment-type)
  162. (configuration
  163. (machine-ssh-configuration
  164. (host-name address)
  165. (identity ssh-key)
  166. (system "x86_64-linux"))))))
  167. (machine-remote-eval delegate exp)))
  168. ;;;
  169. ;;; System deployment.
  170. ;;;
  171. ;; The following script was adapted from the guide available at
  172. ;; <https://wiki.pantherx.org/Installation-digital-ocean/>.
  173. (define (guix-infect network)
  174. "Given NETWORK, an alist describing the Droplet's public IPv4 network
  175. interface, return a Bash script that will install the Guix system."
  176. (format #f "#!/bin/bash
  177. apt-get update
  178. apt-get install xz-utils -y
  179. wget https://ftp.gnu.org/gnu/guix/guix-binary-1.0.1.x86_64-linux.tar.xz
  180. cd /tmp
  181. tar --warning=no-timestamp -xf ~~/guix-binary-1.0.1.x86_64-linux.tar.xz
  182. mv var/guix /var/ && mv gnu /
  183. mkdir -p ~~root/.config/guix
  184. ln -sf /var/guix/profiles/per-user/root/current-guix ~~root/.config/guix/current
  185. export GUIX_PROFILE=\"`echo ~~root`/.config/guix/current\" ;
  186. source $GUIX_PROFILE/etc/profile
  187. groupadd --system guixbuild
  188. for i in `seq -w 1 10`; do
  189. useradd -g guixbuild -G guixbuild \
  190. -d /var/empty -s `which nologin` \
  191. -c \"Guix build user $i\" --system \
  192. guixbuilder$i;
  193. done;
  194. cp ~~root/.config/guix/current/lib/systemd/system/guix-daemon.service /etc/systemd/system/
  195. systemctl start guix-daemon && systemctl enable guix-daemon
  196. mkdir -p /usr/local/bin
  197. cd /usr/local/bin
  198. ln -s /var/guix/profiles/per-user/root/current-guix/bin/guix
  199. mkdir -p /usr/local/share/info
  200. cd /usr/local/share/info
  201. for i in /var/guix/profiles/per-user/root/current-guix/share/info/*; do
  202. ln -s $i;
  203. done
  204. guix archive --authorize < ~~root/.config/guix/current/share/guix/ci.guix.gnu.org.pub
  205. # guix pull
  206. guix package -i glibc-utf8-locales
  207. export GUIX_LOCPATH=\"$HOME/.guix-profile/lib/locale\"
  208. guix package -i openssl
  209. cat > /etc/bootstrap-config.scm << EOF
  210. (use-modules (gnu))
  211. (use-service-modules networking ssh)
  212. (operating-system
  213. (host-name \"gnu-bootstrap\")
  214. (timezone \"Etc/UTC\")
  215. (bootloader (bootloader-configuration
  216. (bootloader grub-bootloader)
  217. (targets '(\"/dev/vda\"))
  218. (terminal-outputs '(console))))
  219. (file-systems (cons (file-system
  220. (mount-point \"/\")
  221. (device \"/dev/vda1\")
  222. (type \"ext4\"))
  223. %base-file-systems))
  224. (services
  225. (append (list (static-networking-service \"eth0\" \"~a\"
  226. #:netmask \"~a\"
  227. #:gateway \"~a\"
  228. #:name-servers '(\"84.200.69.80\" \"84.200.70.40\"))
  229. (simple-service 'guile-load-path-in-global-env
  230. session-environment-service-type
  231. \\`((\"GUILE_LOAD_PATH\"
  232. . \"/run/current-system/profile/share/guile/site/2.2\")
  233. (\"GUILE_LOAD_COMPILED_PATH\"
  234. . ,(string-append \"/run/current-system/profile/lib/guile/2.2/site-ccache:\"
  235. \"/run/current-system/profile/share/guile/site/2.2\"))))
  236. (service openssh-service-type
  237. (openssh-configuration
  238. (log-level 'debug)
  239. (permit-root-login 'prohibit-password))))
  240. %base-services)))
  241. EOF
  242. # guix pull
  243. guix system build /etc/bootstrap-config.scm
  244. guix system reconfigure /etc/bootstrap-config.scm
  245. mv /etc /old-etc
  246. mkdir /etc
  247. cp -r /old-etc/{passwd,group,shadow,gshadow,mtab,guix,bootstrap-config.scm} /etc/
  248. guix system reconfigure /etc/bootstrap-config.scm"
  249. (assoc-ref network "ip_address")
  250. (assoc-ref network "netmask")
  251. (assoc-ref network "gateway")))
  252. (define (machine-wait-until-available machine)
  253. "Block until the initial Debian image has been installed on the droplet
  254. named DROPLET-NAME."
  255. (and-let* ((droplet (machine-droplet machine))
  256. (droplet-id (assoc-ref droplet "id"))
  257. (endpoint (format #f "/v2/droplets/~a/actions" droplet-id)))
  258. (let loop ()
  259. (let ((actions (assoc-ref (fetch-endpoint endpoint) "actions")))
  260. (unless (every (lambda (action)
  261. (string= "completed" (assoc-ref action "status")))
  262. (vector->list actions))
  263. (sleep 5)
  264. (loop))))))
  265. (define (wait-for-ssh address ssh-key)
  266. "Block until the an SSH session can be made as 'root' with SSH-KEY at ADDRESS."
  267. (let loop ()
  268. (catch #t
  269. (lambda ()
  270. (open-ssh-session address #:user "root" #:identity ssh-key))
  271. (lambda args
  272. (sleep 5)
  273. (loop)))))
  274. (define (add-static-networking target network)
  275. "Return an <operating-system> based on TARGET with a static networking
  276. configuration for the public IPv4 network described by the alist NETWORK."
  277. (operating-system
  278. (inherit (machine-operating-system target))
  279. (services (cons* (static-networking-service "eth0"
  280. (assoc-ref network "ip_address")
  281. #:netmask (assoc-ref network "netmask")
  282. #:gateway (assoc-ref network "gateway")
  283. #:name-servers '("84.200.69.80" "84.200.70.40"))
  284. (simple-service 'guile-load-path-in-global-env
  285. session-environment-service-type
  286. `(("GUILE_LOAD_PATH"
  287. . "/run/current-system/profile/share/guile/site/2.2")
  288. ("GUILE_LOAD_COMPILED_PATH"
  289. . ,(string-append "/run/current-system/profile/lib/guile/2.2/site-ccache:"
  290. "/run/current-system/profile/share/guile/site/2.2"))))
  291. (operating-system-user-services
  292. (machine-operating-system target))))))
  293. (define (deploy-digital-ocean target)
  294. "Internal implementation of 'deploy-machine' for 'machine' instances with an
  295. environment type of 'digital-ocean-environment-type'."
  296. (maybe-raise-missing-api-key-error)
  297. (maybe-raise-unsupported-configuration-error target)
  298. (let* ((config (machine-configuration target))
  299. (name (machine-display-name target))
  300. (region (digital-ocean-configuration-region config))
  301. (size (digital-ocean-configuration-size config))
  302. (ssh-key (digital-ocean-configuration-ssh-key config))
  303. (fingerprint (read-key-fingerprint ssh-key))
  304. (enable-ipv6? (digital-ocean-configuration-enable-ipv6? config))
  305. (tags (digital-ocean-configuration-tags config))
  306. (request-body `(("name" . ,name)
  307. ("region" . ,region)
  308. ("size" . ,size)
  309. ("image" . "debian-9-x64")
  310. ("ssh_keys" . ,(vector fingerprint))
  311. ("backups" . #f)
  312. ("ipv6" . ,enable-ipv6?)
  313. ("user_data" . #nil)
  314. ("private_networking" . #nil)
  315. ("volumes" . #nil)
  316. ("tags" . ,(list->vector tags))))
  317. (response (post-endpoint "/v2/droplets" request-body)))
  318. (machine-wait-until-available target)
  319. (let* ((network (machine-public-ipv4-network target))
  320. (address (assoc-ref network "ip_address")))
  321. (wait-for-ssh address ssh-key)
  322. (let* ((ssh-session (open-ssh-session address #:user "root" #:identity ssh-key))
  323. (sftp-session (make-sftp-session ssh-session)))
  324. (call-with-remote-output-file sftp-session "/tmp/guix-infect.sh"
  325. (lambda (port)
  326. (display (guix-infect network) port)))
  327. (rexec ssh-session "/bin/bash /tmp/guix-infect.sh")
  328. ;; Session will close upon rebooting, which will raise 'guile-ssh-error.
  329. (catch 'guile-ssh-error
  330. (lambda () (rexec ssh-session "reboot"))
  331. (lambda args #t)))
  332. (wait-for-ssh address ssh-key)
  333. (let ((delegate (machine
  334. (operating-system (add-static-networking target network))
  335. (environment managed-host-environment-type)
  336. (configuration
  337. (machine-ssh-configuration
  338. (host-name address)
  339. (identity ssh-key)
  340. (system "x86_64-linux"))))))
  341. (deploy-machine delegate)))))
  342. ;;;
  343. ;;; Roll-back.
  344. ;;;
  345. (define (roll-back-digital-ocean target)
  346. "Internal implementation of 'roll-back-machine' for MACHINE instances with an
  347. environment type of 'digital-ocean-environment-type'."
  348. (let* ((network (machine-public-ipv4-network target))
  349. (address (assoc-ref network "ip_address"))
  350. (ssh-key (digital-ocean-configuration-ssh-key
  351. (machine-configuration target)))
  352. (delegate (machine
  353. (inherit target)
  354. (environment managed-host-environment-type)
  355. (configuration
  356. (machine-ssh-configuration
  357. (host-name address)
  358. (identity ssh-key)
  359. (system "x86_64-linux"))))))
  360. (roll-back-machine delegate)))
  361. ;;;
  362. ;;; Environment type.
  363. ;;;
  364. (define digital-ocean-environment-type
  365. (environment-type
  366. (machine-remote-eval digital-ocean-remote-eval)
  367. (deploy-machine deploy-digital-ocean)
  368. (roll-back-machine roll-back-digital-ocean)
  369. (name 'digital-ocean-environment-type)
  370. (description "Provisioning of \"droplets\": virtual machines
  371. provided by the Digital Ocean virtual private server (VPS) service.")))
  372. (define (maybe-raise-missing-api-key-error)
  373. (unless (%digital-ocean-token)
  374. (raise (condition
  375. (&message
  376. (message (G_ "No Digital Ocean access token was provided. This \
  377. may be fixed by setting the environment variable GUIX_DIGITAL_OCEAN_TOKEN to \
  378. one procured from https://cloud.digitalocean.com/account/api/tokens.")))))))
  379. (define (maybe-raise-unsupported-configuration-error machine)
  380. "Raise an error if MACHINE's configuration is not an instance of
  381. <digital-ocean-configuration>."
  382. (let ((config (machine-configuration machine))
  383. (environment (environment-type-name (machine-environment machine))))
  384. (unless (and config (digital-ocean-configuration? config))
  385. (raise (formatted-message (G_ "unsupported machine configuration '~a' \
  386. for environment of type '~a'")
  387. config
  388. environment)))))