;;; GNU Guix --- Functional package management for GNU ;;; Copyright © 2015 David Thompson ;;; Copyright © 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès ;;; Copyright © 2016 Nikita ;;; Copyright © 2016, 2017, 2018 Julien Lepiller ;;; Copyright © 2017 Christopher Baines ;;; Copyright © 2017 nee ;;; Copyright © 2017, 2018 Clément Lassieur ;;; Copyright © 2018 Pierre-Antoine Rouby ;;; Copyright © 2017, 2018, 2019 Christopher Baines ;;; Copyright © 2018 Marius Bakke ;;; Copyright © 2019, 2020 Florian Pelz ;;; Copyright © 2020 Ricardo Wurmus ;;; Copyright © 2020 Tobias Geerinckx-Rice ;;; Copyright © 2020 Arun Isaac ;;; Copyright © 2020 Oleg Pykhalov ;;; Copyrig
aboutsummaryrefslogtreecommitdiff
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2016-2022, 2024 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2018 Chris Marusich <cmmarusich@gmail.com>
;;; Copyright © 2022, 2023 Maxim Cournoyer <maxim.cournoyer@gmail.com>
;;; Copyright © 2023 Bruno Victal <mirai@makinata.eu>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with GNU Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (gnu build marionette)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-64)
  #:use-module (srfi srfi-71)
  #:use-module (rnrs io ports)
  #:use-module (ice-9 match)
  #:use-module (ice-9 popen)
  #:use-module (ice-9 regex)
  #:export (marionette?
            marionette-pid
            make-marionette
            marionette-eval
            wait-for-file
            wait-for-tcp-port
            wait-for-unix-socket
            marionette-control
            wait-for-screen-text
            %default-ocrad-arguments
            %qwerty-us-keystrokes
            marionette-type

            system-test-runner
            qemu-command))

;;; Commentary:
;;;
;;; Instrumentation tools for QEMU virtual machines (VMs).  A "marionette" is
;;; essentially a VM (a QEMU instance) with its monitor connected to a
;;; Unix-domain socket, and with a REPL inside the guest listening on a
;;; virtual console, which is itself connected to the host via a Unix-domain
;;; socket--these are the marionette's strings, connecting it to the almighty
;;; puppeteer.
;;;
;;; Code:

(define-record-type <marionette>
  (marionette command pid monitor repl)
  marionette?
  (command    marionette-command)                 ;list of strings
  (pid        marionette-pid)                     ;integer
  (monitor    marionette-monitor)                 ;port
  (repl       %marionette-repl))                  ;promise of a port

(define-syntax-rule (marionette-repl marionette)
  (force (%marionette-repl marionette)))

(define* (wait-for-monitor-prompt port #:key (quiet? #t))
  "Read from PORT until we have seen all of QEMU's monitor prompt.  When
QUIET? is false, the monitor's output is written to the current output port."
  (define full-prompt
    (string->list "(qemu) "))

  (let loop ((prompt full-prompt)
             (matches '())
             (prefix  '()))
    (match prompt
      (()
       ;; It's useful to set QUIET? so we don't display the echo of our own
       ;; commands.
       (unless quiet?
         (for-each (lambda (line)
                     (format #t "qemu monitor: ~a~%" line))
                   (string-tokenize (list->string (reverse prefix))
                                    (char-set-complement (char-set #\newline))))))
      ((chr rest ...)
       (let ((read (read-char port)))
         (cond ((eqv? read chr)
                (loop rest (cons read matches) prefix))
               ((eof-object? read)
                (error "EOF while waiting for QEMU monitor prompt"
                       (list->string (reverse prefix))))
               (else
                (loop full-prompt
                      '()
                      (cons read (append matches prefix))))))))))

(define* (make-marionette command
                          #:key (socket-directory "/tmp") (timeout 20))
  "Return a QEMU marionette--i.e., a virtual machine with open connections to the
QEMU monitor and to the guest's backdoor REPL."
  (define (file->sockaddr file)
    (make-socket-address AF_UNIX
                         (string-append socket-directory "/" file)))

  (define extra-options
    (list "-nographic"
          "-monitor" (string-append "unix:" socket-directory "/monitor")
          "-chardev" (string-append "socket,id=repl,path=" socket-directory
                                    "/repl")
          "-chardev" (string-append "socket,id=qga,server=on,wait=off,path="
                                    socket-directory "/qemu-ga")

          ;; See
          ;; <http://www.linux-kvm.org/page/VMchannel_Requirements#Invocation>.
          "-device" "virtio-serial"
          "-device" "virtserialport,chardev=repl,name=org.gnu.guix.port.0"
          "-device" "virtserialport,chardev=qga,name=org.qemu.guest_agent.0"))

  (define (accept* port)
    (match (select (list port) '() (list port) timeout)
      (((port) () ())
       (accept port))
      (_
       (error "timeout in 'accept'" port))))

  (let ((monitor (socket AF_UNIX SOCK_STREAM 0))
        (repl    (socket AF_UNIX SOCK_STREAM 0)))
    (bind monitor (file->sockaddr "monitor"))
    (listen monitor 1)
    (bind repl (file->sockaddr "repl"))
    (listen repl 1)

    (match (primitive-fork)
      (0
       (catch #t
         (lambda ()
           (close monitor)
           (close repl)
           (match command
             ((program . args)
              (apply execl program program
                     (append args extra-options)))))
         (lambda (key . args)
           (print-exception (current-error-port)
                            (stack-ref (make-stack #t) 1)
                            key args)
           (primitive-exit 1))))
      (pid
       (format #t "QEMU runs as PID ~a~%" pid)

       (match (accept* monitor)
         ((monitor-conn . _)
          (display "connected to QEMU's monitor\n")
          (close-port monitor)
          (wait-for-monitor-prompt monitor-conn)
          (display "read QEMU monitor prompt\n")

          (marionette (append command extra-options) pid
                      monitor-conn

                      ;; The following 'accept' call connects immediately, but
                      ;; we don't know whether the guest has connected until
                      ;; we actually receive the 'ready' message.
                      (match (accept* repl)
                        ((repl-conn . addr)
                         (display "connected to guest REPL\n")
                         (close-port repl)
                         ;; Delay reception of the 'ready' message so that the
                         ;; caller can already send monitor commands.
                         (delay
                           (match (read repl-conn)
                             ('ready
                              (display "marionette is ready\n")
                              repl-conn))))))))))))

(define (marionette-eval exp marionette)
  "Evaluate EXP in MARIONETTE's backdoor REPL.  Return the result."
  (match marionette
    (($ <marionette> command pid monitor (= force repl))
     (write exp repl)
     (newline repl)
     (with-exception-handler
         (lambda (exn)
           (simple-format
            (current-error-port)
            "error reading marionette response: ~A
  remaining response: ~A\n"
            exn
            (get-line repl))
           (raise-exception exn))
       (lambda ()
         (read repl))
       #:unwind? #t))))

(define* (wait-for-file file marionette
                        #:key (timeout 10) (read 'read))
  "Wait until FILE exists in MARIONETTE; READ its content and return it.  If
FILE has not shown up after TIMEOUT seconds, raise an error."
  (match (marionette-eval
          `(let loop ((i ,timeout))
             (cond ((file-exists? ,file)
                    (cons 'success
                          (let ((content
                                 (call-with-input-file ,file ,read)))
                            (if (eof-object? content)
                                ;; #<eof> can't be read, so convert to the
                                ;; empty string
                                ""
                                content))))
                   ((> i 0)
                    (sleep 1)
                    (loop (- i 1)))
                   (else
                    'failure)))
          marionette)
    (('success . result)
     result)
    ('failure
     (error "file didn't show up" file))))

(define* (wait-for-tcp-port port marionette
                            #:key
                            (timeout 20)
                            (peek? #f)
                            (address `(make-socket-address AF_INET
                                                           INADDR_LOOPBACK
                                                           ,port)))
  "Wait for up to TIMEOUT seconds for PORT to accept connections in
MARIONETTE.  ADDRESS must be an expression that returns a socket address,
typically a call to 'make-socket-address'.  When PEEK? is true, attempt to
read a byte from the socket upon connection; retry if that gives the
end-of-file object.

Raise an error on failure."
  ;; Note: The 'connect' loop has to run within the guest because, when we
  ;; forward ports to the host, connecting to the host never raises
  ;; ECONNREFUSED.
  (match (marionette-eval
          `(let* ((address ,address))
             (define (open-socket)
               (socket (sockaddr:fam address) SOCK_STREAM 0))

             (let loop ((sock (open-socket))
                        (i 0))
               (catch 'system-error
                 (lambda ()
                   (connect sock address)
                   (when ,peek?
                     (let ((byte ((@ (ice-9 binary-ports) lookahead-u8)
                                  sock)))
                       (when (eof-object? byte)
                         (close-port sock)
                         (throw 'system-error
                                "wait-for-tcp-port" "~A"
                                (list (strerror ECONNRESET))
                                (list ECONNRESET)))))
                   (close-port sock)
                   'success)
                 (lambda args
                   (if (< i ,timeout)
                       (begin
                         (sleep 1)
                         (loop (if (port-closed? sock)
                                   (open-socket)
                                   sock)
                               (+ 1 i)))
                       (list 'failure address))))))
          marionette)
    ('success #t)
    (('failure address)
     (error "nobody's listening on port"
            (list (inet-ntop (sockaddr:fam address) (sockaddr:addr address))
                  (sockaddr:port address))))))

(define* (wait-for-unix-socket file-name marionette
                                #:key (timeout 20))
  "Wait for up to TIMEOUT seconds for FILE-NAME, a Unix domain socket, to
accept connections in MARIONETTE.  Raise an error on failure."
  (match (marionette-eval
          `(begin
             (let ((sock (socket PF_UNIX SOCK_STREAM 0)))
               (let loop ((i 0))
                 (catch 'system-error
                   (lambda ()
                     (connect sock AF_UNIX ,file-name)
                     (close-port sock)
                     'success)
                   (lambda args
                     (if (< i ,timeout)
                         (begin
                           (sleep 1)
                           (loop (+ 1 i)))
                         'failure))))))
          marionette)
    ('success #t)
    ('failure
     (error "nobody's listening on unix domain socket" file-name))))

(define (marionette-control command marionette)
  "Run COMMAND in the QEMU monitor of MARIONETTE.  COMMAND is a string such as
\"sendkey ctrl-alt-f1\" or \"screendump foo.ppm\" (info \"(QEMU) QEMU
Monitor\")."
  (match marionette
    (($ <marionette> _ _ monitor)
     (display command monitor)
     (newline monitor)
     ;; The "quit" command terminates QEMU immediately, with no output.
     (unless (string=? command "quit") (wait-for-monitor-prompt monitor)))))

(define %default-ocrad-arguments
  '("--invert" "--scale=10"))

(define* (invoke-ocrad-ocr image #:key (ocrad "ocrad")
                           (ocr-arguments %default-ocrad-arguments))
  "Invoke the OCRAD command on image, and return the recognized text."
  (let* ((command (string-join `(,ocrad ,@ocr-arguments ,image)))
         (pipe (open-input-pipe command))
         (text (get-string-all pipe)))
    (unless (zero? (close-pipe pipe))
      (error "'ocrad' failed" ocrad))
    text))

(define* (invoke-tesseract-ocr image #:key (tesseract "tesseract")
                               (ocr-arguments '()))
  "Invoke the TESSERACT command on IMAGE, and return the recognized text."
  (let* ((output-basename (tmpnam))
         (output-basename* (string-append output-basename ".txt"))
         (arguments (cons* image output-basename ocr-arguments)))
    (dynamic-wind
      (const #t)
      (lambda ()
        (let ((exit-val (status:exit-val
                         (apply system* tesseract arguments))))
          (unless (zero? exit-val)
            (error "'tesseract' failed" tesseract))
          (call-with-input-file output-basename* get-string-all)))
      (lambda ()
        (false-if-exception (delete-file output-basename))
        (false-if-exception (delete-file output-basename*))))))

(define* (marionette-screen-text marionette #:key (ocr "ocrad")
                                 ocr-arguments)
  "Take a screenshot of MARIONETTE, perform optical character
recognition (OCR), and return the text read from the screen as a string, along
the screen dump image used.  Do this by invoking OCR, which should be the file
name of GNU Ocrad's@command{ocrad} or Tesseract OCR's @command{tesseract}
command.  The screen dump image returned as the second value should be deleted
if it is not needed."
  (define image (string-append (tmpnam) ".ppm"))
  ;; Use the QEMU Monitor to save an image of the screen to the host.
  (marionette-control (string-append "screendump " image) marionette)
  ;; Process it via the OCR.
  (cond
   ((string-contains ocr "ocrad")
    (values (invoke-ocrad-ocr image
                              #:ocrad ocr
                              #:ocr-arguments
                              (or ocr-arguments %default-ocrad-arguments))
            image))
   ((string-contains ocr "tesseract")
    (values (invoke-tesseract-ocr image
                                  #:tesseract ocr
                                  #:ocr-arguments (or ocr-arguments '()))
            image))
   (else (error "unsupported ocr command"))))

(define* (wait-for-screen-text marionette predicate
                               #:key
                               (ocr "ocrad")
                               ocr-arguments
                               (timeout 30)
                               pre-action
                               post-action)
  "Wait for TIMEOUT seconds or until the screen text on MARIONETTE matches
PREDICATE, whichever comes first.  Raise an error when TIMEOUT is exceeded.
The error contains the recognized text along the preserved file name of the
screen dump, which is relative to the current working directory.  If
PRE-ACTION is provided, it should be a thunk to call before each OCR attempt.
Likewise for POST-ACTION, except it runs at the end of a successful OCR."
  (define start
    (car (gettimeofday)))

  (define end
    (+ start timeout))

  (let loop ((last-text #f)
             (last-screendump #f))
    (if (> (car (gettimeofday)) end)
        (let ((screendump-backup (string-drop last-screendump 5)))
          ;; Move the file from /tmp/fileXXXXXX.pmm to the current working
          ;; directory, so that it is preserved in the test derivation output.
          (copy-file last-screendump screendump-backup)
          (delete-file last-screendump)
          (error "'wait-for-screen-text' timeout"
                 'ocr-text: last-text
                 'screendump: screendump-backup))
        (let* ((_ (and (procedure? pre-action) (pre-action)))
               (text screendump
                     (marionette-screen-text marionette
                                             #:ocr ocr
                                             #:ocr-arguments ocr-arguments))
               (_ (and (procedure? post-action) (post-action)))
               (result (predicate text)))
          (cond (result
                 (delete-file screendump)
                 result)
                (else
                 (sleep 1)
                 (loop text screendump)))))))

(define %qwerty-us-keystrokes
  ;; Maps "special" characters to their keystrokes.
  '((#\newline . "ret")
    (#\space . "spc")
    (#\- . "minus")
    (#\+ . "shift-equal")
    (#\* . "shift-8")
    (#\= . "equal")
    (#\? . "shift-slash")
    (#\[ . "bracket_left")
    (#\] . "bracket_right")
    (#\{ . "shift-bracket_left")
    (#\} . "shift-bracket_right")
    (#\( . "shift-9")
    (#\) . "shift-0")
    (#\/ . "slash")
    (#\< . "shift-comma")
    (#\> . "shift-dot")
    (#\. . "dot")
    (#\, . "comma")
    (#\: . "shift-semicolon")
    (#\; . "semicolon")
    (#\' . "apostrophe")
    (#\! . "shift-1")
    (#\" . "shift-apostrophe")
    (#\` . "grave_accent")
    (#\bs . "backspace")
    (#\tab . "tab")))

(define (character->keystroke chr keystrokes)
  "Return the keystroke for CHR according to the keyboard layout defined by
KEYSTROKES."
  (if (char-set-contains? char-set:upper-case chr)
      (string-append "shift-" (string (char-downcase chr)))
      (or (assoc-ref keystrokes chr)
          (string chr))))

(define* (string->keystroke-commands str
                                     #:optional
                                     (keystrokes
                                      %qwerty-us-keystrokes))
  "Return a list of QEMU monitor commands to send the keystrokes corresponding
to STR.  KEYSTROKES is an alist specifying a mapping from characters to
keystrokes."
  (string-fold-right (lambda (chr result)
                       (cons (string-append
                              "sendkey "
                              (character->keystroke chr keystrokes))
                             result))
                     '()
                     str))

(define* (marionette-type str marionette
                          #:key (keystrokes %qwerty-us-keystrokes))
  "Type STR on MARIONETTE's keyboard, using the KEYSTROKES alist to map characters
to actual keystrokes."
  (for-each (cut marionette-control <> marionette)
            (string->keystroke-commands str keystrokes)))


;;;
;;; Test helper.
;;;

(define* (system-test-runner #:optional log-directory)
  "Return a SRFI-64 test runner that calls 'exit' upon 'test-end'.  When
LOG-DIRECTORY is specified, create log file within it."
  (let ((runner  (test-runner-simple)))
    ;; Log to a file under LOG-DIRECTORY.
    (test-runner-on-group-begin! runner
      (let ((on-begin (test-runner-on-group-begin runner)))
        (lambda (runner suite-name count)
          (when log-directory
            (catch 'system-error
              (lambda ()
                (mkdir log-directory))
              (lambda args
                (unless (= (system-error-errno args) EEXIST)
                  (apply throw args))))
            (set! test-log-to-file
                  (string-append log-directory "/" suite-name ".log")))
          (on-begin runner suite-name count))))

    ;; The default behavior on 'test-end' is to only write a line if the test
    ;; failed.  Arrange to also write a line on success.
    (test-runner-on-test-end! runner
      (let ((on-end (test-runner-on-test-end runner)))
        (lambda (runner)
          (let* ((kind      (test-result-ref runner 'result-kind))
                 (results   (test-result-alist runner))
                 (test-name (assq-ref results 'test-name)))
            (unless (memq kind '(fail xpass))
              (format (current-output-port) "~a: ~a~%"
                      (string-upcase (symbol->string kind))
                      test-name)))

          (on-end runner))))

    ;; On 'test-end', display test results and exit with zero if and only if
    ;; there were no test failures.
    (test-runner-on-final! runner
      (lambda (runner)
        (let ((success? (= (test-runner-fail-count runner) 0)))
          (test-on-final-simple runner)

          (when (not success?)
            (let* ((log-port (test-runner-aux-value runner))
                   (log-file (port-filename log-port)))
              (format (current-error-port)
                      "\nTests failed, dumping log file '~a'.\n\n"
                      log-file)

              ;; At this point LOG-PORT is not closed yet; flush it.
              (force-output log-port)

              ;; Brute force to avoid dependency on (guix build utils) for
              ;; 'dump-port'.
              (let ((content (call-with-input-file log-file
                               get-bytevector-all)))
                (put-bytevector (current-error-port) content))))

          (exit success?))))
    runner))

(define* (qemu-command #:optional (system %host-type))
  "Return the default name of the QEMU command for SYSTEM."
  (let ((cpu (substring system 0
                        (string-index system #\-))))
    (string-append "qemu-system-"
                   (cond
                    ((string-match "^i[3456]86$" cpu) "i386")
                    ((string-match "armhf" cpu) "arm")
                    (else cpu)))))

;;; marionette.scm ends here
(nginx-upstream-configuration-servers upstream)) " }\n")) (define (flatten . lst) "Return a list that recursively concatenates all sub-lists of LST." (define (flatten1 head out) (if (list? head) (fold-right flatten1 out head) (cons head out))) (fold-right flatten1 '() lst)) (define (default-nginx-config config) (match-record config (nginx log-directory run-directory server-blocks upstream-blocks server-names-hash-bucket-size server-names-hash-bucket-max-size modules global-directives lua-package-path lua-package-cpath extra-content) (apply mixed-text-file "nginx.conf" (flatten "user nginx nginx;\n" "pid " run-directory "/pid;\n" "error_log " log-directory "/error.log info;\n" (map emit-load-module modules) (map emit-global-directive global-directives) "http {\n" " client_body_temp_path " run-directory "/client_body_temp;\n" " proxy_temp_path " run-directory "/proxy_temp;\n" " fastcgi_temp_path " run-directory "/fastcgi_temp;\n" " uwsgi_temp_path " run-directory "/uwsgi_temp;\n" " scgi_temp_path " run-directory "/scgi_temp;\n" " access_log " log-directory "/access.log;\n" " include " nginx "/share/nginx/conf/mime.types;\n" (if lua-package-path #~(format #f " lua_package_path ~s;~%" (string-join (map (lambda (path) (string-append path "/lib/?.lua")) '#$lua-package-path) ";")) "") (if lua-package-cpath #~(format #f " lua_package_cpath ~s;~%" (string-join (map (lambda (cpath) (string-append cpath "/lib/lua/?.lua")) '#$lua-package-cpath) ";")) "") (if server-names-hash-bucket-size (string-append " server_names_hash_bucket_size " (number->string server-names-hash-bucket-size) ";\n") "") (if server-names-hash-bucket-max-size (string-append " server_names_hash_bucket_max_size " (number->string server-names-hash-bucket-max-size) ";\n") "") "\n" (map emit-nginx-upstream-config upstream-blocks) (map emit-nginx-server-config server-blocks) extra-content "\n}\n")))) (define %nginx-accounts (list (user-group (name "nginx") (system? #t)) (user-account (name "nginx") (group "nginx") (system? #t) (comment "nginx server user") (home-directory "/var/empty") (shell (file-append shadow "/sbin/nologin"))))) (define (nginx-activation config) (match-record config (nginx log-directory run-directory file) #~(begin (use-modules (guix build utils)) (format #t "creating nginx log directory '~a'~%" #$log-directory) (mkdir-p #$log-directory) (format #t "creating nginx run directory '~a'~%" #$run-directory) (mkdir-p #$run-directory) (format #t "creating nginx temp directories '~a/{client_body,proxy,fastcgi,uwsgi,scgi}_temp'~%" #$run-directory) (mkdir-p (string-append #$run-directory "/client_body_temp")) (mkdir-p (string-append #$run-directory "/proxy_temp")) (mkdir-p (string-append #$run-directory "/fastcgi_temp")) (mkdir-p (string-append #$run-directory "/uwsgi_temp")) (mkdir-p (string-append #$run-directory "/scgi_temp")) ;; Start-up logs. Once configuration is loaded, nginx switches to ;; log-directory. (mkdir-p (string-append #$run-directory "/logs")) ;; Check configuration file syntax. (system* (string-append #$nginx "/sbin/nginx") "-c" #$(or file (default-nginx-config config)) "-p" #$run-directory "-t")))) (define (nginx-shepherd-service config) (match-record config (nginx file run-directory) (let* ((nginx-binary (file-append nginx "/sbin/nginx")) (pid-file (in-vicinity run-directory "pid")) (nginx-action (lambda args #~(lambda _ (invoke #$nginx-binary "-c" #$(or file (default-nginx-config config)) #$@args) (match '#$args (("-s" . _) #f) (_ ;; When FILE is true, we cannot be sure that PID-FILE will ;; be created, so assume it won't show up. When FILE is ;; false, read PID-FILE. #$(if file #~#t #~(read-pid-file #$pid-file)))))))) ;; TODO: Add 'reload' action. (list (shepherd-service (provision '(nginx)) (documentation "Run the nginx daemon.") (requirement '(user-processes loopback)) (modules `((ice-9 match) ,@%default-modules)) (start (nginx-action "-p" run-directory)) (stop (nginx-action "-s" "stop"))))))) (define nginx-service-type (service-type (name 'nginx) (extensions (list (service-extension shepherd-root-service-type nginx-shepherd-service) (service-extension activation-service-type nginx-activation) (service-extension account-service-type (const %nginx-accounts)))) (compose concatenate) (extend (lambda (config servers) (nginx-configuration (inherit config) (server-blocks (append (nginx-configuration-server-blocks config) servers))))) (default-value (nginx-configuration)) (description "Run the nginx Web server."))) (define-record-type* fcgiwrap-configuration make-fcgiwrap-configuration fcgiwrap-configuration? (package fcgiwrap-configuration-package ; (default fcgiwrap)) (socket fcgiwrap-configuration-socket (default "tcp:127.0.0.1:9000")) (user fcgiwrap-configuration-user (default "fcgiwrap")) (group fcgiwrap-configuration-group (default "fcgiwrap"))) (define fcgiwrap-accounts (match-lambda (($ package socket user group) (filter identity (list (and (equal? group "fcgiwrap") (user-group (name "fcgiwrap") (system? #t))) (and (equal? user "fcgiwrap") (user-account (name "fcgiwrap") (group group) (system? #t) (comment "Fcgiwrap Daemon") (home-directory "/var/empty") (shell (file-append shadow "/sbin/nologin"))))))))) (define fcgiwrap-shepherd-service (match-lambda (($ package socket user group) (list (shepherd-service (provision '(fcgiwrap)) (documentation "Run the fcgiwrap daemon.") (requirement '(networking)) (start #~(make-forkexec-constructor '(#$(file-append package "/sbin/fcgiwrap") "-s" #$socket) #:user #$user #:group #$group #:log-file "/var/log/fcgiwrap.log")) (stop #~(make-kill-destructor))))))) (define fcgiwrap-activation (match-lambda (($ package socket user group) #~(begin ;; When listening on a unix socket, create a parent directory for the ;; socket with the correct permissions. (when (string-prefix? "unix:" #$socket) (let ((run-directory (dirname (substring #$socket (string-length "unix:"))))) (mkdir-p run-directory) (chown run-directory (passwd:uid (getpw #$user)) (group:gid (getgr #$group))))))))) (define fcgiwrap-service-type (service-type (name 'fcgiwrap) (extensions (list (service-extension shepherd-root-service-type fcgiwrap-shepherd-service) (service-extension account-service-type fcgiwrap-accounts) (service-extension activation-service-type fcgiwrap-activation))) (default-value (fcgiwrap-configuration)))) (define-record-type* php-fpm-configuration make-php-fpm-configuration php-fpm-configuration? (php php-fpm-configuration-php ; (default php)) (socket php-fpm-configuration-socket (default (string-append "/var/run/php" (version-major (package-version php)) "-fpm.sock"))) (user php-fpm-configuration-user (default "php-fpm")) (group php-fpm-configuration-group (default "php-fpm")) (socket-user php-fpm-configuration-socket-user (default "php-fpm")) (socket-group php-fpm-configuration-socket-group (default "nginx")) (pid-file php-fpm-configuration-pid-file (default (string-append "/var/run/php" (version-major (package-version php)) "-fpm.pid"))) (log-file php-fpm-configuration-log-file (default (string-append "/var/log/php" (version-major (package-version php)) "-fpm.log"))) (process-manager php-fpm-configuration-process-manager (default (php-fpm-dynamic-process-manager-configuration))) (display-errors php-fpm-configuration-display-errors (default #f)) (timezone php-fpm-configuration-timezone (default #f)) (workers-log-file php-fpm-configuration-workers-log-file (default (string-append "/var/log/php" (version-major (package-version php)) "-fpm.www.log"))) (file php-fpm-configuration-file ;#f | file-like (default #f)) (php-ini-file php-fpm-configuration-php-ini-file ;#f | file-like (default #f))) (define-record-type* php-fpm-dynamic-process-manager-configuration make-php-fpm-dynamic-process-manager-configuration php-fpm-dynamic-process-manager-configuration? (max-children php-fpm-dynamic-process-manager-configuration-max-children (default 5)) (start-servers php-fpm-dynamic-process-manager-configuration-start-servers (default 2)) (min-spare-servers php-fpm-dynamic-process-manager-configuration-min-spare-servers (default 1)) (max-spare-servers php-fpm-dynamic-process-manager-configuration-max-spare-servers (default 3))) (define-record-type* php-fpm-static-process-manager-configuration make-php-fpm-static-process-manager-configuration php-fpm-static-process-manager-configuration? (max-children php-fpm-static-process-manager-configuration-max-children (default 5))) (define-record-type* php-fpm-on-demand-process-manager-configuration make-php-fpm-on-demand-process-manager-configuration php-fpm-on-demand-process-manager-configuration? (max-children php-fpm-on-demand-process-manager-configuration-max-children (default 5)) (process-idle-timeout php-fpm-on-demand-process-manager-configuration-process-idle-timeout (default 10))) (define php-fpm-accounts (match-lambda (($ php socket user group socket-user socket-group _ _ _ _ _ _) `(,@(if (equal? group "php-fpm") '() (list (user-group (name "php-fpm") (system? #t)))) ,(user-group (name group) (system? #t)) ,(user-account (name user) (group group) (supplementary-groups '("php-fpm")) (system? #t) (comment "php-fpm daemon user") (home-directory "/var/empty") (shell (file-append shadow "/sbin/nologin"))))))) (define (default-php-fpm-config socket user group socket-user socket-group pid-file log-file pm display-errors timezone workers-log-file) (apply mixed-text-file "php-fpm.conf" (flatten "[global]\n" "pid =" pid-file "\n" "error_log =" log-file "\n" "[www]\n" "user =" user "\n" "group =" group "\n" "listen =" socket "\n" "listen.owner =" socket-user "\n" "listen.group =" socket-group "\n" (if timezone (string-append "php_admin_value[date.timezone] = \"" timezone "\"\n") "") (match pm (($ pm.max-children pm.start-servers pm.min-spare-servers pm.max-spare-servers) (list "pm = dynamic\n" "pm.max_children =" (number->string pm.max-children) "\n" "pm.start_servers =" (number->string pm.start-servers) "\n" "pm.min_spare_servers =" (number->string pm.min-spare-servers) "\n" "pm.max_spare_servers =" (number->string pm.max-spare-servers) "\n")) (($ pm.max-children) (list "pm = static\n" "pm.max_children =" (number->string pm.max-children) "\n")) (($ pm.max-children pm.process-idle-timeout) (list "pm = ondemand\n" "pm.max_children =" (number->string pm.max-children) "\n" "pm.process_idle_timeout =" (number->string pm.process-idle-timeout) "s\n"))) "php_flag[display_errors] = " (if display-errors "on" "off") "\n" (if workers-log-file (list "catch_workers_output = yes\n" "php_admin_value[error_log] =" workers-log-file "\n" "php_admin_flag[log_errors] = on\n") (list "catch_workers_output = no\n"))))) (define php-fpm-shepherd-service (match-lambda (($ php socket user group socket-user socket-group pid-file log-file pm display-errors timezone workers-log-file file php-ini-file) (list (shepherd-service (provision '(php-fpm)) (documentation "Run the php-fpm daemon.") (requirement '(networking)) (start #~(make-forkexec-constructor '(#$(file-append php "/sbin/php-fpm") "--fpm-config" #$(or file (default-php-fpm-config socket user group socket-user socket-group pid-file log-file pm display-errors timezone workers-log-file)) #$@(if php-ini-file `("-c" ,php-ini-file) '())) #:pid-file #$pid-file)) (stop #~(make-kill-destructor))))))) (define (php-fpm-activation config) #~(begin (use-modules (guix build utils)) (let* ((user (getpwnam #$(php-fpm-configuration-user config))) (touch (lambda (file-name) (call-with-output-file file-name (const #t)))) (workers-log-file #$(php-fpm-configuration-workers-log-file config)) (init-log-file (lambda (file-name) (when workers-log-file (when (not (file-exists? file-name)) (touch file-name)) (chown file-name (passwd:uid user) (passwd:gid user)) (chmod file-name #o660))))) (init-log-file #$(php-fpm-configuration-log-file config)) (init-log-file workers-log-file)))) (define php-fpm-service-type (service-type (name 'php-fpm) (description "Run @command{php-fpm} to provide a fastcgi socket for calling php through a webserver.") (extensions (list (service-extension shepherd-root-service-type php-fpm-shepherd-service) (service-extension activation-service-type php-fpm-activation) (service-extension account-service-type php-fpm-accounts))) (default-value (php-fpm-configuration)))) (define* (nginx-php-location #:key (nginx-package nginx) (socket (string-append "/var/run/php" (version-major (package-version php)) "-fpm.sock"))) "Return a nginx-location-configuration that makes nginx run .php files." (nginx-location-configuration (uri "~ \\.php$") (body (list "fastcgi_split_path_info ^(.+\\.php)(/.+)$;" (string-append "fastcgi_pass unix:" socket ";") "fastcgi_index index.php;" (list "include " nginx-package "/share/nginx/conf/fastcgi.conf;"))))) (define* (cat-avatar-generator-service #:key (cache-dir "/var/cache/cat-avatar-generator") (package cat-avatar-generator) (configuration (nginx-server-configuration))) (simple-service 'cat-http-server nginx-service-type (list (nginx-server-configuration (inherit configuration) (locations (cons (let ((base (nginx-php-location))) (nginx-location-configuration (inherit base) (body (list (string-append "fastcgi_param CACHE_DIR \"" cache-dir "\";") (nginx-location-configuration-body base))))) (nginx-server-configuration-locations configuration))) (root #~(string-append #$package "/share/web/cat-avatar-generator")))))) (define-record-type* hpcguix-web-configuration make-hpcguix-web-configuration hpcguix-web-configuration? (package hpcguix-web-package (default hpcguix-web)) ; ;; Specs is gexp of hpcguix-web configuration file (specs hpcguix-web-configuration-specs)) (define %hpcguix-web-accounts (list (user-group (name "hpcguix-web") (system? #t)) (user-account (name "hpcguix-web") (group "hpcguix-web") (system? #t) (comment "hpcguix-web") (home-directory "/var/empty") (shell (file-append shadow "/sbin/nologin"))))) (define %hpcguix-web-activation (with-imported-modules '((guix build utils)) #~(begin (use-modules (guix build utils) (ice-9 ftw)) (let ((home-dir "/var/cache/guix/web") (user (getpwnam "hpcguix-web"))) (mkdir-p home-dir) (chown home-dir (passwd:uid user) (passwd:gid user)) (chmod home-dir #o755) ;; Remove stale 'packages.json.lock' file (and other lock files, if ;; any) since that would prevent 'packages.json' from being updated. (for-each (lambda (lock) (delete-file (string-append home-dir "/" lock))) (scandir home-dir (lambda (file) (string-suffix? ".lock" file)))))))) (define %hpcguix-web-log-file "/var/log/hpcguix-web.log") (define %hpcguix-web-log-rotations (list (log-rotation (files (list %hpcguix-web-log-file)) (frequency 'weekly)))) (define (hpcguix-web-shepherd-service config) (let ((specs (hpcguix-web-configuration-specs config)) (hpcguix-web (hpcguix-web-package config))) (with-imported-modules (source-module-closure '((gnu build shepherd))) (shepherd-service (documentation "hpcguix-web daemon") (provision '(hpcguix-web)) (requirement '(networking)) (start #~(make-forkexec-constructor (list #$(file-append hpcguix-web "/bin/run") (string-append "--config=" #$(scheme-file "hpcguix-web.scm" specs))) #:user "hpcguix-web" #:group "hpcguix-web" #:environment-variables (list "XDG_CACHE_HOME=/var/cache/guix/web" "SSL_CERT_DIR=/etc/ssl/certs") #:log-file #$%hpcguix-web-log-file)) (stop #~(make-kill-destructor)))))) (define hpcguix-web-service-type (service-type (name 'hpcguix-web) (description "Run the hpcguix-web server.") (extensions (list (service-extension account-service-type (const %hpcguix-web-accounts)) (service-extension activation-service-type (const %hpcguix-web-activation)) (service-extension rottlog-service-type (const %hpcguix-web-log-rotations)) (service-extension shepherd-root-service-type (compose list hpcguix-web-shepherd-service)))))) ;;; ;;; Tailon ;;; (define-record-type* tailon-configuration-file make-tailon-configuration-file tailon-configuration-file? (files tailon-configuration-file-files (default '("/var/log"))) (bind tailon-configuration-file-bind (default "localhost:8080")) (relative-root tailon-configuration-file-relative-root (default #f)) (allow-transfers? tailon-configuration-file-allow-transfers? (default #t)) (follow-names? tailon-configuration-file-follow-names? (default #t)) (tail-lines tailon-configuration-file-tail-lines (default 200)) (allowed-commands tailon-configuration-file-allowed-commands (default '("tail" "grep" "awk"))) (debug? tailon-configuration-file-debug? (default #f)) (wrap-lines tailon-configuration-file-wrap-lines (default #t)) (http-auth tailon-configuration-file-http-auth (default #f)) (users tailon-configuration-file-users (default #f))) (define (tailon-configuration-files-string files) (string-append "\n" (string-join (map (lambda (x) (string-append " - " (cond ((string? x) (simple-format #f "'~A'" x)) ((list? x) (string-join (cons (simple-format #f "'~A':" (car x)) (map (lambda (x) (simple-format #f " - '~A'" x)) (cdr x))) "\n")) (else (error x))))) files) "\n"))) (define-gexp-compiler (tailon-configuration-file-compiler (file ) system target) (match file (($ files bind relative-root allow-transfers? follow-names? tail-lines allowed-commands debug? wrap-lines http-auth users) (text-file "tailon-config.yaml" (string-concatenate (filter-map (match-lambda ((key . #f) #f) ((key . value) (string-append key ": " value "\n"))) `(("files" . ,(tailon-configuration-files-string files)) ("bind" . ,bind) ("relative-root" . ,relative-root) ("allow-transfers" . ,(if allow-transfers? "true" "false")) ("follow-names" . ,(if follow-names? "true" "false")) ("tail-lines" . ,(number->string tail-lines)) ("commands" . ,(string-append "[" (string-join allowed-commands ", ") "]")) ("debug" . ,(if debug? "true" #f)) ("wrap-lines" . ,(if wrap-lines "true" "false")) ("http-auth" . ,http-auth) ("users" . ,(if users (string-concatenate (cons "\n" (map (match-lambda ((user . pass) (string-append " " user ":" pass))) users))) #f))))))))) (define-record-type* tailon-configuration make-tailon-configuration tailon-configuration? (config-file tailon-configuration-config-file (default (tailon-configuration-file))) (package tailon-configuration-package (default tailon))) (define tailon-shepherd-service (match-lambda (($ config-file package) (list (shepherd-service (provision '(tailon)) (documentation "Run the tailon daemon.") (start #~(make-forkexec-constructor `(,(string-append #$package "/bin/tailon") "-c" ,#$config-file) #:user "tailon" #:group "tailon")) (stop #~(make-kill-destructor))))))) (define %tailon-accounts (list (user-group (name "tailon") (system? #t)) (user-account (name "tailon") (group "tailon") (system? #t) (comment "tailon") (home-directory "/var/empty") (shell (file-append shadow "/sbin/nologin"))))) (define tailon-service-type (service-type (name 'tailon) (description "Run Tailon, a Web application for monitoring, viewing, and searching log files.") (extensions (list (service-extension shepherd-root-service-type tailon-shepherd-service) (service-extension account-service-type (const %tailon-accounts)))) (compose concatenate) (extend (lambda (parameter files) (tailon-configuration (inherit parameter) (config-file (let ((old-config-file (tailon-configuration-config-file parameter))) (tailon-configuration-file (inherit old-config-file) (files (append (tailon-configuration-file-files old-config-file) files)))))))) (default-value (tailon-configuration)))) ;;; ;;; Varnish ;;; (define-record-type* varnish-configuration make-varnish-configuration varnish-configuration? (package varnish-configuration-package ; (default varnish)) (name varnish-configuration-name ;string (default "default")) (backend varnish-configuration-backend ;string (default "localhost:8080")) (vcl varnish-configuration-vcl ;#f | (default #f)) (listen varnish-configuration-listen ;list of strings (default '("localhost:80"))) (storage varnish-configuration-storage ;list of strings (default '("malloc,128m"))) (parameters varnish-configuration-parameters ;list of string pairs (default '())) (extra-options varnish-configuration-extra-options ;list of strings (default '()))) (define %varnish-accounts (list (user-group (name "varnish") (system? #t)) (user-account (name "varnish") (group "varnish") (system? #t) (comment "Varnish Cache User") (home-directory "/var/varnish") (shell (file-append shadow "/sbin/nologin"))))) (define varnish-shepherd-service (match-lambda (($ package name backend vcl listen storage parameters extra-options) (list (shepherd-service (provision (list (symbol-append 'varnish- (string->symbol name)))) (documentation (string-append "The Varnish Web Accelerator" " (" name ")")) (requirement '(networking)) (start #~(make-forkexec-constructor (list #$(file-append package "/sbin/varnishd") "-n" #$name #$@(if vcl #~("-f" #$vcl) #~("-b" #$backend)) #$@(append-map (lambda (a) (list "-a" a)) listen) #$@(append-map (lambda (s) (list "-s" s)) storage) #$@(append-map (lambda (p) (list "-p" (format #f "~a=~a" (car p) (cdr p)))) parameters) #$@extra-options) ;; Varnish will drop privileges to the "varnish" user when ;; it exists. Not passing #:user here allows the service ;; to bind to ports < 1024. #:pid-file (if (string-prefix? "/" #$name) (string-append #$name "/_.pid") (string-append "/var/varnish/" #$name "/_.pid")))) (stop #~(make-kill-destructor))))))) (define varnish-service-type (service-type (name 'varnish) (description "Run the Varnish cache server.") (extensions (list (service-extension account-service-type (const %varnish-accounts)) (service-extension shepherd-root-service-type varnish-shepherd-service))) (default-value (varnish-configuration)))) ;;; ;;; Patchwork ;;; (define-record-type* patchwork-database-configuration make-patchwork-database-configuration patchwork-database-configuration? (engine patchwork-database-configuration-engine (default "django.db.backends.postgresql_psycopg2")) (name patchwork-database-configuration-name (default "patchwork")) (user patchwork-database-configuration-user (default "httpd")) (password patchwork-database-configuration-password (default "")) (host patchwork-database-configuration-host (default "")) (port patchwork-database-configuration-port (default ""))) (define-record-type* patchwork-settings-module make-patchwork-settings-module patchwork-settings-module? (database-configuration patchwork-settings-module-database-configuration (default (patchwork-database-configuration))) (secret-key-file patchwork-settings-module-secret-key-file (default "/etc/patchwork/django-secret-key")) (allowed-hosts patchwork-settings-module-allowed-hosts) (default-from-email patchwork-settings-module-default-from-email) (static-url patchwork-settings-module-static-url (default "/static/")) (admins patchwork-settings-module-admins (default '())) (debug? patchwork-settings-module-debug? (default #f)) (enable-rest-api? patchwork-settings-module-enable-rest-api? (default #t)) (enable-xmlrpc? patchwork-settings-module-enable-xmlrpc? (default #t)) (force-https-links? patchwork-settings-module-force-https-links? (default #t)) (extra-settings patchwork-settings-module-extra-settings (default ""))) (define-record-type* patchwork-configuration make-patchwork-configuration patchwork-configuration? (patchwork patchwork-configuration-patchwork (default patchwork)) (domain patchwork-configuration-domain) (settings-module patchwork-configuration-settings-module) (static-path patchwork-configuration-static-url (default "/static/")) (getmail-retriever-config getmail-retriever-config)) ;; Django uses a Python module for configuration, so this compiler generates a ;; Python module from the configuration record. (define-gexp-compiler (patchwork-settings-module-compiler (file ) system target) (match file (($ database-configuration secret-key-file allowed-hosts default-from-email static-url admins debug? enable-rest-api? enable-xmlrpc? force-https-links? extra-configuration) (gexp->derivation "patchwork-settings" (with-imported-modules '((guix build utils)) #~(let ((output #$output)) (define (create-__init__.py filename) (call-with-output-file filename (lambda (port) (display "" port)))) (use-modules (guix build utils) (srfi srfi-1)) (mkdir-p (string-append output "/guix/patchwork")) (create-__init__.py (string-append output "/guix/__init__.py")) (create-__init__.py (string-append output "/guix/patchwork/__init__.py")) (call-with-output-file (string-append output "/guix/patchwork/settings.py") (lambda (port) (display (string-append "from patchwork.settings.base import * # Configuration from Guix with open('" #$secret-key-file "') as f: SECRET_KEY = f.read().strip() ALLOWED_HOSTS = [ " #$(string-concatenate (map (lambda (allowed-host) (string-append " '" allowed-host "'\n")) allowed-hosts)) "] DEFAULT_FROM_EMAIL = '" #$default-from-email "' SERVER_EMAIL = DEFAULT_FROM_EMAIL NOTIFICATION_FROM_EMAIL = DEFAULT_FROM_EMAIL ADMINS = [ " #$(string-concatenate (map (match-lambda ((name email-address) (string-append "('" name "','" email-address "'),"))) admins)) "] DEBUG = " #$(if debug? "True" "False") " ENABLE_REST_API = " #$(if enable-rest-api? "True" "False") " ENABLE_XMLRPC = " #$(if enable-xmlrpc? "True" "False") " FORCE_HTTPS_LINKS = " #$(if force-https-links? "True" "False") " DATABASES = { 'default': { " #$(match database-configuration (($ engine name user password host port) (string-append " 'ENGINE': '" engine "',\n" " 'NAME': '" name "',\n" " 'USER': '" user "',\n" " 'PASSWORD': '" password "',\n" " 'HOST': '" host "',\n" " 'PORT': '" port "',\n"))) " }, } " #$(if debug? #~(string-append "STATIC_ROOT = '" #$(file-append patchwork "/share/patchwork/htdocs") "'") #~(string-append "STATIC_URL = '" #$static-url "'")) " STATICFILES_STORAGE = ( 'django.contrib.staticfiles.storage.StaticFilesStorage' ) # Guix Extra Configuration " #$extra-configuration " ") port))) #t)) #:local-build? #t)))) (define patchwork-virtualhost (match-lambda (($ patchwork domain settings-module static-path getmail-retriever-config) (define wsgi.py (file-append patchwork (string-append "/lib/python" (version-major+minor (package-version python)) "/site-packages/patchwork/wsgi.py"))) (httpd-virtualhost "*:8080" `("ServerAdmin admin@example.com` ServerName " ,domain " LogFormat \"%v %h %l %u %t \\\"%r\\\" %>s %b \\\"%{Referer}i\\\" \\\"%{User-Agent}i\\\"\" customformat LogLevel info CustomLog \"/var/log/httpd/" ,domain "-access_log\" customformat ErrorLog /var/log/httpd/error.log WSGIScriptAlias / " ,wsgi.py " WSGIDaemonProcess " ,(package-name patchwork) " user=httpd group=httpd processes=1 threads=2 display-name=%{GROUP} lang='en_US.UTF-8' locale='en_US.UTF-8' python-path=" ,settings-module " WSGIProcessGroup " ,(package-name patchwork) " WSGIPassAuthorization On Require all granted " ,@(if static-path `("Alias " ,static-path " " ,patchwork "/share/patchwork/htdocs/") '()) " AllowOverride None Options MultiViews Indexes SymlinksIfOwnerMatch IncludesNoExec Require method GET POST OPTIONS "))))) (define (patchwork-httpd-configuration patchwork-configuration) (list "WSGISocketPrefix /var/run/mod_wsgi" (list "LoadModule wsgi_module " (file-append mod-wsgi "/modules/mod_wsgi.so")) (patchwork-virtualhost patchwork-configuration))) (define (patchwork-django-admin-gexp patchwork settings-module) #~(lambda command (let ((pid (primitive-fork)) (user (getpwnam "httpd"))) (if (eq? pid 0) (dynamic-wind (const #t) (lambda () (setgid (passwd:gid user)) (setuid (passwd:uid user)) (setenv "DJANGO_SETTINGS_MODULE" "guix.patchwork.settings") (setenv "PYTHONPATH" #$settings-module) (primitive-exit (if (zero? (apply system* #$(file-append patchwork "/bin/patchwork-admin") command)) 0 1))) (lambda () (primitive-exit 1))) (zero? (cdr (waitpid pid))))))) (define (patchwork-django-admin-action patchwork settings-module) (shepherd-action (name 'django-admin) (documentation "Run a django admin command for patchwork") (procedure (patchwork-django-admin-gexp patchwork settings-module)))) (define patchwork-shepherd-services (match-lambda (($ patchwork domain settings-module static-path getmail-retriever-config) (define secret-key-file-creation-gexp (if (patchwork-settings-module? settings-module) (with-extensions (list guile-gcrypt) #~(let ((secret-key-file #$(patchwork-settings-module-secret-key-file settings-module))) (use-modules (guix build utils) (gcrypt random)) (unless (file-exists? secret-key-file) (mkdir-p (dirname secret-key-file)) (call-with-output-file secret-key-file (lambda (port) (display (random-token 30 'very-strong) port))) (let* ((pw (getpwnam "httpd")) (uid (passwd:uid pw)) (gid (passwd:gid pw))) (chown secret-key-file uid gid) (chmod secret-key-file #o400))))) #~())) (list (shepherd-service (requirement '(postgres)) (provision (list (string->symbol (string-append (package-name patchwork) "-setup")))) (start #~(lambda () (define run-django-admin-command #$(patchwork-django-admin-gexp patchwork settings-module)) #$secret-key-file-creation-gexp (run-django-admin-command "migrate"))) (stop #~(const #f)) (actions (list (patchwork-django-admin-action patchwork settings-module))) (respawn? #f) (documentation "Setup Patchwork.")))))) (define patchwork-getmail-configs (match-lambda (($ patchwork domain settings-module static-path getmail-retriever-config) (list (getmail-configuration (name (string->symbol (package-name patchwork))) (user "httpd") (directory (string-append "/var/lib/getmail/" (package-name patchwork))) (rcfile (getmail-configuration-file (retriever getmail-retriever-config) (destination (getmail-destination-configuration (type "MDA_external") (path (file-append patchwork "/bin/patchwork-admin")) (extra-parameters '((arguments . ("parsemail")))))) (options (getmail-options-configuration (read-all #f) (delivered-to #f) (received #f))))) (idle (assq-ref (getmail-retriever-configuration-extra-parameters getmail-retriever-config) 'mailboxes)) (environment-variables (list "DJANGO_SETTINGS_MODULE=guix.patchwork.settings" #~(string-append "PYTHONPATH=" #$settings-module)))))))) (define patchwork-service-type (service-type (name 'patchwork-setup) (extensions (list (service-extension httpd-service-type patchwork-httpd-configuration) (service-extension shepherd-root-service-type patchwork-shepherd-services) (service-extension getmail-service-type patchwork-getmail-configs))) (description "Patchwork patch tracking system."))) ;;; ;;; Mumi. ;;; (define-record-type* mumi-configuration make-mumi-configuration mumi-configuration? (mumi mumi-configuration-mumi (default mumi)) (mailer? mumi-configuration-mailer? (default #t)) (sender mumi-configuration-sender (default #f)) (smtp mumi-configuration-smtp (default #f))) (define %mumi-activation (with-imported-modules '((guix build utils)) #~(begin (use-modules (guix build utils)) (mkdir-p "/var/mumi/db") (mkdir-p "/var/mumi/mails") (let* ((pw (getpwnam "mumi")) (uid (passwd:uid pw)) (gid (passwd:gid pw))) (chown "/var/mumi" uid gid) (chown "/var/mumi/mails" uid gid) (chown "/var/mumi/db" uid gid))))) (define %mumi-accounts (list (user-group (name "mumi") (system? #t)) (user-account (name "mumi") (group "mumi") (system? #t) (comment "Mumi web server") (home-directory "/var/empty") (shell (file-append shadow "/sbin/nologin"))))) (define (mumi-shepherd-services config) (define environment #~(list "LC_ALL=en_US.utf8" (string-append "GUIX_LOCPATH=" #$glibc-utf8-locales "/lib/locale"))) (match config (($ mumi mailer? sender smtp) (list (shepherd-service (provision '(mumi)) (documentation "Mumi bug-tracking web interface.") (requirement '(networking)) (start #~(make-forkexec-constructor `(#$(file-append mumi "/bin/mumi") "web" ,@(if #$mailer? '() '("--disable-mailer"))) #:environment-variables #$environment #:user "mumi" #:group "mumi" #:log-file "/var/log/mumi.log")) (stop #~(make-kill-destructor))) (shepherd-service (provision '(mumi-worker)) (documentation "Mumi bug-tracking web interface database worker.") (requirement '(networking)) (start #~(make-forkexec-constructor '(#$(file-append mumi "/bin/mumi") "worker") #:environment-variables #$environment #:user "mumi" #:group "mumi" #:log-file "/var/log/mumi.worker.log")) (stop #~(make-kill-destructor))) (shepherd-service (provision '(mumi-mailer)) (documentation "Mumi bug-tracking web interface mailer.") (requirement '(networking)) (start #~(make-forkexec-constructor `(#$(file-append mumi "/bin/mumi") "mailer" ,@(if #$sender (list (string-append "--sender=" #$sender)) '()) ,@(if #$smtp (list (string-append "--smtp=" #$smtp)) '())) #:environment-variables #$environment #:user "mumi" #:group "mumi" #:log-file "/var/log/mumi.mailer.log")) (stop #~(make-kill-destructor))))))) (define mumi-service-type (service-type (name 'mumi) (extensions (list (service-extension activation-service-type (const %mumi-activation)) (service-extension account-service-type (const %mumi-accounts)) (service-extension shepherd-root-service-type mumi-shepherd-services))) (description "Run Mumi, a Web interface to the Debbugs bug-tracking server.") (default-value (mumi-configuration)))) (define %default-gmnisrv-config-file (plain-file "gmnisrv.ini" " listen=0.0.0.0:1965 [::]:1965 [:tls] store=/var/lib/gemini/certs organization=gmnisrv on Guix user [localhost] root=/srv/gemini ")) (define-record-type* gmnisrv-configuration make-gmnisrv-configuration gmnisrv-configuration? (package gmnisrv-configuration-package (default gmnisrv)) (config-file gmnisrv-configuration-config-file (default %default-gmnisrv-config-file))) (define gmnisrv-shepherd-service (match-lambda (($ package config-file) (list (shepherd-service (provision '(gmnisrv)) (requirement '(networking)) (documentation "Run the gmnisrv Gemini server.") (start (let ((gmnisrv (file-append package "/bin/gmnisrv"))) #~(make-forkexec-constructor (list #$gmnisrv "-C" #$config-file) #:user "gmnisrv" #:group "gmnisrv" #:log-file "/var/log/gmnisrv.log"))) (stop #~(make-kill-destructor))))))) (define %gmnisrv-accounts (list (user-group (name "gmnisrv") (system? #t)) (user-account (name "gmnisrv") (group "gmnisrv") (system? #t) (comment "gmnisrv Gemini server") (home-directory "/var/empty") (shell (file-append shadow "/sbin/nologin"))))) (define %gmnisrv-activation (with-imported-modules '((guix build utils)) #~(begin (use-modules (guix build utils)) (mkdir-p "/var/lib/gemini/certs") (let* ((pw (getpwnam "gmnisrv")) (uid (passwd:uid pw)) (gid (passwd:gid pw))) (chown "/var/lib/gemini" uid gid) (chown "/var/lib/gemini/certs" uid gid))))) (define gmnisrv-service-type (service-type (name 'guix) (extensions (list (service-extension activation-service-type (const %gmnisrv-activation)) (service-extension account-service-type (const %gmnisrv-accounts)) (service-extension shepherd-root-service-type gmnisrv-shepherd-service))) (description "Run the gmnisrv Gemini server.") (default-value (gmnisrv-configuration)))) (define-record-type* agate-configuration make-agate-configuration agate-configuration? (package agate-configuration-package (default agate)) (content agate-configuration-content (default "/srv/gemini")) (cert agate-configuration-cert (default #f)) (key agate-configuration-key (default #f)) (addr agate-configuration-addr (default '("0.0.0.0:1965" "[::]:1965"))) (hostname agate-configuration-hostname (default #f)) (lang agate-configuration-lang (default #f)) (silent? agate-configuration-silent (default #f)) (serve-secret? agate-configuration-serve-secret (default #f)) (log-ip? agate-configuration-log-ip (default #t)) (user agate-configuration-user (default "agate")) (group agate-configuration-group (default "agate")) (log-file agate-configuration-log (default "/var/log/agate.log"))) (define agate-shepherd-service (match-lambda (($ package content cert key addr hostname lang silent? serve-secret? log-ip? user group log-file) (list (shepherd-service (provision '(agate)) (requirement '(networking)) (documentation "Run the agate Gemini server.") (start (let ((agate (file-append package "/bin/agate"))) #~(make-forkexec-constructor (list #$agate "--content" #$content "--cert" #$cert "--key" #$key "--addr" #$@addr #$@(if lang (list "--lang" lang) '()) #$@(if hostname (list "--hostname" hostname) '()) #$@(if silent? '("--silent") '()) #$@(if serve-secret? '("--serve-secret") '()) #$@(if log-ip? '("--log-ip") '())) #:user #$user #:group #$group #:log-file #$log-file))) (stop #~(make-kill-destructor))))))) (define agate-accounts (match-lambda (($ _ _ _ _ _ _ _ _ _ _ user group _) `(,@(if (equal? group "agate") '() (list (user-group (name "agate") (system? #t)))) ,(user-group (name group) (system? #t)) ,(user-account (name user) (group group) (supplementary-groups '("agate")) (system? #t) (comment "agate server user") (home-directory "/var/empty") (shell (file-append shadow "/sbin/nologin"))))))) (define agate-service-type (service-type (name 'guix) (extensions (list (service-extension account-service-type agate-accounts) (service-extension shepherd-root-service-type agate-shepherd-service))) (default-value (agate-configuration))))