id
int64 0
45.1k
| file_name
stringlengths 4
68
| file_path
stringlengths 14
193
| content
stringlengths 32
9.62M
| size
int64 32
9.62M
| language
stringclasses 1
value | extension
stringclasses 6
values | total_lines
int64 1
136k
| avg_line_length
float64 3
903k
| max_line_length
int64 3
4.51M
| alphanum_fraction
float64 0
1
| repo_name
stringclasses 779
values | repo_stars
int64 0
882
| repo_forks
int64 0
108
| repo_open_issues
int64 0
90
| repo_license
stringclasses 8
values | repo_extraction_date
stringclasses 146
values | sha
stringlengths 64
64
| __index_level_0__
int64 0
45.1k
| exdup_ids_cmlisp_stkv2
listlengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3,808 | message.lisp | russell_cl-git/tests/message.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test message-trailers ()
(is (equal
'((:key "Fixes" :value "https://example.com/foobar")
(:key "Signed-off-by" :value "John Doe <[email protected]>"))
(message-trailers "ci: fix a broken ci job
Fix a bulid
Fixes: https://example.com/foobar
Signed-off-by: John Doe <[email protected]>"))))
(def-test message-trailers-commit (:fixture repository-with-commit)
(let* ((test-commit (add-test-revision :message "ci: fix a broken ci job
Fix a bulid
Fixes: https://example.com/foobar
Signed-off-by: John Doe <[email protected]>"))
(test-commit-obj (get-object 'commit (getf (car test-commit) :sha)
*test-repository*)))
(is (equal
'((:key "Fixes" :value "https://example.com/foobar")
(:key "Signed-off-by" :value "John Doe <[email protected]>"))
(message-trailers test-commit-obj)))))
| 1,804 | Common Lisp | .lisp | 38 | 43.421053 | 75 | 0.69095 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 7e7547478ff793504128c92795a59afe74df922b68c423dd9b227f8ce1ee5c63 | 3,808 | [
-1
] |
3,809 | index.lisp | russell_cl-git/tests/index.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-fixture index-with-file (filename filetext)
#+sbcl (declare (sb-ext:muffle-conditions sb-ext:compiler-note))
(with-test-repository ()
(let ((filename (if (functionp filename)
(funcall filename)
filename)))
(with-index (*test-repository-index* *test-repository*)
(write-string-to-file filename filetext)
(&body)))))
(defun approximately-now-p (a)
(timestamp-approximately-equal-p a (now)))
(defun timestamp-approximately-equal-p (a b)
(< (timestamp-difference a b) 2))
(defun plist-equal (a b)
"Compare an plist, if the plist contains a function then use that as
a predicate."
(loop :for (key value) :on b :by #'cddr
:do (cond
((functionp value)
(is (funcall value (getf a key))))
((eql (type-of value) 'local-time:timestamp)
(is (timestamp-approximately-equal-p (getf a key) value)))
(t (is (equal (getf a key) value))))))
(defun index-path-test (filename filetext)
(index-add-file filename *test-repository-index*)
(index-write *test-repository-index*)
(mapcar #'plist-equal
(entries *test-repository-index*)
`((:C-TIME ,#'approximately-now-p
:M-TIME ,#'approximately-now-p
:FILE-SIZE ,(length filetext)
:OID 475587057170892494251873940086020553338329808131
:FLAGS ,(length (namestring filename))
:PATH ,(namestring filename)
:STAGE 0))))
(def-test index-add-pathname (:fixture (index-with-file #P"test-file" "foo blah."))
(index-path-test filename filetext))
(def-test index-add-string (:fixture (index-with-file "test-file" "foo blah."))
(index-path-test filename filetext))
(def-test index-add-abspathname (:fixture (index-with-file
(lambda ()
(merge-pathnames (make-pathname :name "test-file")
*repository-path*))
"foo blah."))
(let ((filename (enough-namestring filename *repository-path*)))
(index-path-test filename filetext)))
(def-test index-clear (:fixture (index-with-file #P"test-file" "foo blah."))
"Add an entry to the index and clear it."
(is (eq (entry-count *test-repository-index*) 0))
(index-add-file filename *test-repository-index*)
(is (eq (entry-count *test-repository-index*) 1))
(index-clear *test-repository-index*)
(is (eq (entry-count *test-repository-index*) 0)))
(def-test index-has-conflicts (:fixture repository)
(let ((filename "test-file"))
(with-index (test-index *test-repository*)
(write-string-to-file filename "foo")
(index-add-file filename test-index)
(is (eq (index-conflicts-p test-index)
nil)))))
(def-test index-open (:fixture repository)
(let ((filename "test-file")
(index-file-path (gen-temp-path)))
(with-index (test-index *test-repository*)
(write-string-to-file filename "foo")
(index-add-file filename test-index)
(unwind-protect
(with-index (index-file index-file-path)
(let ((entry (entry-by-index test-index 0)))
;; Add the entry from the other git index.
(index-add-file entry index-file)
(plist-equal entry
(entry-by-index index-file 0))))
(when (file-exists-p index-file-path)
(delete-file index-file-path))))))
(def-test index-new (:fixture repository)
(let ((filename "test-file"))
(with-index (test-index *test-repository*)
(write-string-to-file filename "foo")
(index-add-file filename test-index)
(with-index (index-in-memory)
(index-write test-index)
(let ((entry (entry-by-index test-index 0)))
;; Add the entry from the other git index.
(index-add-file entry index-in-memory)
(let ((entry1 (entry-by-index index-in-memory 0)))
(plist-equal entry entry1)))))))
| 4,999 | Common Lisp | .lisp | 106 | 38.877358 | 95 | 0.630359 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 63d3ee0a17064ac1ad0c5825597e2d83dbb6dea3415b98f27a8e9a4f97b3d346 | 3,809 | [
-1
] |
3,810 | reflog.lisp | russell_cl-git/tests/reflog.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test reflog-entries (:fixture repository-with-commits)
(let ((entries
(entries
(reflog
(get-object 'reference "refs/heads/master" *test-repository*))))
(commits (loop :for commit :in *test-traverse-state*
:collect (getf commit :message))))
(is (equal
(mapcar #'message entries)
(concatenate 'list
(mapcar (lambda (e) (format nil "commit: ~a" e))
(subseq commits 0 (1- (length commits))))
(list (format nil "commit (initial): ~a"
(car (last commits)))))))))
(def-test reflog-entry-count (:fixture repository-with-commits)
(let ((entries
(entries
(reflog
(get-object 'reference "refs/heads/master" *test-repository*))))
(commits (loop :for commit :in *test-traverse-state*
:collect (getf commit :message))))
(is (equal
(length commits)
(length entries)))))
| 1,946 | Common Lisp | .lisp | 43 | 37.488372 | 76 | 0.629083 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | b99894d7e6b490f3290e6d2d3acfda3088c9cd6de41fe5eb99cb166d3d7ce955 | 3,810 | [
-1
] |
3,811 | strings.lisp | russell_cl-git/tests/strings.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test individual-strings ()
(for-all ((strings-fixture (random-list)))
(let ((str-pointer
(cffi:convert-to-foreign strings-fixture '(:struct cl-git::git-strarray))))
(is
(equal
(cffi:convert-from-foreign str-pointer '(:struct cl-git::git-strarray))
strings-fixture))
(cffi:free-converted-object str-pointer '(:struct cl-git::git-strarray) t))))
(def-test string-list ()
(let* ((strings-fixture (funcall (random-list)))
(str-pointer
(cffi:convert-to-foreign strings-fixture '(:struct cl-git::git-strarray))))
(is
(equal
(cffi:convert-from-foreign str-pointer '(:struct cl-git::git-strarray))
strings-fixture))
(cffi:free-converted-object str-pointer '(:struct cl-git::git-strarray) t)))
| 1,690 | Common Lisp | .lisp | 37 | 41.837838 | 87 | 0.702063 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | c9d2cf355cc17734e5695928cf7b9ab2e96574f0b533239ac4aa541434ad121c | 3,811 | [
-1
] |
3,812 | diff.lisp | russell_cl-git/tests/diff.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;;
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(defun sort-flags (object &rest key-path)
(loop :for key :in (butlast key-path)
:for obj = (getf (or obj object) key)
:finally (setf (getf obj (car (last key-path)))
(stable-sort (getf obj (car (last key-path))) #'string<)))
object)
(defun sort-diff-flags (diff)
(loop :for patch :in diff
:collect (sort-flags (sort-flags patch :file-a :flags) :file-b :flags)))
(def-test diff-revisions (:fixture repository-with-changes)
(let ((diffs (diff commit1 commit2)))
(is (eq (diff-deltas-count diffs) 1))
(is (equal '((:status :modified
:similarity 0
:flags (:not-binary)
:file-a (:id-abbrev 40
:mode :blob
:flags (:not-binary :valid-id :exists)
:size 902
:path "test-file"
:oid 97787706012661474925191056142692387097255677107)
:file-b (:id-abbrev 40
:mode :blob
:flags (:not-binary :valid-id :exists)
:size 919
:path "test-file"
:oid 243568240973109882797341286687005129339258402139)))
(diff-deltas-summary diffs)))
(is (equal `((:patch ,repository-with-changes-diff
:status :modified
:similarity 0
:flags (:not-binary)
:file-a (:id-abbrev 40
:mode :blob
:flags (:exists :not-binary :valid-id)
:size 902
:path "test-file"
:oid
97787706012661474925191056142692387097255677107)
:file-b (:id-abbrev 40
:mode :blob
:flags (:exists :not-binary :valid-id)
:size 919
:path "test-file"
:oid
243568240973109882797341286687005129339258402139)))
(sort-diff-flags (make-patch diffs))))))
(def-test diff-working (:fixture repository-with-unstaged)
(let ((diffs (diff *test-repository* (open-index *test-repository*))))
(is (eq (diff-deltas-count diffs) 1))
(is (equal '((:status :modified
:similarity 0
:flags (:not-binary)
:file-a (:id-abbrev 40
:mode :blob
:flags (:not-binary :valid-id :exists)
:size 902
:path "test-file"
:oid 97787706012661474925191056142692387097255677107)
:file-b (:id-abbrev 40
:mode :blob
:flags (:not-binary :valid-id :exists)
:size 919
:path "test-file"
:oid 243568240973109882797341286687005129339258402139)))
(diff-deltas-summary diffs)))
(is (equal `((:patch ,repository-with-changes-diff
:status :modified
:similarity 0
:flags (:not-binary)
:file-a (:id-abbrev 40
:mode :blob
:flags (:exists :not-binary :valid-id)
:size 902
:path "test-file"
:oid
97787706012661474925191056142692387097255677107)
:file-b (:id-abbrev 40
:mode :blob
:flags (:exists :not-binary :valid-id)
:size 919
:path "test-file"
:oid
243568240973109882797341286687005129339258402139)))
(sort-diff-flags (make-patch diffs))))))
(def-test diff-staged (:fixture repository-with-staged)
(let ((diffs (diff commit1 (open-index *test-repository*))))
(is (eq (diff-deltas-count diffs) 1))
(is (equal '((:status :modified
:similarity 0
:flags (:not-binary)
:file-a (:id-abbrev 40
:mode :blob
:flags (:not-binary :valid-id :exists)
:size 902
:path "test-file"
:oid 97787706012661474925191056142692387097255677107)
:file-b (:id-abbrev 40
:mode :blob
:flags (:not-binary :valid-id :exists)
:size 919
:path "test-file"
:oid 243568240973109882797341286687005129339258402139)))
(diff-deltas-summary diffs)))
(is (equal `((:patch ,repository-with-changes-diff
:status :modified
:similarity 0
:flags (:not-binary)
:file-a (:id-abbrev 40
:mode :blob
:flags (:exists :not-binary :valid-id)
:size 902
:path "test-file"
:oid
97787706012661474925191056142692387097255677107)
:file-b (:id-abbrev 40
:mode :blob
:flags (:exists :not-binary :valid-id)
:size 919
:path "test-file"
:oid
243568240973109882797341286687005129339258402139)))
(sort-diff-flags (make-patch diffs))))))
| 6,797 | Common Lisp | .lisp | 143 | 29.314685 | 83 | 0.478405 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 608fde4d5c847577ea592deda9995fc38cbdac33b2d8858aa4b0f6ce586afafc | 3,812 | [
-1
] |
3,813 | references.lisp | russell_cl-git/tests/references.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-fixture reference-with-context ()
(with-test-repository ()
(let* ((test-commit (make-test-revision))
(ref-default (make-object 'reference "refs/heads/oid"
*test-repository*
:target (getf test-commit :sha)))
(ref-symbolic (make-object 'reference "refs/heads/symbolic"
*test-repository*
:target "refs/heads/oid"
:type :symbolic)))
(declare (ignorable ref-symbolic) (ignorable ref-default))
(&body))))
(def-fixture reference ()
(with-test-repository ()
(let ((test-commit (make-test-revision)))
(make-object 'reference "refs/heads/oid"
*test-repository*
:target (getf test-commit :sha)))
(make-object 'reference "refs/heads/symbolic"
*test-repository*
:target "refs/heads/oid"
:type :symbolic)
(&body)))
(def-test references-list-oid (:fixture reference)
(is
(equal
(sort-strings
(mapcar #'full-name
(list-objects 'reference *test-repository*
:test-not #'symbolic-p)))
(sort-strings (list "refs/heads/oid" "refs/heads/master")))))
(def-test references-list-symbolic (:fixture reference)
(is
(equal ;; test the list-objects default args.
(sort-strings
(mapcar #'full-name (list-objects 'reference *test-repository*)))
(sort-strings
(list "refs/heads/oid" "refs/heads/symbolic" "refs/heads/master")))))
(def-test reference-lookup-oid (:fixture reference)
(let ((ref (get-object 'reference "refs/heads/oid" *test-repository*)))
(is
(equal (full-name ref)
"refs/heads/oid"))
(is
(equal (type-of ref)
'reference))))
(def-test reference-lookup-symbolic (:fixture reference)
(let ((ref (get-object 'reference "refs/heads/symbolic" *test-repository*)))
(is
(equal (full-name ref)
"refs/heads/symbolic"))
(is
(equal (type-of ref)
'reference))))
(def-test reference-accessors-oid (:fixture reference-with-context)
"Create oid reference and check accessors."
(is (equal
(symbolic-p ref-default)
nil))
(is (equal
(full-name ref-default)
"refs/heads/oid"))
(is (equal
(short-name ref-default)
"oid")))
(def-test reference-accessors-symbolic (:fixture reference-with-context)
"Create symbolic reference and check it's name."
(is (equal
(symbolic-p ref-symbolic)
t))
(is (equal
(full-name ref-symbolic)
"refs/heads/symbolic"))
(is (equal
(short-name ref-symbolic)
"symbolic")))
(def-test reference-target-oid (:fixture reference-with-context)
"Check that the returned commit id matches the id from the reference
fixture"
(is (equal
(oid (target ref-default))
(getf test-commit :sha))))
(def-test reference-target-symbolic (:fixture reference-with-context)
"Check that the returned commit id matches the id from the reference
fixture"
(is (equal
(oid (target ref-symbolic))
(getf test-commit :sha))))
(def-test reference-is-branch (:fixture reference)
"Check that the ref is a branch."
(is (equal
(branch-p (get-object 'reference "refs/heads/oid" *test-repository*))
t)))
(def-test reference-is-not-remote (:fixture reference)
"Check that the ref is a branch."
(is (equal
(remote-p (get-object 'reference "refs/heads/oid" *test-repository*))
nil)))
;; TODO add test for the positive case
(def-test reference-has-reflog (:fixture reference-with-context)
"Check that the ref has a reflog."
(is (equal
(git-has-log *test-repository* ref-default)
nil)))
(def-test reference-set-target (:fixture reference-with-context)
"Check that the returned commit id matches the id from the reference
fixture"
(let ((test-commit1 (make-test-revision)))
(is (equal
(oid (target ref-default))
(getf test-commit :sha)))
(setf (target ref-default) (getf test-commit1 :sha))
(is (equal
(oid (target ref-default))
(getf test-commit1 :sha)))))
| 5,174 | Common Lisp | .lisp | 134 | 31.843284 | 78 | 0.641307 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 87dea0a9f38bb8cd23d9b348f277d9dba1fb78af926b4bb29a0702a60cd23c03 | 3,813 | [
-1
] |
3,814 | checkout.lisp | russell_cl-git/tests/checkout.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test git-checkout-options-struct ()
"Verify initialising a GIT-CHECKOUT-OPTIONS-STRUCT."
(cffi:with-foreign-object (ptr '(:struct cl-git::git-checkout-options))
(cl-git::%git-checkout-init-options ptr cl-git::+git-checkout-options-version+)
(cffi:with-foreign-slots ((cl-git::version cl-git::perfdata-payload)
ptr (:struct cl-git::git-checkout-options))
(is (eql cl-git::+git-checkout-options-version+ cl-git::version))
(is (cffi:null-pointer-p cl-git::perfdata-payload)))))
| 1,435 | Common Lisp | .lisp | 27 | 49.925926 | 83 | 0.720599 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | dd35a67bee32de6823ed3494f6b1b9cf97508487e98128099b38745d622b5397 | 3,814 | [
-1
] |
3,815 | odb.lisp | russell_cl-git/tests/odb.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test odb-list (:fixture repository-with-commits)
"list all the odb objects in the database."
(let ((oids (list-objects :oid *test-repository*)))
;; XXX (RS) this test is limited because we aren't currently
;; storing a list of the trees and blobs in the
;; *test-repository-state* variable.
(mapcar (lambda (v) (is (member (getf v :sha) oids)))
*test-repository-state*)))
(def-test odb-load (:fixture repository-with-commits)
"load an object from the database."
(let* ((commit (next-test-commit))
(object (get-object 'odb-object (getf commit :sha) *test-repository*)))
(is
(equal
(oid object)
(getf commit :sha)))
(is
(equal
(odb-type object)
:commit))
(is
(search (getf (getf commit :author) :name)
(octets-to-string (odb-data object) :external-format :utf-8)))))
| 1,774 | Common Lisp | .lisp | 42 | 38.642857 | 80 | 0.695072 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | f3e9f300b69e5cdacaa8badfe9ef1ea411c573da19aecdad5b9907c26a5ae292 | 3,815 | [
-1
] |
3,816 | config.lisp | russell_cl-git/tests/config.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test repository-config (:fixture (repository))
(let ((config (sort
(git-values (git-config *test-repository* :level :local))
#'string<
:key (lambda (a) (getf a :name))))
(expected-config
'((:name "core.bare" :value "false" :level :local)
(:name "core.filemode" :value "true" :level :local)
(:name "core.logallrefupdates" :value "true" :level :local)
(:name "core.repositoryformatversion" :value "0" :level :local))))
(is (mapcar #'plist-equal config expected-config))
(is (eql (length config) (length expected-config)))))
| 1,542 | Common Lisp | .lisp | 31 | 44.870968 | 78 | 0.677955 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 81effadde9c56805db0df5459f070a829c93fa4aa034d98b53a53b09e0026f4c | 3,816 | [
-1
] |
3,817 | repository.lisp | russell_cl-git/tests/repository.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test repository-init ()
"Create a repository and open it."
(for-all ((path 'gen-temp-path))
(finishes
(unwind-protect
(progn
(init-repository path :bare t)
(is (typep (open-repository path) 'repository)))
(progn
(delete-directory-and-files path))))))
(def-test repository-path (:fixture (repository :bare t))
(is
(equal
(repository-path *test-repository*)
*repository-path*)))
(def-test repository-path-workdir-bare (:fixture (repository :bare t))
(is
(equal
(repository-workdir *test-repository*)
nil)))
(def-test repository-path-workdir (:fixture (repository))
(is
(equal
(repository-workdir *test-repository*)
*repository-path*)))
(def-test repository-head (:fixture (repository))
(let ((test-commit (make-test-revision)))
(is
(commit-equal
(target (repository-head *test-repository*))
test-commit))))
(def-test repository-head-detached (:fixture (repository))
"Confirm that the current head is detached then check that not."
(make-test-revision)
;; TODO add negative test
(is (equal
(head-detached-p *test-repository*)
nil)))
(def-test is-repository-empty (:fixture (repository))
"Check that the repository is empty."
(is (eq (empty-p *test-repository*) t))
(make-test-revision)
(is (eq (empty-p *test-repository*) nil)))
(def-test is-repository-bare (:fixture (repository :bare t))
"Check that the repository is bare."
(is
(eq
(bare-p *test-repository*)
t)))
(def-test repository-head-unborn (:fixture (repository))
"Confirm that the current head is orphaned then check that not."
;; confirm head is orphaned
(is (equal
(head-unborn-p *test-repository*)
t))
(make-test-revision)
;; confirm head no longer orphaned
(is (equal
(head-unborn-p *test-repository*)
nil)))
(def-test with-repository ()
"Create a repository and test the with-repository macro."
(for-all ((path 'gen-temp-path))
(finishes
(unwind-protect
(progn
(init-repository path :bare t)
(with-repository (repository path)
(is (typep repository 'repository))))
(progn
(delete-directory-and-files path))))))
| 3,189 | Common Lisp | .lisp | 90 | 30.933333 | 70 | 0.681582 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | c036233940fb25f375a642d39efd8315e4ce33efd2356477ece571f6caae37d9 | 3,817 | [
-1
] |
3,818 | commit.lisp | russell_cl-git/tests/commit.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test commit ()
"create a repository and add a file to it."
(with-test-repository ()
(let ((test-commit (make-test-revision))) ;; get first commit
(bind-git-commits (((commit :sha (getf test-commit :sha))) *test-repository*)
(commit-equal test-commit commit)))))
(def-test default-signature ()
"Test to make sure that if there is no time or email address in the
signature then it will be added automatically."
(with-test-repository ()
(let ((test-pre-create (timestamp-to-unix (now))))
(let ((test-post-create (timestamp-to-unix (now)))
(test-commit (make-test-revision :author (list :name (random-string 50)))))
(bind-git-commits (((commit :sha (getf test-commit :sha))) *test-repository*)
;; set the email address the test data to the default.
(setf (getf (getf test-commit :author) :email) (cl-git::default-email))
;; test that the time is correct
(let ((created (getf (getf (commit-to-alist commit) :author) :time)))
(is (<= (timestamp-to-unix created) test-post-create))
(is (>= (timestamp-to-unix created) test-pre-create))
(setf (getf (getf test-commit :author) :time) created))
(commit-equal test-commit commit))))))
(def-test custom-signature-time ()
"test if the time is an integer then it will be parsed correctly."
(with-test-repository ()
(let ((test-commit (make-test-revision
:author (list :name (random-string 50)
:email "test@localhost"
:time 1111111111))))
(bind-git-commits (((commit :sha (getf test-commit :sha))) *test-repository*)
(commit-equal test-commit commit)))))
(def-test commit-parents (:fixture repository-with-commits)
(let ((test-commit (next-test-commit)))
(is (equal
(oid (car (parents (get-object 'commit (getf test-commit :sha)
*test-repository*))))
(getf (next-test-commit) :sha)))
(is (equal
(length (parents (get-object 'commit (getf test-commit :sha)
*test-repository*)))
1))
;; XXX (RS) this is a very low level test to make sure that the
;; lazy oid loading is working. It should probably be covered in
;; a higher level test once one is written.
(is
(pointerp
(cl-git::pointer
(car
(parents
(get-object 'commit (getf test-commit :sha)
*test-repository*))))))))
| 3,477 | Common Lisp | .lisp | 70 | 41.942857 | 87 | 0.633981 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 910a0aaef103fb7c307ce41c62c4f10e3224af1a581647e7174deb672b9de1a2 | 3,818 | [
-1
] |
3,819 | common.lisp | russell_cl-git/tests/common.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(def-suite :cl-git)
(defparameter *test-repository-path* #P"/tmp/")
(defun getpid ()
#+clisp (os:process-id)
#+(or cmu scl) (unix:unix-getpid)
#+sbcl (sb-unix:unix-getpid)
#+gcl (system:getpid)
#+openmcl (ccl::getpid)
#+lispworks (system::getpid)
#+ecl (si:getpid)
#+ccl (ccl::getpid)
#-(or clisp cmu scl sbcl gcl openmcl lispworks ecl ccl) (getpid-from-environment))
(defmacro format-string (control-string &rest format-arguments)
`(with-output-to-string (stream)
(format stream ,control-string ,@format-arguments)))
(defun open-test-files-p (repository-path)
"check if there were any files left open from a test."
(loop :for line
:in (cdr (inferior-shell:run/lines (format-string "lsof -Fn -p ~S" (getpid))))
:when (eq 1 (search (namestring repository-path) line))
:collect (subseq line 1 (length line))))
(defun alpha-or-whitespace-p (c)
(when (member (char-int c)
`(,@(iota 25 :start 65)
,@(iota 25 :start 97)))
t))
(defun gen-alpha-numeric ()
"return either a letter or number."
(gen-character :code-limit 126
:alphanumericp #'alpha-or-whitespace-p))
(defun gen-temp-path ()
(merge-pathnames
(make-pathname
:directory `(:relative
,(concatenate 'string "cl-git-test-"
(funcall
(gen-string :length (gen-integer :min 5 :max 10)
:elements (gen-alpha-numeric))))))
*test-repository-path*))
(defun gen-temp-file-path ()
(merge-pathnames
*test-repository-path*
(make-pathname
:name (concatenate 'string "cl-git-test-"
(funcall
(gen-string :length (gen-integer :min 5 :max 10)
:elements (gen-alpha-numeric)))))))
(defun random-number (min max)
(funcall (gen-integer :min min :max max)))
(defun random-time ()
(unix-to-timestamp
(funcall (gen-integer
:min 0
:max (timestamp-to-unix (now))))))
(defun random-string (length)
(funcall
(gen-string :length (gen-integer :min length :max length)
:elements (gen-alpha-numeric))))
(defun random-list (&key (length (gen-integer :min 0 :max 10)))
(gen-list :length length :elements (gen-string :elements (gen-alpha-numeric))))
(defun assoc-default (key alist)
(cdr (assoc key alist)))
(defun sort-strings (strings)
(sort strings #'string-lessp))
(defvar *repository-path* nil
"the path to the current test repository.")
(defvar *test-repository* nil
"store the state of the current test repository.")
(defvar *test-repository-state* nil
"store the state of the current test repository.")
(defvar *test-traverse-state* nil
"store the state of the current test repository traversal state, it
will update to the new head when a new commit is added.")
(defvar *test-repository-index* nil)
(defmacro with-test-repository ((&key bare) &body body)
"Create a new repository and bind the randomly generated path."
`(let ((*repository-path* (gen-temp-path))
*test-repository-state*
*test-traverse-state*)
(finishes
(unwind-protect
(progn
(init-repository *repository-path* :bare ,bare)
(let ((*test-repository* (open-repository *repository-path*)))
,@body
(free *test-repository*))
(let ((open-files (open-test-files-p *repository-path*)))
(when open-files
(fail "The following files were left open ~S" open-files))))
(progn
(delete-directory-and-files *repository-path*))))))
(defun write-string-to-file (filename content
&optional (repo-path *repository-path*))
(let* ((filename (merge-pathnames
(if (pathnamep filename)
filename
(make-pathname :name filename))
repo-path))
(test-file (namestring filename)))
(with-open-file (stream test-file :direction :output
:if-exists :supersede)
(format stream content))))
(defun read-file-to-string (filename)
(with-open-file (stream filename)
(let ((string (make-string (file-length stream))))
(read-sequence string stream)
string)))
(defun make-test-commit (commit)
"Make a commit to the current repository and return the updated
commit alist. The commit argument is an alist that should contain the
keys :FILES :MESSAGE :AUTHOR :COMMITTER the returned alist will also
contain the a :SHA containing the sha1 hash of the newly created
commit."
(with-index (*test-repository-index* *test-repository*)
(dolist (file (getf commit :files))
(funcall #'write-string-to-file (getf file :filename) (getf file :text))
(index-add-file (getf file :filename) *test-repository-index*))
(index-write *test-repository-index*)
(setf (getf commit :sha)
(oid
(make-commit
(index-to-tree *test-repository-index*)
(getf commit :message)
:repository *test-repository*
:parents (getf commit :parents)
:author (getf commit :author)
:committer (getf commit :committer)))))
commit)
(defun random-commit (&key
(message (random-string 100))
(author (list :name (random-string 50)
:email (random-string 50)
:time (random-time)))
(committer (list :name (random-string 50)
:email (random-string 50)
:time (random-time)))
(file-count 1)
(files (loop :for count :upfrom 0
:collect (list
:filename (random-string 10)
:text (random-string 100))
:while (< count file-count)))
parents)
(let ((parents (if (listp parents) parents (list parents))))
(list
:parents parents
:message message
:files files
:author author
:committer committer)))
(defun add-test-revision (&rest rest)
(let ((args rest))
(setf (getf args :parents) (getf (car *test-repository-state*) :sha))
(push
(make-test-commit
(apply #'random-commit args))
*test-repository-state*)
(setf *test-traverse-state* *test-repository-state*)))
(defun next-test-commit ()
"return the next commit from the traverser and move the traverser to
it's parent."
(pop *test-traverse-state*))
(defun make-test-revisions (depth)
"create a number of random commits to random files."
(loop :for count :upfrom 0
:while (< count depth)
:do (add-test-revision)))
(defun make-test-revision (&rest rest)
"Create one test commit and return the test alist representation."
(apply #'add-test-revision rest)
(next-test-commit))
(defun commit-to-alist (commit)
"Convert a commit to an alist, that is the same format as the test
commit alist."
(list
:message (message commit)
:committer (committer commit)
:author (author commit)))
(defun time-to-unix (time)
(if (integerp time)
time
(timestamp-to-unix time)))
(defun signature-equal (x y)
"Compare two signatures and make sure they are equal."
(is (equal (getf x :name)
(getf y :name)))
(is (equal (getf x :email)
(getf y :email)))
(is (equal (time-to-unix (getf x :time))
(time-to-unix (getf y :time)))))
(defun commit-equal (x y)
"return true if the commits are equal."
(let ((x (if (typep x 'commit)
(commit-to-alist x)
x))
(y (if (typep y 'commit)
(commit-to-alist y)
y)))
(is (equal (getf x :message)
(getf y :message)))
;; TODO test parents
(signature-equal (getf x :author)
(getf y :author))
(signature-equal (getf x :committer)
(getf y :committer))))
| 9,169 | Common Lisp | .lisp | 223 | 32.421525 | 86 | 0.606734 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | d5a4d1cf84068213e885aa1c2e7ad3802419038c9a8e173262674c81b5202c83 | 3,819 | [
-1
] |
3,820 | clone.lisp | russell_cl-git/tests/clone.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test clone-repository (:fixture repository-with-commits)
"Create a new repository and clone it."
(let ((remote-repo-path (gen-temp-path)))
(unwind-protect
(let ((cloned-repository
(clone-repository (namestring *repository-path*)
remote-repo-path)))
(is (eql
(oid (repository-head *test-repository*))
(oid (repository-head cloned-repository)))))
(progn
(delete-directory-and-files remote-repo-path)))))
(def-test clone-repository-https (:fixture repository-with-commits)
"Create a new repository and clone it."
(let ((remote-repo-path (gen-temp-path)))
(unwind-protect
(let ((cloned-repository
(clone-repository
"https://github.com/libgit2/TestGitRepository.git"
remote-repo-path
;; TODO This is only really needed for my local
;; machine that rewrites all github url's to be ssh.
;; But it shuoldn't cause an issue here and still
;; generally tests things. Though not ideal
:credentials 'ssh-key-from-agent)))
(is (eql
;; Hard coded oid
417875169754799628935327977610761210040455787456
(oid (repository-head cloned-repository)))))
(progn
(delete-directory-and-files remote-repo-path)))))
(def-test git-clone-options-struct ()
"Verify initialising a GIT-CLONE-OPTIONS-STRUCT."
(cffi:with-foreign-object (ptr '(:struct cl-git::git-clone-options))
;; change the last value in the struct to be something different
(cffi:with-foreign-slots ((cl-git::remote-cb-payload)
ptr (:struct cl-git::git-clone-options))
(setf cl-git::remote-cb-payload ptr))
(cl-git::%git-clone-init-options ptr cl-git::+git-clone-options-version+)
(cffi:with-foreign-slots ((cl-git::version cl-git::remote-cb-payload)
ptr (:struct cl-git::git-clone-options))
;; verify the first and last values of the struct, it should all be nil
(is (eql cl-git::+git-clone-options-version+ cl-git::version))
(is (cffi:null-pointer-p cl-git::remote-cb-payload)))))
| 3,191 | Common Lisp | .lisp | 63 | 42.174603 | 77 | 0.647869 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | d368a8817137ea604ade9a9e44a6a345c4bc1f0b15044a57eddcf9f9c01bf87b | 3,820 | [
-1
] |
3,821 | blob.lisp | russell_cl-git/tests/blob.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test blob-content (:fixture repository-with-commit)
;; TODO (RS) this test sucks, it should be sorting the tree object
;; at the start.
(let* ((commit (next-test-commit))
(object (get-object 'commit (getf commit :sha) *test-repository*)))
(is
(equal
(sort-strings
(mapcar (compose #'namestring #'filename)
(tree-directory (commit-tree object))))
(sort-strings
(mapcar (lambda (e) (getf e :filename))
(getf commit :files)))))
(is
(equal
(sort-strings
(mapcar (lambda (e) (getf e :text))
(getf commit :files)))
(sort-strings
(mapcar (compose #'(lambda (o) (octets-to-string o :external-format :utf-8))
#'blob-content)
(tree-directory (commit-tree object))))))))
| 1,735 | Common Lisp | .lisp | 41 | 37.04878 | 83 | 0.66213 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 69d415c4fb62763cf6a8af42bdf6fc2fc936b43b277a071c3286d6c709db3ea9 | 3,821 | [
-1
] |
3,822 | remote.lisp | russell_cl-git/tests/remote.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test list-remotes (:fixture repository-with-commits)
"Create a new repository and check it's remotes."
(is
(eq
(list-objects 'remote *test-repository*)
nil)))
(def-test create-remote (:fixture repository-with-commits)
"Create a remote and check it's details."
(make-object 'remote "origin" *test-repository* :url "/dev/null" )
(is
(equal
(mapcar #'full-name (list-objects 'remote *test-repository*))
'("origin")))
(is
(equal
(remote-url (get-object 'remote "origin" *test-repository*))
"/dev/null")))
(def-test ls-remote (:fixture repository-with-commits)
"Create a new repository and check the contents with ls-remote."
(let ((remote-repo-path (gen-temp-path)))
(unwind-protect
(progn
(init-repository remote-repo-path)
(let ((remote-repo (open-repository remote-repo-path)))
(make-object 'remote "origin"
remote-repo
:url (namestring *repository-path*))
(let ((remote (get-object 'remote "origin" remote-repo)))
(signals connection-error
(ls-remote remote))
(remote-connect remote)
(is
(equal
`((:local nil
:remote-oid ,(oid (repository-head *test-repository*))
:local-oid 0
:name "HEAD"
:symref-target "refs/heads/master")
(:local nil
:remote-oid ,(oid (repository-head *test-repository*))
:local-oid 0
:name "refs/heads/master"
:symref-target nil))
(ls-remote remote))))))
(progn
(delete-directory-and-files remote-repo-path)))))
(def-test fetch-remotes (:fixture repository-with-commits)
"Create a new repository and check it's remotes."
(let ((remote-repo-path (gen-temp-path)))
(unwind-protect
(progn
(init-repository remote-repo-path)
(let ((remote-repo (open-repository remote-repo-path)))
(make-object 'remote "origin"
remote-repo
:url (namestring *repository-path*))
(let ((remote (get-object 'remote "origin" remote-repo)))
(remote-download remote)
(is
(equal
(remote-fetch-refspecs remote)
'("+refs/heads/*:refs/remotes/origin/*"))))))
(progn
(delete-directory-and-files remote-repo-path)))))
(def-test push-remote (:fixture repository-with-commits)
"Create a new bare repo and push to it."
(let ((push-repo-path (gen-temp-path)))
(unwind-protect
(progn
(init-repository push-repo-path :bare t)
(let ((remote
(make-object 'remote "origin"
*test-repository*
:url (namestring push-repo-path))))
(is
(equal
(remote-fetch-refspecs remote)
'("+refs/heads/*:refs/remotes/origin/*")))
(remote-push remote :refspecs '("refs/heads/master")))
(let ((push-repo (open-repository push-repo-path)))
(is (eql
(oid (repository-head *test-repository*))
(oid (repository-head push-repo))))
;; Test repo should now show the remote branch
(is (equal
'("refs/heads/master" "refs/remotes/origin/master")
(mapcar #'full-name
(list-objects 'reference *test-repository*))))
;; The bare repo should have a master branch
(is (equal
'("refs/heads/master")
(mapcar #'full-name
(list-objects 'reference push-repo))))))
(progn
(delete-directory-and-files push-repo-path)))))
(def-test git-fetch-options-struct ()
"Verify initialising a GIT-FETCH-OPTIONS-STRUCT."
(cffi:with-foreign-object (ptr '(:struct cl-git::git-fetch-options))
(cffi:with-foreign-slots ((cl-git::version cl-git::custom-headers)
ptr (:struct cl-git::git-fetch-options))
(setf cl-git::version 1234)
(setf cl-git::custom-headers (cffi:convert-to-foreign (funcall (random-list)) '(:struct cl-git::git-strarray))))
(cl-git::%git-fetch-options-init ptr cl-git::+git-fetch-options-version+)
(cffi:with-foreign-slots ((cl-git::version cl-git::custom-headers)
ptr (:struct cl-git::git-fetch-options))
(is (eql cl-git::+git-fetch-options-version+ cl-git::version))
(is (eql nil cl-git::custom-headers)))))
| 5,684 | Common Lisp | .lisp | 126 | 34.309524 | 118 | 0.582071 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | bad9aced2b84a29a420f8ea579bb39b5d711edfed07d93f9c91ead7367604e24 | 3,822 | [
-1
] |
3,823 | revwalker.lisp | russell_cl-git/tests/revwalker.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test revision-walker-test ()
"create a repository and add several random commits to it. then
check that the commit messages match the expected messages."
(with-test-repository ()
(make-test-revisions 10)
(let* ((commit-list *test-repository-state*)
(tcommit (pop commit-list))
(count 0))
(let ((walker (revision-walk (get-object 'commit (getf tcommit :sha) *test-repository*)
:ordering :topological)))
(do ((commit (next-revision walker) (next-revision walker)))
((null commit))
(commit-equal tcommit commit)
(setf count (1+ count))
(setq tcommit (pop commit-list)))
(is (equal count 10))))))
| 1,632 | Common Lisp | .lisp | 35 | 41.657143 | 93 | 0.685104 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | b6943fcc23205991ada45a97ecee7e6d6e6f90a6af8f350e5f238d0793b9c763 | 3,823 | [
-1
] |
3,824 | fixtures.lisp | russell_cl-git/tests/fixtures.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git is a Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-fixture repository (&key bare)
(with-test-repository (:bare bare)
(&body)))
(def-fixture repository-with-commits ()
(with-test-repository ()
(make-test-revisions 10)
(&body)))
(def-fixture repository-with-commit ()
(with-test-repository ()
(make-test-revisions 1)
(&body)))
(defvar test-file "
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Donec hendrerit tempor tellus.
Donec pretium posuere tellus.
Proin quam nisl, tincidunt et, mattis eget, convallis nec, purus.
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
Nulla posuere.
Donec vitae dolor.
Nullam tristique diam non turpis.
Cras placerat accumsan nulla.
Nullam rutrum.
Nam vestibulum accumsan nisl.
Aliquam erat volutpat.
Nunc eleifend leo vitae magna.
In id erat non orci commodo lobortis.
Proin neque massa, cursus ut, gravida ut, lobortis eget, lacus.
Sed diam.
Praesent fermentum tempor tellus.
Nullam tempus.
Mauris ac felis vel velit tristique imperdiet.
Donec at pede.
Etiam vel neque nec dui dignissim bibendum.
Vivamus id enim.
Phasellus neque orci, porta a, aliquet quis, semper a, massa.
Phasellus purus.
Pellentesque tristique imperdiet tortor.
Nam euismod tellus id erat.
")
(defvar test-file1 "
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Donec hendrerit tempor tellus.
Donec pretium posuere tellus.
Proin quam nisl, tincidunt et, mattis eget, convallis nec, purus.
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
Aliquam erat volutpat.
Nunc eleifend leo vitae magna.
In id erat non orci commodo lobortis.
Nullam tristique diam non turpis.
Cras placerat accumsan nulla.
Nullam rutrum.
Nam vestibulum accumsan nisl.
Aliquam erat volutpat.
Nunc eleifend leo vitae magna.
In id erat non orci commodo lobortis.
Proin neque massa, cursus ut, gravida ut, lobortis eget, lacus.
Sed diam.
Praesent fermentum tempor tellus.
Nullam tempus.
Mauris ac felis vel velit tristique imperdiet.
Donec at pede.
Etiam vel neque nec dui dignissim bibendum.
Vivamus id enim.
Phasellus neque orci, porta a, aliquet quis, semper a, massa.
Phasellus purus.
Nam euismod tellus id erat.
")
(defvar test-file2 "
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Donec hendrerit tempor tellus.
Donec pretium posuere tellus.
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
Proin quam nisl, tincidunt et, mattis eget, convallis nec, purus.
Aliquam erat volutpat.
Nunc eleifend leo vitae magna.
In id erat non orci commodo lobortis.
Nullam tristique diam non turpis.
Cras accumsan eleifend nulla.
Nullam rutrum.
Nam vestibulum accumsan nisl.
Aliquam erat volutpat.
Nunc eleifend leo vitae magna.
In id erat non orci commodo lobortis.
Proin neque massa, cursus ut, gravida ut, lobortis eget, lacus.
Sed diam.
Praesent fermentum tempor tellus.
Nullam tempus.
Mauris ac felis vel velit tristique imperdiet.
Donec at pede.
Etiam vel neque nec dui dignissim bibendum.
Vivamus id enim.
Phasellus neque orci, porta a, aliquet quis, semper a, massa.
Phasellus purus.
Nam euismod tellus id erat.
")
(def-fixture repository-with-changes ()
(with-test-repository ()
(let* ((commit1-content
(make-test-commit
(random-commit
:files `((:filename "test-file"
:text ,test-file)))))
(commit2-content
(make-test-commit
(random-commit
:parents (getf commit1-content :sha)
:files `((:filename "test-file"
:text ,test-file1))))))
(bind-git-commits (((commit1 :sha (getf commit1-content :sha))
(commit2 :sha (getf commit2-content :sha)))
*test-repository* )
(&body)))))
(def-fixture repository-with-unstaged ()
(with-test-repository ()
(let* ((commit1-content
(make-test-commit
(random-commit
:files `((:filename "test-file"
:text ,test-file))))))
(funcall #'write-string-to-file "test-file" test-file1)
(bind-git-commits (((commit1 :sha (getf commit1-content :sha)))
*test-repository*)
(&body)))))
(def-fixture repository-with-staged ()
(with-test-repository ()
(let* ((commit1-content
(make-test-commit
(random-commit
:files `((:filename "test-file"
:text ,test-file))))))
(write-string-to-file "test-file" test-file1)
(with-index (*test-repository-index* *test-repository*)
(index-add-file "test-file" *test-repository-index*)
(index-write *test-repository-index*))
(write-string-to-file "test-file" test-file2)
(bind-git-commits (((commit1 :sha (getf commit1-content :sha)))
*test-repository*)
(&body)))))
(defvar repository-with-changes-diff
(with-open-file (stream (merge-pathnames "repository-with-changes.diff"
#.(or *compile-file-truename* *load-truename*)))
(let ((string (make-string (file-length stream))))
(read-sequence string stream)
string)))
| 6,127 | Common Lisp | .lisp | 163 | 32.90184 | 91 | 0.707485 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | c492730352694efadffc003b3c12f5732d2034d1a39bac79681b47c8fded86e4 | 3,824 | [
-1
] |
3,825 | libgit2.lisp | russell_cl-git/tests/libgit2.lisp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
;; cl-git an Common Lisp interface to git repositories.
;; Copyright (C) 2011-2022 Russell Sim <[email protected]>
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 of
;; the License, or (at your option) any later version.
;;
;; This program 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this program. If not, see
;; <http://www.gnu.org/licenses/>.
(in-package #:cl-git-tests)
(in-suite :cl-git)
(def-test libgit2-version ()
"Check the format of the version number."
(destructuring-bind (major minor revision)
(libgit2-version)
(is (integerp major))
(is (integerp minor))
(is (integerp revision))))
(def-test libgit2-features ()
"Check that the capabilities of libgit2, can only really check it's
a list."
(let ((capabilities (libgit2-features)))
(is (listp capabilities))))
| 1,307 | Common Lisp | .lisp | 31 | 40.032258 | 70 | 0.734854 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 754bb86bfb9c79329b8803a83a09a4b5f8ad44ee1c31b146a87d727c6b0e6e3f | 3,825 | [
-1
] |
3,826 | cl-git.asd | russell_cl-git/cl-git.asd | ;;;; cl-git.asd
(eval-when (:compile-toplevel :load-toplevel :execute)
#+quicklisp
(ql:quickload 'cffi-grovel :silent t)
(asdf:oos 'asdf:load-op :cffi-grovel))
(defsystem "cl-git"
:description "A CFFI wrapper of libgit2."
:version (:read-file-form "version.lisp-expr")
;; https://github.com/quicklisp/quicklisp-client/issues/108 There
;; will be errors if loading without first calling `(ql:quickload
;; 'cffi :silent t)'
:defsystem-depends-on (:asdf :cffi-grovel)
:depends-on ("cffi"
"local-time"
"cl-fad"
"flexi-streams"
"trivial-garbage"
"anaphora"
"alexandria"
"closer-mop"
"uiop")
:author "Russell Sim <[email protected]>"
:licence "Lisp-LGPL"
:pathname "src/"
:components
((:file "package")
(:file "git-pointer"
:depends-on ("package"))
(:file "libgit2" :depends-on ("package"
"libgit2-lib"
"libgit2-types"
"libgit2-types-grovel1"))
(:file "libgit2-lib" :depends-on ("package"))
(:file "libgit2-types" :depends-on ("package"
"git-pointer"
"libgit2-features"
"libgit2-types-grovel0"))
(:file "libgit2-features" :depends-on ("package"
"libgit2-lib"))
(cffi-grovel:grovel-file "libgit2-types-grovel0"
:depends-on ("package"
"libgit2-features"
"libgit2-lib"))
(cffi-grovel:grovel-file "libgit2-types-grovel1"
:depends-on ("package"
"libgit2-features"
"libgit2-types"
"libgit2-types-grovel0"))
(:file "api" :depends-on ("package"))
(:file "buffer" :depends-on ("libgit2"))
(:file "error" :depends-on ("libgit2"))
(:file "strarray" :depends-on ("libgit2"))
(:file "proxy" :depends-on ("libgit2"))
(:file "message" :depends-on ("libgit2" "commit"))
(:file "oid" :depends-on ("api" "libgit2"))
(:file "object" :depends-on ("git-pointer" "repository" "oid"))
(:file "signature" :depends-on ("libgit2"))
(:file "index" :depends-on ("git-pointer" "signature" "oid"))
(:file "repository" :depends-on ("git-pointer"))
(:file "references" :depends-on ("object"))
(:file "reflog" :depends-on ("git-pointer"))
(:file "branch" :depends-on ("object"))
(:file "commit" :depends-on ("object" "tree" "signature"))
(:file "graph" :depends-on ("oid" "repository"))
(:file "tag" :depends-on ("object"))
(:file "diff" :depends-on ("libgit2-types" "git-pointer" "tree" "buffer"))
(:file "blob" :depends-on ("object"))
(:file "tree" :depends-on ("object" "blob"))
(:file "config" :depends-on ("git-pointer"))
(:file "status" :depends-on ("git-pointer"))
(:file "revwalk" :depends-on ("git-pointer"))
(:file "remote" :depends-on ("object" "credentials"))
(:file "odb" :depends-on ("object"))
(:file "checkout" :depends-on ("object"))
(:file "clone" :depends-on ("checkout" "credentials" "remote"))
(:file "credentials" :depends-on ("object")))
:in-order-to ((test-op (test-op "cl-git/tests"))))
(defsystem "cl-git/tests"
:defsystem-depends-on (:asdf)
:depends-on ("cl-git"
"fiveam"
"cl-fad"
"unix-options"
"inferior-shell"
"local-time"
"alexandria"
"flexi-streams")
:version (:read-file-form "version.lisp-expr")
:licence "Lisp-LGPL"
:pathname "tests/"
:components
((:file "package")
(:file "common" :depends-on ("package"))
(:file "fixtures" :depends-on ("package"))
(:file "commit" :depends-on ("common"))
(:file "clone" :depends-on ("common" "fixtures"))
(:file "checkout" :depends-on ("common"))
(:file "index" :depends-on ("common" "fixtures"))
(:file "repository" :depends-on ("common" "fixtures"))
(:file "remote" :depends-on ("common" "fixtures"))
(:file "strings" :depends-on ("common" "fixtures"))
(:file "tag" :depends-on ("common" "fixtures"))
(:file "diff" :depends-on ("common" "fixtures"))
(:file "tree" :depends-on ("common" "fixtures"))
(:file "graph" :depends-on ("common" "fixtures"))
(:file "message" :depends-on ("common" "fixtures"))
(:file "config" :depends-on ("common" "fixtures"))
(:file "odb" :depends-on ("common" "fixtures"))
(:file "blob" :depends-on ("common" "fixtures"))
(:file "references" :depends-on ("common"))
(:file "error" :depends-on ("common"))
(:file "revwalker" :depends-on ("common"))
(:file "libgit2" :depends-on ("common")))
:in-order-to ((compile-op (load-op :cl-git)))
:perform (test-op (o c) (symbol-call :fiveam '#:run! :cl-git)))
| 5,034 | Common Lisp | .asd | 115 | 34.33913 | 77 | 0.553408 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | ef7708e826fa7c0f8353f096318f28977d076279300ade5d9af4834ee9ece8e6 | 3,826 | [
-1
] |
3,828 | .balanced-parentheses.sexp | russell_cl-git/.balanced-parentheses.sexp | ;;; -*- Mode: Lisp; Syntax: COMMON-LISP; Base: 10 -*-
(deftask prepare-release (:summary "Prepare to release a new version.")
(format t "working dir is ~a~%" (working-directory*))
(with-changes (:changes (changes-from-git))
(with-semantic-version (:current (highest-git-tag))
(setf (next-version*) (version-from-conventional-commits))
(write-version-sexp-file "version.lisp-expr")
(write-changelog-file "CHANGELOG" :rst
:style :conventional-commits
:after "---------"
:header-char "~")
(prin1 (changelog-lines :markdown :conventional-commits))
(write-file ".git/RELEASE_CHANGELOG"
(format nil "Release ~a~%~%~a"
(next-version*)
(changelog-lines :markdown :conventional-commits))))))
(deftask release-new-version (:summary "Release a new version.")
(format t "working dir is ~a~%" (working-directory*))
(with-changes (:changes (changes-from-git))
(with-semantic-version (:current (highest-git-tag))
(setf (next-version*) (version-from-conventional-commits))
(let ((message (read-file ".git/RELEASE_CHANGELOG")))
(git-commit-changes
:message message
:author '(:name "Russell Sim"
:email "[email protected]"))
(git-create-tag
:message message
:author '(:name "Russell Sim"
:email "[email protected]"))))))
| 1,509 | Common Lisp | .l | 30 | 39.1 | 80 | 0.582373 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 7aad1c447db32c6d78fd103ea6ebd0edafb05a494e2361f9c44b5f69c368b9ac | 3,828 | [
-1
] |
3,831 | Earthfile | russell_cl-git/Earthfile | VERSION 0.6
FROM debian:stable
WORKDIR /cl-git
ENV ROSWELL_DIST=https://raw.githubusercontent.com/roswell/roswell/master/scripts/install-for-ci.sh
libgit2:
ARG --required LIBGIT2_VERSION
RUN apt-get update && apt-get install -y curl cmake gcc libssl-dev libcurl4-gnutls-dev libssh2-1-dev
RUN curl -L https://github.com/libgit2/libgit2/archive/v${LIBGIT2_VERSION}.tar.gz > v${LIBGIT2_VERSION}.tar.gz
RUN tar -zxf v${LIBGIT2_VERSION}.tar.gz
RUN mkdir libgit-build
RUN cd libgit-build && \
cmake -DBUILD_TESTS=OFF -DBUILD_CLAR=OFF -DCMAKE_VERBOSE_MAKEFILE=ON ../libgit2-${LIBGIT2_VERSION} && \
cmake --build . && \
cmake --build . --target install
RUN ldconfig
deps:
FROM +libgit2
ENV CI=true
ENV PATH="~/.roswell/bin:$PATH"
RUN apt-get update && apt-get install -y curl make bzip2 libcurl3-gnutls zlib1g-dev lsof build-essential chrpath install-info texinfo file
RUN curl -L $ROSWELL_DIST | sh
build:
FROM +deps
COPY cl-git.asd version.lisp-expr run-tests.lisp ./src/ ./tests/ /root/.roswell/local-projects/cl-git/
COPY src /root/.roswell/local-projects/cl-git/src
COPY tests /root/.roswell/local-projects/cl-git/tests
test-libgit2-sbcl:
FROM +build
RUN ros install sbcl-bin
RUN ros use sbcl-bin
test-libgit2-ecl:
FROM +build
RUN apt update && apt install -y libgmp-dev
RUN ros install ecl/21.2.1
RUN ros use ecl
test-libgit2-ccl:
FROM +build
RUN ros install ccl-bin/1.12
RUN ros use ccl-bin
test-libgit2-clasp:
FROM +build
RUN apt update && apt install -y libelf1 libllvm9 libgmpxx4ldbl locales-all
RUN ros install clasp-bin
RUN ros use clasp-bin
test-libgit2-0.27-sbcl:
FROM +test-libgit2-sbcl --LIBGIT2_VERSION=0.27.10
RUN /root/.roswell/local-projects/cl-git/run-tests.lisp
test-libgit2-0.28-sbcl:
FROM +test-libgit2-sbcl --LIBGIT2_VERSION=0.28.5
RUN /root/.roswell/local-projects/cl-git/run-tests.lisp
test-libgit2-1.0-sbcl:
FROM +test-libgit2-sbcl --LIBGIT2_VERSION=1.0.1
RUN /root/.roswell/local-projects/cl-git/run-tests.lisp
test-libgit2-1.1-sbcl:
FROM +test-libgit2-sbcl --LIBGIT2_VERSION=1.1.1
RUN /root/.roswell/local-projects/cl-git/run-tests.lisp
test-libgit2-1.2-sbcl:
FROM +test-libgit2-sbcl --LIBGIT2_VERSION=1.2.0
RUN /root/.roswell/local-projects/cl-git/run-tests.lisp
test-libgit2-1.3-sbcl:
FROM +test-libgit2-sbcl --LIBGIT2_VERSION=1.3.2
RUN /root/.roswell/local-projects/cl-git/run-tests.lisp
test-libgit2-1.4-sbcl:
FROM +test-libgit2-sbcl --LIBGIT2_VERSION=1.4.4
RUN /root/.roswell/local-projects/cl-git/run-tests.lisp
test-libgit2-1.5-sbcl:
FROM +test-libgit2-sbcl --LIBGIT2_VERSION=1.5.0
RUN /root/.roswell/local-projects/cl-git/run-tests.lisp
test-libgit2-1.5-ecl:
FROM +test-libgit2-ecl --LIBGIT2_VERSION=1.5.0
RUN /root/.roswell/local-projects/cl-git/run-tests.lisp
test-libgit2-1.5-ccl:
FROM +test-libgit2-ccl --LIBGIT2_VERSION=1.5.0
RUN /root/.roswell/local-projects/cl-git/run-tests.lisp
test-libgit2-1.5-clasp:
FROM +test-libgit2-clasp --LIBGIT2_VERSION=1.5.0
RUN /root/.roswell/local-projects/cl-git/run-tests.lisp
| 3,196 | Common Lisp | .l | 77 | 37.25974 | 142 | 0.724605 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 910d379f8fca50bce1f3b35c097efa6dde1fbd284a9bda0ab7b50cee38524842 | 3,831 | [
-1
] |
3,868 | doc.yml | russell_cl-git/.builds/doc.yml | image: debian/bullseye
arch: amd64
secrets:
- 9e3bc7b6-11d3-4f20-85a0-ac35c55b0548
- c0b0af54-29b4-45a2-abe3-961a84ca672a
environment:
ROSWELL_DIST: https://raw.githubusercontent.com/roswell/roswell/master/scripts/install-for-ci.sh
CI: true
packages:
- bzip2
- curl
- emacs-nox
- fonts-freefont-otf
- graphviz
- imagemagick
- jq
- latexmk
- libcurl3-gnutls
- libgit2-dev
- lmodern
- make
- python3-pip
- python3.9-full
- s3cmd
- tex-gyre
- texinfo
- texlive-fonts-extra
- texlive-fonts-recommended
- texlive-lang-chinese
- texlive-lang-cjk
- texlive-lang-japanese
- texlive-latex-extra
- texlive-latex-recommended
- texlive-luatex
- texlive-xetex
- xindy
- zlib1g-dev
sources:
- https://git.sr.ht/~rsl/cl-git
shell: false
tasks:
- build: |
curl -L $ROSWELL_DIST | sh
export PATH="$HOME/.roswell/bin:$HOME/.local/bin:$PATH"
cd cl-git
./doc/install-dependencies.ros
./doc/build.sh
- publish: |
cd cl-git
s3cmd sync doc/build/html/ s3://cl-git/
- update-readme: |
cd cl-git
export SOURCEHUT_TOKEN=$(cat ~/.source_hut_token)
./scripts/update_sourcehut_readme.sh
| 1,193 | Common Lisp | .l | 54 | 18.592593 | 98 | 0.691901 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 7bbddbd7e244349248d3dd8b1574fdc10c1dfe8e42c90337be77efcb097d0f0a | 3,868 | [
-1
] |
3,869 | ci.yml | russell_cl-git/.builds/ci.yml | image: debian/bullseye
arch: amd64
environment:
packages:
- wget
- docker.io
sources:
- https://git.sr.ht/~rsl/cl-git
shell: false
tasks:
- enable-docker: |
sudo adduser build docker
- install-earthly: |
sudo /bin/sh -c 'wget https://github.com/earthly/earthly/releases/latest/download/earthly-linux-amd64 -O /usr/local/bin/earthly && chmod +x /usr/local/bin/earthly'
earthly bootstrap
- sbcl-with-libgit2-0-27: |
cd cl-git
earthly +test-libgit2-0.27-sbcl
- sbcl-with-libgit2-0-28: |
cd cl-git
earthly +test-libgit2-0.28-sbcl
- sbcl-with-libgit2-1-0: |
cd cl-git
earthly +test-libgit2-1.0-sbcl
- sbcl-with-libgit2-1-1: |
cd cl-git
earthly +test-libgit2-1.1-sbcl
- sbcl-with-libgit2-1-2: |
cd cl-git
earthly +test-libgit2-1.2-sbcl
- sbcl-with-libgit2-1-3: |
cd cl-git
earthly +test-libgit2-1.3-sbcl
- sbcl-with-libgit2-1-4: |
cd cl-git
earthly +test-libgit2-1.4-sbcl
- sbcl-with-libgit2-1-5: |
cd cl-git
earthly +test-libgit2-1.5-sbcl
| 1,082 | Common Lisp | .l | 39 | 22.948718 | 169 | 0.654106 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | b9f44b2c312cedc896d6e60a9d05455168814a922e561e240357f2481e0d1089 | 3,869 | [
-1
] |
3,894 | install-dependencies.ros | russell_cl-git/doc/install-dependencies.ros | #!/bin/sh
#|-*- mode:lisp -*-|#
#|
exec ros -Q -- $0 "$@"
|#
(progn ;;init forms
(ros:ensure-asdf)
#+quicklisp
(ql:quickload '(cffi-grovel)))
(defpackage :ros.script.install-dependencies.3867652984
(:use :cl))
(in-package :ros.script.install-dependencies.3867652984)
(defun main (&rest argv)
(declare (ignorable argv)))
;;; vim: set ft=lisp lisp:
| 359 | Common Lisp | .l | 15 | 22.133333 | 56 | 0.678363 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 698f29e13c4a5b76aba73b1050909c32ca8332de0e094f1be6b7166772f9d3c2 | 3,894 | [
-1
] |
3,895 | build.sh | russell_cl-git/doc/build.sh | #!/bin/bash
DIR=$(cd $(dirname "${BASH_SOURCE[0]}") && pwd)
if [ -z "$VIRTUAL_ENV" ]; then
(cd $DIR; python3 -m venv .venv)
echo "Using virtualenv $DIR/.venv/"
source $DIR/.venv/bin/activate
fi
(cd $DIR; pip install -U -r requirements.txt)
(cd $DIR; make latexpdf)
(cd $DIR; make info)
(cd $DIR; make html)
| 322 | Common Lisp | .l | 11 | 26.909091 | 47 | 0.642857 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 04de86f5ca2672f536445d16ddacf99bc0b206ecef1911049a3afbe70fc88b71 | 3,895 | [
-1
] |
3,896 | Makefile | russell_cl-git/doc/Makefile | # Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = .
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
| 633 | Common Lisp | .l | 16 | 38.1875 | 72 | 0.707993 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 34e311d27fed99f90806e482549c0ac9aa320d65926e4e2d1dd65788409dd642 | 3,896 | [
-1
] |
3,897 | style.css | russell_cl-git/doc/style.css | .node { visibility:hidden; height: 0px; }
.menu { visibility:hidden; height: 0px; }
.appendix { background-color:#a4bbff; padding: 0.2em; }
.chapter { background-color:#a4bbff; padding: 0.2em; }
.section { background-color:#a4bbff; padding: 0.2em; }
.settitle { background-color:#a4bbff; }
.contents { border: 2px solid black;
margin: 1cm 1cm 1cm 1cm;
padding-left: 3mm; }
.lisp { padding: 0; margin: 0em; background-color: lightgray;}
code { font-family: sans-serif; font-style: italic;}
body { padding: 2em 8em; font-family: sans-serif; }
h1 { padding: 1em; text-align: center; }
li { margin: 1em; }
| 655 | Common Lisp | .l | 14 | 42 | 64 | 0.657813 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 98d6fc9e7fc7dd6326a322bda0b3553273b69f1fd9e71e59bd9783c0e838cc0a | 3,897 | [
-1
] |
3,898 | internals.rst | russell_cl-git/doc/low-level/internals.rst | Internals
=========
.. cl:package:: cl-git
Libgit2
-------
.. cl:function:: libgit2-capabilities
.. cl:function:: libgit2-version
Memory Management
-----------------
Because C has manual memory management and Lisp automatic memory
management there is the question on how these two systems integrate.
First most libgit2 objects need to be freeed. There are different free
calls in libgit2, but in CL-git they are all replaced by git-free.
Second of all, this call is made optional. The package
‘trivial-garbage’ takes care of freeing the object when the garbage
collector collects the Lisp git object wrappers.
So normally you do not have to call the free explicitly. However there
are a few reasons you might want to do it anyway:
* Having a repository and commit objects open has the side effect that
file descriptors to the underlying git files stay open. When you
iterate over may commits manually (not using the convenience macros)
can trigger the Lisp process to run out of available file handles.
* Some libgit2 calls can potentially allocate lots of memory. Because
the Lisp garbage collector does not see the memory allocated by the
libgit2 library, it helps to call the git-free call to avoid usage
build up.
.. cl:generic:: free
Object that have been freed have `(disposed)` in their title when
printed.
Lazy Loading
~~~~~~~~~~~~
Some types like references are lazy loaded when possible. This can be
seen when they are printed.
.. code-block:: common-lisp-repl
GIT> (list-objects 'reference (open-repository #p"/home/russell/projects/ecl/"))
(...
#<REFERENCE refs/tags/ECL.0.9f (weak) {100657CCB3}>
...)
The `(weak)` identifier shows that this object hasn't been looked up
in the odb yet.
Dependant Objects
~~~~~~~~~~~~~~~~~
Some objects, such as commits, are only valid as long as another
object is valid, like a repository. This means that as soon as a
repository is git-free'ed the commit becomes invalid. Also conversely,
as long as we keep a reference to a commit and we expect that one to
be valid, the repository can not be collected. We call the commit the
depend object and the repository the facilitating object.
These dependencies are handled in CL-git in the following way:
* When a facilitating object is explicitly freed, or when a
convenience macro such as with-repository frees the object because
the execution path leaves scope, all dependend objects on that
facilitating object are freed.
* Any depenend object holds a reference to its facilitator as long as
it is not freed.
The consequences are that the following is not correct
.. code-block:: common-lisp
(with-repository (..)
(object-get ...))
Because the returned object from the lookup call is not valid anymore
because the repository is closed.
However the following, although uncertain when the repository is
closed, is correct
.. code-block:: common-lisp
(object-get ... (repository-open ...))
| 2,967 | Common Lisp | .l | 65 | 43.353846 | 84 | 0.771269 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 8150350de20cf3739ef6762536884ab65b9ea379cdcbcc3bfbc7f0efdb060056 | 3,898 | [
-1
] |
3,899 | page.html | russell_cl-git/doc/_templates/page.html | {%- extends "layout.html" %}
{% block body %}
{% if pagename == 'index' %}
<div class="jumbotron">
<h1>CL-GIT</h1>
</div>
{% endif %}
{{ body }}
{% endblock %}
| 180 | Common Lisp | .l | 9 | 16.777778 | 30 | 0.508772 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | cf7f484a57c266216e35f73bd3246ac6624dd818249318c4a9a370e5248d3059 | 3,899 | [
-1
] |
3,900 | index.html | russell_cl-git/doc/_templates/index.html | {%- extends "layout.html" %}
{% block body %}
<div class="jumbotron">
<h1>Hello, world!</h1>
<p>...</p>
</div>
{{ body }}
{% endblock %}
| 151 | Common Lisp | .l | 8 | 16.125 | 28 | 0.517483 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 93f8452556835cd81d4600b0683adc6fab985c15d32da2bf609064ad35689e36 | 3,900 | [
-1
] |
3,901 | glossary.rst | russell_cl-git/doc/usage/glossary.rst | Glossary
========
.. glossary::
oid
The Object Identifier of an object is normally known as it's
sha1 hash, this can be represented as either a string or as a 46
digit number.
| 199 | Common Lisp | .l | 7 | 24.142857 | 70 | 0.678947 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 8b666432887e8e3957bf3f5dc04b05544b34b925d23dbb646eb49f120fb651e9 | 3,901 | [
-1
] |
3,902 | reflog.rst | russell_cl-git/doc/usage/reflog.rst | Reference Logs
==============
.. cl:package:: cl-git
.. cl:generic:: reflog
.. cl:method:: entries cl-git:reflog
.. cl:method:: message cl-git:reflog-entry
.. cl:method:: commiter cl-git:reflog-entry
| 205 | Common Lisp | .l | 7 | 27.571429 | 43 | 0.678756 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 924230c7086f525f13b57bdfcd58e11e46fa7e1f54a4c36956cb3e51964cc459 | 3,902 | [
-1
] |
3,903 | blob.rst | russell_cl-git/doc/usage/blob.rst | Blob
====
.. cl:package:: cl-git
.. cl:type:: blob
.. cl:generic:: blob-size
.. cl:generic:: blob-content
.. cl:generic:: binary-p
Accessing
---------
Blobs can be accessed usually via :cl:symbol:`TREE` objects or
directly by :term:`OID`.
.. cl:method:: get-object blob common-lisp:t common-lisp:t
.. cl:method:: list-objects blob common-lisp:t
Content
-------
Before we dive into this, we can get the content of the file by
extracting the :term:`OID`, "6AEF1FC9F802DB1D903200F39E1D776CE355565F"
and lookup this object:
.. code-block:: common-lisp-repl
GIT> (get-object 'blob "6AEF1FC9F802DB1D903200F39E1D776CE355565F"
(open-repository (merge-pathnames #p"projects/ecl"
(user-homedir-pathname))))
#<BLOB 6AEF1FC9F802DB1D903200F39E1D776CE355565F {10068F1493}>
A blob is just raw data, stored as raw bytes. Basically everything in
the git database is stored as blobs. So to extract the content we can
do
.. code-block:: common-lisp-repl
GIT> (blob-content
(get-object 'blob "6AEF1FC9F802DB1D903200F39E1D776CE355565F"
(open-repository (merge-pathnames #p"projects/ecl"
(user-homedir-pathname)))))
#(35 33 47 98 105 110 47 115 104 10 35 10 35 32 84 104 105 115 32 105 115 32
106 117 115 116 32 97 32 100 114 105 118 101 114 32 102 111 114 32 99 111 110
102 105 103 117 114 101 44 32 116 104 101 32 114 101 97 108 32 99 111 110 102
105 103 117 114 101 32 105 115 32 105 110 32 115 114 99 46 10 35 32 84 104
105 115 32 115 99 114 105 112 116 32 105 100 101 110 116 105 102 105 101 115
32 116 104 101 32 109 97 99 104 105 110 101 44 32 97 110 100 32 99 114 ....)
If the content is of a string type then we can print it's contents.
.. code-block:: common-lisp-repl
GIT> (binary-p
(get-object 'blob "6AEF1FC9F802DB1D903200F39E1D776CE355565F"
(open-repository (merge-pathnames #p"projects/ecl"
(user-homedir-pathname)))))
NIL
Since this is a string then we can convert it, `flexi-streams`_ has a
convenient mechanism to convent this to a string.
.. _flexi-streams: http://weitz.de/flexi-streams/
.. code-block:: common-lisp-repl
GIT> (flexi-streams:octets-to-string
(blob-content
(get-object 'blob "6AEF1FC9F802DB1D903200F39E1D776CE355565F"
(open-repository (merge-pathnames #p"projects/ecl"
(user-homedir-pathname))))))
"#!/bin/sh
#
# This is just a driver for configure, the real configure is in src.
# This script identifies the machine, and creates a directory for
# the installation, where it runs ${srcdir}/configure.
set -e
#if uname -a | grep -i 'mingw32' > /dev/null; then
# srcdir=`pwd -W`/src;
| 2,926 | Common Lisp | .l | 61 | 39.918033 | 84 | 0.652572 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | c3e64c40c729013811689f32d89ed5ea0396ac4efc5e29282922d05b49ceb4e6 | 3,903 | [
-1
] |
3,904 | Dockerfile.testserver | russell_cl-git/scripts/Dockerfile.testserver | FROM ubuntu:focal
RUN apt-get update
RUN DEBIAN_FRONTEND=noninteractive apt-get -y install git openssh-client openssh-server
RUN useradd -rm -d /home/git -s /bin/bash -u 1000 git
RUN echo 'git:test1234' | chpasswd
RUN mkdir /home/git/.ssh
COPY id_gituser_rsa id_gituser_rsa.pub /home/git/.ssh/
COPY id_gituser_rsa.pub /home/git/.ssh/authorized_keys
COPY environment /home/git/.ssh/
RUN chmod 600 -R /home/git/.ssh && \
chmod 700 /home/git/.ssh && \
chown git:git -R /home/git/.ssh
# Add git repositories
RUN git init --bare /home/git/test.git && \
chown git:git -R /home/git/test.git
RUN git init --bare /home/git/test-push-options.git && \
git config -f /home/git/test-push-options.git/config receive.advertisePushOptions true && \
chown git:git -R /home/git/test-push-options.git
# Setup SSH
RUN echo 'PermitUserEnvironment yes' >> /etc/ssh/sshd_config
RUN mkdir /var/run/sshd
EXPOSE 22
CMD ["/usr/sbin/sshd", "-D", "-e"]
# CMD ["/usr/bin/git", "daemon", "--verbose", "--listen=0.0.0.0", "--port=9419", "--export-all", "--enable=receive-pack", "--base-path=/home/git/", "/home/git/"]
| 1,110 | Common Lisp | .l | 24 | 44.25 | 161 | 0.705176 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 9a44bae3c222415cfe934dd10acdf1ed3ffe9e30727893fc6acd54c3b0a6682d | 3,904 | [
-1
] |
3,905 | build_test_git_server.sh | russell_cl-git/scripts/build_test_git_server.sh | #!/bin/bash
DIR="$( cd "$( dirname "$0" )" && pwd )"
cd $DIR
if [ ! -e id_gituser_rsa ]; then
ssh-keygen -t rsa -b 4096 -C "[email protected]" -f id_gituser_rsa -N ""
fi
docker build -t cl-git-test:latest -f Dockerfile.testserver .
# docker run --rm -it --name cl-git-test -p 2222:22 cl-git-test:latest
| 315 | Common Lisp | .l | 8 | 37 | 77 | 0.643333 | russell/cl-git | 54 | 18 | 0 | LGPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | ba1a50aeede33c5d519ef5740db1d668c73db2ec1b4a7ff71b8fb1966594499f | 3,905 | [
-1
] |
3,921 | compile-and-tests.lisp | spwhitton_consfigurator/debian/tests/compile-and-tests.lisp | (require "asdf")
;; this in itself ensures that we've listed the files in consfigurator.asd in
;; the correct order
(let ((asdf:*compile-file-failure-behaviour* :error)
(asdf:*compile-file-warnings-behaviour* :error)
(asdf:*user-cache* (uiop:getenv "AUTOPKGTEST_TMP")))
(asdf:load-system "consfigurator/tests"))
;; We can't use ASDF:TEST-SYSTEM because its return value does not indicate
;; whether any tests failed. We have to switch the package back and forth as
;; CL-USER has no *CONSFIG*.
(let ((*package* (find-package :consfigurator/tests)))
;; Set TMPDIR so UIOP temporary file utilities use AUTOPKGTEST_TMP.
(setf (uiop:getenv "TMPDIR") (uiop:getenv "AUTOPKGTEST_TMP"))
(unless (consfigurator/tests::runner)
(uiop:quit 2)))
(fresh-line)
| 774 | Common Lisp | .lisp | 16 | 45.6875 | 77 | 0.73245 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 23180b6e5c45a14f14bfc2a9178eeaea03d8c6691ef9c8216c09cf41611056ef | 3,921 | [
-1
] |
3,922 | package.lisp | spwhitton_consfigurator/src/package.lisp | (in-package :cl-user)
(defpackage :consfigurator
(:use #:cl #:anaphora #:alexandria #:cffi)
(:local-nicknames (#:re #:cl-ppcre))
(:shadowing-import-from #:uiop
#:strcat
#:string-prefix-p
#:string-suffix-p
#:split-string
#:first-char
#:last-char
#:run-program
#:read-file-string
#:copy-stream-to-stream
#:slurp-stream-string
#:subprocess-error
#:stripln
#:println
#:unix-namestring
#:parse-unix-namestring
#:pathname-directory-pathname
#:pathname-parent-directory-pathname
#:resolve-symlinks
#:with-temporary-file
#:ensure-directory-pathname
#:ensure-pathname
#:enough-pathname
#:pathname-equal
#:subpathp
#:relative-pathname-p
#:absolute-pathname-p
#:directory-pathname-p
#:getenv
#:subdirectories
#:directory-files
#:file-exists-p
#:directory-exists-p
#:rename-file-overwriting-target
#:with-current-directory
#:delete-empty-directory
#:delete-directory-tree
#:with-safe-io-syntax
#:slurp-stream-form
#:safe-read-file-form
#:safe-read-from-string
#:compile-file*
#:compile-file-pathname*)
(:shadowing-import-from #:parse-number #:parse-number)
(:export ;; re-export from UIOP
#:strcat
#:string-prefix-p
#:string-suffix-p
#:split-string
#:first-char
#:last-char
#:run-program
#:read-file-string
#:copy-stream-to-stream
#:slurp-stream-string
#:subprocess-error
#:stripln
#:println
#:unix-namestring
#:parse-unix-namestring
#:pathname-directory-pathname
#:pathname-parent-directory-pathname
#:resolve-symlinks
#:with-temporary-file
#:ensure-directory-pathname
#:ensure-pathname
#:enough-pathname
#:pathname-equal
#:subpathp
#:relative-pathname-p
#:absolute-pathname-p
#:directory-pathname-p
#:getenv
#:subdirectories
#:directory-files
#:file-exists-p
#:directory-exists-p
#:rename-file-overwriting-target
#:with-current-directory
#:delete-empty-directory
#:delete-directory-tree
#:with-safe-io-syntax
#:slurp-stream-form
#:safe-read-file-form
#:safe-read-from-string
#:compile-file*
#:compile-file-pathname*
;; re-export from PARSE-NUMBER
#:parse-number
;; libc.lisp
#:uid_t
#:gid_t
#:CLONE_NEWCGROUP
#:CLONE_NEWIPC
#:CLONE_NEWNET
#:CLONE_NEWNS
#:CLONE_NEWPID
#:CLONE_NEWTIME
#:CLONE_NEWUSER
#:CLONE_NEWUTS
#:NS_GET_OWNER_UID
;; util.lisp
#:multiple-value-mapcan
#:lines
#:unlines
#:words
#:unwords
#:strip-prefix
#:memstr=
#:define-simple-error
#:plist-to-long-options
#:systemd-user-instance-args
#:with-local-temporary-directory
#:pathname-file
#:local-directory-contents
#:ensure-trailing-slash
#:drop-trailing-slash
#:define-simple-print-object
#:chroot-pathname
#:in-chroot-pathname
#:sh-escape
#:defpackage-consfig
#:lambda-ignoring-args
#:parse-cidr
#:random-alphanumeric
#:valid-hostname-p
#:prog-changes
#:add-change
#:return-changes
#:sh-script-to-single-line
#:*consfigurator-debug-level*
#:with-indented-inform
#:inform
#:informat
#:version<
#:version>
#:version<=
#:version>=
#:string-to-filename
#:filename-to-string
#:exit-code-to-retval
#:posix-login-environment
#:define-error-retval-cfun
#:chroot
#:unshare
#:mapc-open-input-streams
#:mapc-open-output-streams
;; connection.lisp
#:establish-connection
#:continue-connection
#:preprocess-connection-args
#:connection
#:lisp-connection
#:posix-connection
#:connection-parent
#:lisp-connection-p
#:connection-run
#:connection-read-file
#:connection-read-and-remove-file
#:connection-write-file
#:connection-tear-down
#:connection-connattr
#:propagate-connattr
#:run
#:mrun
#:with-remote-temporary-file
#:mkstemp-cmd
#:mktemp
#:with-remote-current-directory
#:run-failed
#:run-failed-cmd
#:run-failed-stdout
#:run-failed-stderr
#:run-failed-exit
#:runlines
#:remote-test
#:remote-exists-p
#:remote-exists-every-p
#:remote-exists-some-p
#:remote-file-stats
#:remote-last-reboot
#:remote-executable-find
#:remote-mount-point-p
#:delete-remote-trees
#:empty-remote-directory
#:read-remote-file
#:write-remote-file
#:get-connattr
#:with-connattrs
;; property.lisp
#:combine-propapp-types
#:propapp-type
#:propapp-args
#:propapp-desc
#:propapp-attrs
#:check-propapp
#:apply-propapp
#:unapply-propapp
#:ignoring-hostattrs
#:defprop
#:defpropspec
#:defproplist
#:inapplicable-property
#:get-hostattrs
#:get-hostattrs-car
#:get-parent-hostattrs
#:get-parent-hostattrs-car
#:push-hostattr
#:push-hostattrs
#:pushnew-hostattr
#:pushnew-hostattrs
#:get-hostname
#:get-short-hostname
#:require-data
#:failed-change
#:aborted-change
#:assert-remote-euid-root
#:maybe-write-remote-file-string
#:with-change-if-changes-file
#:with-change-if-changes-files
#:with-change-if-changes-file-content
#:ptype
#:plambda
#:papply
#:punapply
;; propspec.lisp
#:in-consfig
#:propspec-systems
#:propspec-props
#:make-propspec
#:append-propspecs
#:propapp
;; combinator.lisp
#:define-function-property-combinator
#:define-choosing-property-combinator
#:seqprops
#:eseqprops
#:eseqprops-until
#:silent-seqprops
#:unapply
#:unapplied
#:reapplied
#:desc
#:on-change
#:on-apply-change
#:as
#:with-flagfile
#:with-unapply
#:with-homedir
;; host.lisp
#:host
#:unpreprocessed-host
#:defhost
#:make-host
#:make-child-host
#:union-propspec-into-host
#:replace-propspec-into-host
#:hostattrs
#:host-propspec
#:preprocess-host
#:ensure-host
#:with-preserve-hostattrs
#:has-hostattrs
;; deployment.lisp
#:at-end
#:consfigure
#:defdeploy
#:defdeploy-these
#:deploy
#:deploy*
#:deploys
#:deploys.
#:deploy-these
#:deploys-these.
#:deploy-these*
#:deploys-these
#:hostdeploy
#:hostdeploy*
#:hostdeploy-these
#:hostdeploy-these*
#:localsudo
#:localhd
#:continue-deploy*
#:evals
;; data.lisp
#:data
#:data-iden1
#:data-iden2
#:data-version
#:data-mime
#:string-data
#:data-string
#:file-data
#:data-file
#:data-source-providing-p
#:maybe-write-remote-file-data
#:missing-data-source
#:data-pathname
#:local-data-pathname
#:remote-data-pathname
#:get-remote-cached-prerequisite-data
#:get-local-cached-prerequisite-data
#:get-highest-local-cached-prerequisite-data
#:try-register-data-source
#:register-data-source
#:reset-data-sources
#:get-data-stream
#:with-data-stream
#:get-data-string
#:connection-upload
#:connection-clear-data-cache
#:upload-all-prerequisite-data
#:wrapped-passphrase
#:wrap-passphrase
#:unwrap-passphrase
#:get-data-protected-string
#:*data-source-gnupghome*
#:with-reset-data-sources
#:missing-data
;; image.lisp
#:eval-in-grandchild
#:eval-in-reinvoked
#:wrong-execution-context-for-image-dump
#:image-dumped
#:asdf-requirements-for-host-and-features
#:request-asdf-requirements
#:continue-deploy*-program))
(macrolet
((package (package &body options &aux (use (find :use options :key #'car)))
`(defpackage ,package
(:use #:cl #:anaphora #:alexandria #:consfigurator ,@(cdr use))
,@(remove use options))))
(package :consfigurator.util.posix1e
(:use #:cffi)
(:export #:acl_type_t
#:acl_entry_t
#:ACL_USER
#:ACL_GROUP
#:ACL_TYPE_ACCESS
#:ACL_TYPE_DEFAULT
#:ACL_NEXT_ENTRY
#:ACL_FIRST_ENTRY
#:with-acl-free
#:acl-get-file
#:acl-set-file
#:acl-get-entry
#:acl-get-tag-type
#:acl-get-qualifier
#:acl-set-qualifier
#:CAP_CHOWN
#:CAP_DAC_OVERRIDE
#:CAP_DAC_READ_SEARCH
#:CAP_FOWNER
#:CAP_FSETID
#:CAP_KILL
#:CAP_SETGID
#:CAP_SETUID
#:CAP_SETPCAP
#:CAP_LINUX_IMMUTABLE
#:CAP_NET_BIND_SERVICE
#:CAP_NET_BROADCAST
#:CAP_NET_ADMIN
#:CAP_NET_RAW
#:CAP_IPC_LOCK
#:CAP_IPC_OWNER
#:CAP_SYS_MODULE
#:CAP_SYS_RAWIO
#:CAP_SYS_CHROOT
#:CAP_SYS_PTRACE
#:CAP_SYS_PACCT
#:CAP_SYS_ADMIN
#:CAP_SYS_BOOT
#:CAP_SYS_NICE
#:CAP_SYS_RESOURCE
#:CAP_SYS_TIME
#:CAP_SYS_TTY_CONFIG
#:CAP_MKNOD
#:CAP_LEASE
#:CAP_AUDIT_WRITE
#:CAP_AUDIT_CONTROL
#:CAP_SETFCAP
#:CAP_MAC_OVERRIDE
#:CAP_MAC_ADMIN
#:CAP_SYSLOG
#:CAP_WAKE_ALARM
#:CAP_BLOCK_SUSPEND
#:CAP_AUDIT_READ
#:CAP_PERFMON
#:CAP_BPF
#:CAP_CHECKPOINT_RESTORE
#:posix-capability-p))
(package :consfigurator.property.cmd
(:export #:single))
(package :consfigurator.property.file
(:local-nicknames (#:re #:cl-ppcre))
(:export #:map-remote-file-lines
#:has-content
#:exists-with-content
#:contains-lines
#:lacks-lines
#:lacks-lines-matching
#:has-mode
#:has-ownership
#:does-not-exist
#:directory-does-not-exist
#:empty-directory-does-not-exist
#:data-uploaded
#:host-data-uploaded
#:secret-uploaded
#:host-secret-uploaded
#:data-cache-purged
#:contains-conf-equals
#:contains-conf-unspaced
#:contains-conf-space
#:contains-conf-tab
#:contains-conf-shell
#:contains-ini-settings
#:regex-replaced-lines
#:directory-exists
#:containing-directory-exists
#:symlinked
#:is-copy-of
#:update-unix-table))
(package :consfigurator.property.etc-default
(:local-nicknames (#:file #:consfigurator.property.file))
(:export #:contains))
(package :consfigurator.property.os
(:shadow #:typecase #:etypecase)
(:export #:unixlike
#:linux
#:debianlike
#:debian
#:debian-stable
#:debian-testing
#:debian-unstable
#:debian-experimental
#:debian-suite
#:debian-architecture
#:debian-architecture-string
#:freebsd
#:freebsd-release
#:freebsd-devel
#:freebsd-architecture
#:freebsd-version
#:typecase
#:host-typecase
#:etypecase
#:host-etypecase
#:debian-suite-case
#:host-debian-suite-case
#:debian-suite-ecase
#:host-debian-suite-ecase
#:required
#:supports-arch-p))
(package :consfigurator.property.rc.conf
(:local-nicknames (#:os #:consfigurator.property.os))
(:export #:contains
#:file-contains
#:ws-list-contains
#:ws-list-lacks
#:file-ws-list-contains
#:file-ws-list-lacks))
(package :consfigurator.property.container
(:export #:contained
#:contained-p
#:when-contained))
(package :consfigurator.property.periodic
(:local-nicknames (#:file #:consfigurator.property.file))
(:export #:at-most
#:reapplied-at-most))
(package :consfigurator.property.mount
(:local-nicknames (#:os #:consfigurator.property.os)
(#:cmd #:consfigurator.property.cmd)
(#:file #:consfigurator.property.file))
(:export #:mounted
#:unmounted-below
#:unmounted-below-and-removed
#:all-mounts
#:+linux-basic-vfs+
#:+linux-efivars-vfs+
#:assert-devtmpfs-udev-/dev))
(package :consfigurator.property.service
(:local-nicknames (#:os #:consfigurator.property.os)
(#:file #:consfigurator.property.file))
(:export #:no-services
#:no-services-p
#:running
#:restarted
#:reloaded
#:without-starting-services))
(package :consfigurator.property.apt
(:local-nicknames (#:re #:cl-ppcre)
(#:cmd #:consfigurator.property.cmd)
(#:file #:consfigurator.property.file)
(#:os #:consfigurator.property.os)
(#:service #:consfigurator.property.service))
(:export #:known-installed-removed-packages-reset
#:installed
#:installed-minimally
#:backports-installed
#:backports-installed-minimally
#:removed
#:reconfigured
#:service-installed-running
#:all-configured
#:updated
#:upgraded
#:autoremoved
#:periodic-updates
#:unattended-upgrades
#:mirrors
#:uses-parent-mirrors
#:proxy
#:uses-parent-proxy
#:uses-local-cacher
#:get-mirrors
#:standard-sources.list
#:additional-sources
#:cache-cleaned
#:trusts-key
#:all-installed-p
#:none-installed-p
#:suites-available-pinned
#:pinned
#:no-pdiffs))
(package :consfigurator.property.pkgng
(:local-nicknames (#:os #:consfigurator.property.os))
(:export #:installed
#:deleted
#:upgraded
#:autoremoved
#:cache-cleaned
#:cache-emptied))
(package :consfigurator.property.package
(:local-nicknames (#:apt #:consfigurator.property.apt)
(#:pkgng #:consfigurator.property.pkgng))
(:export #:+consfigurator-system-dependencies+
#:package-manager-not-found
#:installed))
(package :consfigurator.connection.sbcl
(:local-nicknames (#:os #:consfigurator.property.os)
(#:package #:consfigurator.property.package)))
(package :consfigurator.property.user
(:local-nicknames (#:file #:consfigurator.property.file)
(#:os #:consfigurator.property.os))
(:export #:has-account
#:has-account-with-uid
#:group-exists
#:has-groups
#:has-desktop-groups
#:has-login-shell
#:has-enabled-password
#:has-locked-password
#:passwd-field
#:user-info))
(package :consfigurator.util.linux-namespace
(:use #:consfigurator.util.posix1e #:cffi)
(:local-nicknames (#:user #:consfigurator.property.user))
(:export #:get-ids-offset
#:reduce-id-maps
#:shift-ids
#:setgroups-p
#:get-userns-owner))
(package :consfigurator.property.chroot
(:local-nicknames (#:service #:consfigurator.property.service)
(#:apt #:consfigurator.property.apt)
(#:os #:consfigurator.property.os)
(#:package #:consfigurator.property.package)
(#:container #:consfigurator.property.container)
(#:mount #:consfigurator.property.mount)
(#:file #:consfigurator.property.file))
(:shadow #:deploys #:deploys. #:deploys-these #:deploys-these.)
(:export #:deploys
#:deploys.
#:deploys-these
#:deploys-these.
#:os-bootstrapped-for
#:os-bootstrapped-for.
#:os-bootstrapped
#:os-bootstrapped.))
(package :consfigurator.property.disk
(:local-nicknames (#:re #:cl-ppcre)
(#:chroot #:consfigurator.property.chroot)
(#:cmd #:consfigurator.property.cmd)
(#:file #:consfigurator.property.file)
(#:os #:consfigurator.property.os)
(#:apt #:consfigurator.property.apt))
(:export #:volume
#:volume-label
#:volume-contents
#:volume-size
#:volume-bootloaders
#:subvolumes-of-type
#:all-subvolumes
#:copy-volume-and-contents
#:require-volumes-data
#:opened-volume
#:device-file
#:physical-disk
#:disk-image
#:image-file
#:raw-disk-image
#:opened-raw-disk-image
#:partitioned-volume
#:opened-partitioned-volume
#:partition
#:opened-partition
#:lvm-volume-group
#:lvm-logical-volume
#:activated-lvm-logical-volume
#:lvm-physical-volume
#:opened-lvm-physical-volume
#:filesystem
#:mount-point
#:mount-options
#:mounted-filesystem
#:ext4-filesystem
#:mounted-ext4-filesystem
#:fat32-filesystem
#:mounted-fat32-filesystem
#:luks-container
#:opened-luks-container
#:crypttab-options
#:crypttab-keyfile
#:linux-swap
#:opened-volumes
#:opened-volume-parents
#:with-opened-volumes
#:has-volumes
#:raw-image-built-for
#:first-disk-installed-for
#:volumes-installed-for
#:debian-live-iso-built
#:debian-live-iso-built.
#:host-logical-volumes-exist
#:volumes))
(package :consfigurator.property.fstab
(:use #:consfigurator.property.disk)
(:local-nicknames (#:os #:consfigurator.property.os)
(#:file #:consfigurator.property.file)
(#:disk #:consfigurator.property.disk))
(:export #:volume-to-entry
#:has-entries
#:has-entries-for-volumes
#:has-entries-for-opened-volumes))
(package :consfigurator.property.crypttab
(:use #:consfigurator.property.disk)
(:local-nicknames (#:re #:cl-ppcre)
(#:os #:consfigurator.property.os)
(#:file #:consfigurator.property.file)
(#:disk #:consfigurator.property.disk))
(:export #:volume-to-entry
#:has-entries-for-opened-volumes))
(package :consfigurator.property.gnupg
(:local-nicknames (#:re #:cl-ppcre))
(:export #:public-key-imported
#:secret-key-imported))
(package :consfigurator.property.git
(:local-nicknames (#:os #:consfigurator.property.os)
(#:file #:consfigurator.property.file)
(#:apt #:consfigurator.property.apt)
(#:pkgng #:consfigurator.property.pkgng))
(:export #:installed
#:snapshot-extracted
#:cloned
#:pulled
#:repo-configured))
(package :consfigurator.property.sshd
(:local-nicknames (#:re #:cl-ppcre)
(#:os #:consfigurator.property.os)
(#:file #:consfigurator.property.file)
(#:apt #:consfigurator.property.apt)
(#:service #:consfigurator.property.service))
(:export #:installed
#:configured
#:no-passwords
#:host-public-keys
#:has-host-public-key
#:has-host-key))
(package :consfigurator.property.ssh
(:local-nicknames (#:file #:consfigurator.property.file)
(#:sshd #:consfigurator.property.sshd))
(:export #:authorized-keys
#:has-user-key
#:known-host
#:system-known-host
#:parent-is-system-known-host))
(package :consfigurator.property.locale
(:local-nicknames (#:re #:cl-ppcre)
(#:os #:consfigurator.property.os)
(#:apt #:consfigurator.property.apt)
(#:cmd #:consfigurator.property.cmd)
(#:file #:consfigurator.property.file))
(:export #:available
#:selected-for))
(package :consfigurator.property.reboot
(:local-nicknames (#:container #:consfigurator.property.container))
(:shadow #:at-end)
(:export #:at-end))
(package :consfigurator.property.installer
(:use #:consfigurator.property.disk #:cffi)
(:local-nicknames (#:os #:consfigurator.property.os)
(#:cmd #:consfigurator.property.cmd)
(#:file #:consfigurator.property.file)
(#:chroot #:consfigurator.property.chroot)
(#:mount #:consfigurator.property.mount)
(#:fstab #:consfigurator.property.fstab)
(#:reboot #:consfigurator.property.reboot)
(#:crypttab #:consfigurator.property.crypttab)
(#:disk #:consfigurator.property.disk))
(:export #:install-bootloader-propspec
#:install-bootloader-binaries-propspec
#:files-installed-to-volumes-for
#:bootloader-binaries-installed
#:bootloaders-installed
#:cleanly-installed-once
#:with-cleanly-installed-once))
(package :consfigurator.property.grub
(:use #:consfigurator.property.disk
#:consfigurator.property.installer)
(:local-nicknames (#:os #:consfigurator.property.os)
(#:file #:consfigurator.property.file)
(#:apt #:consfigurator.property.apt)
(#:container #:consfigurator.property.container))
(:export #:grub
#:grub-installed))
(package :consfigurator.property.u-boot
(:use #:consfigurator.property.disk
#:consfigurator.property.installer)
(:local-nicknames (#:os #:consfigurator.property.os)
(#:apt #:consfigurator.property.apt)
(#:container #:consfigurator.property.container))
(:export #:install-rockchip
#:installed-rockchip))
(package :consfigurator.property.hostname
(:local-nicknames (#:cmd #:consfigurator.property.cmd)
(#:container #:consfigurator.property.container)
(#:file #:consfigurator.property.file))
(:export #:is
#:configured
#:mailname-configured
#:search-configured))
(package :consfigurator.property.network
(:local-nicknames (#:os #:consfigurator.property.os)
(#:file #:consfigurator.property.file))
(:export #:aliases
#:ipv4
#:ipv6
#:clean-/etc/network/interfaces
#:static
#:preserve-static-once))
(package :consfigurator.property.libvirt
(:local-nicknames (#:os #:consfigurator.property.os)
(#:cmd #:consfigurator.property.cmd)
(#:service #:consfigurator.property.service)
(#:file #:consfigurator.property.file)
(#:chroot #:consfigurator.property.chroot)
(#:apt #:consfigurator.property.apt)
(#:disk #:consfigurator.property.disk))
(:export #:installed
#:default-network-started
#:default-network-autostarted
#:defined-for
#:started
#:destroyed
#:when-started
#:kvm-boots-chroot-for
#:kvm-boots-chroot-for.
#:kvm-boots-chroot
#:kvm-boots-chroot.
#:kvm-boots-lvm-lv-for
#:kvm-boots-lvm-lv-for.
#:kvm-boots-lvm-lv
#:kvm-boots-lvm-lv.
#:virsh-get-columns))
(package :consfigurator.property.ccache
(:local-nicknames (#:os #:consfigurator.property.os)
(#:file #:consfigurator.property.file)
(#:apt #:consfigurator.property.apt))
(:export #:installed
#:has-limits
#:cache-for-group))
(package :consfigurator.property.schroot
(:local-nicknames (#:os #:consfigurator.property.os)
(#:file #:consfigurator.property.file)
(#:apt #:consfigurator.property.apt))
(:export #:installed
#:uses-overlays
#:overlays-in-tmpfs))
(package :consfigurator.property.sbuild
(:local-nicknames (#:os #:consfigurator.property.os)
(#:file #:consfigurator.property.file)
(#:chroot #:consfigurator.property.chroot)
(#:user #:consfigurator.property.user)
(#:apt #:consfigurator.property.apt)
(#:ccache #:consfigurator.property.ccache)
(#:schroot #:consfigurator.property.schroot)
(#:periodic #:consfigurator.property.periodic))
(:export #:installed
#:usable-by
#:built
#:built.
#:standard-debian-schroot))
(package :consfigurator.property.postfix
(:local-nicknames (#:cmd #:consfigurator.property.cmd)
(#:service #:consfigurator.property.service)
(#:apt #:consfigurator.property.apt)
(#:os #:consfigurator.property.os)
(#:file #:consfigurator.property.file)
(#:user #:consfigurator.property.user))
(:export #:installed
#:reloaded
#:main-configured
#:mapped-file
#:daemon-socket-directory))
(package :consfigurator.property.cron
(:local-nicknames (#:re #:cl-ppcre)
(#:service #:consfigurator.property.service)
(#:apt #:consfigurator.property.apt)
(#:os #:consfigurator.property.os)
(#:file #:consfigurator.property.file))
(:export #:system-job
#:nice-system-job
#:runs-consfigurator
#:user-crontab-installed))
(package :consfigurator.property.lets-encrypt
(:local-nicknames (#:apt #:consfigurator.property.apt)
(#:os #:consfigurator.property.os))
(:export #:installed
#:agree-tos
#:certificate-obtained
#:certificate-obtained-standalone
#:fullchain-for
#:chain-for
#:certificate-for
#:privkey-for))
(package :consfigurator.property.apache
(:local-nicknames
(#:service #:consfigurator.property.service)
(#:apt #:consfigurator.property.apt)
(#:os #:consfigurator.property.os)
(#:file #:consfigurator.property.file)
(#:network #:consfigurator.property.network)
(#:lets-encrypt #:consfigurator.property.lets-encrypt))
(:export #:installed
#:reloaded
#:mod-enabled
#:conf-enabled
#:conf-available
#:site-enabled
#:site-available
#:https-vhost))
(package :consfigurator.property.systemd
(:local-nicknames (#:service #:consfigurator.property.service))
(:export #:daemon-reloaded
#:started
#:stopped
#:reloaded
#:restarted
#:enabled
#:disabled
#:masked
#:lingering-enabled))
(package :consfigurator.property.firewalld
(:local-nicknames (#:cmd #:consfigurator.property.cmd)
(#:file #:consfigurator.property.file)
(#:apt #:consfigurator.property.apt)
(#:os #:consfigurator.property.os)
(#:service #:consfigurator.property.service))
(:export #:installed
#:knows-service
#:has-policy
#:has-zone-xml
#:has-zone
#:zone-has-target
#:default-route-zoned-once
#:zone-has-interface
#:zone-has-source
#:zone-has-service
#:zone-has-masquerade
#:zone-has-rich-rule
#:has-direct-rule
#:has-default-zone))
(package :consfigurator.property.timezone
(:local-nicknames (#:file #:consfigurator.property.file)
(#:apt #:consfigurator.property.apt)
(#:os #:consfigurator.property.os))
(:export #:configured
#:configured-from-parent))
(package :consfigurator.property.swap
(:local-nicknames (#:cmd #:consfigurator.property.cmd)
(#:fstab #:consfigurator.property.fstab)
(#:os #:consfigurator.property.os))
(:export #:has-swap-file))
(package :consfigurator.property.lxc
(:use #:consfigurator.util.linux-namespace #:cffi)
(:local-nicknames (#:file #:consfigurator.property.file)
(#:apt #:consfigurator.property.apt)
(#:os #:consfigurator.property.os)
(#:service #:consfigurator.property.service)
(#:chroot #:consfigurator.property.chroot)
(#:user #:consfigurator.property.user)
(#:systemd #:consfigurator.property.systemd))
(:export #:installed
#:user-container-started
#:user-container-stopped
#:when-user-container-running
#:user-containers-autostart
#:usernet-veth-usable-by
#:user-container-for
#:user-container-for.
#:user-container
#:user-container.
#:lxc-ls))
(package :consfigurator.property.postgres
(:local-nicknames (#:apt #:consfigurator.property.apt)
(#:os #:consfigurator.property.os)
(#:cmd #:consfigurator.property.cmd))
(:export #:installed
#:superuser-is
#:has-role
#:has-database
#:database-has-owner
#:has-group
#:user-can-login))
(package :consfigurator.connection.local
(:export #:local-connection))
(package :consfigurator.connection.shell-wrap
(:export #:shell-wrap-connection #:connection-shell-wrap))
(package :consfigurator.connection.fork
(:use #:consfigurator.connection.local)
(:export #:fork-connection
#:post-fork
#:init-hooks-connection))
(package :consfigurator.connection.rehome
(:use #:consfigurator.connection.fork)
(:export #:rehome-connection
#:rehome-datadir))
(package :consfigurator.connection.as
(:use #:consfigurator.connection.fork #:cffi))
(package :consfigurator.connection.ssh
(:use #:consfigurator.connection.shell-wrap))
(package :consfigurator.connection.sudo
(:use #:consfigurator.connection.shell-wrap))
(package :consfigurator.connection.su
(:use #:consfigurator.connection.shell-wrap))
(package :consfigurator.connection.chroot
(:use #:consfigurator.connection.fork
#:consfigurator.connection.rehome
#:consfigurator.connection.shell-wrap
#:cffi)
(:local-nicknames (#:disk #:consfigurator.property.disk)
(#:mount #:consfigurator.property.mount)))
(package :consfigurator.connection.setuid
(:use #:consfigurator.connection.fork
#:consfigurator.connection.rehome
#:cffi)
(:local-nicknames (#:re #:cl-ppcre)
(#:user #:consfigurator.property.user)))
(package :consfigurator.connection.linux-namespace
(:use #:consfigurator.util.linux-namespace
#:consfigurator.connection.fork
#:consfigurator.connection.shell-wrap)
(:local-nicknames (#:user #:consfigurator.property.user)
(#:lxc #:consfigurator.property.lxc)))
(package :consfigurator.data.util
(:export #:literal-data-pathname #:gpg-file-as-string #:gpg))
(package :consfigurator.data.asdf)
(package :consfigurator.data.pgp
(:use #:consfigurator.data.util)
(:export #:list-data #:get-data #:set-data #:set-data-from-file))
(package :consfigurator.data.git-snapshot)
(package :consfigurator.data.gpgpubkeys)
(package :consfigurator.data.ssh-askpass
(:local-nicknames (#:re #:cl-ppcre)))
(package :consfigurator.data.local-file)
(package :consfigurator.data.pass
(:use #:consfigurator.data.util))
(package :consfigurator.data.files-tree
(:use #:consfigurator.data.util)))
| 41,103 | Common Lisp | .lisp | 984 | 24.762195 | 79 | 0.462988 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 7319627e104c4adbb042eafcd6caba02d7e2dad67ee4681ce22886f4c2e85f1b | 3,922 | [
-1
] |
3,923 | util.lisp | spwhitton_consfigurator/src/util.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2020-2022 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator)
(named-readtables:in-readtable :consfigurator)
(defun multiple-value-mapcan (function &rest lists)
"Variant of MAPCAN which preserves multiple return values."
(loop with lists = (copy-list lists)
with results = (make-array '(1) :initial-element nil :adjustable t)
for new = (multiple-value-list
(apply function
(maplist (lambda (lists)
(if (endp (car lists))
(return
(values-list
(map 'list #'nreverse results)))
(pop (car lists))))
lists)))
do (loop
initially
(adjust-array results (max (length results) (length new))
:initial-element nil)
for result in new and i upfrom 0 do
(setf (aref results i) (nreconc result (aref results i))))))
(defun words (text)
(delete "" (split-string text) :test #'string=))
(defun unwords (words)
(format nil "~{~A~^ ~}" words))
(defun strip-prefix (prefix string)
"If STRING is prefixed by PREFIX, return the rest of STRING,
otherwise return NIL."
(nth-value 1 (starts-with-subseq prefix string :return-suffix t)))
(defun memstr= (string list)
(member string list :test #'string=))
(defun assert-ordinary-ll-member (arg)
"Assert that ARG is not an implementation-specific lambda list keyword or a
lambda list keyword which is not permitted in ordinary lambda lists.
Consfigurator's property-writing macros do not support lambda list keywords
which fail this assertion."
(or
(not
(member arg
'#.(set-difference lambda-list-keywords
'(&optional &rest &key &allow-other-keys &aux))))
(simple-program-error
"Implementation-specific or non-ordinary lambda list keyword ~A not
supported."
arg)))
(defun ordinary-ll-without-&aux (ll)
(loop for arg in ll
do (assert-ordinary-ll-member arg)
if (eq '&aux arg) return accum
else collect arg into accum
finally (return accum)))
(defun ordinary-ll-variable-names (ll &key include-supplied-p)
(loop for arg in ll
for arg* = (ensure-car arg)
do (assert-ordinary-ll-member arg)
unless (char= #\& (char (symbol-name arg*) 0))
collect arg*
and when (and include-supplied-p (listp arg) (caddr arg))
collect (caddr arg)))
(defmacro defun-with-args (name argsym lambda-list &body forms &aux remaining)
(multiple-value-bind (required optional rest kwargs aokeys)
(parse-ordinary-lambda-list lambda-list)
(when (and aokeys (not rest))
(simple-program-error
"&ALLOW-OTHER-KEYS without &REST in property lambda list not supported."))
(let ((normalisedll (reverse required)))
(when optional
(push '&optional normalisedll)
(loop for (name init suppliedp) in optional
for suppliedp* = (or suppliedp (gensym))
do (push `(,name ,init ,suppliedp*) normalisedll)
do (push `(when ,suppliedp* (push ,name ,argsym)) remaining)))
(when rest
(push '&rest normalisedll)
(push rest normalisedll)
(push `(dolist (r ,rest) (push r ,argsym)) remaining))
(when kwargs
(push '&key normalisedll)
(loop for ((keyword-name name) init suppliedp) in kwargs
for suppliedp* = (if (or rest suppliedp) suppliedp (gensym))
do (push `((,keyword-name ,name) ,init ,suppliedp*)
normalisedll)
unless rest do (push `(when ,suppliedp*
(push ,keyword-name ,argsym)
(push ,name ,argsym))
remaining)))
(when aokeys
(push '&allow-other-keys normalisedll))
`(defun ,name ,(nreverse normalisedll)
(let ((,argsym (list ,@(reverse required))))
,@(nreverse remaining)
(nreversef ,argsym)
,@forms)))))
(defmacro define-simple-error (name &optional parent-types docstring)
`(progn
(define-condition ,name (,@parent-types simple-error) ()
,@(and docstring `((:documentation ,docstring))))
(defun ,name (message &rest args)
,@(and docstring `(,docstring))
(error ',name :format-control message :format-arguments args))))
(defmacro form-beginning-with (sym form)
`(and (listp ,form)
(symbolp (car ,form))
(string= (symbol-name (car ,form)) ,(symbol-name sym))))
(defun strip-declarations (forms)
(loop while (form-beginning-with declare (car forms))
do (pop forms)
finally (return forms)))
(defun plist-to-long-options (plist &aux args)
(doplist (k v plist args)
(push (strcat "--" (string-downcase (symbol-name k)) "=" v) args)))
(defun systemd-user-instance-args (args)
"Where ARGS are args to RUN or MRUN for an invocation of a systemd command
which can take \"--user\", insert the \"--user\" parameter, and modify or
insert an :ENV parameter so that the call is more likely to succeed."
(loop with xrd = (format nil "/run/user/~D" (get-connattr :remote-uid))
with dsba = (format nil "unix:path=~A/bus" xrd)
with arg-done and env-done while args
as next = (pop args) collect next into accum
if (and (not arg-done) (stringp next))
collect "--user" into accum and do (setq arg-done t)
if (eql :env next)
collect (aprog1 (copy-list (pop args))
(setf (getf it :XDG_RUNTIME_DIR) xrd
(getf it :DBUS_SESSION_BUS_ADDRESS) dsba
env-done t))
into accum
if (eql :input next)
collect (pop args)
finally (return (if env-done
accum
(list* :env `(:XDG_RUNTIME_DIR ,xrd
:DBUS_SESSION_BUS_ADDRESS ,dsba)
accum)))))
(defmacro with-local-temporary-directory ((dir) &body forms)
"Execute FORMS with a local temporary directory's pathname in DIR.
Currently assumes GNU mktemp(1).
There is no WITH-REMOTE-TEMPORARY-DIRECTORY because POSIX doesn't include a
shell utility to create temporary directories. If you need a remote temporary
directory, one solution is to convert your property to a :LISP property."
`(let ((,dir (ensure-directory-pathname
(stripln
(run-program "umask 077; mktemp -d" :output :string)))))
(unwind-protect (progn ,@forms)
(delete-directory-tree ,dir :validate t))))
(defun pathname-file (pathname)
"Like PATHNAME-NAME but include any file extension."
(and (pathname-name pathname)
(namestring
(if (pathname-directory pathname)
(enough-pathname pathname (pathname-directory-pathname pathname))
pathname))))
(defun local-directory-contents (pathname)
"Return the immediate contents of PATHNAME, a directory, without resolving
symlinks. Not suitable for use by :POSIX properties."
;; On SBCL on Debian UIOP:*WILD-FILE-FOR-DIRECTORY* is #P"*.*".
(uiop:directory*
(merge-pathnames uiop:*wild-file-for-directory*
(ensure-directory-pathname pathname))))
(defun ensure-trailing-slash (namestring)
(if (string-suffix-p namestring "/")
namestring
(strcat namestring "/")))
(defun drop-trailing-slash (namestring)
(if (string-suffix-p namestring "/")
(subseq namestring 0 (1- (length namestring)))
namestring))
(defun reinit-from-simple-print (class &rest slots)
(aprog1 (allocate-instance (find-class class))
(loop for (slot-name slot-value) on slots by #'cddr
do (setf (slot-value it slot-name) slot-value))))
(defmacro quote-nonselfeval (x)
(once-only (x)
`(if (member (type-of ,x) '(cons symbol))
`',,x ,x)))
(defmacro define-simple-print-object (class)
"Define an implementation of PRINT-OBJECT suitable for classes representing
simple collections of readably-printable values."
`(defmethod print-object ((object ,class) stream)
(if (and *print-readably* *read-eval*)
(format
stream "#.~S"
`(reinit-from-simple-print
',(type-of object)
;; Call CLASS-OF so that subclasses of CLASS are handled too.
,@(loop for slot in (closer-mop:class-slots (class-of object))
for slot-name = (closer-mop:slot-definition-name slot)
when (slot-boundp object slot-name)
collect `',slot-name
and collect (quote-nonselfeval
(slot-value object slot-name)))))
(call-next-method))
object))
(defun chroot-pathname (pathname chroot)
(merge-pathnames (enough-pathname pathname #P"/")
(ensure-directory-pathname chroot)))
(defun in-chroot-pathname (pathname chroot)
(ensure-pathname (enough-pathname pathname chroot)
:ensure-absolute t :defaults #P"/"))
(defun sh-escape (token-or-cmd &optional s)
(cond ((listp token-or-cmd) (uiop:escape-command token-or-cmd s 'sh-escape))
((pathnamep token-or-cmd) (sh-escape (unix-namestring token-or-cmd) s))
((string= token-or-cmd "") (format s "\"\""))
(t (uiop:escape-sh-token token-or-cmd s))))
(defun parse-username-from-id (output)
"Where OUTPUT is the output of the id(1) command, extract the username."
(#1~/^uid=[0-9]+\(([^)]+)/ output))
(defun abbreviate-consfigurator-package (name)
(with-standard-io-syntax
(let* ((*package* (find-package :consfigurator))
(name (etypecase name
(string name)
(package (package-name name))
(symbol (prin1-to-string name)))))
(cond ((string-prefix-p "CONSFIGURATOR.PROPERTY." name)
(subseq name 23))
((string-prefix-p "CONSFIGURATOR.DATA." name)
(subseq name 14))
(t name)))))
;; not DEFCONSFIG because a consfig is a system not a package
(defmacro defpackage-consfig (name &body forms)
"Convenience wrapper around DEFPACKAGE for consfigs.
Adds recommended local nicknames for all the property and data source packages
that come with Consfigurator. Either use this directly or use its macro
expansion as a starting point for your own DEFPACKAGE form for your consfig."
(let ((forms (copy-tree forms))
(local-nicknames
(cons :local-nicknames
(loop for package in (list-all-packages)
for name = (package-name package)
for abbrevd = (abbreviate-consfigurator-package name)
unless (string= abbrevd name)
collect (list (make-symbol abbrevd)
(make-symbol name))))))
(if-let ((form (loop for form on forms
when (and (listp (car form))
(eql :local-nicknames (caar form)))
return form)))
(rplaca form (nconc local-nicknames (cdar form)))
(push local-nicknames forms))
;; Not much benefit to importing CONSFIGURATOR for the user as it only
;; needs to be done once, and some users will prefer to import qualified,
;; but we could also have:
;; (if-let ((form (loop for form on forms
;; when (and (listp (car form)) (eql :use (caar form)))
;; return form)))
;; (rplaca form (list* :use '#:consfigurator (cdar form)))
;; (push '(:use '#:cl '#:consfigurator) forms))
`(defpackage ,name ,@forms)))
(defmacro lambda-ignoring-args (&body body)
(multiple-value-bind (forms declarations) (parse-body body)
(with-gensyms (ignore)
`(lambda (&rest ,ignore)
(declare (ignore ,ignore) ,@declarations)
,@forms))))
(defun parse-cidr (address-with-suffix)
(destructuring-bind (address cidr)
(split-string address-with-suffix :separator "/")
(unless cidr
(simple-program-error "~A is not in CIDR notation."
address-with-suffix))
(values
address
(loop with cidr = (parse-integer cidr)
with type = (if (or (> cidr 32) (find #\: address)) 6 4)
with block-digits = (if (= type 4) 8 16)
repeat (if (= type 4) 4 8)
for digits = (min cidr block-digits)
do (decf cidr digits)
collect (parse-integer
(with-output-to-string (s)
(loop repeat digits do (princ #\1 s))
(loop repeat (- block-digits digits) do (princ #\0 s)))
:radix 2)
into accum
finally (return (if (= type 4)
(format nil "~{~D~^.~}" accum)
(with-output-to-string (s)
(loop for blocks on accum
if (> (car blocks) 0)
do (format s "~X" (car blocks))
and if (cdr blocks) do (princ #\: s)
end
else do (princ #\: s)
(loop-finish)))))))))
(defun try-parse-number (string &rest args &key &allow-other-keys)
(and string
(handler-case (apply #'parse-number string args)
(parse-error () string))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-constant +alphanum+
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
:test #'string=))
(defun random-alphanumeric (length)
"Return a random alphanumeric string of length LENGTH."
(aprog1 (make-string length)
(loop with *random-state* = (make-random-state t)
for i below length
do (setf (char it i)
(char +alphanum+ (random #.(length +alphanum+)))))))
(defun mkfifo ()
"Use mkfifo(3) to create a named pipe with a mkstemp(3)-like name."
(let* ((dir (drop-trailing-slash (or (getenv "TMPDIR") "/tmp")))
(dir-ls (run-program
`("env" "LANG=C" "ls" "-lnd" ,dir) :output :string))
(prefix (strcat dir "/tmp.")))
(unless (and (char= #\d (char dir-ls 0))
(char-equal #\t (char dir-ls 9))
(zerop (parse-integer (caddr (words dir-ls)))))
(error "~A is not a root-owned dir with the sticky bit set." dir))
(flet ((mktemp ()
;; We need to generate a temporary name. We don't have to worry
;; about race conditions as mkfifo(3) will fail if the file
;; already exists.
(loop with result = (make-string (+ 6 (length prefix)))
initially (setf (subseq result 0 (length prefix)) prefix)
for i from (length prefix) below (length result)
do (setf (char result i)
(char +alphanum+ (random #.(length +alphanum+))))
finally (return result)))
(mkfifo (temp)
(handler-case (nix:mkfifo temp #o600)
(serious-condition (c)
(if (or (file-exists-p temp) (directory-exists-p temp))
nil
(signal c))))))
(loop with *random-state* = (make-random-state t)
repeat 3 for temp = (mktemp)
when (mkfifo temp) return (pathname temp)))))
(defmacro with-mkfifos ((&rest mkfifos) &body forms)
`(let ,(loop for mkfifo in mkfifos collect `(,mkfifo (mkfifo)))
(unwind-protect (progn ,@forms)
,@(loop for mkfifo in mkfifos collect `(delete-file ,mkfifo)))))
(defun write-to-mkfifo (object fifo)
(with-standard-io-syntax
(write object :stream fifo) (terpri fifo) (finish-output fifo)))
(defun valid-hostname-p (string)
"Test whether STRING looks like a valid hostname, as defined by RFCs 952 and
1123."
(and
(<= (length string) 253)
(let ((parts (split-string string :separator ".")))
(every (lambda (part)
(and (<= (length part) 63)
(re:scan "^[a-zA-Z0-9][a-zA-Z0-9-]*$" part)))
parts))))
(defmacro prog-changes (&body body)
(with-gensyms (result)
`(let ((,result :no-change))
(block prog-changes
(flet ((add-change (&optional result)
(case result
(:no-change result)
(t (setq ,result result))))
(return-changes ()
(return-from prog-changes ,result)))
(declare (ignorable #'return-changes))
,@body
,result)))))
(defun sh-script-to-single-line (script)
"Attempt to convert a multiline POSIX sh script to a single line.
The current implementation is naïve, and certainly unsuitable for converting
arbitrary scripts. Thus, this function is presently intended to be used only
on simple scripts embedded in source code, written with newlines for the sake
of maintainability. Converting those scripts to single lines before they are
executed improves Consfigurator's debug output, and also makes process names
visible to remote commands like ps(1) more readable."
(#~s/\s+/ /g
(#~s/(then|else|elif|fi|case|in|;;|do|done);/\1/g
(format nil "~{~A~^; ~}" (lines script)))))
;;;; Progress & debug printing
(defvar *consfigurator-debug-level* 0
"Integer. Higher values mean be more verbose during deploys.")
(defvar *inform-prefix* ";; ")
(defmacro with-indented-inform (&body forms)
`(let ((*inform-prefix* (strcat *inform-prefix* " ")))
,@forms))
(defun inform (level output &key strip-empty (fresh-line t))
"Print something to the user during deploys."
(unless (and (numberp level) (> level *consfigurator-debug-level*))
(let ((lines (loop for line in (etypecase output
(cons output)
(string (lines output)))
;; strip (first part of) prefix added by a remote Lisp
for stripped = (if (string-prefix-p ";; " line)
(subseq line 3)
line)
unless (and strip-empty (re:scan #?/\A\s*\z/ stripped))
collect stripped)))
(when fresh-line
(fresh-line)
(princ *inform-prefix*))
(princ (pop lines))
(dolist (line lines)
(fresh-line)
(princ *inform-prefix*)
(princ line)))))
(defun informat (level control-string &rest format-arguments)
"Print something to the user during deploys using FORMAT.
Be sure to begin CONTROL-STRING with ~& unless you want to continue from
previous output."
(if (string-prefix-p "~&" control-string)
(inform level
(apply #'format nil (subseq control-string 2) format-arguments)
:fresh-line t)
(inform level
(apply #'format nil control-string format-arguments)
:fresh-line nil)))
;;;; Version numbers
(defun compare-versions (x y &optional less-than-or-equal)
(flet
((components (v)
(etypecase v
(number (list v))
(string
(loop with buf
= (make-array 0 :fill-pointer 0 :element-type 'character)
for c across v
if (digit-char-p c)
do (vector-push-extend c buf)
else if (and (char= c #\.) (plusp (fill-pointer buf)))
collect (parse-integer buf) into accum
and do (setf (fill-pointer buf) 0)
else do (loop-finish)
finally (return (if (plusp (fill-pointer buf))
(nconc accum (list (parse-integer buf)))
accum)))))))
(setq x (components x) y (components y))
(if less-than-or-equal
(loop while (or x y) for a = (or (pop x) 0) and b = (or (pop y) 0)
never (> a b)
if (< a b) return t)
(loop while (or x y) for a = (or (pop x) 0) and b = (or (pop y) 0)
thereis (> b a)
if (< b a) return nil))))
(defun version< (x y)
(compare-versions x y))
(defun version<= (x y)
(compare-versions x y t))
(defun version> (x y)
(compare-versions y x))
(defun version>= (x y)
(compare-versions y x t))
;;;; Encoding of strings to filenames
;; Encoding scheme based on one by Joey Hess -- File.configFileName in
;; propellor. Try to avoid including non-alphanumerics other than '.' and '_'
;; in the filename, such that it both remains roughly human-readable and is
;; likely to be accepted by programs which don't treat filenames as opaque
;; (and interpret them with a charset sufficiently similar to Lisp's).
;; This implementation also assumes that the Lisp doing the decoding has the
;; same charset as the Lisp doing the encoding.
(defun string-to-filename (s)
(apply #'concatenate 'string
(loop for c
across (etypecase s (string s) (number (write-to-string s)))
if (or (char= c #\.)
(alpha-char-p c)
(digit-char-p c))
collect (format nil "~C" c)
else
collect (format nil "_~X_" (char-code c)))))
(defun filename-to-string (s)
(loop with decoding
with buffer
with result
for c across s
do (cond
((and (char= c #\_) (not decoding))
(setq decoding t))
((and (char= c #\_) decoding)
(unless buffer (error "invalid encoding"))
(push (code-char
(read-from-string
(coerce (list* #\# #\x (nreverse buffer)) 'string)))
result)
(setq buffer nil
decoding nil))
(decoding
(push c buffer))
(t
(push c result)))
finally (return (coerce (nreverse result) 'string))))
;;;; Forking utilities
;;; Use implementation-specific fork(2) wrapper, and never fork(2) itself, to
;;; allow the implementation to handle things like finaliser threads. For all
;;; other syscalls/libc & POSIX macros like WIFEXITED, use CFFI, via Osicat
;;; when there's a wrapper available, for portability.
(defun fork ()
;; Normalise any other implementations such that we signal an error if
;; fork(2) returns -1, so caller doesn't have to check for that.
#+sbcl (sb-posix:fork))
(defmacro forked-progn (child-pid child-form &body parent-forms)
(with-gensyms (retval)
`(progn
#-(or sbcl) (error "Don't know how to safely fork(2) in this Lisp.")
(mapc-open-output-streams
#'force-output (list *debug-io* *terminal-io*
*standard-output* *error-output*))
(let ((,retval (fork)))
(if (zerop ,retval)
;; We leave it to the caller to appropriately call CLOSE or
;; CLEAR-INPUT on input streams shared with the parent, because
;; at least SBCL's CLEAR-INPUT clears the OS buffer as well as
;; Lisp's, potentially denying data to both sides of the fork.
,child-form
(let ((,child-pid ,retval)) ,@parent-forms))))))
(define-condition skipped-properties () ()
(:documentation
"There were failed changes, but instead of aborting, that particular property
application was instead skipped over, either due to the semantics of a
property combinator, or because the user elected to skip the property in the
interactive debugger."))
(defmacro with-deployment-report (&body forms)
(with-gensyms (failures)
`(let* (,failures
(result (handler-bind ((skipped-properties (lambda (c)
(declare (ignore c))
(setq ,failures t))))
,@forms)))
(inform
t
(cond
((eql :no-change result)
"No changes were made.")
(,failures
"There were failures while attempting to apply some properties.")
(t
"Changes were made without any reported failures."))))))
(defmacro with-backtrace-and-exit-code (&body forms)
(with-gensyms (failures)
`(let* (,failures
(result (handler-bind ((serious-condition
(lambda (c)
(trivial-backtrace:print-backtrace
c :output *error-output*)
(uiop:quit 1)))
(skipped-properties (lambda (c)
(declare (ignore c))
(setq ,failures t))))
,@forms)))
(uiop:quit (cond ((eql :no-change result) 0)
(,failures 22)
(t 23))))))
(defmacro exit-code-to-retval (exit &key on-failure)
`(values
nil
(case ,exit
(0 :no-change)
(22 (signal 'skipped-properties) nil)
(23 nil)
(t ,on-failure))))
(defun posix-login-environment (&optional uid logname home)
"Reset the environment after switching UID, or similar, in a :LISP connection.
Does not currently establish a PAM session."
(let ((rootp (zerop (or uid (nix:geteuid))))
(maybe-preserve '("TERM")))
(when rootp
(push "SSH_AUTH_SOCK" maybe-preserve))
(let ((preserved (loop for var in maybe-preserve
for val = (getenv var)
when val collect var and collect val)))
(clearenv)
(loop for (var val) on preserved by #'cddr do (setf (getenv var) val)))
(when logname
(setf (getenv "USER") logname (getenv "LOGNAME") logname))
(when home
(setf (getenv "HOME") (drop-trailing-slash (unix-namestring home)))
(uiop:chdir home))
(setf (getenv "SHELL") "/bin/sh"
(getenv "PATH")
(if rootp
"/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"
"/usr/local/bin:/bin:/usr/bin"))))
;;;; System and libc calls which can fail
;;; Osicat has an implementation of this but it's not exported. However, we
;;; are able to instantiate Osicat's POSIX-ERROR to simplify errno handling.
(defmacro define-error-retval-cfun
((&key (errno t) (failure-val -1)) &body defcfun-args)
(let ((defun (etypecase (car defcfun-args)
(string
(translate-name-from-foreign (car defcfun-args) '*package*))
(list (cadar defcfun-args))))
(cfun (etypecase (car defcfun-args)
(string (car defcfun-args))
(list (caar defcfun-args))))
(failure-val-check
(once-only (failure-val)
`(cond ((numberp ,failure-val) (= ,failure-val result))
((pointerp ,failure-val) (pointer-eq ,failure-val result))
(t (simple-program-error
"Don't know how to compare function return value with ~S."
,failure-val))))))
`(defun ,defun ,(loop for arg in (cddr defcfun-args) collect (car arg))
,@(and (eql errno :zero) '((nix:set-errno 0)))
(let ((result (foreign-funcall
,cfun
,@(loop for arg in (cddr defcfun-args)
collect (cadr arg) collect (car arg))
,(cadr defcfun-args))))
(if ,(if (eql errno :zero)
`(and ,failure-val-check (not (zerop (nix:get-errno))))
failure-val-check)
(nix:posix-error ,(and errno '(nix:get-errno)) nil ',defun)
result)))))
;;;; Miscellaneous system functions
(define-error-retval-cfun () "clearenv" :int)
(define-error-retval-cfun () "chroot" :int (path :string))
(define-error-retval-cfun () "unshare" :int (flags :int))
;;;; Lisp data files
(defmacro with-lisp-data-file ((data file) &body forms)
(with-gensyms (before)
`(let* ((,before (and (file-exists-p ,file) (read-file-string ,file)))
(,data (and ,before (plusp (length ,before))
(safe-read-from-string ,before))))
(unwind-protect (progn ,@forms)
(with-open-file
(stream ,file :direction :output :if-exists :supersede)
(with-standard-io-syntax
(prin1 ,data stream)))))))
;;;; Streams
(defun stream->input-stream (stream)
(etypecase stream
(synonym-stream (stream->input-stream
(symbol-value (synonym-stream-symbol stream))))
(two-way-stream (two-way-stream-input-stream stream))
(stream (and (input-stream-p stream) stream))))
(defun mapc-open-input-streams (function streams)
(dolist (stream streams streams)
(when-let ((input-stream (stream->input-stream stream)))
(when (open-stream-p input-stream)
(funcall function input-stream)))))
(defun stream->output-stream (stream)
(etypecase stream
(synonym-stream (stream->output-stream
(symbol-value (synonym-stream-symbol stream))))
(two-way-stream (two-way-stream-output-stream stream))
(stream (and (output-stream-p stream) stream))))
(defun mapc-open-output-streams (function streams)
(dolist (stream streams streams)
(when-let ((output-stream (stream->output-stream stream)))
(when (open-stream-p output-stream)
(funcall function output-stream)))))
| 30,879 | Common Lisp | .lisp | 654 | 36.431193 | 81 | 0.58107 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 63f270edd35a78ca6c07bd574b0fa953c67e4514fdd03902f583b846a6f6027c | 3,923 | [
-1
] |
3,924 | libacl.lisp | spwhitton_consfigurator/src/libacl.lisp | (in-package :consfigurator.util.posix1e)
(include "sys/types.h" "sys/acl.h")
(ctype acl_tag_t "acl_tag_t")
(ctype acl_type_t "acl_type_t")
(ctype acl_entry_t "acl_entry_t")
(constant (ACL_USER "ACL_USER"))
(constant (ACL_GROUP "ACL_GROUP"))
(constant (ACL_TYPE_ACCESS "ACL_TYPE_ACCESS"))
(constant (ACL_TYPE_DEFAULT "ACL_TYPE_DEFAULT"))
(constant (ACL_NEXT_ENTRY "ACL_NEXT_ENTRY"))
(constant (ACL_FIRST_ENTRY "ACL_FIRST_ENTRY"))
| 432 | Common Lisp | .lisp | 11 | 38 | 48 | 0.720096 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 37fae5aae2967f00ee8040c54eb69e9a55508186f372e0a0003627871fc98864 | 3,924 | [
-1
] |
3,925 | libc.lisp | spwhitton_consfigurator/src/libc.lisp | (in-package :consfigurator)
(include "unistd.h")
(ctype uid_t "uid_t")
(ctype gid_t "gid_t")
#+linux
(progn
(define "_GNU_SOURCE")
(include "linux/sched.h")
(include "linux/capability.h")
(include "linux/nsfs.h"))
#+linux
(progn
(constant (CLONE_NEWCGROUP "CLONE_NEWCGROUP"))
(constant (CLONE_NEWIPC "CLONE_NEWIPC"))
(constant (CLONE_NEWNET "CLONE_NEWNET"))
(constant (CLONE_NEWNS "CLONE_NEWNS"))
(constant (CLONE_NEWPID "CLONE_NEWPID"))
(constant (CLONE_NEWTIME "CLONE_NEWTIME"))
(constant (CLONE_NEWUSER "CLONE_NEWUSER"))
(constant (CLONE_NEWUTS "CLONE_NEWUTS"))
(constant (NS_GET_OWNER_UID "NS_GET_OWNER_UID")))
| 666 | Common Lisp | .lisp | 21 | 29.238095 | 51 | 0.682813 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 4232e060569dc6d74f1a81a2c8eca735411ed89d306fffd8ee1cec5d09497a58 | 3,925 | [
-1
] |
3,926 | propspec.lisp | spwhitton_consfigurator/src/propspec.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator)
(named-readtables:in-readtable :consfigurator)
;;;; Property application specifications
(define-condition ambiguous-propspec (undefined-function) ()
(:report
(lambda (condition stream)
(format
stream
"The function, property or property combinator ~A is undefined.
Ensure that all functions, properties and property combinators used in a
propspec are defined before that propspec is processed by Consfigurator."
(cell-error-name condition)))))
(define-condition invalid-propspec (error)
((original-error :initarg :error :reader original-error)
(broken-propspec :initarg :propspec :reader broken-propspec))
(:report
(lambda (condition stream)
(format
stream
"The code walker could not process the following propspec.~%~%~S"
(broken-propspec condition))
(when (slot-boundp condition 'original-error)
(format stream "~&~%The error from the code walker was:~%~%~A"
(original-error condition))))))
(defun map-propspec-propapps (function propspec &optional reconstruct env)
"Map FUNCTION over each propapp occurring in PROPSPEC after macroexpansion.
FUNCTION designates a pure function from propapps to propapps. PROPSPEC is a
property application specification expression.
RECONSTRUCT is a boolean flag indicating whether to return code which will
evaluate to the resultant propspec rather than that propspec itself; if t,
FUNCTION too should return code which will evaluate to propapps rather than
propapps themselves. This is useful for when this function is called by
macros. ENV is passed along to AGNOSTIC-LIZARD:WALK-FORM.
This implementation will fail to map propapps appearing within the arguments
to properties in propapps, but that should not be needed. It can very
occasionally give incorrect results due to limitations of the Common Lisp
standard with respect to code walking; see \"Pitfalls\" in the Consfigurator
manual."
(let* (replaced-propapps
;; First we need to find all the propapps, after macro expansion.
;; Propapps contain the arguments to be passed to properties rather
;; than expressions which will evaluate to those arguments, and some
;; of these might be lists, which will look like invalid function
;; calls to the code walker. So we replace every known property so
;; that the code walker does not assume these arguments are to be
;; evaluated as arguments to ordinary functions are.
(expanded
(handler-case
(agnostic-lizard:walk-form
propspec env
:on-macroexpanded-form
(lambda (form env &aux (c (and (listp form) (car form))))
(declare (ignore env))
(cond ((and c (isprop c))
(aprog1 (gensym)
(push (cons it form) replaced-propapps)))
;; We also look for any symbols without function or
;; property definitions occurring in function call
;; positions. These could potentially be properties
;; whose definitions have not been loaded --
;; especially since we get called at compile time by
;; PROPS -- and if so, we would return an incorrect
;; result because the previous branch will not have
;; identified all the propapps in the propspec. So
;; error out if we detect that situation.
((and c (not (fboundp c)))
(error 'ambiguous-propspec :name c))
(t
form))))
(ambiguous-propspec (c) (error c))
(error (condition)
(error 'invalid-propspec :error condition :propspec propspec))))
(replaced-propapps
(alist-hash-table replaced-propapps :test 'eq)))
;; Finally, substitute the mapped propapps back in to the propspec.
(labels ((walk (tree)
(if (atom tree)
(if-let ((propapp (gethash tree replaced-propapps)))
(funcall function propapp)
(if (and reconstruct (symbolp tree)) `',tree tree))
(let ((walked (mapcar #'walk tree)))
(if reconstruct (cons 'list walked) walked)))))
(walk expanded))))
(defmacro in-consfig (&rest systems)
"Sets the variable *CONSFIG* in the current package to SYSTEMS.
Used at the top of your consfig, right after IN-PACKAGE.
This is used to record a list of the names of the ASDF systems in which you
define your hosts, site-specific properties and deployments. These systems
should depend on the \"consfigurator\" system.
SYSTEMS should satisfy the following condition: in normal usage of
Consfigurator, evaluating (mapc #'asdf:load-system SYSTEMS) should be
sufficient to define all the properties you intend to apply to hosts and
property combinators you intend to use in specifying propspecs.
Consfigurator uses this information when starting up remote Lisp images to
effect deployments: it sends over the ASDF systems specified by SYSTEMS."
(when (null systems)
(simple-program-error "Cannot pass no arguments to IN-CONSFIG."))
(let ((sym (intern "*CONSFIG*")))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter ,sym ',systems
"ASDF systems the loading of all of which is sufficient to define all the
Consfigurator properties and property combinators code in this symbol's
package applies to hosts."))))
(define-condition no-consfig (simple-warning) ())
(defun warn-no-consfig ()
(warn 'no-consfig :format-arguments `(,*package*) :format-control
"Initialising propspec without any list of ASDF systems supplied,
and *PACKAGE* is not a package for which IN-CONSFIG has been called.
Consfigurator may not be able to start up remote Lisp images to effect
deployments involving this propspec; see the docstring for IN-CONSFIG.
Either call IN-CONSFIG for ~S, explicitly pass
:SYSTEMS NIL to MAKE-PROPSPEC, or muffle this warning if code using this
propspec will not need to start up any remote Lisp images."))
(defclass propspec ()
((systems
:initarg :systems
:initform
(or (aand (find-symbol "*CONSFIG*") (boundp it) (symbol-value it))
(warn-no-consfig))
:reader propspec-systems
:documentation
"List of names of ASDF systems, the loading of all of which is sufficient
to evaluate and to deploy this propspec."))
(:documentation
"Abstract superclass for propspecs. Do not instantiate."))
(defclass preprocessed-propspec (propspec)
((preprocessed-propspec-expression
:initarg :propspec
:documentation
"Preprocessed propspec corresponding to the propspec represented by this
object. A preprocessed propspec is not itself a valid propspec, so the value
of this slot should be considered opaque."))
(:documentation
"A propspec which has been preprocessed. The only valid methods operating
directly on instances of this class are PROPSPEC-SYSTEMS, EVAL-PROPSPEC and
PRINT-OBJECT."))
(defclass unpreprocessed-propspec (propspec)
((propspec-expression
:initarg :propspec
:reader propspec-props)))
(defgeneric preprocess-propspec (propspec)
(:documentation
"Quote all propapps in PROPSPEC, after calling :PREPROCESS subroutines."))
(defmethod preprocess-propspec ((propspec unpreprocessed-propspec))
(make-instance 'preprocessed-propspec
:systems (propspec-systems propspec)
:propspec (map-propspec-propapps
(lambda (propapp)
(destructuring-bind (prop . args) propapp
`',(cons prop (apply (proppp prop) args))))
(propspec-props propspec))))
(defun make-propspec (&key (systems nil systems-supplied-p) propspec)
"Convert a property application specification expression into a property
application specification proper by associating it with a list of ASDF
systems."
(if systems-supplied-p
(make-instance 'unpreprocessed-propspec
:systems systems :propspec propspec)
(make-instance 'unpreprocessed-propspec :propspec propspec)))
(define-simple-print-object preprocessed-propspec)
(define-simple-print-object unpreprocessed-propspec)
;; this could be defined for preprocessed propspecs easily enough but we
;; shouldn't need to append those
(defmethod append-propspecs
((first unpreprocessed-propspec) (second unpreprocessed-propspec))
(make-propspec
:systems (union (propspec-systems first) (propspec-systems second))
:propspec
(let ((firstp (propspec-props first))
(secondp (propspec-props second)))
(if (and firstp secondp)
(destructuring-bind (1first . 1rest) firstp
(destructuring-bind (2first . 2rest) secondp
;; We used to unconditionally combine with SILENT-SEQPROPS but
;; (i) if either FIRSTP or SECONDP don't call APPLY-AND-PRINT
;; then properties get applied without any output being printed
;; which would normally be printed; and (ii) it implicitly
;; suppresses errors but we should only do that when SEQPROPS or
;; similar is used explicitly (or by DEFHOST).
(cond ((and (eql 1first 2first)
(member 1first '(eseqprops seqprops)))
(cons 1first (append 1rest 2rest)))
;; Already combined with sequencing combinators, so let
;; them handle it.
((and (member 1first '(eseqprops seqprops))
(member 2first '(eseqprops seqprops)))
`(silent-seqprops ,firstp ,secondp))
;; Avoid a pointless nested ESEQPROPS.
((eql 1first 'eseqprops)
`(eseqprops ,@1rest ,secondp))
((eql 2first 'eseqprops)
`(eseqprops ,firstp ,@2rest))
;; Default.
(t `(eseqprops ,firstp ,secondp)))))
(or firstp secondp)))))
(defmethod append-propspecs ((first null) (second unpreprocessed-propspec))
second)
(defmethod append-propspecs ((first unpreprocessed-propspec) (second null))
first)
(defmethod append-propspecs ((first null) (second null))
nil)
(defmethod eval-propspec ((propspec preprocessed-propspec))
(eval (slot-value propspec 'preprocessed-propspec-expression)))
(define-condition ambiguous-unevaluated-propspec (ambiguous-propspec) ()
(:report
(lambda (condition stream)
(format
stream
"The function, property or property combinator ~A is undefined.
Ensure that all functions, properties and property combinators used in an
unevaluated propspec are defined before that unevaluated propspec is
processed."
(cell-error-name condition)))))
(defmacro propapp (form)
"Convert a single element of an unevaluated property application specification
expression to a property application specification expression."
(flet ((evaluate (propapp)
`(list ',(car propapp) ,@(cdr propapp))))
(handler-case (map-propspec-propapps #'evaluate form t)
(ambiguous-propspec (c)
;; resignal with a more specific error message
(error 'ambiguous-unevaluated-propspec :name (cell-error-name c))))))
(defmacro props (combinator &rest forms)
"Apply variadic COMBINATOR to FORMS and convert from an unevaluated property
application specification expression to a property application specification
expression."
`(propapp ,(cons combinator forms)))
| 12,553 | Common Lisp | .lisp | 239 | 44.502092 | 80 | 0.68863 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 2d254eb4d01fa04d8cf5c451725a1715611e23ca6b3757526d767d9017107caa | 3,926 | [
-1
] |
3,927 | libcap.lisp | spwhitton_consfigurator/src/libcap.lisp | (in-package :consfigurator.util.posix1e)
(include "sys/capability.h")
(ctype cap_t "cap_t")
(ctype cap_value_t "cap_value_t")
(cenum cap_flag_t
((:cap-effective "CAP_EFFECTIVE"))
((:cap-permitted "CAP_PERMITTED"))
((:cap-inheritable "CAP_INHERITABLE")))
(cenum cap_flag_value_t ((:cap-set "CAP_SET")) ((:cap-clear "CAP_CLEAR")))
(constant (CAP_CHOWN "CAP_CHOWN"))
(constant (CAP_DAC_OVERRIDE "CAP_DAC_OVERRIDE"))
(constant (CAP_DAC_READ_SEARCH "CAP_DAC_READ_SEARCH"))
(constant (CAP_FOWNER "CAP_FOWNER"))
(constant (CAP_FSETID "CAP_FSETID"))
(constant (CAP_KILL "CAP_KILL"))
(constant (CAP_SETGID "CAP_SETGID"))
(constant (CAP_SETUID "CAP_SETUID"))
#+linux
(progn
(constant (CAP_SETPCAP "CAP_SETPCAP"))
(constant (CAP_LINUX_IMMUTABLE "CAP_LINUX_IMMUTABLE"))
(constant (CAP_NET_BIND_SERVICE "CAP_NET_BIND_SERVICE"))
(constant (CAP_NET_BROADCAST "CAP_NET_BROADCAST"))
(constant (CAP_NET_ADMIN "CAP_NET_ADMIN"))
(constant (CAP_NET_RAW "CAP_NET_RAW"))
(constant (CAP_IPC_LOCK "CAP_IPC_LOCK"))
(constant (CAP_IPC_OWNER "CAP_IPC_OWNER"))
(constant (CAP_SYS_MODULE "CAP_SYS_MODULE"))
(constant (CAP_SYS_RAWIO "CAP_SYS_RAWIO"))
(constant (CAP_SYS_CHROOT "CAP_SYS_CHROOT"))
(constant (CAP_SYS_PTRACE "CAP_SYS_PTRACE"))
(constant (CAP_SYS_PACCT "CAP_SYS_PACCT"))
(constant (CAP_SYS_ADMIN "CAP_SYS_ADMIN"))
(constant (CAP_SYS_BOOT "CAP_SYS_BOOT"))
(constant (CAP_SYS_NICE "CAP_SYS_NICE"))
(constant (CAP_SYS_RESOURCE "CAP_SYS_RESOURCE"))
(constant (CAP_SYS_TIME "CAP_SYS_TIME"))
(constant (CAP_SYS_TTY_CONFIG "CAP_SYS_TTY_CONFIG"))
(constant (CAP_MKNOD "CAP_MKNOD"))
(constant (CAP_LEASE "CAP_LEASE"))
(constant (CAP_AUDIT_WRITE "CAP_AUDIT_WRITE"))
(constant (CAP_AUDIT_CONTROL "CAP_AUDIT_CONTROL"))
(constant (CAP_SETFCAP "CAP_SETFCAP"))
(constant (CAP_MAC_OVERRIDE "CAP_MAC_OVERRIDE"))
(constant (CAP_MAC_ADMIN "CAP_MAC_ADMIN"))
(constant (CAP_SYSLOG "CAP_SYSLOG"))
(constant (CAP_WAKE_ALARM "CAP_WAKE_ALARM"))
(constant (CAP_BLOCK_SUSPEND "CAP_BLOCK_SUSPEND"))
(constant (CAP_AUDIT_READ "CAP_AUDIT_READ"))
(constant (CAP_PERFMON "CAP_PERFMON"))
(constant (CAP_BPF "CAP_BPF"))
(constant (CAP_CHECKPOINT_RESTORE "CAP_CHECKPOINT_RESTORE")))
| 2,596 | Common Lisp | .lisp | 52 | 47.153846 | 74 | 0.593541 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 19161a47a1c91625e961f128672ec3f650b218807d3ed0fe541509c9125c6db3 | 3,927 | [
-1
] |
3,928 | data.lisp | spwhitton_consfigurator/src/data.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021-2022, 2024 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator)
(named-readtables:in-readtable :consfigurator)
;;;; Prerequisite data
(defclass data ()
((data-iden1
:initarg :iden1
:initform (simple-program-error "Must supply iden1 for data.")
:reader data-iden1)
(data-iden2
:initarg :iden2
:initform (simple-program-error "Must supply iden2 for data.")
:reader data-iden2)
(data-version
:initarg :version
:initform (simple-program-error "Must supply version for data.")
:reader data-version)
(data-mime
:initarg :mime
:accessor data-mime
:documentation "The MIME type of the data, if known."))
(:documentation
"An item of prerequisite data as provided by a registered prerequisite data
source, or, outside of the root Lisp, as fished out of a local cache of
prerequisite data."))
(defclass string-data (data)
((data-string
:initarg :string
:reader data-string))
(:documentation
"An item of prerequisite data directly accessible to Lisp."))
(defclass file-data (data)
((data-cksum :initarg :cksum)
(data-file :initarg :file :reader data-file))
(:documentation
"An item of prerequisite data accessible via the filesystem."))
(defgeneric data-cksum (data)
(:documentation
"Return a CRC checksum for the data as calculated by POSIX cksum(1).")
(:method ((data file-data))
(if (slot-boundp data 'data-cksum)
(slot-value data 'data-cksum)
(setf (slot-value data 'data-cksum)
(parse-integer
(car
(split-string
(run-program `("cksum" ,(unix-namestring (data-file data)))
:output :string))))))))
;; If this proves to be inadequate then an alternative would be to maintain a
;; mapping of ASDF systems to data sources, and then DEPLOY* could look up the
;; data sources registered for the systems in (slot-value (slot-value host
;; 'propspec) 'systems) and bind *data-sources* to point to those just how it
;; binds *host* and *connection*. Registering a source would the mean
;; registering it in the mapping of systems to sources.
;;
;; Sources of data are not associated with propspecs because the latter might
;; request "/etc/foo/key.sec for whatever host I'm being applied to" using
;; FILE:HOST-DATA-UPLOADED, and different hosts in different consfigs might
;; have different data sources for that file. So one possibility is to
;; associate sources of prerequisite data to hosts, or to the consfigs which
;; define those hosts. But associating them to the root Lisp makes more
;; sense, I think, because it reflects the idea that prerequisite data sources
;; are associated with the user of the Lisp image -- what data they are able
;; to get at from this terminal.
(defgeneric register-data-source (type &key)
(:documentation
"Initialise and register a source of prerequisite data in this Lisp image.
Registered data sources are available to all deployments executed from the
root Lisp, regardless of the consfig which defines the host to which
properties are to be applied. (This could only cause problems if you have
different consfigs with prerequisite data which is identified by the same two
strings, in which case you will need to wrap your deployments with registering
and unregistering data sources. Usually items of prerequisite data are
identified using things like hostnames, so this shouldn't be necessary.)
Implementations of this function return a pair of functions.
Signals a condition MISSING-DATA-SOURCE when unable to access the data source
(e.g. because can't decrypt it). This condition is captured and ignored in
all new Lisp images started up by Consfigurator, since prerequisite data
sources are not expected to be available outside of the root Lisp."))
(define-simple-error missing-data-source)
(defvar *data-sources* nil "Known sources of prerequisite data.")
(defvar *data-source-registrations* nil
"Successful attempts to register data sources, which need not be repeated.")
(defvar *no-data-sources* nil
"If t, silently fail to register any data sources.")
(defvar *string-data* (make-hash-table :test #'equal)
"Items of STRING-DATA obtained from data sources by this Lisp image.")
(defun try-register-data-source (&rest args)
"Register sources of prerequisite data.
This function is typically called in consfigs. Any relative pathnames in ARGS
will be resolved as paths under the home directory of the user Lisp is running
as, before being passed to implementations of REGISTER-DATA-SOURCE."
(unless *no-data-sources*
(let ((home (user-homedir-pathname)))
(setq args
(loop
for arg in args
if (pathnamep arg)
collect (ensure-pathname arg :defaults home :ensure-absolute t)
else collect arg)))
(when-let ((pair (and (not (find args *data-source-registrations*
:test #'equal))
(restart-case (apply #'register-data-source args)
(skip-data-source () nil)))))
(push pair *data-sources*)
(push args *data-source-registrations*))))
(defun reset-data-sources ()
"Forget all data sources registered in this Lisp image and items of string
data obtained from data sources by this Lisp image.
This function is typically called at the REPL."
(setq *string-data* (clrhash *string-data*)
*data-sources* nil
*data-source-registrations* nil))
(defmacro with-reset-data-sources (&body body)
"Run BODY with initially empty data sources and string data.
This macro is typically used for testing or debugging."
`(let ((*string-data* (make-hash-table))
*data-sources*
*data-source-registrations*)
,@body))
(defun get-data-string (iden1 iden2)
"Return the content of an item of prerequisite data as a string.
This function is called by property :APPLY and :UNAPPLY subroutines."
(%get-data-string (funcall (%get-data iden1 iden2))))
(defun get-data-stream (iden1 iden2)
"Return a stream which will produce the content of an item of prerequisite
data. The elements of the stream are always octets. If the item of
prerequisite data was provided by the prerequisite data source as a string, it
will be encoded in UTF-8.
This function is called by property :APPLY and :UNAPPLY subroutines."
(%get-data-stream (funcall (%get-data iden1 iden2))))
(defmacro with-data-stream ((s iden1 iden2) &body body)
`(with-open-stream (,s (get-data-stream ,iden1 ,iden2))
,@body))
(define-condition missing-data (error)
((iden1 :initarg :iden1 :reader missing-iden1)
(iden2 :initarg :iden2 :reader missing-iden2))
(:report (lambda (condition stream)
(format stream "Could not provide prerequisite data ~S | ~S"
(missing-iden1 condition) (missing-iden2 condition)))))
(defun %get-data (iden1 iden2)
(alet (first-char iden1)
(unless (or (char= #\_ it) (char= #\- it) (valid-hostname-p iden1))
(simple-program-error "Invalid IDEN1: ~S" iden1)))
(let* ((idenpair (cons iden1 iden2))
(from-source (query-data-sources iden1 iden2))
(from-source-version (and from-source (car from-source)))
(in-memory (gethash idenpair *string-data*))
(in-memory-version (and in-memory (data-version in-memory)))
(local-cached
(car (remove-if-not (lambda (c)
(and (string= (first c) iden1)
(string= (second c) iden2)))
(sort-prerequisite-data-cache
(get-local-cached-prerequisite-data
(get-local-data-cache-dir))))))
(local-cached-version (caddr local-cached)))
(cond
((and in-memory
(or (not from-source) (version>= in-memory-version
from-source-version))
(or (not local-cached) (version>= in-memory-version
local-cached-version)))
(informat 3 "~&Obtaining ~S | ~S from in-memory cache" iden1 iden2)
(values (lambda () in-memory) in-memory-version))
((and from-source
(or (not in-memory) (version>= from-source-version
in-memory-version))
(or (not local-cached) (version>= from-source-version
local-cached-version)))
(informat 3 "~&Obtaining ~S | ~S from a data source" iden1 iden2)
(values
(lambda ()
(aprog1 (funcall (cdr from-source))
(when (subtypep (type-of it) 'string-data)
(setf (gethash idenpair *string-data*) it))))
from-source-version))
((and local-cached
(or (not from-source) (version>= local-cached-version
from-source-version))
(or (not in-memory) (version>= local-cached-version
in-memory-version)))
(informat 3 "~&Obtaining ~S | ~S from local cache" iden1 iden2)
(values
(lambda ()
(let ((file (apply #'local-data-pathname local-cached)))
(make-instance 'file-data
:iden1 iden1
:iden2 iden2
:version local-cached-version
:file file
:mime (try-get-file-mime-type file))))
local-cached-version))
(t
(error 'missing-data :iden1 iden1 :iden2 iden2)))))
(defmethod %get-data-stream ((data string-data))
(babel-streams:make-in-memory-input-stream
(babel:string-to-octets (data-string data) :encoding :UTF-8)
:element-type '(unsigned-byte 8)))
(defmethod %get-data-stream ((data file-data))
(open (data-file data) :direction :input
:element-type '(unsigned-byte 8)))
(defmethod %get-data-string ((data string-data))
(data-string data))
(defmethod %get-data-string ((data file-data))
(read-file-string (data-file data)))
(defun query-data-sources (iden1 iden2)
(flet ((make-thunk (v iden1 iden2)
(lambda ()
(funcall v iden1 iden2))))
(car (sort (loop for (ver . get) in *data-sources*
for version = (funcall ver iden1 iden2)
when version
collect (cons version (make-thunk get iden1 iden2)))
(lambda (x y)
(version> (car x) (car y)))))))
(defun data-source-providing-p (iden1 iden2)
"Is there a data source which can provide the item of prerequisite data
identified by IDEN1 and IDEN2?
This function is for implementation of REGISTER-DATA-SOURCE to check for
clashes. It should not be called by properties."
(if (query-data-sources iden1 iden2) t nil))
(defun maybe-write-remote-file-data
(path iden1 iden2 &key (mode nil mode-supplied-p))
"Wrapper around WRITE-REMOTE-FILE which returns :NO-CHANGE and avoids touching
PATH if PATH's content is already the prerequisite data identified by IDEN1
and IDEN2 and PATH has mode MODE."
(let ((data (funcall (%get-data iden1 iden2))))
(etypecase data
(string-data
(apply #'maybe-write-remote-file-string path (data-string data)
(and mode-supplied-p `(:mode ,mode))))
(file-data
(let ((stream (%get-data-stream data)))
(if (and (remote-exists-p path)
(multiple-value-bind (existing-mode existing-size)
(remote-file-stats path)
(and (or (not mode-supplied-p) (= mode existing-mode))
(= (file-length stream) existing-size)
(= (data-cksum data) (cksum path)))))
:no-change
(apply #'write-remote-file path stream
(and mode-supplied-p `(:mode ,mode)))))))))
(defgeneric connection-upload (connection data)
(:documentation
"Subroutine to upload an item of prerequisite data to the remote cache.
The default implementation will work for any connection which implements
CONNECTION-WRITE-FILE and CONNECTION-RUN, but connection types which work by
calling CONTINUE-DEPLOY* or CONTINUE-DEPLOY*-PROGRAM will need their own
implementation."))
(defmethod connection-upload ((connection connection) (data data))
(flet ((upload (from to)
(with-open-file (stream from :element-type '(unsigned-byte 8))
(write-remote-file to stream))))
(with-slots (data-iden1 data-iden2 data-version) data
(informat 1 "~&Uploading (~@{~S~^ ~}) ... "
data-iden1 data-iden2 data-version)
(let* ((*connection* connection)
(dest (remote-data-pathname data-iden1 data-iden2 data-version))
(destdir (pathname-directory-pathname dest))
(destfile (pathname-file dest)))
(mrun "mkdir" "-p" destdir)
(with-remote-current-directory (destdir)
(etypecase data
(string-data
(write-remote-file destfile (data-string data)))
(file-data
(let ((source (unix-namestring (data-file data))))
(if (and (slot-boundp data 'data-mime)
(string-prefix-p "text/" (data-mime data)))
(let ((destfile (strcat destfile ".gz")))
(with-temporary-file (:pathname tmp)
(run-program
(strcat "gzip -c " (sh-escape source)) :output tmp)
(upload tmp destfile)
(mrun "gunzip" destfile)))
(upload source destfile)))))))))
(inform 1 "done." :fresh-line nil))
(defgeneric connection-clear-data-cache (connection iden1 iden2)
(:documentation
"Delete all versions of the data identified by IDEN1 and IDEN2 from the remote
cache of CONNECTION. Called by UPLOAD-ALL-PREREQUISITE-DATA before uploading
new versions of data, to avoid them piling up."))
(defmethod connection-clear-data-cache ((connection connection) iden1 iden2)
(let* ((*connection* connection)
(dir (ensure-directory-pathname (remote-data-pathname iden1 iden2))))
(delete-remote-trees dir)))
(defmethod connection-connattr
((connection connection) (k (eql 'cached-data)))
(make-hash-table :test #'equal))
(defun upload-all-prerequisite-data (&optional (connection *connection*))
"Upload all prerequisite data required by the current deployment to the remote
cache of the current connection hop, or to the remote cache of CONNECTION.
This is called by implementations of ESTABLISH-CONNECTION which call
CONTINUE-DEPLOY* or CONTINUE-DEPLOY*-PROGRAM."
(flet ((record-cached-data (iden1 iden2 version)
(let ((*connection* connection))
(setf (gethash (cons iden1 iden2) (get-connattr 'cached-data))
(remote-data-pathname iden1 iden2 version)))))
(loop with *data-sources* = (cons (register-data-source :asdf)
*data-sources*)
with remote-cached
= (sort-prerequisite-data-cache
(get-remote-cached-prerequisite-data connection))
for (iden1 . iden2) in (get-hostattrs :data)
for highest-remote-version
= (caddar (remove-if-not (lambda (c)
(and (string= (first c) iden1)
(string= (second c) iden2)))
remote-cached))
for (thunk highest-local-version)
= (handler-case (multiple-value-list (%get-data iden1 iden2))
(missing-data () nil))
if (and highest-local-version
(or (not highest-remote-version)
(version> highest-local-version highest-remote-version)))
do (let ((data (funcall thunk)))
(connection-clear-data-cache connection iden1 iden2)
(connection-upload connection data)
(record-cached-data iden1 iden2 (data-version data)))
else if highest-remote-version
do (informat 3 "~&Not uploading ~S | ~S ver ~S as remote has ~S"
iden1 iden2
highest-local-version highest-remote-version)
(record-cached-data iden1 iden2 highest-remote-version)
else do (error 'missing-data :iden1 iden1 :iden2 iden2))))
(defun try-get-file-mime-type (file)
(handler-case (stripln
(run-program
(sh-escape `("file" "-E" "--mime-type" "--brief" ,file))
:output :string))
(subprocess-error () nil)))
(defun sort-prerequisite-data-cache (cache)
(sort cache (lambda (x y) (version> (third x) (third y)))))
(defun data-pathname (root &rest segments)
(destructuring-bind (last . rest)
(nreverse (mapcar #'string-to-filename segments))
(merge-pathnames last (reduce #'merge-pathnames
(mapcar (lambda (s) (strcat s "/")) rest)
:from-end t :initial-value root))))
(defun local-data-pathname (&optional iden1 iden2 version)
"Get a pathname where an item of prerequisite data may be cached, ensuring
that parent directories exist.
This is exported for use by prerequisite data sources which work by generating
new files and need somewhere to store them. It should not be used by
properties, or data sources which return objects referencing existing files.
Note that since prerequisite data sources are queried only in the root Lisp,
but items of prerequisite data are never uploaded to the root Lisp, there is
no risk of clashes between fresly generated files and cached copies of files."
(let ((pn (apply #'data-pathname (get-local-data-cache-dir)
(delete nil (list iden1 iden2 version)))))
(ensure-directories-exist
(if version pn (ensure-directory-pathname pn)))))
(defun remote-data-pathname (&rest args)
(apply #'data-pathname
(merge-pathnames "data/" (get-connattr :consfigurator-cache)) args))
;;;; Remote caches
(defgeneric get-remote-cached-prerequisite-data (connection)
(:documentation
"Return a list of items of prerequisite data in the cache on the remote side
of CONNECTION, where each entry is of the form
'(iden1 iden2 version)."))
(defmethod get-remote-cached-prerequisite-data ((connection connection))
(let* ((*connection* connection)
(dir (unix-namestring
(merge-pathnames "data/" (get-connattr :consfigurator-cache))))
(drop (1- (length (split-string dir :separator "/")))))
(mapcar (lambda (line)
(mapcar #'filename-to-string
(nthcdr drop (split-string line :separator "/"))))
(multiple-value-bind (out exit)
(mrun :may-fail "find" dir "-type" "f")
(and (zerop exit) (lines out))))))
;;;; Local caches
(defun get-local-cached-prerequisite-data (where)
"Scan a local cache of prerequisite data at WHERE, and return a list of
items of prerequisite data where each entry is of the form
'(iden1 iden2 version).
This is exported for use by implementations of CONNECTION-UPLOAD, which should
always supply a value for WHERE."
(loop for dir in (subdirectories where)
nconc (loop for subdir in (subdirectories dir)
nconc (loop for file in (directory-files subdir)
collect
(mapcar #'filename-to-string
(list (lastcar
(pathname-directory dir))
(lastcar
(pathname-directory subdir))
(pathname-file file)))))))
(defun get-highest-local-cached-prerequisite-data (iden1 iden2)
"Get the highest version of prerequisite data identified by IDEN1 and IDEN2
available in the local cache.
This is exported for use by prerequisite data sources which work by generating
new files and need somewhere to store them. It should not be used by
properties, or data sources which return objects referencing existing files."
(when-let ((triple (car (remove-if-not
(lambda (c)
(and (string= (car c) iden1)
(string= (cadr c) iden2)))
(sort-prerequisite-data-cache
(get-local-cached-prerequisite-data
(get-local-data-cache-dir)))))))
(make-instance 'file-data :file (apply #'local-data-pathname triple)
:iden1 (car triple)
:iden2 (cadr triple)
:version (caddr triple))))
(defun get-local-data-cache-dir ()
(merge-pathnames
"data/"
;; A combinator like WITH-HOMEDIR might have temporarily set the HOME
;; and/or XDG_CACHE_HOME environment variables, so use a cached value if we
;; can find one.
(or (loop for conn = *connection* then (connection-parent conn)
while conn
when (subtypep (type-of conn) 'lisp-connection)
return (connection-connattr conn :consfigurator-cache))
(connection-connattr
(establish-connection :local nil) :consfigurator-cache))))
;;;; Passphrases
(defclass wrapped-passphrase ()
((passphrase :initarg :passphrase :reader unwrap-passphrase)))
(defun wrap-passphrase (passphrase)
"Make an object which is unprintable by default to contain a passphrase."
(make-instance 'wrapped-passphrase :passphrase passphrase))
(defun get-data-protected-string (iden1 iden2)
"Like GET-DATA-STRING, but wrap the content in an object which is unprintable
by default. Intended for code which fetches passwords and wants to lessen the
chance of those passwords showing up in the clear in the Lisp debugger."
(wrap-passphrase (get-data-string iden1 iden2)))
(defvar *allow-printing-passphrases* nil)
(defmethod print-object ((passphrase wrapped-passphrase) stream)
(if *allow-printing-passphrases*
(format stream "#.~S"
`(make-instance 'wrapped-passphrase
:passphrase ,(unwrap-passphrase passphrase)))
(print-unreadable-object (passphrase stream)
(format stream "PASSPHRASE")))
passphrase)
(defvar *data-source-gnupghome* nil
"Home directory for gnupg when used in a data source.
Because gnupg uses Unix domain sockets internally, this path should be short
enough to avoid the 108 char limit on socket paths.")
| 23,395 | Common Lisp | .lisp | 454 | 42.42511 | 81 | 0.650105 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | ebb67515e6e0a1c3e79e90616e93d4c9fa9947d92557c5e83f2e357e858f7504 | 3,928 | [
-1
] |
3,929 | util.lisp | spwhitton_consfigurator/src/data/util.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2022 David Bremner <[email protected]>
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.data.util)
(named-readtables:in-readtable :consfigurator)
(defun literal-data-pathname (base-path iden1 iden2 &key type)
"Generate a path from BASE-PATH, IDEN1 and IDEN2 by concatentation,
optionally adding extension TYPE.
No escaping of special characters is done, but extra '/' characters between
pathname components are removed.
The intended use case is to map IDEN1 and IDEN2 to files in a user-maintained
hierarchy under BASE-PATH. In particular IDEN2 and (if prefixed by '_') IDEN1
may contain '/' characters to map into multiple levels of directory."
(let ((base-dir (parse-unix-namestring base-path :ensure-directory t)))
(unless (directory-pathname-p base-dir)
(simple-program-error "~A does not specify a directory" base-dir))
(merge-pathnames
(uiop:relativize-pathname-directory
(parse-unix-namestring iden2 :type type))
(merge-pathnames
(uiop:relativize-pathname-directory
(ensure-directory-pathname iden1))
base-dir))))
(defun gpg (args &key input output)
"Run gnupg, taking homedir from *DATA-SOURCE-GNUPGHOME* if set.
INPUT and OUTPUT have the same meaning as for RUN-PROGRAM, except that OUTPUT
defaults to :STRING. The default return value is thus the output from gnupg,
as a string."
(run-program
`("gpg"
,@(and *data-source-gnupghome*
(list "--homedir" (namestring *data-source-gnupghome*)))
,@args)
:input input
:output (or output :string)))
(defun gpg-file-as-string (location)
"Decrypt the contents of a gpg encrypted file at LOCATION, return as a
string."
(handler-case
(gpg (list "--decrypt" (unix-namestring location)))
(subprocess-error (error)
(missing-data-source "While attempt to decrypt ~A, gpg exited with ~A"
location (uiop:subprocess-error-code error)))))
| 2,667 | Common Lisp | .lisp | 53 | 46.962264 | 78 | 0.742221 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | c6655b833984886950fd09406f4f79bd627e47e9bd28486df152b8a213d5c77b | 3,929 | [
-1
] |
3,930 | pass.lisp | spwhitton_consfigurator/src/data/pass.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2022 David Bremner <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.data.pass)
(named-readtables:in-readtable :consfigurator)
(defmethod register-data-source ((type (eql :pass))
&key (location "~/.password-store"))
"Provide the contents of a pass(1) store on the machine running the root
Lisp. Register this data source multiple times to provide multiple stores.
LOCATION specifies the root of the password store.
LOCATION, IDEN1, and IDEN2 are concatenated to locate a file in the password
store.
For retrieving user account passwords, IDEN1 can be a valid hostname or
'--user-passwd--HOST' where HOST is a valid hostname, and IDEN2 the username.
Otherwise, IDEN1 should begin with '_' (see the 'Prerequisite Data' section of
the Consfigurator user's manual). In the latter case, if the concatenated
path does not exist in the password store then the search is tried again after
dropping the '_'. This means that while user consfigs should always prefix
any IDEN1 that is not a valid hostname or of the form '--user-passwd--HOST'
with '_', existing pass(1) entries do not need to be renamed. Other forms for
IDEN1 are not supported by this data source."
(let ((base-path (ensure-directory-pathname location)))
(unless (directory-exists-p base-path)
(missing-data-source
"~A does not exist, or is not a directory." base-path))
(labels
((%gpg-file-p (iden1 iden2)
(file-exists-p
(literal-data-pathname base-path iden1 iden2 :type "gpg")))
(%make-path (iden1 iden2)
(acond
((strip-prefix "--user-passwd--" iden1)
(and (valid-hostname-p it) (%gpg-file-p it iden2)))
((strip-prefix "_" iden1)
(or (%gpg-file-p iden1 iden2) (%gpg-file-p it iden2)))
(t
(and (valid-hostname-p iden1) (%gpg-file-p iden1 iden2)))))
(check (iden1 iden2)
(when-let ((file-path (%make-path iden1 iden2)))
(file-write-date file-path)))
(extract (iden1 iden2)
(when-let ((file-path (%make-path iden1 iden2)))
(make-instance 'string-data
:string (stripln (gpg-file-as-string file-path))
:iden1 iden1
:iden2 iden2
:version (file-write-date file-path)))))
(cons #'check #'extract))))
| 3,155 | Common Lisp | .lisp | 57 | 47.631579 | 78 | 0.665588 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | e07c6714805d20252e9972e3a39e15896eee48863440b62c2466109a21b0fd2b | 3,930 | [
-1
] |
3,931 | gpgpubkeys.lisp | spwhitton_consfigurator/src/data/gpgpubkeys.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.data.gpgpubkeys)
(named-readtables:in-readtable :consfigurator)
(defmethod register-data-source
((type (eql :gpgpubkeys)) &key keyring try-recv-key)
"Obtain ASCII-armoured PGP public keys by querying local gpg keyring KEYRING.
If TRY-RECV-KEY, try to add any missing keys to KEYRING by querying keyservers
configured in dirmngr.conf."
(unless (file-exists-p keyring)
(missing-data-source "~A does not exist." keyring))
(let (cache lastmod)
(labels ((reset-cache (&optional (new-lastmod (file-write-date keyring)))
(setq cache (make-hash-table :test #'equal)
lastmod new-lastmod))
(retrieve (iden1 fingerprint)
(declare (ignore iden1))
(let ((new-lastmod (file-write-date keyring)))
(when (> new-lastmod lastmod)
(reset-cache new-lastmod)))
(or (gethash fingerprint cache)
(multiple-value-bind (key queriedp)
(getkey keyring fingerprint try-recv-key)
(when queriedp (reset-cache))
(and key
(setf (gethash fingerprint cache)
(make-instance 'string-data
:string key
:mime "application/pgp-keys"
:iden1 "--pgp-pubkey"
:iden2 fingerprint
:version lastmod))))))
(check (iden1 iden2)
;; We can't avoid running gpg(1) to find out whether a PGP key
;; is available, so we might as well just do the extraction
;; work when asked whether we can extract.
(and (string= iden1 "--pgp-pubkey")
(let ((retrieved (retrieve nil iden2)))
(and retrieved (data-version retrieved))))))
(reset-cache)
(cons #'check #'retrieve))))
(defun local-getkey (keyring fingerprint)
(multiple-value-bind (output _ exit-code)
(run-program `("gpg" "--armor" "--no-default-keyring"
"--keyring" ,(namestring keyring)
"--export-options" "export-minimal"
"--export" ,fingerprint)
:output :string :ignore-error-status t)
(declare (ignore _))
(let ((key (stripln output)))
(and (zerop exit-code) (not (string-equal "" key)) key))))
(defun getkey (keyring fingerprint try-recv-key)
(let ((local (local-getkey keyring fingerprint)))
(when (or local (not try-recv-key))
(return-from getkey (values local nil)))
(let ((exit-code
(nth-value
2 (run-program
`("gpg" "--no-default-keyring"
"--keyring" ,(namestring keyring)
"--recv-key" ,fingerprint)
:output :string :ignore-error-status t))))
(when (zerop exit-code)
(values (local-getkey keyring fingerprint) t)))))
| 3,926 | Common Lisp | .lisp | 74 | 39.662162 | 79 | 0.574922 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 10355e2a93a1a12736faea4e733b230893c1dc34435c5347ec025ceed398a21a | 3,931 | [
-1
] |
3,932 | files-tree.lisp | spwhitton_consfigurator/src/data/files-tree.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 David Bremner <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.data.files-tree)
(named-readtables:in-readtable :consfigurator)
(defmethod register-data-source ((type (eql :files-tree)) &key location)
"Provide the contents of a local directory on the machine running the root
Lisp. Register this data source multiple times to provide multiple trees.
LOCATION is either a designator for a pathname representing the root of the
tree of files or a symbol which designates an ASDF package where the tree is
contained in the subdirectory 'data/'.
LOCATION, IDEN1 and IDEN2 are concatenated to locate files. Thus, IDEN1
specifies a (possibly nested) subdirectory under LOCATION and IDEN2 a relative
path within that subdirectory.
Special characters in IDEN1 and IDEN2 are not encoded. This means that each
character in IDEN1 and IDEN2 must be permitted in filenames on this system,
and that any slashes in IDEN1 and IDEN2 will probably act as path separators.
For convenience IDEN1 and IDEN2 may be passed as absolute and will be
converted to relative paths. The usual cases of IDEN1 as a hostname, IDEN1 as
an underscore-prefixed identifier, and IDEN2 an an absolute or relative path
are all supported."
(let ((base-path (if (symbolp location)
(asdf:system-relative-pathname location "data/")
(ensure-directory-pathname location))))
(unless (directory-exists-p base-path)
(missing-data-source
"~A does not exist, or is not a directory." base-path))
(labels ((check (iden1 iden2)
(let ((file-path (literal-data-pathname base-path iden1 iden2)))
(and (file-exists-p file-path)
(file-write-date file-path))))
(extract (iden1 iden2)
(let ((file-path (literal-data-pathname base-path iden1 iden2)))
(and (file-exists-p file-path)
(make-instance 'file-data
:file file-path
:iden1 iden1
:iden2 iden2
:version (file-write-date file-path))))))
(cons #'check #'extract))))
| 2,941 | Common Lisp | .lisp | 49 | 51.714286 | 79 | 0.688411 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 0ff785e21f6d7d63b9303b258b476540c4204e3391aa3d0959c2c7d573f06e39 | 3,932 | [
-1
] |
3,933 | git-snapshot.lisp | spwhitton_consfigurator/src/data/git-snapshot.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.data.git-snapshot)
(named-readtables:in-readtable :consfigurator)
(defmethod register-data-source ((type (eql :git-snapshot))
&key name repo depth branch)
"Provide tarball snapshots of a branch of a local git repository.
Provides prerequisite data identified by \"--git-snapshot\", \"NAME\".
Rather than using git-bundle(1) or git-archive(1), we create a (possibly
shallow) clone and tar it up. That way, it's still a git repo on the remote
side, but we don't require git to be installed on the remote side to get a
copy of the working tree over there."
(when (data-source-providing-p "--git-snapshot" name)
(simple-program-error
"Another data source is providing git snapshots identified by ~S." name))
(with-current-directory (repo)
(unless (zerop (nth-value 2 (run-program '("git" "rev-parse" "--git-dir")
:ignore-error-status t)))
(missing-data-source "~A is not a git repository." repo)))
(let* ((cached
(get-highest-local-cached-prerequisite-data "--git-snapshot" name))
(cached-commit (and cached (nth 1 (split-string (data-version cached)
:separator ".")))))
(when cached
(setf (data-mime cached) "application/gzip"))
(labels ((latest-version (tip)
(format nil "~A.~A" (get-universal-time) tip))
(check (iden1 iden2)
(and (string= iden1 "--git-snapshot")
(string= iden2 name)
(let ((tip (get-branch-tip repo branch)))
(if (and cached-commit (string= cached-commit tip))
(data-version cached)
(latest-version tip)))))
(extract (&rest ignore)
(declare (ignore ignore))
(let* ((tip (get-branch-tip repo branch))
(version (latest-version tip))
(path (local-data-pathname
"--git-snapshot" name version)))
(if (and cached-commit (string= cached-commit tip))
cached
(progn
(ignore-errors
(mapc #'delete-file
(directory-files
(pathname-directory-pathname path))))
(make-snapshot name repo depth branch path)
(setq cached-commit tip
cached (make-instance 'file-data
:file path
:mime "application/gzip"
:iden1 "--git-snapshot"
:iden2 name
:version version)))))))
(cons #'check #'extract))))
(defun make-snapshot (name repo depth branch output)
(with-local-temporary-directory (dir)
(let ((loc (ensure-directory-pathname (merge-pathnames name dir))))
(run-program `("git" "clone"
"--no-hardlinks"
,@(and depth `("--depth" ,(write-to-string depth)))
"--origin" "local"
,@(and branch (list "--branch" branch))
,(strcat "file://" (namestring repo))
,(namestring loc)))
(with-current-directory (loc)
(run-program '("git" "remote" "rm" "local")))
(delete-directory-tree (merge-pathnames ".git/refs/remotes/local/" loc)
:validate t :if-does-not-exist :ignore)
(with-current-directory (dir)
(run-program
`("tar" "cfz" ,(namestring output) ,(namestring name)))))))
(defun get-branch-tip (repo branch)
(with-current-directory (repo)
(stripln
(run-program `("git" "rev-parse" "--verify" ,(strcat branch "^{commit}"))
:output :string))))
| 4,872 | Common Lisp | .lisp | 88 | 40.090909 | 78 | 0.547644 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | f3326ee1235d38416fa2be1ac3813f5a0da66e1ff34e4f2b22d79af77659a138 | 3,933 | [
-1
] |
3,934 | pgp.lisp | spwhitton_consfigurator/src/data/pgp.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.data.pgp)
(named-readtables:in-readtable :consfigurator)
;; Simple PGP-encrypted file source of prerequisite data
;; We provide an implementation of REGISTER-DATA-SOURCE and functions for the
;; user to call at the REPL to add pieces of data, see what's there, etc. (a
;; prerequisite data source which was some sort of external file-generating or
;; secrets storage database might not provide any functions for the REPL).
;;
;; You will need to use SET-DATA to create an encrypted store before
;; attempting to call REGISTER-DATA-SOURCE in your consfig.
(defmethod register-data-source ((type (eql :pgp)) &key location)
(unless (file-exists-p location)
(error 'missing-data-source
:text (format nil "Could not open ~A" location)))
(let ((mod (file-write-date location))
(cache (read-store location)))
(labels ((update-cache ()
(let ((new-mod (file-write-date location)))
(when (> new-mod mod)
(setq mod new-mod
cache (read-store location)))))
(check (iden1 iden2)
(update-cache)
(cadr (data-assoc iden1 iden2 cache)))
(extract (iden1 iden2)
(update-cache)
(let ((data (data-assoc iden1 iden2 cache)))
(make-instance 'string-data
:iden1 iden1 :iden2 iden2
:string (cddr data) :version (cadr data)))))
(cons #'check #'extract))))
(defun read-store (location)
(safe-read-from-string
(gpg-file-as-string location)))
(defun put-store (location data)
(gpg '("--encrypt")
:input (make-string-input-stream
(with-standard-io-syntax
(prin1-to-string data)))
:output (unix-namestring location)))
(defun data-assoc (iden1 iden2 data)
(assoc (cons iden1 iden2) data
:test (lambda (x y)
(and (string= (car x) (car y))
(string= (cdr x) (cdr y))))))
(defun get-data (location iden1 iden2)
"Fetch a piece of prerequisite data.
Useful at the REPL."
(cddr (data-assoc iden1 iden2 (read-store location))))
(defun set-data (location iden1 iden2 val)
"Set a piece of prerequisite data.
Useful at the REPL."
(let ((data (delete-if
(lambda (d)
(and (string= (caar d) iden1) (string= (cdar d) iden2)))
(and (file-exists-p location) (read-store location)))))
(push (cons (cons iden1 iden2) (cons (get-universal-time) val)) data)
(put-store location data)))
(defun set-data-from-file (location iden1 iden2 file)
"Set a piece of prerequisite data from the contents of a file.
Useful at the REPL."
(set-data location iden1 iden2 (read-file-string file)))
(defun list-data (location)
"List all prerequisite data in the PGP store at LOCATION.
Useful at the REPL."
(dolist (item (read-store location))
(format t "~A ~A~%" (caar item) (cdar item))))
| 3,787 | Common Lisp | .lisp | 79 | 40.898734 | 78 | 0.655733 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 700d71d2b8209f0dedf5cd27abc5749730d60c3f77cc9dca0297936d6ee73d03 | 3,934 | [
-1
] |
3,935 | ssh-askpass.lisp | spwhitton_consfigurator/src/data/ssh-askpass.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.data.ssh-askpass)
(named-readtables:in-readtable :consfigurator)
(defmethod register-data-source
((type (eql :ssh-askpass)) &key iden1-re iden2-re)
"Data source which will attempt to provide any piece of data matching the
CL-PPCRE regular expressions IDEN1-RE and IDEN2-RE, obtaining the data by
using ssh-askpass(1) to prompt the user to input it. Useful for things like
sudo passwords."
(unless (getenv "DISPLAY")
(missing-data-source "DISPLAY not set; cannot launch ssh-askpass(1)."))
;; This cache duplicates CONSFIGURATOR::*STRING-DATA*, but if we don't keep
;; our own cache here, then we would always have to return the current time
;; from the first closure, and then we'd prompt the user for input every
;; time, bypassing CONSFIGURATOR::*STRING-DATA*.
(let ((cache (make-hash-table :test #'equal)))
(cons
(lambda (iden1 iden2)
(and (re:scan iden1-re iden1)
(re:scan iden2-re iden2)
(if-let ((cached (gethash (cons iden1 iden2) cache)))
(data-version cached) (get-universal-time))))
(lambda (iden1 iden2)
(let ((pair (cons iden1 iden2)))
(or (gethash pair cache)
(setf (gethash pair cache)
(loop with msg
for first = (ssh-askpass iden1 iden2 msg)
for second = (ssh-askpass iden1 iden2 "confirm")
if (string= first second)
return (make-instance
'string-data
:string first :mime "text/plain"
:version (get-universal-time)
:iden1 iden1 :iden2 iden2)
else do (setq msg "did not match; try again")))))))))
(defun ssh-askpass (iden1 iden2 &optional note)
(stripln (run-program
(list "ssh-askpass"
(format nil "~A | ~A~:[~; (~:*~A)~]" iden1 iden2 note))
:output :string)))
| 2,814 | Common Lisp | .lisp | 52 | 44.519231 | 78 | 0.632668 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 2b61a83768a080a9323048c0bff35b202e55a48e6aef2cec898e10591d4c408d | 3,935 | [
-1
] |
3,936 | asdf.lisp | spwhitton_consfigurator/src/data/asdf.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.data.asdf)
(named-readtables:in-readtable :consfigurator)
(defmethod register-data-source ((type (eql :asdf)) &key)
(cons #'asdf-data-source-check #'get-path-to-system-tarball))
(defun asdf-data-source-check (iden1 system)
(let ((system (and (string= iden1 "--lisp-system")
(asdf:find-system system nil))))
(and system (system-version-files system))))
(defun get-path-to-system-tarball (iden1 system)
(let* ((tarball (merge-pathnames
(strcat "consfigurator/systems/" system ".tar.gz")
(uiop:xdg-cache-home)))
(tarball-write-date
(and (file-exists-p tarball) (file-write-date tarball))))
(multiple-value-bind (version files) (system-version-files system)
(if (and tarball-write-date (>= tarball-write-date version))
(setq version tarball-write-date)
(let* ((dir (asdf:system-source-directory system))
(relative
(loop for file in files
if (subpathp file dir)
collect (unix-namestring
(enough-pathname file dir))
else
do (error "~A is not a subpath of ~A." file dir))))
(run-program
(list* "tar" "-C" (unix-namestring dir)
"-czf" (unix-namestring (ensure-directories-exist tarball))
relative))))
(make-instance 'file-data :file tarball :mime "application/gzip"
:iden1 iden1 :iden2 system :version version))))
(defun system-version-files (system)
(let* ((system (asdf:find-system system))
(name (asdf:component-name system))
(file (asdf:system-source-file system))
(written (file-write-date file)))
(unless (string= (pathname-name file) name)
(error "Cannot upload secondary systems directly."))
(labels ((recurse (component)
(let ((pathname (asdf:component-pathname component))
(rest (and (compute-applicable-methods
#'asdf:component-children (list component))
(mapcan #'recurse
(asdf:component-children component)))))
(if (and pathname (file-exists-p pathname))
(progn (maxf written (file-write-date pathname))
(cons pathname rest))
rest))))
;; We include secondary systems because otherwise, for systems using the
;; package-inferred-system extension, we could end up uploading a huge
;; number of tarballs. We need to ensure SYSTEM is loaded so that all
;; the secondary systems are known to ASDF.
(asdf:load-system system)
(let ((files
(nconc
(recurse system)
(loop for other in (asdf:registered-systems)
for other* = (asdf:find-system other)
when (and (not (eql system other*))
(string= name (asdf:primary-system-name other*)))
nconc (recurse other*)))))
(values written (cons file files))))))
| 4,050 | Common Lisp | .lisp | 74 | 42.081081 | 80 | 0.595664 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 4d3e1bd25e3414e437e0357225b548c98a9a460c5dc6f85d4aad775eb21b8022 | 3,936 | [
-1
] |
3,937 | local-file.lisp | spwhitton_consfigurator/src/data/local-file.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.data.local-file)
(named-readtables:in-readtable :consfigurator)
(defmethod register-data-source
((type (eql :local-file)) &key location version iden1 iden2)
"Provide the contents of a single local file on the machine running the root
Lisp. Register this data source more than once to provide multiple files.
The version of the data provided is either VERSION or the file's last
modification time."
(unless (file-exists-p location)
(missing-data-source "~A does not exist." location))
(cons (lambda (iden1* iden2*)
(and (string= iden1 iden1*) (string= iden2 iden2*)
(file-exists-p location)
(or version (file-write-date location))))
(lambda (iden1* iden2*)
(and (string= iden1 iden1*) (string= iden2 iden2*)
(file-exists-p location)
(make-instance 'file-data
:file location
:iden1 iden1 :iden2 iden2
:version (or version
(file-write-date location)))))))
| 1,886 | Common Lisp | .lisp | 34 | 47.382353 | 78 | 0.670639 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 601fe6efb4b367ca046fd7cee39c6c439bc29675ef15f66d82bd8bd36cf8c9c0 | 3,937 | [
-1
] |
3,938 | ssh.lisp | spwhitton_consfigurator/src/connection/ssh.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.connection.ssh)
(named-readtables:in-readtable :consfigurator)
(defmethod establish-connection ((type (eql :ssh)) remaining
&key
(hop (get-hostname))
user)
(declare (ignore remaining))
(informat 1 "~&Establishing SSH connection to ~A" hop)
(aprog1 (make-instance 'ssh-connection :hostname hop :user user)
(mrun "ssh" (ssh-host it) ":")))
(defclass ssh-connection (shell-wrap-connection)
((hostname
:initarg :hostname
:documentation "Hostname to SSH to.")
;; This is deliberately distinct from the :REMOTE-USER connattr.
(user
:initarg :user
:documentation "User to log in as."))
(:documentation "Deploy properties using non-interactive SSH."))
(defun ssh-host (connection)
(if-let ((user (slot-value connection 'user)))
(format nil "~A@~A" user (slot-value connection 'hostname))
(slot-value connection 'hostname)))
(defmethod connection-shell-wrap ((connection ssh-connection) cmd)
;; wrap in 'sh -c' in case the login shell is not POSIX
(format nil "ssh ~A ~A"
(ssh-host connection)
(sh-escape (format nil "sh -c ~A" (sh-escape cmd)))))
| 2,012 | Common Lisp | .lisp | 40 | 44.75 | 74 | 0.69027 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | cd440149083dccfcb11dde160d153719ef2cdb3fd94f8e68a8c3bb16f2009dbb | 3,938 | [
-1
] |
3,939 | rehome.lisp | spwhitton_consfigurator/src/connection/rehome.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.connection.rehome)
(named-readtables:in-readtable :consfigurator)
(defclass rehome-connection ()
((rehome-datadir
:type :string :initarg :rehome-datadir :reader rehome-datadir
:documentation
"Where Consfigurator would cache items of prerequisite data in the new HOME,
as accessible from the previous connection hop.
In the case of a connection which chroots, for example, this will be the path
to a directory inside the chroot as seen from outside the chroot."))
(:documentation
"A connection which works by switching to a new HOME on the same host."))
(defmethod continue-connection
:before ((connection rehome-connection) remaining)
(upload-all-prerequisite-data connection))
(defmethod connection-upload ((connection rehome-connection) (data file-data))
(with-slots (data-iden1 data-iden2 data-version) data
(let ((inside
(data-pathname
(rehome-datadir connection) data-iden1 data-iden2 data-version))
(outside (remote-data-pathname data-iden1 data-iden2 data-version)))
(mrun "mkdir" "-p" (pathname-directory-pathname inside))
(if (remote-exists-p outside)
(mrun "cp" outside inside)
(let (done)
(unwind-protect
(progn
(connection-upload (connection-parent connection) data)
(mrun "mv" outside inside)
(setq done t))
(unless done (mrun "rm" "-f" outside))))))))
(defmethod connection-clear-data-cache
((connection rehome-connection) iden1 iden2)
(delete-remote-trees
(data-pathname (rehome-datadir connection) iden1 iden2)))
(defmethod get-remote-cached-prerequisite-data
((connection rehome-connection))
(get-local-cached-prerequisite-data (rehome-datadir connection)))
| 2,598 | Common Lisp | .lisp | 50 | 46.32 | 83 | 0.718959 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 18325bd6a5b58d6325714b9ab6b7a8a1e3082b1b7bfac38bce837b1e6c431223 | 3,939 | [
-1
] |
3,940 | sudo.lisp | spwhitton_consfigurator/src/connection/sudo.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.connection.sudo)
(named-readtables:in-readtable :consfigurator)
;; Note that a password needed to sudo is technically not a piece of
;; prerequisite data required by a deployment, because it is not used in
;; deploying properties in the context of a connection chain which has already
;; been fully established. Nevertheless, we can query sources of prerequisite
;; data to obtain passwords by following the conventions for having
;; prerequisite data sources provide them.
(defmethod preprocess-connection-args ((type (eql :sudo)) &key from (user "root"))
(list :sudo
:user user
:password (and
from
(destructuring-bind (user host)
(split-string from :separator "@")
(get-data-protected-string
(strcat "--user-passwd--" host) user)))))
;; With sudo -S, we must ensure that sudo's stdin is a pipe, not a file,
;; because otherwise the program sudo invokes may rewind(stdin) and read the
;; password, intentionally or otherwise. And UIOP:RUN-PROGRAM empties input
;; streams into temporary files, so there is the potential for this to happen
;; when using :SUDO to apply properties to localhost. Other connection types
;; might work similarly.
;;
;; The simplest way to handle this would be to just put 'cat |' at the
;; beginning of the shell command we construct, but that relies on cat(1) not
;; calling rewind(stdin) either. So we write the password input out to a
;; temporary file ourselves, and use cat(1) to concatenate that file with the
;; actual input.
(defclass sudo-connection (shell-wrap-connection)
((password-file :initarg :password-file)))
(defmethod establish-connection ((type (eql :sudo))
remaining
&key
user
password)
(declare (ignore remaining))
(informat 1 "~&Establishing sudo connection to ~A" user)
(make-instance
'sudo-connection
:connattrs `(:remote-user ,user)
:password-file
(and password
(aprog1 (mktemp)
;; We'll send the password followed by ^M, then the real stdin. Use
;; CODE-CHAR in this way so that we can be sure ASCII ^M is what
;; will get emitted.
(write-remote-file it (strcat (unwrap-passphrase password)
(string (code-char 13)))
:mode #o600)))))
(defmethod connection-tear-down :after ((connection sudo-connection))
(when-let ((file (slot-value connection 'password-file)))
(delete-remote-trees file)))
(defmethod connection-run ((connection sudo-connection) cmd input)
(let* ((file (slot-value connection 'password-file))
(user (connection-connattr connection :remote-user))
(prefix (if file
(format nil "cat ~A - | sudo -HkS --prompt=\"\""
(sh-escape file))
"sudo -Hkn")))
;; Wrap in sh -c so that it is more likely we are either asked for a
;; password for all our commands or not asked for one for any.
;;
;; Preserve SSH_AUTH_SOCK for root to enable this sort of workflow: deploy
;; laptop using (:SUDO :SBCL) and then DEFHOST for laptop contains
;; (DEPLOYS ((:SSH :USER "root")) ...) to deploy a VM on the laptop.
;;
;; This only works for sudoing to root because only the superuser can
;; access the socket (and was always able to, so we're not granting new
;; access which may be unwanted).
(mrun :may-fail :input input
(format nil
"~A ~:[~;--preserve-env=SSH_AUTH_SOCK ~]--user=~A sh -c ~A"
prefix (string= user "root") user (sh-escape cmd)))))
| 4,588 | Common Lisp | .lisp | 86 | 45.44186 | 82 | 0.657461 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | dde3d039c08e6e7824dd55c730fef6bba59f8fb1ba83b3b1c203fde5d64cfb87 | 3,940 | [
-1
] |
3,941 | local.lisp | spwhitton_consfigurator/src/connection/local.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2020-2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.connection.local)
(named-readtables:in-readtable :consfigurator)
(defmethod establish-connection ((type (eql :local)) host &key)
(make-instance 'local-connection))
(defclass local-connection (lisp-connection)
()
(:documentation
"Applying properties to the machine Lisp is running on, as Lisp's uid."))
(defmethod connection-run ((c local-connection) cmd (s stream))
;; see https://gitlab.common-lisp.net/asdf/asdf/-/issues/59
(call-next-method c cmd `(,s :element-type ,(stream-element-type s))))
(defmethod connection-run ((c local-connection) cmd (s string))
(call-next-method c cmd (make-string-input-stream s)))
(defmethod connection-run ((connection local-connection) shell-cmd input)
(multiple-value-bind (output _ exit-code)
;; call sh(1) so we know we'll get POSIX
(run-program `("sh" "-c" ,shell-cmd)
:input input :output :string
:error-output :output :ignore-error-status t)
(declare (ignore _))
(values output exit-code)))
(defmethod connection-read-file ((connection local-connection) path)
(read-file-string path))
(defmethod connection-read-and-remove-file ((connection local-connection) path)
(prog1 (read-file-string path) (delete-file path)))
(defmethod connection-write-file ((connection local-connection)
path
content
mode)
;; we cannot use UIOP:WITH-TEMPORARY-FILE etc., because those do not ensure
;; the file is only readable by us, and we might be writing a secret key
(with-remote-temporary-file
(temp :connection connection
:directory (pathname-directory-pathname path))
(nix:chmod temp mode)
(etypecase content
(string
(with-open-file (stream temp :direction :output :if-exists :supersede)
(write-string content stream)))
(stream
(let ((type (stream-element-type content)))
(with-open-file (stream temp :direction :output
:if-exists :supersede
:element-type type)
(copy-stream-to-stream content stream :element-type type)))))
;; TEMP's pathname will always have a PATHNAME-TYPE which is the random
;; string of characters suffixed to make the filename unique. If PATH
;; doesn't have a file extension then the merging behaviour of RENAME-FILE
;; will add the random suffix as the file type of the rename destination.
;; So we make two new pathnames.
(flet ((detype-pathname (pn)
(make-pathname
:defaults uiop:*nil-pathname* :type :unspecific
:name (pathname-file pn) :directory (pathname-directory pn))))
(rename-file-overwriting-target
(detype-pathname temp) (detype-pathname path)))))
(defmethod connection-connattr
((connection local-connection) (k (eql :XDG_CACHE_HOME)))
(uiop:xdg-cache-home))
| 3,764 | Common Lisp | .lisp | 71 | 45.788732 | 79 | 0.681979 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | f3d615e42bf82e1d44ac8160872962c66e3301d39981b424dbb3764b56ee52a9 | 3,941 | [
-1
] |
3,942 | as.lisp | spwhitton_consfigurator/src/connection/as.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.connection.as)
(named-readtables:in-readtable :consfigurator)
;; currently we only check whether we're root, but, for example, on Linux, we
;; might have a CAP_* which lets us setuid as non-root
(defun can-setuid ()
(zerop (nix:geteuid)))
(defmethod establish-connection ((type (eql :as)) remaining &key user)
"Establish a :SETUID or :SU connection to another user account, depending on
whether it is possible to establish a :SETUID connection.
Note that both these connection types require root."
;; An alternative to :SU would be :SUDO or runuser(1), but :SU is more
;; portable.
(let ((setuid (and (lisp-connection-p) (can-setuid))))
(establish-connection
(if setuid :setuid :su) remaining (if setuid :user :to) user)))
| 1,541 | Common Lisp | .lisp | 27 | 55.074074 | 78 | 0.750332 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 0e397afbbcb6fa44178b9a6a5d0e0fcdda0ad641f8681256ff4789d6a74ccd7a | 3,942 | [
-1
] |
3,943 | su.lisp | spwhitton_consfigurator/src/connection/su.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.connection.su)
(named-readtables:in-readtable :consfigurator)
(defmethod establish-connection ((type (eql :su)) remaining &key to)
(declare (ignore remaining))
;; We don't support using su with a password. Use :SUDO for that.
(assert-remote-euid-root)
(informat 1 "~&Switching to user ~A" to)
(make-instance 'su-connection :user to))
(defclass su-connection (shell-wrap-connection)
((user :initarg :user)))
;; Note that the -c here is an argument to the user's login shell, not the -c
;; argument to su(1) on, e.g., FreeBSD. So this should be fairly portable.
(defmethod connection-shell-wrap ((connection su-connection) cmd)
(format nil "su ~A -c ~A"
(sh-escape (slot-value connection 'user)) (sh-escape cmd)))
| 1,537 | Common Lisp | .lisp | 27 | 54.740741 | 77 | 0.741012 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 03fa1b5ef70b9d4ab52194210b7f41a150469a6dd27ca24c8e9c0ce7fcc9b9b7 | 3,943 | [
-1
] |
3,944 | fork.lisp | spwhitton_consfigurator/src/connection/fork.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.connection.fork)
(named-readtables:in-readtable :consfigurator)
(defclass fork-connection (local-connection) ())
(defgeneric post-fork (connection)
(:documentation
"Code to execute after forking/reinvoking but before calling CONTINUE-DEPLOY*.
Must not start up any threads."))
(defmethod continue-connection ((connection fork-connection) remaining)
(multiple-value-bind (out err exit)
(eval-in-grandchild `(post-fork ,connection)
`(continue-deploy* ,connection ',remaining))
(when-let ((lines (lines out)))
(inform t lines))
(exit-code-to-retval
exit
:on-failure (failed-change
"~&Fork connection child failed; stderr was ~%~%~A" err))))
;;;; Dumping and then immediately reinvoking Lisp
(defclass init-hooks-connection (fork-connection) ()
(:documentation "On SBCL, call POST-FORK using SB-EXT:*INIT-HOOKS*.
The primary purpose of this connection type is to obtain a truly
single-threaded context for the execution of POST-FORK."))
#+(and sbcl sb-thread)
(eval-when (:compile-toplevel :load-toplevel :execute)
;; UIOP:VERSION< cannot handle Debian-patched SBCL version numbers, so we
;; split it up ourselves.
(destructuring-bind (major minor patch . rest)
(mapcar (lambda (s) (parse-integer s :junk-allowed t))
(split-string (lisp-implementation-version) :separator '(#\.)))
(declare (ignore rest))
(unless (or (> major 2)
(and (= major 2)
(or (> minor 1) (and (= minor 1) (> patch 7)))))
(pushnew 'older-sbcl *features*))))
#+sbcl
(defmethod continue-connection ((connection init-hooks-connection) remaining)
(multiple-value-bind (out err exit)
(eval-in-reinvoked
`(push
(lambda ()
(handler-bind
((serious-condition
(lambda (c)
(trivial-backtrace:print-backtrace c :output *error-output*)
(uiop:quit 1))))
;; Handle the finaliser thread in older SBCL, before the change in
;; 2.1.8 to call *INIT-HOOKS* before starting system threads.
#+consfigurator.connection.fork::older-sbcl
(sb-int:with-system-mutex (sb-thread::*make-thread-lock*)
(sb-impl::finalizer-thread-stop))
(post-fork ,connection)
#+consfigurator.connection.fork::older-sbcl
(sb-impl::finalizer-thread-start)))
sb-ext:*init-hooks*)
`(continue-deploy* ,connection ',remaining))
(when-let ((lines (lines out)))
(inform t lines))
(exit-code-to-retval
exit
:on-failure (failed-change
"~&Reinvoked Lisp image failed; stderr was ~%~%~A" err))))
| 3,544 | Common Lisp | .lisp | 73 | 41.424658 | 81 | 0.664641 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | f77fbaaadd03c56b9c9fea3bb294f6fe1472e42a612bc7177837ade735ce89e9 | 3,944 | [
-1
] |
3,945 | shell-wrap.lisp | spwhitton_consfigurator/src/connection/shell-wrap.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.connection.shell-wrap)
(named-readtables:in-readtable :consfigurator)
(defclass shell-wrap-connection (posix-connection) ())
(defgeneric connection-shell-wrap (connection cmd))
(defmethod connection-run ((c shell-wrap-connection) cmd input)
(apply #'mrun :may-fail :input input
(ensure-cons (connection-shell-wrap c cmd))))
(defun %readfile (c path &optional delete)
(multiple-value-bind (out exit)
(let* ((path (sh-escape path))
(base #?"test -r ${path} && cat ${path}")
(cmd (if delete (strcat base #?" && rm ${path}") base)))
(connection-run c cmd nil))
(if (zerop exit)
out
(error "Could not read~:[~; and/or remove~] ~S" delete path))))
(defmethod connection-read-file ((c shell-wrap-connection) path)
(%readfile c path))
(defmethod connection-read-and-remove-file ((c shell-wrap-connection) path)
(%readfile c path t))
(defmethod connection-write-file ((conn shell-wrap-connection)
path
content
mode)
(let* ((mkstemp (mkstemp-cmd
(merge-pathnames "tmp.XXXXXX"
(pathname-directory-pathname path))))
(cmd (sh-script-to-single-line
(format nil "set -e
tmpf=$(~A)
trap \"rm -f '$tmpf'\" EXIT HUP KILL TERM INT
chmod ~O \"$tmpf\"
cat >\"$tmpf\"
mv \"$tmpf\" ~A" mkstemp mode (sh-escape path)))))
(multiple-value-bind (out exit) (connection-run conn cmd content)
(unless (zerop exit)
(error "Failed to write ~A: ~A" path out)))))
| 2,551 | Common Lisp | .lisp | 49 | 42.285714 | 78 | 0.614859 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 0d161a000be745a95ee8bc886dd1dc4d739990e0841ece6ae760dc23403da9ec | 3,945 | [
-1
] |
3,946 | chroot.lisp | spwhitton_consfigurator/src/connection/chroot.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.connection.chroot)
(named-readtables:in-readtable :consfigurator)
;; currently we only check whether we're root, but, for example, on Linux, we
;; might have a CAP_* which lets us chroot as non-root
(defun can-chroot ()
(zerop (nix:geteuid)))
(defmethod establish-connection ((type (eql :chroot)) remaining &key into)
(establish-connection (if (and (lisp-connection-p) (can-chroot))
:chroot.fork
:chroot.shell)
remaining
:into into))
;;;; Chroot connections superclass
(defclass chroot-connection ()
((into :type :string :initarg :into)
(chroot-mounts :type list :initform nil :accessor chroot-mounts)))
(defgeneric chroot-mount (connection &rest mount-args)
(:documentation
"Temporarily mount something into the chroot. The last element of MOUNT-ARGS
should be the mount point, without the chroot's root prefixed.")
(:method ((connection chroot-connection) &rest mount-args)
(let ((dest (chroot-pathname (lastcar mount-args)
(slot-value connection 'into))))
;; We only mount when the target is not already a mount point, so we
;; don't shadow anything that the user has already set up.
(unless (remote-mount-point-p dest)
(setq mount-args (copy-list mount-args))
(setf (lastcar mount-args) dest)
(apply #'mrun "mount" mount-args)
(push dest (chroot-mounts connection))))))
(defgeneric linux-chroot-mounts (connection)
(:method ((connection chroot-connection))
(with-slots (into) connection
;; Ensure the chroot itself is a mountpoint so that findmnt(8) works
;; correctly within the chroot.
(unless (remote-mount-point-p into)
(chroot-mount connection "--bind" into "/"))
;; Now set up the usual bind mounts. Help here from arch-chroot(8).
(mount:assert-devtmpfs-udev-/dev)
(dolist (mount mount:+linux-basic-vfs+)
(apply #'chroot-mount connection mount))
(chroot-mount connection "--bind" "/run" "/run")
(when (remote-exists-p "/sys/firmware/efi/efivars")
(apply #'chroot-mount connection mount:+linux-efivars-vfs+)))))
(defun copy-and-update-volumes (volumes connection)
(with-slots (into) connection
(loop for volume in volumes
when (and (subtypep (type-of volume) 'disk:filesystem)
(slot-boundp volume 'disk:mount-point)
(subpathp (disk:mount-point volume) into))
collect (aprog1 (disk:copy-volume-and-contents volume)
(setf (disk:mount-point it)
(in-chroot-pathname (disk:mount-point it) into)))
else collect volume)))
(defmethod propagate-connattr
((type (eql 'disk:opened-volumes)) connattr (connection chroot-connection))
(copy-and-update-volumes connattr connection))
(defmethod propagate-connattr
((type (eql 'disk:opened-volume-parents)) connattr (connection chroot-connection))
(copy-and-update-volumes connattr connection))
(defmethod propagate-connattr
((type (eql :remote-uid)) connattr (connection chroot-connection))
connattr)
(defmethod propagate-connattr
((type (eql :remote-gid)) connattr (connection chroot-connection))
connattr)
(defmethod propagate-connattr
((type (eql :no-services)) connattr (connection chroot-connection))
connattr)
;;;; :CHROOT.FORK
(defclass chroot.fork-connection
(rehome-connection chroot-connection fork-connection) ())
(defmethod establish-connection ((type (eql :chroot.fork)) remaining &key into)
(unless (and (lisp-connection-p) (zerop (nix:geteuid)))
(error "~&Forking into a chroot requires a Lisp image running as root"))
(informat 1 "~&Forking into chroot at ~A" into)
(let* ((into (ensure-pathname into
:defaults (uiop:getcwd)
:ensure-absolute t :ensure-directory t))
(connection (make-instance 'shell-chroot-connection :into into)))
;; Populate the CONSFIGURATOR::ID and :REMOTE-HOME connattrs correctly to
;; ensure they don't get bogus values when this connection object is used
;; in UPLOAD-ALL-PREREQUISITE-DATA.
(connection-connattr connection :remote-home)
;; Cache XDG_CACHE_HOME inside the chroot, and compute REHOME-DATADIR.
(let ((xdg-cache-home (connection-connattr connection :XDG_CACHE_HOME)))
(setf connection (change-class connection 'chroot.fork-connection)
(slot-value connection 'rehome-datadir)
(merge-pathnames
"consfigurator/data/" (chroot-pathname xdg-cache-home into))))
(continue-connection connection remaining)))
(defmethod post-fork ((connection chroot.fork-connection))
(with-slots (into) connection
#+linux
(progn (unshare CLONE_NEWNS)
(mrun "mount" "--make-rslave"
(stripln (run "findmnt" "-nro" "TARGET" "-T" into)))
(linux-chroot-mounts connection))
(chroot (unix-namestring into))
(let ((home (connection-connattr connection :remote-home)))
(setf (getenv "HOME") (unix-namestring home))
;; chdir, else our current working directory is a pointer to something
;; outside the chroot
(uiop:chdir home))))
;;;; :CHROOT.SHELL
(defmethod establish-connection ((type (eql :chroot.shell)) remaining &key into)
(declare (ignore remaining))
(informat 1 "~&Shelling into chroot at ~A" into)
(aprog1 (make-instance 'shell-chroot-connection :into into)
(when (string= "Linux" (stripln (run "uname")))
(linux-chroot-mounts it))))
(defclass shell-chroot-connection (chroot-connection shell-wrap-connection) ())
(defmethod connection-shell-wrap ((connection shell-chroot-connection) cmd)
(format nil "chroot ~A sh -c ~A"
(sh-escape (slot-value connection 'into)) (sh-escape cmd)))
(defmethod connection-tear-down :before ((connection shell-chroot-connection))
(dolist (mount (chroot-mounts connection))
;; There shouldn't be any processes left running in the chroot after we've
;; finished deploying it, but it's quite easy to end up with things like
;; gpg-agent holding on to /dev/null, for example, so for simplicity, do a
;; lazy unmount.
(mrun "umount" "-l" mount)))
| 7,047 | Common Lisp | .lisp | 134 | 46.30597 | 86 | 0.693359 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | d95784e95b085b10a17d85e7c2ca19eb54d8c2fd399e6113d18cbd103339bdee | 3,946 | [
-1
] |
3,947 | sbcl.lisp | spwhitton_consfigurator/src/connection/sbcl.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.connection.sbcl)
(named-readtables:in-readtable :consfigurator)
(defparameter *sbcl* '("sbcl" "--noinform" "--noprint"
"--disable-debugger" "--no-sysinit" "--no-userinit"))
(defmethod establish-connection
((type (eql :sbcl)) remaining
&key (package-manager nil package-manager-supplied-p))
"Start up a remote Lisp image using SBCL.
Specifying PACKAGE-MANAGER avoids the need to see what package managers are
available on PATH, which can provide a performance improvement."
(when (lisp-connection-p)
(warn
"Looks like you might be starting a fresh Lisp image directly from the root
Lisp. This can mean that prerequisite data gets extracted from encrypted
stores and stored unencrypted under ~~/.cache, and as such is not
recommended."))
;; Allow the user to request no attempt to install the dependencies at all,
;; perhaps because they know they're already manually installed.
(unless (and package-manager-supplied-p (not package-manager))
(handler-case (package:installed
package-manager '(:apt "sbcl" :pkgng "sbcl")
package:+consfigurator-system-dependencies+)
;; If we couldn't find any package manager on PATH, just proceed in the
;; hope that everything we need is already installed; we'll find out
;; whether it's actually a problem pretty quickly, when the remote SBCL
;; tries to compile and load the ASDF systems.
(package:package-manager-not-found (c)
(apply #'warn (simple-condition-format-control c)
(simple-condition-format-arguments c)))))
(let ((requirements (asdf-requirements-for-host-and-features
(safe-read-from-string
(run :input "(prin1 *features*)" *sbcl*)
:package :cl-user))))
;; Don't preserve the ASDF requirements :DATA hostattrs because they are
;; valid only for this hop, not necessarily beyond here. For example, if
;; we have a connection chain like (:ssh :sbcl (:lxc :name ...)) then we
;; don't want to upload all the ASDF systems into the container.
(with-preserve-hostattrs
(request-asdf-requirements requirements) (upload-all-prerequisite-data))
(inform t "Waiting for remote Lisp to exit, this may take some time ... ")
(force-output)
(multiple-value-bind (program forms)
(continue-deploy*-program remaining requirements)
(multiple-value-bind (out err exit) (run :may-fail :input program *sbcl*)
(inform t (if (member exit '(0 22 23)) "done." "failed.") :fresh-line nil)
(when-let ((lines (lines out)))
(inform t " Output was:" :fresh-line nil)
(with-indented-inform (inform t lines)))
(exit-code-to-retval
exit
;; print FORMS not PROGRAM because latter might contain sudo passwords
:on-failure
(failed-change
"~&Remote Lisp failed; stderr was:~%~%~A~&~%Program we sent:~%~%~S"
err forms))))))
| 3,797 | Common Lisp | .lisp | 67 | 50.119403 | 82 | 0.689683 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | de1cb9cb523f86f32cfdf6135d31fa3b0fc0d3ef7bc2ccefd332db26037978bb | 3,947 | [
-1
] |
3,948 | setuid.lisp | spwhitton_consfigurator/src/connection/setuid.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.connection.setuid)
(named-readtables:in-readtable :consfigurator)
(defclass setuid-connection (rehome-connection fork-connection) ())
(defmethod establish-connection ((type (eql :setuid)) remaining &key user)
(unless (and (lisp-connection-p) (zerop (nix:geteuid)))
(error "~&SETUIDing requires a Lisp image running as root"))
(informat 1 "~&SETUIDing to ~A" user)
(let* ((ent
(or (user:user-info user)
(failed-change "~&Could not look up user info for ~A." user)))
(xdg-cache-home
(ensure-directory-pathname
(stripln
;; su(1) is not POSIX but very likely to be present. Note that
;; the -c argument here is to the user's login shell, not the -c
;; argument to su(1) on, e.g., FreeBSD. So should be fairly
;; portable.
(mrun "su" (cdr (assoc :name ent))
"-c" "echo ${XDG_CACHE_HOME:-$HOME/.cache}"))))
(cache (merge-pathnames "consfigurator/" xdg-cache-home))
(datadir (merge-pathnames "data/" cache)))
(dolist (dir (list xdg-cache-home cache datadir))
(unless (directory-exists-p dir)
(nix:chown (ensure-directories-exist dir)
(cdr (assoc :user-id ent)) (cdr (assoc :group-id ent)))))
(continue-connection
(make-instance
'setuid-connection
:rehome-datadir datadir
:connattrs `(:remote-uid ,(cdr (assoc :user-id ent))
:remote-gid ,(cdr (assoc :group-id ent))
:remote-user ,(cdr (assoc :name ent))
:remote-home ,(ensure-directory-pathname
(cdr (assoc :home ent)))
:consfigurator-cache ,cache
:XDG_CACHE_HOME ,xdg-cache-home))
remaining)))
(defmethod post-fork ((connection setuid-connection))
(let ((uid (connection-connattr connection :remote-uid))
(gid (connection-connattr connection :remote-gid))
(user (connection-connattr connection :remote-user)))
(run-program
(list "chown" "-R"
(format nil "~A:~A" uid gid)
(unix-namestring (slot-value connection 'rehome-datadir))))
(posix-login-environment
uid user (connection-connattr connection :remote-home))
;; We are privileged, so this sets the real, effective and saved IDs.
(nix:setgid gid) (nix:initgroups user gid) (nix:setuid uid)))
(defmethod propagate-connattr
((type (eql :no-services)) connattr (connection setuid-connection))
connattr)
| 3,316 | Common Lisp | .lisp | 64 | 44.125 | 77 | 0.654332 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 852d59288e09008568ddb427b6434c7d3a62a2672ada8643e27fd1638426c5a6 | 3,948 | [
-1
] |
3,949 | package.lisp | spwhitton_consfigurator/src/property/package.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.package)
(named-readtables:in-readtable :consfigurator)
(define-constant +consfigurator-system-dependencies+
'(:apt ("build-essential" "libacl1-dev" "libcap-dev"))
:test #'equal)
(defgeneric %command (package-manager)
(:documentation
"Returns a command which, if found on PATH, indicates that the system package
manager identified by PACKAGE-MANAGER is available."))
(defmethod %command ((package-manager (eql :apt)))
"apt-get")
(defmethod %command ((package-manager (eql :pkgng)))
"pkg")
(defgeneric %installed (package-manager packages)
(:documentation
"Install each of PACKAGES using the system package manager identified by
PACKAGE-MANAGER.
Implementations should not fail just because we are not root, or otherwise
privileged, if the package is already installed."))
;; Call APPLY-PROPAPP directly because we want the :CHECK subroutine run, but
;; it doesn't make sense to run :HOSTATTRS because *HOST* doesn't necessarily
;; correspond to the host on which we're attempting to install packages.
(defmethod %installed ((package-manager (eql :apt)) packages)
(apply-propapp `(apt:installed ,@packages)))
(defmethod %installed ((package-manager (eql :pkgng)) packages)
(apply-propapp `(pkgng:installed ,@packages)))
(define-simple-error package-manager-not-found (aborted-change))
(defprop installed :posix
(package-manager &rest package-lists &aux package-list)
"Attempt to use a system package manager to install system packages as
specified by PACKAGE-LISTS. If PACKAGE-MANAGER, a keyword, use that
particular package manager; otherwise, see what we can find on PATH.
Each of PACKAGE-LISTS is a plist where the keys identify package managers, and
where the values are lists of package names to install using that package
manager. See PACKAGE:+CONSFIGURATOR-SYSTEM-DEPENDENCIES+ for an example.
This property should not typically be applied to hosts. It is preferable to
use an operating system-specific property, such as APT:INSTALLED. This
property exists because in a few cases it is necessary to install packages
where there is no known-valid HOST value for the machine upon which we need to
install packages, and thus we cannot infer what package manager to use from
the host's OS, and must fall back to seeing what's on PATH.
In particular, when starting up a remote Lisp image when the REMAINING
argument to ESTABLISH-CONNECTION is non-nil, we might be starting up Lisp on a
machine other than the one to be deployed and we do not have HOST values for
intermediate hops. Another case is INSTALLED:CLEANLY-INSTALLED-ONCE;
regardless of REMAINING, the initial OS might be the one we will replace, not
the declared OS for the host."
(:apply
(dolist (list package-lists)
(doplist (k v list)
(dolist (p (ensure-cons v))
(push p (getf package-list k)))))
(loop with reversed
for (k v) on package-list by #'cddr
do (push v reversed) (push k reversed)
finally (setq package-list reversed))
(if package-manager
(return-from installed
(%installed package-manager (getf package-list package-manager)))
(doplist (package-manager packages package-list)
(when (remote-executable-find (%command package-manager))
(return-from installed (%installed package-manager packages)))))
(package-manager-not-found
"Could not find any package manager on PATH with which to install ~S."
package-list)))
| 4,256 | Common Lisp | .lisp | 77 | 52.168831 | 80 | 0.76226 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | a6b41a191e65f64dcc37efd11f248fa8d245f925430b582c01cf30d6175b7846 | 3,949 | [
-1
] |
3,950 | hostname.lisp | spwhitton_consfigurator/src/property/hostname.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.hostname)
(named-readtables:in-readtable :consfigurator)
(defun domain (hostname)
(if-let ((pos (position #\. hostname)))
(subseq hostname (min (length hostname) (1+ pos)))
""))
(defprop is :posix (hostname)
"Specify that the hostname of this host is HOSTNAME.
Useful for hosts implicitly defined inline using dotted propapp notation.
Unlikely to be useful for hosts defined using DEFHOST."
(:desc #?"Hostname is ${hostname}")
(:hostattrs (push-hostattr :hostname hostname)))
(defpropspec configured :posix
(&optional (hostname (get-hostname) hostname-supplied-p)
&aux (short (car (split-string hostname :separator "."))))
"Set the hostname in the standard Debian way."
(:desc "Hostname configured")
`(seqprops
,@(and hostname-supplied-p `((is ,hostname)))
(on-change (file:has-content "/etc/hostname" ,short)
(container:when-contained (:hostname)
(cmd:single ,(strcat "hostname " short))))
(file:contains-conf-tab
"/etc/hosts"
,@(and (position #\. hostname)
`("127.0.1.1" ,(strcat hostname " " short)))
"127.0.0.1" "localhost")))
(defproplist mailname-configured :posix (&optional (mailname (get-hostname)))
"Sets the mailname to MAILNAME.
The FQDN is a good choice for unclustered machines which do not have
publically advertised MX records; in other cases it will often be better to
use only the domain name portion of the hostname."
(:desc "/etc/mailname configured")
(file:has-content "/etc/mailname" mailname))
(defproplist search-configured :posix (&optional (domain (domain (get-hostname))))
"Set the default DOMAIN for hostname lookup in /etc/resolv.conf.
DOMAIN defaults to everything after the first dot of the machine's hostname,
which is assumed to be an FQDN."
(:desc "Search domain in /etc/resolv.conf configured")
(file:contains-conf-space "/etc/resolv.conf" "search" domain))
| 2,709 | Common Lisp | .lisp | 52 | 48.865385 | 82 | 0.731394 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 9fb41c83a096dd24b6b7e60d114293f73d3a2eea8bd1ae10ad8d7e3875add97e | 3,950 | [
-1
] |
3,951 | disk.lisp | spwhitton_consfigurator/src/property/disk.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021-2024 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.disk)
(named-readtables:in-readtable :consfigurator)
;;; All Linux-specific for now, so properties using these data types and
;;; functions should declare a hostattrs requirement (os:required 'os:linux).
;;;; Volumes
(defclass volume ()
((volume-label
:type string :initarg :volume-label :accessor volume-label
:documentation "The name or label of the volume.
Can only be recorded in or on the volume itself for certain subclasses. For
example, mostly meaningless for a Linux swap partition.")
(volume-contents
:type volume :initarg :volume-contents :accessor volume-contents)
;; (volume-depth
;; :initarg :volume-depth
;; :accessor volume-depth
;; :type integer
;; :documentation
;; "Number representing the degree to which this volume is nested within other
;; volumes. All volumes with a lower value for VOLUME-DEPTH should be opened
;; before any attempt to open this volume is made.
;; For example, an LVM volume group needs a VOLUME-DEPTH strictly greater than
;; the VOLUME-DEPTH of all its physical volumes.")
(volume-size
:initarg :volume-size :accessor volume-size
:documentation "The size of the volume, in whole mebibytes (MiB).
The special value :REMAINING means all remaining free space in the volume
containing this one.
If a larger size is required to accommodate the VOLUME-CONTENTS of the volume
plus any metadata (e.g. partition tables), this value will be ignored.")
(volume-bootloaders
:type list :initarg :boots-with :accessor volume-bootloaders
:documentation
"List or list of lists specifying bootloaders to be installed to this volume.
The first element of each list is a symbol identifying the type of bootloader,
and the remaining elements are a plist of keyword arguments to be passed to
the implementation of INSTALLER:INSTALL-BOOTLOADER for that bootloader type.
Typically only the top level PHYSICAL-DISK of a host's volumes will have this
slot bound."))
(:documentation
"Something which contains filesystems and/or other volumes."))
(define-simple-print-object volume)
(defgeneric copy-volume-and-contents
(volume &rest initialisations &key &allow-other-keys)
(:documentation
"Make a fresh copy of VOLUME, shallowly, except for the VOLUME-CONTENTS of
volume, which is recursively copied. Keyword arguments may be used to
subsequently replace the copied values of some slots.")
(:method ((volume volume) &rest initialisations &key &allow-other-keys)
(let* ((class (class-of volume))
(copy (allocate-instance class))
(contents-bound-p (slot-boundp volume 'volume-contents))
(contents (and contents-bound-p (volume-contents volume))))
(dolist (slot-name (delete 'volume-contents
(mapcar #'closer-mop:slot-definition-name
(closer-mop:class-slots class))))
(when (slot-boundp volume slot-name)
(setf (slot-value copy slot-name) (slot-value volume slot-name))))
(when contents-bound-p
(setf (volume-contents copy)
(if (listp contents)
(mapcar #'copy-volume-and-contents contents)
(copy-volume-and-contents contents))))
(apply #'reinitialize-instance copy initialisations))))
(defgeneric subvolumes-of-type (type volume)
(:documentation
"Recursively examine VOLUME and its VOLUME-CONTENTS and return a list of all
volumes encountered whose type is a subtype of TYPE.
Returns as a second value a corresponding list of the immediate parents of
each returned volume.")
(:method ((type symbol) (volume volume))
(labels ((walk (volume parent &aux (second-arg (list volume)))
(multiple-value-bind (contents contents-parents)
(and (slot-boundp volume 'volume-contents)
(multiple-value-mapcan
#'walk (ensure-cons (volume-contents volume))
(rplacd second-arg second-arg)))
(if (subtypep (type-of volume) type)
(values (cons volume contents)
(cons parent contents-parents))
(values contents contents-parents)))))
(walk volume nil))))
(defgeneric all-subvolumes (volume)
(:documentation
"Recursively examine VOLUME and its VOLUME-CONTENTS and return a list of all
volumes encountered.")
(:method ((volume volume))
(subvolumes-of-type 'volume volume)))
(defgeneric volume-contents-minimum-size (volume)
(:documentation
"Return the minimum size required to accommodate the VOLUME-CONTENTS of VOLUME.")
(:method ((volume volume))
(if (slot-boundp volume 'volume-contents)
(reduce #'+ (mapcar #'volume-minimum-size
(ensure-cons (volume-contents volume))))
0)))
(defgeneric volume-minimum-size (volume)
(:documentation
"Return the VOLUME-SIZE of the volume or the minimum size required to
accommodate its contents, whichever is larger.")
(:method ((volume volume))
(let ((volume-minimum-size
(cond ((not (slot-boundp volume 'volume-size))
0)
((eql (volume-size volume) :remaining)
1)
((numberp (volume-size volume))
(volume-size volume))
(t
(simple-program-error "Invalid volume size ~A"
(volume-size volume))))))
(max volume-minimum-size
(volume-contents-minimum-size volume)))))
(defclass top-level-volume (volume) ()
(:documentation
"A volume which never appears as the VOLUME-CONTENTS of another volume."))
(defgeneric create-volume (volume file)
(:documentation
"Create VOLUME. FILE is a pathname at or on which to create VOLUME, for types
of VOLUME where that makes sense, and explicitly nil otherwise.
Return values, if any, should be ignored."))
(defgeneric volume-required-data (volume)
(:documentation
"Return (IDEN1 . IDEN2) pairs for each item of prerequisite data opening
and/or creating the volume requires.")
(:method ((volume volume))
"Default implementation: nothing required."
nil))
(defun require-volumes-data (volumes)
"Call REQUIRE-DATA on each item of prerequisite data requires for opening
and/or creating each of VOLUMES.
Called by property :HOSTATTRS subroutines."
(dolist (pair (mapcan #'volume-required-data
(mapcan #'all-subvolumes volumes)))
(require-data (car pair) (cdr pair))))
;;;; Opened volumes
(defgeneric open-volume (volume file)
(:documentation "Renders contents of VOLUME directly accessible.
FILE is something in the filesystem which serves as a means of accessing
VOLUME, for types of VOLUME where that makes sense, and explicitly nil
otherwise.
Returns as a first value a fresh instance of OPENED-VOLUME corresponding to
VOLUME. In this case, it is legitimate to subsequently call OPEN-VOLUME on
the VOLUME-CONTENTS of VOLUME.
If opening this kind of volume results in opening its VOLUME-CONTENTS too,
also return as a second value a list of fresh OPENED-VOLUME values
corresponding to the VOLUME-CONTENTS of VOLUME. In this case, the caller
should not attempt to call OPEN-VOLUME on the VOLUME-CONTENTS of VOLUME."))
(defgeneric close-volume (volume)
(:documentation
"Inverse of OPEN-VOLUME: `kpartx -d`, `cryptsetup luksClose`, etc.
Return values, if any, should be ignored.")
(:method ((volume volume))
"Default implementation: assume there is nothing to close."
(values)))
(defclass opened-volume (volume)
((device-file
:type pathname
:initarg :device-file
:accessor device-file
:documentation "File under /dev giving access to the opened volume."))
(:documentation
"A VOLUME object which has been made directly accessible as a block device."))
(defmethod open-volume ((volume opened-volume) file)
(copy-volume-and-contents volume))
(defgeneric make-opened-volume (volume device-file)
(:documentation
"Where there is a class which is a subclass of both the class of VOLUME and
OPENED-VOLUME, make a fresh instance of that class copying all slots from
VOLUME, and setting the DEVICE-FILE slot to DEVICE-FILE."))
(defmacro defclass-opened-volume
(name (subclass-of-volume &rest other-superclasses)
&key (device-file-type 'pathname))
"Define a subclass of SUBCLASS-OF-VOLUME and OPENED-VOLUME called NAME, and an
appropriate implementation of MAKE-OPENED-VOLUME for NAME.
SUBCLASS-OF-VOLUME should be a symbol naming a subclass of VOLUME."
`(progn
(defclass ,name (,subclass-of-volume ,@other-superclasses opened-volume) ()
(:documentation
,(format
nil
"Instance of ~A which has been made directly accessible as a block device."
name)))
(defmethod make-opened-volume
((volume ,subclass-of-volume) (device-file ,device-file-type))
,(format nil "Make instance of ~A from instance of ~A."
name subclass-of-volume)
(let ((old-class (find-class ',subclass-of-volume)))
(closer-mop:ensure-finalized old-class)
(let ((new (allocate-instance (find-class ',name))))
(dolist (slot-name (mapcar #'closer-mop:slot-definition-name
(closer-mop:class-slots old-class)))
(when (slot-boundp volume slot-name)
(setf (slot-value new slot-name)
(slot-value volume slot-name))))
(setf (slot-value new 'device-file) device-file)
(reinitialize-instance new))))))
(defclass physical-disk (top-level-volume opened-volume) ()
(:documentation
"A physical disk drive attached to the machine, which always has a
corresponding block device in /dev available to access it. Should be used for
whole disks, not partitions (e.g. /dev/sda, not /dev/sda1)."))
;;;; Disk images
(defclass disk-image (volume)
((image-file :initarg :image-file :accessor image-file)))
;;;; Raw disk images
(defclass raw-disk-image (disk-image) ()
(:documentation
"A raw disk image, customarily given an extension of .img, suitable for
directly writing out with dd(1)."))
(defclass-opened-volume opened-raw-disk-image (raw-disk-image))
;; kpartx(1) can operate directly upon raw disk images, and will also make the
;; whole disk image accessible as a loop device whose name we can infer from
;; the kpartx(1) output (from partitions at /dev/mapper/loopNpM we can infer
;; that /dev/loopN is the whole disk). So we could examine the type of
;; (volume-contents volume), and if we find it's PARTITIONED-VOLUME, we could
;; skip executing losetup(1), and just call (open-volume (volume-contents
;; volume) file) and convert the return values into something appropriate for
;; us to return. But for simplicity and composability, just make the whole
;; disk image accessible at this step of the recursion.
(defmethod open-volume ((volume raw-disk-image) (file null))
(make-opened-volume
volume
(ensure-pathname
(stripln (run "losetup" "--show" "-f" (image-file volume))))))
(defmethod close-volume ((volume opened-raw-disk-image))
(mrun "losetup" "-d" (device-file volume)))
(defmethod create-volume ((volume raw-disk-image) (file null))
"Ensure that a raw disk image exists. Will overwrite only regular files."
(let ((f (image-file volume)))
(when (zerop
(mrun :for-exit
;; && and || have equal precedence in shell.
#?'[ -L "${f}" ] || { [ -e "${f}" ] && [ ! -f "${f}" ]; }'))
(failed-change "~A already exists and is not a regular file." f))
;; Here, following Propellor, we want to ensure that the disk image size
;; is a multiple of 4096 bytes, so that the size is aligned to the common
;; sector sizes of both 512 and 4096. But since we currently only support
;; volume sizes in whole mebibytes, we know it's already aligned.
(file:does-not-exist f)
(mrun "fallocate" "-l" (format nil "~DM" (volume-minimum-size volume))
f)))
;;;; Partitioned block devices and their partitions
;;; No support for MSDOS partition tables.
(defclass partitioned-volume (volume)
((volume-contents
:type list
:documentation "A list of partitions."))
(:documentation "A device with a GPT partition table and partitions."))
(defclass-opened-volume opened-partitioned-volume (partitioned-volume))
(defclass partition (volume)
((partition-typecode
:initform #x8300 :initarg :partition-typecode :accessor partition-typecode
:documentation
"The type code for the partition; see the --typecode option to sgdisk(1).
Either a two-byte hexadecimal number, or a string specifying the GUID.
On GNU/Linux systems, you typically only need to set this to a non-default
value in the case of EFI system partitions, for which case use #xEF00.")
(partition-bootable
:initform nil :initarg :partition-bootable :accessor partition-bootable
:documentation "Whether the legacy BIOS bootable attribute is set.")
(partition-start-sector
:type integer
:initform 0
:initarg :partition-start-sector
:accessor partition-start-sector
:documentation "The sector at which the partition should start.
The default value of 0 means the next free sector.")
(partition-sectors
:type integer
:initarg :partition-sectors
:accessor partition-sectors
:documentation "The size of the partition in sectors."))
(:documentation "A GPT partition."))
(defclass-opened-volume opened-partition (partition))
(defmethod volume-contents-minimum-size ((volume partitioned-volume))
"Add two mebibytes for the GPT metadata."
(+ 2 (call-next-method)))
(defmethod open-volume ((volume partitioned-volume) (file pathname))
(let ((loopdevs (mapcar
(lambda (line)
(destructuring-bind (add map loopdev &rest ignore)
(split-string line)
(declare (ignore ignore))
(unless (and (string= add "add") (string= map "map"))
(failed-change
"Unexpected kpartx output ~A" line))
(ensure-pathname (strcat "/dev/mapper/" loopdev))))
(runlines "kpartx" "-avs" file))))
(unless (= (length loopdevs) (length (volume-contents volume)))
(mrun "kpartx" "-d" file)
(failed-change
"kpartx(1) returned ~A loop devices, but volume has ~A partitions."
(length loopdevs) (length (volume-contents volume))))
(values
(make-opened-volume volume file)
(loop for partition in (volume-contents volume) and loopdev in loopdevs
collect (make-opened-volume partition loopdev)))))
(defmethod close-volume ((volume opened-partitioned-volume))
(mrun "kpartx" "-dv" (device-file volume)))
(defmethod create-volume ((volume partitioned-volume) (file pathname))
(with-slots (volume-contents) volume
;; See <https://bugs.launchpad.net/ironic-python-agent/+bug/1737556>.
;; We don't take sgdisk upstream's suggestion there to ignore the exit
;; code of --zap-all because we do want to assert somehow that a
;; successful zeroing-out of any old partition tables has occurred.
(mrun :may-fail "sgdisk" "--clear" file)
(mrun :inform "sgdisk" "--zap-all" file)
(mrun :inform "sgdisk"
;; Turn off partition alignment when specific start sectors have
;; been specified, so that we can be sure they will be respected.
;;
;; Given this approach, if specify start sector for one partition,
;; probably want to specify for all partitions to ensure alignment.
(and (loop for partition in volume-contents
thereis (plusp (partition-start-sector partition)))
"--set-alignment=1")
(loop for partition in volume-contents
for code = (partition-typecode partition)
when (and (slot-boundp partition 'volume-size)
(slot-boundp partition 'partition-sectors))
do (failed-change
"~A has both VOLUME-SIZE and PARTITION-SECTORS bound."
partition)
collect (strcat
"--new=0:"
(format nil "~D" (partition-start-sector partition))
":"
(cond
((slot-boundp partition 'partition-sectors)
(format nil "~D"
(+ (partition-start-sector partition)
(1- (partition-sectors partition)))))
((and (slot-boundp partition 'volume-size)
(eql (volume-size partition) :remaining))
"0")
(t
(format nil "+~DM"
(volume-minimum-size partition)))))
collect (strcat "--typecode=0:"
(etypecase code
(string code)
(integer (format nil "~X" code))))
when (partition-bootable partition)
collect "--attributes=0:set:2")
file)))
;;;; LVM
(defclass lvm-physical-volume (volume)
((lvm-volume-group
:type string
:initarg :volume-group
:initform
(simple-program-error "LVM physical volume must have volume group.")
:accessor lvm-volume-group
:documentation
"The name of the LVM volume group to which this volume belongs.")
;; pvcreate(8) options
(data-alignment
:type string
:initarg :data-alignment
:accessor data-alignment
:documentation "Value for the --dataalignment argument to pvcreate(8).")
;; vgcreate(8) options
(physical-extent-size
:type string
:initarg :physical-extent-size
:accessor physical-extent-size
:documentation "Value for the --dataalignment argument to vgcreate(8).
Should be the same for all PVs in this VG.")
(alloc
:type string
:initarg :alloc
:accessor alloc
:documentation "Value for the --alloc argument to vgcreate(8).
Should be the same for all PVs in this VG."))
(:documentation "An LVM physical volume.
We do not specify what logical volumes it contains."))
(defclass-opened-volume opened-lvm-physical-volume (lvm-physical-volume))
(defmethod open-volume ((volume lvm-physical-volume) (file pathname))
(make-opened-volume volume file))
(defmethod create-volume ((volume lvm-physical-volume) (file pathname))
(mrun :inform "pvcreate"
(and (slot-boundp volume 'data-alignment)
`("--dataalignment" ,(data-alignment volume)))
file)
(if (memstr= (lvm-volume-group volume) (all-lvm-volume-groups))
(mrun :inform "vgextend" (lvm-volume-group volume) file)
(mrun :inform "vgcreate" "--systemid" ""
(and (slot-boundp volume 'physical-extent-size)
`("--physicalextentsize" ,(physical-extent-size volume)))
(and (slot-boundp volume 'alloc)
`("--alloc" ,(alloc volume)))
(lvm-volume-group volume) file)))
(defun all-lvm-volume-groups ()
(mapcar (curry #'string-trim " ")
(runlines "vgs" "--no-headings" "-ovg_name")))
(defclass lvm-logical-volume (top-level-volume)
((volume-label
:initform (simple-program-error "LVs must have names.")
:documentation "The name of the LV, often starting with \"lv_\".")
(lvm-volume-group
:type string
:initarg :volume-group
:initform
(simple-program-error "LVM logical volumes must have a volume group.")
:accessor lvm-volume-group
:documentation
"The name of the LVM volume group to which this volume belongs.")))
(defclass-opened-volume activated-lvm-logical-volume (lvm-logical-volume))
(defmethod volume-contents-minimum-size ((volume lvm-logical-volume))
"LVs cannot be of zero size."
(max 1 (call-next-method)))
(defmethod open-volume ((volume lvm-logical-volume) (file null))
(with-slots (volume-label lvm-volume-group) volume
(mrun "lvchange" "-ay" (strcat lvm-volume-group "/" volume-label))
;; lvm(8) says not to use the /dev/mapper names, but rather /dev/vg/lv
(make-opened-volume
volume (merge-pathnames volume-label
(ensure-directory-pathname
(merge-pathnames lvm-volume-group #P"/dev/"))))))
(defmethod close-volume ((volume activated-lvm-logical-volume))
(mrun "lvchange" "-an"
(strcat (lvm-volume-group volume) "/" (volume-label volume))))
(defmethod create-volume ((volume lvm-logical-volume) (file null))
(with-slots (volume-label lvm-volume-group) volume
;; Check that the VG exists.
(unless (memstr= lvm-volume-group (all-lvm-volume-groups))
(failed-change "Looks like no PVs for VG ~A?" lvm-volume-group))
;; Create the LV.
(mrun :inform "lvcreate" "-Wn"
(if (and (slot-boundp volume 'volume-size)
(eql (volume-size volume) :remaining))
'("-l" "100%FREE")
`("-L" ,(format nil "~DM" (volume-minimum-size volume))))
lvm-volume-group "-n" volume-label)))
(defprop host-lvm-logical-volumes-exist :lisp ()
(:desc "Host LVM logical volumes all exist")
(:hostattrs (os:required 'os:linux))
(:apply
(assert-remote-euid-root)
(let* ((existing-lvs
(loop for (lv vg) in (mapcar #'words (cdr (runlines "lvs")))
collect (cons lv vg)))
(to-create
;; LVs are TOP-LEVEL-VOLUMEs.
(loop for volume in (get-hostattrs :volumes)
when (subtypep (class-of volume) 'lvm-logical-volume)
unless (member (cons (volume-label volume)
(lvm-volume-group volume))
existing-lvs :test #'equal)
collect volume))
(to-mount
(loop for volume in to-create
nconc (loop for volume
in (subvolumes-of-type 'filesystem volume)
when (slot-boundp volume 'mount-point)
collect volume))))
(if to-create
(prog2
(ignoring-hostattrs
(consfigurator.property.fstab:has-entries-for-volumes to-mount))
(create-volumes-and-contents to-create)
(dolist (volume to-create)
(open-volume volume nil))
(dolist (volume to-mount)
(consfigurator.property.mount:mounted
:target (mount-point volume))))
:no-change))))
;;;; Filesystems
(defparameter *mount-below* #P"/"
"Prefix for all filesystem mount points. Bound by functions to request that
filesystems be mounted relative to a different filesystem root, e.g. under a
chroot.")
(defclass filesystem (volume)
((mount-point :type pathname :initarg :mount-point :accessor mount-point)
(mount-options
:type list :initform nil :initarg :mount-options :accessor mount-options)
(extra-space
:type integer :initform 0 :initarg :extra-space :accessor extra-space
:documentation
"When creating the filesystem to accommodate a directory tree whose size is
already known, add this many whole mebibytes of extra free space where
possible. Ignored if VOLUME-SIZE is also bound."))
(:documentation
"A block device containing a filesystem, which can be mounted."))
(defclass-opened-volume mounted-filesystem (filesystem))
(defmethod open-volume ((volume filesystem) (file pathname))
(let* ((mount-point (chroot-pathname (mount-point volume) *mount-below*))
(opened-volume (make-opened-volume volume file)))
(setf (mount-point opened-volume) mount-point)
(file:directory-exists mount-point)
(mrun "mount" file mount-point)
opened-volume))
(defmethod close-volume ((volume mounted-filesystem))
(mrun "umount" (device-file volume)))
(defclass ext4-filesystem (filesystem)
((mount-options :initform '("relatime"))))
(defclass-opened-volume
mounted-ext4-filesystem (ext4-filesystem mounted-filesystem))
(defmethod create-volume ((volume ext4-filesystem) (file pathname))
(mrun :inform
"mkfs.ext4" file (and (slot-boundp volume 'volume-label)
`("-L" ,(volume-label volume)))))
(defclass fat32-filesystem (filesystem) ())
(defclass-opened-volume
mounted-fat32-filesystem (fat32-filesystem mounted-filesystem))
(defmethod create-volume ((volume fat32-filesystem) (file pathname))
(mrun :inform
"mkdosfs" "-F" "32" (and (slot-boundp volume 'volume-label)
`("-n" ,(volume-label volume)))
file))
;;;; Other volumes which can be made accessible as block devices
(defclass luks-container (volume)
((luks-passphrase-iden1
:type string :initform "--luks-passphrase" :initarg :luks-passphrase-iden1)
(luks-type
:type string :initform "luks" :initarg :luks-type :accessor luks-type
:documentation
"The value of the --type parameter to cryptsetup luksFormat.
Note that GRUB2 older than 2.06 cannot open the default LUKS2 format, so
specify \"luks1\" if this is needed.")
(cryptsetup-options
:type list :initform nil :initarg :cryptsetup-options
:documentation
"Extra arguments to pass to cryptsetup(8) when creating the volume, such as
'--cipher'. Use the LUKS-TYPE slot for '--type'.")
(crypttab-options
:type list :initform '("luks" "discard" "initramfs")
:initarg :crypttab-options :accessor crypttab-options)
(crypttab-keyfile :initarg :crypttab-keyfile :accessor crypttab-keyfile)))
(defclass-opened-volume opened-luks-container (luks-container))
(defmethod volume-required-data ((volume luks-container))
(with-slots (luks-passphrase-iden1 volume-label) volume
(list (cons luks-passphrase-iden1 volume-label))))
(defmethod open-volume ((volume luks-container) (file pathname))
(with-slots (luks-passphrase-iden1 volume-label) volume
(unless (and (stringp volume-label) (plusp (length volume-label)))
(failed-change "LUKS volume has invalid VOLUME-LABEL."))
(mrun "cryptsetup" "-d" "-" "luksOpen" file volume-label
:input (get-data-string luks-passphrase-iden1 volume-label))
(make-opened-volume volume
(merge-pathnames volume-label #P"/dev/mapper/"))))
(defmethod create-volume ((volume luks-container) (file pathname))
(with-slots
(luks-passphrase-iden1 volume-label luks-type cryptsetup-options)
volume
(mrun :inform
:input (get-data-string luks-passphrase-iden1 (volume-label volume))
"cryptsetup" "--type" luks-type
(and (member luks-type '("luks" "luks2") :test #'string=)
`("--label" ,volume-label))
cryptsetup-options
"luksFormat" file "-")))
(defmethod close-volume ((volume opened-luks-container))
(mrun "cryptsetup" "luksClose" (device-file volume)))
(defclass linux-swap (volume) ())
(defmethod create-volume ((volume linux-swap) (file pathname))
(mrun "mkswap" file))
;;;; Recursive operations
(defmacro with-mount-below (form)
"Avoid establishing any binding for *MOUNT-BELOW* when the caller did not
explicitly request one."
`(if mount-below-supplied-p
(let ((*mount-below* mount-below)) ,form)
,form))
(defun open-volumes-and-contents
(volumes &key (mount-below nil mount-below-supplied-p))
"Where each of VOLUMES is a VOLUME which may be opened by calling OPEN-VOLUME
with NIL as the second argument, recursively open each of VOLUMES and any
contents thereof, and return a list of the volumes that were opened, in the
order in which they should be closed, and as a second value, a corresponding
list of the immediate parents of each opened volume. MOUNT-BELOW specifies a
pathname to prefix to mount points when opening FILESYSTEM volumes.
Also return as third and fourth values a list of volumes encountered that were
already open and a corresponding list of their immediate parents.
Calling this function can be useful for testing at the REPL, but code should
normally use WITH-OPEN-VOLUMES or WITH-OPENED-VOLUMES.
If an error is signalled while the attempt to open volumes is in progress, a
single attempt will be made to close all volumes opened up to that point."
(let
(opened-volumes opened-parents already-open already-parents filesystems)
(handler-case
(labels
((open-volume-and-contents (volume file parent)
;; Postpone filesystems until the end so that we can sort
;; them before mounting, to avoid unintended shadowing.
(if (subtypep (type-of volume) 'filesystem)
(push (list parent volume file) filesystems)
(multiple-value-bind (opened opened-contents)
(open-volume volume file)
(let ((opened-contents-parents
(make-list (length opened-contents)
:initial-element volume)))
;; Don't queue for closure volumes which were already
;; open before we began.
(if (subtypep (class-of volume) 'opened-volume)
(setq opened-volumes
(append opened-contents opened-volumes)
opened-parents
(nconc opened-contents-parents
opened-parents)
already-open
(cons volume already-open)
already-parents
(cons parent already-parents))
(setq opened-volumes
(append opened-contents
(cons opened opened-volumes))
opened-parents
(nconc opened-contents-parents
(cons parent opened-parents)))))
(dolist (opened-volume (or opened-contents `(,opened)))
(when (slot-boundp opened-volume 'volume-contents)
(open-volume-and-contents
(volume-contents opened-volume)
(device-file opened-volume)
opened-volume)))))))
(mapc (rcurry #'open-volume-and-contents nil nil) volumes)
;; Note that filesystems never have any VOLUME-CONTENTS to open.
(with-mount-below
(dolist (filesystem
(nreverse
(sort filesystems #'subpathp
:key (compose #'ensure-directory-pathname
#'mount-point
#'cadr))))
(push (pop filesystem) opened-parents)
(push (apply #'open-volume filesystem) opened-volumes)))
(values opened-volumes opened-parents already-open already-parents))
(serious-condition (condition)
(unwind-protect (mapc #'close-volume opened-volumes)
(error condition))))))
(defmacro with-open-volumes ((volumes
&key
(mount-below nil mount-below-supplied-p)
opened-volumes)
&body forms)
"Where each of VOLUMES is a VOLUME which may be opened by calling OPEN-VOLUME
with NIL as the second argument, recursively open each of VOLUMES and any
contents thereof, execute forms, and close all volumes that were opened.
MOUNT-BELOW specifies a pathname to prefix to mount points when opening
FILESYSTEM volumes. OPENED-VOLUMES specifies a symbol to which a list of all
volumes that were opened will be bound, which can be used to do things like
populate /etc/fstab and /etc/crypttab. Do not modify this list."
(let ((opened-volumes (or opened-volumes (gensym))))
`(let ((,opened-volumes (open-volumes-and-contents
,volumes
,@(and mount-below-supplied-p
`(:mount-below ,mount-below)))))
(unwind-protect (progn ,@forms)
(mrun "sync")
(mapc #'close-volume ,opened-volumes)))))
(defmacro with-opened-volumes
((volumes &key (mount-below nil mount-below-supplied-p) leave-open)
&body propapps)
"Macro property combinator. Where each of VOLUMES is a VOLUME which may be
opened by calling OPEN-VOLUME with NIL as the second argument, recursively
open each of VOLUMES and any contents thereof, apply PROPAPPS, and, unless
LEAVE-OPEN, close all volumes that were opened.
MOUNT-BELOW specifies a pathname to prefix to mount points when opening
FILESYSTEM volumes. During the application of PROPAPPS, all
'DISK:OPENED-VOLUMES and 'DISK:OPENED-VOLUME-PARENTS connattrs are replaced
with lists of the volumes that were opened/already open and corresponding
immediate parent volumes."
`(with-opened-volumes*
',volumes
,(if (cdr propapps) `(eseqprops ,@propapps) (car propapps))
,@(and mount-below-supplied-p `(:mount-below ,mount-below))
:leave-open ,leave-open))
(define-function-property-combinator with-opened-volumes*
(volumes propapp &key (mount-below nil mount-below-supplied-p) leave-open)
(:retprop
:type (propapp-type propapp)
:hostattrs (lambda-ignoring-args
(require-volumes-data volumes)
(propapp-attrs propapp))
:apply
(lambda-ignoring-args
(multiple-value-bind
(opened-volumes opened-parents already-open already-parents)
(apply #'open-volumes-and-contents
`(,volumes ,@(and mount-below-supplied-p
`(:mount-below ,mount-below))))
(with-connattrs
('opened-volumes (append opened-volumes already-open)
'opened-volume-parents (append opened-parents already-parents))
(unwind-protect (apply-propapp propapp)
(mrun "sync")
(unless leave-open (mapc #'close-volume opened-volumes))))))
:args (cdr propapp)))
(defun create-volumes-and-contents (volumes &optional files)
"Where each of VOLUMES is a VOLUME which may be created by calling
CREATE-VOLUME with the corresponding entry of FILES, or NIL, as a second
argument, recursively create each of VOLUMES and any contents thereof.
**THIS FUNCTION UNCONDITIONALLY FORMATS DISKS, POTENTIALLY DESTROYING DATA.**"
(let (opened-volumes)
(labels
((create-volume-and-contents
(volume file
&aux
(already-opened (subtypep (class-of volume) 'opened-volume)))
(unless already-opened
(create-volume volume file))
(when (slot-boundp volume 'volume-contents)
(multiple-value-bind (opened opened-contents)
(open-volume volume file)
(setq opened-volumes
(append opened-contents
;; Don't queue for closure volumes which were
;; already open before we began.
(if already-opened
opened-volumes
(cons opened opened-volumes))))
(if opened-contents
(dolist (opened-volume opened-contents)
(when (slot-boundp opened-volume 'volume-contents)
(create-volume-and-contents
(volume-contents opened-volume)
(device-file opened-volume))))
(create-volume-and-contents
(volume-contents opened) (device-file opened)))))))
(unwind-protect
(mapc #'create-volume-and-contents
volumes (loop repeat (length volumes) collect (pop files)))
(mrun "sync")
(mapc #'close-volume opened-volumes)))))
;;;; Properties
(defmacro has-volumes (&rest volume-specifications)
"Specify non-removable volumes normally accessible to the kernel on this host.
The order of the list of volumes is significant: it is the order in which
attempts to open all of the volumes should be made. So, for example, any LVM
volume groups should occur later in the list than the partitions containing
the LVM physical volumes corresponding to those volume groups."
`(has-volumes* (volumes ,@volume-specifications)))
(defprop has-volumes* :posix (volumes)
(:desc "Has specified volumes.")
(:hostattrs
(os:required 'os:linux)
(push-hostattrs :volumes volumes)))
;; TODO This should probably be in another package, and exported from there.
(defproplist caches-cleaned :posix ()
"Clean all caches we know how to clean in preparation for image creation."
(:desc "Caches cleaned")
(file:data-cache-purged)
(os:typecase
(debianlike (apt:cache-cleaned))))
(defprop %raw-image-created :lisp (volumes &key chroot rebuild)
(:desc (declare (ignore volumes chroot rebuild))
#?"Created raw disk image & other volumes")
(:hostattrs
(require-volumes-data volumes)
;; We require GNU du(1).
(os:required 'os:linux))
(:check
(declare (ignore chroot))
(and
(not rebuild)
(file-exists-p
(image-file
(find-if (rcurry #'subtypep 'raw-disk-image) volumes :key #'type-of)))))
(:apply
(declare (ignore rebuild))
(multiple-value-bind (mount-points volumes)
;; Find all mount points, and make modifiable copies of volumes
;; containing filesystems without VOLUME-SIZE, which we'll set.
(loop for volume in volumes
for filesystems
= (delete-if-not (rcurry #'slot-boundp 'mount-point)
(subvolumes-of-type 'filesystem volume))
nconc (mapcar #'mount-point filesystems) into mount-points
if (loop for filesystem in filesystems
thereis (not (slot-boundp filesystem 'volume-size)))
collect (copy-volume-and-contents volume) into volumes
else collect volume into volumes
finally (return (values mount-points volumes)))
;; Do the VOLUME-SIZE updates. For now we make the assumption that a
;; copy of the files made by rsync will fit in a disk of 1.1 times the
;; size of however much space the files are taking up on whatever
;; filesystem underlies the chroot. An alternative would be to find the
;; actual size of each file's data and round it up to the block size of
;; FILESYSTEM, which could be stored in a slot. Since some filesystems
;; are able to store more than one file per block, we would probably want
;; a method on filesystem types to compute the expected size the file
;; will take up, call that on each file, and sum.
(dolist (filesystem
(mapcan (curry #'subvolumes-of-type 'filesystem) volumes))
(when (and (slot-boundp filesystem 'mount-point)
(not (slot-boundp filesystem 'volume-size)))
(let ((dir (mount-point filesystem)))
(setf (volume-size filesystem)
(+ (ceiling
(* 1.1
(parse-integer
(car
(split-string
(run "du" "-msx" (chroot-pathname dir chroot)
(loop for mount-point in mount-points
unless (eql mount-point dir)
collect (strcat "--exclude="
(unix-namestring
(chroot-pathname
mount-point chroot))
"/*"))))))))
(extra-space filesystem))))))
;; Finally, create the volumes.
(create-volumes-and-contents volumes))))
(defun image-chroot (image-pathname)
(ensure-directory-pathname
(strcat (unix-namestring image-pathname) ".chroot")))
(defun host-volumes-just-one-physical-disk (host fun)
(loop
with found
for volume in (get-hostattrs :volumes (preprocess-host host))
for physical-disk-p = (subtypep (type-of volume) 'physical-disk)
if (and physical-disk-p (not found) (slot-boundp volume 'volume-contents))
do (setq found t)
and collect (aprog1 (copy-volume-and-contents volume) (funcall fun it))
else unless physical-disk-p
collect volume
finally
(unless found
(inapplicable-property
"Volumes list for host has no DISK:PHYSICAL-DISK with contents."))))
(defpropspec raw-image-built-for :lisp
(options host image-pathname &key rebuild)
"Build a raw disk image for HOST at IMAGE-PATHNAME.
The image corresponds to the first DISK:PHYSICAL-DISK entry in the host's
volumes, as specified using DISK:HAS-VOLUMES; there must be at least one such
entry. Other DISK:PHYSICAL-DISK entries will be ignored, so ensure that none
of the properties of the host will write to areas of the filesystem where
filesystems stored on other physical disks would normally be mounted.
OPTIONS will be passed on to CHROOT:OS-BOOTSTRAPPED-FOR, which see.
In most cases you will need to ensure that HOST has properties which do at
least the following:
- declare the host's OS
- install a kernel
- install the binaries/packages needed to install the host's bootloader to
its volumes (usually with INSTALLER:BOOTLOADER-BINARIES-INSTALLED).
Unless REBUILD, the image will not be repartitioned even if the specification
of the host's volumes changes, although the contents of the image's
filesystems will be incrementally updated when other properties change."
(:desc #?"Built image for ${(get-hostname host)} @ ${image-pathname}")
(let ((chroot (image-chroot image-pathname))
(volumes (host-volumes-just-one-physical-disk
host (lambda (volume)
(change-class volume 'raw-disk-image)
(setf (image-file volume) image-pathname)))))
`(on-change (eseqprops
,(propapp (chroot:os-bootstrapped-for. options chroot host
(caches-cleaned)))
(%raw-image-created
,volumes :chroot ,chroot :rebuild ,rebuild))
(consfigurator.property.installer:files-installed-to-volumes-for
nil ,host ,volumes :chroot ,chroot))))
(defprop %volumes-created :lisp (volumes)
(:desc "Created host volumes")
(:hostattrs (os:required 'os:linux) (require-volumes-data volumes))
(:apply
(dolist (volume volumes)
(when (subtypep (type-of volume) 'physical-disk)
(setf (volume-size volume)
(floor (/ (parse-integer
(stripln
(run "blockdev" "--getsize64" (device-file volume))))
1048576)))))
(create-volumes-and-contents volumes)))
(defpropspec first-disk-installed-for :lisp
(options host device-file &key chroot)
"Install HOST to the DISK:PHYSICAL-DISK accessible at DEVICE-FILE.
**THIS PROPERTY UNCONDITIONALLY FORMATS DISKS, POTENTIALLY DESTROYING DATA,
EACH TIME IT IS APPLIED.**
Do not apply in DEFHOST. Apply with DEPLOY-THESE/HOSTDEPLOY-THESE.
The DISK:VOLUME-CONTENTS of the first DISK:PHYSICAL-DISK entry in the host's
volumes, as specified using DISK:HAS-VOLUMES, will be created at DEVICE-FILE;
there must be at least one such DISK:PHYSICAL-DISK entry. Other
DISK:PHYSICAL-DISK entries will be ignored, so ensure that none of the
properties of the host will write to areas of the filesystem where filesystems
stored on other physical disks would normally be mounted.
OPTIONS will be passed on to CHROOT:OS-BOOTSTRAPPED-FOR, which see.
In most cases you will need to ensure that HOST has properties which do at
least the following:
- declare the host's OS
- install a kernel
- install the binaries/packages needed to install the host's bootloader to
its volumes (usually with INSTALLER:BOOTLOADER-BINARIES-INSTALLED).
If CHROOT, an intermediate chroot is bootstrapped at CHROOT, and HOST's
properties are applied to that. Otherwise, HOST's OS is bootstrapped directly
to DEVICE-FILE. It's useful to supply CHROOT when you expect to install the
same HOST to a number of physical disks. It also makes it faster to try
deploying again if failures occur during the application of HOST's properties.
Applying this property is similar to applying DISK:RAW-IMAGE-BUILT-FOR and
then immediately dd'ing out the image to DEVICE-FILE. The advantage of this
property is that there is no need to resize filesystems to fill the size of
the host's actual physical disk upon first boot."
(:desc #?"Installed ${(get-hostname host)} to ${device-file}")
(let ((volumes (host-volumes-just-one-physical-disk
host (lambda (v)
(setf (device-file v)
(parse-unix-namestring device-file))))))
`(eseqprops
(%volumes-created ,volumes)
,@(and chroot
(list (propapp (chroot:os-bootstrapped-for. options chroot host
(caches-cleaned)))))
(consfigurator.property.installer:files-installed-to-volumes-for
,options ,host ,volumes :chroot ,chroot))))
(defpropspec volumes-installed-for :lisp (options host &key chroot leave-open)
"Install HOST to its volumes, as specified using DISK:HAS-VOLUMES.
**THIS PROPERTY UNCONDITIONALLY FORMATS DISKS, POTENTIALLY DESTROYING DATA,
EACH TIME IT IS APPLIED.**
Do not apply in DEFHOST. Apply with DEPLOY-THESE/HOSTDEPLOY-THESE.
OPTIONS will be passed on to CHROOT:OS-BOOTSTRAPPED-FOR, which see.
In most cases you will need to ensure that HOST has properties which do at
least the following:
- declare the host's OS
- install a kernel
- install the binaries/packages needed to install the host's bootloader to
its volumes (usually with INSTALLER:BOOTLOADER-BINARIES-INSTALLED).
If CHROOT, an intermediate chroot is bootstrapped at CHROOT, and HOST's
properties are applied to that. Otherwise, HOST's OS is bootstrapped directly
to its volumes. This parameter is useful for the case of installing HOST from
a live system which might not have network access. See \"Tutorial: OS
installation\" in the Consfigurator user's manual.
If LEAVE-OPEN, HOST's volumes will not be closed. This allows you to inspect
the result of the installation. If you want to run this property again, you
should first manually close all the volumes."
(:desc #?"Installed ${(get-hostname host)}")
(let ((volumes (get-hostattrs :volumes host)))
`(eseqprops
(%volumes-created ,volumes)
,@(and chroot
(list (propapp (chroot:os-bootstrapped-for. options chroot host
(caches-cleaned)))))
(consfigurator.property.installer:files-installed-to-volumes-for
,options ,host ,volumes :chroot ,chroot :leave-open ,leave-open))))
(defprop %squashfsed :posix (chroot image &optional (compression "xz"))
(:apply
(file:does-not-exist image)
(with-remote-temporary-file (excludes)
(write-remote-file
excludes (format nil "~@{~&~A~}" "/boot" "/proc" "/dev" "/sys" "/run"))
(run :inform "nice" "mksquashfs" chroot image
"-no-progress" "-comp" compression "-ef" excludes))))
;; Based on live-wrapper, and some help from this guide:
;; <https://willhaley.com/blog/custom-debian-live-environment/>
(defpropspec debian-live-iso-built :lisp (options image-pathname properties)
"Build a Debian Live hybrid ISO at IMAGE-PATHNAME for a host with properties
PROPERTIES, which should specify, at a minimum, the operating system for the
live system. OPTIONS is a plist of keyword parameters:
- :CHROOT-OPTIONS -- passed on to CHROOT:OS-BOOTSTRAPPED-FOR, which see.
Currently only BIOS boot is implemented."
(:desc #?"Debian Live ISO built @ ${image-pathname}")
(destructuring-bind
(&key chroot-options
&aux (chroot (image-chroot image-pathname))
(iso-root (ensure-directory-pathname
(strcat (unix-namestring image-pathname) ".cd")))
(isolinux (merge-pathnames "isolinux/" iso-root))
(squashfs (merge-pathnames "live/filesystem.squashfs" iso-root))
(host (make-host
:hostattrs '(:hostname ("debian"))
:propspec
(append-propspecs
properties
(make-propspec
:propspec
'(eseqprops
(apt:installed "initramfs-tools" "linux-image-amd64"
"live-boot" "task-laptop" "libnss-myhostname"
"syslinux-common" "isolinux")
(caches-cleaned))))))
(host-arch (os:debian-architecture (get-hostattrs-car :os host))))
options
(unless (member host-arch '(:amd64))
(inapplicable-property
"Architecture ~A of live host not supported." host-arch))
`(eseqprops
(apt:installed "squashfs-tools" "xorriso")
(file:directory-exists ,isolinux)
(file:containing-directory-exists ,squashfs)
(on-change (chroot:os-bootstrapped-for ,chroot-options ,chroot ,host)
(%squashfsed ,chroot ,squashfs)
;; Copy the chroot's versions of bootloader binaries.
(file:is-copy-of ,(merge-pathnames "isolinux.bin" isolinux)
,(chroot-pathname "/usr/lib/ISOLINUX/isolinux.bin"
chroot))
,@(loop for basename in '("ldlinux" "libcom32" "vesamenu" "libutil"
"libutil" "libmenu" "libgpl" "hdt")
for file = (strcat basename ".c32")
collect
`(file:is-copy-of
,(merge-pathnames file isolinux)
,(chroot-pathname
(merge-pathnames file "/usr/lib/syslinux/modules/bios/")
chroot)))
;; Copy the targets of the symlinks in the root of the chroot.
(file:is-copy-of ,(merge-pathnames "live/vmlinuz" iso-root)
,(merge-pathnames "vmlinuz" chroot))
(file:is-copy-of ,(merge-pathnames "live/initrd.img" iso-root)
,(merge-pathnames "initrd.img" chroot))
(file:exists-with-content ,(merge-pathnames "isolinux.cfg" isolinux)
("UI vesamenu.c32"
""
"MENU TITLE Live Boot Menu"
"DEFAULT linux"
"TIMEOUT 600"
"MENU RESOLUTION 640 480"
""
"LABEL linux"
" MENU LABEL Debian Live [BIOS/ISOLINUX]"
" MENU DEFAULT"
" KERNEL /live/vmlinuz"
" APPEND initrd=/live/initrd.img boot=live"
""
"LABEL linux"
" MENU LABEL Debian Live [BIOS/ISOLINUX] (nomodeset)"
" MENU DEFAULT"
" KERNEL /live/vmlinuz"
" APPEND initrd=/live/initrd.img boot=live nomodeset"))
(cmd:single
:inform
"xorriso" "-as" "mkisofs" "-iso-level" "3" "-o" ,image-pathname
"-full-iso9660-filenames" "-volid" "DEBIAN_LIVE"
"-isohybrid-mbr" ,(chroot-pathname "/usr/lib/ISOLINUX/isohdpfx.bin"
chroot)
"-eltorito-boot" "isolinux/isolinux.bin"
"-no-emul-boot" "-boot-load-size" "4" "-boot-info-table"
"--eltorito-catalog" "isolinux/isolinux.cat"
,iso-root)))))
;; TODO Possibly we want (a version of) this to not fail, but just do nothing,
;; if the relevant volume groups etc. are inactive?
(defproplist host-logical-volumes-exist :lisp ()
"Create missing logical volumes, like LVM logical volumes and BTRFS
subvolumes, as specified by DISK:HAS-VOLUMES. Does not delete or overwrite
anything, aside from editing /etc/fstab in some cases. Intended to make it
easy to add new logical volumes by just editing the volumes specification.
For logical volumes containing instances of FILESYSTEM with a specified
MOUNT-POINT, ensure there's an /etc/fstab entry and try to mount.
Currently only handling of LVM logical volumes is implemented."
(:desc "Host logical volumes all exist")
(host-lvm-logical-volumes-exist))
;;;; Utilities
(defun parse-volume-size (volume-size-specification)
(if (stringp volume-size-specification)
(aif (#~/\A(\d+)([MGT])?\z/p volume-size-specification)
(* (elt it 0)
(eswitch ((elt it 1) :test #'string=)
("M" 1)
("G" 1024)
("T" 1048576)))
(simple-program-error "~A is not a valid volume size."
volume-size-specification))
volume-size-specification))
(defmacro volumes (&body volume-specifications)
"Return a list of instances of VOLUME, one for each element of
VOLUME-SPECIFICATIONS. Each of VOLUME-SPECIFICATIONS is an (unquoted) list of
the form (TYPE &REST INITARGS).
TYPE is a symbol naming the volume type to be initialised. If the symbol does
not name a subclass of VOLUME, it will be replaced with a symbol of the same
name in the DISK package; this allows type names to be used unqualified.
INITARGS is an even-length plist, possibly with a final additional element,
which is either another volume specification or an (unquoted) list of volume
specifications. This becomes the VOLUME-CONTENTS of the VOLUME.
The following keys in INITARGS are handled specially:
- :VOLUME-SIZE -- may be a string like \"100M\", \"2G\", \"1T\" which will
be converted into a whole number of mebibytes. \"M\", \"G\", and \"T\"
are currently supported.
Example usage:
(volumes
(physical-disk
(partitioned-volume
((partition
:partition-typecode #xef00
(fat32-filesystem
:volume-size \"512M\"
:mount-point #P\"/boot/efi\"))
(partition
(luks-container
(lvm-physical-volume
:volume-group \"vg_laptop\"))))))
(lvm-logical-volume
:volume-group \"vg_laptop\"
:volume-label \"lv_laptop_root\"
(ext4-filesystem :mount-point #P\"/\")))"
(labels
((parse (spec)
(unless (listp spec)
(simple-program-error "~A is not a list." spec))
(let* ((contentsp (not (evenp (length (cdr spec)))))
(initargs
(if contentsp (butlast (cdr spec)) (cdr spec)))
(contents (and contentsp (lastcar (cdr spec)))))
(when (loop for key on initargs by #'cddr
thereis (and (eql (car key) :volume-size)))
(setf (getf initargs :volume-size)
`(parse-volume-size ,(getf initargs :volume-size))))
(when (and contents (not (listp contents)))
(simple-program-error "~A is not a list." contents))
`(make-instance
',(let ((class (find-class (car spec) nil)))
(if (and class (subtypep (class-name class) 'volume))
(car spec)
(intern (symbol-name (car spec))
(find-package :consfigurator.property.disk))))
,@initargs
,@(and contentsp
`(:volume-contents
,(if (listp (car contents))
`(list ,@(mapcar #'parse contents))
(parse contents))))))))
`(list ,@(mapcar #'parse volume-specifications))))
| 56,925 | Common Lisp | .lisp | 1,123 | 41.347284 | 85 | 0.648239 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 88ab6a2bbee5c0937c9ab8e2557e084736a046d84ff290405909a6227020204c | 3,951 | [
-1
] |
3,952 | reboot.lisp | spwhitton_consfigurator/src/property/reboot.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.reboot)
(named-readtables:in-readtable :consfigurator)
(defprop %at-end :posix ()
(:apply
(consfigurator:at-end
(lambda (result)
(declare (ignore result))
(handler-case (mrun "shutdown" "-r" "+1")
;; Sometimes after INSTALLER::%ROOT-FILESYSTEMS-FLIPPED shutdown(8)
;; can't schedule a future reboot, but an immediate one is fine.
(run-failed ()
(mrun "nohup" "sh" "-c"
"(sleep 60; shutdown -r now) </dev/null >/dev/null 2>&1 &")))
(inform t "*** SYSTEM REBOOT SCHEDULED, one minute delay ***")))))
(defproplist at-end :posix ()
"Schedule a reboot for the end of the current (sub)deployment.
The reboot is scheduled with a one minute delay to allow remote Lisp images to
return correct exit statuses to the root Lisp, for the root Lisp to have time
to download their output, etc."
(container:when-contained (:reboot) (%at-end)))
| 1,716 | Common Lisp | .lisp | 32 | 49.875 | 78 | 0.713775 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | fdcee2731eb46503783f7e65a1aaa18bbec527de7248ef391d6613920f774e95 | 3,952 | [
-1
] |
3,953 | firewalld.lisp | spwhitton_consfigurator/src/property/firewalld.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.firewalld)
(named-readtables:in-readtable :consfigurator)
(defproplist installed :posix ()
(:desc "firewalld installed")
(os:etypecase
(debianlike (apt:installed "firewalld"))))
;; We employ three strategies for determining whether or not a change was
;; already applied: checking for exit status zero from a firewall-cmd(1) query
;; subcommand like --query-masquerade, looking for certain warning messages in
;; the output, and checking whether certain files under /etc/firewalld change.
;; It would be better if we could just look for the warnings, but
;; firewall-cmd(1) is not consistent about emitting a warning when no change
;; was made -- for example, --set-target always just says "success", but
;; --add-service will say "ALREADY_ENABLED". We can't completely rely on file
;; content changes either because this is no use when changing the runtime
;; configuration, and if we make no change to a built-in zone, or similar, the
;; corresponding .xml file may not exist either before or after running the
;; command, and given how WITH-CHANGE-IF-CHANGES-FILE works, this means we
;; would fail to return :NO-CHANGE.
;;
;; We incorporate :CHECK into :APPLY here because for most commands we need to
;; check runtime and permanent configuration separately, and two properties is
;; unwieldy. Previously we updated only the permanent configuration, and then
;; did 'firewall-cmd --reload' when we detected that a change had been made.
;; However, that has the side effect of wiping out configuration which should
;; only ever be part of the runtime configuration, perhaps added by scripts.
;; A disadvantage of the current approach is that it is probably more likely
;; to lead to inconsistent runtime configurations.
;;
;; Both WARNING and APPLY are usually different for unapplication, so we rely
;; on WITH-UNAPPLY together with another application of this property when we
;; want to make a property unapplicable, rather than defining :UNAPPLY here.
(defprop %firewall-cmd :posix
(runtimep &key file warning check complement-check
apply (offline-apply apply) (--permanent t)
&aux (check-fn (if complement-check #'plusp #'zerop)))
(:apply
(setq check (ensure-list check)
apply (ensure-list apply)
offline-apply (ensure-list offline-apply))
(labels ((search-warning (output)
(and warning (search output warning) :no-change))
(permanent-change ()
(search-warning
(if (service:no-services-p)
;; Contrary to its manpage, firewall-offline-cmd(1) often
;; exits nonzero when issuing the ALREADY_ENABLED,
;; NOT_ENABLED and ZONE_ALREADY_SET warnings.
(handler-bind
((run-failed
(lambda (c)
(when (and warning
(search warning (run-failed-stdout c)))
(return-from permanent-change :no-change)))))
(apply #'mrun "firewall-offline-cmd" offline-apply))
(if --permanent
(apply #'mrun "firewall-cmd" "--permanent" apply)
(apply #'mrun "firewall-cmd" apply))))))
(let* ((runtime-check
(or (service:no-services-p)
(and runtimep check
(funcall
check-fn
(apply #'mrun :for-exit "firewall-cmd" check)))))
(permanent-check
(and check
(funcall check-fn
(apply #'mrun :for-exit
(if (service:no-services-p)
"firewall-offline-cmd"
'("firewall-cmd" "--permanent"))
check))))
(runtime (if (or runtime-check (not runtimep))
:no-change
(search-warning (apply #'mrun "firewall-cmd" apply))))
(permanent
(if permanent-check
:no-change
(if file
(with-change-if-changes-file
((merge-pathnames file #P"/etc/firewalld/"))
(permanent-change))
(permanent-change)))))
(and (eql :no-change permanent) (eql :no-change runtime) :no-change)))))
;;;; Setting contents of XML configuration files
(defprop %reloaded :posix ()
(:apply (if (service:no-services-p)
:no-change
(mrun "firewall-cmd" "--reload"))))
(defproplist %setxml :posix (type name xml)
(installed)
(on-change
(file:exists-with-content #?"/etc/firewalld/${type}/${name}.xml" xml)
(%reloaded)))
(defproplist knows-service :posix (service xml)
(:desc #?"firewalld knows service ${service}")
(%setxml "services" service xml))
(defproplist has-policy :posix (policy xml)
(:desc #?"firewalld has policy ${policy}")
(%setxml "policies" policy xml))
(defproplist has-zone-xml :posix (zone xml)
"Set the whole XML configuration for zone ZONE.
In preference to using this property, it is usually best to incrementally
build up the configuration for a zone using properties like
FIREWALLD:ZONE-HAS-SERVICE, FIREWALLD:ZONE-HAS-INTERFACE etc.. Using this
property forces most of your firewall configuration to be in a single place in
your consfig, but it is typically more readable and flexible to have
properties which set up the actual services and interfaces interact with the
firewall configuration themselves, to render the things that those properties
set up appropriately accessible and inaccessible.
(By contrast, for defining services and policies we take the simpler approach
of just setting the whole XML configuration, using FIREWALLD:KNOWS-SERVICE and
FIREWALLD:HAS-POLICY.)"
;; Another option might be to push all the settings to hostattrs and then at
;; :APPLY time, generate the whole .xml / run commands to set all the XML.
(:desc #?"firewalld has zone configuration for ${zone}")
(%setxml "zones" zone xml))
;;;; Incremental configuration of zones
(defproplist has-zone :posix (zone)
"Ensure that the zone ZONE exists.
You will not usually need to call this property directly; it is applied by
properties which add services, interfaces etc. to zones."
(:desc #?"firewalld zone ${zone} exists")
(on-change (with-unapply
(%firewall-cmd nil :check `(,#?"--zone=${zone}" "--get-target")
:apply #?"--new-zone=${zone}")
:unapply
(%firewall-cmd nil :complement-check t
:check `(,#?"--zone=${zone}" "--get-target")
:apply #?"--delete-zone=${zone}"))
(%reloaded)))
(defproplist zone-has-target :posix (zone target)
(:desc #?"firewalld zone ${zone} has target ${target}")
(:check (if (service:no-services-p)
(string= target
(stripln (run :may-fail "firewall-offline-cmd"
#?"--zone=${zone}" "--get-target")))
(string= target
(stripln
(run :may-fail "firewall-cmd" "--permanent"
#?"--zone=${zone}" "--get-target")))))
(installed)
(has-zone zone)
(on-change (%firewall-cmd
nil :file #?"zones/${zone}.xml"
:apply `(,#?"--zone=${zone}" ,#?"--set-target=${target}"))
(%reloaded)))
(defprop %default-route-zoned :posix (zone)
(:apply
(aif (loop for line in (runlines "ip" "route" "list" "scope" "global")
when (string-prefix-p "default " line)
return (fifth (words line)))
(%firewall-cmd
t :file #?"zones/${zone}.xml"
:check `(,#?"--zone=${zone}" ,#?"--query-interface=${it}")
:apply `(,#?"--zone=${zone}" ,#?"--change-interface=${it}"))
(failed-change
"Could not determine the interface of the default route."))))
(defproplist default-route-zoned-once :posix (&optional (zone "public"))
"Bind the interface of the default route to zone ZONE, only if this property
has not done that yet for at least one (INTERFACE . ZONE) pair.
This property is intended for machines which have firewalld but do not use
Network Manager, as is typical on Debian servers using firewalld. On such
machines firewalld will fail to add the primary network interface to any zone
when the interface comes up before firewalld does.
This property avoids the situation in which the primary network interface is
not part of any zone by explicitly adding it to ZONE, determining the name of
the interface by examining the current default route. The property only adds
an interface to a zone once, as the default route might later be changed
temporarily by something like a VPN connection, and in such a case the
firewall should not be reconfigured.
Typically you will apply both this property and FIREWALLD:HAS-DEFAULT-ZONE,
passing the same zone name to each. If you have Network Manager, you need
only FIREWALLD:HAS-DEFAULT-ZONE."
(with-flagfile "/etc/consfigurator/firewalld/default-route-zoned"
(installed)
(has-zone zone)
(%default-route-zoned zone)))
(defproplist zone-has-interface :posix (zone interface)
(:desc #?"firewalld zone ${zone} has interface ${interface}")
(with-unapply
(installed)
(has-zone zone)
(%firewall-cmd
t :file #?"zones/${zone}.xml"
:check `(,#?"--zone=${zone}" ,#?"--query-interface=${interface}")
:apply `(,#?"--zone=${zone}" ,#?"--change-interface=${interface}"))
:unapply
(%firewall-cmd
t :file #?"zones/${zone}.xml" :complement-check t
:check `(,#?"--zone=${zone}" ,#?"--query-interface=${interface}")
:apply `(,#?"--zone=${zone}" ,#?"--remove-interface=${interface}"))))
(defproplist zone-has-source :posix (zone source)
(:desc #?"firewalld zone ${zone} has source ${source}")
(with-unapply
(installed)
(has-zone zone)
(%firewall-cmd
t :file #?"zones/${zone}.xml" :warning "ZONE_ALREADY_SET"
:check `(,#?"--zone=${zone}" ,#?"--query-source=${source}")
:apply `(,#?"--zone=${zone}" ,#?"--add-source=${source}"))
:unapply
(%firewall-cmd
t :file #?"zones/${zone}.xml" :warning "UNKNOWN_SOURCE"
:complement-check t
:check `(,#?"--zone=${zone}" ,#?"--query-source=${source}")
:apply `(,#?"--zone=${zone}" ,#?"--remove-source=${source}"))))
(defproplist zone-has-service :posix (zone service)
(:desc #?"firewalld zone ${zone} has service ${service}")
(with-unapply
(installed)
(has-zone zone)
(%firewall-cmd
t :file #?"zones/${zone}.xml"
:warning "ALREADY_ENABLED"
:check `(,#?"--zone=${zone}" ,#?"--query-service=${service}")
:apply `(,#?"--zone=${zone}" ,#?"--add-service=${service}"))
:unapply
(%firewall-cmd
t :file #?"zones/${zone}.xml" :warning "NOT_ENABLED"
:complement-check t
:check `(,#?"--zone=${zone}" ,#?"--query-service=${service}")
:apply `(,#?"--zone=${zone}" ,#?"--remove-service=${service}")
:offline-apply
`(,#?"--zone=${zone}" ,#?"--remove-service-from-zone=${service}"))))
(defproplist zone-has-masquerade :posix (zone)
(:desc #?"firewalld zone ${zone} has masquerade")
(with-unapply
(installed)
(has-zone zone)
(%firewall-cmd t :file #?"zones/${zone}.xml" :warning "ALREADY_ENABLED"
:check `(,#?"--zone=${zone}" "--query-masquerade")
:apply `(,#?"--zone=${zone}" "--add-masquerade"))
:unapply
(%firewall-cmd t :file #?"zones/${zone}.xml" :warning "NOT_ENABLED"
:complement-check t
:check `(,#?"--zone=${zone}" "--query-masquerade")
:apply `(,#?"--zone=${zone}" "--remove-masquerade"))))
(defproplist zone-has-rich-rule :posix (zone rule)
(:desc #?"firewalld zone ${zone} has rich rule \"${rule}\"")
(with-unapply
(installed)
(has-zone zone)
(%firewall-cmd
t :file #?"zones/${zone}.xml" :warning "ALREADY_ENABLED"
:check `(,#?"--zone=${zone}" ,#?"--query-rich-rule=${rule}")
:apply `(,#?"--zone=${zone}" ,#?"--add-rich-rule=${rule}"))
:unapply
(%firewall-cmd
t :file #?"zones/${zone}.xml" :warning "NOT_ENABLED"
:complement-check t
:check `(,#?"--zone=${zone}" ,#?"--query-rich-rule=${rule}")
:apply `(,#?"--zone=${zone}" ,#?"--remove-rich-rule=${rule}"))))
;;;; Other daemon configuration
;; Note that direct rules will be deprecated as of firewalld 1.0.0, as
;; policies and rich rules should be able to cover all uses of direct rules.
;; <https://firewalld.org/2021/06/the-upcoming-1-0-0>
(defpropspec has-direct-rule :posix (&rest rule-args)
(:desc #?"firewalld has direct rule \"@{rule-args}\"")
`(with-unapply
(installed)
(%firewall-cmd t :file "direct.xml" :warning "ALREADY_ENABLED"
:check ("--direct" "--query-rule" ,@rule-args)
:apply ("--direct" "--add-rule" ,@rule-args))
:unapply
(%firewall-cmd t :file "direct.xml" :warning "NOT_ENABLED"
:complement-check t
:check ("--direct" "--query-rule" ,@rule-args)
:apply ("--direct" "--remove-rule" ,@rule-args))))
(defproplist has-default-zone :posix (zone)
(:desc #?"firewalld default zone is ${zone}")
(installed)
(has-zone zone)
(%firewall-cmd nil
:file "firewalld.conf" :warning "ZONE_ALREADY_SET"
:--permanent nil :apply #?"--set-default-zone=${zone}"))
| 14,565 | Common Lisp | .lisp | 288 | 42.28125 | 79 | 0.622305 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 467bb52a719fd1c6083839f4f288ee09e4455e51bdc09d8f56f7bd56c2b09e8a | 3,953 | [
-1
] |
3,954 | u-boot.lisp | spwhitton_consfigurator/src/property/u-boot.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021-2022 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.u-boot)
(named-readtables:in-readtable :consfigurator)
;; Currently we have a distinct property for each (Debian-specific)
;; installation script. Perhaps there is some sensible parameterisation of
;; these available instead.
(defmethod install-bootloader-propspec
((type (eql 'install-rockchip)) volume &rest args &key &allow-other-keys)
`(installed-rockchip ,volume ,@args))
(defmethod install-bootloader-binaries-propspec
((type (eql 'install-rockchip)) volume &key &allow-other-keys)
'(os:etypecase
(debianlike
(apt:installed "u-boot-rockchip"))))
(defprop installed-rockchip :posix (volume &key target)
(:desc "Installed U-Boot using Debian scripts")
(:hostattrs
(os:required 'os:debianlike)
(or (container:contained-p :physical-disks) target
(inapplicable-property
"Must specify TARGET for u-boot-install-rockchip(8) unless running on device.")))
(:apply
(let ((args (list "u-boot-install-rockchip" (device-file volume))))
(if target
(apply #'mrun :env `(:TARGET ,target) args)
(apply #'mrun args)))))
| 1,903 | Common Lisp | .lisp | 37 | 48.027027 | 89 | 0.736672 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 2c7eafff8c806e9cc122c461ad7537a59a5c19ec3d500f5668ac0f39bff0586a | 3,954 | [
-1
] |
3,955 | sbuild.lisp | spwhitton_consfigurator/src/property/sbuild.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2016, 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.sbuild)
(named-readtables:in-readtable :consfigurator)
(defproplist installed :posix ()
"Ensure that sbuild and associated utilities are installed."
(:desc "sbuild and associated utilities installed")
(os:etypecase
(debianlike (apt:installed "piuparts" "autopkgtest" "lintian" "sbuild"))))
(defproplist usable-by :posix (username)
"Add a user to the sbuild group in order to use sbuild."
(:desc #?"sbuild usable by ${username}")
(installed)
(user:has-groups username "sbuild"))
(defproplist %sbuild-ccache-has-some-limits :posix ()
"Set a default limit on the sbuild ccache, only if the ccache does not already
exist, so that the user can easily override this default."
(:desc #?"Default limits on sbuild ccache")
(:check (remote-exists-p "/var/cache/ccache-sbuild"))
(ccache:has-limits "/var/cache/ccache-sbuild" :max-size "2Gi"))
(defpropspec built :lisp
(options properties
&aux (host
(make-child-host
:propspec
(append-propspecs
properties
(make-propspec
:systems nil
:propspec
'(desc "Build packages installed into chroot"
(os:etypecase
(debianlike (apt:installed "eatmydata" "ccache"))))))))
(os (get-hostattrs-car :os host))
(suite (os:debian-suite os))
(arch (os:debian-architecture-string os)))
"Build and configure a schroot for use with sbuild.
For convenience we set up several enhancements, such as ccache and eatmydata.
In the case of Debian, we assume you are building for Debian stretch or newer,
and we assume that you have sbuild 0.71.0 or later and, if overlays are
enabled, Linux 3.18 or newer.
OPTIONS is a plist of keyword parameters:
- :USE-CCACHE -- whether builds using the schroot should use ccache. ccache
is generally useful but breaks building some packages; this option allows
you to toggle it on and off for particular schroots. Defaults to t.
- :CHROOT-OPTIONS -- passed on to CHROOT:OS-BOOTSTRAPPED-FOR, which see.
PROPERTIES should specify, at a minimum, the operating system for the schroot.
Example usage:
(os:debian-stable \"bullseye\" :amd64)
(apt:uses-local-cacher)
(apt:mirrors \"...\")
(sbuild:usable-by \"spwhitton\")
(schroot:overlays-in-tmpfs)
(periodic:reapplied-at-most :monthly \"sbuild sid schroot (re)built\"
(sbuild:built. nil
(os:debian-unstable :amd64)
(sbuild:standard-debian-schroot)
(apt:uses-parent-proxy)
(apt:uses-parent-mirrors)))
To take advantage of the piuparts and autopkgtest support, add to your
~/.sbuildrc:
$piuparts_opts = [
'--no-eatmydata',
'--schroot',
'%r-%a-sbuild',
'--log-level=info',
];
$autopkgtest_root_args = \"\";
$autopkgtest_opts = [\"--\", \"schroot\", \"%r-%a-sbuild\"];"
(:desc (format nil "Built sbuild schroot for ~A/~A" suite arch))
(destructuring-bind
(&key (use-ccache t) chroot-options
&aux
(chroot-options (if (member :variant chroot-options)
chroot-options
(list* :variant "buildd" chroot-options)))
(chroot
(ensure-pathname
(format nil "~A-~A" suite arch)
:ensure-directory t :ensure-absolute t :defaults #P"/srv/chroot/"))
(desc (format nil "~A/~A autobuilder" suite arch))
(conf (ensure-pathname
(format nil "~A-~A-sbuild-consfigurator" suite arch)
:ensure-absolute t :defaults #P"/etc/schroot/chroot.d/")))
options
`(with-unapply
(installed)
;; ccache
,@(and use-ccache '((%sbuild-ccache-has-some-limits)
(ccache:cache-for-group "sbuild")))
(desc
"ccache mounted in sbuild schroots"
(file:contains-lines "/etc/schroot/sbuild/fstab"
"/var/cache/ccache-sbuild /var/cache/ccache-sbuild none rw,bind 0 0"))
;; Script from <https://wiki.debian.org/sbuild>.
(file:has-content "/var/cache/ccache-sbuild/sbuild-setup" #>>~EOF>>
#!/bin/sh
export CCACHE_DIR=/var/cache/ccache-sbuild
export CCACHE_UMASK=002
export CCACHE_COMPRESS=1
unset CCACHE_HARDLINK
export PATH="/usr/lib/ccache:$PATH"
exec "$@"
EOF :mode #o755)
;; schroot
(chroot:os-bootstrapped-for ,chroot-options ,chroot ,host)
(desc
,(strcat "schroot configuration for " desc)
(file:contains-ini-settings
,conf
,@(mapcar
(curry #'cons (format nil "~A-~A-sbuild" suite arch))
`(("description" ,desc)
("groups" "root,sbuild")
("root-groups" "root,sbuild")
("profile" "sbuild")
("type" "directory")
("directory" ,(drop-trailing-slash (unix-namestring chroot)))
,@(and (get-hostattrs-car 'schroot:uses-overlays)
`(("union-type" "overlay")))
;; If we're building a sid chroot, add useful aliases. In order
;; to avoid more than one schroot getting the same aliases, we
;; only do this if the arch of the chroot equals the host arch.
,@(and (string= suite "unstable")
(string=
arch
(os:debian-architecture-string (get-hostattrs-car :os)))
`(("aliases"
,(format
nil "~@{~A~^,~}"
"sid"
;; If the user wants to build for experimental, they
;; would use their sid chroot and sbuild's
;; --extra-repository option to enable experimental.
"rc-buggy"
"experimental"
;; We assume that building for UNRELEASED means
;; building for unstable.
"UNRELEASED"
;; The following is for dgit compatibility.
(strcat "UNRELEASED-"
(os:debian-architecture-string os)
"-sbuild")))))
("command-prefix"
,(if use-ccache
"/var/cache/ccache-sbuild/sbuild-setup,eatmydata"
"eatmydata"))))))
;; TODO We should kill any sessions still using the chroot before
;; destroying it (as suggested by sbuild-destroychroot(8)).
:unapply
(unapplied (chroot:os-bootstrapped-for ,chroot-options ,chroot ,host))
(file:does-not-exist ,conf))))
;; Here we combine Propellor's Sbuild.osDebianStandard and Sbuild.update.
(defpropspec standard-debian-schroot :posix (&key (upgrade :weekly))
"Properties that will be wanted in almost any Debian sbuild schroot, but not
in sbuild schroots for other operating systems.
Includes replacing use of sbuild-update(1)."
(:desc "Standard Debian sbuild properties")
(:hostattrs (os:required 'os:debian))
`(eseqprops (apt:standard-sources.list)
(periodic:at-most ,upgrade
;; For normal use we don't require a unique description in
;; order to ensure that we properly track the updating of
;; each of multiple Debian build schroots on one machine.
;; That's because each schroot is its own host.
;; Nonetheless, it is helpful to have the suite and
;; architecture present in Consfigurator's output.
,(alet (get-hostattrs-car :os)
(format nil "sbuild schroot for ~A/~A updated"
(os:debian-suite it)
(os:debian-architecture-string it)))
(apt:updated) (apt:upgraded) (apt:autoremoved))))
| 9,056 | Common Lisp | .lisp | 182 | 37.697802 | 81 | 0.58777 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | d1ae2690ae401af35594201e18fcdd6ffd235e6b8f9c6449b8e8ba4af271c5d8 | 3,955 | [
-1
] |
3,956 | installer.lisp | spwhitton_consfigurator/src/property/installer.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021-2022 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.installer)
(named-readtables:in-readtable :consfigurator)
;;;; Bootloaders
;;; The basic reason VOLUME-BOOTLOADERS is not just a propspec but a
;;; specification for a propspec is that we need to pass an OPENED-VOLUME to
;;; the property that will install the bootloader. But maybe we could have
;;; INSTALL-BOOTLOADER-PROPSPEC but not INSTALL-BOOTLOADER-BINARIES-PROPSPEC.
;;; The installation of the bootloader binaries would always be done just
;;; before installing the bootloader, and the user would not need to
;;; separately apply BOOTLOADER-BINARIES-INSTALLED.
(defgeneric install-bootloader-propspec (bootloader-type volume &key)
(:documentation
"Return a propspec expression which installs bootloader of type
BOOTLOADER-TYPE to VOLUME.
The propapp yielded by the propspec may be of type :POSIX or of type :LISP.
The property can call CONTAINER:CONTAINED-P with relevant factors to determine
whether the host to which we are connected is the host the bootloader will
boot. For example, (container:contained-p :efi-nvram) returns NIL when
building disk images, and T when installing a host from a live environment.
Bootloader installation might behave differently when certain factors are not
contained, or error out. For examples, see GRUB:GRUB-INSTALLED and
U-BOOT:INSTALLED-ROCKCHIP."))
(defgeneric install-bootloader-binaries-propspec (bootloader-type volume &key)
(:documentation
"Return a propspec expression evaluating to a :POSIX propapp which
fetches/installs whatever binaries/packages need to be available to install
BOOTLOADER-TYPE to VOLUME."))
(defun get-propspecs (volumes)
(loop for volume in (mapcan #'all-subvolumes volumes)
when (slot-boundp volume 'volume-bootloaders)
nconc (loop with bls = (volume-bootloaders volume)
for bootloader in (if (listp (car bls)) bls (list bls))
collect (destructuring-bind (type . args) bootloader
(apply #'install-bootloader-propspec
type volume args)))))
;; At :HOSTATTRS time we don't have the OPENED-VOLUME values required by the
;; :APPLY subroutines which actually install the bootloaders. So we call
;; GET-PROPSPECS twice: (in FILES-INSTALLED-TO-VOLUMES-FOR) at :HOSTATTRS time
;; to generate propspecs for the sake of running :HOSTATTRS subroutines, and
;; then at :APPLY time where we can get at the OPENED-VOLUME values, we ignore
;; the previously generated propspecs and call GET-PROPSPECS again. This
;; approach should work for any sensible VOLUME<->OPENED-VOLUME pairs.
(define-function-property-combinator %install-bootloaders (&rest propapps)
(:retprop
:type :lisp
:hostattrs (lambda () (mapc #'propapp-attrs propapps))
:apply
(lambda ()
(mapc #'consfigure (get-propspecs (get-connattr 'disk:opened-volumes)))
(mrun "sync"))))
;;;; Properties
(defprop %update-target-from-chroot :posix (chroot target)
(:desc #?"Updated ${target} from ${chroot}")
(:apply
(assert-remote-euid-root)
(run "rsync" "-PSavx" "--delete"
(loop for volume
in (mapcan (curry #'subvolumes-of-type 'mounted-filesystem)
(get-connattr 'disk:opened-volumes))
collect (strcat "--exclude="
(unix-namestring (mount-point volume))))
(strcat (unix-namestring chroot) "/")
(strcat (unix-namestring target) "/"))))
(defun chroot-target (chroot)
(ensure-directory-pathname
(strcat
(drop-trailing-slash (unix-namestring (ensure-directory-pathname chroot)))
".target")))
(defpropspec files-installed-to-volumes-for :lisp
(options host volumes &key chroot leave-open
(mount-below (if chroot (chroot-target chroot) #P"/target/")))
"Where CHROOT contains the root filesystem of HOST and VOLUMES is a list of
volumes, recursively open the volumes and rsync in the contents of CHROOT.
Also update the fstab and crypttab, and try to install bootloader(s).
If CHROOT is NIL, bootstrap a root filesystem for HOST directly to VOLUMES.
In that case, OPTIONS is passed on to CHROOT:OS-BOOTSTRAPPED-FOR, which see.
MOUNT-BELOW and LEAVE-OPEN are passed on to WITH-OPENED-VOLUMES, which see."
(:desc (format nil "~A installed to volumes"
(or chroot (get-hostname host))))
`(with-opened-volumes
(,volumes :mount-below ,mount-below :leave-open ,leave-open)
,(if chroot
`(%update-target-from-chroot ,chroot ,mount-below)
`(chroot:os-bootstrapped-for ,options ,mount-below ,host))
(chroot:deploys-these
,mount-below ,host
,(make-propspec
:propspec
`(eseqprops
,(propapp
(os:etypecase
(debianlike
(file:lacks-lines
"/etc/fstab" "# UNCONFIGURED FSTAB FOR BASE SYSTEM")
;; These will overwrite any custom mount options, etc., with
;; values from VOLUMES. Possibly it would be better to use
;; properties which only update the fs-spec/source fields.
;; However, given that VOLUMES ultimately comes from the
;; volumes the user has declared for the host, it is unlikely
;; there are other properties setting mount options etc. which
;; are in conflict with VOLUMES.
(fstab:has-entries-for-opened-volumes)
(on-change (crypttab:has-entries-for-opened-volumes)
(cmd:single "update-initramfs" "-u")))))
(%install-bootloaders
,@(get-propspecs (get-hostattrs :volumes))))))))
(defpropspec bootloader-binaries-installed :posix ()
"Install whatever binaries/packages need to be available to install the host's
bootloaders to its volumes from within that host. For example, this might
install a package providing /usr/sbin/grub-install, but it won't execute it."
(:desc "Bootloader binaries installed")
(loop
for volume in (mapcan #'all-subvolumes (get-hostattrs :volumes))
when (slot-boundp volume 'volume-bootloaders)
nconc (loop with bls = (volume-bootloaders volume)
for bootloader in (if (listp (car bls)) bls (list bls))
collect (destructuring-bind (type . args) bootloader
(apply #'install-bootloader-binaries-propspec
type volume args)))
into propspecs
finally
(setq propspecs (delete-duplicates propspecs :test #'tree-equal))
(return
(if (cdr propspecs) (cons 'eseqprops propspecs) (car propspecs)))))
(defpropspec bootloaders-installed :lisp ()
"Install the host's bootloaders to its volumes.
Intended to be attached to properties like INSTALLER:CLEANLY-INSTALLED-ONCE
using a combinator like ON-CHANGE, or applied manually with DEPLOY-THESE."
(:desc "Bootloaders installed")
`(eseqprops
(bootloader-binaries-installed)
,@(get-propspecs (get-hostattrs :volumes))))
;;;; Live replacement of GNU/Linux distributions
;;; This is based on Propellor's OS.cleanInstallOnce property -- very cool!
;;;
;;; We prepare only a base system chroot, and then apply the rest of the
;;; host's properties after the flip, rather than applying all of the host's
;;; properties to the chroot and only then flipping. This has the advantage
;;; that properties which normally restrict themselves when running in a
;;; chroot will instead apply all of their changes. There could be failures
;;; due to still running the old OS's kernel and init system, however, which
;;; might be avoided by applying the properties only to the chroot.
;;;
;;; Another option would be a new SERVICES:WITHOUT-STARTING-SERVICES-UNTIL-END
;;; which would disable starting services and push the cleanup forms inside
;;; the definition of SERVICES:WITHOUT-STARTING-SERVICES to *AT-END-FUNCTIONS*
;;; in a closure. We'd also want %CONSFIGURE to use UNWIND-PROTECT to ensure
;;; that the AT-END functions get run even when there's a nonlocal exit from
;;; %CONSFIGURE's call to APPLY-PROPAPP; perhaps we could pass a second
;;; argument to the AT-END functions indicating whether there was a non-local
;;; transfer of control. REBOOT:AT-END might only reboot when there was a
;;; normal return from APPLY-PROPAPP, whereas the cleanup forms from
;;; SERVICES:WITHOUT-STARTING-SERVICES would always be evaluated.
(defprop %root-filesystems-flipped :lisp (new-os old-os)
(:hostattrs (os:required 'os:linux))
(:apply
(assert-remote-euid-root)
(let ((new-os (ensure-directory-pathname new-os))
(old-os
(ensure-directories-exist (ensure-directory-pathname old-os)))
(preserved-directories
'(;; This can contain sockets, remote Lisp image output, etc.;
;; avoid upsetting any of those.
#P"/tmp/"
;; Makes sense to keep /proc until we replace the running init,
;; and we want to retain all the systemd virtual filesystems
;; under /sys to avoid problems applying other properties. Both
;; are empty directories right after debootstrap, so nothing to
;; copy out.
#P"/proc/" #P"/sys/"
;; This we make use of below.
#P"/old-run/"))
efi-system-partition-mount-args)
(flet ((system (&rest args)
(alet (loop for arg in args
if (pathnamep arg)
collect (unix-namestring arg)
else collect arg)
(foreign-funcall "system" :string (sh-escape it) :int)))
(preservedp (pathname)
(member pathname preserved-directories :test #'pathname-equal)))
(mount:assert-devtmpfs-udev-/dev)
(unless (remote-mount-point-p "/run")
(failed-change "/run is not a mount point; don't know what to do."))
;; If there's an EFI system partition, we need to store knowledge of
;; how to mount it so that we can restore the mount after doing the
;; moves, so that installing an EFI bootloader is possible. The user
;; is responsible for adding an entry for the EFI system partition to
;; the new system's fstab, but we are responsible for restoring
;; knowledge of the partition to the kernel's mount table.
(when (remote-mount-point-p "/boot/efi")
(destructuring-bind (type source options)
(words (stripln (run "findmnt" "-nro" "FSTYPE,SOURCE,OPTIONS"
"/boot/efi")))
(setq efi-system-partition-mount-args
`("-t" ,type "-o" ,options ,source "/boot/efi"))))
;; /run is tricky because we want to retain the contents of the tmpfs
;; mounted there until reboot, for similar reasons to wanting to retain
;; /tmp, but unlike /tmp, /proc and /sys, a freshly debootstrapped
;; system contains a few things under /run and we would like to move
;; these out of /new-os. So we temporarily relocate the /run mount.
;;
;; If this causes problems we could reconsider -- there's usually a
;; tmpfs mounted at /run, so those files underneath might not matter.
(mrun "mount" "--make-private" "/")
(system "mount" "--move" "/run" (ensure-directories-exist "/old-run/"))
;; We are not killing any processes, so lazily unmount everything
;; before trying to perform any renames. (Present structure of this
;; loop assumes that each member of PRESERVED-DIRECTORIES is directly
;; under '/'.)
;;
;; We use system(3) to mount and unmount because once we unmount /dev,
;; there may not be /dev/null anymore, depending on whether the root
;; filesystems of the old and new OSs statically contain the basic /dev
;; entries or not, and at least on SBCL on Debian UIOP:RUN-PROGRAM
;; wants to open /dev/null when executing a command with no input.
;; Another option would be to pass an empty string as input.
(loop with sorted = (cdr (mount:all-mounts)) ; drop '/' itself
as next = (pop sorted)
while next
do (loop while (subpathp (car sorted) next) do (pop sorted))
unless (preservedp next)
do (system "umount" "--recursive" "--lazy" next))
(let (done)
(handler-case
(flet ((rename (s d) (rename-file s d) (push (cons s d) done)))
(dolist (file (local-directory-contents #P"/"))
(unless (or (preservedp file)
(pathname-equal file new-os)
(pathname-equal file old-os))
(rename file (chroot-pathname file old-os))))
(dolist (file (local-directory-contents new-os))
(let ((dest (in-chroot-pathname file new-os)))
(unless (preservedp dest)
(when (or (file-exists-p dest) (directory-exists-p dest))
(failed-change
"~A already exists in root directory." dest))
(rename file dest)))))
(serious-condition (c)
;; Make a single attempt to undo the moves to increase the chance
;; we can fix things and try again.
(loop for (source . dest) in done do (rename-file dest source))
(signal c))))
(delete-directory-tree new-os :validate t)
;; Restore /run and any submounts, like /run/lock.
(system "mount" "--move" "/old-run" "/run")
(delete-empty-directory "/old-run")
;; For the freshly bootstrapped OS let's assume that HOME is /root and
;; XDG_CACHE_HOME is /root/.cache; we do want to try to read the old
;; OS's actual XDG_CACHE_HOME. Move cache & update environment.
(let ((source
(chroot-pathname
(merge-pathnames
"consfigurator/" (get-connattr :XDG_CACHE_HOME))
old-os)))
(when (directory-exists-p source)
(rename-file source (ensure-directories-exist
#P"/root/.cache/consfigurator/"))))
(setf (get-connattr :remote-user) "root"
(get-connattr :remote-home) #P"/root/"
(get-connattr :XDG_CACHE_HOME) #P"/root/.cache/"
(get-connattr :consfigurator-cache) #P"/root/.cache/consfigurator/")
(posix-login-environment 0 "root" "/root")
;; Remount (mainly virtual) filesystems that other properties we will
;; apply might require (esp. relevant for installing bootloaders).
(dolist (mount mount:+linux-basic-vfs+)
(unless (preservedp (ensure-directory-pathname (lastcar mount)))
(apply #'system "mount" mount)))
(when efi-system-partition-mount-args
(ensure-directories-exist #P"/boot/efi/")
(apply #'mrun "mount" efi-system-partition-mount-args))))))
(defproplist %cleanly-installed-once :lisp
(options original-os
&aux
(new (make-host :hostattrs `(:os ,(get-hostattrs :os))))
(original-host
(make-host
:propspec
(make-propspec
:propspec
`(eseqprops
,(or original-os '(os:linux))
(chroot:os-bootstrapped-for ,options "/new-os" ,new))))))
(with-flagfile "/etc/consfigurator/os-cleanly-installed"
(deploys :local original-host)
(%root-filesystems-flipped "/new-os" "/old-os")
;; Prevent boot issues caused by disabled shadow passwords.
(cmd:single "shadowconfig" "on")))
(defproplist cleanly-installed-once :lisp (&optional options original-os)
"Replaces whatever operating system the host has with a clean installation of
the OS that the host is meant to have, and reboot, once. This is intended for
freshly launched machines in faraway datacentres, where your provider has
installed some operating system image to get you started, but you'd like have
a greater degree of control over the contents and configuration of the
machine. For example, this can help you ensure that the operation of the host
does not implicitly depend upon configuration present in the provider's image
but not captured by your consfig. This property's approach can fail and leave
the system unbootable, but it's an time-efficient way to ensure that you're
starting from a truly clean slate for those cases in which it works.
OPTIONS will be passed on to CHROOT:OS-BOOTSTRAPPED-FOR, which see.
ORIGINAL-OS, if supplied, is a propapp specifying the old OS, as you would
apply to a host with that OS.
The internal property CHROOT::%OS-BOOTSTRAPPER-INSTALLED will attempt to
install the OS bootstrapper (e.g. debootstrap(8) for Debian). If ORIGINAL-OS
is supplied then installation will use a package manager property for that OS.
Otherwise, CHROOT::%OS-BOOTSTRAPPER-INSTALLED will fall back to trying
PACKAGE:INSTALLED. Alternatively, you can install the bootstrapper manually
before running Consfigurator and not supply ORIGINAL-OS. This is useful for
original OSs whose package managers Consfigurator doesn't yet know how to
drive. You might apply an OS-agnostic property before this one which manually
downloads the bootstrapper and puts it on PATH.
The files from the old OS will be left in '/old-os'. Typically you will need
to perform some additional configuration before rebooting to increase the
likelihood that the system boots and is network-accessible. This might
require copying information from '/old-os' and/or the kernel's state before
the reboot. Some of this will need to be attached to the application of this
property using ON-CHANGE, whereas other fixes can just be applied subsequent
to this property. Here are two examples. If you already know the machine's
network configuration you might use
(os:debian-stable \"bullseye\" :amd64)
(installer:cleanly-installed-once ...)
(network:static \"ens3\" \"1.2.3.4\" ...)
(file:has-content \"/etc/resolv.conf\" ...)
whereas if you don't have that information, you would want something like
(os:debian-stable \"bullseye\" :amd64)
(on-change (installer:cleanly-installed-once ...)
(file:is-copy-of \"/etc/resolv.conf\" \"/old-os/etc/resolv.conf\"))
(network:preserve-static-once)
You will probably need to install a kernel, bootloader, sshd etc. in the list
of properties subsequent to this one. A more complete example, using the
combinator INSTALLER:WITH-CLEANLY-INSTALLED-ONCE, which see:
(os:debian-stable \"bullseye\" :amd64)
(disk:has-volumes
(physical-disk
:device-file #P\"/dev/sda\"
:boots-with '(grub:grub :target \"x86_64-efi\")))
(installer:with-cleanly-installed-once
(nil '(os:debian-stable \"buster\" :amd64))
:post-install
;; Clear out the old OS's EFI system partition contents.
(file:directory-does-not-exist \"/boot/efi/EFI\")
(apt:installed \"linux-image-amd64\")
(installer:bootloaders-installed)
(fstab:has-entries-for-volumes
(disk:volumes
(mounted-ext4-filesystem :mount-point #P\"/\")
(partition
(mounted-fat32-filesystem :mount-point #P\"/boot/efi/\"))))
(file:is-copy-of \"/etc/resolv.conf\" \"/old-os/etc/resolv.conf\")
(mount:unmounted-below-and-removed \"/old-os\")
:always
(network:static ...)
(sshd:installed)
(swap:has-swap-file \"2G\"))
Here are some other propapps you might want in the :POST-INSTALL list:
(bootloaders-installed)
(fstab:has-entries-for-volumes
(disk:volumes
(mounted-ext4-filesystem :mount-point #P\"/\")
(partition (mounted-fat32-filesystem :mount-point #P\"/boot/efi/\"))))
(file:is-copy-of \"/root/.ssh/authorized_keys\"
\"/old-os/root/.ssh/authorized_keys\")
(mount:unmounted-below-and-removed \"/old-os\")
If the system is not freshly provisioned, you couldn't easily recover from the
system becoming unbootable, or you have physical access to the machine, it is
probably better to use Consfigurator to build a disk image, or boot into a
live system and use Consfigurator to install to the host's usual storage."
(:desc "OS cleanly installed once")
(:hostattrs (os:required 'os:linux))
(on-change (%cleanly-installed-once options original-os) (reboot:at-end)))
(defmacro with-cleanly-installed-once
((&optional options original-os) &body propapps)
"Apply INSTALLER:CLEANLY-INSTALLED-ONCE, passing along OPTIONS and
ORIGINAL-OS, and attach to that application, using other property combinators,
the application of PROPAPPS.
PROPAPPS is a concatenation of three lists of propapps delimited by keywords:
'(:post-install
(propapp1) (propapp2) ...
:always
(propapp3) (propapp4) ...
:post-first-reboot
(propapp5) (propapp6) ...)
Any of the keywords and their propapps may be absent, but the three lists must
appear in this order. The :POST-INSTALL propapps are applied only if this
deployment performed the clean reinstallation, right after that. The :ALWAYS
propapps are applied next, whether or not this deployment performed the clean
reinstallation. Finally, the :POST-FIRST-REBOOT propapps are applied, only if
this deployment did not perform the clean reinstallation.
This mechanism handles common usages of INSTALLER:CLEANLY-INSTALLED-ONCE. For
example:
(installer:with-cleanly-installed-once (...)
:post-install
(installer:bootloaders-installed)
(file:is-copy-of \"/etc/resolv.conf\" \"/old-os/etc/resolv.conf\")
(mount:unmounted-below-and-removed \"/old-os\")
:always
(apt:installed \"openssh-server\")
(ssh:authorized-keys ...)
(network:static \"enp1s0\" ...)
:post-first-reboot
(my-cool-web-service)
(apache:https-vhost ...))
Properties that should be applied only once, or that rely on accessing files
from /old-os, are applied under :POST-INSTALL. Networking and shell access
are established before the first reboot, so we don't lock ourselves out.
However, as these properties are part of the usual definition of the host,
they go under :ALWAYS, not :POST-INSTALL, so that Consfigurator checks they
are still applied each deployment. Finally, we defer setting up the host's
sites and services until after the first reboot, in case there are any
problems setting those up when it's still the old OS's kernel that's running."
`(with-cleanly-installed-once*
(%cleanly-installed-once ,options ,original-os) ,@propapps))
(define-function-property-combinator with-cleanly-installed-once*
(cleanly-installed-once-propapp &rest propapps)
(let* ((post-first-reboot (member :post-first-reboot propapps))
(always-kw (member :always propapps))
(always (ldiff always-kw post-first-reboot))
(post-install (ldiff (member :post-install propapps)
(or always-kw post-first-reboot)))
(post-install (apply #'eseqprops (cdr post-install)))
(always-before (apply #'eseqprops (cdr always)))
;; Use SEQPROPS like DEFHOST does.
(always-after (apply #'seqprops (cdr always)))
(post-first-reboot (apply #'seqprops (cdr post-first-reboot))))
(:retprop :type :lisp
:hostattrs (lambda-ignoring-args
(propapp-attrs cleanly-installed-once-propapp)
(propapp-attrs post-install)
(propapp-attrs always-after)
(propapp-attrs post-first-reboot))
:apply (lambda-ignoring-args
(case (apply-propapp cleanly-installed-once-propapp)
(:no-change
(prog-changes
(add-change (apply-propapp always-after))
(add-change (apply-propapp post-first-reboot))))
(t
(apply-propapp post-install)
(apply-propapp always-before)
(reboot:at-end)
nil))))))
| 25,081 | Common Lisp | .lisp | 453 | 47.165563 | 81 | 0.672624 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | f9f4cad3b6a6860ee452f8cbd47b1e58fa6df1bded93d4e3c193b0bf787eea41 | 3,956 | [
-1
] |
3,957 | swap.lisp | spwhitton_consfigurator/src/property/swap.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.swap)
(named-readtables:in-readtable :consfigurator)
(defprop %swapfile-exists :posix (size location)
(:check
(declare (ignore size))
(remote-exists-p location))
(:apply
(mrun #?"umask 077; fallocate -l ${size} ${(unix-namestring location)}")
(mrun "mkswap" location))
(:unapply
(declare (ignore size))
(mrun :may-fail "swapoff" location)
(delete-remote-trees location)))
(defproplist has-swap-file :posix (size &key (location #P"/var/lib/swapfile"))
"Add a swap file. SIZE is the -l argument to fallocate(1).
Current implementation assumes a non-CoW filesystem; see NOTES in swapon(8)."
(:desc #?"Has swapfile of size ${size}")
(:hostattrs (os:required 'os:linux))
(on-apply-change (%swapfile-exists size location)
(cmd:single "swapon" location))
(fstab:has-entries
(strcat (unix-namestring location) " swap swap defaults 0 0")))
| 1,683 | Common Lisp | .lisp | 34 | 47 | 78 | 0.735688 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | e1f4b3435a1903553cfbc1c5189dfe4bf21b9f9977f8085f66b1403774ee1711 | 3,957 | [
-1
] |
3,958 | gnupg.lisp | spwhitton_consfigurator/src/property/gnupg.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.gnupg)
(named-readtables:in-readtable :consfigurator)
(defprop %public-key-imported :posix (fingerprint)
(:desc #?"PGP public key ${fingerprint} imported")
(:preprocess
(list (remove #\Space fingerprint)))
(:hostattrs
(require-data "--pgp-pubkey" fingerprint))
(:apply
;; always do an import, in case we have a newer version of the key than
;; last time
(with-change-if-changes-file (".gnupg/pubring.kbx")
(mrun
:input (get-data-stream "--pgp-pubkey" fingerprint) "gpg" "--import"))))
(defprop %trusts-public-key :posix (fingerprint level)
(:desc #?"PGP public key ${fingerprint} trusted, level ${level}")
(:preprocess (list (remove #\Space fingerprint) level))
(:apply (with-change-if-changes-file (".gnupg/trustdb.gpg")
(mrun :input (format nil "~A:~A:~%" fingerprint level)
"gpg" "--import-ownertrust"))))
(defpropspec public-key-imported :posix (fingerprint &key trust-level)
"Import the PGP public key identified by FINGERPRINT to gpg's default keyring.
If TRUST-LEVEL, also ensure that the key is trusted at that level, an
integer."
(:desc
(if trust-level
#?"PGP public key ${fingerprint} imported and trusted, level ${trust-level}"
#?"PGP public key ${fingerprint} imported"))
(if trust-level
`(eseqprops (%public-key-imported ,fingerprint)
(%trusts-public-key ,fingerprint ,trust-level))
`(%public-key-imported ,fingerprint)))
(defprop secret-key-imported :posix (fingerprint)
(:desc #?"PGP secret key ${fingerprint} imported")
(:preprocess (list (remove #\Space fingerprint)))
(:hostattrs (require-data "--pgp-seckey" fingerprint))
(:check
;; Look for plain "sec" not, e.g., "sec#", which indicates the secret key
;; is not available.
(multiple-value-bind (out err exit)
(run :may-fail "gpg" "--list-secret-keys" fingerprint)
(declare (ignore err))
(and (zerop exit) (re:scan #?/^sec\s/ out))))
(:apply (mrun :input (get-data-stream "--pgp-seckey" fingerprint)
"gpg" "--batch" "--no-tty" "--import")))
| 2,895 | Common Lisp | .lisp | 57 | 46.561404 | 83 | 0.695652 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 538487fba26e6c2772128eeadd28a594ea2159b5378071d67be018babe118a6e | 3,958 | [
-1
] |
3,959 | lxc.lisp | spwhitton_consfigurator/src/property/lxc.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021, 2023 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.lxc)
(named-readtables:in-readtable :consfigurator)
;;;; Properties and combinators
(defproplist installed :posix ()
"Install the LXC userspace tools."
(:desc "LXC installed")
(os:etypecase
(debianlike (apt:installed "lxc"))))
(defmacro default-maps-params (uid-maps-param gid-maps-param)
`(setq ,uid-maps-param
(or ,uid-maps-param
(list (cons 0 (multiple-value-list
(get-ids-offset "/etc/subuid" user)))))
,gid-maps-param
(or ,gid-maps-param
(list (cons 0 (multiple-value-list
(get-ids-offset "/etc/subgid" user)))))))
(defprop user-container-started :posix (host &optional owner)
"Ensure the LXC unprivileged container for the host designated by HOST owned
by OWNER, defaulting to the current user, is started.
(I.e., if HOST is a string, ensure the container named HOST is started; if
HOST is a HOST value, start the container whose name is HOST's hostname.)"
(:desc #?"LXC container ${(get-hostname host)} started")
(:check (or (service:no-services-p) (user-container-active-p host owner)))
(:apply (lxc-cmd owner "lxc-unpriv-start" "-n" (get-hostname host))))
(defprop user-container-stopped :posix (host &optional owner)
"Ensure the LXC unprivileged container for the host designated by HOST owned
by OWNER, defaulting to the current user, is stopped."
(:desc #?"LXC container ${(get-hostname host)} stopped")
(:check (not (user-container-active-p host owner)))
(:apply (lxc-cmd owner "lxc-stop" "-n" (get-hostname host))))
(defmacro when-user-container-running ((host &key owner) &body propapps)
"Apply PROPAPPS only when the unprivileged LXC for the host designated by HOST
and owned by OWNER, defaulting to the current user, is already started."
`(when-user-container-running*
,host ,owner
,(if (cdr propapps) `(eseqprops ,@propapps) (car propapps))))
(define-function-property-combinator
when-user-container-running* (host owner propapp)
(macrolet ((check-running (form)
`(if (user-container-running-p host owner) ,form :no-change)))
(:retprop :type (propapp-type propapp)
:desc (get (car propapp) 'desc)
:hostattrs (get (car propapp) 'hostattrs)
:apply (lambda-ignoring-args
(check-running (apply-propapp propapp)))
:unapply (lambda-ignoring-args
(check-running (unapply-propapp propapp)))
:args (cdr propapp))))
(defproplist user-containers-autostart :posix (user)
"Install a systemd user unit for USER to autostart all LXC user containers
owned by that user which have lxc.start.auto turned on. Also ensures that
lingering is enabled for USER, so the user unit triggers at system boot.
A limitation of the current implementation is that it assumes XDG_CONFIG_HOME
is ~/.config."
(:desc #?"LXC autostart systemd user unit installed for ${user}")
(user:has-account user)
(systemd:lingering-enabled user)
(as user
(file:has-content ".config/systemd/user/lxc-autostart.service"
'("[Unit]"
"Description=\"lxc-autostart\""
"[Service]"
"Type=oneshot"
"Delegate=yes"
"ExecStart=/usr/bin/lxc-autostart"
"ExecStop=/usr/bin/lxc-autostart --shutdown"
"RemainAfterExit=yes"
"[Install]"
"WantedBy=default.target"))
(systemd:enabled "lxc-autostart" :user-instance t)))
(defprop usernet-veth-usable-by :posix
(user &optional (interface "lxcbr0") (count 10))
"Ensure that USER is allowed to attach up to COUNT unprivileged LXCs to the
LXC-managed bridge INTERFACE.
As a special case, INTERFACE may also be \"none\", which gives USER permission
to create veth pairs where the peer outside the container is not attached to
any bridge."
(:desc #?"${user} may attach LXC veth devices to ${interface}")
(:apply (file:map-remote-file-lines
"/etc/lxc/lxc-usernet"
(lambda (lines)
(loop with done
and want = (format nil "~A veth ~A ~D" user interface count)
and prefix = (strcat user " veth " interface)
for line in lines
if (string-prefix-p prefix line)
unless done collect want into accum and do (setq done t)
end
else collect line into accum
finally (return
(if done accum (nconc accum (list want)))))))))
(defprop %ids-shifted-for :lisp
(user directory uid-maps gid-maps
&optional
(rootfs
(merge-pathnames "rootfs/"
(ensure-directory-pathname directory))))
"Recursively shift the user and group ownership of ROOTFS according to
UID-MAPS and GID-MAPS and chown DIRECTORY to root's UID according to UID-MAPS.
Not idempotent! Also set the mode of DIRECTORY to 0770, as is standard for
unprivileged LXCs."
(:apply
(default-maps-params uid-maps gid-maps)
(let ((dir (ensure-directory-pathname directory))
(uidmap (reduce-id-maps uid-maps))
(gidmap (reduce-id-maps gid-maps)))
(handler-bind ((serious-condition
;; Don't leave a partially-shifted tree.
(lambda-ignoring-args (delete-remote-trees rootfs))))
(shift-ids rootfs uidmap gidmap))
;; Don't see how to pass (gid_t)-1 as the third argument via CFFI. Note
;; that gid_t is not guaranteed to be unsigned.
(nix:chown dir (funcall uidmap 0) (nix:stat-gid (nix:stat dir)))
(nix:chmod dir #o770))))
(defprop %container-config-populated :posix
(prelude-lines user uid-maps gid-maps directory autostart hostname
additional-lines)
(:apply
(default-maps-params uid-maps gid-maps)
(let ((uid-maps (loop for (inside outside count) in uid-maps
collect (format nil "lxc.idmap = u ~D ~D ~D"
inside outside count)))
(gid-maps (loop for (inside outside count) in gid-maps
collect (format nil "lxc.idmap = g ~D ~D ~D"
inside outside count)))
(rootfs
(strcat
"dir:"
(unix-namestring
(merge-pathnames
"rootfs"
(merge-pathnames directory (get-connattr :remote-home)))))))
(file:has-content (merge-pathnames "config" directory)
(append prelude-lines uid-maps gid-maps
(list (strcat "lxc.rootfs.path = " rootfs)
(strcat "lxc.start.auto = " (if autostart "1" "0"))
(strcat "lxc.uts.name = " hostname))
additional-lines)
:mode #o640))))
(defpropspec user-container-for :lisp
(options user host &optional additional-properties
&aux (host* (preprocess-host
(make-child-host
:hostattrs (hostattrs host)
:propspec (host-propspec
(union-propspec-into-host
host additional-properties))))))
"Build an unprivileged, non-system-wide LXC container for HOST.
Must be applied using a connection chain which grants root access, primarily
for the sake of bootstrapping the container's root filesystem. Once built,
however, the container will be launched by USER, which should be non-root.
If the container has already been bootstrapped and is running at the time this
property is applied, enter the container and apply all its properties.
OPTIONS is a plist of keyword parameters:
- :AUTOSTART -- Lisp boolean corresponding to lxc.start.auto in the
container's config file, and also determines whether applying this
property attempts to start the container. Defaults to nil. See also
LXC:USER-CONTAINERS-AUTOSTART.
- :PRELUDE-LINES -- additional lines to prepend to the container's
configuration file, before the lines generated by this property. See
lxc.container.conf(5). The default value is usually sufficient; if you
add lines, you will probably want to include the lines from the default
value too.
- :ADDITIONAL-LINES -- additional lines to append to the container's
configuration file, after the lines generated by this property. See
lxc.container.conf(5). In most cases you will need to include, at a
minimum, lines setting up a network interface for the container. The
default value serves as an example of a standard way to do this; if you
use them unmodified, you will also need to apply
LXC:USERNET-VETH-USABLE-BY for USER before this property.
- :UID-MAPS -- a list of the form (INSIDE OUTSIDE COUNT), or a list of such
lists, specifying the subordinate UIDs for the container's user namespace.
OUTSIDE is the beginning of a UID range, as seen from outside the
container, and INSIDE is the UID that OUTSIDE is mapped to, as seen from
inside the container. COUNT is the number of consecutive UIDs mapped.
This property will ensure that USER has permission to use that range of
UIDs by updating /etc/subuid if necessary.
As a special case, if NIL, instead use the first range of UIDs assigned to
USER in /etc/subuid, with a value of zero for INSIDE, and do not modify
/etc/subuid. (If you want to use the first range of UIDs assigned to USER
in /etc/subuid and also other ranges, you must specify them all explicitly
and cannot rely on this special case.)
It is usually sufficient not to specify this parameter, as distribution
scripts automatically add an entry to /etc/subuid for each regular user,
and most containers use a value of zero for INSIDE.
- :GID-MAPS -- as :UID-MAPS, but for GIDs and /etc/subgid.
- :CHROOT-OPTIONS -- passed on to CHROOT:OS-BOOTSTRAPPED-FOR, which see.
A limitation of the current implementation is that the root filesystem of the
container is always created under ~/.local/share/lxc/HOSTNAME where HOSTNAME
is the hostname of HOST, ignoring any configured XDG_DATA_HOME for USER.
Internally we use setns(2) to enter the container. See \"Connections which
use setns(2) to enter containers\" in the Consfigurator manual for security
implications."
(:desc #?"LXC container for ${(get-hostname host*)} configured")
;; Same hostname probably means that the container HOST inherited the
;; container host's hostname as one was not explicitly set; probably a
;; mistake.
(when (string= (get-hostname host*) (get-hostname))
(aborted-change "LXC container has same hostname as container host."))
(destructuring-bind
(&key chroot-options autostart uid-maps gid-maps
(prelude-lines '("lxc.include = /usr/share/lxc/config/common.conf"
"lxc.include = /usr/share/lxc/config/userns.conf"))
(additional-lines '("lxc.net.0.type = veth"
"lxc.net.0.flags = up"
"lxc.net.0.link = lxcbr0"))
&aux
(directory
(ensure-directory-pathname
(merge-pathnames (get-hostname host*) ".local/share/lxc/")))
(rootfs (merge-pathnames "rootfs/" directory))
(uid-maps (if (listp (car uid-maps)) uid-maps (list uid-maps)))
(uid-maps-lines
(loop for (inside outside count) in uid-maps
collect (format nil "~A:~D:~D" user outside count)))
(gid-maps (if (listp (car gid-maps)) gid-maps (list gid-maps)))
(gid-maps-lines
(loop for (inside outside count) in gid-maps
collect (format nil "~A:~D:~D" user outside count)))
(flagfile (merge-pathnames "rootfs.bootstrapped" directory)))
options
`(with-unapply
(installed)
(user:has-account ,user)
(systemd:lingering-enabled ,user) ; required for lxc-ls(1) to work at all
,@(and uid-maps-lines
`((desc ,#?"/etc/subuid has mappings for ${(get-hostname host*)}"
(file:contains-lines "/etc/subuid" ,@uid-maps-lines))))
,@(and gid-maps-lines
`((desc ,#?"/etc/subgid has mappings for ${(get-hostname host*)}"
(file:contains-lines "/etc/subgid" ,@gid-maps-lines))))
,(propapp (desc "Base directory for container exists"
(as user (file:directory-exists directory))))
(with-homedir (:user ,user)
(with-flagfile ,flagfile
;; It would be nice to branch here such that if we are about to
;; start up the container and enter it, just bootstrap a minimal
;; root filesystem, and only otherwise get all the other properties
;; applied before the ID shifting. I.e.
;;
;; (chroot:os-bootstrapped-for
;; ,chroot-options ,rootfs
;; ,@(if autostart
;; `(,(make-host :hostattrs
;; (list :os (get-hostattrs :os host*))))
;; `(,host ,additional-properties)))
;;
;; However, it might be that we need to apply the other properties
;; in order that the container is startable; for example, getting
;; systemd installed.
(chroot:os-bootstrapped-for
,chroot-options ,rootfs ,host ,additional-properties)
(%ids-shifted-for ,user ,directory ,uid-maps ,gid-maps)))
,(propapp
(desc "Container configuration file populated"
(as user
(%container-config-populated
prelude-lines user uid-maps gid-maps directory autostart
(car (split-string (get-hostname host*) :separator "."))
additional-lines))))
,@(and autostart `((user-container-started ,host ,user)))
(when-user-container-running (,host :owner ,user)
(deploys ((:lxc :owner ,user :name ,(get-hostname host*)))
,host ,additional-properties))
:unapply
(user-container-stopped ,host ,user)
,@(and uid-maps-lines
`((desc ,#?"/etc/subuid mappings for ${(get-hostname host*)} cleaned up"
(file:lacks-lines "/etc/subuid" ,@uid-maps-lines))))
,@(and gid-maps-lines
`((desc ,#?"/etc/subgid mappings for ${(get-hostname host*)} cleaned up"
(file:lacks-lines "/etc/subgid" ,@gid-maps-lines))))
(with-homedir (:user ,user)
(file:does-not-exist ,(merge-pathnames "config" directory))
(unapplied
(with-flagfile ,flagfile
(chroot:os-bootstrapped-for
,chroot-options ,rootfs ,host ,additional-properties)))
(file:empty-directory-does-not-exist ,directory)))))
(defproplist user-container :lisp (options user properties)
"Like LXC:USER-CONTAINER-FOR but define a new host using PROPERTIES."
(:desc "LXC container defined")
(user-container-for options user (make-host :propspec properties)))
;;;; Utility functions
(defun lxc-cmd (&optional owner &rest cmd-and-args)
(let* ((runuser
(and owner (not (string= owner (get-connattr :remote-user)))))
(uid (if runuser
(user:passwd-field 2 owner)
(get-connattr :remote-uid))))
(apply #'run :env `(:DBUS_SESSION_BUS_ADDRESS nil
:XDG_RUNTIME_DIR ,(format nil "/run/user/~D" uid))
(and runuser (list "runuser" "-u" owner "--")) cmd-and-args)))
(defun lxc-ls (&optional owner &rest args)
"Return the lines of output from lxc-ls(1) called with ARGS and for OWNER."
(lines (apply #'lxc-cmd owner "lxc-ls" "-1" args)))
(defun user-container-active-p (host &optional owner)
(and (not (service:no-services-p))
(memstr= (get-hostname host) (lxc-ls owner "--active"))))
(defun user-container-running-p (host &optional owner)
(and (not (service:no-services-p))
(memstr= (get-hostname host) (lxc-ls owner "--running"))))
| 16,926 | Common Lisp | .lisp | 315 | 44.67619 | 86 | 0.645142 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | cf52dd23f53d9a7580cb9dfebf2f8ee5e64912b5553a0906b134511f249906c0 | 3,959 | [
-1
] |
3,960 | pkgng.lisp | spwhitton_consfigurator/src/property/pkgng.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2024 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.pkgng)
(named-readtables:in-readtable :consfigurator)
;;;; FreeBSD's pkg(8)
(defun mrun-pkg (&rest args)
(let ((env '(:ASSUME_ALWAYS_YES "YES")))
(when (get-connattr 'updatedp)
(setq env (list* :REPO_AUTOUPDATE "NO" env)))
(apply #'mrun :env env "pkg" args)))
(defun get-installed-packages ()
(or (get-connattr 'installed-packages)
(setf (get-connattr 'installed-packages)
(mapcar #1~/^(\S+)-[^-]+?\s/ (lines (mrun-pkg "info" "-a"))))))
(defprop installed :posix (&rest packages)
"Ensure all of the pkg(8) packages PACKAGES are installed."
(:desc #?"pkg(8) installed @{packages}")
(:hostattrs (os:required 'os:freebsd))
(:check (subsetp packages (get-installed-packages) :test #'string=))
(:apply (mrun-pkg :inform "install" packages)
(setf (get-connattr 'updatedp) t
;; Reset Consfigurator's idea of what's installed, as we don't
;; know what additional dependencies were just installed.
(get-connattr 'installed-packages) nil)))
(defprop deleted :posix (&rest packages)
"Ensure all of the pkg(8) packages PACKAGES are removed."
(:desc #?"pkg(8) removed @{packages}")
(:hostattrs (os:required 'os:freebsd))
(:check (null (intersection packages (get-installed-packages)
:test #'string=)))
(:apply (mrun-pkg :inform "delete" packages)
(setf (get-connattr 'installed-packages)
(set-difference (get-connattr 'installed-packages) packages
:test #'string=))))
(defprop upgraded :posix ()
(:desc "pkg(8) upgraded")
(:hostattrs (os:required 'os:freebsd))
(:check (prog1 (zerop (mrun-pkg :for-exit "upgrade" "-q" "-n"))
(setf (get-connattr 'updatedp) t)))
(:apply (mrun-pkg :inform "upgrade")
;; Reset Consfigurator's idea of what's installed, as some packages
;; may have been removed.
(setf (get-connattr 'installed-packages) nil)))
(defprop autoremoved :posix ()
(:desc "pkg(8) removed automatically installed packages")
(:hostattrs (os:required 'os:freebsd))
(:check (null (lines (mrun-pkg "autoremove" "-q" "-n"))))
(:apply (mrun-pkg :inform "autoremove")
;; Reset Consfigurator's idea of what's installed, as we don't know
;; what was just removed.
(setf (get-connattr 'installed-packages) nil)))
(defprop cache-cleaned :posix ()
"Remove superseded & obsolete data from the local package cache."
(:desc "pkg(8) cache cleaned")
(:hostattrs (os:required 'os:freebsd))
(:apply (mrun-pkg "clean") :no-change))
(defprop cache-emptied :posix ()
"Completely empty the local package cache."
(:desc "pkg(8) cache emptied")
(:hostattrs (os:required 'os:freebsd))
(:apply (mrun-pkg "clean" "-a") :no-change))
| 3,616 | Common Lisp | .lisp | 71 | 45.422535 | 78 | 0.669216 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 133af91f250fe4b1487cf9f832abaf4558c13f4ac0d8934daa84e80ceaa6b9bd | 3,960 | [
-1
] |
3,961 | cron.lisp | spwhitton_consfigurator/src/property/cron.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.cron)
(named-readtables:in-readtable :consfigurator)
;;; A number of techniques here are from Propellor's Cron properties module.
(defpropspec system-job :posix (desc when user shell-command)
"Installs a cronjob running SHELL-COMMAND as USER to ``/etc/cron.*``.
DESC must be unique, as it will be used as a filename for a script. WHEN is
either :DAILY, WEEKLY, :MONTHLY or a string formatted according to crontab(5),
e.g. ``0 3 * * *``.
The output of the cronjob will be mailed only if the job exits nonzero."
(:desc #?"Cronned ${desc}")
(:hostattrs
;; /etc/cron.* is Debian-specific. Also, we rely on runuser(1), which is
;; Linux-specific. This is done because su(1) for non-interactive usage
;; has some pitfalls.
(os:required 'os:debianlike))
(let* ((times (not (keywordp when)))
(dir (ensure-directory-pathname
(strcat "/etc/cron." (if (keywordp when)
(string-downcase (symbol-name when))
"d"))))
(job (merge-pathnames (string-to-filename desc) dir))
(script (merge-pathnames (strcat (string-to-filename desc) "_cronjob")
#P"/usr/local/bin/"))
(script* (sh-escape script)))
`(with-unapply
(apt:service-installed-running "cron")
(apt:installed "moreutils")
(file:exists-with-content ,job
,`(,@(and (not times) '("#!/bin/sh" "" "set -e" ""))
"SHELL=/bin/sh"
"PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"
""
,@`(,(if times
#?"${when} ${user} chronic ${script*}"
(if (string= user "root")
(format nil "chronic ~A" script*)
(format nil "chronic runuser -u ~A -c ~A"
user script*)))))
,@(and (not times) '(:mode #o755)))
;; Using a separate script makes for more readable e-mail subject lines,
;; and also makes it easy to do a manual run of the job.
(file:exists-with-content ,script
,`("#!/bin/sh"
""
"set -e"
""
;; Use flock(1) to ensure that only one instance of the job is ever
;; running, no matter how long one run of the job takes.
,(format nil "flock -n ~A sh -c ~A"
(sh-escape job) (sh-escape shell-command)))
:mode #o755)
:unapply (file:does-not-exist ,job ,script))))
(defproplist nice-system-job :posix (desc when user shell-command)
"Like CRON:SYSTEM-JOB, but run the command niced and ioniced."
(:desc #?"Cronned ${desc}, niced and ioniced")
(system-job desc when user (format nil "nice ionice -c 3 sh -c ~A"
(sh-escape shell-command))))
(defproplist runs-consfigurator :lisp (when)
"Re-execute the most recent deployment that included an application of this
property, or of IMAGE-DUMPED with no arguments, using CRON:NICE-SYSTEM-JOB.
This can be useful to ensure that your system remains in a consistent state
between manual deployments, and to ensure the timely application of properties
modified by the PERIODIC:AT-MOST combinator.
For hosts to which this property is applied, mixing usage of DEPLOY and
DEPLOY-THESE (or HOSTDEPLOY and HOSTDEPLOY-THESE, etc.) can lead to some
inconsistent situations. For example, suppose you
(hostdeploy foo.example.org (additional-property))
and then later
(hostdeploy-these foo.example.org (unapplied (additional-property)).
As neither CRON:RUNS-CONFIGURATOR nor IMAGE-DUMPED with no arguments was
applied since ADDITIONAL-PROPERTY was unapplied, the executable invoked by the
CRON:RUNS-CONFIGURATOR cronjob will try to apply ADDITIONAL-PROPERTY again.
One straightforward way to reduce the incidence of this sort of problem would
be to refrain from using the ADDITIONAL-PROPERTIES argument to DEPLOY,
HOSTDEPLOY etc.
You may wish to apply this property within ESEQPROPS-UNTIL; see the docstring
of IMAGE-DUMPED."
(with-unapply
(image-dumped)
(nice-system-job
"consfigurator" when "root"
"${XDG_CACHE_HOME:-$HOME/.cache}/consfigurator/images/latest")
:unapply (unapplied (system-job "consfigurator" when "" ""))))
(defprop user-crontab-installed :posix (env &rest jobs)
"Set the contents of the current user's crontab. ENV is like the ENV argument
to RUN/MRUN, except that the environment variables will be set at the top of
the generated crontab. Each of JOBS is a line for the body of the crontab.
In both ENV and JOBS, the string \"$HOME\" is replaced with the remote home
directory."
;; We set the contents of the whole file rather than providing properties to
;; specify individual jobs, because then it is straightforward to
;; incrementally develop jobs without having to unapply old versions first.
(:desc "Crontab populated")
(:apply
(unless (member :path env)
(setq env
(list*
:path
(if (zerop (get-connattr :remote-uid))
"/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin"
"/usr/local/bin:/bin:/usr/bin")
env)))
(let* ((home (drop-trailing-slash
(unix-namestring (get-connattr :remote-home))))
(old (runlines :may-fail "crontab" "-l"))
(new
(mapcar
#~s/\$HOME/${home}/g
(nconc
(list "# Automatically updated by Consfigurator; do not edit" "")
(loop for (k v) on env by #'cddr
collect (strcat (string-upcase (symbol-name k)) "=" v))
(list "")
jobs))))
(if (tree-equal old new :test #'string=)
:no-change
(mrun :input (unlines new)
"crontab" "-u" (get-connattr :remote-user) "-")))))
| 6,686 | Common Lisp | .lisp | 130 | 43.507692 | 80 | 0.648363 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | b04d3a73a80e51942e5718339d5eb81385486739ed7f75ae790928d3cb82d8d4 | 3,961 | [
-1
] |
3,962 | grub.lisp | spwhitton_consfigurator/src/property/grub.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021-2022 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.grub)
(named-readtables:in-readtable :consfigurator)
(defmethod install-bootloader-propspec
((type (eql 'grub)) volume &rest args &key &allow-other-keys)
`(grub-installed ,volume ,@args))
(defmethod install-bootloader-binaries-propspec
((type (eql 'grub)) volume &key (target "i386-pc") &allow-other-keys)
`(os:etypecase
(debianlike
(apt:installed
"initramfs-tools"
,(eswitch (target :test #'string=)
("i386-pc" "grub-pc")
("x86_64-efi" "grub-efi-amd64")
("arm64-efi" "grub-efi-arm64"))))))
(defprop grub-installed :posix
(volume &key (target "i386-pc") force-extra-removable)
"Use grub-install(8) to install grub to VOLUME."
(:desc "GRUB installed")
(:apply
(let ((running-on-target (container:contained-p :efi-nvram)))
(assert-remote-euid-root)
(mrun :inform "update-initramfs" "-u")
(let ((os-prober (and (not running-on-target)
(remote-exists-p "/etc/grub.d/30_os-prober"))))
;; work around Debian bug #802717
(when os-prober (file:has-mode "/etc/grub.d/30_os-prober" #o644))
(mrun :inform "update-grub")
(when os-prober (file:has-mode "/etc/grub.d/30_os-prober" #o755)))
(mrun :inform "grub-install" (strcat "--target=" target)
(and (string-suffix-p target "-efi") (not running-on-target)
"--no-nvram")
(and force-extra-removable "--force-extra-removable")
(device-file volume)))))
| 2,318 | Common Lisp | .lisp | 46 | 44.478261 | 74 | 0.670053 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 80e1bc29ff2284480ef629f12ae2fcd301d2a774d4839830c7b3d39028c37ba4 | 3,962 | [
-1
] |
3,963 | timezone.lisp | spwhitton_consfigurator/src/property/timezone.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.timezone)
(named-readtables:in-readtable :consfigurator)
(defproplist configured :posix (timezone)
"Set the system timezone. TIMEZONE is a relative path under /usr/share/zoneinfo,
e.g. \"Europe/London\"."
(:hostattrs (push-hostattr 'timezone timezone))
(os:etypecase
(linux
(file:symlinked :from "/etc/localtime"
:to (merge-pathnames timezone #P"/usr/share/zoneinfo/"))))
(os:typecase
(os:debianlike
(on-change (file:has-content "/etc/timezone" (list timezone))
(apt:reconfigured "tzdata")))))
(defproplist configured-from-parent :posix ()
"Sets the system timezone to match the parent host's."
(configured (or (get-parent-hostattrs-car 'timezone)
(failed-change "Parent has no known timezone"))))
| 1,582 | Common Lisp | .lisp | 30 | 48.966667 | 83 | 0.730097 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 30f0b4a0a25ee1df13ce4cf794dda647362baeea09fa125542e315d12bf229be | 3,963 | [
-1
] |
3,964 | os.lisp | spwhitton_consfigurator/src/property/os.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021-2022, 2024 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.os)
(named-readtables:in-readtable :consfigurator)
;;;; Basic OS types
(defclass unixlike () ())
(defclass linux (unixlike) ())
(defprop linux :posix ()
(:desc "Host kernel is Linux")
(:hostattrs (push-hostattr :os (make-instance 'linux))))
(define-simple-print-object linux)
(defclass debianlike (linux) ())
(defclass debian (debianlike)
((architecture
:initarg :arch :reader debian-architecture
:documentation
"Keyword whose name is Debian's name for this architecture, e.g. :AMD64")
(suite :initarg :suite
:reader debian-suite
:initform (error "Must provide suite"))))
(define-simple-print-object debian)
(defclass debian-stable (debian) ())
(defprop debian-stable :posix (suite architecture)
(:desc
(declare (ignore architecture))
#?{Host is Debian "${suite}"})
(:hostattrs
(push-hostattr :os
(make-instance 'debian-stable
:arch architecture :suite suite))))
(defclass debian-testing (debian)
((suite :initform "testing")))
(defprop debian-testing :posix (architecture)
(:desc
(declare (ignore architecture))
"Host is Debian testing")
(:hostattrs
(push-hostattr :os
(make-instance 'debian-testing
:arch architecture))))
(defclass debian-unstable (debian)
((suite :initform "unstable")))
(defprop debian-unstable :posix (architecture)
(:desc
(declare (ignore architecture))
"Host is Debian unstable")
(:hostattrs
(push-hostattr :os
(make-instance 'debian-unstable
:arch architecture))))
(defclass debian-experimental (debian)
((suite :initform "experimental")))
(defmethod debian-architecture-string ((os debian))
"Return a string representing the architecture of OS as used by Debian."
(string-downcase (symbol-name (debian-architecture os))))
(defclass freebsd (unixlike)
((architecture
:initarg :arch :reader freebsd-architecture
:documentation
"Keyword whose name is FreeBSD's name for this architecture, e.g. :AMD64")))
(defclass freebsd-release (freebsd)
((version :initarg :version
:type string
:reader freebsd-version
:initform (error "Must provide version")
:documentation "The numeric part of the version, e.g. 14.1")))
(define-simple-print-object freebsd-release)
(defprop freebsd-release :posix (version architecture)
(:desc #?"Host runs FreeBSD ${version}-RELEASE")
(:hostattrs
(push-hostattr :os (make-instance 'freebsd-release
:arch architecture :version version))))
(defclass freebsd-devel (freebsd) ()
(:documentation
"An unreleased version of FreeBSD: -CURRENT, -STABLE, -ALPHA, -BETA etc."))
(define-simple-print-object freebsd-devel)
(defprop freebsd-devel :posix (architecture)
(:desc #?"Host runs development version of FreeBSD")
(:hostattrs
(push-hostattr :os (make-instance 'freebsd-devel :arch architecture))))
;;;; Property combinators
(defun cases-type (cases)
(combine-propapp-types (loop for pa in (cdr cases) by #'cddr collect pa)))
(defun case-host (host fn)
(funcall fn (if host (get-hostattrs-car :os host) (get-hostattrs-car :os))))
(defun case-choose (host cases reader pred &optional default)
(loop with slot = (case-host host reader)
for (case propapp) on cases by #'cddr
when (or (and default (eql case t))
(funcall pred slot case))
return propapp))
(defmacro define-host-case-combinators
(name ename reader pred convert-key error-control)
(with-gensyms (host cases key forms)
(let ((case* (symbolicate name 'case*))
(ecase* (symbolicate ename 'case*))
(flatten `(loop for (,key . ,forms) in ,cases
collect (funcall ,convert-key ,key)
collect (if (cdr ,forms)
`(eseqprops ,@,forms)
(car ,forms)))))
`(progn
(define-choosing-property-combinator ,case* (host &rest cases)
:type (cases-type cases)
:choose (case-choose host cases ,reader ,pred t))
(define-choosing-property-combinator ,ecase* (host &rest cases)
:type (cases-type cases)
:choose
(or (case-choose host cases ,reader ,pred)
(inapplicable-property ,error-control (case-host host ,reader))))
(defmacro ,(symbolicate name 'case) (&body ,cases)
`(,',case* nil ,@,flatten))
(defmacro ,(symbolicate ename 'case) (&body ,cases)
`(,',ecase* nil ,@,flatten))
(defmacro ,(symbolicate 'host- name 'case) (,host &body ,cases)
`(,',case* ,,host ,@,flatten))
(defmacro ,(symbolicate 'host- ename 'case) (,host &body ,cases)
`(,',ecase* ,,host ,@,flatten))))))
(define-host-case-combinators type etype
#'class-of #'subtypep
(lambda (key)
`',(intern (symbol-name key)
(find-package :consfigurator.property.os)))
"Host's OS ~S fell through OS:ETYPECASE.")
(define-host-case-combinators debian-suite- debian-suite-e
#'debian-suite #'string= #'identity
"Host's Debian suite ~S fell through OS:DEBIAN-SUITE-ECASE.")
;;;; Utilities
(defun required (type)
"Error out if the OS of the host being deployed is not of type TYPE.
Used in property :HOSTATTRS subroutines."
(let ((os (class-of (get-hostattrs-car :os))))
(unless (and os (subtypep os type))
(inapplicable-property #?"Property requires OS of type ${type}"))))
(defgeneric supports-arch-p (target-os binary-os)
(:documentation "Can binaries for BINARY-OS run on TARGET-OS?"))
(defmethod supports-arch-p ((target-os debian) (binary-os debian))
(let ((target (debian-architecture target-os))
(binary (debian-architecture binary-os)))
(or (eq target binary)
(member binary (assoc target '((:amd64 :i386)
(:i386 :amd64)))))))
| 6,870 | Common Lisp | .lisp | 152 | 38.282895 | 80 | 0.65857 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | a8d57d1e9764a93d3c429d149325d44187c795d8a63b5b3153e2c45a06de9ec4 | 3,964 | [
-1
] |
3,965 | periodic.lisp | spwhitton_consfigurator/src/property/periodic.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.periodic)
(named-readtables:in-readtable :consfigurator)
;; Use of this combinator requires always supplying a description, to reduce
;; the chance of accidental description clashes.
(defmacro at-most (period desc &body propapps)
"Only attempt to apply PROPAPPS at most every PERIOD. Supported values for
PERIOD are :each-reboot, :hourly, :daily, :weekly, :monthly, :yearly. It is
assumed that a month has 30 days and a year has 365.25 days.
The purpose of this combinator is to avoid applying properties that are
expensive to apply more often than it is useful to apply them. It is not for
scheduling tasks to occur at specific times or on specific days.
The application of PROPAPPS is tracked by creating a flagfile on the remote
with a name computed from DESC. The mtime of this file is examined to
determine whether PERIOD has passed and another attempt to apply PROPAPPS
should be made. Thus, you must ensure that DESC is unique among the
descriptions of all the properties that will be applied to this host as this
user."
`(at-most* ,period ,desc
,(if (cdr propapps) `(eseqprops ,@propapps) (car propapps))))
(define-function-property-combinator at-most* (period desc propapp)
(symbol-macrolet
((flagfile (merge-pathnames
(string-to-filename desc)
(merge-pathnames "at-most/"
(get-connattr :consfigurator-cache)))))
(destructuring-bind (psym . args) propapp
(:retprop :type (propapp-type propapp)
:desc (lambda-ignoring-args desc)
:hostattrs (get psym 'hostattrs)
:check
(lambda-ignoring-args
(let ((now (get-universal-time))
(mtime (nth-value 2 (remote-file-stats flagfile))))
(and
mtime
(case period
(:each-reboot (< (remote-last-reboot) mtime))
(:hourly (< now (+ #.(* 60 60) mtime)))
(:daily (< now (+ #.(* 24 60 60) mtime)))
(:weekly (< now (+ #.(* 7 24 60 60) mtime)))
(:monthly (< now (+ #.(* 30 24 60 60) mtime)))
(:yearly
(< now (+ #.(ceiling (* 365.25 24 60 60)) mtime)))))))
:apply (lambda-ignoring-args
(prog1 (apply-propapp propapp)
(file:containing-directory-exists flagfile)
(mrun "touch" flagfile)))
:args args))))
(defmacro reapplied-at-most (period desc &body propapps)
"Apply PROPAPPS; only every PERIOD, also unapply them before applying them.
This is useful to periodically redo the application of PROPAPPS.
For example, you can use this to occasionally completely rebuild a
CHROOT:OS-BOOTSTRAPPED chroot instead of only ever updating its contents.
PERIOD and DESC are as for PERIODIC:AT-MOST, which see."
(let ((propapp (if (cdr propapps) `(eseqprops ,@propapps) (car propapps))))
`(eseqprops (desc ,(format nil "Unapplied ~(~A~): ~A" period desc)
(at-most* ,period ,desc (unapplied ,propapp)))
(desc ,desc ,propapp))))
| 4,058 | Common Lisp | .lisp | 70 | 48.328571 | 78 | 0.644869 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | ee66e432dcd9a84548fdcb0ae9d9367e6776b9d463c05dd5ae00f20cf9002ac3 | 3,965 | [
-1
] |
3,966 | apache.lisp | spwhitton_consfigurator/src/property/apache.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021, 2024 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.apache)
(named-readtables:in-readtable :consfigurator)
(defproplist installed :posix ()
(:desc "Apache installed")
(os:etypecase
(debianlike (apt:installed "apache2"))))
(defproplist reloaded :posix ()
(:desc "Apache reloaded")
(service:reloaded "apache2"))
(defprop %mod-enabled :posix (name)
(:hostattrs (os:required 'os:debianlike))
(:check (zerop (mrun :for-exit "a2query" "-q" "-m" name)))
(:apply (mrun "a2enmod" "--quiet" name))
(:unapply (mrun "a2dismod" "--quiet" name)))
(defproplist mod-enabled :posix (name)
(:desc #?"Apache module ${name} enabled")
(installed)
(on-change (%mod-enabled name)
(reloaded)))
(defproplist conf-available :posix (name config)
(:desc #?"Apache conf ${name} available")
(file:exists-with-content
(merge-pathnames (strcat name ".conf") #P"/etc/apache2/conf-available/")
config))
(defprop %conf-enabled :posix (name)
(:hostattrs (os:required 'os:debianlike))
(:check (zerop (mrun :for-exit "a2query" "-q" "-c" name)))
(:apply (mrun "a2enconf" "--quiet" name))
(:unapply (mrun "a2disconf" "--quiet" name)))
(defpropspec conf-enabled :posix (name &optional config)
(:desc #?"Apache configuration ${name} enabled")
`(eseqprops
(installed)
(on-change ,(if config
`(eseqprops (conf-available ,name ,config)
(%conf-enabled ,name))
`(%conf-enabled ,name))
(reloaded))))
(defproplist site-available :posix (domain config)
(:desc #?"Apache site ${domain} available")
(file:exists-with-content
(merge-pathnames (strcat domain ".conf") #P"/etc/apache2/sites-available/")
config))
(defprop %site-enabled :posix (domain)
(:hostattrs (os:required 'os:debianlike))
(:check (zerop (mrun :for-exit "a2query" "-q" "-s" domain)))
(:apply (mrun "a2ensite" "--quiet" domain))
(:unapply (mrun "a2dissite" "--quiet" domain)))
(defpropspec site-enabled :posix (domain &optional config)
(:desc #?"Apache site ${domain} enabled")
`(eseqprops
(installed)
(on-change ,(if config
`(eseqprops (site-available ,domain ,config)
(%site-enabled ,domain))
`(%site-enabled ,domain))
(reloaded))))
(defpropspec https-vhost :posix
(domain htdocs agree-tos
&key aliases additional-config additional-config-https)
"Configure an HTTPS Apache virtual host using a Let's Encrypt certificate.
ALIASES are the values for ServerAlias entries; these must be specified
separately for proper handling of the redirects from HTTP to HTTPS. Use of
this property implies agreement with the Let's Encrypt Subscriber Agreement;
AGREE-TOS is an instance of LETS-ENCRYPT:AGREE-TOS. ADDITIONAL-CONFIG are
additional lines to add to the Apache configuration for both the HTTP and
HTTPS virtual hosts; ADDITIONAL-CONFIG-HTTPS are additional lines to be added
only to the HTTPS virtual host.
Unapplying removes the Apache site config but leaves the certificate behind.
The current implementation does not install a certificate renewal hook to
restart Apache."
`(with-unapply
(network:aliases ,domain ,@aliases)
(mod-enabled "ssl")
(conf-enabled "stapling"
("SSLStaplingCache shmcb:/tmp/stapling_cache(128000)"))
(mod-enabled "rewrite")
(site-enabled
,domain
,(let ((initial `(,(strcat "DocumentRoot " htdocs)
"ErrorLog /var/log/apache2/error.log"
"LogLevel warn"
"CustomLog /var/log/apache2/access.log combined"
"ServerSignature on")))
`(,(strcat "<IfFile " (unix-namestring
(lets-encrypt:certificate-for domain))
">")
"<VirtualHost *:443>"
,(strcat "ServerName " domain ":443")
,@(loop for alias in aliases collect (strcat "ServerAlias " alias))
,@initial
"SSLEngine on"
,(strcat "SSLCertificateFile "
(unix-namestring (lets-encrypt:certificate-for domain)))
,(strcat "SSLCertificateKeyFile "
(unix-namestring (lets-encrypt:privkey-for domain)))
,(strcat "SSLCertificateChainFile "
(unix-namestring (lets-encrypt:chain-for domain)))
"SSLUseStapling on"
,@additional-config
,@additional-config-https
"</VirtualHost>" "</IfFile>"
,@(loop for name in (cons domain aliases) append
`(""
"<VirtualHost *:80>"
,(strcat "ServerName " name ":80")
,@initial
"RewriteEngine On"
"RewriteRule ^/.well-known/acme-challenge.* - [L]"
,(format nil "<Directory ~A>"
(unix-namestring
(merge-pathnames
#P".well-known/acme-challenge/"
(ensure-directory-pathname htdocs))))
"Require all granted"
"</Directory>"
,@additional-config
;; redirect everything else to https
"RewriteRule (.*) https://%{SERVER_NAME}$1 [R=301,L,NE]"
"</VirtualHost>")))))
(on-change (lets-encrypt:certificate-obtained
,agree-tos ,htdocs ,domain ,@aliases)
(reloaded))
:unapply
(unapplied (site-enabled ,domain))
(unapplied (site-available ,domain ""))))
| 6,432 | Common Lisp | .lisp | 138 | 37.347826 | 78 | 0.619981 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | c67757d3fb42b9877c9f7c85ac49243d3d900047deec30d766da4ba9fe5f0028 | 3,966 | [
-1
] |
3,967 | systemd.lisp | spwhitton_consfigurator/src/property/systemd.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021-2022 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.systemd)
(named-readtables:in-readtable :consfigurator)
;;; Using systemctl(1), we cannot enable or disable user units unless the
;;; user's service manager is actually running, and using loginctl(1), we
;;; cannot enable or disable user lingering unless systemd is PID 1.
;;;
;;; Possibly we should manually create the symlinks in the former case, and
;;; touch and delete the file under /var/lib/systemd/linger in the latter
;;; case, so that more configuration is applicable to unbooted chroots.
;;; We might have a combinator which implies ':user-instance t' for any of the
;;; following properties it contains. The idea would be that within a
;;; sequence of properties you probably want to affect only either the system
;;; daemon or the user instance.
(defun systemctl (fn user &rest args &aux (args (cons "systemctl" args)))
(apply fn (if user (systemd-user-instance-args args) args)))
(defprop daemon-reloaded :posix (&key user-instance)
(:desc "Attempt to reload systemd manager configuration")
(:apply (if (service:no-services-p)
:no-change
(systemctl #'mrun user-instance "daemon-reload"))))
(defprop started :posix (service &key user-instance)
(:desc #?"systemd service ${service} started")
(:check
(or (service:no-services-p)
(zerop (systemctl #'mrun user-instance :for-exit "is-active" service))))
(:apply (systemctl #'mrun user-instance "start" service)))
(defprop stopped :posix (service &key user-instance)
(:desc #?"systemd service ${service} stopped")
(:check
(or (service:no-services-p)
(plusp (systemctl #'mrun user-instance :for-exit "is-active" service))))
(:apply (systemctl #'mrun user-instance "stop" service)))
(defprop restarted :posix (service &key user-instance)
(:desc #?"Attempt to restart systemd service ${service}")
(:apply (if (service:no-services-p)
:no-change
(systemctl #'mrun user-instance "restart" service))))
(defprop reloaded :posix (service &key user-instance)
(:desc #?"Attempt to reload systemd service ${service}")
(:apply (if (service:no-services-p)
:no-change
(systemctl #'mrun user-instance "reload" service))))
(defprop enabled :posix (service &key user-instance)
(:desc #?"systemd service ${service} enabled")
(:check
(or (and user-instance (service:no-services-p))
(zerop
(systemctl #'mrun user-instance :for-exit "is-enabled" service))))
(:apply (systemctl #'mrun user-instance "enable" service)))
(defprop disabled :posix (service &key user-instance)
(:desc #?"systemd service ${service} disabled")
(:check
(or
(and user-instance (service:no-services-p))
(let ((status
(stripln
(systemctl #'run user-instance :may-fail "is-enabled" service))))
(or (string-prefix-p "linked" status)
(string-prefix-p "masked" status)
(memstr= status '("static" "disabled" "generated" "transient" "indirect"))))))
(:apply (systemctl #'mrun user-instance "disable" service)))
(defprop masked :posix (service &key user-instance)
(:desc #?"systemd service ${service} masked")
(:check
(or (and user-instance (service:no-services-p))
(string-prefix-p
"masked"
(systemctl #'run user-instance :may-fail "is-enabled" service))))
(:apply (systemctl #'mrun user-instance "mask" service))
(:unapply (if (and user-instance (service:no-services-p))
:no-change
(systemctl #'mrun user-instance "unmask" service))))
(defprop lingering-enabled :posix (user)
(:desc #?"User lingering enable for ${user}")
(:check
(or (service:no-services-p)
;; 'loginctl show-user' fails if the user is neither logged in nor
;; lingering. There is no dedicated exit code for that, so just assume
;; lingering is not enabled if command exits nonzero.
(multiple-value-bind (out err exit)
(run :may-fail "loginctl" "show-user" user)
(declare (ignore err))
(and (zerop exit) (memstr= "Linger=yes" (lines out))))))
(:apply (mrun "loginctl" "enable-linger" user))
(:unapply (if (service:no-services-p)
:no-change
(mrun "loginctl" "disable-linger" user))))
| 5,065 | Common Lisp | .lisp | 99 | 46.070707 | 88 | 0.688826 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | d7774419adc15a16fc94a8f47ff4711f7bdabb6464e29ab232b4899615820785 | 3,967 | [
-1
] |
3,968 | postgres.lisp | spwhitton_consfigurator/src/property/postgres.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021-2022 David Bremner <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.postgres)
(named-readtables:in-readtable :consfigurator)
(defproplist installed :posix ()
"Ensure that postgresql and associated utilities are installed."
(:desc "postgresql and associated utilities installed")
(os:etypecase
(debianlike (apt:installed "postgresql" "postgresql-client"))))
(defprop superuser-is :posix (name)
"Record Postgres superuser"
(:desc "postgres superuser is ${name}")
(:hostattrs
(push-hostattr 'postgres-superuser name)))
(defprop %psql :posix (sql &key unless)
(:check
(declare (ignore sql))
(and
unless
(let ((result (string-trim '(#\Space #\Newline #\Tab #\Return)
(mrun "psql" "-t" "postgres" :input unless))))
(informat 4 "~&PSQL=> ~a" result)
;; this is case insensitive on purpose.
(string-equal "yes" result))))
(:apply
(declare (ignore unless))
(mrun :inform "psql" "postgres" :input sql)))
(defproplist %run-sql :posix (sql &key unless)
(installed)
(as (or (get-hostattrs-car 'postgres-superuser) "postgres")
(%psql sql :unless unless)))
(defproplist has-role :posix (role)
"Ensure ROLE exists in the Postgres cluster."
(:desc #?"Postgres role ${role} exists")
(%run-sql
#?"DO $$
BEGIN
CREATE ROLE ${role};
EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping',
SQLERRM USING ERRCODE = SQLSTATE;
END
$$;"
:unless #?"select 'yes' from pg_roles where rolname='${role}';"))
(defproplist has-database :posix (db-name)
"Ensure Postgres DATABASE exists"
(:desc #?"Postgres database ${db-name} exists")
;; this has a potential race condition between test and creation
(%run-sql
#?"CREATE DATABASE ${db-name};"
:unless #?"SELECT 'yes' FROM pg_database WHERE datname = '${db-name}';"))
(defproplist database-has-owner :posix (database owner)
(:desc #?"Postgres database ${database} has owner ${owner}")
(%run-sql #?"ALTER DATABASE ${database} OWNER TO ${owner}"
:unless #?"select 'yes' from pg_database d, pg_authid a
where d.datname='${database}' and d.datdba = a.oid
and a.rolname='${owner}';"))
(defproplist has-group :posix (user group)
"Ensure Postgres user USER is a member of GROUP."
(:desc #?"Postgres role ${user} is a member of group ${group}")
(%run-sql #?"ALTER GROUP ${group} ADD USER ${user}"
:unless #?"select 'yes' from pg_auth_members m, pg_authid u, pg_authid g
where u.rolname='${user}' and g.rolname='${group}'
and m.member=u.oid and m.roleid=g.oid;"))
(defproplist user-can-login :posix (user)
"Ensure USER can login to Postgres."
(:desc #?"Postgres role ${user} can login to database")
(%run-sql #?"ALTER USER ${user} WITH LOGIN;"
:unless #?"select 'yes' from pg_authid where rolname='${user}' and rolcanlogin=true;"))
| 3,703 | Common Lisp | .lisp | 78 | 42.320513 | 99 | 0.670451 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 9c4f06260c3a51c595c59a7c3ee1b8221fa10fb8713e54d4e63fbf4d65b42058 | 3,968 | [
-1
] |
3,969 | chroot.lisp | spwhitton_consfigurator/src/property/chroot.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021-2022 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.chroot)
(named-readtables:in-readtable :consfigurator)
(defprop %debootstrapped :posix (root host &rest options)
"Bootstrap The Universal Operating System into ROOT using debootstrap(1)."
(:check
(declare (ignore options host))
;; check whether a previous debootstrap failed partway through
(if (remote-test "-d" (merge-pathnames "debootstrap/"
(ensure-directory-pathname root)))
(progn (empty-remote-directory root) nil)
(remote-exists-p (chroot-pathname "/usr/lib/os-release" root))))
(:apply
(destructuring-bind
(&key (apt.proxy (get-hostattrs-car :apt.proxy host))
(apt.mirror (get-hostattrs-car :apt.mirrors host))
&allow-other-keys
&aux (os (get-hostattrs-car :os host))
(args (list "debootstrap"
(plist-to-long-options
(remove-from-plist options :apt.proxy :apt.mirrors))
(strcat "--arch=" (os:debian-architecture-string os))
(os:debian-suite os)
root)))
options
;; In the case where the chroot arch is not equal to the host arch, we
;; could execute arch-test(1) here to confirm the architecture is
;; executable by the running kernel; we'd add arch-test alongside
;; qemu-user-static in %OS-BOOTSTRAPPER-INSTALLED. Or possibly we only
;; try to execute arch-test(1) when we find it's already on PATH.
(when apt.proxy
(setq args (list* :env (list :http_proxy apt.proxy) args)))
(when apt.mirror
(nconcf args (list apt.mirror)))
(apply #'run args))))
(defproplist %debootstrap-manually-installed :posix ()
;; Accept any debootstrap we find on path to enable installing Debian on
;; arbitrary unixes, where Consfigurator does not know how to install
;; packages, but the user has manually installed debootstrap(8).
(:check (remote-executable-find "debootstrap"))
(package:installed nil '(:apt ("debootstrap"))))
(defpropspec %os-bootstrapper-installed :posix (host)
(:desc "OS bootstrapper installed")
(let ((host (preprocess-host host)))
`(os:host-etypecase ,host
(debian
(os:typecase
(debianlike (apt:installed "debootstrap"))
(t (%debootstrap-manually-installed)))
;; Don't have an escape hatch like the :CHECK subroutine of
;; %DEBOOTSTRAP-MANUALLY-INSTALLED for the case where the
;; architectures do not match because ensuring that debootstrap(8)
;; will be able to bootstrap a foreign arch is more involved.
,@(and (compute-applicable-methods
#'os:supports-arch-p
(list (get-hostattrs-car :os) (get-hostattrs-car :os host)))
(not (os:supports-arch-p
(get-hostattrs-car :os) (get-hostattrs-car :os host)))
'((os:etypecase
(debianlike (apt:installed "qemu-user-static")))))))))
(defpropspec %os-bootstrapped :posix (options root host)
"Bootstrap OS into ROOT, e.g. with debootstrap(1)."
;; evaluate HOST once; can't use ONCE-ONLY because gensyms not serialisable
;; for sending to remote Lisp images
(:desc (declare (ignore options root host)) "OS bootstrapped")
(let ((host host))
`(os:host-etypecase ,host
(debian (%debootstrapped ,root ,host ,@options)))))
(defmethod %make-child-host ((host unpreprocessed-host))
(let ((propspec (host-propspec host)))
(make-child-host
:hostattrs (hostattrs host)
:propspec (make-propspec
:systems (propspec-systems propspec)
:propspec `(service:without-starting-services
(container:contained :filesystem)
,(propspec-props propspec))))))
(defproplist deploys :lisp (root host &optional additional-properties)
"Like DEPLOYS with first argument ```((:chroot :into ,root))``, but disable
starting services in the chroot, and set up access to parent hostattrs."
(:desc #?"Subdeployment of ${root}")
(consfigurator:deploys
`((:chroot :into ,root))
(%make-child-host (union-propspec-into-host host additional-properties))))
(defproplist deploys-these :lisp (root host properties)
"Like DEPLOYS-THESE with first argument ```((:chroot :into ,root))``, but
disable starting services in the chroot, and set up access to parent
hostattrs."
(:desc #?"Subdeployment of ${root}")
(consfigurator:deploys
`((:chroot :into ,root))
(%make-child-host
(replace-propspec-into-host (ensure-host host) properties))))
(defproplist os-bootstrapped-for :lisp
(options root host &optional additional-properties
&aux
(child-host (%make-child-host
(union-propspec-into-host host additional-properties)))
(child-host* (preprocess-host child-host)))
"Bootstrap an OS for HOST into ROOT and apply the properties of HOST.
OPTIONS is a plist of values to pass to the OS-specific bootstrapping property."
(:desc
(declare (ignore options))
#?"Built chroot for ${(get-hostname child-host*)} @ ${root}")
(with-unapply
(%os-bootstrapper-installed child-host*)
(%os-bootstrapped options root child-host*)
(consfigurator:deploys `((:chroot :into ,root)) child-host)
:unapply (mount:unmounted-below-and-removed root)))
(defproplist os-bootstrapped :lisp (options root properties)
"Bootstrap an OS into ROOT and apply PROPERTIES.
OPTIONS is a plist of values to pass to the OS-specific bootstrapping property."
(:desc (declare (ignore options properties))
#?"Built chroot @ ${root}")
(os-bootstrapped-for options root (make-host :propspec properties)))
| 6,531 | Common Lisp | .lisp | 126 | 44.746032 | 81 | 0.676945 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | de3ef63cf00e599bb9550bb562897da8143b0d257633f473c2043f9fc4160e79 | 3,969 | [
-1
] |
3,970 | schroot.lisp | spwhitton_consfigurator/src/property/schroot.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2016, 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.schroot)
(named-readtables:in-readtable :consfigurator)
(defproplist installed :posix ()
"Ensure that schroot(1) is installed."
(:desc "schroot(1) installed")
(os:etypecase
(debianlike (apt:installed "schroot"))))
(defprop uses-overlays :posix ()
"Indicate that schroots on a host should use 'union-type=overlay'.
Adding this property does not actually ensure that the line
'union-type=overlay' is present in any schroot config files. See SBUILD:BUILT
for example usage, via SCHROOT:OVERLAYS-IN-TMPFS."
(:desc "schroots on host use union-type=overlay")
(:hostattrs (push-hostattr 'uses-overlays t)))
(defprop overlays-in-tmpfs :posix ()
"Configure schroot(1) such that all schroots with 'union-type=overlay' in
their configuration will run their overlays in a tmpfs. Unapplicable, so if
the package you are working on FTBFS when overlays are in tmpfs, you can
toggle this off for a host, and then toggle it back on again later.
Implicitly sets SCHROOT:USES-OVERLAYS.
Shell script from <https://wiki.debian.org/sbuild>."
(:desc "schroot overlays in tmpfs")
(:hostattrs (push-hostattr 'uses-overlays t))
(:apply
(file:has-content "/etc/schroot/setup.d/04tmpfs" #>>~EOF>>
#!/bin/sh
set -e
. "$SETUP_DATA_DIR/common-data"
. "$SETUP_DATA_DIR/common-functions"
. "$SETUP_DATA_DIR/common-config"
if [ $STAGE = "setup-start" ]; then
mount -t tmpfs overlay /var/lib/schroot/union/overlay
elif [ $STAGE = "setup-recover" ]; then
mount -t tmpfs overlay /var/lib/schroot/union/overlay
elif [ $STAGE = "setup-stop" ]; then
umount -f /var/lib/schroot/union/overlay
fi
EOF :mode #o755))
(:unapply (file:does-not-exist "/etc/schroot/setup.d/04tmpfs")))
| 2,773 | Common Lisp | .lisp | 51 | 46.941176 | 78 | 0.675037 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 8279fe7b2b709fe5e2042ca313308bf1c646c0976f0ac29cbf89487003d6853b | 3,970 | [
-1
] |
3,971 | service.lisp | spwhitton_consfigurator/src/property/service.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.service)
(named-readtables:in-readtable :consfigurator)
;;;; Controlling services using service(1), and the :NO-SERVICES hostattr and
;;;; connattr. A host has the :NO-SERVICES hostattr when it has static
;;;; configuration never to start services. The connattr is for when we
;;;; should not start any services because we're doing something like
;;;; chrooting in to the host's unbooted root filesystem.
(define-constant +policyrcd+ #P"/usr/sbin/policy-rc.d" :test #'equal)
(defprop %no-services :posix ()
(:hostattrs
(push-hostattr :no-services t)))
(defprop %policy-rc.d :posix ()
(:apply
(assert-remote-euid-root)
(file:has-content +policyrcd+ '("#!/bin/sh" "exit 101"))
(file:has-mode +policyrcd+ #o755))
(:unapply
(assert-remote-euid-root)
(file:does-not-exist +policyrcd+)))
(defproplist no-services :posix ()
"Disable starting services with service(1) and by the package manager.
The implementation for Debian and Debian derivatives is currently very
simplistic, and will interact badly with any other properties which want to
use /usr/sbin/policy-rc.d. However, if for all other purposes you use systemd
configuration instead of editing /usr/sbin/policy-rc.d, this limitation should
not affect you."
(:desc #?"Starting services disabled")
(%no-services)
(os:etypecase
(debianlike (%policy-rc.d))))
(defun no-services-p ()
"Returns true if no services should be started by the current deployment."
(or (get-hostattrs-car :no-service) (get-connattr :no-services)))
(defun service (service action)
(unless (no-services-p)
(run :may-fail "service" service action)))
(defprop running :posix (service)
"Attempt to start service using service(1).
Assumes that if service(1) returns nonzero, it means the service was already
running. If something more robust is required, use init system-specific
properties."
(:desc #?"Attempt to start ${service} has been made")
(:apply
(service service "start")
;; assume it was already running
:no-change))
(defprop restarted :posix (service)
(:desc #?"Attempt to restart ${service}")
(:apply (service service "restart")))
(defprop reloaded :posix (service)
(:desc #?"Attempt to reload ${service}")
(:apply (service service "reload")))
(define-function-property-combinator without-starting-services (&rest propapps)
"Apply PROPAPPS with the :NO-SERVICES connattr temporarily in effect. Also
disable starting services by the package manager."
(let ((propapp (if (cdr propapps) (apply #'eseqprops propapps) (car propapps))))
(:retprop :type :lisp
:hostattrs (lambda ()
(propapp-attrs propapp)
(os:required 'os:debianlike))
:apply
(lambda (&aux (already-exists (file-exists-p +policyrcd+)))
(with-remote-temporary-file (temp :directory "/usr/sbin")
(when already-exists
(rename-file +policyrcd+ temp))
(%policy-rc.d)
(let ((before (get-universal-time)))
;; Sleep for one second so that we know BEFORE is in the
;; past. (SLEEP 1) is only approximately one second so
;; check that it's actually been a second.
(loop do (sleep 1) until (> (get-universal-time) before))
(unwind-protect (with-connattrs (:no-services t)
(apply-propapp propapp))
(if already-exists
;; Check whether some property we applied set the
;; contents of /usr/sbin/policy-rc.d, in which case
;; we won't restore our backup.
(unless (> (file-write-date +policyrcd+) before)
(rename-file temp +policyrcd+))
(when (file-exists-p +policyrcd+)
(delete-file +policyrcd+)))))))
:unapply (lambda () (unapply-propapp propapp)))))
| 4,874 | Common Lisp | .lisp | 94 | 44.021277 | 82 | 0.658828 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 49b8c8cd0b0885ebff56e02e36bf4e861ae761f202d614059b65dd930c824b59 | 3,971 | [
-1
] |
3,972 | mount.lisp | spwhitton_consfigurator/src/property/mount.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.mount)
(named-readtables:in-readtable :consfigurator)
(defprop mounted :posix (&key target)
"Ensures that TARGET, a mount point configured in /etc/fstab, is mounted.
Mainly useful as a dependency of properties which might do the wrong thing if
the mount is not actually active."
(:desc #?"${target} mounted")
(:hostattrs (os:required 'os:linux))
(:check (zerop (mrun :for-exit "findmnt" target)))
(:apply (assert-remote-euid-root)
(file:directory-exists target)
(mrun "mount" target)))
(defprop unmounted-below :posix (dir &key (and-at t))
"Unmount anything mounted below DIR, and when AND-AT, anything mounted at DIR.
Not aware of shared subtrees, so you might need to use the --make-rslave
option to mount(8) first. For example, if you did 'mount --rbind /dev
chroot/dev' then unless you also execute 'mount --make-rslave chroot/dev',
this property will empty /dev, breaking all kinds of things."
(:desc #?"${dir} unmounted")
(:hostattrs
;; findmnt(8) & --recursive argument to umount(8) are from util-linux
(os:required 'os:linux))
(:apply
(with-change-if-changes-file-content ("/proc/mounts")
;; We used to call --make-rslave as we worked through, but for mounts
;; which were *not* made using the --rbind option to mount(8) or similar,
;; doing that can can get us into a state where we can unmount everything
;; we can see under DIR but the kernel will still consider the block
;; device to be in use. That's a bit much for this property to deal
;; with, so we require that the caller call --make-rslave as appropriate.
;;
;; In addition to that problem, we would also require multiple unmount
;; passes; for example if we
;;
;; % mount --bind chroot chroot
;; % mount proc chroot/proc -t proc
;; % mount --make-rslave chroot
;;
;; then we would need
;;
;; % umount chroot/proc
;; % umount chroot
;; % umount chroot/proc
;;
;; because the --make-rslave leaves us with two independent mounts of
;; /proc, and the second can't be removed until the bind mount is
;; removed. (This situation arises because :CHROOT.FORK connections bind
;; mount the chroot on itself if it is not already a mount point.)
(loop with sorted
= (if and-at
(all-mounts dir)
(delete (ensure-directory-pathname dir) (all-mounts dir)
:test #'pathname-equal))
as next = (pop sorted)
while next
do (loop while (subpathp (car sorted) next) do (pop sorted))
(mrun "umount" "--recursive" next)))))
(defprop unmounted-below-and-removed :posix (dir)
"Unmount anything mounted below DIR, recursively delete the contents of DIR,
and unless DIR is itself a mount point, also remove DIR."
(:desc #?"${dir} unmounted below and emptied/removed")
(:hostattrs (os:required 'os:linux))
(:check (or (not (remote-exists-p dir))
(and (remote-mount-point-p dir)
(null (runlines "find" dir "-not" "-path" dir)))))
(:apply (ignoring-hostattrs (unmounted-below dir :and-at nil))
(if (remote-mount-point-p dir)
(empty-remote-directory dir)
(delete-remote-trees dir))))
(defun all-mounts (&optional (below #P"/"))
"Retrieve all mountpoints below BELOW, ordered lexicographically.
If BELOW is itself a mountpoint, it will be included as the first element.
Uses findmnt(8), so Linux-specific."
(let* ((below (ensure-directory-pathname below))
(all-mounts (mapcar #'ensure-directory-pathname
(runlines "findmnt" "-rn" "--output" "target")))
(mounts-below (remove-if-not (rcurry #'subpathp below) all-mounts)))
(sort mounts-below #'string< :key #'unix-namestring)))
;;;; Utilities for :LISP properties
(define-constant +linux-basic-vfs+ '(
("-t" "proc" "-o" "nosuid,noexec,nodev" "proc" "/proc")
("-t" "sysfs" "-o" "nosuid,noexec,nodev,ro" "sys" "/sys")
("-t" "devtmpfs" "-o" "mode=0755,nosuid" "udev" "/dev")
("-t" "devpts" "-o" "mode=0620,gid=5,nosuid,noexec" "devpts" "/dev/pts")
("-t" "tmpfs" "-o" "mode=1777,nosuid,nodev" "shm" "/dev/shm")
("-t" "tmpfs" "-o" "mode=1777,strictatime,nodev,nosuid" "tmp" "/tmp"))
:test #'equal)
(define-constant +linux-efivars-vfs+
'("-t" "efivarfs" "-o" "nosuid,noexec,nodev" "efivarfs"
"/sys/firmware/efi/efivars")
:documentation "Arguments to mount(8) to mount the UEFI NVRAM.
After mounting /sys, mount this when /sys/firmware/efi/efivars exists."
:test #'equal)
(defun assert-devtmpfs-udev-/dev ()
"On a system with the Linux kernel, assert that /dev has fstype devtmpfs."
(unless (and (remote-mount-point-p "/dev")
(string= "devtmpfs udev"
(stripln (run "findmnt" "-nro" "fstype,source" "/dev"))))
(failed-change
"/dev is not udev devtmpfs; support for other kinds of /dev unimplemented.")))
| 5,905 | Common Lisp | .lisp | 112 | 47.098214 | 83 | 0.657375 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | d949a572a8dd21444715a55cef0778aafdd95f785692ec9f1fa3f9d576f61899 | 3,972 | [
-1
] |
3,973 | ccache.lisp | spwhitton_consfigurator/src/property/ccache.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.property.ccache)
(named-readtables:in-readtable :consfigurator)
(defproplist installed :posix ()
(:desc "ccache installed")
(os:etypecase
(debianlike (apt:installed "ccache"))))
(defprop has-limits :posix (cache
&key (max-size nil max-size-supplied-p)
(max-files nil max-files-supplied-p))
"Set limits on a given ccache.
See ccache(1) for the format of MAX-SIZE."
(:desc (format nil "~A has max size ~D & max files ~D"
cache max-size max-files))
(:apply
(installed)
(with-change-if-changes-file-content
((merge-pathnames "ccache.conf" (ensure-directory-pathname cache)))
;; Let ccache(1) handle editing and deduplicating the config file, etc.
(mrun "ccache" :env `(:CCACHE_DIR ,cache)
(and max-size-supplied-p
(strcat "--max-size=" (or max-size "0")))
(and max-files-supplied-p
(strcat "--max-files=" (or max-files "0")))))))
(defpropspec cache-for-group :posix
(group &key (max-size nil max-size-supplied-p)
(max-files nil max-files-supplied-p)
&aux (dir (ensure-directory-pathname
(strcat "/var/cache/ccache-" group))))
"Configures a ccache in /var/cache for a group."
(:desc #?"ccache for group ${group} exists")
`(with-unapply
(installed)
(file:directory-exists ,dir)
(file:has-mode ,dir #o2775)
(file:has-ownership ,dir :user "root" :group ,group)
,@(and (or max-size-supplied-p max-files-supplied-p)
`((has-limits ,dir
,@(and max-size-supplied-p
`(:max-size ,max-size))
,@(and max-files-supplied-p
`(:max-files ,max-files)))))
:unapply (file:directory-does-not-exist ,dir)))
| 2,658 | Common Lisp | .lisp | 54 | 41.074074 | 76 | 0.635208 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 430b855bc1aae6615b679fb21141829b53f83c45979e32a4b7da1dfaf3b76c9c | 3,973 | [
-1
] |
3,974 | posix1e.lisp | spwhitton_consfigurator/src/util/posix1e.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.util.posix1e)
(named-readtables:in-readtable :consfigurator)
;;;; POSIX ACLs
(define-foreign-library libacl (:linux (:default "libacl")))
#+linux (use-foreign-library libacl)
(define-error-retval-cfun () "acl_free" :int (obj_p :pointer))
(define-error-retval-cfun (:failure-val (null-pointer))
"acl_get_file" :pointer (path-p :string) (type acl_type_t))
(define-error-retval-cfun ()
"acl_set_file" :int (path-p :string) (type acl_type_t) (acl :pointer))
(define-error-retval-cfun ()
"acl_get_entry" :int (acl :pointer) (entry-id :int) (entry-p :pointer))
(define-error-retval-cfun ()
("acl_get_tag_type" %acl-get-tag-type)
:int (entry-d acl_entry_t) (tag-type-p :pointer))
(defun acl-get-tag-type (entry-d)
(with-foreign-object (tag-type-p 'acl_tag_t)
(%acl-get-tag-type entry-d tag-type-p)
(mem-ref tag-type-p 'acl_tag_t)))
(defmacro with-acl-free (((aclvar aclcall)) &body forms)
(with-gensyms (aclvar*)
`(let* ((,aclvar ,aclcall)
(,aclvar* (make-pointer (pointer-address ,aclvar))))
(unwind-protect (progn ,@forms) (acl-free ,aclvar*)))))
(define-error-retval-cfun (:failure-val (null-pointer))
("acl_get_qualifier" %acl-get-qualifier) :pointer (entry-d acl_entry_t))
(define-error-retval-cfun ()
"acl_set_qualifier" :int (entry-d acl_entry_t) (qualifier-p :pointer))
(defun acl-get-qualifier (entry-d type)
(with-acl-free ((qualifier-p (%acl-get-qualifier entry-d)))
(mem-ref qualifier-p type)))
;;;; Capabilities
(define-foreign-library libcap (:linux (:default "libcap")))
#+linux
(progn
(use-foreign-library libcap)
(define-error-retval-cfun () "cap_free" :int (obj_d :pointer))
(define-error-retval-cfun (:failure-val (null-pointer))
"cap_get_proc" :pointer)
(define-error-retval-cfun ()
"cap_get_flag" :int
(cap-p :pointer) (cap cap_value_t) (flag cap_flag_t) (value-p :pointer))
(defun posix-capability-p (set &rest capabilities)
"Does the current thread have each of CAPABILITIES in SET?"
(let ((cap-opaque (cap-get-proc)))
(unwind-protect
(with-foreign-object (value-p 'cap_flag_value_t)
(loop for capability in capabilities
do (cap-get-flag cap-opaque capability set value-p)
always (eql :cap-set (mem-ref value-p 'cap_flag_value_t))))
(cap-free cap-opaque)))))
| 3,154 | Common Lisp | .lisp | 63 | 46.079365 | 78 | 0.69517 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 3fc540cc915bd528d2f7748986d6813e13d14089684adca3b1cd83298bbf56db | 3,974 | [
-1
] |
3,975 | linux-namespace.lisp | spwhitton_consfigurator/src/util/linux-namespace.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2021 Sean Whitton <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator.util.linux-namespace)
(named-readtables:in-readtable :consfigurator)
(defun get-ids-offset (file identifier)
"Where IDENTIFIER is a username or uid, and FILE is structured like
/etc/subuid and /etc/subuid (see subuid(5) and subgid(5)), return the
numerical subordinate ID and numerical subordinate ID count for the first
entry in FILE for IDENTIFIER."
(with-open-file (file file)
(loop with info = (user:user-info identifier)
with fields
= (list (cdr (assoc :name info))
(write-to-string (cdr (assoc :user-id info))))
for line = (read-line file)
for (field start count) = (split-string line :separator '(#\:))
when (memstr= field fields)
return (values (parse-integer start) (parse-integer count)))))
(defun reduce-id-maps (id-maps)
"Where each of ID-MAPS is a list of three integers corresponding to the lines
of the uid_map (resp. gid_map) of a process in a different user namespace as
would be read by a process in the current user namespace, return a function
which maps UIDs (resp. GIDs) in the current user namespace to UIDs
(resp. GIDs) in the user namespace of the process. The function returns NIL,
not 65534, for values which are unmapped.
A process's uid_map & gid_map files are under /proc; see user_namespaces(7)."
(let ((cache (make-hash-table))
(sorted (sort (copy-list id-maps) #'< :key #'car)))
(labels ((make-subtree (limit)
(and (plusp limit)
(let* ((new-limit (floor limit 2))
(left (make-subtree new-limit))
(next (pop sorted)))
(destructuring-bind (inside outside count) next
(let ((end (1- (+ inside count))))
(assert (and (every #'integerp next)
(not (minusp inside))
(not (minusp outside))
(plusp count))
nil "Invalid ID map ~S" next)
(assert
(or (not sorted) (> (caar sorted) end))
nil "ID maps overlap: ~S & ~S" next (car sorted))
(list inside end (- outside inside) left
(make-subtree (1- (- limit new-limit)))))))))
(tree-lookup (id tree)
(and tree
(destructuring-bind (start end offset left right) tree
(cond ((> id end) (tree-lookup id right))
((< id start) (tree-lookup id left))
(t (+ id offset))))))
;; Memoisation ought to be really worthwhile because we will
;; likely be looking up the same few IDs over and over (e.g. 0).
(cache-or-tree-lookup (id tree)
(multiple-value-bind (result found) (gethash id cache)
(if found
result
(setf (gethash id cache) (tree-lookup id tree))))))
(rcurry #'cache-or-tree-lookup (make-subtree (length sorted))))))
(defun shift-ids (root uidmap gidmap
&aux (seen (make-hash-table :test #'equal)))
"Recursively map the ownership and POSIX ACLs of files under ROOT by applying
the function UIDMAP to user ownership and UIDs appearing in ACLs, and the
function GIDMAP to group ownership and GIDs appearing in ACLs. Each of UIDMAP
and GIDMAP should return a non-negative integer or NIL for each non-negative
integer input; in the latter case, no update will be made to the UID or GID.
For example, to recursively shift the ownership and POSIX ACLs of a filesystem
hierarchy to render it suitable for use as a root filesystem in a different
user namespace, you might use
(shift-ids \"/var/lib/lxc/mycontainer/rootfs\"
(reduce-id-maps '(0 100000 65536))
(reduce-id-maps '(0 100000 65536)))
Here the list (0 100000 65536) describes the relationship between the present
user namespace and the container's user namespace; see the docstring for
CONSFIGURATOR.UTIL.LINUX-NAMESPACE:REDUCE-ID-MAPS and user_namespaces(7)."
(labels
((shift (file)
(let* ((file (drop-trailing-slash (unix-namestring file)))
(stat (nix:lstat file))
(pair (cons (nix:stat-dev stat) (nix:stat-ino stat)))
(uid (nix:stat-uid stat))
(gid (nix:stat-gid stat))
(mode (nix:stat-mode stat))
(dirp (nix:s-isdir mode))
(linkp (nix:s-islnk mode)))
(unless (gethash pair seen)
(setf (gethash pair seen) t)
(nix:lchown file
(or (funcall uidmap uid) uid)
(or (funcall gidmap gid) gid))
(unless linkp
;; Restore mode because chown wipes setuid/setgid.
(nix:chmod file mode)
;; Now do the ACL shifts; directories have two.
(shift-acl file ACL_TYPE_ACCESS)
(when dirp (shift-acl file ACL_TYPE_DEFAULT)))
(when (and dirp (not linkp))
(mapc #'shift (local-directory-contents file))))))
(shift-acl (file type)
(with-acl-free ((acl (acl-get-file file type)))
(with-foreign-objects
((uid 'uid_t) (gid 'gid_t) (entry-p 'acl_entry_t))
(loop with setp
for etype = ACL_FIRST_ENTRY then ACL_NEXT_ENTRY
while (plusp (acl-get-entry acl etype entry-p))
for entry = (mem-ref entry-p 'acl_entry_t)
for tag-type = (acl-get-tag-type entry)
when (= tag-type ACL_USER)
do (awhen
(funcall uidmap (acl-get-qualifier entry 'uid_t))
(setf setp t (mem-ref uid 'uid_t) it)
(acl-set-qualifier entry uid))
when (= tag-type ACL_GROUP)
do (awhen
(funcall gidmap (acl-get-qualifier entry 'gid_t))
(setf setp t (mem-ref gid 'gid_t) it)
(acl-set-qualifier entry gid))
finally (when setp (acl-set-file file type acl)))))))
(shift (ensure-directory-pathname root))))
#+linux
(defun get-userns-owner (fd)
(with-foreign-object (owner 'uid_t)
(if (minusp
(foreign-funcall
"ioctl" :int fd :unsigned-long NS_GET_OWNER_UID :pointer owner
:int))
(error "Couldn't determine owner of target userns.")
(mem-ref owner 'uid_t))))
(defun setgroups-p ()
"In a Lisp-type connection, do we have the ability to use setgroups(2)?"
(and #-linux (zerop (nix:geteuid))
#+linux (posix-capability-p :cap-effective CAP_SETGID)
#+linux (string= "allow"
(stripln
(read-file-string "/proc/thread-self/setgroups")))))
| 7,889 | Common Lisp | .lisp | 145 | 41.524138 | 79 | 0.580854 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 404fded5158c1501ae3d91386a57c82ddfaf15ae12bcf877c2c53a8333207a20 | 3,975 | [
-1
] |
3,976 | package.lisp | spwhitton_consfigurator/tests/package.lisp | (in-package :cl-user)
(defpackage :consfigurator/tests
(:use #:cl #:consfigurator #:consfigurator.data.util #:alexandria #:anaphora
#+sbcl :sb-rt #-sbcl :rtest)
(:local-nicknames (#:file #:consfigurator.property.file)
(#:data.pgp #:consfigurator.data.pgp)))
| 294 | Common Lisp | .lisp | 6 | 43.333333 | 78 | 0.651568 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 76661fe6f8d534a90467f12f8a2bc19073d9c7331a75256e529db668218d9c0d | 3,976 | [
-1
] |
3,977 | util.lisp | spwhitton_consfigurator/tests/util.lisp | (in-package :consfigurator/tests)
(named-readtables:in-readtable :consfigurator)
(in-consfig "consfigurator/tests")
(deftest multiple-value-mapcan.1
(multiple-value-mapcan
(lambda (car1 car2 car3)
(values (list car1 car2 car3) (list car3 car2 car1)))
'(1 2 3 4) '(1 2 3) '(5 4 3 2 1))
(1 1 5 2 2 4 3 3 3) (5 1 1 4 2 2 3 3 3))
(deftest multiple-value-mapcan.2
(multiple-value-mapcan #'list '(1 2 3 4 5))
(1 2 3 4 5))
(deftest multiple-value-mapcan.3
(let ((n 0))
(multiple-value-mapcan
(lambda (car1 car2 car3)
(if (> (incf n) 2)
(list car2)
(values (list car1 car2 car3) (list car3))))
'(1 2 3 4) '(1 2 3) '(5 4 3 2 1)))
(1 1 5 2 2 4 3) (5 4))
(deftest version<.1 (version< "1.0.1" "1.0.2") t)
(deftest version<=.1 (version<= "1.0.1" "1.0.2") t)
(deftest version<.2 (version< "1.0.1" "1.0.1") nil)
(deftest version<=.2 (version<= "1.0.1" "1.0.1") t)
(deftest version<.3 (version< "1.1" "1.0.1") nil)
(deftest version<=.3 (version<= "1.1" "1.0.1") nil)
(deftest version<.4 (version< "1.a.1" "1.1") t)
(deftest version<.5 (version< "1..1" "1.1") t)
;; without domain
(deftest valid-hostname-p.1 (valid-hostname-p "localhost") t)
(deftest valid-hostname-p.2 (valid-hostname-p "host.example.com") t)
;; case insensitive check
(deftest valid-hostname-p.3 (valid-hostname-p "host.Example.Com") t)
;; total length too long
(deftest valid-hostname-p.4
(valid-hostname-p (format nil "~127@{a.~}a" nil))
nil)
;; label too long
(deftest valid-hostname-p.5
(valid-hostname-p (format nil "~64@{a~}a" nil))
nil)
;; valid use of '-'
(deftest valid-hostname-p.6 (valid-hostname-p "host-name.example.com") t)
;; invalid use of '-'
(deftest valid-hostname-p.7 (valid-hostname-p "-hostname.example.com") nil)
;; invalid character
(deftest valid-hostname-p.8 (valid-hostname-p "_hostname.example.com") nil)
;; invalid character 2
(deftest valid-hostname-p.9 (valid-hostname-p "foo/bar") nil)
| 1,994 | Common Lisp | .lisp | 50 | 36.44 | 75 | 0.647089 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 3fd7823af397066578c97c0d4f225d8a2814dd88eab7523381a90b0a9e5eab03 | 3,977 | [
-1
] |
3,978 | runner.lisp | spwhitton_consfigurator/tests/runner.lisp | ;;; Consfigurator -- Lisp declarative configuration management system
;;; Copyright (C) 2022 David Bremner <[email protected]>
;;; This file 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, or (at your option)
;;; any later version.
;;; This file 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 this program. If not, see <https://www.gnu.org/licenses/>.
(in-package :consfigurator/tests)
(named-readtables:in-readtable :consfigurator)
(defparameter *test-gnupg-fingerprint* nil
"Fingerprint of trusted gpg key usable for encryption and signing.")
(defun first-gpg-fingerprint ()
"Return the fingerprint of the first (primary) key listed by gpg.
This is mainly useful when there is a single primary key."
(some
(lambda (line) (aand (strip-prefix "fpr:::::::::" line)
(string-trim ":" it)))
(lines (gpg '("--with-colons" "--list-keys")))))
(defun make-test-gnupghome ()
"Create and populate *DATA-SOURCE-GNUPGHOME* for tests."
(unless (nth-value 1 (ensure-directories-exist
*data-source-gnupghome* :mode #o700))
(error "~s already exists" *data-source-gnupghome*))
(gpg '("--batch" "--pinentry-mode" "loopback" "--passphrase" "" "--yes"
"--quick-generate-key" "[email protected] (insecure!)"))
(with-open-file (stream #?"${*data-source-gnupghome*}/gpg.conf"
:direction :output)
(format stream "default-key ~a~%default-recipient-self~%"
*test-gnupg-fingerprint*)))
(defmacro with-test-gnupg-home (base-dir &rest body)
"Set up gnupg homedir for test suite under BASE-DIR and run BODY with
*DATA-SOURCE-GNUPGHOME* and *TEST-GNUPG-FINGERPRINT* set appropriately."
`(let ((*data-source-gnupghome* (merge-pathnames #P"gnupg/" ,base-dir)))
(unwind-protect
(progn
(make-test-gnupghome)
(let ((*test-gnupg-fingerprint* (first-gpg-fingerprint)))
,@body))
(run-program "gpgconf" "--homedir" *data-source-gnupghome*
"--kill" "all"))))
(defparameter *test-pgp-file* nil)
(defmacro with-test-pgp-source (base-dir &rest body)
"Run BODY with *TEST-PGP-FILE* defined and a corresponding pgp data source
registered and populated."
`(let ((*test-pgp-file* (merge-pathnames "pgp-secrets.gpg" ,base-dir)))
(populate-data-pgp)
(handler-case
(try-register-data-source :pgp :location *test-pgp-file*)
(missing-data-source ()
(error "Test setup failure for pgp file ~a" *test-pgp-file*)))
,@body))
(defparameter *test-pass-dir* nil
"pass(1) store for use in test suite.")
(defun pass (args &key input)
(run-program `("env" ,#?"GNUPGHOME=${*data-source-gnupghome*}"
,#?"PASSWORD_STORE_DIR=${*test-pass-dir*}" "pass"
,@args)
:input (if input (make-string-input-stream input) nil)
:output :string :error-output :output))
(defmacro with-test-pass-source (test-home &rest body)
"Run BODY with pass(1) data source in TEST-HOME populated and registed."
`(let ((*test-pass-dir* (merge-pathnames #P"password-store/" ,test-home)))
(pass (list "init" *test-gnupg-fingerprint*))
(populate-data-pass)
(handler-case
(try-register-data-source :pass :location *test-pass-dir*)
(missing-data-source ()
(error "Test setup failure for pass directory ~a" *test-pass-dir*)))
,@body))
(defun runner ()
"Run tests via (sb-)rt, with setup and teardown."
(with-local-temporary-directory (test-home)
(with-test-gnupg-home test-home
(with-reset-data-sources
(with-test-pgp-source test-home
(with-test-pass-source test-home
(do-tests)))))))
;;;; tests for test runner machinery
(deftest runner.0 (not *data-source-gnupghome*) nil)
(deftest runner.1
(count-if
(lambda (line) (string-prefix-p "pub" line))
(lines (gpg '("--with-colons" "--list-keys"))))
1)
(deftest runner.2 (not *test-gnupg-fingerprint*) nil)
(deftest runner.3 (not *test-pgp-file*) nil)
(deftest runner.4 (nth-value 2 (pass '("list"))) 0)
| 4,520 | Common Lisp | .lisp | 92 | 43.097826 | 77 | 0.663564 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 1f498a25b77bec7b5ce066e3dc575c7fc3fc33a4c558bdb9db889e29bfc7fd59 | 3,978 | [
-1
] |
3,979 | reader.lisp | spwhitton_consfigurator/tests/reader.lisp | (in-package :consfigurator/tests)
(named-readtables:in-readtable :consfigurator)
(in-consfig "consfigurator/tests")
(deftest read-heredoc.1
#>EOF>yesEOF
"yes")
(deftest read-heredoc.2
#>>EOF>>yes
yesEOF
" yes")
(deftest read-heredoc.3
#>>EOF>> ; well
line 1
EOF
"line 1
")
(deftest read-heredoc.4
#>~EOF> blah
blah
EOF
"blah
blah
")
(deftest read-heredoc.5
#>>~EOF>>
line 1
line 2
EOF
"line 1
line 2
")
(deftest perl-tilde-reader.1
(#~/bar/ "foo bar ")
"bar")
(deftest perl-tilde-reader.2
(#~/(f.*) (bar)/ "foo bar ")
#("foo" "bar"))
(deftest perl-tilde-reader.3
(#0~/(f.*) (bar)/ "foo bar ")
"foo bar" #("foo" "bar"))
(deftest perl-tilde-reader.4
(#2~/(f.*) (bar)/ "foo bar ")
"bar" #("foo" "bar"))
(deftest perl-tilde-reader.5
(#!~/bar/ "foo")
t)
(deftest perl-tilde-reader.6
(handler-case (let ((*readtable*
(named-readtables:find-readtable :consfigurator)))
(read-from-string "(#!/bar/ \"foo\")"))
(simple-reader-error (err)
(format nil (simple-condition-format-control err))))
"Expected \"~\" following \"!\".")
(deftest perl-tilde-reader.7
(#~/\w{2}/g "aa bb cc")
("aa" "bb" "cc"))
(deftest perl-tilde-reader.8
(mapcar #~s/foo/bar/ '("foo" "bar"))
("bar" "bar"))
(deftest perl-tilde-reader.9
(#~s/${(+ 1 1)}/${(+ 2 2)}/ "2")
"4" t)
(deftest perl-tilde-reader.10
(#~s/\w/\w/ "a")
"w" t)
(deftest perl-tilde-reader.11
(#~s/foo/bar/ "foo foo foo")
"bar foo foo" t)
(deftest perl-tilde-reader.12
(#~s/foo/bar/g "foo foo foo")
"bar bar bar" t)
(deftest perl-tilde-reader.13
(#~s/ \s\w d \w\s /!/ix "aDa bDa cDa")
"aDa!cDa" t)
(deftest perl-tilde-reader.14
(#~s[^(\d) ]{`\1` } "4 foo")
"`4` foo" t)
(deftest perl-tilde-reader.15
(#~s(\d)((\&\)\()) " 4 ")
" (4)() " t)
(deftest perl-tilde-reader.16
(#~s/foo/#bar#/ "foo")
"#bar#" t)
(deftest perl-tilde-reader.17
(#~s#foo#\#bar\## "foo")
"#bar#" t)
(deftest perl-tilde-reader.18
(#~s'foo'${bar}' "foo")
"${bar}" t)
(deftest perl-tilde-reader.19
(#~/\d+/p "1234")
1234)
(deftest perl-tilde-reader.19
(#~/(\d+)/p "1234")
#(1234))
(deftest perl-tilde-reader.21
(#~/\d+/gp "1234 6789")
(1234 6789))
(deftest perl-tilde-reader.22
(#0~/aa (\d+)/p "aa 1234")
"aa 1234" #(1234))
(deftest perl-tilde-reader.22
(#0~/aa (.+)/p "aa bbbb")
"aa bbbb" #("bbbb"))
(deftest perl-tilde-reader.24
(#0~/(\d+)../p "1234")
1234 #(12))
(deftest perl-tilde-reader.25
(#1~/(\d+)../p "1234")
12 #(12))
(deftest perl-tilde-reader.26
(#1~/(..)../p "aabb")
"aa" #("aa"))
(deftest perl-tilde-reader.27
(#~/d(.)?$/p "d")
#(nil))
| 2,751 | Common Lisp | .lisp | 116 | 20.12931 | 76 | 0.565117 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | ef3586c9460e3ee3ae50ba92231c807749d5e363120d3ebc12baf95e4ff562f4 | 3,979 | [
-1
] |
3,980 | util.lisp | spwhitton_consfigurator/tests/data/util.lisp | (in-package :consfigurator/tests)
(named-readtables:in-readtable :consfigurator)
(in-consfig "consfigurator/tests")
;; relative parts
(deftest literal-data-pathname.1
(unix-namestring (literal-data-pathname "/home/user/data/" "foo" "bar"))
"/home/user/data/foo/bar")
;; missing trailing / on part 1
(deftest literal-data-pathname.2
(unix-namestring (literal-data-pathname "/home/user/data" "foo" "bar"))
"/home/user/data/foo/bar")
;; absolute part 2
(deftest literal-data-pathname.3
(unix-namestring (literal-data-pathname "/home/user/data/" "/foo" "bar"))
"/home/user/data/foo/bar")
;; relative part 2, "_"
(deftest literal-data-pathname.4
(unix-namestring (literal-data-pathname "/home/user/data/" "_foo" "bar"))
"/home/user/data/_foo/bar")
;; absolute part 3
(deftest literal-data-pathname.5
(unix-namestring (literal-data-pathname "/home/user/" "/data" "/foo/bar"))
"/home/user/data/foo/bar")
;; with type
(deftest literal-data-pathname.6
(unix-namestring
(literal-data-pathname "/home/user/" "/data" "/foo/bar" :type "txt"))
"/home/user/data/foo/bar.txt")
;; base-path is pathname
(deftest literal-data-pathname.7
(unix-namestring (literal-data-pathname #P"/home/user/data/" "foo" "bar"))
"/home/user/data/foo/bar")
;; base-path not a directory
(deftest literal-data-pathname.8
(handler-case
(literal-data-pathname #P"/home/user/data" "foo" "bar")
(simple-program-error (c) "fail"))
"fail")
;; extra '/' at end
(deftest literal-data-pathname.9
(unix-namestring (literal-data-pathname "/home/user/data//" "foo" "bar"))
"/home/user/data/foo/bar")
;; extra '/' in middle
(deftest literal-data-pathname.10
(unix-namestring (literal-data-pathname "/home/user//data/" "foo" "bar"))
"/home/user/data/foo/bar")
;; extra '/' part 2
(deftest literal-data-pathname.11
(unix-namestring (literal-data-pathname "/home/user/data/" "foo//" "bar"))
"/home/user/data/foo/bar")
;; extra '/' part 3
(deftest literal-data-pathname.12
(unix-namestring (literal-data-pathname "/home/user/data/" "foo" "//bar"))
"/home/user/data/foo/bar")
| 2,124 | Common Lisp | .lisp | 54 | 36.407407 | 78 | 0.695187 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 2e314cf82b4ae300efceb1ec0233119f8a8f2d74d76293a59dd381aa063fed17 | 3,980 | [
-1
] |
3,981 | pass.lisp | spwhitton_consfigurator/tests/data/pass.lisp | (in-package :consfigurator/tests)
(named-readtables:in-readtable :consfigurator)
(in-consfig "consfigurator/tests")
(defun populate-data-pass ()
"Invoked by test runner before data source is registered."
(pass '("insert" "-m" "server.example.org/account") :input "hunter2")
(pass '("insert" "-m" "_foo/bar/baz") :input "OK")
(pass '("insert" "-m" "foo/bar/baz") :input "illegal")
(pass '("insert" "-m" "valid/file") :input "shadowed")
(pass '("insert" "-m" "_valid/file") :input "visible")
(pass '("insert" "-m" "toplevel") :input "sekrit")
(pass '("insert" "-m" "server.example.org/etc/foo.conf")
:input "[section]
key=value"))
(deftest pass-host.1
(get-data-string "server.example.org" "account")
"hunter2")
(deftest pass-host.2
(get-data-string "--user-passwd--server.example.org" "account")
"hunter2")
(deftest pass-host.3
(get-data-string "server.example.org" "/etc/foo.conf") "[section]
key=value")
(deftest pass-host.4
(handler-case
(get-data-string "a.example.com" "/etc/foo.conf")
(missing-data (c) "fail"))
"fail")
(deftest pass-underscore.1
(get-data-string "_server.example.org" "account")
"hunter2")
(deftest pass-underscore.2
(get-data-string "_foo/bar" "baz") "OK")
(deftest pass-underscore.3
(handler-case
(get-data-string "foo/bar" "baz")
(simple-program-error (c) "fail"))
"fail")
(deftest pass-underscore.4
(get-data-string "_valid" "file") "visible")
(deftest pass-underscore.5
(get-data-string "_" "toplevel") "sekrit")
| 1,549 | Common Lisp | .lisp | 42 | 33.309524 | 71 | 0.661323 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | cdcd1b9e388538fcf06bd669ce4192ff02e7ce9a44ad3b3736f83e857eb7230b | 3,981 | [
-1
] |
3,982 | pgp.lisp | spwhitton_consfigurator/tests/data/pgp.lisp | (in-package :consfigurator/tests)
(named-readtables:in-readtable :consfigurator)
(in-consfig "consfigurator/tests")
(defun populate-data-pgp ()
"Invoked by test runner before data source is registered."
(data.pgp:set-data *test-pgp-file* "_secrets" "test" "this is a sekrit")
(data.pgp:set-data *test-pgp-file* "host.example.com" "/etc/foo.conf"
"secret file content"))
(deftest data.pgp.1
(data.pgp:get-data *test-pgp-file* "_secrets" "test")
"this is a sekrit")
(deftest data.pgp.2
(get-data-string "_secrets" "test")
"this is a sekrit")
(deftest data.pgp.3
(get-data-string "host.example.com" "/etc/foo.conf")
"secret file content")
| 685 | Common Lisp | .lisp | 17 | 36.411765 | 74 | 0.692771 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 5e320bd6f21eb9987652dcd48daf9e3206a099278a16c40fbe9d0c650a76e70b | 3,982 | [
-1
] |
3,983 | file.lisp | spwhitton_consfigurator/tests/property/file.lisp | (in-package :consfigurator/tests)
(named-readtables:in-readtable :consfigurator)
(in-consfig "consfigurator/tests")
(deftest contains-conf-space
(with-temporary-file (:pathname temp)
(with-open-file (s temp :if-exists :supersede :direction :output)
(write-sequence #>EOF>foo bar
# one two
one three
# one three
EOF s))
(deploy-these :local "localhost"
(evals `(file:contains-conf-space ,temp "foo" "baz" "one" "four" "two" "five")))
(read-file-string temp))
#>EOF>foo baz
one four
# one three
# one three
two five
EOF)
(deftest contains-conf-shell
(with-temporary-file (:pathname temp)
(with-open-file (s temp :if-exists :supersede :direction :output)
(write-sequence #>EOF>foo="bar baz"
# bar=baz
other="three word s"
EOF s))
(deploy-these :local "localhost"
(evals `(file:contains-conf-shell
,temp "bar" "two words" "quux" "one" "other" "one")))
(read-file-string temp))
#>EOF>foo="bar baz"
bar="two words"
other=one
quux=one
EOF)
(deftest contains-ini-settings
(with-temporary-file (:pathname temp)
(with-open-file (s temp :if-exists :supersede :direction :output)
(write-sequence #>EOF>[one]
two=three
[other]
; bar = ba
bar = baz baz quux
EOF s))
(deploy-these :local "localhost"
(evals `(file:contains-ini-settings ,temp
'("one" "four" "five")
'("another" "k" "v")
'("other" "bar" "baz")
'("another" "key" "val")
'("finally" "this" "one"))))
(read-file-string temp))
#>EOF>[one]
two=three
four=five
[other]
bar=baz
# bar=baz baz quux
[another]
k=v
key=val
[finally]
this=one
EOF)
| 1,854 | Common Lisp | .lisp | 65 | 21.861538 | 88 | 0.584364 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | ec87a1a304b7a229d7d58e90bec80757f3068b0fa9bfbba52ee91be2548b9cd7 | 3,983 | [
-1
] |
3,984 | consfigurator.asd | spwhitton_consfigurator/consfigurator.asd | (defsystem "consfigurator"
:description "Lisp declarative configuration management system"
:version "1.4.3"
:author "Sean Whitton <[email protected]>"
:licence "GPL-3+"
:serial t
:defsystem-depends-on (#:cffi-grovel)
:depends-on (#:agnostic-lizard
#:alexandria
#:anaphora
#:babel
#:babel-streams
#:bordeaux-threads
#:cffi
#:cl-heredoc
#:cl-interpol
#:cl-ppcre
#:closer-mop
#:named-readtables
#:osicat
#:parse-number
(:feature :sbcl (:require #:sb-posix))
#:trivial-backtrace)
:components ((:file "src/package")
(:file "src/reader")
(:cffi-grovel-file "src/libc")
(:cffi-grovel-file "src/libacl")
(:cffi-grovel-file "src/libcap" :if-feature :linux)
(:file "src/util")
(:file "src/util/posix1e")
(:file "src/connection")
(:file "src/property")
(:file "src/propspec")
(:file "src/host")
(:file "src/combinator")
(:file "src/deployment")
(:file "src/connection/local")
(:file "src/data")
(:file "src/image")
(:file "src/property/cmd")
(:file "src/property/file")
(:file "src/property/etc-default")
(:file "src/property/os")
(:file "src/property/rc.conf")
(:file "src/property/container")
(:file "src/property/periodic")
(:file "src/property/mount")
(:file "src/property/service")
(:file "src/property/apt")
(:file "src/property/pkgng")
(:file "src/property/package")
(:file "src/property/chroot")
(:file "src/property/disk")
(:file "src/property/fstab")
(:file "src/property/crypttab")
(:file "src/property/user")
(:file "src/util/linux-namespace")
(:file "src/property/git")
(:file "src/property/gnupg")
(:file "src/property/ssh")
(:file "src/property/sshd")
(:file "src/property/locale")
(:file "src/property/reboot")
(:file "src/property/installer")
(:file "src/property/grub")
(:file "src/property/u-boot")
(:file "src/property/hostname")
(:file "src/property/network")
(:file "src/property/libvirt")
(:file "src/property/ccache")
(:file "src/property/schroot")
(:file "src/property/sbuild")
(:file "src/property/postfix")
(:file "src/property/cron")
(:file "src/property/lets-encrypt")
(:file "src/property/apache")
(:file "src/property/systemd")
(:file "src/property/firewalld")
(:file "src/property/timezone")
(:file "src/property/swap")
(:file "src/property/lxc")
(:file "src/property/postgres")
(:file "src/connection/shell-wrap")
(:file "src/connection/fork")
(:file "src/connection/rehome")
(:file "src/connection/ssh")
(:file "src/connection/sudo")
(:file "src/connection/su")
(:file "src/connection/sbcl")
(:file "src/connection/chroot")
(:file "src/connection/setuid")
(:file "src/connection/as")
(:file "src/connection/linux-namespace")
(:file "src/data/util")
(:file "src/data/asdf")
(:file "src/data/pgp")
(:file "src/data/git-snapshot")
(:file "src/data/gpgpubkeys")
(:file "src/data/ssh-askpass")
(:file "src/data/local-file")
(:file "src/data/pass")
(:file "src/data/files-tree"))
:in-order-to ((test-op (test-op "consfigurator/tests"))))
(defsystem "consfigurator/tests"
:description
"Tests for Consfigurator, Lisp declarative configuration management system"
:version "1.4.3"
:author "Sean Whitton <[email protected]>"
:licence "GPL-3+"
:serial t
:depends-on (#:consfigurator
(:feature :sbcl (:require #:sb-rt))
(:feature (:not :sbcl) #:rt))
:components ((:file "tests/package")
(:file "tests/runner")
(:file "tests/data/pass")
(:file "tests/data/pgp")
(:file "tests/data/util")
(:file "tests/reader")
(:file "tests/util")
(:file "tests/property/file"))
:perform (test-op (o c) (symbol-call :consfigurator/tests '#:runner)))
| 4,989 | Common Lisp | .asd | 122 | 27.336066 | 77 | 0.49589 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 7e2dc211237ea75689ddd25b0a9d6f68d096cfe410510d1822b8f81e6e718d33 | 3,984 | [
-1
] |
3,988 | .dir-locals.el | spwhitton_consfigurator/.dir-locals.el | ;;; Directory Local Variables
;;; For more information see (info "(emacs) Directory Variables")
((nil . ((tab-width . 8)
(fill-column . 78)
(sentence-end-double-space . t)))
(lisp-mode . ((indent-tabs-mode . nil)))
(auto-mode-alist . (("\\.lisp\\'" . consfigurator-lisp-mode))))
| 300 | Common Lisp | .l | 7 | 38.857143 | 65 | 0.619863 | spwhitton/consfigurator | 57 | 1 | 0 | GPL-3.0 | 9/19/2024, 11:26:04 AM (Europe/Amsterdam) | 28ba6dd79601daee44f22f9cd43d105113304d62736c42501e1f48f45180180d | 3,988 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.