aboutsummaryrefslogtreecommitdiff
path: root/gnu/tests/vnstat.scm
blob: c498b987ffd2f328535469e41bd5f03ac9e45d96 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
;;; GNU Guix --- Functional package management for GNU
;;; 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 tests vnstat)
  #:use-module (gnu tests)
  #:use-module ((gnu packages networking) #:select (socat vnstat))
  #:use-module (gnu services)
  #:use-module (gnu services networking)
  #:use-module (gnu services monitoring)
  #:use-module (gnu system)
  #:use-module (gnu system vm)
  #:use-module (guix gexp)
  #:use-module (ice-9 format)
  #:export (%test-vnstat))


(define (run-vnstat-test)
  "Run tests in a vm which has vnstat running."

  (define vnstat-config
    (vnstat-configuration
     (max-bandwidth 0)
     (time-sync-wait 0)
     (bandwidth-detection-interval 0)))

  (define inetd-service-entry-config
    (inetd-entry
     (name "discard")
     (socket-type 'stream)
     (protocol "tcp")
     (wait? #t)
     (user "nobody")))

  (define os
    (marionette-operating-system
     (simple-operating-system
      (service dhcp-client-service-type)
      (service vnstat-service-type
               vnstat-config)
      (service inetd-service-type
               (inetd-configuration
                (entries
                 (list inetd-service-entry-config)))))
     #:imported-modules '((gnu services herd))))

  (define forwarded-port 9999)

  (define vm
    ;; The 'discard' port is 9.  Avoid using 'getservbyname' as that might
    ;; fail depending on what /etc/services has (if it's available).
    (let ((guest-port 9))
      (virtual-machine
       (operating-system os)
       (port-forwardings `((,forwarded-port . ,guest-port))))))

  ;; The test duration is inconsistent, at times a test may complete under
  ;; 2 minutes and at times it may take up to 5 minutes.
  (define test-timeout (* 60 5))

  (define test
    (with-imported-modules '((gnu build marionette))
      #~(begin
          (use-modules (gnu build marionette)
                       (srfi srfi-64))

          (let ((marionette (make-marionette (list #$vm)))
                (pid-file #$(vnstat-configuration-pid-file vnstat-config)))

            (test-runner-current (system-test-runner #$output))
            (test-begin "vnstat")

            (test-assert "service is running"
              (marionette-eval
               '(begin
                  (use-modules (gnu services herd))
                  (start-service 'vnstatd))
               marionette))

            (test-assert "vnstatd ready"
              (wait-for-file pid-file marionette))

            ;; Pump garbage into the 'discard' inetd service within the vm.
            (let* ((socat #$(file-append socat "/bin/socat"))
                   (dest-addr #$(format #f "TCP4:localhost:~d"
                                        forwarded-port))
                   (args `("socat" "-u" "/dev/zero" ,dest-addr))
                   ;; XXX: Guile bug (22/03/2023, Guile 3.0.9)
                   ;; Fixed in main: <https://issues.guix.gnu.org/61073>
                   ;; FIXME: re-add #:output (%make-void-port "w") below on
                   ;; next Guile release.
                   (garbage-pump-pid
                    (spawn socat args)))
              (test-group-with-cleanup "Logging"
                ;; To aid debugging, this test returns #t on success
                ;; and either #f or 'timed-out otherwise.
                (test-eq "vnstatd is logging"
                  #t
                  (marionette-eval
                   '(begin
                      (use-modules (ice-9 popen)
                                   (ice-9 match)
                                   (sxml simple)
                                   (sxml xpath))

                      (define selector
                        (let ((xpath '(vnstat interface traffic total)))
                          (compose (node-pos 1) (sxpath xpath))))

                      (let loop ((i 0))
                        (let* ((vnstat #$(file-append vnstat "/bin/vnstat"))
                               (query-cmd (format #f "~a --xml" vnstat))
                               (proc (compose selector xml->sxml))
                               (result
                                (call-with-port
                                    (open-input-pipe query-cmd) proc)))
                          (match result
                            ;; Counter still warming up.
                            ((('total ('rx "0") ('tx "0")))
                             (sleep 1)
                             (if (< i #$test-timeout)
                                 (loop (+ i 1))
                                 'timed-out))
                            ;; Count of bytes on iface was non-zero.
                            ((('total ('rx rx) ('tx tx)))
                             #t)
                            ;; Unknown data encountered, perhaps the
                            ;; data format changed?
                            (_ #f)))))
                   marionette))
                ;; Cleanup: shutdown garbage pump.
                (kill garbage-pump-pid SIGTERM)))

            (test-end)))))

  (gexp->derivation "vnstat-test" test))

(define %test-vnstat
  (system-test
   (name "vnstat")
   (description "Basic tests for vnstat service.")
   (value (run-vnstat-test))))
\ -c \"Guix build user $i\" --system \ guixbuilder$i; done; cp ~~root/.config/guix/current/lib/systemd/system/guix-daemon.service /etc/systemd/system/ systemctl start guix-daemon && systemctl enable guix-daemon mkdir -p /usr/local/bin cd /usr/local/bin ln -s /var/guix/profiles/per-user/root/current-guix/bin/guix mkdir -p /usr/local/share/info cd /usr/local/share/info for i in /var/guix/profiles/per-user/root/current-guix/share/info/*; do ln -s $i; done guix archive --authorize < ~~root/.config/guix/current/share/guix/ci.guix.gnu.org.pub # guix pull guix package -i glibc-utf8-locales export GUIX_LOCPATH=\"$HOME/.guix-profile/lib/locale\" guix package -i openssl cat > /etc/bootstrap-config.scm << EOF (use-modules (gnu)) (use-service-modules base networking ssh) ~a EOF # guix pull guix system build /etc/bootstrap-config.scm guix system reconfigure /etc/bootstrap-config.scm mv /etc /old-etc mkdir /etc cp -r /old-etc/{passwd,group,shadow,gshadow,mtab,guix,bootstrap-config.scm} /etc/ guix system reconfigure /etc/bootstrap-config.scm" ;; Escape the bare backtick to avoid having it interpreted by Bash. (string-replace-substring (format #f "~y" os) "`" "\\`"))) (define (machine-wait-until-available machine) "Block until the initial Debian image has been installed on the droplet named DROPLET-NAME." (and-let* ((droplet (machine-droplet machine)) (droplet-id (assoc-ref droplet "id")) (endpoint (format #f "/v2/droplets/~a/actions" droplet-id))) (let loop () (let ((actions (assoc-ref (fetch-endpoint endpoint) "actions"))) (unless (every (lambda (action) (string= "completed" (assoc-ref action "status"))) (vector->list actions)) (sleep 5) (loop)))))) (define (wait-for-ssh address ssh-key) "Block until the an SSH session can be made as 'root' with SSH-KEY at ADDRESS." (let loop () (catch #t (lambda () (open-ssh-session address #:user "root" #:identity ssh-key)) (lambda args (sleep 5) (loop))))) (define (add-static-networking target network) "Return an <operating-system> based on TARGET with a static networking configuration for the public IPv4 network described by the alist NETWORK." (operating-system (inherit (machine-operating-system target)) (services (cons* (service static-networking-service-type (list (static-networking (addresses (list (network-address (device "eth0") (value (ip+netmask->cidr (assoc-ref network "ip_address") (assoc-ref network "netmask")))))) (routes (list (network-route (destination "default") (gateway (assoc-ref network "gateway"))))) (name-servers '("84.200.69.80" "84.200.70.40"))))) (simple-service 'guile-load-path-in-global-env session-environment-service-type `(("GUILE_LOAD_PATH" . "/run/current-system/profile/share/guile/site/3.0") ("GUILE_LOAD_COMPILED_PATH" . ,(string-append "/run/current-system/profile/lib/guile/3.0/site-ccache:" "/run/current-system/profile/share/guile/site/3.0")))) (operating-system-user-services (machine-operating-system target)))))) (define (deploy-digital-ocean target) "Internal implementation of 'deploy-machine' for 'machine' instances with an environment type of 'digital-ocean-environment-type'." (maybe-raise-missing-api-key-error) (maybe-raise-unsupported-configuration-error target) (let* ((config (machine-configuration target)) (name (machine-display-name target)) (region (digital-ocean-configuration-region config)) (size (digital-ocean-configuration-size config)) (ssh-key (digital-ocean-configuration-ssh-key config)) (fingerprint (read-key-fingerprint ssh-key)) (enable-ipv6? (digital-ocean-configuration-enable-ipv6? config)) (tags (digital-ocean-configuration-tags config)) (request-body `(("name" . ,name) ("region" . ,region) ("size" . ,size) ("image" . "debian-9-x64") ("ssh_keys" . ,(vector fingerprint)) ("backups" . #f) ("ipv6" . ,enable-ipv6?) ("user_data" . #nil) ("private_networking" . #nil) ("volumes" . #nil) ("tags" . ,(list->vector tags)))) (response (post-endpoint "/v2/droplets" request-body))) (machine-wait-until-available target) (let* ((network (machine-public-ipv4-network target)) (address (assoc-ref network "ip_address"))) (wait-for-ssh address ssh-key) (let* ((ssh-session (open-ssh-session address #:user "root" #:identity ssh-key)) (sftp-session (make-sftp-session ssh-session))) (call-with-remote-output-file sftp-session "/tmp/guix-infect.sh" (lambda (port) (display (guix-infect network) port))) (rexec ssh-session "/bin/bash /tmp/guix-infect.sh") ;; Session will close upon rebooting, which will raise 'guile-ssh-error. (catch 'guile-ssh-error (lambda () (rexec ssh-session "reboot")) (lambda args #t))) (wait-for-ssh address ssh-key) (let ((delegate (machine (operating-system (add-static-networking target network)) (environment managed-host-environment-type) (configuration (machine-ssh-configuration (host-name address) (identity ssh-key) (system "x86_64-linux")))))) (deploy-machine delegate))))) ;;; ;;; Roll-back. ;;; (define (roll-back-digital-ocean target) "Internal implementation of 'roll-back-machine' for MACHINE instances with an environment type of 'digital-ocean-environment-type'." (let* ((network (machine-public-ipv4-network target)) (address (assoc-ref network "ip_address")) (ssh-key (digital-ocean-configuration-ssh-key (machine-configuration target))) (delegate (machine (inherit target) (environment managed-host-environment-type) (configuration (machine-ssh-configuration (host-name address) (identity ssh-key) (system "x86_64-linux")))))) (roll-back-machine delegate))) ;;; ;;; Environment type. ;;; (define digital-ocean-environment-type (environment-type (machine-remote-eval digital-ocean-remote-eval) (deploy-machine deploy-digital-ocean) (roll-back-machine roll-back-digital-ocean) (name 'digital-ocean-environment-type) (description "Provisioning of \"droplets\": virtual machines provided by the Digital Ocean virtual private server (VPS) service."))) (define (maybe-raise-missing-api-key-error) (unless (%digital-ocean-token) (raise (condition (&message (message (G_ "No Digital Ocean access token was provided. This \ may be fixed by setting the environment variable GUIX_DIGITAL_OCEAN_TOKEN to \ one procured from https://cloud.digitalocean.com/account/api/tokens."))))))) (define (maybe-raise-unsupported-configuration-error machine) "Raise an error if MACHINE's configuration is not an instance of <digital-ocean-configuration>." (let ((config (machine-configuration machine)) (environment (environment-type-name (machine-environment machine)))) (unless (and config (digital-ocean-configuration? config)) (raise (formatted-message (G_ "unsupported machine configuration '~a' \ for environment of type '~a'") config environment)))))