forked from minimization/content-resolver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfeedback_pipeline.py
executable file
·3948 lines (3150 loc) · 146 KB
/
feedback_pipeline.py
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
#!/usr/bin/python3
import argparse, yaml, tempfile, os, subprocess, json, jinja2, datetime, copy, re, dnf, pprint
import concurrent.futures
import rpm_showme as showme
from functools import lru_cache
# Features of this new release
# - multiarch from the ground up!
# - more resilient
# - better internal data structure
# - user-defined views
###############################################################################
### Help ######################################################################
###############################################################################
# Configs:
# TYPE: KEY: ID:
# - repo repos repo_id
# - env_conf envs env_id
# - workload_conf workloads workload_id
# - label labels label_id
# - conf_view views view_id
#
# Data:
# TYPE: KEY: ID:
# - pkg pkgs/repo_id/arch NEVR
# - env envs env_id:repo_id:arch_id
# - workload workloads workload_id:env_id:repo_id:arch_id
# - view views view_id:repo_id:arch_id
#
#
#
###############################################################################
### Some initial stuff ########################################################
###############################################################################
# Error in global settings for Feedback Pipeline
# Settings to be implemented, now hardcoded below
class SettingsError(Exception):
pass
# Error in user-provided configs
class ConfigError(Exception):
pass
# Error in downloading repodata
class RepoDownloadError(Exception):
pass
def log(msg):
print(msg)
def err_log(msg):
print("ERROR LOG: {}".format(msg))
class SetEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
return json.JSONEncoder.default(self, obj)
def dump_data(path, data):
with open(path, 'w') as file:
json.dump(data, file, cls=SetEncoder)
def load_data(path):
with open(path, 'r') as file:
data = json.load(file)
return data
def size(num, suffix='B'):
for unit in ['','k','M','G']:
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, 'T', suffix)
def pkg_id_to_name(pkg_id):
pkg_name = pkg_id.rsplit("-",2)[0]
return pkg_name
def pkg_placeholder_name_to_id(placeholder_name):
placeholder_id = "{name}-000-placeholder.placeholder".format(name=placeholder_name)
return placeholder_id
def load_settings():
settings = {}
parser = argparse.ArgumentParser()
parser.add_argument("configs", help="Directory with YAML configuration files. Only files ending with '.yaml' are accepted.")
parser.add_argument("output", help="Directory to contain the output.")
args = parser.parse_args()
settings["configs"] = args.configs
settings["output"] = args.output
# FIXME: This is hardcorded, and it shouldn't be!
#settings["allowed_arches"] = ["armv7hl","aarch64","i686","ppc64le","s390x","x86_64"]
# FIXME Limiting arches for faster results during development
settings["allowed_arches"] = ["armv7hl","aarch64","ppc64le","s390x","x86_64"]
return(settings)
###############################################################################
### Loading user-provided configs #############################################
###############################################################################
# Configs:
# TYPE: KEY: ID:
# - repo repos repo_id
# - env envs env_id
# - workload workloads workload_id
# - label labels label_id
# - view views view_id
def _load_config_repo(document_id, document, settings):
config = {}
config["id"] = document_id
# Step 1: Mandatory fields
try:
# Name is an identifier for humans
config["name"] = str(document["data"]["name"])
# A short description, perhaps hinting the purpose
config["description"] = str(document["data"]["description"])
# Who maintains it? This is just a freeform string
# for humans to read. In Fedora, a FAS nick is recommended.
config["maintainer"] = str(document["data"]["maintainer"])
# Where does this repository come from?
# Right now, only Fedora repositories are supported,
# defined by their releasever.
config["source"] = {}
# Only Fedora repos supported at this time.
# Fedora release.
config["source"]["fedora_release"] = str(document["data"]["source"]["fedora_release"])
# List of architectures
config["source"]["architectures"] = []
for arch_raw in document["data"]["source"]["architectures"]:
arch = str(arch_raw)
if arch not in settings["allowed_arches"]:
err_log("Warning: {file}.yaml lists an invalid architecture: {arch}. Ignoring.".format(
file=document_id,
arch=arch))
continue
config["source"]["architectures"].append(str(arch))
except KeyError:
raise ConfigError("Error: {file} is invalid.".format(file=yml_file))
# Step 2: Optional fields
# An additional repository to be added to the mix.
# This repository will get a higher priority then the primary
# one defined by fedora_release.
# Practiaclly, this has been added for Fedora ELN that's used
# on top of Rawhide.
config["source"]["additional_repository"] = None
if "additional_repository" in document["data"]["source"]:
config["source"]["additional_repository"] = str(document["data"]["source"]["additional_repository"])
return config
def _load_config_env(document_id, document, settings):
config = {}
config["id"] = document_id
# Step 1: Mandatory fields
try:
# Name is an identifier for humans
config["name"] = str(document["data"]["name"])
# A short description, perhaps hinting the purpose
config["description"] = str(document["data"]["description"])
# Who maintains it? This is just a freeform string
# for humans to read. In Fedora, a FAS nick is recommended.
config["maintainer"] = str(document["data"]["maintainer"])
# Different instances of the environment, one per repository.
config["repositories"] = []
for repo in document["data"]["repositories"]:
config["repositories"].append(str(repo))
# Packages defining this environment.
# This list includes packages for all
# architectures — that's the one to use by default.
config["packages"] = []
for pkg in document["data"]["packages"]:
config["packages"].append(str(pkg))
# Labels connect things together.
# Workloads get installed in environments with the same label.
# They also get included in views with the same label.
config["labels"] = []
for repo in document["data"]["labels"]:
config["labels"].append(str(repo))
except KeyError:
raise ConfigError("Error: {file} is invalid.".format(file=document_id))
# Step 2: Optional fields
# Architecture-specific packages.
config["arch_packages"] = {}
for arch in settings["allowed_arches"]:
config["arch_packages"][arch] = []
if "arch_packages" in document["data"]:
for arch, pkgs in document["data"]["arch_packages"].items():
if arch not in settings["allowed_arches"]:
err_log("Warning: {file}.yaml lists an invalid architecture: {arch}. Ignoring.".format(
file=document_id,
arch=arch
))
continue
for pkg_raw in pkgs:
pkg = str(pkg_raw)
config["arch_packages"][arch].append(pkg)
# Extra installation options.
# The following are now supported:
# - "include-docs" - include documentation packages
# - "include-weak-deps" - automatically pull in "recommends" weak dependencies
config["options"] = []
if "options" in document["data"]:
if "include-docs" in document["data"]["options"]:
config["options"].append("include-docs")
if "include-weak-deps" in document["data"]["options"]:
config["options"].append("include-weak-deps")
return config
def _load_config_workload(document_id, document, settings):
config = {}
config["id"] = document_id
# Step 1: Mandatory fields
try:
# Name is an identifier for humans
config["name"] = str(document["data"]["name"])
# A short description, perhaps hinting the purpose
config["description"] = str(document["data"]["description"])
# Who maintains it? This is just a freeform string
# for humans to read. In Fedora, a FAS nick is recommended.
config["maintainer"] = str(document["data"]["maintainer"])
# Packages defining this workload.
# This list includes packages for all
# architectures — that's the one to use by default.
config["packages"] = []
# This workaround allows for "packages" to be left empty in the config
try:
for pkg in document["data"]["packages"]:
config["packages"].append(str(pkg))
except TypeError:
err_log("Warning: {file} has an empty 'packages' field defined which is invalid. Moving on...".format(
file=document_id
))
# Labels connect things together.
# Workloads get installed in environments with the same label.
# They also get included in views with the same label.
config["labels"] = []
for repo in document["data"]["labels"]:
config["labels"].append(str(repo))
except KeyError:
raise ConfigError("Error: {file} is invalid.".format(file=document_id))
# Step 2: Optional fields
# Architecture-specific packages.
config["arch_packages"] = {}
for arch in settings["allowed_arches"]:
config["arch_packages"][arch] = []
if "arch_packages" in document["data"]:
for arch, pkgs in document["data"]["arch_packages"].items():
if arch not in settings["allowed_arches"]:
err_log("Error: {file}.yaml lists an invalid architecture: {arch}. Ignoring.".format(
file=document_id,
arch=arch
))
continue
# This workaround allows for "arch_packages/ARCH" to be left empty in the config
try:
for pkg_raw in pkgs:
pkg = str(pkg_raw)
config["arch_packages"][arch].append(pkg)
except TypeError:
err_log("Warning: {file} has an empty 'arch_packages/{arch}' field defined which is invalid. Moving on...".format(
file=document_id,
arch=arch
))
# Extra installation options.
# The following are now supported:
# - "include-docs" - include documentation packages
# - "include-weak-deps" - automatically pull in "recommends" weak dependencies
config["options"] = []
if "options" in document["data"]:
if "include-docs" in document["data"]["options"]:
config["options"].append("include-docs")
if "include-weak-deps" in document["data"]["options"]:
config["options"].append("include-weak-deps")
# Disable module streams.
config["modules_disable"] = []
if "modules_disable" in document["data"]:
for module in document["data"]["modules_disable"]:
config["modules_disable"].append(module)
# Enable module streams.
config["modules_enable"] = []
if "modules_enable" in document["data"]:
for module in document["data"]["modules_enable"]:
config["modules_enable"].append(module)
# Package placeholders
# Add packages to the workload that don't exist (yet) in the repositories.
config["package_placeholders"] = {}
if "package_placeholders" in document["data"]:
for pkg_name, pkg_data in document["data"]["package_placeholders"].items():
pkg_description = pkg_data.get("description", "Description not provided.")
pkg_requires = pkg_data.get("requires", [])
pkg_buildrequires = pkg_data.get("buildrequires", [])
config["package_placeholders"][pkg_name] = {}
config["package_placeholders"][pkg_name]["name"] = pkg_name
config["package_placeholders"][pkg_name]["description"] = pkg_description
config["package_placeholders"][pkg_name]["requires"] = pkg_requires
config["package_placeholders"][pkg_name]["buildrequires"] = pkg_buildrequires
return config
def _load_config_label(document_id, document, settings):
config = {}
config["id"] = document_id
# Step 1: Mandatory fields
try:
# Name is an identifier for humans
config["name"] = str(document["data"]["name"])
# A short description, perhaps hinting the purpose
config["description"] = str(document["data"]["description"])
# Who maintains it? This is just a freeform string
# for humans to read. In Fedora, a FAS nick is recommended.
config["maintainer"] = str(document["data"]["maintainer"])
except KeyError:
raise ConfigError("Error: {file} is invalid.".format(file=yml_file))
# Step 2: Optional fields
# none here
return config
def _load_config_compose_view(document_id, document, settings):
config = {}
config["id"] = document_id
config["type"] = "compose"
# Step 1: Mandatory fields
try:
# Name is an identifier for humans
config["name"] = str(document["data"]["name"])
# A short description, perhaps hinting the purpose
config["description"] = str(document["data"]["description"])
# Who maintains it? This is just a freeform string
# for humans to read. In Fedora, a FAS nick is recommended.
config["maintainer"] = str(document["data"]["maintainer"])
# Labels connect things together.
# Workloads get installed in environments with the same label.
# They also get included in views with the same label.
config["labels"] = []
for repo in document["data"]["labels"]:
config["labels"].append(str(repo))
# Choose one repository that gets used as a source.
config["repository"] = str(document["data"]["repository"])
except KeyError:
raise ConfigError("Error: {document_id}.yml is invalid.".format(document_id=document_id))
# Step 2: Optional fields
# Limit this view only to the following architectures
config["architectures"] = []
if "architectures" in document["data"]:
for repo in document["data"]["architectures"]:
config["architectures"].append(str(repo))
# Limit this view only to the following pkgs
config["unwanted_packages"] = []
if "unwanted_packages" in document["data"]:
for pkg in document["data"]["unwanted_packages"]:
config["unwanted_packages"].append(str(pkg))
# Architecture-specific packages.
config["unwanted_arch_packages"] = {}
for arch in settings["allowed_arches"]:
config["unwanted_arch_packages"][arch] = []
if "unwanted_arch_packages" in document["data"]:
for arch, pkgs in document["data"]["unwanted_arch_packages"].items():
if arch not in settings["allowed_arches"]:
err_log("Error: {file}.yaml lists an invalid architecture: {arch}. Ignoring.".format(
file=document_id,
arch=arch
))
continue
for pkg_raw in pkgs:
pkg = str(pkg_raw)
config["unwanted_arch_packages"][arch].append(pkg)
return config
def _load_config_unwanted(document_id, document, settings):
config = {}
config["id"] = document_id
# Step 1: Mandatory fields
try:
# Name is an identifier for humans
config["name"] = str(document["data"]["name"])
# A short description, perhaps hinting the purpose
config["description"] = str(document["data"]["description"])
# Who maintains it? This is just a freeform string
# for humans to read. In Fedora, a FAS nick is recommended.
config["maintainer"] = str(document["data"]["maintainer"])
# Labels connect things together.
# Workloads get installed in environments with the same label.
# They also get included in views with the same label.
config["labels"] = []
for repo in document["data"]["labels"]:
config["labels"].append(str(repo))
except KeyError:
raise ConfigError("Error: {document_id}.yml is invalid.".format(document_id=document_id))
# Step 2: Optional fields
# Limit this view only to the following pkgs
config["unwanted_packages"] = []
if "unwanted_packages" in document["data"]:
for pkg in document["data"]["unwanted_packages"]:
config["unwanted_packages"].append(str(pkg))
# Architecture-specific packages.
config["unwanted_arch_packages"] = {}
for arch in settings["allowed_arches"]:
config["unwanted_arch_packages"][arch] = []
if "unwanted_arch_packages" in document["data"]:
for arch, pkgs in document["data"]["unwanted_arch_packages"].items():
if arch not in settings["allowed_arches"]:
err_log("Error: {file}.yaml lists an invalid architecture: {arch}. Ignoring.".format(
file=document_id,
arch=arch
))
continue
for pkg_raw in pkgs:
pkg = str(pkg_raw)
config["unwanted_arch_packages"][arch].append(pkg)
# Limit this view only to the following pkgs
config["unwanted_source_packages"] = []
if "unwanted_source_packages" in document["data"]:
for pkg in document["data"]["unwanted_source_packages"]:
config["unwanted_source_packages"].append(str(pkg))
# Architecture-specific packages.
config["unwanted_arch_source_packages"] = {}
for arch in settings["allowed_arches"]:
config["unwanted_arch_source_packages"][arch] = []
if "unwanted_arch_source_packages" in document["data"]:
for arch, pkgs in document["data"]["unwanted_arch_source_packages"].items():
if arch not in settings["allowed_arches"]:
err_log("Error: {file}.yaml lists an invalid architecture: {arch}. Ignoring.".format(
file=document_id,
arch=arch
))
continue
for pkg_raw in pkgs:
pkg = str(pkg_raw)
config["unwanted_arch_source_packages"][arch].append(pkg)
return config
def get_configs(settings):
log("")
log("###############################################################################")
log("### Loading user-provided configs #############################################")
log("###############################################################################")
log("")
directory = settings["configs"]
if "allowed_arches" not in settings:
err_log("System error: allowed_arches not configured")
raise SettingsError
if not settings["allowed_arches"]:
err_log("System error: no allowed_arches not configured")
raise SettingsError
configs = {}
configs["repos"] = {}
configs["envs"] = {}
configs["workloads"] = {}
configs["labels"] = {}
configs["views"] = {}
configs["unwanteds"] = {}
# Step 1: Load all configs
log("Loading config files...")
for yml_file in os.listdir(directory):
# Only accept yaml files
if not yml_file.endswith(".yaml"):
continue
document_id = yml_file.split(".yaml")[0]
try:
with open(os.path.join(directory, yml_file), "r") as file:
# Safely load the config
try:
document = yaml.safe_load(file)
except yaml.YAMLError as err:
raise ConfigError("Error loading a config '{filename}': {err}".format(
filename=yml_file,
err=err))
# Only accept yaml files stating their purpose!
if not ("document" in document and "version" in document):
raise ConfigError("Error: {file} is invalid.".format(file=yml_file))
# === Case: Repository config ===
if document["document"] == "feedback-pipeline-repository":
configs["repos"][document_id] = _load_config_repo(document_id, document, settings)
# === Case: Environment config ===
if document["document"] == "feedback-pipeline-environment":
configs["envs"][document_id] = _load_config_env(document_id, document, settings)
# === Case: Workload config ===
if document["document"] == "feedback-pipeline-workload":
configs["workloads"][document_id] = _load_config_workload(document_id, document, settings)
# === Case: Label config ===
if document["document"] == "feedback-pipeline-label":
configs["labels"][document_id] = _load_config_label(document_id, document, settings)
# === Case: View config ===
if document["document"] == "feedback-pipeline-compose-view":
configs["views"][document_id] = _load_config_compose_view(document_id, document, settings)
# === Case: Unwanted config ===
if document["document"] == "feedback-pipeline-unwanted":
configs["unwanteds"][document_id] = _load_config_unwanted(document_id, document, settings)
except ConfigError as err:
err_log("Config load error: {err}. Ignoring.".format(err=err))
continue
log(" Done!")
log("")
# Step 2: cross check configs for references and other validation
log(" Validating configs...")
# FIXME: Do this, please!
log(" Warning: This is not implemented, yet!")
log(" But there would be a traceback somewhere during runtime ")
log(" if an error exists, so wrong outputs won't happen.")
log(" Done!")
log("")
log("Done! Loaded:")
log(" - {} repositories".format(len(configs["repos"])))
log(" - {} environments".format(len(configs["envs"])))
log(" - {} workloads".format(len(configs["workloads"])))
log(" - {} labels".format(len(configs["labels"])))
log(" - {} views".format(len(configs["views"])))
log(" - {} exclusion lists".format(len(configs["unwanteds"])))
log("")
return configs
###############################################################################
### Analyzing stuff! ##########################################################
###############################################################################
# Configs:
# TYPE: KEY: ID:
# - repo repos repo_id
# - env_conf envs env_id
# - workload_conf workloads workload_id
# - label labels label_id
# - conf_view views view_id
#
# Data:
# TYPE: KEY: ID:
# - pkg pkgs/repo_id/arch NEVR
# - env envs env_id:repo_id:arch_id
# - workload workloads workload_id:env_id:repo_id:arch_id
# - view views view_id:repo_id:arch_id
#
# tmp contents:
# - dnf_cachedir-{repo}-{arch}
# - dnf_generic_installroot-{repo}-{arch}
# - dnf_env_installroot-{env_conf}-{repo}-{arch}
#
#
def _analyze_pkgs(tmp, repo, arch):
log("Analyzing pkgs for {repo_name} ({repo_id}) {arch}".format(
repo_name=repo["name"],
repo_id=repo["id"],
arch=arch
))
with dnf.Base() as base:
# Local DNF cache
cachedir_name = "dnf_cachedir-{repo}-{arch}".format(
repo=repo["id"],
arch=arch
)
base.conf.cachedir = os.path.join(tmp, cachedir_name)
# Generic installroot
root_name = "dnf_generic_installroot-{repo}-{arch}".format(
repo=repo["id"],
arch=arch
)
base.conf.installroot = os.path.join(tmp, root_name)
# Architecture
base.conf.arch = arch
base.conf.ignorearch = True
# Repository
base.conf.substitutions['releasever'] = repo["source"]["fedora_release"]
# Additional repository (if configured)
if repo["source"]["additional_repository"]:
additional_repo = dnf.repo.Repo(name="additional-repository",parent_conf=base.conf)
additional_repo.baseurl = [repo["source"]["additional_repository"]]
additional_repo.priority = 1
base.repos.add(additional_repo)
# Load repos
log(" Loading repos...")
base.read_all_repos()
# At this stage, I need to get all packages from the repo listed.
# That also includes modular packages. Modular packages in non-enabled
# streams would be normally hidden. So I mark all the available repos as
# hotfix repos to make all packages visible, including non-enabled streams.
for repo in base.repos.all():
repo.module_hotfixes = True
# This sometimes fails, so let's try at least N times
# before totally giving up!
MAX_TRIES = 10
attempts = 0
success = False
while attempts < MAX_TRIES:
try:
base.fill_sack(load_system_repo=False)
success = True
break
except dnf.exceptions.RepoError as err:
attempts +=1
log(" Failed to download repodata. Trying again!")
if not success:
err = "Failed to download repodata while analyzing repo '{repo_name} ({repo_id}) {arch}".format(
repo_name=repo["name"],
repo_id=repo["id"],
arch=arch
)
err_log(err)
raise RepoDownloadError(err)
# DNF query
query = base.sack.query
# Get all packages
all_pkgs_set = set(query())
pkgs = {}
for pkg_object in all_pkgs_set:
pkg_nevra = "{name}-{evr}.{arch}".format(
name=pkg_object.name,
evr=pkg_object.evr,
arch=pkg_object.arch)
pkg = {}
pkg["id"] = pkg_nevra
pkg["name"] = pkg_object.name
pkg["evr"] = pkg_object.evr
pkg["arch"] = pkg_object.arch
pkg["installsize"] = pkg_object.installsize
pkg["description"] = pkg_object.description
#pkg["provides"] = pkg_object.provides
#pkg["requires"] = pkg_object.requires
#pkg["recommends"] = pkg_object.recommends
#pkg["suggests"] = pkg_object.suggests
pkg["summary"] = pkg_object.summary
pkg["source_name"] = pkg_object.source_name
pkg["sourcerpm"] = pkg_object.sourcerpm
pkgs[pkg_nevra] = pkg
log(" Done! ({pkg_count} packages in total)".format(
pkg_count=len(pkgs)
))
log("")
return pkgs
def _analyze_env(tmp, env_conf, repo, arch):
env = {}
env["env_conf_id"] = env_conf["id"]
env["pkg_ids"] = []
env["repo_id"] = repo["id"]
env["arch"] = arch
env["errors"] = {}
env["errors"]["non_existing_pkgs"] = []
env["succeeded"] = True
with dnf.Base() as base:
# Local DNF cache
cachedir_name = "dnf_cachedir-{repo}-{arch}".format(
repo=repo["id"],
arch=arch
)
base.conf.cachedir = os.path.join(tmp, cachedir_name)
# Environment installroot
root_name = "dnf_env_installroot-{env_conf}-{repo}-{arch}".format(
env_conf=env_conf["id"],
repo=repo["id"],
arch=arch
)
base.conf.installroot = os.path.join(tmp, root_name)
# Architecture
base.conf.arch = arch
base.conf.ignorearch = True
# Repository
base.conf.substitutions['releasever'] = repo["source"]["fedora_release"]
# Additional repository (if configured)
if repo["source"]["additional_repository"]:
additional_repo = dnf.repo.Repo(name="additional-repository",parent_conf=base.conf)
additional_repo.baseurl = [repo["source"]["additional_repository"]]
additional_repo.priority = 1
base.repos.add(additional_repo)
# Additional DNF Settings
base.conf.tsflags.append('justdb')
# Environment config
if "include-weak-deps" not in env_conf["options"]:
base.conf.install_weak_deps = False
if "include-docs" not in env_conf["options"]:
base.conf.tsflags.append('nodocs')
# Load repos
log(" Loading repos...")
base.read_all_repos()
# This sometimes fails, so let's try at least N times
# before totally giving up!
MAX_TRIES = 10
attempts = 0
success = False
while attempts < MAX_TRIES:
try:
base.fill_sack(load_system_repo=False)
success = True
break
except dnf.exceptions.RepoError as err:
attempts +=1
log(" Failed to download repodata. Trying again!")
if not success:
err = "Failed to download repodata while analyzing environment '{env_conf}' from '{repo}' {arch}:".format(
env_conf=env_conf["id"],
repo=repo["id"],
arch=arch
)
err_log(err)
raise RepoDownloadError(err)
# Packages
log(" Adding packages...")
for pkg in env_conf["packages"]:
try:
base.install(pkg)
except dnf.exceptions.MarkingError:
env["errors"]["non_existing_pkgs"].append(pkg)
continue
# Architecture-specific packages
for pkg in env_conf["arch_packages"][arch]:
try:
base.install(pkg)
except dnf.exceptions.MarkingError:
env["errors"]["non_existing_pkgs"].append(pkg)
continue
# Resolve dependencies
log(" Resolving dependencies...")
try:
base.resolve()
except dnf.exceptions.DepsolveError as err:
err_log("Failed to analyze environment '{env_conf}' from '{repo}' {arch}:".format(
env_conf=env_conf["id"],
repo=repo["id"],
arch=arch
))
err_log(" - {err}".format(err=err))
env["succeeded"] = False
env["errors"]["message"] = str(err)
return env
# Write the result into RPMDB.
# The transaction needs us to download all the packages. :(
# So let's do that to make it happy.
log(" Downloading packages...")
base.download_packages(base.transaction.install_set)
log(" Running DNF transaction, writing RPMDB...")
try:
base.do_transaction()
except (dnf.exceptions.TransactionCheckError, dnf.exceptions.Error) as err:
err_log("Failed to analyze environment '{env_conf}' from '{repo}' {arch}:".format(
env_conf=env_conf["id"],
repo=repo["id"],
arch=arch
))
err_log(" - {err}".format(err=err))
env["succeeded"] = False
env["errors"]["message"] = str(err)
return env
# DNF Query
log(" Creating a DNF Query object...")
query = base.sack.query().filterm(pkg=base.transaction.install_set)
for pkg in query:
pkg_id = "{name}-{evr}.{arch}".format(
name=pkg.name,
evr=pkg.evr,
arch=pkg.arch
)
env["pkg_ids"].append(pkg_id)
log(" Done! ({pkg_count} packages in total)".format(
pkg_count=len(env["pkg_ids"])
))
log("")
return env
def _analyze_envs(tmp, configs):
envs = {}
# Look at all env configs...
for env_conf_id, env_conf in configs["envs"].items():
# For each of those, look at all repos it lists...
for repo_id in env_conf["repositories"]:
# And for each of the repo, look at all arches it supports.
repo = configs["repos"][repo_id]
for arch in repo["source"]["architectures"]:
# Now it has
# all env confs *
# repos each config lists *
# archeas each repo supports
# Analyze all of that!
log("Analyzing {env_name} ({env_id}) from {repo_name} ({repo}) {arch}...".format(
env_name=env_conf["name"],
env_id=env_conf_id,
repo_name=repo["name"],
repo=repo_id,
arch=arch
))
env_id = "{env_conf_id}:{repo_id}:{arch}".format(
env_conf_id=env_conf_id,
repo_id=repo_id,
arch=arch
)
envs[env_id] = _analyze_env(tmp, env_conf, repo, arch)
return envs
def _analyze_package_relations(dnf_query, package_placeholders = None):
relations = {}
for pkg in dnf_query:
pkg_id = "{name}-{evr}.{arch}".format(
name=pkg.name,
evr=pkg.evr,
arch=pkg.arch
)
required_by = set()
recommended_by = set()
suggested_by = set()
for dep_pkg in dnf_query.filter(requires=pkg.provides):
dep_pkg_id = "{name}-{evr}.{arch}".format(
name=dep_pkg.name,
evr=dep_pkg.evr,
arch=dep_pkg.arch
)
required_by.add(dep_pkg_id)
for dep_pkg in dnf_query.filter(recommends=pkg.provides):
dep_pkg_id = "{name}-{evr}.{arch}".format(
name=dep_pkg.name,
evr=dep_pkg.evr,
arch=dep_pkg.arch
)
recommended_by.add(dep_pkg_id)
for dep_pkg in dnf_query.filter(suggests=pkg.provides):
dep_pkg_id = "{name}-{evr}.{arch}".format(
name=dep_pkg.name,
evr=dep_pkg.evr,
arch=dep_pkg.arch
)
suggested_by.add(dep_pkg_id)
relations[pkg_id] = {}
relations[pkg_id]["required_by"] = sorted(list(required_by))
relations[pkg_id]["recommended_by"] = sorted(list(recommended_by))
relations[pkg_id]["suggested_by"] = sorted(list(suggested_by))
if package_placeholders:
for placeholder_name,placeholder_data in package_placeholders.items():
placeholder_id = pkg_placeholder_name_to_id(placeholder_name)
relations[placeholder_id] = {}
relations[placeholder_id]["required_by"] = []
relations[placeholder_id]["recommended_by"] = []
relations[placeholder_id]["suggested_by"] = []
for placeholder_name,placeholder_data in package_placeholders.items():
placeholder_id = pkg_placeholder_name_to_id(placeholder_name)
for placeholder_dependency_name in placeholder_data["requires"]:
for pkg_id in relations:
pkg_name = pkg_id_to_name(pkg_id)
if pkg_name == placeholder_dependency_name:
relations[pkg_id]["required_by"].append(placeholder_id)
return relations
def _return_failed_workload_env_err(workload_conf, env_conf, repo, arch):