digital-ocean.scm 17 KB

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