diff --git a/NEWS.md b/NEWS.md index f2fc9a9..dd311a7 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,9 @@ # climateData (development version) +- Reading the bundled tile index (`latestHistoricalYear()`, the tile lookup in `ClimateNA_useTiles()`) no longer + writes `-wal`/`-shm` files into the installed package folder. Read-only `ClimateNA_sql()` connections open the + file with SQLite's `immutable=1`, and the bundled index is shipped in rollback-journal mode instead of WAL. + - `latestHistoricalYear()` and the tile lookup in `ClimateNA_useTiles()` open the bundled tile index read-only and set the SQLite busy timeout before any other statement. Before, many processes opening it together (e.g. parallel hindcast jobs parsing fireSense modules on NFS) could fail with "database is locked". diff --git a/R/ClimateNA_createTiles.R b/R/ClimateNA_createTiles.R index 3e77095..620f708 100644 --- a/R/ClimateNA_createTiles.R +++ b/R/ClimateNA_createTiles.R @@ -75,6 +75,20 @@ ClimateNA_path <- function(dataPath, tile = NULL, type = NULL, msy = NULL, gcm = })() } +#' SQLite `file:` URI that opens `dbfile` immutably +#' +#' POSIX paths give `file:///home/...`; Windows paths give `file:///C:/...` (backslashes become `/`, the +#' drive colon stays). The rest of the path is percent-encoded. +#' +#' @keywords internal +sqlite_immutable_uri <- function(dbfile) { + path <- gsub("\\", "/", normalizePath(dbfile, winslash = "/", mustWork = FALSE), fixed = TRUE) + drive <- if (grepl("^[A-Za-z]:", path)) substr(path, 1L, 2L) else "" + rest <- substring(path, nchar(drive) + 1L) + rest <- gsub("%2F", "/", utils::URLencode(rest, reserved = TRUE), fixed = TRUE) + paste0("file://", if (nzchar(drive)) "/", drive, rest, "?immutable=1") +} + #' @keywords internal #' @importFrom DBI dbExecute #' @importFrom RSQLite dbConnect SQLite @@ -92,9 +106,15 @@ sqlite_connect_db <- function(dbfile, readonly = FALSE) { ## builds a library containing only this package's Depends/Imports/LinkingTo. ## climateData therefore declares hms in its own Imports: the requirement is ## real and RSQLite does not state it correctly. + ## A read-only connection opens the file with SQLite's `immutable=1` URI parameter: SQLite then takes no + ## locks and creates no `-wal`/`-shm` files, so reading never writes beside the database (e.g. into the + ## installed package folder, which may be read-only or shared). Use it only for a file nobody is changing. + ## RSQLite hands a `file:` URI straight to SQLite, so no extra flag is needed beyond `SQLITE_RO`. + dbname <- if (isTRUE(readonly)) sqlite_immutable_uri(dbfile) else dbfile + db <- RSQLite::dbConnect( drv = RSQLite::SQLite(), - dbname = dbfile, + dbname = dbname, ## `synchronous = NULL`: dbConnect would otherwise run `PRAGMA synchronous` before any busy timeout ## is set, which fails at once with "database is locked" when other processes have the file open. synchronous = NULL, @@ -102,13 +122,15 @@ sqlite_connect_db <- function(dbfile, readonly = FALSE) { extended_types = TRUE ## for DATETIME -- see note above re: hms ) - ## must come first: every statement below waits (ms) for a lock instead of failing at once - DBI::dbExecute(db, "PRAGMA busy_timeout = 60000") - if (!isTRUE(readonly)) { + ## must come first: every statement below waits (ms) for a lock instead of failing at once + DBI::dbExecute(db, "PRAGMA busy_timeout = 60000") DBI::dbExecute(db, "PRAGMA synchronous = normal") if (isTRUE(newDb)) { - DBI::dbExecute(db, "PRAGMA journal_mode = WAL") ## using WAL allows concurrency + ## WAL allows concurrent writers while building. Switch back to `journal_mode = DELETE` before the + ## file is shipped in inst/extdata (see data-raw/06-archive_fingerprints.R): a WAL file creates + ## `-wal`/`-shm` files beside it even when only read. + DBI::dbExecute(db, "PRAGMA journal_mode = WAL") } } diff --git a/data-raw/06-archive_fingerprints.R b/data-raw/06-archive_fingerprints.R index 4ec114d..2b3edc5 100644 --- a/data-raw/06-archive_fingerprints.R +++ b/data-raw/06-archive_fingerprints.R @@ -35,6 +35,7 @@ db <- sqlite_connect_db(wrkngDBfile) n <- .archivesUpsert(db, fingerprints) message(n, " fingerprints written; ", sum(is.na(fingerprints$verified)), " zips not verified") DBI::dbExecute(db, "PRAGMA wal_checkpoint(TRUNCATE)") +DBI::dbExecute(db, "PRAGMA journal_mode = DELETE") ## ship in rollback-journal mode: reading a WAL file writes -wal/-shm beside it DBI::dbDisconnect(db) stopifnot(!file.exists(paste0(wrkngDBfile, "-wal")) || file.size(paste0(wrkngDBfile, "-wal")) == 0) diff --git a/inst/extdata/ClimateNA_tiles.sqlite b/inst/extdata/ClimateNA_tiles.sqlite index 48e98cf..e177d06 100755 Binary files a/inst/extdata/ClimateNA_tiles.sqlite and b/inst/extdata/ClimateNA_tiles.sqlite differ diff --git a/man/sqlite_immutable_uri.Rd b/man/sqlite_immutable_uri.Rd new file mode 100644 index 0000000..f33288e --- /dev/null +++ b/man/sqlite_immutable_uri.Rd @@ -0,0 +1,13 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/ClimateNA_createTiles.R +\name{sqlite_immutable_uri} +\alias{sqlite_immutable_uri} +\title{SQLite \verb{file:} URI that opens \code{dbfile} immutably} +\usage{ +sqlite_immutable_uri(dbfile) +} +\description{ +POSIX paths give \verb{file:///home/...}; Windows paths give \verb{file:///C:/...} (backslashes become \code{/}, the +drive colon stays). The rest of the path is percent-encoded. +} +\keyword{internal} diff --git a/tests/testthat/helper-sqlite.R b/tests/testthat/helper-sqlite.R new file mode 100644 index 0000000..12f8573 --- /dev/null +++ b/tests/testthat/helper-sqlite.R @@ -0,0 +1,13 @@ +## A copy of the shipped tile index in its own temporary folder (removed when the calling test ends), +## so a test can tell whether anything else appears beside it. +dbCopy <- function(env = parent.frame()) { + d <- tempfile("extdata") + dir.create(d) + f <- file.path(d, "ClimateNA_tiles.sqlite") + file.copy(ClimateNA_tiles_sqlite(), f) + withr::defer({ + Sys.chmod(d, "755") + unlink(d, recursive = TRUE) + }, envir = env) + f +} diff --git a/tests/testthat/test-sqliteConcurrency.R b/tests/testthat/test-sqliteConcurrency.R index bc553cf..87c6635 100644 --- a/tests/testthat/test-sqliteConcurrency.R +++ b/tests/testthat/test-sqliteConcurrency.R @@ -4,12 +4,6 @@ skip_on_os("windows") ## uses forked workers -dbCopy <- function() { - f <- tempfile(fileext = ".sqlite") - file.copy(ClimateNA_tiles_sqlite(), f) - f -} - test_that("parallel latestHistoricalYear() calls on one database do not fail", { f <- dbCopy() on.exit(unlink(paste0(f, c("", "-wal", "-shm"))), add = TRUE) @@ -50,23 +44,42 @@ test_that("a read-only lookup neither writes nor creates tables", { expect_false(DBI::dbExistsTable(con, "future_normals")) }) -test_that("a lookup waits for a lock held by another process instead of failing", { +test_that("writing connections wait for each other's lock; an immutable read does not", { f <- dbCopy() on.exit(unlink(paste0(f, c("", "-wal", "-shm"))), add = TRUE) - ## rollback-journal mode, where a writer's lock blocks readers + ## rollback-journal mode, as shipped, where a writer's lock blocks other connections con <- DBI::dbConnect(RSQLite::SQLite(), f) DBI::dbExecute(con, "PRAGMA journal_mode = DELETE") DBI::dbDisconnect(con) testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f) + nRows <- function() { + d <- ClimateNA_sql(f, "historical", readonly = TRUE) + on.exit(DBI::dbDisconnect(d[["db"]])) + nrow(dplyr::collect(d[["df"]])) + } + nBefore <- nRows() holder <- parallel::mcparallel({ con <- DBI::dbConnect(RSQLite::SQLite(), f) DBI::dbExecute(con, "BEGIN EXCLUSIVE") - Sys.sleep(2) + Sys.sleep(3) DBI::dbExecute(con, "COMMIT") DBI::dbDisconnect(con) }) Sys.sleep(0.5) ## let the holder take its lock - expect_no_error(latestHistoricalYear()) + + ## the immutable read ignores the lock: it neither waits nor fails + t0 <- Sys.time() + expect_no_error(yr <- latestHistoricalYear()) + expect_lt(as.numeric(difftime(Sys.time(), t0, units = "secs")), 2) + + ## a second writing connection waits for the lock (busy_timeout) instead of failing, then writes + t0 <- Sys.time() + w <- ClimateNA_sql(f, "historical") + expect_no_error(DBI::dbExecute(w[["db"]], "DELETE FROM historical WHERE rowid = (SELECT max(rowid) FROM historical)")) + DBI::dbDisconnect(w[["db"]]) + expect_gt(as.numeric(difftime(Sys.time(), t0, units = "secs")), 1) parallel::mccollect(holder) + + expect_identical(nRows(), nBefore - 1L) }) diff --git a/tests/testthat/test-sqliteReadOnlyNoWrites.R b/tests/testthat/test-sqliteReadOnlyNoWrites.R new file mode 100644 index 0000000..43bdae7 --- /dev/null +++ b/tests/testthat/test-sqliteReadOnlyNoWrites.R @@ -0,0 +1,51 @@ +## Reading the shipped tile index must not write anything beside it (no -wal/-shm files, no change to the +## database file), also when the folder is read-only (read-only installs, hard-linked or shared libraries). + +dbState <- function(f) { + list(files = list.files(dirname(f), all.files = TRUE, no.. = TRUE), + size = file.size(f), mtime = file.mtime(f), md5 = unname(tools::md5sum(f))) +} + +lookup <- function() { + dbdf <- ClimateNA_sql(ClimateNA_tiles_sqlite(), "historical", readonly = TRUE) + on.exit(DBI::dbDisconnect(dbdf[["db"]]), add = TRUE) + dplyr::collect(dplyr::arrange(dplyr::filter(dbdf[["df"]], tileid <= 20L), rowid)) +} + +test_that("the shipped tile index is not in WAL mode", { + con <- DBI::dbConnect(RSQLite::SQLite(), dbCopy(), flags = RSQLite::SQLITE_RO) + on.exit(DBI::dbDisconnect(con)) + expect_identical(DBI::dbGetQuery(con, "PRAGMA journal_mode")[[1]], "delete") +}) + +test_that("read-only lookups write nothing beside the database", { + f <- dbCopy() + testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f) + before <- dbState(f) + res <- lookup() + yr <- latestHistoricalYear() + expect_identical(dbState(f), before) + expect_gt(nrow(res), 0L) + expect_true(is.numeric(yr) || is.integer(yr)) +}) + +test_that("read-only lookups work in a read-only folder and give the same rows", { + f <- dbCopy() + testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f) + expected <- lookup() + expectedYr <- latestHistoricalYear() + Sys.chmod(dirname(f), "555") + before <- dbState(f) + expect_identical(lookup(), expected) + expect_identical(latestHistoricalYear(), expectedYr) + expect_identical(dbState(f), before) + + ## Windows ignores folder modes, and root can write anywhere: then only the assertions above ran + skip_if(file.access(dirname(f), 2) == 0, "cannot make a folder read-only here (Windows or root)") +}) + +test_that("the immutable URI is built for POSIX and Windows paths", { + expect_identical(sqlite_immutable_uri("C:\\Users\\a b\\x.sqlite"), "file:///C:/Users/a%20b/x.sqlite?immutable=1") + skip_on_os("windows") ## normalizePath() adds a drive letter to a POSIX path + expect_identical(sqlite_immutable_uri("/home/a b/x#.sqlite"), "file:///home/a%20b/x%23.sqlite?immutable=1") +})