-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathzypp_server.rs
More file actions
1024 lines (922 loc) · 36.8 KB
/
zypp_server.rs
File metadata and controls
1024 lines (922 loc) · 36.8 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
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) [2025] SUSE LLC
//
// All Rights Reserved.
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, contact SUSE LLC.
//
// To contact SUSE LLC about this file by physical or electronic mail, you may
// find current contact information at www.suse.com.
use agama_security as security;
use agama_utils::{
actor::Handler,
api::{
self,
software::{Pattern, SelectedBy, SoftwareProposal, SystemInfo},
Issue, Scope,
},
helpers::copy_dir_all,
kernel_cmdline::KernelCmdline,
products::ProductSpec,
progress, question,
};
use camino::{Utf8Path, Utf8PathBuf};
use gettextrs::gettext;
use std::collections::HashMap;
use tokio::sync::{
mpsc::{self, UnboundedSender},
oneshot,
};
use zypp_agama::{errors::ZyppResult, ZyppError};
use crate::{
callbacks,
model::{
registration::RegistrationError,
state::{self, SoftwareState},
WriteIssues,
},
state::{Addon, RegistrationState, RepoKey, ResolvableSelection, ResolvablesState},
Registration, ResolvableType,
};
const GPG_KEYS: &str = "/usr/lib/rpm/gnupg/keys/gpg-*";
#[derive(thiserror::Error, Debug)]
pub enum ZyppDispatchError {
#[error(transparent)]
Zypp(#[from] ZyppError),
#[error("libzypp error: {0}")]
ZyppServer(#[from] Box<ZyppServerError>),
#[error("Response channel closed")]
ResponseChannelClosed,
#[error("Target creation failed: {0}")]
TargetCreationFailed(#[source] std::io::Error),
#[error(transparent)]
Progress(#[from] progress::service::Error),
}
impl From<ZyppServerError> for ZyppDispatchError {
fn from(err: ZyppServerError) -> Self {
Self::ZyppServer(Box::new(err))
}
}
#[derive(thiserror::Error, Debug)]
pub enum ZyppServerError {
#[error("Response channel closed")]
ResponseChannelClosed,
#[error("Receiver error: {0}")]
RecvError(#[from] oneshot::error::RecvError),
#[error("Sender error: {0}")]
SendError(#[from] Box<mpsc::error::SendError<SoftwareAction>>),
#[error("Error from libzypp: {0}")]
ZyppError(#[from] zypp_agama::ZyppError),
#[error("Could not find a mount point to calculate the used space")]
MissingMountPoint,
#[error("SSL error: {0}")]
SSL(#[from] openssl::error::ErrorStack),
#[error("Failed to copy to target system: {0}")]
IO(#[from] std::io::Error),
}
impl From<mpsc::error::SendError<SoftwareAction>> for ZyppServerError {
fn from(err: mpsc::error::SendError<SoftwareAction>) -> Self {
Self::SendError(Box::new(err))
}
}
pub type ZyppServerResult<R> = Result<R, ZyppServerError>;
pub enum SoftwareAction {
Install(
oneshot::Sender<ZyppServerResult<bool>>,
Handler<progress::Service>,
Handler<question::Service>,
),
Finish(oneshot::Sender<ZyppServerResult<()>>),
GetSystemInfo(ProductSpec, oneshot::Sender<ZyppServerResult<SystemInfo>>),
GetProposal(
ProductSpec,
oneshot::Sender<ZyppServerResult<SoftwareProposal>>,
),
Write {
state: SoftwareState,
progress: Handler<progress::Service>,
question: Handler<question::Service>,
security: Handler<security::Service>,
tx: oneshot::Sender<ZyppServerResult<WriteIssues>>,
},
}
/// Registration status.
#[derive(Default)]
pub enum RegistrationStatus {
#[default]
NotRegistered,
Registered(Box<Registration>),
Failed(RegistrationError),
}
/// Software service server.
pub struct ZyppServer {
receiver: mpsc::UnboundedReceiver<SoftwareAction>,
registration: RegistrationStatus,
root_dir: Utf8PathBuf,
install_dir: Utf8PathBuf,
trusted_keys: Vec<RepoKey>,
unsigned_repos: Vec<String>,
only_required: bool,
save_solver_testcase: bool,
}
impl ZyppServer {
/// Starts the software service loop and returns a client.
///
/// The service runs on a separate thread and gets the client requests using a channel.
pub fn start<P: AsRef<Utf8Path>>(
root_dir: P,
install_dir: P,
cmdline: &KernelCmdline,
) -> ZyppServerResult<UnboundedSender<SoftwareAction>> {
let (sender, receiver) = mpsc::unbounded_channel();
let server = Self {
receiver,
root_dir: root_dir.as_ref().to_path_buf(),
install_dir: install_dir.as_ref().to_path_buf(),
registration: Default::default(),
trusted_keys: vec![],
unsigned_repos: vec![],
only_required: false,
save_solver_testcase: cmdline.get_last("inst.solver_testcase") == Some("1".to_string()),
};
// drop the returned JoinHandle: the thread will be detached
// but that's OK for it to run until the process dies
std::thread::spawn(move || server.run());
Ok(sender)
}
/// Runs the server dispatching the actions received through the input channel.
fn run(mut self) -> Result<(), ZyppDispatchError> {
let zypp = self.initialize_target_dir()?;
loop {
// what happens here is that we need synchronized code
// and only for small async interface run it in blocking way. Receiver handling is done to explicit passing
// of ownership as receiver do not implement Copy.
// It creates own runtime here as we are on dedicated zypp thread and there is no tokio runtime yet. So we
// create a new one with single thread to run tasks in its own dedicated thread.
// unwrap OK: unwrap is fine as if we eat all IO resources, we are doomed, so failing is good solution
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let res = rt.spawn(async move { (self.receiver.recv().await, self.receiver) });
// unwrap OK: receiver hopefuly should not panic when just receiving message
let (action, receiver) = rt.block_on(res).unwrap();
self.receiver = receiver;
let Some(action) = action else {
tracing::info!("Software action channel closed. So time for rest in peace.");
break;
};
match self.dispatch(action, &zypp) {
Ok(false) => {
break;
}
Err(error) => {
tracing::error!("Software dispatch error: {:?}", error);
}
_ => {}
};
}
// drop explicitly zypp to release lock ASAP
drop(zypp);
Ok(())
}
/// Forwards the action to the appropriate handler.
fn dispatch(
&mut self,
action: SoftwareAction,
zypp: &zypp_agama::Zypp,
) -> Result<bool, ZyppDispatchError> {
match action {
SoftwareAction::Write {
state,
progress,
question,
security: security_srv,
tx,
} => {
let mut security_callback = callbacks::Security::new(question.clone());
self.write(
state,
progress,
question,
security_srv,
&mut security_callback,
tx,
zypp,
)?;
}
SoftwareAction::GetSystemInfo(product_spec, tx) => {
self.system_info(product_spec, tx, zypp)?;
}
SoftwareAction::Install(tx, progress, question) => {
tx.send(self.install(zypp, progress, question))
.map_err(|_| ZyppDispatchError::ResponseChannelClosed)?;
}
SoftwareAction::Finish(tx) => {
self.finish(zypp, tx)?;
// stop server after finish action to release zypp lock ASAP.
return Ok(false);
}
SoftwareAction::GetProposal(product_spec, sender) => {
self.proposal(product_spec, sender, zypp)?
}
}
Ok(true)
}
// Install rpms
fn install(
&self,
zypp: &zypp_agama::Zypp,
progress: Handler<progress::Service>,
question: Handler<question::Service>,
) -> ZyppServerResult<bool> {
let mut download_callback =
callbacks::CommitDownload::new(progress.clone(), question.clone());
let mut install_callback = callbacks::Install::new(progress.clone(), question.clone());
let mut security_callback = callbacks::Security::new(question);
security_callback.set_trusted_gpg_keys(self.trusted_keys.clone());
security_callback.set_unsigned_repos(self.unsigned_repos.clone());
let packages_count = zypp.packages_count();
// use packages count *2 as we need to download package and also install it
let steps = (packages_count * 2) as usize;
let _ = progress.cast(progress::message::Start::new(
Scope::Software,
steps,
"Starting packages installation",
));
zypp.switch_target(self.install_dir.as_ref())?;
let result = zypp.commit(
&mut download_callback,
&mut install_callback,
&mut security_callback,
)?;
tracing::info!("libzypp commit ends with {}", result);
let res = progress.cast(progress::message::Finish::new(Scope::Software));
tracing::info!("Software install finished. Progress result {:#?}", res);
Ok(result)
}
fn read(&self, zypp: &zypp_agama::Zypp) -> Result<SoftwareState, ZyppError> {
let repositories = zypp
.list_repositories()?
.into_iter()
// filter out service managed repositories
.filter(|repo| repo.service.is_none())
.map(|repo| state::Repository {
name: repo.user_name,
alias: repo.alias,
url: repo.url,
enabled: repo.enabled,
})
.collect();
// FIXME: read the real product. It is not a problem because it is replaced
// later.
let mut state = SoftwareState::new("SLES");
state.repositories = repositories;
Ok(state)
}
#[allow(clippy::too_many_arguments)]
fn write(
&mut self,
state: SoftwareState,
progress: Handler<progress::Service>,
_questions: Handler<question::Service>,
security_srv: Handler<security::Service>,
security: &mut callbacks::Security,
tx: oneshot::Sender<ZyppServerResult<WriteIssues>>,
zypp: &zypp_agama::Zypp,
) -> Result<(), ZyppDispatchError> {
let mut issues = WriteIssues::default();
let mut steps = vec![
gettext("Updating the list of repositories"),
gettext("Refreshing metadata from the repositories"),
gettext("Calculating the software proposal"),
];
if state.registration.is_some() {
steps.insert(0, gettext("Registering the system"));
}
_ = progress.cast(progress::message::StartWithSteps::new(
Scope::Software,
steps,
));
// TODO: add information about the current registration state
let old_state = self.read(zypp)?;
if let Some(registration_config) = &state.registration {
self.update_registration(
registration_config,
zypp,
security,
&security_srv,
&mut issues,
);
if !issues.is_empty() {
return Self::send_issues_and_finish(issues, tx, progress);
}
}
self.trusted_keys = state.trusted_gpg_keys;
security.set_trusted_gpg_keys(self.trusted_keys.clone());
self.unsigned_repos = state.unsigned_repos;
security.set_unsigned_repos(self.unsigned_repos.clone());
progress.cast(progress::message::Next::new(Scope::Software))?;
let old_aliases: Vec<_> = old_state
.repositories
.iter()
.map(|r| r.alias.clone())
.collect();
let aliases: Vec<_> = state.repositories.iter().map(|r| r.alias.clone()).collect();
let to_add: Vec<_> = state
.repositories
.iter()
.filter(|r| !old_aliases.contains(&r.alias))
.collect();
let to_remove: Vec<_> = old_state
.repositories
.iter()
.filter(|r| !aliases.contains(&r.alias))
.collect();
for repo in &to_add {
let result = zypp.add_repository(&repo.alias, &repo.url, |percent, alias| {
tracing::info!("Adding repository {} ({}%)", alias, percent);
true
});
if let Err(error) = result {
let message = format!("Could not add the repository {}", repo.alias);
issues.software.push(
Issue::new("software.add_repo", &message).with_details(&error.to_string()),
);
}
}
for repo in &to_remove {
let result = zypp.remove_repository(&repo.alias, |percent, alias| {
tracing::info!("Removing repository {} ({}%)", alias, percent);
true
});
if let Err(error) = result {
// TRANSLATORS: %s is the alias of the repository.
let message = gettext("Could not remove the repository %s")
.as_str()
.replace("%s", &repo.alias);
issues.software.push(
Issue::new("software.remove_repo", &message).with_details(&error.to_string()),
);
}
}
progress.cast(progress::message::Next::new(Scope::Software))?;
if !to_add.is_empty() || !to_remove.is_empty() {
let result = zypp.load_source(
|percent, alias| {
tracing::info!("Refreshing repositories: {} ({}%)", alias, percent);
true
},
security,
);
if let Err(error) = result {
let message = gettext("Could not read the repositories");
issues.software.push(
Issue::new("software.load_source", &message).with_details(&error.to_string()),
);
}
}
// reset everything to start from scratch
zypp.reset_resolvables();
tracing::info!("Selecting base product: {}", &state.product);
// FIXME: hotfix/workaround for bsc#1259311 - this should be removed after fixing the solver
let result = match Self::find_release_package(&state.resolvables) {
Some(package) => zypp.select_resolvable(
&package,
zypp_agama::ResolvableKind::Package,
zypp_agama::ResolvableSelected::Installation,
),
None => zypp.select_resolvable(
&state.product,
zypp_agama::ResolvableKind::Product,
zypp_agama::ResolvableSelected::Installation,
),
};
if let Err(error) = result {
tracing::info!(
"Failed to find the product {} in the repositories: {}",
&state.product,
&error
);
if state.allow_registration && !self.is_registered() {
let message = gettext("Failed to find the product in the repositories. You might need to register the system.");
let issue =
Issue::new("missing_registration", &message).with_details(&error.to_string());
issues.product.push(issue);
} else {
let message = gettext("Failed to find the product in the repositories.");
let issue =
Issue::new("missing_product", &message).with_details(&error.to_string());
issues.software.push(issue);
};
return Self::send_issues_and_finish(issues, tx, progress);
}
for (name, r#type, selection) in &state.resolvables.to_vec() {
match selection {
ResolvableSelection::AutoSelected { skip_if_missing } => {
issues.software.append(&mut self.select_resolvable(
zypp,
name,
*r#type,
zypp_agama::ResolvableSelected::Installation,
*skip_if_missing,
));
}
ResolvableSelection::Selected => {
issues.software.append(&mut self.select_resolvable(
zypp,
name,
*r#type,
zypp_agama::ResolvableSelected::User,
false,
));
}
// the removal is handled in a separate iteration to unselect resolvables selected
// by dependencies
ResolvableSelection::Removed => {}
};
}
// if registered select products from add-on services
if let RegistrationStatus::Registered(boxed_registration) = &self.registration {
let registration = boxed_registration.as_ref();
for name in registration.addon_product_service_names() {
zypp.select_products_from_service(&name)?;
}
}
self.only_required = state.options.only_required;
tracing::info!("Install only required packages: {}", self.only_required);
// run the solver to select the dependencies, ignore the errors, the solver runs again later
// do not save the solver testcase in this intermediate step
let _ = zypp.run_solver(self.only_required, false);
// unselect packages including the autoselected dependencies
for (name, r#type, selection) in &state.resolvables.to_vec() {
if selection == &ResolvableSelection::Removed {
self.unselect_resolvable(zypp, name, *r#type)
};
}
if let Ok(false) = zypp.run_solver(self.only_required, self.save_solver_testcase) {
let message = gettext("There are conflicts in the software selection");
issues
.software
.push(Issue::new("software.conflict", &message));
}
Self::send_issues_and_finish(issues, tx, progress)
}
fn select_resolvable(
&self,
zypp: &zypp_agama::Zypp,
name: &str,
r#type: ResolvableType,
reason: zypp_agama::ResolvableSelected,
skip_if_missing: bool,
) -> Vec<Issue> {
let mut issues = vec![];
let result = zypp.select_resolvable(name, r#type.into(), reason);
if let Err(error) = result {
if skip_if_missing {
tracing::info!(
"Could not select '{}' but it should be skipped if missing.",
name
);
} else {
// TRANSLATORS: the first %s is the kind of resolvable (e.g., "package")
// and the second %s is the name of the resolvable.
let message = gettext("Could not select %s '%s' for installation")
.as_str()
.replacen("%s", &r#type.to_string(), 1)
.replace("%s", name);
issues.push(
Issue::new("software.select_resolvable", &message)
.with_details(&error.to_string()),
);
}
}
issues
}
fn unselect_resolvable(&self, zypp: &zypp_agama::Zypp, name: &str, r#type: ResolvableType) {
if let Err(error) =
zypp.unselect_resolvable(name, r#type.into(), zypp_agama::ResolvableSelected::User)
{
tracing::info!("Could not unselect '{name}': {error}");
}
}
fn finish(
&mut self,
zypp: &zypp_agama::Zypp,
tx: oneshot::Sender<ZyppServerResult<()>>,
) -> Result<(), ZyppDispatchError> {
if let Err(error) = self.remove_dud_repo(zypp) {
tracing::warn!("Failed to remove the DUD repository: {error}");
tx.send(Err(error))
.map_err(|_| ZyppDispatchError::ResponseChannelClosed)?;
return Ok(());
}
if let Err(error) = self.disable_local_repos(zypp) {
tracing::warn!("Failed to disable local repositories: {error}");
tx.send(Err(error))
.map_err(|_| ZyppDispatchError::ResponseChannelClosed)?;
return Ok(());
}
let _ = self.registration_finish(); // TODO: move it outside of zypp server as it do not need zypp lock
self.modify_zypp_conf();
if let Err(error) = self.modify_full_repo(zypp) {
tracing::warn!("Failed to modify the full repository: {error}");
tx.send(Err(error))
.map_err(|_| ZyppDispatchError::ResponseChannelClosed)?;
return Ok(());
}
if let Err(error) = self.copy_files() {
tracing::warn!("Failed to copy zypp files: {error}");
tx.send(Err(error))
.map_err(|_| ZyppDispatchError::ResponseChannelClosed)?;
return Ok(());
}
// if we fail to send ok, lets just ignore it
let _ = tx.send(Ok(()));
Ok(())
}
const ZYPP_DIRS: [&str; 4] = [
"etc/zypp/services.d",
"etc/zypp/repos.d",
"etc/zypp/credentials.d",
"var/cache/zypp",
];
fn copy_files(&self) -> ZyppServerResult<()> {
for path in Self::ZYPP_DIRS {
let source_path = self.root_dir.join(path);
let target_path = self.install_dir.join(path);
if source_path.exists() {
copy_dir_all(&source_path, &target_path)?;
}
}
Ok(())
}
fn modify_full_repo(&self, zypp: &zypp_agama::Zypp) -> ZyppServerResult<()> {
let repos = zypp.list_repositories()?;
// if url is invalid, then do not disable it and do not touch it
let repos = repos
.iter()
.filter(|r| r.url.starts_with("dvd:/install?devices="));
for r in repos {
zypp.set_repository_url(&r.alias, "dvd:/install")?;
}
Ok(())
}
fn remove_dud_repo(&self, zypp: &zypp_agama::Zypp) -> ZyppServerResult<()> {
const DUD_NAME: &str = "AgamaDriverUpdate";
let repos = zypp.list_repositories()?;
let repo = repos.iter().find(|r| r.alias.as_str() == DUD_NAME);
if let Some(repo) = repo {
zypp.remove_repository(&repo.alias, |_, _| true)?;
}
Ok(())
}
fn disable_local_repos(&self, zypp: &zypp_agama::Zypp) -> ZyppServerResult<()> {
let repos = zypp.list_repositories()?;
// if url is invalid, then do not disable it and do not touch it
let repos = repos.iter().filter(|r| r.is_local().unwrap_or(false));
for r in repos {
zypp.disable_repository(&r.alias)?;
}
Ok(())
}
fn registration_finish(&mut self) -> ZyppServerResult<()> {
let RegistrationStatus::Registered(registration) = &mut self.registration else {
tracing::info!(
"Skipping the copy of registration files because the system was not registered"
);
return Ok(());
};
if let Err(error) = registration.finish(&self.install_dir) {
// just log error and continue as registration config is recoverable
tracing::error!("Failed to finish the registration: {error}");
};
Ok(())
}
fn is_registered(&self) -> bool {
matches!(self.registration, RegistrationStatus::Registered(_))
}
fn modify_zypp_conf(&self) {
// write only if different from default
if self.only_required {
let contents = "# Use only hard dependencies as configured in installer\nsolver.onlyRequires = true\n";
let path = self.install_dir.join("etc/zypp/zypp.conf.d/installer.conf");
let write_result = std::fs::write(path.as_path(), contents);
if write_result.is_err() {
tracing::error!("Failed to write {path}: {write_result:?}");
}
}
}
fn system_info(
&self,
product: ProductSpec,
tx: oneshot::Sender<ZyppServerResult<SystemInfo>>,
zypp: &zypp_agama::Zypp,
) -> Result<(), ZyppDispatchError> {
let patterns = self.patterns(&product, zypp)?;
let repositories = self.repositories(zypp)?;
// let registration = self.registration.as_ref().map(|r| r.to_registration_info());
let registration = match &self.registration {
RegistrationStatus::Registered(registration) => {
Some(registration.to_registration_info())
}
_ => None,
};
let system_info = SystemInfo {
patterns,
repositories,
registration,
};
tx.send(Ok(system_info))
.map_err(|_| ZyppDispatchError::ResponseChannelClosed)?;
Ok(())
}
fn user_patterns<'a>(
&self,
product: &'a ProductSpec,
zypp: &zypp_agama::Zypp,
) -> ZyppResult<impl Iterator<Item = zypp_agama::Pattern> + use<'a, '_>> {
let product_pattern_names: Vec<_> = product
.software
.user_patterns
.iter()
.map(|p| p.name())
.collect();
let repositories = zypp.list_repositories()?;
let zypp_patterns = zypp.list_patterns()?;
Ok(zypp_patterns.into_iter().filter(move |p| {
// lets explain here logic for user selectable patterns
// if pattern is listed in product pattern names then use it
// else include only patterns coming from repository that is
// NOT predefined as agama-* one neither from repository
// added by base product registration
if product_pattern_names.contains(&p.name.as_str()) {
return true;
}
let repository = repositories.iter().find(|r| r.alias == p.repo_alias);
let Some(repository) = repository else {
tracing::error!(
"Unknown alias {} found in pattern selectable.",
p.repo_alias
);
return false;
};
if repository.alias.starts_with("agama-") {
return false;
}
if let RegistrationStatus::Registered(registration) = &self.registration {
repository.service.is_some()
&& repository.service != registration.base_product_service_name()
} else {
false
}
}))
}
fn patterns(&self, product: &ProductSpec, zypp: &zypp_agama::Zypp) -> ZyppResult<Vec<Pattern>> {
let preselected_patterns: Vec<_> = product
.software
.user_patterns
.iter()
.filter(|p| p.preselected())
.map(|p| p.name())
.collect();
let patterns = self
.user_patterns(product, zypp)?
.map(|p| {
let preselected = preselected_patterns.contains(&p.name.as_str());
Pattern {
name: p.name,
category: p.category,
description: p.description,
icon: p.icon,
summary: p.summary,
order: p.order,
preselected,
}
})
.collect();
Ok(patterns)
}
fn repositories(&self, zypp: &zypp_agama::Zypp) -> ZyppResult<Vec<api::software::Repository>> {
let result = zypp
.list_repositories()?
.into_iter()
.map(|r| api::software::Repository {
alias: r.alias.clone(),
name: r.alias,
url: r.url,
enabled: r.enabled,
// At this point, there is no way to determine if the repository is
// predefined or not. It will be adjusted in the Model::repositories
// function.
predefined: false,
})
.collect();
Ok(result)
}
fn initialize_target_dir(&self) -> Result<zypp_agama::Zypp, ZyppDispatchError> {
let target_dir = self.root_dir.as_path();
if target_dir.exists() {
_ = std::fs::remove_dir_all(target_dir);
}
std::fs::create_dir_all(target_dir.as_str())
.map_err(ZyppDispatchError::TargetCreationFailed)?;
let zypp = zypp_agama::Zypp::init_target(target_dir.as_str(), |text, step, total| {
tracing::info!("Initializing target: {} ({}/{})", text, step, total);
})?;
self.import_gpg_keys(&zypp);
tracing::info!("zypp initialized");
Ok(zypp)
}
fn import_gpg_keys(&self, zypp: &zypp_agama::Zypp) {
// unwrap OK: glob pattern is created by us
for file in glob::glob(GPG_KEYS).unwrap() {
match file {
Ok(file) => {
if let Err(e) = zypp.import_gpg_key(&file.to_string_lossy()) {
tracing::error!("Failed to import GPG key: {}", e);
}
}
Err(e) => {
tracing::error!("Could not read GPG key file: {}", e);
}
}
}
}
fn proposal(
&self,
product: ProductSpec,
tx: oneshot::Sender<ZyppServerResult<SoftwareProposal>>,
zypp: &zypp_agama::Zypp,
) -> Result<(), ZyppDispatchError> {
let proposal = SoftwareProposal {
used_space: self.used_space(zypp)?,
patterns: self.patterns_selection(&product, zypp)?,
};
tx.send(Ok(proposal))
.map_err(|_| ZyppDispatchError::ResponseChannelClosed)?;
Ok(())
}
fn used_space(&self, zypp: &zypp_agama::Zypp) -> Result<i64, ZyppServerError> {
// TODO: for now it just compute total size, but it can get info about partitions from storage and pass it to libzypp
let mount_points = vec![zypp_agama::MountPoint {
directory: "/".to_string(),
filesystem: "btrfs".to_string(),
grow_only: false, // not sure if it has effect as we install everything fresh
used_size: 0,
}];
let computed_mount_points = zypp.count_disk_usage(mount_points)?;
computed_mount_points
.first()
.map(|m| m.used_size)
.ok_or(ZyppServerError::MissingMountPoint)
}
fn patterns_selection(
&self,
product: &ProductSpec,
zypp: &zypp_agama::Zypp,
) -> Result<HashMap<String, SelectedBy>, ZyppServerError> {
self.user_patterns(product, zypp)
.map(|patterns| {
patterns
.map(|pattern| {
// NOTE: cannot be implemented From as one lives in agama-utils which does not depend on zypp-agama and should not
// and other way it also does not make sense
let tag = match pattern.selected {
zypp_agama::ResolvableSelected::Installation => SelectedBy::Auto,
zypp_agama::ResolvableSelected::Not => SelectedBy::None,
zypp_agama::ResolvableSelected::Solver => SelectedBy::Auto,
zypp_agama::ResolvableSelected::User => SelectedBy::User,
zypp_agama::ResolvableSelected::Removed => SelectedBy::Removed,
};
(pattern.name.clone(), tag)
})
.collect()
})
.map_err(|e| e.into())
}
/// Update the registration status.
///
/// Register the system and the add-ons. If it was not possible to register the system
/// on a previous call to this function, do not try again. Otherwise, it might fail
/// again.
///
/// - `state`: wanted registration state.
/// - `zypp`: zypp instance.
/// - `issues`: list of issues to update.
fn update_registration(
&mut self,
state: &RegistrationState,
zypp: &zypp_agama::Zypp,
security: &mut callbacks::Security,
security_srv: &Handler<security::Service>,
issues: &mut WriteIssues,
) {
match &self.registration {
RegistrationStatus::Failed(_) | RegistrationStatus::NotRegistered => {
self.register_base_system(state, zypp, security, security_srv, issues);
}
RegistrationStatus::Registered(_) => {}
};
if !state.addons.is_empty() {
self.register_addons(&state.addons, zypp, security, issues);
}
}
fn register_base_system(
&mut self,
state: &RegistrationState,
zypp: &zypp_agama::Zypp,
security: &mut callbacks::Security,
security_srv: &Handler<security::Service>,
issues: &mut WriteIssues,
) {
let mut registration =
Registration::builder(self.root_dir.clone(), &state.product, &state.version);
if let Some(code) = &state.code {
registration = registration.with_code(code);
}
if let Some(email) = &state.email {
registration = registration.with_email(email);
}
if let Some(url) = &state.url {
registration = registration.with_url(url);
}
match registration.register(zypp, security, security_srv) {
Ok(registration) => {
self.registration = RegistrationStatus::Registered(Box::new(registration));
}
Err(error) => {
issues.product.push(
Issue::new(
"system_registration_failed",
&gettext("Failed to register the system"),
)
.with_details(&error.to_string()),
);
self.registration = RegistrationStatus::Failed(error);
}
}
}
fn register_addons(
&mut self,
addons: &Vec<Addon>,
zypp: &zypp_agama::Zypp,
security: &mut callbacks::Security,
issues: &mut WriteIssues,
) {
let RegistrationStatus::Registered(registration) = &mut self.registration else {
tracing::error!("Could not register addons because the base system is not registered");
return;
};
for addon in addons {
if registration.is_addon_registered(addon) {
tracing::info!("Skipping already registered add-on {}", &addon.id);
continue;
}
if let Err(error) = registration.register_addon(zypp, security, addon) {
let message = format!("Failed to register the add-on {}", addon.id);
let issue_id = format!("addon_registration_failed[{}]", &addon.id);
let issue = Issue::new(&issue_id, &message).with_details(&error.to_string());
issues.product.push(issue);
}
}
}
/// Ancillary function to send the issues and finish the progress early.
fn send_issues_and_finish(
issues: WriteIssues,
tx: oneshot::Sender<ZyppServerResult<WriteIssues>>,
progress: Handler<progress::Service>,
) -> Result<(), ZyppDispatchError> {
if let Err(e) = tx.send(Ok(issues)) {