forked from mamba-org/mamba
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.cpp
1420 lines (1246 loc) · 49.7 KB
/
transaction.cpp
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2019, QuantStack and Mamba Contributors
//
// Distributed under the terms of the BSD 3-Clause License.
//
// The full license is in the file LICENSE, distributed with this software.
#include <iostream>
#include <stack>
#include <thread>
#include "mamba/core/channel.hpp"
#include "mamba/core/context.hpp"
#include "mamba/core/transaction.hpp"
#include "mamba/core/link.hpp"
#include "mamba/core/match_spec.hpp"
#include "mamba/core/thread_utils.hpp"
#include "termcolor/termcolor.hpp"
extern "C"
{
#include "solv/selection.h"
}
namespace
{
bool need_pkg_download(const mamba::PackageInfo& pkg_info, mamba::MultiPackageCache& caches)
{
return caches.get_extracted_dir_path(pkg_info).empty()
&& caches.get_tarball_path(pkg_info).empty();
}
} // anonymouse namspace
namespace mamba
{
nlohmann::json solvable_to_json(Solvable* s)
{
return PackageInfo(s).json_record();
}
/********************************
* PackageDownloadExtractTarget *
********************************/
counting_semaphore DownloadExtractSemaphore::semaphore(0);
void DownloadExtractSemaphore::set_max(int value)
{
DownloadExtractSemaphore::semaphore.set_max(value);
}
static std::mutex lookup_checksum_mutex;
std::string lookup_checksum(Solvable* s, Id checksum_type)
{
Id unused;
std::lock_guard<std::mutex> lock(lookup_checksum_mutex);
std::string chksum = check_char(solvable_lookup_checksum(s, checksum_type, &unused));
return chksum;
}
PackageDownloadExtractTarget::PackageDownloadExtractTarget(Solvable* solvable)
: PackageDownloadExtractTarget(PackageInfo(solvable))
{
}
PackageDownloadExtractTarget::PackageDownloadExtractTarget(const PackageInfo& pkg_info)
: m_finished(false)
, m_package_info(pkg_info)
{
m_filename = pkg_info.fn;
m_channel = pkg_info.channel;
m_url = pkg_info.url;
m_name = pkg_info.name;
m_expected_size = pkg_info.size;
m_sha256 = pkg_info.sha256;
m_md5 = pkg_info.md5;
auto& ctx = Context::instance();
m_has_progress_bars = !(ctx.no_progress_bars || ctx.quiet || ctx.json);
}
void PackageDownloadExtractTarget::write_repodata_record(const fs::path& base_path)
{
fs::path repodata_record_path = base_path / "info" / "repodata_record.json";
fs::path index_path = base_path / "info" / "index.json";
nlohmann::json index, solvable_json;
std::ifstream index_file = open_ifstream(index_path);
index_file >> index;
solvable_json = m_package_info.json_record();
index.insert(solvable_json.cbegin(), solvable_json.cend());
if (index.find("size") == index.end() || index["size"] == 0)
{
index["size"] = fs::file_size(m_tarball_path);
}
std::ofstream repodata_record(repodata_record_path);
repodata_record << index.dump(4);
}
static std::mutex urls_txt_mutex;
void PackageDownloadExtractTarget::add_url()
{
std::lock_guard<std::mutex> lock(urls_txt_mutex);
std::ofstream urls_txt(m_cache_path / "urls.txt", std::ios::app);
urls_txt << m_url << std::endl;
}
void PackageDownloadExtractTarget::validate()
{
m_validation_result = VALIDATION_RESULT::VALID;
if (m_expected_size && size_t(m_target->downloaded_size) != m_expected_size)
{
LOG_ERROR << "File not valid: file size doesn't match expectation " << m_tarball_path
<< "\nExpected: " << m_expected_size
<< "\nActual: " << size_t(m_target->downloaded_size) << "\n";
if (m_has_progress_bars)
{
m_download_bar.set_postfix("validation failed");
m_download_bar.mark_as_completed();
}
Console::instance().print(m_filename + " tarball has incorrect size");
m_validation_result = SIZE_ERROR;
return;
}
interruption_point();
if (!m_sha256.empty())
{
auto sha256sum = validate::sha256sum(m_tarball_path);
if (m_sha256 != sha256sum)
{
m_validation_result = SHA256_ERROR;
if (m_has_progress_bars)
{
m_download_bar.set_postfix("validation failed");
m_download_bar.mark_as_completed();
}
Console::instance().print(m_filename + " tarball has incorrect checksum");
LOG_ERROR << "File not valid: SHA256 sum doesn't match expectation "
<< m_tarball_path << "\nExpected: " << m_sha256
<< "\nActual: " << sha256sum << "\n";
}
return;
}
if (!m_md5.empty())
{
auto md5sum = validate::md5sum(m_tarball_path);
if (m_md5 != md5sum)
{
m_validation_result = MD5SUM_ERROR;
if (m_has_progress_bars)
{
m_download_bar.set_postfix("validation failed");
m_download_bar.mark_as_completed();
}
Console::instance().print(m_filename + " tarball has incorrect checksum");
LOG_ERROR << "File not valid: MD5 sum doesn't match expectation " << m_tarball_path
<< "\nExpected: " << m_md5 << "\nActual: " << md5sum << "\n";
}
}
}
std::function<void(ProgressBarRepr&)> PackageDownloadExtractTarget::extract_repr()
{
return [&](ProgressBarRepr& r) -> void {
if (r.progress_bar().started())
r.postfix.set_value("extracting");
else
r.postfix.set_value("extracted");
};
}
std::function<void(ProgressProxy&)> PackageDownloadExtractTarget::extract_progress_callback()
{
return [&](ProgressProxy& bar) -> void {
if (bar.started())
bar.set_progress(0, 1);
};
}
bool PackageDownloadExtractTarget::extract()
{
// Extracting is __not__ yet thread safe it seems...
interruption_point();
if (m_has_progress_bars)
m_extract_bar.start();
LOG_DEBUG << "Waiting for decompression " << m_tarball_path;
if (m_has_progress_bars)
m_extract_bar.update_progress(0, 1);
{
std::lock_guard<counting_semaphore> lock(DownloadExtractSemaphore::semaphore);
interruption_point();
LOG_DEBUG << "Decompressing '" << m_tarball_path.string() << "'";
fs::path extract_path;
try
{
std::string fn = m_filename;
if (ends_with(fn, ".tar.bz2"))
fn = fn.substr(0, fn.size() - 8);
else if (ends_with(fn, ".conda"))
fn = fn.substr(0, fn.size() - 6);
else
{
LOG_ERROR << "Unknown package format '" << m_filename << "'";
throw std::runtime_error("Unknown package format.");
}
// Be sure the first writable cache doesn't contain invalid extracted package
extract_path = m_cache_path / fn;
if (fs::exists(extract_path))
{
LOG_DEBUG << "Removing '" << extract_path.string()
<< "' before extracting it again";
remove_all(extract_path);
}
mamba::extract_subproc(m_tarball_path, extract_path);
// mamba::extract(m_tarball_path, extract_path);
interruption_point();
LOG_DEBUG << "Extracted to '" << extract_path.string() << "'";
write_repodata_record(extract_path);
add_url();
if (m_has_progress_bars)
{
m_extract_bar.set_full();
m_extract_bar.mark_as_completed();
}
}
catch (std::exception& e)
{
Console::instance().print(m_filename + " extraction failed");
LOG_ERROR << "Error when extracting package: " << e.what();
m_decompress_exception = e;
m_validation_result = VALIDATION_RESULT::EXTRACT_ERROR;
if (m_has_progress_bars)
{
m_extract_bar.set_postfix("extraction failed");
m_extract_bar.mark_as_completed();
}
return false;
}
}
return true;
}
bool PackageDownloadExtractTarget::extract_from_cache()
{
this->extract();
m_finished = true;
return true;
}
bool PackageDownloadExtractTarget::validate_extract()
{
using std::chrono::nanoseconds;
if (m_has_progress_bars)
{
m_extract_bar.start();
m_extract_bar.set_postfix("validating");
}
validate();
// Validation
if (m_validation_result != VALIDATION_RESULT::VALID)
{
if (m_has_progress_bars)
m_extract_bar.set_postfix("validation failed");
LOG_WARNING << "'" << m_tarball_path.string() << "' validation failed";
// abort here, but set finished to true
m_finished = true;
return true;
}
if (m_has_progress_bars)
m_extract_bar.set_postfix("validated");
LOG_DEBUG << "'" << m_tarball_path.string() << "' successfully validated";
bool result = this->extract();
m_finished = true;
return result;
}
bool PackageDownloadExtractTarget::finalize_callback()
{
if (m_has_progress_bars)
{
m_download_bar.repr().postfix.set_value("downloaded").deactivate();
m_download_bar.mark_as_completed();
}
LOG_INFO << "Download finished, validating '" << m_tarball_path.string() << "'";
thread v(&PackageDownloadExtractTarget::validate_extract, this);
v.detach();
return true;
}
bool PackageDownloadExtractTarget::finished()
{
return m_finished;
}
auto PackageDownloadExtractTarget::validation_result() const
{
return m_validation_result;
}
void PackageDownloadExtractTarget::clear_cache() const
{
fs::remove_all(m_tarball_path);
fs::path dest_dir = strip_package_extension(m_tarball_path);
if (fs::exists(dest_dir))
{
fs::remove_all(dest_dir);
}
}
const std::string& PackageDownloadExtractTarget::name() const
{
return m_name;
}
std::size_t PackageDownloadExtractTarget::expected_size() const
{
return m_expected_size;
}
// todo remove cache from this interface
DownloadTarget* PackageDownloadExtractTarget::target(MultiPackageCache& caches)
{
// tarball can be removed, it's fine if only the correct dest dir exists
// 1. If there is extracted cache, use it, otherwise next.
// 2. If there is valid tarball, extract it, otherwise next.
// 3. Run the full download pipeline.
fs::path extracted_cache = caches.get_extracted_dir_path(m_package_info);
if (extracted_cache.empty())
{
fs::path tarball_cache = caches.get_tarball_path(m_package_info);
// Compute the first writable cache and clean its status for the current package
caches.first_writable_cache(true).clear_query_cache(m_package_info);
m_cache_path = caches.first_writable_path();
if (m_has_progress_bars)
{
m_extract_bar = Console::instance().add_progress_bar(m_name, 1);
m_extract_bar.activate_spinner();
m_extract_bar.set_progress_hook(extract_progress_callback());
m_extract_bar.set_repr_hook(extract_repr());
Console::instance().progress_bar_manager().add_label("Extract", m_extract_bar);
}
if (!tarball_cache.empty())
{
LOG_DEBUG << "Found valid tarball cache at '" << tarball_cache.string() << "'";
m_tarball_path = tarball_cache / m_filename;
m_validation_result = VALIDATION_RESULT::VALID;
thread v(&PackageDownloadExtractTarget::extract_from_cache, this);
v.detach();
LOG_DEBUG << "Using cached tarball '" << m_filename << "'";
return nullptr;
}
else
{
caches.clear_query_cache(m_package_info);
// need to download this file
LOG_DEBUG << "Adding '" << m_name << "' to download targets from '" << m_url << "'";
m_tarball_path = m_cache_path / m_filename;
m_target = std::make_unique<DownloadTarget>(m_name, m_url, m_tarball_path);
m_target->set_finalize_callback(&PackageDownloadExtractTarget::finalize_callback,
this);
m_target->set_expected_size(m_expected_size);
if (m_has_progress_bars)
{
m_download_bar = Console::instance().add_progress_bar(m_name, m_expected_size);
m_target->set_progress_bar(m_download_bar);
Console::instance().progress_bar_manager().add_label("Download",
m_download_bar);
}
return m_target.get();
}
}
LOG_DEBUG << "Using cached '" << m_name << "'";
m_finished = true;
return nullptr;
}
/*******************************
* MTransaction implementation *
*******************************/
bool MTransaction::filter(Solvable* s)
{
if (m_filter_type == FilterType::none)
return false;
bool spec_in_filter = m_filter_name_ids.count(s->name);
if (m_filter_type == FilterType::keep_only)
{
return spec_in_filter;
}
else
{
return !spec_in_filter;
}
}
MTransaction::MTransaction(MPool& pool,
const std::vector<MatchSpec>& specs_to_remove,
const std::vector<MatchSpec>& specs_to_install,
MultiPackageCache& caches,
std::vector<MRepo*> repos)
: m_multi_cache(caches)
, m_repos(repos)
{
// auto& ctx = Context::instance();
std::vector<PackageInfo> pi_result;
for (auto& ms : specs_to_install)
{
PackageInfo p(ms.name);
p.url = ms.url;
p.build_string = ms.build;
p.version = ms.version;
p.channel = ms.channel;
p.fn = ms.fn;
if (ms.brackets.find("md5") != ms.brackets.end())
{
p.md5 = ms.brackets.at("md5");
}
if (ms.brackets.find("sha256") != ms.brackets.end())
{
p.sha256 = ms.brackets.at("sha256");
}
pi_result.push_back(p);
}
MRepo mrepo(pool, "__explicit_specs__", pi_result);
pool.create_whatprovides();
// Just add the packages we want to remove directly to the transaction
Queue q, job, decision;
queue_init(&q);
queue_init(&job);
queue_init(&decision);
std::vector<std::string> not_found;
for (auto& s : specs_to_remove)
{
queue_empty(&job);
queue_empty(&q);
Id id = pool_conda_matchspec((Pool*) pool, s.conda_build_form().c_str());
if (id)
{
queue_push2(&job, SOLVER_SOLVABLE_PROVIDES, id);
}
selection_solvables((Pool*) pool, &job, &q);
if (q.count == 0)
{
not_found.push_back("\n - " + s.str());
}
for (std::size_t i = 0; i < q.count; i++)
{
// To remove, these have to be negative
queue_push(&decision, -q.elements[i]);
}
}
if (!not_found.empty())
{
LOG_ERROR << "Could not find packages to remove:" + join("", not_found) << std::endl;
throw std::runtime_error("Could not find packages to remove:" + join("", not_found));
}
selection_solvables((Pool*) pool, &job, &q);
bool remove_success = q.count >= specs_to_remove.size();
Console::instance().json_write({ { "success", remove_success } });
Id pkg_id;
Solvable* solvable;
// find repo __explicit_specs__ and install all packages from it
FOR_REPO_SOLVABLES(mrepo.repo(), pkg_id, solvable)
{
queue_push(&decision, pkg_id);
}
queue_free(&job);
m_transaction = transaction_create_decisionq((Pool*) pool, &decision, nullptr);
init();
m_history_entry = History::UserRequest::prefilled();
for (auto& s : specs_to_remove)
m_history_entry.remove.push_back(s.str());
for (auto& s : specs_to_install)
m_history_entry.update.push_back(s.str());
// if no action required, don't even start logging them
if (!empty())
{
Console::instance().json_down("actions");
Console::instance().json_write({ { "PREFIX", Context::instance().target_prefix } });
}
queue_free(&q);
queue_free(&decision);
queue_free(&job);
m_transaction_context = TransactionContext(
Context::instance().target_prefix, find_python_version(), specs_to_install);
}
MTransaction::MTransaction(MSolver& solver,
MultiPackageCache& caches,
std::vector<MRepo*> repos)
: m_multi_cache(caches)
, m_repos(repos)
{
if (!solver.is_solved())
{
throw std::runtime_error(
"Cannot create transaction without calling solver.solve() first.");
}
m_transaction = solver_create_transaction(solver);
transaction_order(m_transaction, 0);
auto* pool = static_cast<Solver*>(solver)->pool;
m_history_entry = History::UserRequest::prefilled();
if (solver.no_deps || solver.only_deps)
{
m_filter_type = solver.only_deps ? FilterType::keep_only : FilterType::ignore;
for (auto& s : solver.install_specs())
{
m_filter_name_ids.insert(pool_str2id(pool, s.name.c_str(), 0));
}
for (auto& s : solver.remove_specs())
{
m_filter_name_ids.insert(pool_str2id(pool, s.name.c_str(), 0));
}
if (solver.only_deps)
{
Queue q;
queue_init(&q);
transaction_installedresult(m_transaction, &q);
for (int i = 0; i < q.count; ++i)
{
Solvable* s = pool_id2solvable(pool, q.elements[i]);
if (m_filter_name_ids.count(s->name))
{
// add the dependencies of this selected package to the added specs
Id* reqp;
for (reqp = s->repo->idarraydata + s->requires; *reqp; reqp++)
{
const char* depname = pool_id2str(pool, *reqp);
const char* depevr = pool_id2evr(pool, *reqp);
std::string add_spec;
if (depname)
{
add_spec += depname;
if (depevr && strlen(depevr))
{
add_spec += " ";
add_spec += depevr;
}
}
m_history_entry.update.push_back(MatchSpec(add_spec).str());
}
}
}
queue_free(&q);
}
}
if (solver.only_deps == false)
{
auto to_string_vec = [](const std::vector<MatchSpec>& vec) -> std::vector<std::string> {
std::vector<std::string> res;
for (const auto& el : vec)
res.push_back(el.str());
return res;
};
m_history_entry.update = to_string_vec(solver.install_specs());
m_history_entry.remove = to_string_vec(solver.remove_specs());
}
m_force_reinstall = solver.force_reinstall;
init();
// if no action required, don't even start logging them
if (!empty())
{
Console::instance().json_down("actions");
Console::instance().json_write({ { "PREFIX", Context::instance().target_prefix } });
}
m_transaction_context = TransactionContext(
Context::instance().target_prefix, find_python_version(), solver.install_specs());
}
MTransaction::~MTransaction()
{
LOG_INFO << "Freeing transaction.";
transaction_free(m_transaction);
}
void MTransaction::init()
{
for (int i = 0; i < m_transaction->steps.count && !is_sig_interrupted(); i++)
{
Id p = m_transaction->steps.elements[i];
Id ttype = transaction_type(m_transaction, p, SOLVER_TRANSACTION_SHOW_ALL);
Solvable* s = pool_id2solvable(m_transaction->pool, p);
if (filter(s))
{
continue;
}
switch (ttype)
{
case SOLVER_TRANSACTION_DOWNGRADED:
case SOLVER_TRANSACTION_UPGRADED:
case SOLVER_TRANSACTION_CHANGED:
case SOLVER_TRANSACTION_REINSTALLED:
{
if (ttype == SOLVER_TRANSACTION_REINSTALLED && m_force_reinstall == false)
break;
m_to_remove.push_back(s);
m_to_install.push_back(m_transaction->pool->solvables
+ transaction_obs_pkg(m_transaction, p));
break;
}
case SOLVER_TRANSACTION_ERASE:
{
m_to_remove.push_back(s);
break;
}
case SOLVER_TRANSACTION_INSTALL:
{
m_to_install.push_back(s);
break;
}
case SOLVER_TRANSACTION_IGNORE:
break;
default:
LOG_ERROR << "Exec case not handled: " << ttype;
break;
}
}
}
std::string MTransaction::find_python_version()
{
// We need to find the python version that will be there after this
// Transaction is finished in order to compile the noarch packages correctly,
// for example
Pool* pool = m_transaction->pool;
assert(pool != nullptr);
std::string py_ver;
Id python = pool_str2id(pool, "python", 0);
for (Solvable* s : m_to_install)
{
if (s->name == python)
{
py_ver = pool_id2str(pool, s->evr);
LOG_INFO << "Found python version in packages to be installed " << py_ver;
return py_ver;
}
}
if (pool->installed != nullptr)
{
Id p;
Solvable* s;
FOR_REPO_SOLVABLES(pool->installed, p, s)
{
if (s->name == python)
{
py_ver = pool_id2str(pool, s->evr);
LOG_INFO << "Found python in installed packages " << py_ver;
break;
}
}
}
if (py_ver.size())
{
// we need to make sure that we're not about to remove python!
for (Solvable* s : m_to_remove)
{
if (s->name == python)
return "";
}
}
return py_ver;
}
class TransactionRollback
{
public:
void record(const UnlinkPackage& unlink)
{
m_unlink_stack.push(unlink);
}
void record(const LinkPackage& link)
{
m_link_stack.push(link);
}
void rollback()
{
while (!m_link_stack.empty())
{
m_link_stack.top().undo();
m_link_stack.pop();
}
while (!m_unlink_stack.empty())
{
m_unlink_stack.top().undo();
m_unlink_stack.pop();
}
}
private:
std::stack<UnlinkPackage> m_unlink_stack;
std::stack<LinkPackage> m_link_stack;
};
bool MTransaction::execute(PrefixData& prefix)
{
auto& ctx = Context::instance();
// JSON output
// back to the top level if any action was required
if (!empty())
Console::instance().json_up();
Console::instance().json_write(
{ { "dry_run", ctx.dry_run }, { "prefix", ctx.target_prefix } });
if (empty())
Console::instance().json_write(
{ { "message", "All requested packages already installed" } });
// finally, print the JSON
Console::instance().json_print();
if (ctx.dry_run)
{
Console::stream() << "Dry run. Not executing the transaction.";
return true;
}
LockFile lf(ctx.target_prefix / "conda-meta");
clean_trash_files(ctx.target_prefix, false);
Console::stream() << "\nTransaction starting";
fetch_extract_packages();
// m_transaction_context = TransactionContext(prefix.path(), find_python_version());
History::UserRequest ur = History::UserRequest::prefilled();
TransactionRollback rollback;
auto* pool = m_transaction->pool;
for (int i = 0; i < m_transaction->steps.count && !is_sig_interrupted(); i++)
{
Id p = m_transaction->steps.elements[i];
Id ttype = transaction_type(m_transaction, p, SOLVER_TRANSACTION_SHOW_ALL);
Solvable* s = pool_id2solvable(pool, p);
if (filter(s))
{
continue;
}
switch (ttype)
{
case SOLVER_TRANSACTION_DOWNGRADED:
case SOLVER_TRANSACTION_UPGRADED:
case SOLVER_TRANSACTION_CHANGED:
case SOLVER_TRANSACTION_REINSTALLED:
{
if (ttype == SOLVER_TRANSACTION_REINSTALLED && m_force_reinstall == false)
break;
Solvable* s2
= m_transaction->pool->solvables + transaction_obs_pkg(m_transaction, p);
Console::stream()
<< "Changing " << PackageInfo(s).str() << " ==> " << PackageInfo(s2).str();
PackageInfo package_to_unlink(s);
const fs::path ul_cache_path(
m_multi_cache.get_extracted_dir_path(package_to_unlink));
PackageInfo package_to_link(s2);
const fs::path l_cache_path(
m_multi_cache.get_extracted_dir_path(package_to_link, false));
UnlinkPackage up(package_to_unlink, ul_cache_path, &m_transaction_context);
up.execute();
rollback.record(up);
LinkPackage lp(package_to_link, l_cache_path, &m_transaction_context);
lp.execute();
rollback.record(lp);
m_history_entry.unlink_dists.push_back(package_to_unlink.long_str());
m_history_entry.link_dists.push_back(package_to_link.long_str());
break;
}
case SOLVER_TRANSACTION_ERASE:
{
PackageInfo p(s);
Console::stream() << "Unlinking " << p.str();
const fs::path cache_path(m_multi_cache.get_extracted_dir_path(p));
UnlinkPackage up(p, cache_path, &m_transaction_context);
up.execute();
rollback.record(up);
m_history_entry.unlink_dists.push_back(p.long_str());
break;
}
case SOLVER_TRANSACTION_INSTALL:
{
PackageInfo p(s);
Console::stream() << "Linking " << p.str();
const fs::path cache_path(m_multi_cache.get_extracted_dir_path(p, false));
LinkPackage lp(p, cache_path, &m_transaction_context);
lp.execute();
rollback.record(lp);
m_history_entry.link_dists.push_back(p.long_str());
break;
}
case SOLVER_TRANSACTION_IGNORE:
break;
default:
LOG_ERROR << "Exec case not handled: " << ttype;
break;
}
}
bool interrupted = is_sig_interrupted();
if (interrupted)
{
Console::stream() << "Transaction interrupted, rollbacking";
rollback.rollback();
}
else
{
LOG_INFO << "Waiting for pyc compilation to finish";
m_transaction_context.wait_for_pyc_compilation();
Console::stream() << "Transaction finished";
prefix.history().add_entry(m_history_entry);
}
return !interrupted;
}
auto MTransaction::to_conda() -> to_conda_type
{
Id real_repo_key = pool_str2id(m_transaction->pool, "solvable:real_repo_url", 1);
to_install_type to_install_structured;
to_remove_type to_remove_structured;
for (Solvable* s : m_to_remove)
{
const char* mediafile = solvable_lookup_str(s, SOLVABLE_MEDIAFILE);
to_remove_structured.emplace_back(s->repo->name, mediafile);
}
for (Solvable* s : m_to_install)
{
const char* mediafile = solvable_lookup_str(s, SOLVABLE_MEDIAFILE);
std::string s_json = solvable_to_json(s).dump(4);
std::string channel;
if (solvable_lookup_str(s, real_repo_key))
{
channel = solvable_lookup_str(s, real_repo_key);
}
else
{
channel = s->repo->name; // note this can and should be <unknown> when
// e.g. installing from a tarball
}
to_install_structured.emplace_back(channel, mediafile, s_json);
}
to_specs_type specs;
std::get<0>(specs) = m_history_entry.update;
std::get<1>(specs) = m_history_entry.remove;
return std::make_tuple(specs, to_install_structured, to_remove_structured);
}
void MTransaction::log_json()
{
std::vector<nlohmann::json> to_fetch, to_link, to_unlink;
for (Solvable* s : m_to_install)
{
if (!need_pkg_download(s, m_multi_cache))
{
to_link.push_back(solvable_to_json(s));
}
else
{
to_fetch.push_back(solvable_to_json(s));
to_link.push_back(solvable_to_json(s));
}
}
for (Solvable* s : m_to_remove)
{
to_unlink.push_back(solvable_to_json(s));
}
auto add_json = [](const auto& jlist, const char* s) {
if (!jlist.empty())
{
Console::instance().json_down(s);
for (nlohmann::json j : jlist)
{
Console::instance().json_append(j);
}
Console::instance().json_up();
}
};
add_json(to_fetch, "FETCH");
add_json(to_link, "LINK");
add_json(to_unlink, "UNLINK");
}
bool MTransaction::fetch_extract_packages()
{
std::vector<std::unique_ptr<PackageDownloadExtractTarget>> targets;
MultiDownloadTarget multi_dl;
auto& pbar_manager
= Console::instance().init_progress_bar_manager(ProgressBarMode::aggregated);
auto& aggregated_pbar_manager = dynamic_cast<AggregatedBarManager&>(pbar_manager);
auto& ctx = Context::instance();
DownloadExtractSemaphore::set_max(ctx.extract_threads);
if (ctx.experimental && ctx.verify_artifacts)
LOG_INFO << "Content trust is enabled, package(s) signatures will be verified";
for (auto& s : m_to_install)
{
std::string url;
MRepo* mamba_repo = nullptr;
for (auto& r : m_repos)
{
if (r->repo() == s->repo)
{
mamba_repo = r;
break;
}
}
if (mamba_repo == nullptr || mamba_repo->url() == "")
{
// use fallback mediadir / mediafile
// this happens with explicit transactions
url = solvable_lookup_str(s, SOLVABLE_MEDIADIR);
if (url.empty())
throw std::runtime_error("Repo not associated.");
}
if (ctx.experimental && ctx.verify_artifacts)
{
const auto& repo_checker
= make_channel(mamba_repo->url()).repo_checker(m_multi_cache);
auto pkg_info = PackageInfo(s);
repo_checker.verify_package(pkg_info.json_signable(),
nlohmann::json::parse(pkg_info.signatures));