Debian Codegraph @

R/cache.R

raw
1
2 # tools for interacting with the renv global package cache
3 renv_cache_version <- function() {
4 renv_bootstrap_cache_version()
5 }
6
7 renv_cache_version_previous <- function() {
8 renv_bootstrap_cache_version_previous()
9 }
10
11 # given a record, find a compatible version of that package in the cache,
12 # using a computed hash if available; if no hash is available, then try
13 # to match based on the package name + version
14 renv_cache_find <- function(record) {
15
16 # validate required fields -- if any are missing, we can't use the cache
17 required <- c("Package", "Version")
18 missing <- renv_vector_diff(required, names(record))
19 if (length(missing))
20 return("")
21
22 # if we have a hash, use it directly
23 if (!is.null(record$Hash)) {
24
25 # generate path to package installations in cache
26 paths <- with(record, renv_paths_cache(Package, Version, Hash, Package))
27
28 # if there are multiple cache entries, return the first existing one
29 # if no entries exist, return path into first cache entry
30 for (path in paths)
31 if (file.exists(path))
32 return(path)
33
34 return(paths[[1L]])
35
36 }
37
38 # if the record doesn't have a hash, check to see if we can still locate a
39 # compatible package version within the cache
40 root <- with(record, renv_paths_cache(Package, Version))
41 hashes <- list.files(root, full.names = TRUE)
42 packages <- list.files(hashes, full.names = TRUE)
43
44 # iterate over package paths, read DESCRIPTION, and look
45 # for something compatible with the requested record
46 for (package in packages) {
47
48 # try to read the DESCRIPTION file
49 dcf <- catch(as.list(renv_description_read(package)))
50 if (inherits(dcf, "error"))
51 next
52
53 # if we're requesting an install from an R package repository,
54 # and the cached package has a "Repository" field, then use it
55 source <- renv_record_source(record)
56 hasrepo <-
57 source %in% c("cran", "repository") &&
58 "Repository" %in% names(dcf)
59
60 if (hasrepo)
61 return(package)
62
63 # check for compatible fields
64 fields <- unique(c(
65 renv_record_names(record, c("Package", "Version")),
66 renv_record_names(dcf, c("Package", "Version"))
67 ))
68
69 # drop unnamed fields
70 record <- record[nzchar(record)]
71 dcf <- dcf[nzchar(dcf)]
72
73 # drop remote fields for cranlike remotes
74 if (renv_record_cranlike(dcf))
75 dcf <- dcf[grep("^Remote(?!s)", names(dcf), invert = TRUE, perl = TRUE)]
76
77 # check identical
78 lhs <- keep(record, fields)
79 rhs <- keep(dcf, fields)
80 if (identical(lhs, rhs))
81 return(package)
82
83 }
84
85 # failed; return "" as proxy for missing file
86 ""
87
88 }
89
90 # given the path to a package's description file,
91 # compute the location it would be assigned if it
92 # were moved to the renv cache
93 renv_cache_path <- function(path) {
94 record <- renv_description_read(path)
95 record[["Hash"]] <- renv_hash_description(path)
96 renv_cache_find(record)
97 }
98
99 renv_cache_path_components <- function(path) {
100
101 data_frame(
102 Package = renv_path_component(path, 1L),
103 Hash = renv_path_component(path, 2L),
104 Version = renv_path_component(path, 3L)
105 )
106
107 }
108
109 renv_cache_synchronize <- function(record, linkable = FALSE) {
110
111 # construct path to package in library
112 library <- renv_libpaths_active()
113 path <- file.path(library, record$Package)
114 if (!file.exists(path))
115 return(FALSE)
116
117 # bail if the package source is unknown
118 # (packages with an unknown source are not cacheable)
119 desc <- renv_description_read(path)
120 source <- renv_snapshot_description_source(desc)
121 if (identical(source, list(Source = "unknown")))
122 return(FALSE)
123
124 # bail if record not cacheable
125 if (!renv_record_cacheable(record))
126 return(FALSE)
127
128 # if we don't have a hash, compute it now
129 record[["Hash"]] <- record[["Hash"]] %||% renv_hash_description(path)
130
131 # construct cache entry
132 caches <- renv_cache_find(record)
133
134 # try to synchronize
135 copied <- FALSE
136 for (cache in caches) {
137 copied <- renv_cache_synchronize_impl(cache, record, linkable, path)
138 if (copied)
139 return(TRUE)
140 }
141
142 return(FALSE)
143
144 }
145
146 renv_cache_synchronize_impl <- function(cache, record, linkable, path) {
147
148 # double-check we have a valid cache path
149 if (!nzchar(cache))
150 return(FALSE)
151
152 # if our cache -> path link is already up to date, then nothing to do
153 if (renv_file_same(cache, path))
154 return(TRUE)
155
156 # try to create the cache directory target
157 # (catch errors due to permissions, etc)
158 parent <- dirname(cache)
159 status <- catchall(ensure_directory(parent))
160 if (inherits(status, "error"))
161 return(FALSE)
162
163 # double-check that the cache is writable
164 writable <- local({
165 file <- renv_scope_tempfile("renv-tempfile-", tmpdir = parent)
166 status <- catchall(file.create(file))
167 file.exists(file)
168 })
169
170 if (!writable)
171 return(FALSE)
172
173 # obtain lock on the cache
174 lockpath <- file.path(parent, ".cache.lock")
175 renv_scope_lock(lockpath)
176
177 # if we already have a cache entry, back it up
178 restore <- renv_file_backup(cache)
179 defer(restore())
180
181 # copy package from source location into the cache
182 if (linkable) {
183 renv_cache_move(path, cache, overwrite = TRUE)
184 renv_file_link(cache, path, overwrite = TRUE)
185 } else {
186 renv_cache_copy(path, cache, overwrite = TRUE)
187 }
188
189 # invoke cache callbacks
190 renv_cache_callbacks(cache)
191
192 TRUE
193
194 }
195
196 renv_cache_callbacks <- function(cache) {
197
198 # only done on unix platforms
199 if (!renv_platform_unix())
200 return(FALSE)
201
202 # change the cache owner if set
203 user <- Sys.getenv("RENV_CACHE_USER", unset = NA)
204 if (!is.na(user)) {
205 parent <- dirname(dirname(dirname(cache)))
206 renv_system_exec(
207 command = "chown",
208 args = c("-Rf", renv_shell_quote(user), renv_shell_path(parent)),
209 action = "chowning cached package",
210 quiet = TRUE,
211 success = NULL
212 )
213 }
214
215 # change file modes after copy if set
216 mode <- Sys.getenv("RENV_CACHE_MODE", unset = NA)
217 if (!is.na(mode)) {
218 parent <- dirname(dirname(dirname(cache)))
219 renv_system_exec(
220 command = "chmod",
221 args = c("-Rf", renv_shell_quote(mode), renv_shell_path(parent)),
222 action = "chmoding cached package",
223 quiet = TRUE,
224 success = NULL
225 )
226 }
227
228 # finally, allow for an arbitrary callback if set
229 callback <- getOption("renv.cache.callback")
230 if (is.function(callback))
231 callback(cache)
232
233 }
234
235 renv_cache_list <- function(cache = NULL, packages = NULL) {
236 caches <- cache %||% renv_paths_cache()
237 paths <- map(caches, renv_cache_list_impl, packages = packages)
238 unlist(paths, recursive = TRUE, use.names = FALSE)
239 }
240
241 renv_cache_list_impl <- function(cache, packages) {
242
243 # paths to packages in the cache have the following format:
244 #
245 # <package>/<version>/<hash>/<package>
246 #
247 # so find entries in the cache by listing files in each directory
248 names <- file.path(cache, packages %||% list.files(cache))
249 versions <- list.files(names, full.names = TRUE)
250 hashes <- list.files(versions, full.names = TRUE)
251 paths <- list.files(hashes, full.names = TRUE)
252
253 # only keep paths that appear to be valid
254 valid <- grep(renv_regexps_package_name(), basename(paths))
255 paths[valid]
256
257 }
258
259 renv_cache_problems <- function(paths, reason) {
260
261 data_frame(
262 Package = renv_path_component(paths, 1L),
263 Version = renv_path_component(paths, 3L),
264 Path = paths,
265 Reason = reason
266 )
267
268 }
269
270 renv_cache_diagnose_corrupt_metadata <- function(paths, problems, verbose) {
271
272 # check for missing metadata files
273 metapaths <- file.path(paths, "Meta/package.rds")
274 ok <- file.exists(metapaths)
275 bad <- paths[!ok]
276
277 if (length(bad)) {
278
279 # nocov start
280 if (verbose) {
281 bulletin(
282 "The following package(s) are missing 'Meta/package.rds':",
283 renv_cache_format_path(bad),
284 "These packages should be purged and reinstalled."
285 )
286 }
287 # nocov end
288
289 data <- renv_cache_problems(
290 paths = bad,
291 reason = "'Meta/package.rds' does not exist"
292 )
293
294 problems$push(data)
295
296 }
297
298 # check for corrupt / unreadable metadata files
299 ok <- map_lgl(metapaths, function(path) {
300 rds <- catch(readRDS(path))
301 !inherits(rds, "error")
302 })
303
304 bad <- paths[!ok]
305
306 if (length(bad)) {
307
308 # nocov start
309 if (verbose) {
310 bulletin(
311 "The following package(s) have corrupt 'Meta/package.rds' files:",
312 renv_cache_format_path(bad),
313 "These packages should be purged and reinstalled."
314 )
315 }
316 # nocov end
317
318 data <- renv_cache_problems(
319 paths = bad,
320 reason = "'Meta/package.rds' does not exist"
321 )
322
323 problems$push(data)
324
325 }
326
327 paths
328
329 }
330
331 renv_cache_diagnose_missing_descriptions <- function(paths, problems, verbose) {
332
333 descpaths <- file.path(paths, "DESCRIPTION")
334 exists <- file.exists(descpaths)
335 bad <- paths[!exists]
336 if (empty(bad))
337 return(paths)
338
339 # nocov start
340 if (verbose) {
341 bulletin(
342 "The following packages are missing DESCRIPTION files in the cache:",
343 renv_cache_format_path(bad),
344 "These packages should be purged and reinstalled."
345 )
346 }
347 # nocov end
348
349 data <- renv_cache_problems(
350 paths = bad,
351 reason = "'DESCRIPTION' file does not exist"
352 )
353
354 problems$push(data)
355 paths[exists]
356
357 }
358
359 renv_cache_diagnose_bad_hash <- function(paths, problems, verbose) {
360
361 expected <- map_chr(paths, renv_cache_path)
362 wrong <- paths != expected & !file.exists(expected)
363 if (!any(wrong))
364 return(paths)
365
366 # nocov start
367 if (verbose) {
368
369 lhs <- renv_cache_path_components(paths[wrong])
370 rhs <- renv_cache_path_components(expected[wrong])
371
372 fmt <- "%s %s [Hash: %s != %s]"
373 entries <- sprintf(fmt, lhs$Package, lhs$Version, lhs$Hash, rhs$Hash)
374
375 bulletin(
376 "The following packages have incorrect hashes:",
377 entries,
378 "Consider using `renv::rehash()` to re-hash these packages."
379 )
380 }
381 # nocov end
382
383 data <- renv_cache_problems(
384 paths = paths[wrong],
385 reason = "unexpected hash"
386 )
387
388 problems$push(data)
389 paths
390
391 }
392
393 renv_cache_diagnose_wrong_built_version <- function(paths, problems, verbose) {
394
395 # form paths to DESCRIPTION files
396 descpaths <- file.path(paths, "DESCRIPTION")
397
398 # parse the version of R each was built for
399 versions <- map_chr(descpaths, function(descpath) {
400
401 tryCatch(
402 renv_description_built_version(descpath),
403 error = function(e) {
404 warning(e)
405 NA
406 }
407 )
408
409 })
410
411 # check for NAs, report and remove them
412 isna <- is.na(versions)
413 if (any(isna)) {
414
415 # nocov start
416 if (verbose) {
417
418 bulletin(
419 "The following packages have no 'Built' field recorded in their DESCRIPTION file:",
420 paths[isna],
421 "renv is unable to validate the version of R this package was built for."
422 )
423
424 }
425 # nocov end
426
427 data <- renv_cache_problems(
428 paths = paths[isna],
429 reason = "missing Built field"
430 )
431
432 problems$push(data)
433
434 paths <- paths[!isna]
435 versions <- versions[!isna]
436
437 }
438
439 # check for incompatible versions
440 wrong <- map_lgl(versions, function(version) {
441 tryCatch(
442 renv_version_compare(version, getRversion(), 2L) != 0,
443 error = function(e) {
444 warning(e)
445 TRUE
446 }
447 )
448 })
449
450 if (!any(wrong))
451 return(paths)
452
453 # nocov start
454 if (verbose) {
455
456 bulletin(
457 "The following packages in the cache were built for a different version of R:",
458 renv_cache_format_path(paths[wrong]),
459 "These packages will need to be purged and reinstalled."
460 )
461
462 }
463 # nocov end
464
465 data <- renv_cache_problems(
466 paths = paths[wrong],
467 reason = "built for different version of R"
468 )
469
470 problems$push(data)
471 paths
472
473 }
474
475 renv_cache_diagnose <- function(verbose = NULL) {
476
477 verbose <- verbose %||% renv_verbose()
478
479 problems <- stack()
480 paths <- renv_cache_list()
481 paths <- renv_cache_diagnose_corrupt_metadata(paths, problems, verbose)
482 paths <- renv_cache_diagnose_missing_descriptions(paths, problems, verbose)
483 paths <- renv_cache_diagnose_bad_hash(paths, problems, verbose)
484 paths <- renv_cache_diagnose_wrong_built_version(paths, problems, verbose)
485
486 invisible(bind(problems$data()))
487
488 }
489
490 renv_cache_acls_reset <- function(target) {
491
492 enabled <- Sys.getenv("RENV_CACHE_ACLS", unset = "TRUE")
493 if (enabled)
494 renv_acls_reset(target)
495
496 }
497
498 # copies a package at location 'source' to cache location 'target'
499 renv_cache_copy <- function(source, target, overwrite = FALSE) {
500 ensure_parent_directory(target)
501 renv_file_copy(source, target, overwrite = overwrite)
502 renv_cache_acls_reset(target)
503 }
504
505 # moves a package from location 'source' to cache location 'target',
506 # and then links back from 'target' to 'source'
507 renv_cache_move <- function(source, target, overwrite = FALSE) {
508
509 # move package into the cache if requested
510 if (overwrite || !file.exists(target)) {
511 ensure_parent_directory(target)
512 renv_file_move(source, target, overwrite = TRUE)
513 }
514
515 # try to reset ACLs on the cache directory
516 renv_cache_acls_reset(target)
517
518 # link from the cache back to the target location
519 renv_file_link(target, source, overwrite = TRUE)
520
521 }
522
523 # nocov start
524 renv_cache_format_path <- function(paths) {
525
526 # extract path components
527 names <- format(renv_path_component(paths, 1L))
528 hashes <- format(renv_path_component(paths, 2L))
529 versions <- format(renv_path_component(paths, 3L))
530
531 # format and write
532 fmt <- "%s %s [Hash: %s]"
533 sprintf(fmt, names, versions, hashes)
534
535 }
536 # nocov end
537
538 renv_cache_clean_empty <- function(cache = NULL) {
539 caches <- cache %||% renv_paths_cache()
540 map(caches, renv_cleanse_empty)
541 }
542
543 renv_cache_package_validate <- function(path) {
544
545 if (renv_project_type(path) == "package")
546 return(TRUE)
547
548 type <- renv_file_type(path, symlinks = FALSE)
549 if (!nzchar(type))
550 return(FALSE)
551
552 name <- if (type == "directory") "directory" else "file"
553 fmt <- "%s %s exists but does not appear to be an R package"
554 warningf(fmt, name, dQuote(path))
555
556 FALSE
557
558 }
559
560 renv_cache_config_enabled <- function(project) {
561 config$cache.enabled() && settings$use.cache(project = project)
562 }
563
564 renv_cache_config_symlinks <- function(project) {
565
566 usesymlinks <-
567 config$cache.symlinks(default = NULL) %||%
568 renv_cache_config_symlinks_default(project = project)
569
570 usesymlinks && settings$use.cache(project = project)
571
572 }
573
574 renv_cache_config_symlinks_default <- function(project) {
575
576 # on linux, we can always use symlinks
577 if (renv_platform_unix())
578 return(TRUE)
579
580 # on Windows, only try to use symlinks (junction points) if the cache
581 # and the project library appear to live on the same drive
582 libpath <- renv_paths_library(project = project)
583 cachepath <- renv_paths_cache()
584
585 # TODO: with this change, anyone using networks not mapped to a local drive
586 # would need to opt-in to using symlinks, but that's probably okay?
587 all(
588 substring(libpath, 1L, 2L) == substring(cachepath, 1L, 2L),
589 substring(libpath, 2L, 2L) == ":",
590 substring(cachepath, 2L, 2L) == ":"
591 )
592
593
594 }
595
596 renv_cache_linkable <- function(project, library) {
597 renv_cache_config_enabled(project = project) &&
598 renv_cache_config_symlinks(project = project) &&
599 getOption(
600 "renv.cache.linkable",
601 renv_path_same(library, renv_paths_library(project = project))
602 )
603 }