database.scm 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2017, 2019 Caleb Ristvedt <caleb.ristvedt@cune.org>
  3. ;;; Copyright © 2018 Ludovic Courtès <ludo@gnu.org>
  4. ;;;
  5. ;;; This file is part of GNU Guix.
  6. ;;;
  7. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  8. ;;; under the terms of the GNU General Public License as published by
  9. ;;; the Free Software Foundation; either version 3 of the License, or (at
  10. ;;; your option) any later version.
  11. ;;;
  12. ;;; GNU Guix is distributed in the hope that it will be useful, but
  13. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;;; GNU General Public License for more details.
  16. ;;;
  17. ;;; You should have received a copy of the GNU General Public License
  18. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  19. (define-module (guix store database)
  20. #:use-module (sqlite3)
  21. #:use-module (guix config)
  22. #:use-module (guix serialization)
  23. #:use-module (guix store deduplication)
  24. #:use-module (guix base16)
  25. #:use-module (guix progress)
  26. #:use-module (guix build syscalls)
  27. #:use-module ((guix build utils)
  28. #:select (mkdir-p executable-file?))
  29. #:use-module (guix build store-copy)
  30. #:use-module (srfi srfi-1)
  31. #:use-module (srfi srfi-11)
  32. #:use-module (srfi srfi-19)
  33. #:use-module (srfi srfi-26)
  34. #:use-module (rnrs io ports)
  35. #:use-module (ice-9 match)
  36. #:use-module (system foreign)
  37. #:export (sql-schema
  38. %default-database-file
  39. with-database
  40. path-id
  41. sqlite-register
  42. register-path
  43. register-items
  44. %epoch
  45. reset-timestamps))
  46. ;;; Code for working with the store database directly.
  47. (define sql-schema
  48. ;; Name of the file containing the SQL scheme or #f.
  49. (make-parameter #f))
  50. (define sqlite-exec
  51. ;; XXX: This is was missing from guile-sqlite3 until
  52. ;; <https://notabug.org/guile-sqlite3/guile-sqlite3/commit/b87302f9bcd18a286fed57b2ea521845eb1131d7>.
  53. (let ((exec (pointer->procedure
  54. int
  55. (dynamic-func "sqlite3_exec" (@@ (sqlite3) libsqlite3))
  56. '(* * * * *))))
  57. (lambda (db text)
  58. (let ((ret (exec ((@@ (sqlite3) db-pointer) db)
  59. (string->pointer text)
  60. %null-pointer %null-pointer %null-pointer)))
  61. (unless (zero? ret)
  62. ((@@ (sqlite3) sqlite-error) db "sqlite-exec" ret))))))
  63. (define (initialize-database db)
  64. "Initializing DB, an empty database, by creating all the tables and indexes
  65. as specified by SQL-SCHEMA."
  66. (define schema
  67. (or (sql-schema)
  68. (search-path %load-path "guix/store/schema.sql")))
  69. (sqlite-exec db (call-with-input-file schema get-string-all)))
  70. (define (call-with-database file proc)
  71. "Pass PROC a database record corresponding to FILE. If FILE doesn't exist,
  72. create it and initialize it as a new database."
  73. (let ((new? (not (file-exists? file)))
  74. (db (sqlite-open file)))
  75. ;; Turn DB in "write-ahead log" mode, which should avoid SQLITE_LOCKED
  76. ;; errors when we have several readers: <https://www.sqlite.org/wal.html>.
  77. (sqlite-exec db "PRAGMA journal_mode=WAL;")
  78. ;; Install a busy handler such that, when the database is locked, sqlite
  79. ;; retries until 30 seconds have passed, at which point it gives up and
  80. ;; throws SQLITE_BUSY.
  81. (sqlite-exec db "PRAGMA busy_timeout = 30000;")
  82. (dynamic-wind noop
  83. (lambda ()
  84. (when new?
  85. (initialize-database db))
  86. (proc db))
  87. (lambda ()
  88. (sqlite-close db)))))
  89. ;; XXX: missing in guile-sqlite3@0.1.0
  90. (define SQLITE_BUSY 5)
  91. (define (call-with-transaction db proc)
  92. "Start a transaction with DB (make as many attempts as necessary) and run
  93. PROC. If PROC exits abnormally, abort the transaction, otherwise commit the
  94. transaction after it finishes."
  95. (catch 'sqlite-error
  96. (lambda ()
  97. ;; We use begin immediate here so that if we need to retry, we
  98. ;; figure that out immediately rather than because some SQLITE_BUSY
  99. ;; exception gets thrown partway through PROC - in which case the
  100. ;; part already executed (which may contain side-effects!) would be
  101. ;; executed again for every retry.
  102. (sqlite-exec db "begin immediate;")
  103. (let ((result (proc)))
  104. (sqlite-exec db "commit;")
  105. result))
  106. (lambda (key who error description)
  107. (if (= error SQLITE_BUSY)
  108. (call-with-transaction db proc)
  109. (begin
  110. (sqlite-exec db "rollback;")
  111. (throw 'sqlite-error who error description))))))
  112. (define %default-database-file
  113. ;; Default location of the store database.
  114. (string-append %store-database-directory "/db.sqlite"))
  115. (define-syntax-rule (with-database file db exp ...)
  116. "Open DB from FILE and close it when the dynamic extent of EXP... is left.
  117. If FILE doesn't exist, create it and initialize it as a new database."
  118. (call-with-database file (lambda (db) exp ...)))
  119. (define (last-insert-row-id db)
  120. ;; XXX: (sqlite3) currently lacks bindings for 'sqlite3_last_insert_rowid'.
  121. ;; Work around that.
  122. (let* ((stmt (sqlite-prepare db "SELECT last_insert_rowid();"
  123. #:cache? #t))
  124. (result (sqlite-fold cons '() stmt)))
  125. (sqlite-finalize stmt)
  126. (match result
  127. ((#(id)) id)
  128. (_ #f))))
  129. (define path-id-sql
  130. "SELECT id FROM ValidPaths WHERE path = :path")
  131. (define* (path-id db path)
  132. "If PATH exists in the 'ValidPaths' table, return its numerical
  133. identifier. Otherwise, return #f."
  134. (let ((stmt (sqlite-prepare db path-id-sql #:cache? #t)))
  135. (sqlite-bind-arguments stmt #:path path)
  136. (let ((result (sqlite-fold cons '() stmt)))
  137. (sqlite-finalize stmt)
  138. (match result
  139. ((#(id) . _) id)
  140. (_ #f)))))
  141. (define update-sql
  142. "UPDATE ValidPaths SET hash = :hash, registrationTime = :time, deriver =
  143. :deriver, narSize = :size WHERE id = :id")
  144. (define insert-sql
  145. "INSERT INTO ValidPaths (path, hash, registrationTime, deriver, narSize)
  146. VALUES (:path, :hash, :time, :deriver, :size)")
  147. (define* (update-or-insert db #:key path deriver hash nar-size time)
  148. "The classic update-if-exists and insert-if-doesn't feature that sqlite
  149. doesn't exactly have... they've got something close, but it involves deleting
  150. and re-inserting instead of updating, which causes problems with foreign keys,
  151. of course. Returns the row id of the row that was modified or inserted."
  152. (let ((id (path-id db path)))
  153. (if id
  154. (let ((stmt (sqlite-prepare db update-sql #:cache? #t)))
  155. (sqlite-bind-arguments stmt #:id id
  156. #:deriver deriver
  157. #:hash hash #:size nar-size #:time time)
  158. (sqlite-fold cons '() stmt)
  159. (sqlite-finalize stmt)
  160. (last-insert-row-id db))
  161. (let ((stmt (sqlite-prepare db insert-sql #:cache? #t)))
  162. (sqlite-bind-arguments stmt
  163. #:path path #:deriver deriver
  164. #:hash hash #:size nar-size #:time time)
  165. (sqlite-fold cons '() stmt) ;execute it
  166. (sqlite-finalize stmt)
  167. (last-insert-row-id db)))))
  168. (define add-reference-sql
  169. "INSERT OR REPLACE INTO Refs (referrer, reference) VALUES (:referrer, :reference);")
  170. (define (add-references db referrer references)
  171. "REFERRER is the id of the referring store item, REFERENCES is a list
  172. ids of items referred to."
  173. (let ((stmt (sqlite-prepare db add-reference-sql #:cache? #t)))
  174. (for-each (lambda (reference)
  175. (sqlite-reset stmt)
  176. (sqlite-bind-arguments stmt #:referrer referrer
  177. #:reference reference)
  178. (sqlite-fold cons '() stmt) ;execute it
  179. (last-insert-row-id db))
  180. references)
  181. (sqlite-finalize stmt)))
  182. (define* (sqlite-register db #:key path (references '())
  183. deriver hash nar-size time)
  184. "Registers this stuff in DB. PATH is the store item to register and
  185. REFERENCES is the list of store items PATH refers to; DERIVER is the '.drv'
  186. that produced PATH, HASH is the base16-encoded Nix sha256 hash of
  187. PATH (prefixed with \"sha256:\"), and NAR-SIZE is the size in bytes PATH after
  188. being converted to nar form. TIME is the registration time to be recorded in
  189. the database or #f, meaning \"right now\".
  190. Every store item in REFERENCES must already be registered."
  191. (let ((id (update-or-insert db #:path path
  192. #:deriver deriver
  193. #:hash hash
  194. #:nar-size nar-size
  195. #:time (time-second
  196. (or time
  197. (current-time time-utc))))))
  198. ;; Call 'path-id' on each of REFERENCES. This ensures we get a
  199. ;; "non-NULL constraint" failure if one of REFERENCES is unregistered.
  200. (add-references db id
  201. (map (cut path-id db <>) references))))
  202. ;;;
  203. ;;; High-level interface.
  204. ;;;
  205. (define (reset-timestamps file)
  206. "Reset the modification time on FILE and on all the files it contains, if
  207. it's a directory. While at it, canonicalize file permissions."
  208. ;; Note: We're resetting to one second after the Epoch like 'guix-daemon'
  209. ;; has always done.
  210. (let loop ((file file)
  211. (type (stat:type (lstat file))))
  212. (case type
  213. ((directory)
  214. (chmod file #o555)
  215. (utime file 1 1 0 0)
  216. (let ((parent file))
  217. (for-each (match-lambda
  218. (("." . _) #f)
  219. ((".." . _) #f)
  220. ((file . properties)
  221. (let ((file (string-append parent "/" file)))
  222. (loop file
  223. (match (assoc-ref properties 'type)
  224. ((or 'unknown #f)
  225. (stat:type (lstat file)))
  226. (type type))))))
  227. (scandir* parent))))
  228. ((symlink)
  229. (utime file 1 1 0 0 AT_SYMLINK_NOFOLLOW))
  230. (else
  231. (chmod file (if (executable-file? file) #o555 #o444))
  232. (utime file 1 1 0 0)))))
  233. (define* (register-path path
  234. #:key (references '()) deriver prefix
  235. state-directory (deduplicate? #t)
  236. (reset-timestamps? #t)
  237. (schema (sql-schema)))
  238. "Register PATH as a valid store file, with REFERENCES as its list of
  239. references, and DERIVER as its deriver (.drv that led to it.) If PREFIX is
  240. given, it must be the name of the directory containing the new store to
  241. initialize; if STATE-DIRECTORY is given, it must be a string containing the
  242. absolute file name to the state directory of the store being initialized.
  243. Return #t on success.
  244. Use with care as it directly modifies the store! This is primarily meant to
  245. be used internally by the daemon's build hook."
  246. (register-items (list (store-info path deriver references))
  247. #:prefix prefix #:state-directory state-directory
  248. #:deduplicate? deduplicate?
  249. #:reset-timestamps? reset-timestamps?
  250. #:schema schema
  251. #:log-port (%make-void-port "w")))
  252. (define %epoch
  253. ;; When it all began.
  254. (make-time time-utc 0 1))
  255. (define* (register-items items
  256. #:key prefix state-directory
  257. (deduplicate? #t)
  258. (reset-timestamps? #t)
  259. registration-time
  260. (schema (sql-schema))
  261. (log-port (current-error-port)))
  262. "Register all of ITEMS, a list of <store-info> records as returned by
  263. 'read-reference-graph', in the database under PREFIX/STATE-DIRECTORY. ITEMS
  264. must be in topological order (with leaves first.) If the database is
  265. initially empty, apply SCHEMA to initialize it. REGISTRATION-TIME must be the
  266. registration time to be recorded in the database; #f means \"now\".
  267. Write a progress report to LOG-PORT."
  268. ;; Priority for options: first what is given, then environment variables,
  269. ;; then defaults. %state-directory, %store-directory, and
  270. ;; %store-database-directory already handle the "environment variables /
  271. ;; defaults" question, so we only need to choose between what is given and
  272. ;; those.
  273. (define db-dir
  274. (cond (state-directory
  275. (string-append state-directory "/db"))
  276. (prefix
  277. (string-append prefix %localstatedir "/guix/db"))
  278. (else
  279. %store-database-directory)))
  280. (define store-dir
  281. (if prefix
  282. (string-append prefix %storedir)
  283. %store-directory))
  284. (define (register db item)
  285. (define to-register
  286. (if prefix
  287. (string-append %storedir "/" (basename (store-info-item item)))
  288. ;; note: we assume here that if path is, for example,
  289. ;; /foo/bar/gnu/store/thing.txt and prefix isn't given, then an
  290. ;; environment variable has been used to change the store directory
  291. ;; to /foo/bar/gnu/store, since otherwise real-path would end up
  292. ;; being /gnu/store/thing.txt, which is probably not the right file
  293. ;; in this case.
  294. (store-info-item item)))
  295. (define real-file-name
  296. (string-append store-dir "/" (basename (store-info-item item))))
  297. ;; When TO-REGISTER is already registered, skip it. This makes a
  298. ;; significant differences when 'register-closures' is called
  299. ;; consecutively for overlapping closures such as 'system' and 'bootcfg'.
  300. (unless (path-id db to-register)
  301. (when reset-timestamps?
  302. (reset-timestamps real-file-name))
  303. (let-values (((hash nar-size) (nar-sha256 real-file-name)))
  304. (sqlite-register db #:path to-register
  305. #:references (store-info-references item)
  306. #:deriver (store-info-deriver item)
  307. #:hash (string-append "sha256:"
  308. (bytevector->base16-string hash))
  309. #:nar-size nar-size
  310. #:time registration-time)
  311. (when deduplicate?
  312. (deduplicate real-file-name hash #:store store-dir)))))
  313. (mkdir-p db-dir)
  314. (parameterize ((sql-schema schema))
  315. (with-database (string-append db-dir "/db.sqlite") db
  316. (call-with-transaction db
  317. (lambda ()
  318. (let* ((prefix (format #f "registering ~a items" (length items)))
  319. (progress (progress-reporter/bar (length items)
  320. prefix log-port)))
  321. (call-with-progress-reporter progress
  322. (lambda (report)
  323. (for-each (lambda (item)
  324. (register db item)
  325. (report))
  326. items)))))))))