-
Notifications
You must be signed in to change notification settings - Fork 137
/
sync.rs
558 lines (504 loc) · 19.4 KB
/
sync.rs
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
use crate::{
prefix::Prefix,
progress::{default_progress_style, finished_progress_style, global_multi_progress},
project::Project,
};
use anyhow::Context;
use clap::Parser;
use futures::{future::ready, stream, FutureExt, StreamExt, TryFutureExt, TryStreamExt};
use indicatif::ProgressBar;
use itertools::Itertools;
use rattler::{
install::{link_package, InstallDriver, InstallOptions, Transaction, TransactionOperation},
package_cache::PackageCache,
};
use rattler_conda_types::{
conda_lock::{
self,
builder::LockFileBuilder,
builder::{LockedPackage, LockedPackages},
CondaLock, PackageHashes, VersionConstraint,
},
ChannelConfig, MatchSpec, NamelessMatchSpec, PackageRecord, Platform, PrefixRecord,
RepoDataRecord, Version,
};
use rattler_repodata_gateway::sparse::SparseRepoData;
use rattler_solve::{LibsolvRepoData, SolverBackend};
use reqwest::Client;
use std::{
collections::HashSet,
ffi::OsStr,
io::ErrorKind,
path::{Path, PathBuf},
str::FromStr,
time::Duration,
};
/// Adds a dependency to the project
#[derive(Parser, Debug)]
pub struct Args {}
// TODO: I dont like this command, if it is at all possible it would be so much better when this
// command is run when needed. E.g. have a cheap way to determine if the environment is up-to-date,
// if not, update it.
pub async fn execute(_: Args) -> anyhow::Result<()> {
let project = Project::discover()?;
let platforms = project.platforms()?;
let dependencies = project.dependencies()?;
// Load the lockfile or create a dummy one
let lock_file_path = project.lock_file_path();
let lock_file = if lock_file_path.is_file() {
CondaLock::from_path(&lock_file_path)?
} else {
LockFileBuilder::default().build()?
};
// Check if the lock file is up to date with the requirements in the project.
let specs_out_of_date = dependencies.iter().any(|(dep_name, constraints)| {
!lock_file.package.iter().any(|locked_package| {
locked_dependency_satisfies(locked_package, dep_name, constraints)
})
});
let platforms_out_of_date =
HashSet::<Platform>::from_iter(lock_file.metadata.platforms.iter().copied())
!= HashSet::from_iter(platforms.into_iter());
let channels_out_of_date = false; // TODO:
let lock_file = if platforms_out_of_date || channels_out_of_date || specs_out_of_date {
update_lock_file(&project, lock_file).await?
} else {
lock_file
};
// Check to see if the environment is out of date or not.
let prefix = Prefix::new(project.root().join(".pax/env"))?;
let current_packages = prefix
.find_installed_packages(None)
.await
.context("failed to determine the currently installed packages")?;
// TODO: Stop doing anything if the currently installed packages already match our lock file
let current_platform = Platform::current();
let required_packages = lock_file
.package
.into_iter()
.filter(|pkg| pkg.platform == current_platform)
.map(|pkg| {
Ok(RepoDataRecord {
channel: String::new(),
file_name: Path::new(pkg.url.path())
.file_name()
.and_then(OsStr::to_str)
.ok_or_else(|| {
anyhow::anyhow!("failed to determine file name from {}", &pkg.url)
})?
.to_owned(),
url: pkg.url,
package_record: PackageRecord {
arch: None,
build: pkg.build.unwrap_or_default(),
build_number: 0,
constrains: vec![],
depends: pkg
.dependencies
.into_iter()
.map(|(pkg_name, spec)| format!("{} {}", pkg_name, spec))
.collect(),
features: None,
legacy_bz2_md5: None,
legacy_bz2_size: None,
license: None,
license_family: None,
md5: match &pkg.hash {
PackageHashes::Md5(md5) => Some(*md5),
PackageHashes::Sha256(_) => None,
PackageHashes::Md5Sha256(md5, _) => Some(*md5),
},
name: pkg.name,
noarch: Default::default(),
platform: None,
sha256: match &pkg.hash {
PackageHashes::Md5(_) => None,
PackageHashes::Sha256(sha256) => Some(*sha256),
PackageHashes::Md5Sha256(_, sha256) => Some(*sha256),
},
size: None,
subdir: "".to_string(),
timestamp: None,
track_features: vec![],
version: Version::from_str(&pkg.version)?,
},
})
})
.collect::<anyhow::Result<Vec<_>>>()?;
// Construct a transaction to be able to update the environment to the correct versions of all
// packages.
let transaction = rattler::install::Transaction::from_current_and_desired(
current_packages,
required_packages,
current_platform,
)?;
if !transaction.operations.is_empty() {
// Execute the operations that are returned by the solver.
execute_transaction(
transaction,
prefix.root().to_path_buf(),
rattler::default_cache_dir()?,
Client::default(),
)
.await?;
println!(
"{} Successfully updated the environment",
console::style(console::Emoji("✔", "")).green(),
);
} else {
println!(
"{} Already up to date",
console::style(console::Emoji("✔", "")).green(),
);
}
Ok(())
}
/// Returns true if the specified [`conda_lock::LockedDependency`] satisfies the given match spec.
/// TODO: Move this back to rattler.
/// TODO: Make this more elaborate to include all properties of MatchSpec
fn locked_dependency_satisfies(
locked_package: &conda_lock::LockedDependency,
name: &str,
spec: &NamelessMatchSpec,
) -> bool {
// Check if the name of the package matches
if locked_package.name.as_str() != name {
return false;
}
// Check if the version matches
if let Some(version_spec) = &spec.version {
let v = match Version::from_str(&locked_package.version) {
Err(_) => return false,
Ok(v) => v,
};
if !version_spec.matches(&v) {
return false;
}
}
// Check if the build string matches
match (spec.build.as_ref(), &locked_package.build) {
(Some(build_spec), Some(build)) => {
if !build_spec.matches(build) {
return false;
}
}
(Some(_), None) => return false,
_ => {}
}
true
}
async fn update_lock_file(
project: &Project,
_existing_lock_file: CondaLock,
) -> anyhow::Result<CondaLock> {
let platforms = project.platforms()?;
let dependencies = project.dependencies()?;
// Extract the package names from the dependencies
let package_names = dependencies.keys().collect_vec();
// Get the repodata for the project
let sparse_repo_data = project.fetch_sparse_repodata().await?;
// Construct a conda lock file
let channels = project
.channels(&ChannelConfig::default())?
.into_iter()
.map(|channel| conda_lock::Channel::from(channel.base_url().to_string()));
let match_specs = dependencies
.iter()
.map(|(name, constraint)| MatchSpec::from_nameless(constraint.clone(), Some(name.clone())))
.collect_vec();
let mut builder = LockFileBuilder::new(channels, platforms.clone(), match_specs.clone());
for platform in platforms {
// Get the repodata for the current platform and for NoArch
let platform_sparse_repo_data = sparse_repo_data.iter().filter(|sparse| {
sparse.subdir() == platform.as_str() || sparse.subdir() == Platform::NoArch.as_str()
});
// Load only records we need for this platform
let available_packages = SparseRepoData::load_records_recursive(
platform_sparse_repo_data,
package_names.iter().copied(),
)?;
// Construct a solver task that we can start solving.
let task = rattler_solve::SolverTask {
specs: match_specs.clone(),
available_packages: available_packages
.iter()
.map(|records| LibsolvRepoData::from_records(records)),
// TODO: All these things.
locked_packages: vec![],
pinned_packages: vec![],
virtual_packages: vec![],
};
// Solve the task
let records = rattler_solve::LibsolvBackend.solve(task)?;
let mut locked_packages = LockedPackages::new(platform);
for record in records {
locked_packages = locked_packages.add_locked_package(LockedPackage {
name: record.package_record.name,
version: record.package_record.version.to_string(),
build_string: record.package_record.build.to_string(),
url: record.url,
package_hashes: match (record.package_record.sha256, record.package_record.md5) {
(Some(sha256), Some(md5)) => PackageHashes::Md5Sha256(md5, sha256),
(Some(sha256), None) => PackageHashes::Sha256(sha256),
(None, Some(md5)) => PackageHashes::Md5(md5),
_ => unreachable!("package without any hash??"),
},
dependency_list: record
.package_record
.depends
.iter()
.map(|dep| {
MatchSpec::from_str(dep)
.map_err(anyhow::Error::from)
.and_then(|spec| match &spec.name {
Some(name) => Ok((
name.to_owned(),
VersionConstraint::from(NamelessMatchSpec::from(spec)),
)),
None => Err(anyhow::anyhow!(
"dependency matchspec missing a name '{}'",
dep
)),
})
})
.collect::<Result<_, _>>()?,
optional: None,
});
}
builder = builder.add_locked_packages(locked_packages);
}
let conda_lock = builder.build()?;
// Write the conda lock to disk
conda_lock.to_path(&project.lock_file_path())?;
Ok(conda_lock)
}
/// Executes the transaction on the given environment.
async fn execute_transaction(
transaction: Transaction<PrefixRecord, RepoDataRecord>,
target_prefix: PathBuf,
cache_dir: PathBuf,
download_client: Client,
) -> anyhow::Result<()> {
// Open the package cache
let package_cache = PackageCache::new(cache_dir.join("pkgs"));
// Create an install driver which helps limit the number of concurrent fileystem operations
let install_driver = InstallDriver::default();
// Define default installation options.
let install_options = InstallOptions {
python_info: transaction.python_info.clone(),
platform: Some(transaction.platform),
..Default::default()
};
// Create a progress bars for downloads.
let multi_progress = global_multi_progress();
let total_packages_to_download = transaction
.operations
.iter()
.filter(|op| op.record_to_install().is_some())
.count();
let download_pb = if total_packages_to_download > 0 {
let pb = multi_progress.add(
indicatif::ProgressBar::new(total_packages_to_download as u64)
.with_style(default_progress_style())
.with_finish(indicatif::ProgressFinish::WithMessage("Done!".into()))
.with_prefix("downloading"),
);
pb.enable_steady_tick(Duration::from_millis(100));
Some(pb)
} else {
None
};
// Create a progress bar to track all operations.
let total_operations = transaction.operations.len();
let link_pb = multi_progress.add(
indicatif::ProgressBar::new(total_operations as u64)
.with_style(default_progress_style())
.with_finish(indicatif::ProgressFinish::WithMessage("Done!".into()))
.with_prefix("linking"),
);
link_pb.enable_steady_tick(Duration::from_millis(100));
// Perform all transactions operations in parallel.
stream::iter(transaction.operations)
.map(Ok)
.try_for_each_concurrent(50, |op| {
let target_prefix = target_prefix.clone();
let download_client = download_client.clone();
let package_cache = &package_cache;
let install_driver = &install_driver;
let download_pb = download_pb.as_ref();
let link_pb = &link_pb;
let install_options = &install_options;
async move {
execute_operation(
&target_prefix,
download_client,
package_cache,
install_driver,
download_pb,
link_pb,
op,
install_options,
)
.await
}
})
.await?;
Ok(())
}
/// Executes a single operation of a transaction on the environment.
/// TODO: Move this into an object or something.
#[allow(clippy::too_many_arguments)]
async fn execute_operation(
target_prefix: &Path,
download_client: Client,
package_cache: &PackageCache,
install_driver: &InstallDriver,
download_pb: Option<&ProgressBar>,
link_pb: &ProgressBar,
op: TransactionOperation<PrefixRecord, RepoDataRecord>,
install_options: &InstallOptions,
) -> anyhow::Result<()> {
// Determine the package to install
let install_record = op.record_to_install();
let remove_record = op.record_to_remove();
// Create a future to remove the existing package
let remove_future = if let Some(remove_record) = remove_record {
remove_package_from_environment(target_prefix, remove_record).left_future()
} else {
ready(Ok(())).right_future()
};
// Create a future to download the package
let cached_package_dir_fut = if let Some(install_record) = install_record {
async {
// Make sure the package is available in the package cache.
let result = package_cache
.get_or_fetch_from_url(
&install_record.package_record,
install_record.url.clone(),
download_client.clone(),
)
.map_ok(|cache_dir| Some((install_record.clone(), cache_dir)))
.map_err(anyhow::Error::from)
.await;
// Increment the download progress bar.
if let Some(pb) = download_pb {
pb.inc(1);
if pb.length() == Some(pb.position()) {
pb.set_style(finished_progress_style());
}
}
result
}
.left_future()
} else {
ready(Ok(None)).right_future()
};
// Await removal and downloading concurrently
let (_, install_package) = tokio::try_join!(remove_future, cached_package_dir_fut)?;
// If there is a package to install, do that now.
if let Some((record, package_dir)) = install_package {
install_package_to_environment(
target_prefix,
package_dir,
record.clone(),
install_driver,
install_options,
)
.await?;
}
// Increment the link progress bar since we finished a step!
link_pb.inc(1);
if link_pb.length() == Some(link_pb.position()) {
link_pb.set_style(finished_progress_style());
}
Ok(())
}
/// Install a package into the environment and write a `conda-meta` file that contains information
/// about how the file was linked.
async fn install_package_to_environment(
target_prefix: &Path,
package_dir: PathBuf,
repodata_record: RepoDataRecord,
install_driver: &InstallDriver,
install_options: &InstallOptions,
) -> anyhow::Result<()> {
// Link the contents of the package into our environment. This returns all the paths that were
// linked.
let paths = link_package(
&package_dir,
target_prefix,
install_driver,
install_options.clone(),
)
.await?;
// Construct a PrefixRecord for the package
let prefix_record = PrefixRecord {
repodata_record,
package_tarball_full_path: None,
extracted_package_dir: Some(package_dir),
files: paths
.iter()
.map(|entry| entry.relative_path.clone())
.collect(),
paths_data: paths.into(),
// TODO: Retrieve the requested spec for this package from the request
requested_spec: None,
// TODO: What to do with this?
link: None,
};
// Create the conda-meta directory if it doesnt exist yet.
let target_prefix = target_prefix.to_path_buf();
match tokio::task::spawn_blocking(move || {
let conda_meta_path = target_prefix.join("conda-meta");
std::fs::create_dir_all(&conda_meta_path)?;
// Write the conda-meta information
let pkg_meta_path = conda_meta_path.join(format!(
"{}-{}-{}.json",
prefix_record.repodata_record.package_record.name,
prefix_record.repodata_record.package_record.version,
prefix_record.repodata_record.package_record.build
));
prefix_record.write_to_path(pkg_meta_path, true)
})
.await
{
Ok(result) => Ok(result?),
Err(err) => {
if let Ok(panic) = err.try_into_panic() {
std::panic::resume_unwind(panic);
}
// The operation has been cancelled, so we can also just ignore everything.
Ok(())
}
}
}
/// Completely remove the specified package from the environment.
async fn remove_package_from_environment(
target_prefix: &Path,
package: &PrefixRecord,
) -> anyhow::Result<()> {
// TODO: Take into account any clobbered files, they need to be restored.
// TODO: Can we also delete empty directories?
// Remove all entries
for paths in package.paths_data.paths.iter() {
match tokio::fs::remove_file(target_prefix.join(&paths.relative_path)).await {
Ok(_) => {}
Err(e) if e.kind() == ErrorKind::NotFound => {
// Simply ignore if the file is already gone.
}
Err(e) => {
return Err(e)
.with_context(|| format!("failed to delete {}", paths.relative_path.display()))
}
}
}
// Remove the conda-meta file
let conda_meta_path = target_prefix.join("conda-meta").join(format!(
"{}-{}-{}.json",
package.repodata_record.package_record.name,
package.repodata_record.package_record.version,
package.repodata_record.package_record.build
));
tokio::fs::remove_file(conda_meta_path).await?;
Ok(())
}