digital-ocean.scm 17 KB

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