-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathcache.rs
More file actions
232 lines (203 loc) · 7.82 KB
/
cache.rs
File metadata and controls
232 lines (203 loc) · 7.82 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
// 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().unwrap().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().unwrap().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().unwrap().replace(cache_dir);
}
fn clear(&self) -> io::Result<()> {
trace!("Clearing cache");
self.locks.lock().unwrap().clear();
if let Some(cache_directory) = self.cache_dir.lock().unwrap().clone() {
std::fs::remove_dir_all(cache_directory)
} else {
Ok(())
}
}
fn create_cache(&self, executable: PathBuf) -> LockableCacheEntry {
let cache_directory = self.cache_dir.lock().unwrap().clone();
match self.locks.lock().unwrap().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()
}
}
}
}
type FilePathWithMTimeCTime = (PathBuf, SystemTime, 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().unwrap().iter() {
if let Ok(metadata) = symlink_info.0.metadata() {
if metadata.modified().ok() != Some(symlink_info.1)
|| metadata.created().ok() != Some(symlink_info.2)
{
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().unwrap().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().unwrap().clone() {
return Some(env);
}
}
if let Some(ref cache_directory) = self.cache_directory {
let (env, symlinks) = get_cache_from_file(cache_directory, &self.executable)?;
self.envoronment.lock().unwrap().replace(env.clone());
self.symlinks.lock().unwrap().clear();
self.symlinks.lock().unwrap().append(&mut symlinks.clone());
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 only care if we have the information
if let (Some(modified), Some(created)) =
(metadata.modified().ok(), metadata.created().ok())
{
symlinks.push((symlink.clone(), modified, created));
}
}
}
symlinks.sort();
symlinks.dedup();
self.symlinks.lock().unwrap().clear();
self.symlinks.lock().unwrap().append(&mut symlinks.clone());
self.envoronment
.lock()
.unwrap()
.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()
.unwrap()
.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.
}
}
}
}