-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathsysdiff.py
executable file
·1536 lines (1380 loc) · 49.8 KB
/
sysdiff.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.7
#
# Copyright (c) 2020, 2022, Oracle and/or its affiliates.
#
"""sysdiff script"""
__version__ = "20220614"
import sys
import os
import stat
import fileinput
import subprocess
import time
import argparse
import configparser
class ContentsEntry:
"""contents file entry"""
def __init__(self):
self.ftype = None
self.major = None
self.minor = None
self.mode = None
self.owner = None
self.group = None
self.size = None
self.cksum = None
self.modtime = None
self.target = None
self.inode = None
self.list = None
self.pkglist = None
class FileDesc:
"""File description for the IPS packaging"""
#
# path is the path to file, si is stat_result for the file
#
def __init__(self, si, entry):
self.type = "unknown"
self.mode = stat.S_IMODE(si.st_mode)
self.owner = None
self.group = None
self.modtime = int(si.st_mtime)
self.nlink = si.st_nlink
self.inode = (si.st_dev, si.st_ino)
self.target = None
self.comment = ""
self.preserve = None
self.owner = get_user(si.st_uid)
if self.owner is None:
self.comment += f" Unmatched uid: {si.st_uid}"
self.group = get_group(si.st_gid)
if self.group is None:
self.comment += f" Unmatched gid: {si.st_gid}"
#
# We cannot distinguish between file and hardlink for 'new' files -
# all hardlinks for given file are identical from the OS
# point of view - so we initially set every regular file as 'file',
# process the contents to take advantage of known links, and,
# after the directory scan is complete, we'll re-work the 'new'
# files assuming first encountered file for given inode is 'file'
# and the remaining ones are 'hardlink'
# IPS does not deal with packaging block or character device files
# nor pipes or doors - all of them have to be handled by the app or
# driver itself. Note that /dev/ entries can be delivered, but these
# are plain symlinks into /devices/, not special files. All of these
# files will end up as the 'unhandled' type, as we cannot package them.
#
if stat.S_ISLNK(si.st_mode):
self.type = "link"
self.target = os.readlink(entry.path)
elif stat.S_ISDIR(si.st_mode):
self.type = "dir"
elif stat.S_ISREG(si.st_mode):
self.type = "file"
if self.nlink > 1:
self.type = "hardlink"
if self.inode in hardlinks:
self.target = hardlinks[self.inode]
elif stat.S_ISFIFO(si.st_mode):
self.type = "unhandled"
self.comment += "file type: FIFO"
elif stat.S_ISCHR(si.st_mode):
self.type = "unhandled"
self.comment += "file type: character device"
elif stat.S_ISBLK(si.st_mode):
self.type = "unhandled"
self.comment += "file type: block device"
elif stat.S_ISSOCK(si.st_mode):
self.type = "unhandled"
self.comment += "file type: socket"
elif stat.S_ISDOOR(si.st_mode):
self.type = "unhandled"
self.comment += "file type: door"
elif stat.S_ISPORT(si.st_mode):
self.type = "unhandled"
self.comment += "file type: event port"
zone_name = ""
zone_root = ""
tstamp = time.strftime("%Y%m%d%H%M%S")
output_dir = "/var/tmp"
new_files_fname = "new_files"
mod_files_fname = "mod_files"
mod_vol_files_fname = "mod_vol_files"
matched_files_fname = "matched_files"
pkg_fname = "pkg"
param_fname = "params"
param_section = "params"
params_read = False
pkg_file = None
defcache = "cache"
volTypes = {"v", "e"}
fileTypes = {"f"} | volTypes
devTypes = {"b", "c"}
dirTypes = {"d", "x"}
linkTypes = {"s", "l"}
excludeDirs = set()
excludeDirsPath = os.path.join(sys.path[0], "excludeDirs")
knownNewFiles = set()
knownModFiles = set()
pkglist = set()
newpkgs = set()
contents = {}
passwd = {}
group = {}
new_files = {}
mod_files = {}
mod_vol_files = {}
matched_files = {}
hardlinks = {}
enable_checksums = False
plain_output = False
quiet = False
preserve_age = 5
now = time.time()
pkg_fmri = "[email protected]"
pkg_summary = "test package"
pkg_desc = None
def parse_group():
"""Parse the group file from the target zone to populate cache"""
for line in fileinput.input(zone_root + "/etc/group"):
s = line.split(":")
if s[2] in group:
print("Duplicate entry in /etc/group|" + line + "|\n")
continue
group[s[2]] = s[0]
def parse_passwd():
"""Parse the psswd file from the target zone to populate cache"""
for line in fileinput.input(zone_root + "/etc/passwd"):
s = line.split(":")
if s[2] in passwd:
print("Duplicate entry in /etc/passwd|" + line + "|\n")
continue
passwd[s[2]] = s[0]
def get_group(gid):
"""Convert the gid to group name. The group cache is consulted first, then
a call to the naming service is done. If a match is found the result is
cached"""
if str(gid) in group:
return group[str(gid)]
command = ["getent", "group", str(gid)]
sp = subprocess.run(command, capture_output=True, text=True, check=False)
if sp.returncode != 0:
if not quiet:
print("command\n", " ".join(command), "\nfailed")
return None
s = sp.stdout.split(":")
if len(s) == 4:
group[str(gid)] = s[0]
return s[0]
return None
def get_user(uid):
"""Convert the uid to user name. The passwd cache is consulted first, then
a call to the naming service is done. If a match is found the result is
cached"""
if str(uid) in passwd:
return passwd[str(uid)]
command = ["getent", "passwd", str(uid)]
sp = subprocess.run(command, capture_output=True, text=True, check=False)
if sp.returncode != 0:
if not quiet:
print("command\n", " ".join(command), "\nfailed")
return None
s = sp.stdout.split(":")
if len(s) == 7:
passwd[str(uid)] = s[0]
return s[0]
return None
def get_cksum(path):
"""Calculate the checksum of the file"""
sp = subprocess.run(
("/usr/bin/sum", path), capture_output=True, text=True, check=False
)
if sp.returncode != 0:
sys.stdout.flush()
sys.stderr.write("sum " + path + " failed\n")
sys.stderr.write(sp.stderr)
sys.exit(1)
s = sp.stdout.split(" ")
return s[0]
def parse_contents(cpath):
"""Parse the 'contents' file from the target zone"""
for line in fileinput.input(cpath):
line = line.rstrip("\n")
#
# Skip comments
#
if line[0] == "#":
continue
#
# New style entries always start with /
#
if line[0] == "/":
#
# We split the entry into path, type, class and remainder,
# which will be further split depending on type
#
s = line.split(" ", 3)
path = s[0]
entry = ContentsEntry()
entry.ftype = s[1]
if entry.ftype in fileTypes:
s = s[3].split(" ", 6)
entry.mode = int(s[0], 8)
entry.owner = s[1]
entry.group = s[2]
entry.size = int(s[3])
entry.cksum = s[4]
entry.modtime = int(s[5])
entry.pkglist = s[6].split(" ")
elif entry.ftype in dirTypes:
s = s[3].split(" ", 3)
entry.mode = int(s[0], 8)
entry.owner = s[1]
entry.group = s[2]
entry.pkglist = s[3].split(" ")
elif entry.ftype in devTypes:
s = s[3].split(" ", 5)
entry.major = s[0]
entry.minor = s[1]
entry.mode = int(s[2], 8)
entry.owner = s[3]
entry.group = s[4]
entry.pkglist = s[5].split(" ")
elif entry.ftype in linkTypes:
entry.pkglist = s[3].split(" ")
# if (entry.ftype == "l"):
# print(entry.__dict__)
# sys.exit()
else:
#
# Parse old style entries
#
if not quiet:
print("Parsing old style entry |" + line + "|\n")
s = line.split(" ", 3)
entry = ContentsEntry()
entry.ftype = s[0]
path = s[2]
entry.pkglist = s[3].split(" ")
if entry.ftype in linkTypes:
#
# Link entries have path in format path=rpath - we need to split
# them for easier matching
#
s = path.split("=")
if len(s) != 2:
sys.stdout.flush()
print("Invalid link entry |" + path + "|\n", file=sys.stderr)
sys.exit(1)
path = s[0]
entry.target = s[1]
#
# This should never happen - there can be only single entry for each
# path
#
if path in contents:
sys.stdout.flush()
print("Duplicate entry for |" + path + "|\n", file=sys.stderr)
print(entry.__dict__, file=sys.stderr)
print(contents[path].__dict__, file=sys.stderr)
sys.exit(1)
#
# We check the pkglist for given entry against the 'clean' list
# to find non-Solaris pkgs installed
#
if len(pkglist) != 0:
for d in entry.pkglist:
if d.split(":")[0].lstrip("*") not in pkglist:
newpkgs.add(d)
contents[path] = entry
def walk_and_compare(dir_path):
"""Walk the target zone root and match the files against the manifest"""
try:
with os.scandir(dir_path) as it:
for entry in it:
#
# We walk the tree from 'outside' of the zone, but the
# contents list 'internal' paths, so we need to cut off
# the zone_root at the beginning of the path. The '/' needs
# to be left in place.
#
path = entry.path[len(zone_root):]
#
# We skip the excluded dirs first - no point processing them
# any further
#
if entry.is_dir(follow_symlinks=False):
if path in excludeDirs:
if not quiet:
print("Skipping directory |" + path + "|")
continue
si = entry.stat(follow_symlinks=False)
f = FileDesc(si, entry)
#
# If the entry is not matched against the contents database
# we just record it as 'new'. For directories we do a simple
# traversal, just adding the contents to new files as well.
#
if path not in contents:
new_files[path] = f
if entry.is_dir(follow_symlinks=False):
walk_and_compare(entry.path)
continue
continue
#
# Symlinks are a special case - they don't have their own
# attributes, only the target. We can handle them ahead of
# anything else
#
if entry.is_symlink():
if contents[path].ftype != "s":
f.comment += " S " + " file replaced by link"
mod_files[path] = f
continue
if os.readlink(entry.path) == contents[path].target:
matched_files[path] = f
continue
f.comment += (
" S |"
+ os.readlink(entry.path)
+ "| vs |"
+ contents[path].target
+ "|\n"
)
mod_files[path] = f
continue
#
# We need to differentiate between regular files which got
# modified, which is unexpected, and the volatile files, which
# are expected to change.
#
if contents[path].ftype in volTypes:
modified_files = mod_vol_files
f.preserve = "true"
else:
modified_files = mod_files
#
# We need to treat 'link' file entries in a special way
# since they represent hardlinks, which from the FS point of
# view are regular files, but 'contents' lists just target
# for them.
# On first passage we'll preserve the (fs, inode) tuple and
# the list where the target entry belongs, and use it for
# subsequent hardlinks.
#
if contents[path].ftype == "l":
first_pass = False
ldir = dir_path[len(zone_root):]
rpath = os.path.normpath(
os.path.join(ldir, contents[path].target)
)
#
# If the link target is not in contents, or it's not a file
# it's a fatal error because the database is corrupted.
#
if rpath not in contents:
sys.stdout.flush()
print(
rpath + " not found in contents.", file=sys.stderr
)
sys.exit(1)
if contents[rpath].ftype not in fileTypes:
sys.stdout.flush()
print(
path
+ " target path "
+ rpath
+ " is not a file, type: "
+ contents[rpath].ftype,
file=sys.stderr,
)
sys.exit(1)
if f.nlink == 1:
f.comment += (
" plain file replaced a hardlink to "
+ contents[path].target
)
modified_files[path] = f
continue
if contents[rpath].inode is None:
tsi = os.stat(zone_root + rpath)
contents[rpath].inode = (tsi.st_dev, tsi.st_ino)
if contents[rpath].inode not in hardlinks:
hardlinks[contents[rpath].inode] = rpath
elif hardlinks[contents[rpath].inode] != rpath:
sys.stdout.flush()
print(
"hardlinks table contains different entry for"
+ rpath
+ " : "
+ hardlinks[contents[rpath].inode],
file=sys.stderr,
)
sys.exit(1)
#
# We'll adjust this later if the file does match
#
first_pass = True
contents[rpath].list = modified_files
if f.inode == contents[rpath].inode:
f.type = "hardlink"
f.target = contents[path].target
if not first_pass:
contents[rpath].list[path] = f
continue
else:
f.type = "hardlink"
f.comment += " hardlink pointing to different target"
modified_files[path] = f
continue
else:
rpath = path
#
# Directories are handled in 2 parts - first we handle
# the recursion, then pass through the attributes matching
# and handle the directory entry itself
#
if entry.is_dir(follow_symlinks=False):
walk_and_compare(entry.path)
#
# It might happen that a directory has replaced a regular
# file registered in contents - hopefully it should not
# happen often.
#
if contents[rpath].ftype not in dirTypes:
modified_files[path] = f
continue
#
# We'll test parameters common to all entries first
#
# volatile and editable files probably need to be treated
# more leniently - we expect them to not match.
#
if f.owner is not None:
if f.owner != contents[rpath].owner:
f.comment += (
" owner differs "
+ contents[rpath].owner
+ " vs "
+ f.owner
)
modified_files[path] = f
continue
else:
#
# The comment already states the uid is not matched, so
# by definition the file cannot match a known one
#
modified_files[path] = f
continue
if f.group is not None:
if f.group != contents[rpath].group:
f.comment += (
" group differs "
+ contents[rpath].group
+ " vs "
+ f.group
)
modified_files[path] = f
continue
else:
#
# The comment already states the gid is not matched, so
# by definition the file cannot match a known one
#
modified_files[path] = f
continue
if f.mode != contents[rpath].mode:
f.comment += (
f" mode differs {contents[rpath].mode:04o} vs"
f" {f.mode:04o}"
)
modified_files[path] = f
continue
if entry.is_dir(follow_symlinks=False):
matched_files[path] = f
continue
if stat.S_ISCHR(si.st_mode):
if contents[rpath].ftype != "c":
f.comment += (
" file type mismatch char device vs "
+ contents[rpath].ftype
)
modified_files[path] = f
continue
if os.major(si.rdev) != contents[rpath].major:
f.comment += (
" device major mismatch "
f" {contents[rpath].major:d}"
f" vs {os.major(si.rdev):d}"
)
modified_files[path] = f
continue
if os.minor(si.rdev) != contents[rpath].minor:
f.comment += (
" device minor mismatch "
f" {contents[rpath].minor:d}"
f" vs {os.minor(si.rdev):d}"
)
modified_files[path] = f
continue
matched_files[path] = f
continue
if stat.S_ISBLK(si.st_mode):
if contents[rpath].ftype != "b":
f.comment += (
" file type mismatch block device vs "
+ contents[rpath].ftype
)
modified_files[path] = f
continue
if os.major(si.rdev) != contents[rpath].major:
f.comment += (
" device major mismatch "
f" {contents[rpath].major:d}"
f" vs {os.major(si.rdev):d}"
)
modified_files[path] = f
continue
if os.minor(si.rdev) != contents[rpath].minor:
f.comment += (
" device minor mismatch "
f" {contents[rpath].minor:d}"
f" vs {os.minor(si.rdev):d}"
)
modified_files[path] = f
continue
matched_files[path] = f
continue
if stat.S_ISREG(si.st_mode):
if si.st_size != contents[rpath].size:
f.comment += (
f" size mismatch {contents[rpath].size:d} vs"
f" {si.st_size:d}"
)
modified_files[path] = f
continue
if f.modtime != contents[rpath].modtime:
f.comment += (
" timestamp mismatch"
f" {contents[rpath].modtime}"
f" vs {f.modtime}"
)
modified_files[path] = f
continue
if enable_checksums or contents[path].ftype in volTypes:
cksum = get_cksum(entry.path)
if cksum != contents[rpath].cksum:
f.comment += (
f" checksum differs {contents[rpath].cksum} vs"
f" {cksum}"
)
modified_files[path] = f
continue
contents[rpath].list = matched_files
matched_files[path] = f
continue
#
# All files should have been handled above
#
sys.stdout.flush()
print(
"Reached the end of checks: |" + path + "|\n",
file=sys.stderr,
)
sys.exit(1)
except OSError as error:
sys.stdout.flush()
print(error, file=sys.stderr)
def handle_hardlinks():
"""Walk files lists to match the hardlinks which
so far weren't matched with targets. Since the hardlink is not
possible to distinguish from 'target file', we simply assume that
the first encountered entry for given inode will be 'file', and all
the remaining ones will be 'hardlinks'"""
for files in (matched_files, mod_files, mod_vol_files, new_files):
for path in list(files):
e = files[path]
if (e.type == "hardlink") and (e.target is None):
if e.inode in hardlinks:
e.target = os.path.relpath(
hardlinks[e.inode], os.path.split(path)[0]
)
else:
e.type = "file"
hardlinks[e.inode] = path
def print_out_files(filename, filelist, known_list=None):
"""Print out the file list in the requested format"""
if preserve_age > 0:
cutoff = now - (preserve_age * 86400)
else:
cutoff = 0
try:
with open(filename, "a", encoding="utf-8") as f:
for path in sorted(list(filelist)):
if known_list is not None:
if path in known_list:
continue
if plain_output:
f.write(f"{path}\n")
continue
e = filelist[path]
if e.comment:
f.write(f"# {e.comment}\n")
if e.type == "unhandled":
f.write("# ")
f.write(e.type)
f.write(f' path="{path[1:]}"')
if e.type == "link":
f.write(f' target="{e.target}"')
elif e.type == "hardlink":
f.write(f' target="{e.target}"')
else:
f.write(f" mode={e.mode:04o}")
if e.owner is not None:
f.write(f" owner={e.owner}")
if e.group is not None:
f.write(f" group={e.group}")
if e.preserve == "true":
f.write(" preserve=true")
elif cutoff > 0:
if e.modtime > cutoff:
f.write(" preserve=true")
f.write("\n")
except OSError as error:
sys.stdout.flush()
print(error, file=sys.stderr)
def emit_results():
"""Handle the processing of results"""
if plain_output:
ext = "out"
filename = f"{output_dir}/{new_files_fname}.{ext}"
else:
ext = "p5m"
filename = f"{output_dir}/{pkg_fname}.{ext}"
manifest_filename = filename
config = configparser.ConfigParser()
config[param_section] = {
"plain_output": plain_output,
"zone_root": zone_root,
"pkg_fmri": pkg_fmri,
"pkg_file": filename,
}
try:
if not plain_output:
with open(filename, "x", encoding="utf-8") as f:
f.write(f"set name=pkg.fmri value={pkg_fmri}\n")
f.write(f'set name=pkg.summary value="{pkg_summary}"\n')
if pkg_desc is not None:
f.write(f'set name=pkg.description value="{pkg_desc}"\n')
except OSError as error:
sys.stdout.flush()
print(error, file=sys.stderr)
if not quiet:
print(f"Writing {filename}")
print_out_files(filename, new_files, knownNewFiles)
filename = f"{output_dir}/{mod_files_fname}.{ext}"
if not quiet:
print(f"Writing {filename}")
print_out_files(filename, mod_files, knownModFiles)
filename = f"{output_dir}/{mod_vol_files_fname}.{ext}"
if not quiet:
print(f"Writing {filename}")
print_out_files(filename, mod_vol_files)
filename = f"{output_dir}/{matched_files_fname}.{ext}"
if not quiet:
print(f"Writing {filename}")
print_out_files(filename, matched_files)
try:
filename = f"{output_dir}/{param_fname}.ini"
with open(filename, "x", encoding="utf-8") as f:
config.write(f)
except OSError as error:
sys.stdout.flush()
print(error, file=sys.stderr)
if plain_output:
print(f"File lists generated in: {output_dir}")
else:
print(
"IPS package manifest generated:\n"
+ f"{manifest_filename}\n\n"
+ "Please review and adjust it as needed before running "
+ "the next step.\n\n"
+ "Please provide the following directory as results-dir for the "
+ "next steps:\n\n"
+ output_dir
)
print("\nThe next step should be 'sysdiff depresolve'")
def parse_ignore(ignore):
"""Parse the ignore file"""
for p in ignore.split(","):
p = p.strip().rstrip("/")
if p[0] != "/":
sys.stdout.flush()
print(
"excluded dir\n" + p + "\nis not an absolute path",
file=sys.stderr,
)
sys.exit(1)
excludeDirs.add(p)
def load_excludeDirs(path):
"""Load the excludeDirs file"""
if path is None:
path = excludeDirsPath
if not quiet:
print(f"Loading excluded dirs list from file:\n{path}")
try:
for p in fileinput.input(path):
p = p.strip().rstrip("/")
if p[0] != "/":
sys.stdout.flush()
print(
f"In file\n{path}\n"
+ f"excluded dir\n{p}\nis not an absolute path",
file=sys.stderr,
)
sys.exit(1)
excludeDirs.add(p)
except OSError as error:
sys.stdout.flush()
print(
"Unable to load excluded dirs from file",
path,
"error:\n",
error,
file=sys.stderr,
)
def load_known_files():
"""Load the known_files lists"""
path = os.path.join(sys.path[0], "known_mod_files." + os.uname().machine)
try:
for line in fileinput.input(path):
knownModFiles.add(line.rstrip("\n"))
except OSError as error:
sys.stdout.flush()
print(
"Unable to load known mod file list from file",
path,
"error:\n",
error,
file=sys.stderr,
)
path = os.path.join(sys.path[0], "known_new_files." + os.uname().machine)
try:
for line in fileinput.input(path):
knownNewFiles.add(line.rstrip("\n"))
except OSError as error:
sys.stdout.flush()
print(
"Unable to load known new file list from file\n",
path,
"\nerror:\n",
error,
file=sys.stderr,
)
def load_pkglist():
"""Load the baseline package list for current architecture"""
path = os.path.join(sys.path[0], "pkglist." + os.uname().machine)
try:
for line in fileinput.input(path):
pkglist.add(line.rstrip("\n"))
except OSError as error:
sys.stdout.flush()
print(
"Unable to load pkg list from file\n",
path,
"\nerror:\n",
error,
file=sys.stderr,
)
def do_sysdiff(args):
"""Handler for the diff subcommand, executed via args.func(args) in main"""
global zone_name, zone_root, enable_checksums, plain_output, preserve_age
global output_dir, pkg_fmri, pkg_summary, pkg_desc, pkg_fname
zone_name = args.zonename
enable_checksums = args.chksum
plain_output = args.plain_output
if args.preserve_age is not None:
preserve_age = args.preserve_age
load_excludeDirs(args.exclude_dirs)
if args.ignore:
parse_ignore(args.ignore)
if args.output_dir is not None:
output_dir = args.output_dir
if output_dir[0] != "/":
sys.stdout.flush()
print("results dir parent must be an absolute path", file=sys.stderr)
sys.exit(1)
if not os.path.isdir(output_dir):
sys.stdout.flush()
print("results dir parent must be a directory", file=sys.stderr)
sys.exit(1)
output_dir = f"{output_dir}/{zone_name}-{tstamp}"
sp = subprocess.run(
("/usr/sbin/zoneadm", "-z", zone_name, "list", "-p"),
capture_output=True,
text=True,
check=False,
)
if sp.returncode != 0:
sys.stdout.flush()
sys.stderr.write("zoneadm failed\n")
sys.stderr.write(sp.stderr)
sys.exit(1)
zi = sp.stdout.split(":")
if zi[5] != "solaris10":
sys.stdout.flush()
sys.stderr.write("zone brand must be solaris10\n")
sys.exit(1)
if zi[2] != "installed":
sys.stdout.flush()
sys.stderr.write('zone must be in the "installed" state.\n')
sys.exit(1)
zone_root = zi[3] + "/root"
if args.pkg_name is not None:
pkg_fmri = args.pkg_name
if "@" in pkg_fmri:
sys.stdout.flush()
print("Please don't use '@' in pkg_name", file=sys.stderr)
sys.exit(1)
else:
pkg_fmri = zone_name
#
# We don't want the @... part in the filename - it messes up pkgdepend
#
pkg_fname = pkg_fmri
if args.pkg_version is not None:
pkg_fmri = pkg_fmri + "@" + args.pkg_version
else:
pkg_fmri = pkg_fmri + "@1.0"
if args.pkg_summary is not None:
pkg_summary = args.pkg_summary
else:
pkg_summary = "package generated from " + zone_name
if args.pkg_desc is not None:
pkg_desc = args.pkg_desc
try:
os.mkdir(output_dir)
except OSError as error:
sys.stdout.flush()
print("Unable to create target dir: " + output_dir, file=sys.stderr)
print(error, file=sys.stderr)
sys.exit(1)
parse_passwd()
if not quiet:
print(f"passwd entries: {len(passwd)}")
parse_group()
if not quiet:
print(f"group entries: {len(group)}")
if not args.full_scan:
load_known_files()
if not quiet:
print(f"known new files loaded: {len(knownNewFiles)}")
print(f"known mod files loaded: {len(knownModFiles)}")
else:
if not quiet:
print("skipping known new/modified files lists")
load_pkglist()
if not quiet:
print(f"pkgs loaded: {len(pkglist)}")
parse_contents(zone_root + "/var/sadm/install/contents")
if not quiet:
print(f"contents entries: {len(contents)}")
if len(newpkgs) != 0:
print(f"{len(newpkgs)} non-Solaris pkgs found:")
for p in sorted(newpkgs):
print(p)
else:
if not quiet:
print("no non-Solaris pkgs found")
walk_and_compare(zone_root)
if not quiet:
print(f"new_files: {len(new_files)}")
print(f"matched_files: {len(matched_files)}")
print(f"mod_files: {len(mod_files)}")
print(f"mod_vol_files: {len(mod_vol_files)}")
handle_hardlinks()
emit_results()
def read_params():
"""Read and parse the params file to initialize the internal state"""
global zone_root, plain_output, pkg_file, params_read, pkg_fmri
config = configparser.ConfigParser()
try:
filename = f"{output_dir}/{param_fname}.ini"
with open(filename, "r", encoding="utf-8") as f:
config.read_file(f)
except OSError as error: