-
Notifications
You must be signed in to change notification settings - Fork 2
/
piuparts.py
2988 lines (2500 loc) · 114 KB
/
piuparts.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/python
#
# Copyright 2005 Lars Wirzenius ([email protected])
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
"""Debian package installation and uninstallation tester.
This program sets up a minimal Debian system in a chroot, and installs
and uninstalls packages and their dependencies therein, looking for
problems.
See the manual page (piuparts.1, generated from piuparts.1.txt) for
more usage information.
Lars Wirzenius <[email protected]>
"""
VERSION = "__PIUPARTS_VERSION__"
import time
import logging
import optparse
import sys
import commands
import tempfile
import shutil
import os
import tarfile
import stat
import re
import pickle
import subprocess
import unittest
import urllib
import uuid
from signal import alarm, signal, SIGALRM, SIGTERM, SIGKILL
try:
from debian import deb822
except ImportError:
from debian_bundle import deb822
import piupartslib.conf
DISTRO_CONFIG_FILE = "/etc/piuparts/distros.conf"
class Defaults:
"""Default settings which depend on flavor of Debian.
Some settings, such as the default mirror and distribution, depend on
which flavor of Debian we run under: Debian itself, or a derived
distribution such as Ubuntu. This class abstracts away the defaults
so that the rest of the code can just refer to the values defined
herein.
"""
def get_components(self):
"""Return list of default components for a mirror."""
def get_mirror(self):
"""Return default mirror."""
def get_distribution(self):
"""Return default distribution."""
class DebianDefaults(Defaults):
def get_components(self):
return ["main", "contrib", "non-free"]
def get_mirror(self):
return [("http://cdn.debian.net/debian", self.get_components())]
def get_distribution(self):
return ["sid"]
class UbuntuDefaults(Defaults):
def get_components(self):
return ["main", "universe", "restricted", "multiverse"]
def get_mirror(self):
return [("http://archive.ubuntu.com/ubuntu", self.get_components())]
def get_distribution(self):
return ["natty"]
class DefaultsFactory:
"""Instantiate the right defaults class."""
def guess_flavor(self):
p = subprocess.Popen(["lsb_release", "-i", "-s"],
stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
return stdout.strip().lower()
def new_defaults(self):
if not settings.defaults:
settings.defaults = self.guess_flavor()
print "Guessed:", settings.defaults
if settings.defaults.lower() == "debian":
return DebianDefaults()
if settings.defaults.lower() == "ubuntu":
return UbuntuDefaults()
logging.error("Unknown set of defaults: %s" % settings.defaults)
panic()
class Settings:
"""Global settings for this program."""
def __init__(self):
self.defaults = None
self.tmpdir = None
self.keep_tmpdir = False
self.max_command_output_size = 3 * 1024 * 1024 # 3 MB (daptup on dist-upgrade)
self.max_command_runtime = 30 * 60 # 30 minutes (texlive-full on dist-upgrade)
self.single_changes_list = False
self.args_are_package_files = True
# distro setup
self.proxy = None
self.debian_mirrors = []
self.extra_repos = []
self.testdebs_repo = None
self.debian_distros = []
self.keep_sources_list = False
self.keyring = None
self.do_not_verify_signatures = False
self.install_recommends = False
self.eatmydata = True
self.dpkg_force_unsafe_io = True
self.dpkg_force_confdef = False
self.scriptsdirs = []
self.bindmounts = []
# chroot setup
self.basetgz = None
self.savetgz = None
self.lvm_volume = None
self.lvm_snapshot_size = "1G"
self.adt_virt = None
self.existing_chroot = None
self.schroot = None
self.end_meta = None
self.save_end_meta = None
self.skip_minimize = True
self.minimize = False
self.debfoster_options = None
# tests and checks
self.no_install_purge_test = False
self.no_upgrade_test = False
self.distupgrade_to_testdebs = False
self.install_remove_install = False
self.install_purge_install = False
self.list_installed_files = False
self.extra_old_packages = []
self.skip_cronfiles_test = False
self.skip_logrotatefiles_test = False
self.check_broken_diversions = True
self.check_broken_symlinks = True
self.warn_broken_symlinks = True
self.warn_on_others = False
self.warn_on_leftovers_after_purge = False
self.warn_on_debsums_errors = False
self.pedantic_purge_test = False
self.ignored_files = [
# piuparts state
"/usr/sbin/policy-rc.d",
# system state
"/boot/grub/",
"/etc/X11/",
"/etc/X11/default-display-manager",
"/etc/aliases",
"/etc/aliases.db",
"/etc/crypttab",
"/etc/group",
"/etc/group-",
"/etc/gshadow",
"/etc/gshadow-",
"/etc/inetd.conf",
"/etc/inittab",
"/etc/ld.so.cache",
"/etc/mailname",
"/etc/mtab",
"/etc/network/interfaces",
"/etc/news/",
"/etc/news/organization",
"/etc/news/server",
"/etc/news/servers",
"/etc/news/whoami",
"/etc/nologin",
"/etc/passwd",
"/etc/passwd-",
"/etc/shadow",
"/etc/shadow-",
"/usr/share/info/dir",
"/usr/share/info/dir.old",
"/var/cache/ldconfig/aux-cache",
"/var/crash/",
"/var/games/",
# package management
"/etc/apt/secring.gpg",
"/etc/apt/trustdb.gpg",
"/etc/apt/trusted.gpg",
"/etc/apt/trusted.gpg~",
"/usr/share/keyrings/debian-archive-removed-keys.gpg~",
"/var/cache/apt/archives/lock",
"/var/cache/apt/pkgcache.bin",
"/var/cache/apt/srcpkgcache.bin",
"/var/cache/debconf/",
"/var/cache/debconf/config.dat",
"/var/cache/debconf/config.dat.old",
"/var/cache/debconf/config.dat-old",
"/var/cache/debconf/passwords.dat",
"/var/cache/debconf/passwords.dat.old",
"/var/cache/debconf/templates.dat",
"/var/cache/debconf/templates.dat.old",
"/var/cache/debconf/templates.dat-old",
"/var/lib/apt/extended_states",
"/var/lib/cdebconf/",
"/var/lib/cdebconf/passwords.dat",
"/var/lib/cdebconf/questions.dat",
"/var/lib/cdebconf/questions.dat-old",
"/var/lib/cdebconf/templates.dat",
"/var/lib/cdebconf/templates.dat-old",
"/var/lib/dpkg/arch",
"/var/lib/dpkg/available",
"/var/lib/dpkg/available-old",
"/var/lib/dpkg/diversions",
"/var/lib/dpkg/diversions-old",
"/var/lib/dpkg/lock",
"/var/lib/dpkg/status",
"/var/lib/dpkg/status-old",
"/var/lib/dpkg/statoverride",
"/var/lib/dpkg/statoverride-old",
"/var/log/alternatives.log",
"/var/log/apt/history.log",
"/var/log/apt/term.log",
"/var/log/bootstrap.log",
"/var/log/dbconfig-common/dbc.log",
"/var/log/dpkg.log",
# system logfiles
"/var/log/auth.log",
"/var/log/daemon.log",
"/var/log/debug",
"/var/log/faillog",
"/var/log/kern.log",
"/var/log/lastlog",
"/var/log/lpr.log",
"/var/log/mail.err",
"/var/log/mail.info",
"/var/log/mail.log",
"/var/log/mail.warn",
"/var/log/messages",
"/var/log/news/",
"/var/log/news/news.crit",
"/var/log/news/news.err",
"/var/log/news/news.notice",
"/var/log/secure",
"/var/log/syslog",
"/var/log/user.log",
# home directories of system accounts
"/var/lib/gozerbot/",
"/var/lib/nagios/", # nagios* (#668756)
"/var/lib/onioncat/", # onioncat
"/var/lib/rbldns/",
"/var/spool/powerdns/", # pdns-server (#531134), pdns-recursor (#531135)
# work around broken symlinks
"/usr/lib/python2.6/dist-packages/python-support.pth", #635493 and #385775
"/usr/lib/python2.7/dist-packages/python-support.pth",
# work around #316521 dpkg: incomplete cleanup of empty directories
"/etc/apache2/",
"/etc/apache2/conf.d/",
"/etc/cron.d/",
"/etc/nagios-plugins/config/",
"/etc/php5/",
"/etc/php5/conf.d/",
"/etc/php5/mods-available/",
"/etc/sgml/",
"/etc/ssl/",
"/etc/ssl/private/",
"/etc/xml/",
# HACKS
]
self.ignored_patterns = [
# system state
"/dev/.*",
"/etc/init.d/\.depend.*",
"/run/.*",
"/var/backups/.*",
"/var/cache/man/.*",
"/var/mail/.*",
"/var/run/.*",
# package management
"/etc/apt/trusted.gpg.d/.*.gpg~",
"/var/lib/apt/lists/.*",
"/var/lib/dpkg/alternatives/.*",
"/var/lib/dpkg/triggers/.*",
"/var/lib/insserv/run.*.log",
"/var/lib/ucf/.*",
"/var/lib/update-rc.d/.*",
# application data
"/var/lib/citadel/(data/.*)?",
"/var/lib/mercurial-server/.*",
"/var/lib/onak/.*",
"/var/lib/openvswitch/(pki/.*)?",
"/var/lib/vmm/(./.*)?", #682184
"/var/log/exim/.*",
"/var/log/exim4/.*",
"/var/spool/exim/.*",
"/var/spool/exim4/.*",
"/var/spool/news/.*",
"/var/spool/squid/(../.*)?",
"/var/www/.*",
# HACKS
"/lib/modules/.*/modules.*",
]
self.non_pedantic_ignore_patterns = [
"/tmp/.*"
]
settings = Settings()
on_panic_hooks = {}
counter = 0
def do_on_panic(hook):
global counter
cid = counter
counter += 1
on_panic_hooks[cid] = hook
return cid
def dont_do_on_panic(id):
del on_panic_hooks[id]
class TimeOffsetFormatter(logging.Formatter):
def __init__(self, fmt=None, datefmt=None):
self.startup_time = time.time()
logging.Formatter.__init__(self, fmt, datefmt)
def formatTime(self, record, datefmt):
t = time.time() - self.startup_time
t_min = int(t / 60)
t_sec = t % 60.0
return "%dm%.1fs" % (t_min, t_sec)
DUMP = logging.DEBUG - 1
HANDLERS = []
def setup_logging(log_level, log_file_name):
logging.addLevelName(DUMP, "DUMP")
logger = logging.getLogger()
logger.setLevel(log_level)
formatter = TimeOffsetFormatter("%(asctime)s %(levelname)s: %(message)s")
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)
HANDLERS.append(handler)
if log_file_name:
handler = logging.FileHandler(log_file_name)
handler.setFormatter(formatter)
logger.addHandler(handler)
HANDLERS.append(handler)
def dump(msg):
logger = logging.getLogger()
logger.log(DUMP, msg)
for handler in HANDLERS:
handler.flush()
def panic(exit=1):
for i in range(counter):
if i in on_panic_hooks:
on_panic_hooks[i]()
logging.error("piuparts run ends.")
sys.exit(exit)
def indent_string(str):
"""Indent all lines in a string with two spaces and return result."""
return "\n".join([" " + line for line in str.split("\n")])
class Alarm(Exception):
pass
def alarm_handler(signum, frame):
raise Alarm
def run(command, ignore_errors=False, timeout=0):
"""Run an external command and die with error message if it fails."""
def kill_subprocess(p, reason):
logging.error("Terminating command due to %s" % reason)
p.terminate()
for i in range(10):
time.sleep(0.5)
if p.poll() is not None:
break
else:
logging.error("Killing command due to %s" % reason)
p.kill()
p.wait()
assert type(command) == type([])
command = [x for x in command if x] # Delete any empty argument
logging.debug("Starting command: %s" % command)
env = os.environ.copy()
env["LC_ALL"] = "C"
env["LANGUAGES"] = ""
env["PIUPARTS_OBJECTS"] = ' '.join(str(vobject) for vobject in settings.testobjects )
devnull = open('/dev/null', 'r')
p = subprocess.Popen(command, env=env, stdin=devnull,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = ""
excessive_output = False
if timeout > 0:
signal(SIGALRM, alarm_handler)
alarm(timeout)
try:
while p.poll() is None:
"""Read 64 KB chunks, but depending on the output buffering behavior
of the command we may get less even if more output is coming later.
Abort after reading max_command_output_size bytes."""
output += p.stdout.read(1 << 16)
if (len(output) > settings.max_command_output_size):
excessive_output = True
ignore_errors = False
alarm(0)
kill_subprocess(p, "excessive output")
output += "\n\n***** Command was terminated after exceeding output limit (%.2f MB) *****\n" \
% (settings.max_command_output_size / 1024. / 1024.)
break
if not excessive_output:
output += p.stdout.read(settings.max_command_output_size)
alarm(0)
except Alarm:
ignore_errors = False
kill_subprocess(p, "excessive runtime")
output += "\n\n***** Command was terminated after exceeding runtime limit (%s s) *****\n" % timeout
devnull.close()
if output:
dump("\n" + indent_string(output.rstrip("\n")))
if p.returncode == 0:
logging.debug("Command ok: %s" % repr(command))
elif ignore_errors:
logging.debug("Command failed (status=%d), but ignoring error: %s" %
(p.returncode, repr(command)))
else:
logging.error("Command failed (status=%d): %s\n%s" %
(p.returncode, repr(command), indent_string(output)))
panic()
return p.returncode, output
def create_temp_file():
"""Create a temporary file and return its full path."""
(fd, path) = tempfile.mkstemp(dir=settings.tmpdir)
logging.debug("Created temporary file %s" % path)
return (fd, path)
def create_file(name, contents):
"""Create a new file with the desired name and contents."""
try:
f = file(name, "w")
f.write(contents)
f.close()
except IOError, detail:
logging.error("Couldn't create file %s: %s" % (name, detail))
panic()
def remove_files(filenames):
"""Remove some files."""
for filename in filenames:
logging.debug("Removing %s" % filename)
try:
os.remove(filename)
except OSError, detail:
logging.error("Couldn't remove %s: %s" % (filename, detail))
panic()
def make_metapackage(name, depends, conflicts):
"""Return the path to a .deb created just for satisfying dependencies
Caller is responsible for removing the temporary directory containing the
.deb when finished.
"""
# Inspired by pbuilder's pbuilder-satisfydepends-aptitude
tmpdir = tempfile.mkdtemp(dir=settings.tmpdir)
panic_handler_id = do_on_panic(lambda: shutil.rmtree(tmpdir))
create_file(os.path.join(tmpdir, ".piuparts.tmpdir"), "metapackage creation")
old_umask = os.umask(0)
os.makedirs(os.path.join(tmpdir, name, 'DEBIAN'), mode = 0755)
os.umask(old_umask)
control = deb822.Deb822()
control['Package'] = name
control['Version'] = '0.invalid.0'
control['Architecture'] = 'all'
control['Maintainer'] = ('piuparts developers team '
'<[email protected]>')
control['Description'] = ('Dummy package to satisfy dependencies - '
'created by piuparts\n'
' This package was created automatically by '
'piuparts and can safely be removed')
if depends:
control['Depends'] = depends
if conflicts:
control['Conflicts'] = conflicts
create_file(os.path.join(tmpdir, name, 'DEBIAN', 'control'),
control.dump())
run(['dpkg-deb', '-b', '--nocheck', os.path.join(tmpdir, name)])
dont_do_on_panic(panic_handler_id)
return os.path.join(tmpdir, name) + '.deb'
def split_path(pathname):
parts = []
while pathname:
(head, tail) = os.path.split(pathname)
#print "split '%s' => '%s' + '%s'" % (pathname, head, tail)
if tail:
parts.append(tail)
elif not head:
break
elif head == pathname:
parts.append(head)
break
pathname = head
return parts
def canonicalize_path(root, pathname):
"""Canonicalize a path name, simulating chroot at 'root'.
When resolving the symlink, pretend (similar to chroot) that
'root' is the root of the filesystem. Also resolve '..' and
'.' components. This should not escape the chroot below
'root', but for security concerns, use chroot and have the
kernel resolve symlinks instead.
"""
#print "\nCANONICALIZE %s %s" % (root, pathname)
seen = []
parts = split_path(pathname)
#print "PARTS ", list(reversed(parts))
path = "/"
while parts:
tag = "\n".join(parts + [path])
#print "TEST '%s' + " % path, list(reversed(parts))
if tag in seen or len(seen) > 1024:
fullpath = os.path.join(path, *reversed(parts))
#print "LOOP %s" % fullpath
path = fullpath
logging.error("ELOOP: Too many symbolic links in '%s'" % path)
break
seen.append(tag)
part = parts.pop()
# Using normpath() to cleanup '.', '..' and multiple slashes.
# Removing a suffix 'foo/..' is safe here since it can't change the
# meaning of 'path' because it contains no symlinks - they have been
# resolved already.
newpath = os.path.normpath(os.path.join(path, part))
rootedpath = os.path.join(root, newpath[1:])
if newpath == "/":
path = "/"
elif os.path.islink(rootedpath):
target = os.readlink(rootedpath)
#print "LINK to '%s'" % target
if os.path.isabs(target):
path = "/"
parts.extend(split_path(target))
else:
path = newpath
#print "FINAL '%s'" % path
return path
def is_broken_symlink(root, dirpath, filename):
"""Is symlink dirpath+filename broken?"""
if dirpath[:len(root)] == root:
dirpath = dirpath[len(root):]
pathname = canonicalize_path(root, os.path.join(dirpath, filename))
pathname = os.path.join(root, pathname[1:])
# The symlink chain, if any, has now been resolved. Does the target
# exist?
#print "EXISTS ", pathname, os.path.exists(pathname)
return not os.path.exists(pathname)
class IsBrokenSymlinkTests(unittest.TestCase):
testdir = "is-broken-symlink-testdir"
def symlink(self, target, name):
pathname = os.path.join(self.testdir, name)
os.symlink(target, pathname)
self.symlinks.append(pathname)
def setUp(self):
self.symlinks = []
os.mkdir(self.testdir)
self.symlink("notexist", "relative-broken")
self.symlink("relative-broken", "relative-broken-to-symlink")
self.symlink(".", "relative-works")
self.symlink("relative-works", "relative-works-to-symlink")
self.symlink("/etc", "absolute-broken")
self.symlink("absolute-broken", "absolute-broken-to-symlink")
self.symlink("/", "absolute-works")
self.symlink("/absolute-works", "absolute-works-to-symlink")
os.mkdir(os.path.join(self.testdir, "dir"))
self.symlink("dir", "dir-link")
os.mkdir(os.path.join(self.testdir, "dir/subdir"))
self.symlink("subdir", "dir/subdir-link")
self.symlink("notexist/", "trailing-slash-broken")
self.symlink("dir/", "trailing-slash-works")
self.symlink("selfloop", "selfloop")
self.symlink("/absolute-selfloop", "absolute-selfloop")
self.symlink("../dir/selfloop", "dir/selfloop")
self.symlink("../dir-link/selfloop", "dir/selfloop1")
self.symlink("../../dir/subdir/selfloop", "dir/subdir/selfloop")
self.symlink("../../dir-link/subdir/selfloop", "dir/subdir/selfloop1")
self.symlink("../../link/subdir-link/selfloop", "dir/subdir/selfloop2")
self.symlink("../../dir-link/subdir-link/selfloop", "dir/subdir/selfloop3")
self.symlink("explode/bomb", "explode")
def tearDown(self):
shutil.rmtree(self.testdir)
def testRelativeBroken(self):
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"relative-broken"))
def testRelativeBrokenToSymlink(self):
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"relative-broken-to-symlink"))
def testAbsoluteBroken(self):
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"absolute-broken"))
def testAbsoluteBrokenToSymlink(self):
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"absolute-broken-to-symlink"))
def testTrailingSlashBroken(self):
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"trailing-slash-broken"))
def testSelfLoopBroken(self):
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"selfloop"))
def testExpandingSelfLoopBroken(self):
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"explode"))
def testAbsoluteSelfLoopBroken(self):
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"absolute-selfloop"))
def testSubdirSelfLoopBroken(self):
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"dir/selfloop"))
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"dir/selfloop1"))
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"dir/subdir/selfloop"))
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"dir/subdir/selfloop1"))
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"dir/subdir/selfloop2"))
self.failUnless(is_broken_symlink(self.testdir, self.testdir,
"dir/subdir/selfloop3"))
def testRelativeWorks(self):
self.failIf(is_broken_symlink(self.testdir, self.testdir,
"relative-works"))
def testRelativeWorksToSymlink(self):
self.failIf(is_broken_symlink(self.testdir, self.testdir,
"relative-works-to-symlink"))
def testAbsoluteWorks(self):
self.failIf(is_broken_symlink(self.testdir, self.testdir,
"absolute-works"))
def testAbsoluteWorksToSymlink(self):
self.failIf(is_broken_symlink(self.testdir, self.testdir,
"absolute-works-to-symlink"))
def testTrailingSlashWorks(self):
self.failIf(is_broken_symlink(self.testdir, self.testdir,
"trailing-slash-works"))
def testMultiLevelNestedSymlinks(self):
# target/first-link -> ../target/second-link -> ../target
os.mkdir(os.path.join(self.testdir, "target"))
self.symlink("../target", "target/second-link")
self.symlink("../target/second-link", "target/first-link")
self.failIf(is_broken_symlink(self.testdir, self.testdir,
"target/first-link"))
def testMultiLevelNestedAbsoluteSymlinks(self):
# first-link -> /second-link/final-target
# second-link -> /target-dir
os.mkdir(os.path.join(self.testdir, "final-dir"))
os.mkdir(os.path.join(self.testdir, "final-dir/final-target"))
self.symlink("/second-link/final-target", "first-link")
self.symlink("/final-dir", "second-link")
self.failIf(is_broken_symlink(self.testdir, self.testdir,
"first-link"))
class Chroot:
"""A chroot for testing things in."""
def __init__(self):
self.name = None
self.bootstrapped = False
def create_temp_dir(self):
"""Create a temporary directory for the chroot."""
self.name = tempfile.mkdtemp(dir=settings.tmpdir)
create_file(os.path.join(self.name, ".piuparts.tmpdir"), "chroot")
os.chmod(self.name, 0755)
logging.debug("Created temporary directory %s" % self.name)
def create(self, temp_tgz = None):
"""Create a chroot according to user's wishes."""
self.panic_handler_id = do_on_panic(self.remove)
if not settings.schroot:
self.create_temp_dir()
if temp_tgz:
self.unpack_from_tgz(temp_tgz)
elif settings.basetgz:
self.unpack_from_tgz(settings.basetgz)
elif settings.lvm_volume:
self.setup_from_lvm(settings.lvm_volume)
elif settings.existing_chroot:
self.setup_from_dir(settings.existing_chroot)
elif settings.schroot:
self.setup_from_schroot(settings.schroot)
else:
self.setup_minimal_chroot()
if not settings.schroot:
self.mount_proc()
self.mount_selinux()
self.configure_chroot()
if settings.basetgz or settings.schroot:
self.run(["apt-get", "-yf", "dist-upgrade"])
self.minimize()
# Copy scripts dirs into the chroot, merging all dirs together,
# later files overwriting earlier ones.
if settings.scriptsdirs:
dest = self.relative("tmp/scripts/")
if not os.path.exists(self.relative("tmp/scripts/")):
os.mkdir(dest)
for sdir in settings.scriptsdirs:
logging.debug("Copying scriptsdir %s to %s" % (sdir, dest))
for sfile in os.listdir(sdir):
if (sfile.startswith("post_") or sfile.startswith("pre_")) \
and not ".dpkg-" in sfile \
and os.path.isfile(os.path.join(sdir, sfile)):
shutil.copy(os.path.join(sdir, sfile), dest)
# Run custom scripts after creating the chroot.
self.run_scripts("post_setup")
if settings.savetgz and not temp_tgz:
self.pack_into_tgz(settings.savetgz)
def remove(self):
"""Remove a chroot and all its contents."""
if not settings.keep_tmpdir and os.path.exists(self.name):
self.terminate_running_processes()
if not settings.schroot:
self.unmount_selinux()
self.unmount_proc()
if settings.lvm_volume:
logging.debug('Unmounting and removing LVM snapshot %s' % self.lvm_snapshot_name)
run(['umount', self.name])
run(['lvremove', '-f', self.lvm_snapshot])
if settings.schroot:
logging.debug("Terminate schroot session '%s'" % self.name)
run(['schroot', '--end-session', '--chroot', "session:" + self.schroot_session])
if not settings.schroot:
run(['rm', '-rf', '--one-file-system', self.name])
if os.path.exists(self.name):
create_file(os.path.join(self.name, ".piuparts.tmpdir"), "removal failed")
logging.debug("Removed directory tree at %s" % self.name)
elif settings.keep_tmpdir:
if settings.schroot:
logging.debug("Keeping schroot session %s at %s" % (self.schroot_session, self.name))
else:
logging.debug("Keeping directory tree at %s" % self.name)
dont_do_on_panic(self.panic_handler_id)
def was_bootstrapped(self):
return self.bootstrapped
def create_temp_tgz_file(self):
"""Return the path to a file to be used as a temporary tgz file"""
# Yes, create_temp_file() would work just as well, but putting it in
# the interface for Chroot allows the VirtServ hack to work.
(fd, temp_tgz) = create_temp_file()
return temp_tgz
def remove_temp_tgz_file(self, temp_tgz):
"""Remove the file that was used as a temporary tgz file"""
# Yes, remove_files() would work just as well, but putting it in
# the interface for Chroot allows the VirtServ hack to work.
remove_files([temp_tgz])
def pack_into_tgz(self, result):
"""Tar and compress all files in the chroot."""
self.run(["apt-get", "clean"])
logging.debug("Saving %s to %s." % (self.name, result))
run(['tar', '-czf', result, '--one-file-system', '--exclude', 'tmp/scripts', '-C', self.name, './'])
def unpack_from_tgz(self, tarball):
"""Unpack a tarball to a chroot."""
logging.debug("Unpacking %s into %s" % (tarball, self.name))
prefix = []
if settings.eatmydata and os.path.isfile('/usr/bin/eatmydata'):
prefix.append('eatmydata')
run(prefix + ["tar", "-C", self.name, "-zxf", tarball])
def setup_from_schroot(self, schroot):
self.schroot_session = schroot.split(":")[1] + "-" + str(uuid.uuid1()) + "-piuparts"
run(['schroot', '--begin-session', '--chroot', schroot , '--session-name', self.schroot_session])
ret_code, output = run(['schroot', '--chroot', "session:" + self.schroot_session, '--location'])
self.name = output.strip()
logging.info("New schroot session in '%s'" % self.name);
def setup_from_lvm(self, lvm_volume):
"""Create a chroot by creating an LVM snapshot."""
self.lvm_base = os.path.dirname(lvm_volume)
self.lvm_vol_name = os.path.basename(lvm_volume)
self.lvm_snapshot_name = self.lvm_vol_name + "-" + str(uuid.uuid1());
self.lvm_snapshot = os.path.join(self.lvm_base, self.lvm_snapshot_name)
logging.debug("Creating LVM snapshot %s from %s" % (self.lvm_snapshot, lvm_volume))
run(['lvcreate', '-n', self.lvm_snapshot, '-s', lvm_volume, '-L', settings.lvm_snapshot_size])
logging.info("Mounting LVM snapshot to %s" % self.name);
run(['mount', self.lvm_snapshot, self.name])
def setup_from_dir(self, dirname):
"""Create chroot from an existing one."""
logging.debug("Copying %s into %s" % (dirname, self.name))
for name in os.listdir(dirname):
src = os.path.join(dirname, name)
dst = os.path.join(self.name, name)
run(["cp", "-ax", src, dst])
def run(self, command, ignore_errors=False):
prefix = []
if settings.eatmydata and os.path.isfile(os.path.join(self.name,
'usr/bin/eatmydata')):
prefix.append('eatmydata')
if settings.schroot:
return run(["schroot", "--preserve-environment", "--run-session", "--chroot", "session:" + self.schroot_session, "--directory", "/", "-u", "root", "--"] + prefix + command,
ignore_errors=ignore_errors, timeout=settings.max_command_runtime)
else:
return run(["chroot", self.name] + prefix + command,
ignore_errors=ignore_errors, timeout=settings.max_command_runtime)
def create_apt_sources(self, distro):
"""Create an /etc/apt/sources.list with a given distro."""
lines = []
lines.extend(settings.distro_config.get_deb_lines(
distro, settings.debian_mirrors[0][1]))
for mirror, components in settings.debian_mirrors[1:]:
lines.append("deb %s %s %s" %
(mirror, distro, " ".join(components)))
for repo in settings.extra_repos:
lines.append(repo)
create_file(self.relative("etc/apt/sources.list"),
"\n".join(lines) + "\n")
logging.debug("sources.list:\n" + indent_string("\n".join(lines)))
def enable_testdebs_repo(self, update=True):
if settings.testdebs_repo:
if settings.testdebs_repo.startswith("deb"):
debline = settings.testdebs_repo
elif settings.testdebs_repo.startswith("/"):
debline = "deb file://%s ./" % settings.testdebs_repo
else:
debline = "deb %s ./" % settings.testdebs_repo
logging.debug("enabling testdebs repository '%s'" % debline)
create_file(self.relative("etc/apt/sources.list.d/piuparts-testdebs-repo.list"), debline + "\n")
if update:
self.run(["apt-get", "update"])
def disable_testdebs_repo(self):
if settings.testdebs_repo:
logging.debug("disabling testdebs repository")
remove_files([self.relative("etc/apt/sources.list.d/piuparts-testdebs-repo.list")])
def create_apt_conf(self):
"""Create /etc/apt/apt.conf.d/piuparts inside the chroot."""
lines = ['APT::Get::Assume-Yes "yes";\n']
lines.append('APT::Install-Recommends "%d";\n' % int(settings.install_recommends))
lines.append('APT::Install-Suggests "0";\n')
lines.append('APT::Get::AllowUnauthenticated "%s";\n' % settings.apt_unauthenticated)
if settings.proxy:
proxy = settings.proxy
elif "http_proxy" in os.environ:
proxy = os.environ["http_proxy"]
else:
proxy = None;
pat = re.compile(r"^Acquire::http::Proxy\s+\"([^\"]+)\"", re.I);
p = subprocess.Popen(["apt-config", "dump"],
stdout=subprocess.PIPE)
stdout, _ = p.communicate()
if stdout:
for line in stdout.split("\n"):
m = re.match(pat, line)
if proxy is None and m:
proxy = m.group(1)
if proxy:
lines.append('Acquire::http::Proxy "%s";\n' % proxy)
if settings.dpkg_force_unsafe_io:
lines.append('Dpkg::Options {"--force-unsafe-io";};\n')
if settings.dpkg_force_confdef:
lines.append('Dpkg::Options {"--force-confdef";};\n')
create_file(self.relative("etc/apt/apt.conf.d/piuparts"),
"".join(lines))
def create_dpkg_conf(self):
"""Create /etc/dpkg/dpkg.cfg.d/piuparts inside the chroot."""
lines = []
if settings.dpkg_force_unsafe_io:
lines.append('force-unsafe-io\n')
if settings.dpkg_force_confdef:
lines.append('force-confdef\n')
logging.info("Warning: dpkg has been configured to use the force-confdef option. This will hide problems, see #466118.")
if lines:
if not os.path.exists(self.relative("etc/dpkg/dpkg.cfg.d")):
os.mkdir(self.relative("etc/dpkg/dpkg.cfg.d"))
create_file(self.relative("etc/dpkg/dpkg.cfg.d/piuparts"),
"".join(lines))
def create_policy_rc_d(self):
"""Create a policy-rc.d that prevents daemons from running."""
full_name = self.relative("usr/sbin/policy-rc.d")
create_file(full_name, "#!/bin/sh\nexit 101\n")