-
Notifications
You must be signed in to change notification settings - Fork 8
/
image-info
executable file
·2883 lines (2404 loc) · 90.7 KB
/
image-info
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
import configparser
import contextlib
import functools
import glob
import mimetypes
import operator
import json
import os
import platform
import re
import stat
import subprocess
import sys
import time
import tempfile
import xml.etree.ElementTree
import yaml
import pathlib
import jsonschema
from collections import OrderedDict
from typing import Dict, Any
from osbuild import devices, host, mounts, meta, monitor
index = meta.Index("/usr/lib/osbuild/")
SECTOR_SIZE = 512
def run_ostree(*args, _input=None, _check=True, **kwargs):
args = list(args) + [f'--{k}={v}' for k, v in kwargs.items()]
print("ostree " + " ".join(args), file=sys.stderr)
res = subprocess.run(["ostree"] + args,
encoding="utf-8",
stdout=subprocess.PIPE,
input=_input,
check=_check)
return res
def loop_open(devmgr: devices.DeviceManager, name: str, image, size, offset=0):
"""
Uses a DeviceManager to open the `name` at `offset`
Retuns a Device object and the path onto wich the image was loopback mounted
"""
info = index.get_module_info("Device", "org.osbuild.loopback")
fname = os.path.basename(image)
options = {
"filename": fname,
"start": offset // SECTOR_SIZE,
"size": size // SECTOR_SIZE
}
if not info:
raise RuntimeError("Can't load org.osbuild.loopback")
jsonschema.validate(options, info.get_schema())
dev = devices.Device(name, info, None, options)
reply = devmgr.open(dev)
return {
"Device": dev,
"path": os.path.join("/dev", reply["path"])
}
@contextlib.contextmanager
def convert_image(image, fmt):
with tempfile.TemporaryDirectory(dir="/var/tmp") as tmp:
if fmt["type"] != "raw":
target = os.path.join(tmp, "image.raw")
# A bug exists in qemu that causes the conversion to raw to fail
# on aarch64 systems with a LOT of CPUs. A workaround is to use
# a single coroutine to do the conversion. It doesn't slow down
# the conversion by much, but it hangs about half the time without
# the limit set. 😢
# Bug: https://bugs.launchpad.net/qemu/+bug/1805256
if platform.machine() == 'aarch64':
subprocess.run(
["qemu-img", "convert", "-m", "1", "-O", "raw", image, target],
check=True
)
else:
subprocess.run(
["qemu-img", "convert", "-O", "raw", image, target],
check=True
)
else:
target = image
yield target
@contextlib.contextmanager
def mount_at(device, mountpoint, options=[], extra=[]):
opts = ",".join(["ro"] + options)
subprocess.run(["mount", "-o", opts] + extra + [device, mountpoint], check=True)
try:
yield mountpoint
finally:
subprocess.run(["umount", "--lazy", mountpoint], check=True)
@contextlib.contextmanager
def mount(device, options=None):
options = options or []
opts = ",".join(["ro"] + options)
with tempfile.TemporaryDirectory() as mountpoint:
subprocess.run(["mount", "-o", opts, device, mountpoint], check=True)
try:
yield mountpoint
finally:
subprocess.run(["umount", "--lazy", mountpoint], check=True)
def parse_environment_vars(s):
r = {}
for line in s.split("\n"):
line = line.strip()
if not line:
continue
if line[0] == '#':
continue
key, value = line.split("=", 1)
r[key] = value.strip('"')
return r
# Parses output of `systemctl list-unit-files`
def parse_unit_files(s, expected_state):
r = []
for line in s.split("\n")[1:]:
state = ""
unit = ""
try:
unit, state, *_ = line.split()
except ValueError:
pass
if state != expected_state:
continue
r.append(unit)
return r
def subprocess_check_output(argv, parse_fn=None) -> Any:
try:
output = subprocess.check_output(argv, encoding="utf-8")
except subprocess.CalledProcessError as e:
sys.stderr.write(f"--- Output from {argv}:\n")
sys.stderr.write(e.stdout)
sys.stderr.write("\n--- End of the output\n")
raise
return parse_fn(output) if parse_fn else output
def read_container_images(tree):
"""
Read installed containers
Returns: a dictionary listing the container images in the format
like `podman images --format json` but with less information.
NB: The parsing is done "manually" since running `podman` in the
chroot does not work.
"""
images = []
images_index = os.path.join("overlay-images", "images.json")
for d in ("/var/lib/containers/storage", ):
path = os.path.join(tree, d.lstrip("/"), images_index)
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
except FileNotFoundError:
continue
for image in data:
img = {
"Id": image["id"],
"Digest": image["digest"],
"Names": image["names"],
}
created = image.get("created")
if created:
img["Created"] = created
images.append(img)
return images
def read_image_format(device) -> Dict[str, str]:
"""
Read image format.
Returns: dictionary with at least one key 'type'. 'type' value is a string
representing the format of the image. In case the type is 'qcow2', the returned
dictionary contains second key 'compat' with a string value representing
the compatibility version of the 'qcow2' image.
An example return value:
{
"compat": "1.1",
"type": "qcow2"
}
"""
qemu = subprocess_check_output(["qemu-img", "info", "--output=json", device], json.loads)
format = qemu["format"]
result = {"type": format}
if format == "qcow2":
result["compat"] = qemu["format-specific"]["data"]["compat"]
return result
def read_partition(device, partition):
"""
Read block device attributes using 'blkid' and extend the passed 'partition'
dictionary.
Returns: the 'partition' dictionary provided as an argument, extended with
'label', 'uuid' and 'fstype' keys and their values.
"""
res = subprocess.run(["blkid", "-c", "/dev/null", "--output", "export",
device],
check=False, encoding="utf-8",
stdout=subprocess.PIPE)
if res.returncode == 0:
blkid = parse_environment_vars(res.stdout)
else:
blkid = {}
partition["label"] = blkid.get("LABEL") # doesn't exist for mbr
partition["uuid"] = blkid.get("UUID")
partition["fstype"] = blkid.get("TYPE")
return partition
def read_partition_table(device):
"""
Read information related to found partitions and partitioning table from
the device.
Returns: dictionary with three keys - 'partition-table', 'partition-table-id'
and 'partitions'.
'partition-table' value is a string with the type of the partition table or 'None'.
'partition-table-id' value is a string with the ID of the partition table or 'None'.
'partitions' value is a list of dictionaries representing found partitions.
An example return value:
{
"partition-table": "gpt",
"partition-table-id": "DA237A6F-F0D4-47DF-BB50-007E00DB347C",
"partitions": [
{
"bootable": false,
"partuuid": "64AF1EC2-0328-406A-8F36-83016E6DD858",
"size": 1048576,
"start": 1048576,
"type": "21686148-6449-6E6F-744E-656564454649",
},
{
"bootable": false,
"partuuid": "D650D523-06F6-4B90-9204-8F998FE9703C",
"size": 6442450944,
"start": 2097152,
"type": "0FC63DAF-8483-4772-8E79-3D69D8477DE4",
}
]
}
"""
partitions = []
info = {"partition-table": None,
"partition-table-id": None,
"partitions": partitions}
try:
sfdisk = subprocess_check_output(["sfdisk", "--json", device], json.loads)
except subprocess.CalledProcessError:
# This handles a case, when the device does contain a filesystem,
# but there is no partition table.
partitions.append(read_partition(device, {}))
return info
ptable = sfdisk["partitiontable"]
assert ptable["unit"] == "sectors"
is_dos = ptable["label"] == "dos"
ssize = ptable.get("sectorsize", SECTOR_SIZE)
for i, p in enumerate(ptable["partitions"]):
partuuid = p.get("uuid")
if not partuuid and is_dos:
# For dos/mbr partition layouts the partition uuid
# is generated. Normally this would be done by
# udev+blkid, when the partition table is scanned.
# 'sfdisk' prefixes the partition id with '0x' but
# 'blkid' does not; remove it to mimic 'blkid'
table_id = ptable['id'][2:]
partuuid = "%.33s-%02x" % (table_id, i+1)
partitions.append({
"bootable": p.get("bootable", False),
"type": p["type"],
"start": p["start"] * ssize,
"size": p["size"] * ssize,
"partuuid": partuuid
})
info["partitions"] = sorted(info["partitions"], key=operator.itemgetter("partuuid"))
info["partition-table"] = ptable["label"]
info["partition-table-id"] = ptable["id"]
return info
def read_bootloader_type(device) -> str:
"""
Read bootloader type from the provided device.
Returns: string representing the found bootloader. Function can return two values:
- 'grub'
- 'unknown'
"""
with open(device, "rb") as f:
if b"GRUB" in f.read(SECTOR_SIZE):
return "grub"
else:
return "unknown"
def read_boot_entries(boot_dir):
"""
Read boot entries.
Returns: list of dictionaries representing configured boot entries.
An example return value:
[
{
"grub_arg": "--unrestricted",
"grub_class": "kernel",
"grub_users": "$grub_users",
"id": "rhel-20210429130346-0-rescue-c116920b13f44c59846f90b1057605bc",
"initrd": "/boot/initramfs-0-rescue-c116920b13f44c59846f90b1057605bc.img",
"linux": "/boot/vmlinuz-0-rescue-c116920b13f44c59846f90b1057605bc",
"options": "$kernelopts",
"title": "Red Hat Enterprise Linux (0-rescue-c116920b13f44c59846f90b1057605bc) 8.4 (Ootpa)",
"version": "0-rescue-c116920b13f44c59846f90b1057605bc"
},
{
"grub_arg": "--unrestricted",
"grub_class": "kernel",
"grub_users": "$grub_users",
"id": "rhel-20210429130346-4.18.0-305.el8.x86_64",
"initrd": "/boot/initramfs-4.18.0-305.el8.x86_64.img $tuned_initrd",
"linux": "/boot/vmlinuz-4.18.0-305.el8.x86_64",
"options": "$kernelopts $tuned_params",
"title": "Red Hat Enterprise Linux (4.18.0-305.el8.x86_64) 8.4 (Ootpa)",
"version": "4.18.0-305.el8.x86_64"
}
]
"""
entries = []
for conf in glob.glob(f"{boot_dir}/loader/entries/*.conf"):
with open(conf) as f:
entries.append(dict(line.strip().split(" ", 1) for line in f))
return sorted(entries, key=lambda e: e["title"])
def rpm_verify(tree):
"""
Read the output of 'rpm --verify'.
Returns: dictionary with two keys 'changed' and 'missing'.
'changed' value is a dictionary with the keys representing modified files from
installed RPM packages and values representing types of applied modifications.
'missing' value is a list of strings prepresenting missing values owned by
installed RPM packages.
An example return value:
{
"changed": {
"/etc/chrony.conf": "S.5....T.",
"/etc/cloud/cloud.cfg": "S.5....T.",
"/etc/nsswitch.conf": "....L....",
"/etc/openldap/ldap.conf": ".......T.",
"/etc/pam.d/fingerprint-auth": "....L....",
"/etc/pam.d/password-auth": "....L....",
"/etc/pam.d/postlogin": "....L....",
"/etc/pam.d/smartcard-auth": "....L....",
"/etc/pam.d/system-auth": "....L....",
"/etc/rhsm/rhsm.conf": "..5....T.",
"/etc/sudoers": "S.5....T.",
"/etc/systemd/logind.conf": "S.5....T."
},
"missing": [
"/etc/udev/rules.d/70-persistent-ipoib.rules",
"/run/cloud-init",
"/run/rpcbind",
"/run/setrans",
"/run/tuned"
]
}
"""
# cannot use `rpm --root` here, because rpm uses passwd from the host to
# verify user and group ownership:
# https://github.com/rpm-software-management/rpm/issues/882
rpm = subprocess.Popen(["chroot", tree, "rpm", "--verify", "--all"],
stdout=subprocess.PIPE, encoding="utf-8")
changed = {}
missing = []
if rpm.stdout:
for line in rpm.stdout:
# format description in rpm(8), under `--verify`
attrs = line[:9]
if attrs == "missing ":
missing.append(line[12:].rstrip())
else:
changed[line[13:].rstrip()] = attrs
# ignore return value, because it returns non-zero when it found changes
rpm.wait()
return {
"missing": sorted(missing),
"changed": changed
}
def rpm_not_installed_docs(tree):
"""
Gathers information on documentation, which is part of RPM packages,
but was not installed.
Returns: list of documentation files, which are normally a part of
the installed RPM packages, but were not installed (e.g. due to using
'--excludedocs' option when executing 'rpm' command).
An example return value:
[
"/usr/share/man/man1/sdiff.1.gz",
"/usr/share/man/man1/seapplet.1.gz",
"/usr/share/man/man1/secon.1.gz",
"/usr/share/man/man1/secret-tool.1.gz",
"/usr/share/man/man1/sed.1.gz",
"/usr/share/man/man1/seq.1.gz"
]
"""
# check not installed Docs (e.g. when RPMs are installed with --excludedocs)
not_installed_docs = []
cmd = ["rpm", "--root", tree, "-qad", "--state"]
if os.path.exists(os.path.join(tree, "usr/share/rpm")):
cmd += ["--dbpath", "/usr/share/rpm"]
elif os.path.exists(os.path.join(tree, "var/lib/rpm")):
cmd += ["--dbpath", "/var/lib/rpm"]
output = subprocess_check_output(cmd)
for line in output.splitlines():
if line.startswith("not installed"):
not_installed_docs.append(line.split()[-1])
return sorted(not_installed_docs)
def rpm_packages(tree):
"""
Read NVRs of RPM packages installed on the system.
Returns: sorted list of strings representing RPM packages installed
on the system.
An example return value:
[
"NetworkManager-1.30.0-7.el8.x86_64",
"PackageKit-glib-1.1.12-6.el8.x86_64",
"PackageKit-gtk3-module-1.1.12-6.el8.x86_64",
"abattis-cantarell-fonts-0.0.25-6.el8.noarch",
"acl-2.2.53-1.el8.x86_64",
"adobe-mappings-cmap-20171205-3.el8.noarch",
"adobe-mappings-cmap-deprecated-20171205-3.el8.noarch",
"adobe-mappings-pdf-20180407-1.el8.noarch",
"adwaita-cursor-theme-3.28.0-2.el8.noarch",
"adwaita-icon-theme-3.28.0-2.el8.noarch",
"alsa-lib-1.2.4-5.el8.x86_64"
]
"""
cmd = ["rpm", "--root", tree, "-qa"]
if os.path.exists(os.path.join(tree, "usr/share/rpm")):
cmd += ["--dbpath", "/usr/share/rpm"]
elif os.path.exists(os.path.join(tree, "var/lib/rpm")):
cmd += ["--dbpath", "/var/lib/rpm"]
subprocess_check_output(cmd)
pkgs = subprocess_check_output(cmd, str.split)
return list(sorted(pkgs))
@contextlib.contextmanager
def change_root(root):
real_root = os.open("/", os.O_RDONLY)
try:
os.chroot(root)
yield None
finally:
os.fchdir(real_root)
os.chroot(".")
os.close(real_root)
def read_services(tree, state):
"""
Read the list of systemd services on the system in the given state.
Returns: alphabetically sorted list of strings representing systemd services
in the given state.
The returned list may be empty.
An example return value:
[
"arp-ethers.service",
"canberra-system-bootup.service",
"canberra-system-shutdown-reboot.service",
"canberra-system-shutdown.service",
"chrony-wait.service"
]
"""
services_state = subprocess_check_output(
["systemctl", f"--root={tree}", "list-unit-files"], (lambda s: parse_unit_files(s, state)))
# Since systemd v246, some services previously reported as "enabled" /
# "disabled" are now reported as "alias". There is no systemd command, that
# would take an "alias" unit and report its state as enabled/disabled
# and could run on a different tree (with "--root" option).
# To make the produced list of services in the given state consistent on
# pre/post v246 systemd versions, check all "alias" units and append them
# to the list, if their target is also listed in 'services_state'.
if state != "alias":
services_alias = subprocess_check_output(
["systemctl", f"--root={tree}", "list-unit-files"], (lambda s: parse_unit_files(s, "alias")))
for alias in services_alias:
# The service may be in one of the following places (output of
# "systemd-analyze unit-paths", it should not change too often).
unit_paths = [
"/etc/systemd/system.control",
"/run/systemd/system.control",
"/run/systemd/transient",
"/run/systemd/generator.early",
"/etc/systemd/system",
"/run/systemd/system",
"/run/systemd/generator",
"/usr/local/lib/systemd/system",
"/usr/lib/systemd/system",
"/run/systemd/generator.late"
]
with change_root(tree):
for path in unit_paths:
unit_path = os.path.join(path, alias)
if os.path.exists(unit_path):
real_unit_path = os.path.realpath(unit_path)
# Skip the alias, if there was a symlink cycle.
# When symbolic link cycles occur, the returned path will
# be one member of the cycle, but no guarantee is made about
# which member that will be.
if os.path.islink(real_unit_path):
continue
# Append the alias unit to the list, if its target is
# already there.
if os.path.basename(real_unit_path) in services_state:
services_state.append(alias)
# deduplicate and sort
services_state = list(set(services_state))
services_state.sort()
return services_state
def read_default_target(tree):
"""
Read the default systemd target.
Returns: string representing the default systemd target.
An example return value:
"multi-user.target"
"""
return subprocess_check_output(["systemctl", f"--root={tree}", "get-default"]).rstrip()
def read_firewall_default_zone(tree):
"""
Read the name of the default firewall zone
Returns: a string with the zone name. If the firewall configuration doesn't
exist, an empty string is returned.
An example return value:
"trusted"
"""
try:
with open(f"{tree}/etc/firewalld/firewalld.conf") as f:
conf = parse_environment_vars(f.read())
return conf["DefaultZone"]
except FileNotFoundError:
return ""
def read_firewall_zone(tree):
"""
Read enabled services from the configuration of the default firewall zone.
Returns: list of strings representing enabled services in the firewall.
The returned list may be empty.
An example return value:
[
"ssh",
"dhcpv6-client",
"cockpit"
]
"""
default = read_firewall_default_zone(tree)
if default == "":
default = "public"
r = []
try:
root = xml.etree.ElementTree.parse(f"{tree}/etc/firewalld/zones/{default}.xml").getroot()
except FileNotFoundError:
root = xml.etree.ElementTree.parse(f"{tree}/usr/lib/firewalld/zones/{default}.xml").getroot()
for element in root.findall("service"):
r.append(element.get("name"))
return r
def read_fstab(tree):
"""
Read the content of /etc/fstab.
Returns: list of all uncommented lines read from the configuration file
represented as a list of values split by whitespaces.
The returned list may be empty.
An example return value:
[
[
"UUID=6d066eb4-e4c1-4472-91f9-d167097f48d1",
"/",
"xfs",
"defaults",
"0",
"0"
]
]
"""
result = []
with contextlib.suppress(FileNotFoundError):
with open(f"{tree}/etc/fstab") as f:
result = sorted([line.split() for line in f if line.strip() and not line.startswith("#")])
return result
def read_rhsm(tree):
"""
Read configuration changes possible via org.osbuild.rhsm stage
and in addition also the whole content of /etc/rhsm/rhsm.conf.
Returns: returns dictionary with two keys - 'dnf-plugins' and 'rhsm.conf'.
'dnf-plugins' value represents configuration of 'product-id' and
'subscription-manager' DNF plugins.
'rhsm.conf' value is a dictionary representing the content of the RHSM
configuration file.
The returned dictionary may be empty.
An example return value:
{
"dnf-plugins": {
"product-id": {
"enabled": true
},
"subscription-manager": {
"enabled": true
}
},
"rhsm.conf": {
"logging": {
"default_log_level": "INFO"
},
"rhsm": {
"auto_enable_yum_plugins": "1",
"baseurl": "https://cdn.redhat.com",
"ca_cert_dir": "/etc/rhsm/ca/",
"consumercertdir": "/etc/pki/consumer",
"entitlementcertdir": "/etc/pki/entitlement",
"full_refresh_on_yum": "0",
"inotify": "1",
"manage_repos": "0",
"package_profile_on_trans": "0",
"pluginconfdir": "/etc/rhsm/pluginconf.d",
"plugindir": "/usr/share/rhsm-plugins",
"productcertdir": "/etc/pki/product",
"repo_ca_cert": "/etc/rhsm/ca/redhat-uep.pem",
"repomd_gpg_url": "",
"report_package_profile": "1"
},
"rhsmcertd": {
"auto_registration": "1",
"auto_registration_interval": "60",
"autoattachinterval": "1440",
"certcheckinterval": "240",
"disable": "0",
"splay": "1"
},
"server": {
"hostname": "subscription.rhsm.redhat.com",
"insecure": "0",
"no_proxy": "",
"port": "443",
"prefix": "/subscription",
"proxy_hostname": "",
"proxy_password": "",
"proxy_port": "",
"proxy_scheme": "http",
"proxy_user": "",
"ssl_verify_depth": "3"
}
}
}
"""
result = {}
# Check RHSM DNF plugins configuration and allowed options
dnf_plugins_config = {
"product-id": f"{tree}/etc/dnf/plugins/product-id.conf",
"subscription-manager": f"{tree}/etc/dnf/plugins/subscription-manager.conf"
}
for plugin_name, plugin_path in dnf_plugins_config.items():
with contextlib.suppress(FileNotFoundError):
with open(plugin_path) as f:
parser = configparser.ConfigParser()
parser.read_file(f)
# only read "enabled" option from "main" section
with contextlib.suppress(configparser.NoSectionError, configparser.NoOptionError):
# get the value as the first thing, in case it raises an exception
enabled = parser.getboolean("main", "enabled")
try:
dnf_plugins_dict = result["dnf-plugins"]
except KeyError as _:
dnf_plugins_dict = result["dnf-plugins"] = {}
try:
plugin_dict = dnf_plugins_dict[plugin_name]
except KeyError as _:
plugin_dict = dnf_plugins_dict[plugin_name] = {}
plugin_dict["enabled"] = enabled
with contextlib.suppress(FileNotFoundError):
rhsm_conf = {}
with open(f"{tree}/etc/rhsm/rhsm.conf") as f:
parser = configparser.ConfigParser()
parser.read_file(f)
for section in parser.sections():
section_dict = {}
section_dict.update(parser[section])
if section_dict:
rhsm_conf[section] = section_dict
result["rhsm.conf"] = rhsm_conf
return result
def read_sysconfig(tree):
"""
Read selected configuration files from /etc/sysconfig.
Currently supported sysconfig files are:
- 'kernel' - /etc/sysconfig/kernel
- 'network' - /etc/sysconfig/network
- 'network-scripts' - /etc/sysconfig/network-scripts/ifcfg-*
Returns: dictionary with the keys being the supported types of sysconfig
configurations read by the function. Values of 'kernel' and 'network' keys
are a dictionaries containing key/values read from the respective
configuration files. Value of 'network-scripts' key is a dictionary with
the keys corresponding to the suffix of each 'ifcfg-*' configuration file
and their values holding dictionaries with all key/values read from the
configuration file.
The returned dictionary may be empty.
An example return value:
{
"kernel": {
"DEFAULTKERNEL": "kernel",
"UPDATEDEFAULT": "yes"
},
"network": {
"NETWORKING": "yes",
"NOZEROCONF": "yes"
},
"network-scripts": {
"ens3": {
"BOOTPROTO": "dhcp",
"BROWSER_ONLY": "no",
"DEFROUTE": "yes",
"DEVICE": "ens3",
"IPV4_FAILURE_FATAL": "no",
"IPV6INIT": "yes",
"IPV6_AUTOCONF": "yes",
"IPV6_DEFROUTE": "yes",
"IPV6_FAILURE_FATAL": "no",
"NAME": "ens3",
"ONBOOT": "yes",
"PROXY_METHOD": "none",
"TYPE": "Ethernet",
"UUID": "106f1b31-7093-41d6-ae47-1201710d0447"
},
"eth0": {
"BOOTPROTO": "dhcp",
"DEVICE": "eth0",
"IPV6INIT": "no",
"ONBOOT": "yes",
"PEERDNS": "yes",
"TYPE": "Ethernet",
"USERCTL": "yes"
}
}
}
"""
result = {}
sysconfig_paths = {
"kernel": f"{tree}/etc/sysconfig/kernel",
"network": f"{tree}/etc/sysconfig/network"
}
# iterate through supported configs
for name, path in sysconfig_paths.items():
with contextlib.suppress(FileNotFoundError):
with open(path) as f:
# if file exists start with empty array of values
result[name] = parse_environment_vars(f.read())
# iterate through all files in /etc/sysconfig/network-scripts
network_scripts = {}
files = glob.glob(f"{tree}/etc/sysconfig/network-scripts/ifcfg-*")
for file in files:
ifname = os.path.basename(file).lstrip("ifcfg-")
with open(file) as f:
network_scripts[ifname] = parse_environment_vars(f.read())
if network_scripts:
result["network-scripts"] = network_scripts
return result
def read_hosts(tree):
"""
Read non-empty lines of /etc/hosts.
Returns: list of strings for all uncommented lines in the configuration file.
The returned list may be empty.
An example return value:
[
"127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4",
"::1 localhost localhost.localdomain localhost6 localhost6.localdomain6"
]
"""
result = []
with contextlib.suppress(FileNotFoundError):
with open(f"{tree}/etc/hosts") as f:
for line in f:
line = line.strip()
if line:
result.append(line)
return result
def read_logind_config(config_path):
"""
Read all uncommented key/values from the 'Login" section of system-logind
configuration file.
Returns: dictionary with key/values read from the configuration file.
The returned dictionary may be empty.
An example return value:
{
"NAutoVTs": "0"
}
"""
result = {}
with open(config_path) as f:
parser = configparser.RawConfigParser()
# prevent conversion of the option name to lowercase
parser.optionxform = lambda option: option
parser.read_file(f)
with contextlib.suppress(configparser.NoSectionError):
result.update(parser["Login"])
return result
def read_logind_configs(tree):
"""
Read all systemd-logind *.conf files from a predefined list of paths and
parse them.
The searched paths are:
- "/etc/systemd/logind.conf"
- "/etc/systemd/logind.conf.d/*.conf"
- "/usr/lib/systemd/logind.conf.d/*.conf"
Returns: dictionary as returned by '_read_glob_paths_with_parser()' with
configuration representation as returned by 'read_logind_config()'.
An example return value:
{
"/etc/systemd/logind.conf": {
"NAutoVTs": "0"
}
}
"""
checked_globs = [
"/etc/systemd/logind.conf",
"/etc/systemd/logind.conf.d/*.conf",
"/usr/lib/systemd/logind.conf.d/*.conf"
]
return _read_glob_paths_with_parser(tree, checked_globs, read_logind_config)
def read_locale(tree):
"""
Read all uncommented key/values set in /etc/locale.conf.
Returns: dictionary with key/values read from the configuration file.
The returned dictionary may be empty.
An example return value:
{
"LANG": "en_US"
}
"""
with contextlib.suppress(FileNotFoundError):
with open(f"{tree}/etc/locale.conf") as f:
return parse_environment_vars(f.read())
def read_selinux_info(tree, is_ostree):
"""
Read information related to SELinux.
Returns: dictionary with two keys - 'policy' and 'context-mismatch'.
'policy' value corresponds to the value returned by read_selinux_conf().
'context-mismatch' value corresponds to the value returned by
read_selinux_ctx_mismatch().
The returned dictionary may be empty. Keys with empty values are omitted.
An example return value:
{
"context-mismatch": [
{
"actual": "system_u:object_r:root_t:s0",
"expected": "system_u:object_r:device_t:s0",
"filename": "/dev"
},
{
"actual": "system_u:object_r:root_t:s0",
"expected": "system_u:object_r:default_t:s0",
"filename": "/proc"
}
],
"policy": {
"SELINUX": "permissive",
"SELINUXTYPE": "targeted"
}
}
"""
result = {}
policy = read_selinux_conf(tree)
if policy:
result["policy"] = policy
with contextlib.suppress(subprocess.CalledProcessError):