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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
use {
super::{
binary::{LibpythonLinkMode, PythonBinaryBuilder},
config::PyembedPythonInterpreterConfig,
standalone_distribution::StandaloneDistribution,
},
crate::{environment::Environment, python_distributions::PYTHON_DISTRIBUTIONS},
anyhow::{anyhow, Context, Result},
fs2::FileExt,
log::info,
python_packaging::{
bytecode::PythonBytecodeCompiler, module_util::PythonModuleSuffixes,
policy::PythonPackagingPolicy, resource::PythonResource,
},
sha2::{Digest, Sha256},
simple_file_manifest::FileEntry,
std::{
collections::HashMap,
fmt::{Display, Formatter},
fs,
fs::{create_dir_all, File},
io::Read,
ops::DerefMut,
path::{Path, PathBuf},
sync::{Arc, Mutex},
},
tugger_common::http::get_http_client,
url::Url,
uuid::Uuid,
};
#[derive(Clone, Debug, PartialEq)]
pub enum BinaryLibpythonLinkMode {
Default,
Static,
Dynamic,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub enum PythonDistributionLocation {
Local { local_path: String, sha256: String },
Url { url: String, sha256: String },
}
impl std::fmt::Display for PythonDistributionLocation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Local { local_path, sha256 } => {
write!(f, "{} (sha256={})", local_path, sha256)
}
Self::Url { url, sha256 } => {
write!(f, "{} (sha256={})", url, sha256)
}
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct PythonDistributionRecord {
pub python_major_minor_version: String,
pub location: PythonDistributionLocation,
pub target_triple: String,
pub supports_prebuilt_extension_modules: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub struct AppleSdkInfo {
pub canonical_name: String,
pub platform: String,
pub version: String,
pub deployment_target: String,
}
pub trait PythonDistribution {
fn clone_trait(&self) -> Arc<dyn PythonDistribution>;
fn target_triple(&self) -> &str;
fn compatible_host_triples(&self) -> Vec<String>;
fn python_exe_path(&self) -> &Path;
fn python_version(&self) -> &str;
fn python_major_minor_version(&self) -> String;
fn python_implementation(&self) -> &str;
fn python_implementation_short(&self) -> &str;
fn python_tag(&self) -> &str;
fn python_abi_tag(&self) -> Option<&str>;
fn python_platform_tag(&self) -> &str;
fn python_platform_compatibility_tag(&self) -> &str;
fn cache_tag(&self) -> &str;
fn python_module_suffixes(&self) -> Result<PythonModuleSuffixes>;
fn python_config_vars(&self) -> &HashMap<String, String>;
fn stdlib_test_packages(&self) -> Vec<String>;
fn apple_sdk_info(&self) -> Option<&AppleSdkInfo>;
fn create_bytecode_compiler(
&self,
env: &Environment,
) -> Result<Box<dyn PythonBytecodeCompiler>>;
fn create_packaging_policy(&self) -> Result<PythonPackagingPolicy>;
fn create_python_interpreter_config(&self) -> Result<PyembedPythonInterpreterConfig>;
#[allow(clippy::too_many_arguments)]
fn as_python_executable_builder(
&self,
host_triple: &str,
target_triple: &str,
name: &str,
libpython_link_mode: BinaryLibpythonLinkMode,
policy: &PythonPackagingPolicy,
config: &PyembedPythonInterpreterConfig,
host_distribution: Option<Arc<dyn PythonDistribution>>,
) -> Result<Box<dyn PythonBinaryBuilder>>;
fn python_resources<'a>(&self) -> Vec<PythonResource<'a>>;
fn ensure_pip(&self) -> Result<PathBuf>;
fn resolve_distutils(
&self,
libpython_link_mode: LibpythonLinkMode,
dest_dir: &Path,
extra_python_paths: &[&Path],
) -> Result<HashMap<String, String>>;
fn supports_in_memory_shared_library_loading(&self) -> bool;
fn is_stdlib_test_package(&self, name: &str) -> bool {
for package in self.stdlib_test_packages() {
let prefix = format!("{}.", package);
if name == package || name.starts_with(&prefix) {
return true;
}
}
false
}
fn tcl_files(&self) -> Result<Vec<(PathBuf, FileEntry)>>;
fn tcl_library_path_directory(&self) -> Option<String>;
}
pub struct DistributionExtractLock {
file: std::fs::File,
}
impl DistributionExtractLock {
pub fn new(extract_dir: &Path) -> Result<Self> {
let lock_path = extract_dir
.parent()
.unwrap()
.join("distribution-extract-lock");
let file = File::create(&lock_path)
.context(format!("could not create {}", lock_path.display()))?;
file.lock_exclusive()
.context(format!("failed to obtain lock for {}", lock_path.display()))?;
Ok(DistributionExtractLock { file })
}
}
impl Drop for DistributionExtractLock {
fn drop(&mut self) {
self.file.unlock().unwrap();
}
}
fn sha256_path(path: &Path) -> Vec<u8> {
let mut hasher = Sha256::new();
let fh = File::open(&path).unwrap();
let mut reader = std::io::BufReader::new(fh);
let mut buffer = [0; 32768];
loop {
let count = reader.read(&mut buffer).expect("error reading");
if count == 0 {
break;
}
hasher.update(&buffer[..count]);
}
hasher.finalize().to_vec()
}
pub fn download_distribution(url: &str, sha256: &str, cache_dir: &Path) -> Result<PathBuf> {
let expected_hash = hex::decode(sha256)?;
let u = Url::parse(url)?;
let basename = u
.path_segments()
.expect("cannot be base path")
.last()
.unwrap()
.to_string();
let cache_path = cache_dir.join(basename);
if cache_path.exists() {
let file_hash = sha256_path(&cache_path);
if file_hash == expected_hash {
return Ok(cache_path);
}
}
let mut data: Vec<u8> = Vec::new();
println!("downloading {}", u);
let client = get_http_client()?;
let mut response = client.get(u.as_str()).send()?;
response.read_to_end(&mut data)?;
let mut hasher = Sha256::new();
hasher.update(&data);
let url_hash = hasher.finalize().to_vec();
if url_hash != expected_hash {
return Err(anyhow!("sha256 of Python distribution does not validate"));
}
let mut temp_cache_path = cache_path.clone();
temp_cache_path.set_file_name(format!("{}.tmp", Uuid::new_v4()));
fs::write(&temp_cache_path, data).context("unable to write distribution file")?;
fs::rename(&temp_cache_path, &cache_path)
.or_else(|e| -> Result<()> {
fs::remove_file(&temp_cache_path)
.context("unable to remove temporary distribution file")?;
if cache_path.exists() {
download_distribution(url, sha256, cache_dir)?;
return Ok(());
}
Err(e.into())
})
.context("unable to rename downloaded distribution file")?;
Ok(cache_path)
}
pub fn copy_local_distribution(path: &Path, sha256: &str, cache_dir: &Path) -> Result<PathBuf> {
let expected_hash = hex::decode(sha256)?;
let basename = path.file_name().unwrap().to_str().unwrap().to_string();
let cache_path = cache_dir.join(basename);
if cache_path.exists() {
let file_hash = sha256_path(&cache_path);
if file_hash == expected_hash {
println!(
"existing {} passes SHA-256 integrity check",
cache_path.display()
);
return Ok(cache_path);
}
}
let source_hash = sha256_path(path);
if source_hash != expected_hash {
return Err(anyhow!("sha256 of Python distribution does not validate"));
}
println!("copying {}", path.display());
std::fs::copy(path, &cache_path)?;
Ok(cache_path)
}
pub fn resolve_python_distribution_archive(
dist: &PythonDistributionLocation,
cache_dir: &Path,
) -> Result<PathBuf> {
if !cache_dir.exists() {
create_dir_all(cache_dir).unwrap();
}
match dist {
PythonDistributionLocation::Local { local_path, sha256 } => {
let p = PathBuf::from(local_path);
copy_local_distribution(&p, sha256, cache_dir)
}
PythonDistributionLocation::Url { url, sha256 } => {
download_distribution(url, sha256, cache_dir)
}
}
}
pub fn resolve_python_distribution_from_location(
location: &PythonDistributionLocation,
distributions_dir: &Path,
) -> Result<(PathBuf, PathBuf)> {
info!("resolving Python distribution {}", location);
let path = resolve_python_distribution_archive(location, distributions_dir)?;
info!("Python distribution available at {}", path.display());
let distribution_hash = match location {
PythonDistributionLocation::Local { sha256, .. } => sha256,
PythonDistributionLocation::Url { sha256, .. } => sha256,
};
let distribution_path = distributions_dir.join(format!("python.{}", &distribution_hash[0..12]));
Ok((path, distribution_path))
}
#[allow(clippy::enum_variant_names)]
#[derive(Debug, PartialEq)]
pub enum DistributionFlavor {
Standalone,
StandaloneStatic,
StandaloneDynamic,
}
impl Default for DistributionFlavor {
fn default() -> Self {
DistributionFlavor::Standalone
}
}
impl Display for DistributionFlavor {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Standalone => "standalone",
Self::StandaloneStatic => "standalone-static",
Self::StandaloneDynamic => "standalone-dynamic",
})
}
}
impl TryFrom<&str> for DistributionFlavor {
type Error = String;
fn try_from(value: &str) -> Result<Self, Self::Error> {
match value {
"standalone" => Ok(Self::Standalone),
"standalone_static" | "standalone-static" => Ok(Self::StandaloneStatic),
"standalone_dynamic" | "standalone-dynamic" => Ok(Self::StandaloneDynamic),
_ => Err(format!("distribution flavor {} not recognized", value)),
}
}
}
type DistributionCacheKey = (PathBuf, PythonDistributionLocation);
type DistributionCacheValue = Arc<Mutex<Option<Arc<StandaloneDistribution>>>>;
#[derive(Debug)]
pub struct DistributionCache {
cache: Mutex<HashMap<DistributionCacheKey, DistributionCacheValue>>,
default_dest_dir: Option<PathBuf>,
}
impl DistributionCache {
pub fn new(default_dest_dir: Option<&Path>) -> Self {
Self {
cache: Mutex::new(HashMap::new()),
default_dest_dir: default_dest_dir.map(|x| x.to_path_buf()),
}
}
pub fn resolve_distribution(
&self,
location: &PythonDistributionLocation,
dest_dir: Option<&Path>,
) -> Result<Arc<StandaloneDistribution>> {
let dest_dir = if let Some(p) = dest_dir {
p
} else if let Some(p) = &self.default_dest_dir {
p
} else {
return Err(anyhow!("no destination directory available"));
};
let key = (dest_dir.to_path_buf(), location.clone());
let entry = {
let mut lock = self
.cache
.lock()
.map_err(|e| anyhow!("cannot obtain distribution cache lock: {}", e))?;
if let Some(value) = lock.get(&key) {
value.clone()
} else {
let value = Arc::new(Mutex::new(None));
lock.insert(key.clone(), value.clone());
value
}
};
let mut lock = entry
.lock()
.map_err(|e| anyhow!("cannot obtain distribution lock: {}", e))?;
let value = lock.deref_mut();
if let Some(dist) = value {
Ok(dist.clone())
} else {
let dist = Arc::new(StandaloneDistribution::from_location(location, dest_dir)?);
lock.replace(dist.clone());
Ok(dist)
}
}
pub fn host_distribution(
&self,
python_major_minor_version: Option<&str>,
dest_dir: Option<&Path>,
) -> Result<Arc<StandaloneDistribution>> {
let location = default_distribution_location(
&DistributionFlavor::Standalone,
crate::environment::default_target_triple(),
python_major_minor_version,
)
.context("resolving host distribution location")?;
self.resolve_distribution(&location, dest_dir)
.context("resolving host distribution from location")
}
}
#[allow(unused)]
pub fn resolve_distribution(
location: &PythonDistributionLocation,
dest_dir: &Path,
) -> Result<Box<dyn PythonDistribution>> {
Ok(
Box::new(StandaloneDistribution::from_location(location, dest_dir)?)
as Box<dyn PythonDistribution>,
)
}
pub fn default_distribution_location(
flavor: &DistributionFlavor,
target: &str,
python_major_minor_version: Option<&str>,
) -> Result<PythonDistributionLocation> {
let dist = PYTHON_DISTRIBUTIONS
.find_distribution(target, flavor, python_major_minor_version)
.ok_or_else(|| anyhow!("could not find default Python distribution for {}", target))?;
Ok(dist.location)
}
#[cfg(test)]
mod tests {
use {super::*, crate::testutil::*};
#[test]
fn test_all_standalone_distributions() -> Result<()> {
assert!(!get_all_standalone_distributions()?.is_empty());
Ok(())
}
}