-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathcache.rs
More file actions
285 lines (256 loc) · 9.6 KB
/
cache.rs
File metadata and controls
285 lines (256 loc) · 9.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use lazy_static::lazy_static;
use log::{trace, warn};
use std::{
collections::{hash_map::Entry, HashMap, HashSet},
io,
path::PathBuf,
sync::{Arc, Mutex},
time::SystemTime,
};
use crate::{
env::ResolvedPythonEnv,
fs_cache::{delete_cache_file, get_cache_from_file, store_cache_in_file},
};
lazy_static! {
static ref CACHE: CacheImpl = CacheImpl::new(None);
}
pub trait CacheEntry: Send + Sync {
fn get(&self) -> Option<ResolvedPythonEnv>;
fn store(&self, environment: ResolvedPythonEnv);
fn track_symlinks(&self, symlinks: Vec<PathBuf>);
}
pub fn clear_cache() -> io::Result<()> {
CACHE.clear()
}
pub fn create_cache(executable: PathBuf) -> Arc<Mutex<Box<dyn CacheEntry>>> {
CACHE.create_cache(executable)
}
pub fn get_cache_directory() -> Option<PathBuf> {
CACHE.get_cache_directory()
}
pub fn set_cache_directory(cache_dir: PathBuf) {
CACHE.set_cache_directory(cache_dir)
}
pub type LockableCacheEntry = Arc<Mutex<Box<dyn CacheEntry>>>;
/// Cache of Interpreter details for a given executable.
/// Uses in memory cache as well as a file cache as backing store.
struct CacheImpl {
cache_dir: Arc<Mutex<Option<PathBuf>>>,
locks: Mutex<HashMap<PathBuf, LockableCacheEntry>>,
}
impl CacheImpl {
fn new(cache_dir: Option<PathBuf>) -> CacheImpl {
CacheImpl {
cache_dir: Arc::new(Mutex::new(cache_dir)),
locks: Mutex::new(HashMap::<PathBuf, LockableCacheEntry>::new()),
}
}
fn get_cache_directory(&self) -> Option<PathBuf> {
self.cache_dir
.lock()
.expect("cache_dir mutex poisoned")
.clone()
}
/// Once a cache directory has been set, you cannot change it.
/// No point supporting such a scenario.
fn set_cache_directory(&self, cache_dir: PathBuf) {
if let Some(cache_dir) = self
.cache_dir
.lock()
.expect("cache_dir mutex poisoned")
.clone()
{
warn!(
"Cache directory has already been set to {:?}. Cannot change it now.",
cache_dir
);
return;
}
trace!("Setting cache directory to {:?}", cache_dir);
self.cache_dir
.lock()
.expect("cache_dir mutex poisoned")
.replace(cache_dir);
}
fn clear(&self) -> io::Result<()> {
trace!("Clearing cache");
self.locks.lock().expect("locks mutex poisoned").clear();
if let Some(cache_directory) = self
.cache_dir
.lock()
.expect("cache_dir mutex poisoned")
.clone()
{
std::fs::remove_dir_all(cache_directory)
} else {
Ok(())
}
}
fn create_cache(&self, executable: PathBuf) -> LockableCacheEntry {
let cache_directory = self
.cache_dir
.lock()
.expect("cache_dir mutex poisoned")
.clone();
match self
.locks
.lock()
.expect("locks mutex poisoned")
.entry(executable.clone())
{
Entry::Occupied(lock) => lock.get().clone(),
Entry::Vacant(lock) => {
let cache = Box::new(CacheEntryImpl::create(cache_directory.clone(), executable))
as Box<dyn CacheEntry + 'static>;
lock.insert(Arc::new(Mutex::new(cache))).clone()
}
}
}
}
/// Represents a file path with its modification time and optional creation time.
/// Creation time (ctime) is optional because many Linux filesystems (ext4, etc.)
/// don't support file creation time, causing metadata.created() to return Err.
/// See: https://github.com/microsoft/python-environment-tools/issues/223
type FilePathWithMTimeCTime = (PathBuf, SystemTime, Option<SystemTime>);
struct CacheEntryImpl {
cache_directory: Option<PathBuf>,
executable: PathBuf,
envoronment: Arc<Mutex<Option<ResolvedPythonEnv>>>,
/// List of known symlinks to this executable.
symlinks: Arc<Mutex<Vec<FilePathWithMTimeCTime>>>,
}
impl CacheEntryImpl {
pub fn create(cache_directory: Option<PathBuf>, executable: PathBuf) -> impl CacheEntry {
CacheEntryImpl {
cache_directory,
executable,
envoronment: Arc::new(Mutex::new(None)),
symlinks: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn verify_in_memory_cache(&self) {
// Check if any of the exes have changed since we last cached this.
for symlink_info in self
.symlinks
.lock()
.expect("symlinks mutex poisoned")
.iter()
{
if let Ok(metadata) = symlink_info.0.metadata() {
let mtime_changed = metadata.modified().ok() != Some(symlink_info.1);
// Only check ctime if we have it stored (may be None on Linux)
let ctime_changed = match symlink_info.2 {
Some(stored_ctime) => metadata.created().ok() != Some(stored_ctime),
None => false, // Can't check ctime if we don't have it
};
if mtime_changed || ctime_changed {
trace!(
"Symlink {:?} has changed since we last cached it. original mtime & ctime {:?}, {:?}, current mtime & ctime {:?}, {:?}",
symlink_info.0,
symlink_info.1,
symlink_info.2,
metadata.modified().ok(),
metadata.created().ok()
);
self.envoronment
.lock()
.expect("envoronment mutex poisoned")
.take();
if let Some(cache_directory) = &self.cache_directory {
delete_cache_file(cache_directory, &self.executable);
}
}
}
}
}
}
impl CacheEntry for CacheEntryImpl {
fn get(&self) -> Option<ResolvedPythonEnv> {
self.verify_in_memory_cache();
// New scope to drop lock immediately after we have the value.
{
if let Some(env) = self
.envoronment
.lock()
.expect("envoronment mutex poisoned")
.clone()
{
return Some(env);
}
}
if let Some(ref cache_directory) = self.cache_directory {
let (env, mut symlinks) = get_cache_from_file(cache_directory, &self.executable)?;
self.envoronment
.lock()
.expect("envoronment mutex poisoned")
.replace(env.clone());
let mut locked_symlinks = self.symlinks.lock().expect("symlinks mutex poisoned");
locked_symlinks.clear();
locked_symlinks.append(&mut symlinks);
Some(env)
} else {
None
}
}
fn store(&self, environment: ResolvedPythonEnv) {
// Get hold of the mtimes and ctimes of the symlinks.
let mut symlinks = vec![];
for symlink in environment.symlinks.clone().unwrap_or_default().iter() {
if let Ok(metadata) = symlink.metadata() {
// We require mtime, but ctime is optional (not available on all Linux filesystems)
// See: https://github.com/microsoft/python-environment-tools/issues/223
if let Ok(modified) = metadata.modified() {
let created = metadata.created().ok(); // May be None on Linux
symlinks.push((symlink.clone(), modified, created));
}
}
}
symlinks.sort();
symlinks.dedup();
{
let mut locked_symlinks = self.symlinks.lock().expect("symlinks mutex poisoned");
locked_symlinks.clear();
locked_symlinks.append(&mut symlinks.clone());
}
self.envoronment
.lock()
.expect("envoronment mutex poisoned")
.replace(environment.clone());
trace!("Caching interpreter info for {:?}", self.executable);
if let Some(ref cache_directory) = self.cache_directory {
store_cache_in_file(cache_directory, &self.executable, &environment, symlinks)
}
}
fn track_symlinks(&self, symlinks: Vec<PathBuf>) {
self.verify_in_memory_cache();
// If we have already seen this symlink, then we do not need to do anything.
let known_symlinks: HashSet<PathBuf> = self
.symlinks
.lock()
.expect("symlinks mutex poisoned")
.clone()
.iter()
.map(|x| x.0.clone())
.collect();
if symlinks.iter().all(|x| known_symlinks.contains(x)) {
return;
}
if let Some(ref cache_directory) = self.cache_directory {
if let Some((mut env, _)) = get_cache_from_file(cache_directory, &self.executable) {
let mut all_symlinks = vec![];
all_symlinks.append(&mut env.symlinks.clone().unwrap_or_default());
all_symlinks.append(&mut symlinks.clone());
all_symlinks.sort();
all_symlinks.dedup();
// Chech whether the details in the cache are the same as the ones we are about to cache.
env.symlinks = Some(all_symlinks);
trace!("Updating cache for {:?} with new symlinks", self.executable);
self.store(env);
} else {
// Unlikely scenario.
}
}
}
}