/
pyfll
2679 lines (2224 loc) · 102 KB
/
pyfll
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 -tt
# -*- coding: utf-8 -*-
__author__ = 'Kel Modderman'
__copyright__ = '(C) 2008 Kel Modderman <kel@otaku42.de>'
__license__ = 'GPLv2 or any later version'
from configobj import ConfigObj
from subprocess import *
import apt_pkg
import apt
import atexit
import datetime
import fileinput
import glob
import logging
import optparse
import os
import sys
import shutil
import signal
import stat
import tempfile
def restore_sigpipe():
"""Convenience function so that subprocess may be executed with
SIGPIPE restored to default (http://bugs.python.org/issue1652)."""
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
FLL_LOCALE_DEFAULTS = {
'be': 'be_BY',
'cs': 'cs_CZ',
'da': 'da_DK',
'en': 'en_US',
'el': 'el_GR',
'ga': 'ga_IE',
'he': 'he_IL',
'ja': 'ja_JP',
'ko': 'ko_KR',
'nb': 'nb_NO',
'nn': 'nn_NO',
'pt': 'pt_BR',
'sl': 'sl_SI',
'zh': 'zh_CN'
}
class FllLocalesError(Exception):
"""
An FllError class for use by FllLocales.
"""
pass
class FllLocales(object):
"""
A class which provides the ability to determine lists of locale specific
Debian packages using it's detect_locale_packages method.
Arguments:
cache - an apt_pkg cache object
packages - a list or dict of package names which are installed, or are
going to be installed. Locale specific packages are selected
for packages in this data structure.
map - a dict which maps package names with a list of package prefixes
from which the locale string pattern matching can be used
to match locale support packages. The prefered input for map is:
ConfigObj('data/fll-locales-pkg-map').
"""
def __init__(self, cache, packages, map):
self.loc_pkgs_set = set()
for pkg in cache.packages:
if not pkg.version_list:
continue
if pkg.name not in packages:
continue
for loc_pkg in map.keys():
if pkg.name == loc_pkg:
loc_pkg_prefix_list = map.get(loc_pkg)
for loc_pkg_prefix in loc_pkg_prefix_list:
self.loc_pkgs_set.add(loc_pkg_prefix)
break
self.loc_pkgs_list_dict = dict()
for loc_pkg in self.loc_pkgs_set:
self.loc_pkgs_list_dict[loc_pkg] = list()
for pkg in cache.packages:
if not pkg.version_list:
continue
for loc_pkg in self.loc_pkgs_set:
if pkg.name.startswith(loc_pkg + '-'):
self.loc_pkgs_list_dict[loc_pkg].append(pkg.name)
def __compute_locale_loc_suf_list(self, locale):
"""
Compute a list of locale package name suffixes. The sequence of
suffixes are in preferential order, the lowest index being most
preferential.
This is a very private method, used by detect_locale_packages.
Arguments:
locale - a locale string (eg. en_AU, pt_PT etc.)
"""
loc_suf_list = list()
try:
ll, cc = locale.lower().split('_')
except ValueError, e:
raise FllLocalesError(e)
loc_suf_list.append(ll + '-' + cc)
loc_suf_list.append(ll + cc)
loc_suf_list.append(ll)
default = FLL_LOCALE_DEFAULTS.get(ll)
if default and default != locale:
try:
ll, cc = default.lower().split('_')
except ValueError, e:
raise FllLocalesError(e)
loc_suf_list.append(ll + '-' + cc)
loc_suf_list.append(ll + cc)
else:
loc_suf_list.append(ll + '-' + ll)
loc_suf_list.append(ll + ll)
if ll != 'en':
loc_suf_list.append('i18n')
return loc_suf_list
def detect_locale_packages(self, locale):
"""
Process the data structures created at FllLocales instantiation and
return a list of package names which are the likely best candidates
for the locale string given as argument.
Arguments:
locale - a locale string (eg. en_AU, pt_PT etc.)
"""
suffixes = self.__compute_locale_loc_suf_list(locale)
loc_pkg_dict = dict()
for pkg in self.loc_pkgs_set:
loc_pkgs_list = self.loc_pkgs_list_dict.get(pkg)
if not loc_pkgs_list:
continue
if pkg not in loc_pkg_dict:
loc_pkg_dict[pkg] = dict()
for loc_pkg in loc_pkgs_list:
for idx, suf in enumerate(suffixes):
if loc_pkg == '-'.join([pkg, suf]):
loc_pkg_dict[pkg][idx] = loc_pkg
packages = list()
for pkg in self.loc_pkgs_set:
pkg_candidates = loc_pkg_dict.get(pkg)
if not pkg_candidates:
continue
best = min(pkg_candidates)
packages.append(pkg_candidates[best])
return packages
class FllError(Exception):
'''A generic error handler that does nothing.'''
pass
class FLLBuilder(object):
env = {'LANGUAGE': 'C', 'LC_ALL': 'C', 'LANG' : 'C', 'HOME': '/root',
'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'SHELL': '/bin/bash',
'DEBIAN_FRONTEND': 'noninteractive', 'DEBIAN_PRIORITY': 'critical',
'DEBCONF_NOWARNINGS': 'yes'}
diverts = ['/usr/sbin/policy-rc.d',
'/sbin/modprobe',
'/sbin/insmod',
'/usr/sbin/update-grub',
'/usr/sbin/update-initramfs']
def __init__(self, options):
'''Accept options dict, setup logging.'''
self.opts = options
self.conf = None
self.temp = None
self.log = logging.getLogger('log')
self.log.setLevel(logging.DEBUG)
self.time = datetime.datetime.utcnow()
self.uuid = self.time.strftime('%Y-%m-%d-%H-%M-%S-00')
self.timestamp = self.time.strftime('%Y%m%d%H%M')
def __filterList(self, list, dup_warn = True):
'''Return a list containing no duplicate items given a list that
may have duplicate items.'''
d = dict()
for l in list:
if l in d and dup_warn:
self.log.debug('duplicate: %s' % l)
else:
d[l] = True
list = d.keys()
list.sort()
return list
def __lines2list(self, lines):
'''Return a list of stripped strings given a group of line
separated strings'''
return [s.strip() for s in lines.splitlines()
if s.strip() and not s.lstrip().startswith('#')]
def __isexecutable(self, file):
'''Return True is file is executable, False otherwise.'''
try:
mode = os.stat(file)[stat.ST_MODE]
except OSError:
return False
if stat.S_ISREG(mode) and mode & stat.S_IXUSR:
return True
else:
return False
def __prepDir(self, dir):
'''Set up working directories.'''
if not os.path.isdir(dir):
try:
os.makedirs(dir)
os.chown(dir, self.opts.u, self.opts.g)
except:
self.log.exception('failed to create dir: %s' % dir)
raise FllError
return os.path.realpath(dir)
def __initLogger(self, lvl):
'''Set up the logger.'''
fmt = logging.Formatter('%(asctime)s %(levelname)-5s - %(message)s')
out = logging.StreamHandler()
out.setFormatter(fmt)
out.setLevel(lvl)
self.log.addHandler(out)
def __initLogFile(self, file):
'''Set up a log file.'''
file = os.path.realpath(file)
dir = os.path.dirname(file)
self.__prepDir(dir)
try:
fmt = logging.Formatter('%(asctime)s %(levelname)-5s ' +
'%(message)s')
logfile = logging.FileHandler(filename = file, mode = 'w')
logfile.setFormatter(fmt)
logfile.setLevel(logging.DEBUG)
self.log.addHandler(logfile)
os.chown(file, self.opts.u, self.opts.g)
except:
self.log.exception('failed to setup logfile')
raise FllError
def checkOpts(self):
'''Check and provide default class options.'''
if self.opts.d:
self.__initLogger(logging.DEBUG)
else:
self.__initLogger(logging.INFO)
if self.opts.l:
self.__initLogFile(self.opts.l)
if self.opts.c:
if os.path.isfile(self.opts.c):
self.opts.c = os.path.realpath(self.opts.c)
else:
self.log.critical('configuration file does not exist: %s' %
self.opts.c)
raise FllError
else:
self.log.critical('no config file specified on command line')
raise FllError
if self.opts.s:
if not os.path.isdir(self.opts.s):
self.log.critical('share directory not exist: %s' %
self.opts.s)
raise FllError
self.opts.s = os.path.realpath(self.opts.s)
if self.opts.o:
self.opts.o = self.__prepDir(self.opts.o)
if self.opts.b:
self.opts.b = self.__prepDir(self.opts.b)
def _processDefaults(self, d):
'''Form a distro-defaults data structure to be written to
/etc/default/distro of each chroot, and used for release name.'''
for k in ['FLL_DISTRO_NAME', 'FLL_IMAGE_DIR', 'FLL_IMAGE_FILE',
'FLL_MEDIA_NAME', 'FLL_MOUNTPOINT', 'FLL_LIVE_USER',
'FLL_LIVE_USER_GROUPS', 'FLL_GFXBOOT_THEME']:
if not d.get(k):
self.log.critical("%s' is required in 'distro' section " % k +
"of build conf")
raise FllError
for k in ['FLL_DISTRO_NAME', 'FLL_IMAGE_DIR', 'FLL_IMAGE_FILE',
'FLL_LIVE_USER', 'FLL_DISTRO_CODENAME_SAFE',
'FLL_DISTRO_CODENAME_REV_SAFE']:
if not d.get(k):
continue
if not d[k].isalnum():
self.log.critical("'%s' is not alphanumeric: %s" % (k, d[k]))
raise FllError
elif d[k].find(' ') >= 0:
self.log.critical("'%s' contains whitespace: %s" % (k, d[k]))
raise FllError
version = d.get('FLL_DISTRO_VERSION')
if version and version != 'snapshot':
if not d.get('FLL_DISTRO_CODENAME_SAFE'):
self.log.critical("'FLL_DISTRO_VERSION' is set, but " +
"'FLL_DISTRO_CODENAME_SAFE' is not")
raise FllError
for k in ['FLL_DISTRO_CODENAME', 'FLL_DISTRO_CODENAME_REV']:
safe = k + '_SAFE'
if d.get(safe) and not d.get(k):
d[k] = d[safe]
else:
d['FLL_DISTRO_VERSION'] = 'snapshot'
def _getDistroImageFile(self, arch):
'''Return image file that compressed chroot will be archived to.'''
image_file = self.conf['distro']['FLL_IMAGE_FILE']
if arch == 'i386':
image_file += '.686'
else:
image_file += '.%s' % arch
self.log.debug('image_file: %s' % image_file)
return image_file
def _getDistroStamp(self):
'''Return a string suitable for the distro stamp file.'''
d = self.conf['distro']
stamp = ' '.join([d['FLL_DISTRO_NAME'], d['FLL_DISTRO_VERSION']])
if d.get('FLL_DISTRO_VERSION') == 'snapshot':
stamp += ' - %s' % self.conf['packages']['profile']
else:
if d.get('FLL_DISTRO_CODENAME_REV'):
stamp += ' - %s' % d['FLL_DISTRO_CODENAME']
stamp += ' %s -' % d['FLL_DISTRO_CODENAME_REV']
else:
stamp += ' %s -' % d['FLL_DISTRO_CODENAME']
stamp += ' %s' % self.conf['packages']['profile']
stamp += ' - (%s)' % self.timestamp
self.log.debug('stamp: %s' % stamp)
return stamp
def _getDistroMediaName(self):
'''Return a string suitable for the distro stamp file.'''
d = self.conf['distro']
name = '-'.join([d['FLL_DISTRO_NAME'], d['FLL_DISTRO_VERSION']])
if d.get('FLL_DISTRO_VERSION') == 'snapshot':
name += '-%s' % self.conf['packages']['profile']
else:
if d.get('FLL_DISTRO_CODENAME_REV'):
name += '-%s-%s' % (d['FLL_DISTRO_CODENAME_SAFE'],
d['FLL_DISTRO_CODENAME_REV_SAFE'])
else:
name += '-%s' % d['FLL_DISTRO_CODENAME_SAFE']
name += '-%s' % self.conf['packages']['profile']
name += '-' + '-'.join(self.conf['archs'].keys())
name += '-%s' % self.timestamp
self.log.debug('name: %s' % name)
return name
def _processConf(self):
'''Process configuration options.'''
arch = ''
if self.opts.a:
arch = self.opts.a
elif not self.conf.get('archs'):
arch = Popen(['dpkg', '--print-architecture'], preexec_fn=restore_sigpipe,
stdout=PIPE).communicate()[0].rstrip()
if len(arch):
self.log.debug('arch: %s' % arch)
if arch not in self.conf['archs'].keys():
self.conf['archs'] = {arch: dict()}
else:
for arch2 in self.conf['archs'].keys():
if arch != arch2:
del self.conf['archs'][arch2]
for arch in self.conf['archs'].keys():
if 'linux' not in self.conf['archs'][arch]:
if arch == 'i386':
cpu = '486'
else:
cpu = arch
linux = cpu
self.conf['archs'][arch].setdefault('linux', [ linux ])
else:
linux = self.conf['archs'][arch]['linux']
if isinstance(linux, str):
self.conf['archs'][arch]['linux'] = [ linux ]
elif not isinstance(linux, list):
self.log.critical('invalid linux for arch %s in config'
% arch)
raise FllError
for linux in self.conf['archs'][arch]['linux']:
self.log.debug("linux (%s): %s" %
(arch, self.conf['archs'][arch]['linux']))
if len(self.conf['repos'].keys()) < 1:
self.log.critical('no apt repos were specified in build config')
raise FllError
if 'sourcedistro' not in self.conf or \
'name' not in self.conf['sourcedistro']:
self.opts.N = 'debian'
self.opts.C = 'sid'
else:
self.opts.N = self.conf['sourcedistro']['name']
if 'codename' not in self.conf['sourcedistro']:
self.log.critical('codename undefined in distro section of build config')
raise FllError
else:
self.opts.C = self.conf['sourcedistro']['codename']
if self.opts.N not in self.conf['repos']:
self.log.critical('%s repo not configured in build config' % self.opts.N)
raise FllError
for repo in self.conf['repos'].keys():
if self.conf['repos'][repo].get('trivial'):
words = ['label', 'uri']
else:
words = ['label', 'uri', 'suite', 'components']
for word in words:
if word not in self.conf['repos'][repo]:
self.log.critical("no '%s' for apt repo '%s'" %
(word, repo))
raise FllError
if self.opts.p:
self.conf['packages']['profile'] = self.opts.p
elif 'profile' not in self.conf['packages']:
self.conf['packages']['profile'] = 'kde-lite'
self.log.debug('profile: %s' % self.conf['packages']['profile'])
if 'i18n' not in self.conf['packages'] or \
not self.__lines2list(self.conf['packages']['i18n']):
self.conf['packages']['i18n'] = 'en_US'
i18n = self.__lines2list(self.conf['packages']['i18n'])
self.log.debug('i18n: %s' % ' '.join(i18n))
if 'hashkey' not in self.conf['options']:
self.log.info('No key for signing ISO hashes!')
self.opts.k = None
else:
self.opts.k = self.conf['options'].get('hashkey')
self.log.debug('Using key %s for signing.' % self.opts.k)
if not 'options' in self.conf:
self.conf['options'] = dict()
if self.conf['options'].get('build_dir'):
if not self.opts.b:
dir = self.conf['options']['build_dir']
self.opts.b = self.__prepDir(dir)
else:
if not self.opts.b:
self.opts.b = self.__prepDir(os.getcwd())
if self.conf['options'].get('output_dir'):
if not self.opts.o:
dir = self.conf['options']['output_dir']
self.opts.o = self.__prepDir(dir)
else:
if not self.opts.o:
self.opts.o = self.__prepDir(os.getcwd())
if self.conf['options'].get('build_log'):
if not self.opts.l:
self.opts.l = self.conf['options']['build_log']
self.__initLogFile(self.opts.l)
if self.conf['options'].get('http_proxy'):
self.env['http_proxy'] = self.conf['options']['http_proxy']
if self.conf['options'].get('ftp_proxy'):
self.env['ftp_proxy'] = self.conf['options']['ftp_proxy']
self.conf['options'].setdefault('apt_preferences', None)
self.conf['options'].setdefault('apt_recommends', 'no')
self.conf['options'].setdefault('media_include', None)
if 'distro' in self.conf:
self._processDefaults(self.conf['distro'])
self.log.debug('distro-defaults:')
for k, v in self.conf['distro'].items():
self.log.debug('%s="%s"' % (k, v))
self.log.debug('testing stamp/name:')
self._getDistroStamp()
self._getDistroMediaName()
else:
self.log.critical('distro section not found in build config')
raise FllError
def parseConf(self):
'''Parse build configuration file and return it in a dict.'''
self.log.info('reading configuration file...')
self.conf = ConfigObj(self.opts.c)
self._processConf()
def _processPkgProfile(self, arch, profile, dir):
'''Return a dict, arch string as key and package, debconf and postinst
lists.'''
pkgs = {'debconf': [], 'packages': [], 'postinst': []}
linux_meta = ['linux-image', 'linux-headers']
for kvers in self.conf['archs'][arch]['linux']:
pkgs['packages'].extend(['-'.join([l, kvers]) for l in linux_meta])
pname = os.path.basename(profile)
self.log.debug('processing package profile for %s: %s' % (arch, pname))
pfile = ConfigObj(profile)
if 'desc' in pfile:
for l in self.__lines2list(pfile['desc']):
self.log.debug(' %s' % l)
if 'debconf' in pfile:
self.log.debug('debconf:')
for d in self.__lines2list(pfile['debconf']):
pkgs['debconf'].append(d)
self.log.debug(' %s', d)
if 'debconf' in self.conf['packages']:
self.log.debug('debconf (config):')
for d in self.__lines2list(self.conf['packages']['debconf']):
pkgs['debconf'].append(d)
self.log.debug(' %s' % d)
if 'packages' in pfile:
self.log.debug('packages:')
for p in self.__lines2list(pfile['packages']):
pkgs['packages'].append(p)
self.log.debug(' %s' % p)
if 'packages' in self.conf['packages']:
self.log.debug('packages (config):')
for p in self.__lines2list(self.conf['packages']['packages']):
pkgs['packages'].append(p)
self.log.debug(' %s' % p)
if arch in pfile:
self.log.debug('packages (%s):' % arch)
for p in self.__lines2list(pfile[arch]):
pkgs['packages'].append(p)
self.log.debug(' %s' % p)
deps = ['essential']
if 'deps' in pfile:
self.log.debug('deps:')
for dep in self.__lines2list(pfile['deps']):
deps.append(dep)
self.log.debug(' %s' % dep)
if 'deps' in self.conf['packages']:
self.log.debug('deps (config):')
for dep in self.__lines2list(self.conf['packages']['deps']):
deps.append(dep)
self.log.debug(' %s' % dep)
if os.path.isfile(profile + '.postinst'):
self.log.debug('registering postinst script')
pkgs['postinst'].append(profile + '.postinst')
self.log.debug('---')
for dep in deps:
depfile = os.path.join(dir, 'packages.d', dep)
if not os.path.isfile(depfile):
self.log.critical('no such dep file: %s' % depfile)
raise FllError
dname = os.path.basename(depfile)
self.log.debug('processing dependency file: %s' % dname)
dfile = ConfigObj(depfile)
if 'desc' in dfile:
for l in self.__lines2list(dfile['desc']):
self.log.debug(' %s' % l)
if 'debconf' in dfile:
self.log.debug('debconf:')
for d in self.__lines2list(dfile['debconf']):
pkgs['debconf'].append(d)
self.log.debug(' %s' % d)
if 'packages' in dfile:
self.log.debug('packages:')
for p in self.__lines2list(dfile['packages']):
pkgs['packages'].append(p)
self.log.debug(' %s' % p)
if arch in dfile:
self.log.debug('packages (%s):' % arch)
for p in self.__lines2list(dfile[arch]):
pkgs['packages'].append(p)
self.log.debug(' %s' % p)
if os.path.isfile(depfile + '.postinst'):
self.log.debug('registering postinst script')
pkgs['postinst'].append(depfile + '.postinst')
self.log.debug('---')
self.log.debug('package summary for %s:' % arch)
pkgs['packages'].sort()
for p in pkgs['packages']:
self.log.debug(' %s' % p)
self.log.debug('debconf summary for %s:' % arch)
pkgs['debconf'].sort()
for d in pkgs['debconf']:
self.log.debug(' %s' % d)
pkgs['packages'] = self.__filterList(pkgs['packages'])
return pkgs
def parsePkgProfile(self):
'''Parse packages profile file(s).'''
self.log.info('processing package profile (%s)...' %
self.conf['packages']['profile'])
dir = os.path.join(self.opts.s, 'packages')
file = os.path.join(dir, self.conf['packages']['profile'])
if not os.path.isfile(file):
self.log.critical('no such package profile file: %s' % file)
raise FllError
self.pkgs = dict()
for arch in self.conf['archs'].keys():
self.pkgs[arch] = self._processPkgProfile(arch, file, dir)
try:
self.pkgs[arch]['packages'] += \
self.__lines2list(self.conf['packages'][arch])
except KeyError:
pass
def _getDebconfList(self, arch):
'''Return debconf list for arch.'''
return self.pkgs[arch]['debconf']
def _getPackageList(self, arch):
'''Return package list for arch.'''
return self.pkgs[arch]['packages']
def _getPostinstList(self, arch):
'''Return postinst list for arch.'''
return self.pkgs[arch]['postinst']
def _stageMedia(self, point, dir, fnames):
'''Copy content from a directory to live media staging area.'''
orig, dest = point
dirname = dir.partition(orig)[2].lstrip('/')
remove = []
for f in fnames:
if f.startswith('.') or f.endswith('~'):
remove.append(f)
elif os.path.isdir(os.path.join(dir, f)) and \
f == 'boot':
remove.append(f)
elif os.path.isdir(os.path.join(dir, f)):
if not os.path.isdir(os.path.join(dest, dirname, f)):
os.mkdir(os.path.join(dest, dirname, f))
else:
if not os.path.isfile(os.path.join(dest, dirname, f)):
shutil.copy(os.path.join(dir, f),
os.path.join(dest, dirname))
for r in remove:
fnames.remove(r)
def stageBuildArea(self):
'''Prepare temporary directory for chroots and result staging area.'''
self.log.debug('preparing build area...')
self.temp = tempfile.mkdtemp(prefix = 'fll_', dir = self.opts.b)
os.chown(self.temp, self.opts.u, self.opts.g)
atexit.register(self.cleanup)
stage = os.path.join(self.temp, 'staging')
os.mkdir(stage)
os.mkdir(os.path.join(stage, 'boot'))
os.mkdir(os.path.join(stage, self.conf['distro']['FLL_IMAGE_DIR']))
if self.conf['options']['media_include']:
media_include = self.conf['options']['media_include']
if os.path.isdir(media_include):
try:
os.path.walk(media_include, self._stageMedia,
(media_include, stage))
except:
self.log.exception('problem copying media_include ' +
'contents to staging dir')
raise FllError
def _mount(self, chroot):
'''Mount virtual filesystems in a chroot.'''
virtfs = {'devpts': 'dev/pts', 'proc': 'proc'}
for v in virtfs.items():
cmd = ['mount', '-t', v[0], 'fll-' + v[0],
os.path.join(chroot, v[1])]
retv = call(cmd, preexec_fn=restore_sigpipe)
if retv != 0:
self.log.critical('failed to mount chroot %s' % v[0])
raise FllError
def _umount(self, chrootdir):
'''Umount any mount points in a chroot.'''
umount_list = []
try:
for line in open('/proc/mounts'):
(dev, mnt, fs, options, d, p) = line.split()
if mnt.startswith(chrootdir):
umount_list.append(mnt)
except IOError:
self.log.exception('failed to open /proc/mounts')
raise FllError
umount_list.sort(key=len)
umount_list.reverse()
for mpoint in umount_list:
retv = call(['umount', mpoint], preexec_fn=restore_sigpipe)
if retv != 0:
self.log.critical('umount failed for: %s' % mpoint)
raise FllError
def _nuke(self, dir):
'''Nuke directory tree.'''
if os.path.isdir(dir):
self.log.debug('nuking directory: %s' % dir)
try:
shutil.rmtree(dir)
except:
self.log.exception('unable to remove %s' % dir)
raise FllError
else:
self.log.debug('not nuking directory (does not exist): %s' % dir)
def _nukeChroot(self, arch):
'''Convenience function to nuke chroot given by arch name.'''
if not self.opts.P:
self.log.info('nuking %s chroot...' % arch)
chroot = os.path.join(self.temp, arch)
self._umount(chroot)
self._nuke(chroot)
def cleanup(self):
'''Clean up the build area after taking care that all build chroots
have been taken care of.'''
self.log.info('cleaning up...')
for arch in self.conf['archs'].keys():
dir = os.path.join(self.temp, arch)
if os.path.isdir(dir):
self.log.debug('cleaning up %s chroot...' % arch)
self._umount(dir)
if not self.opts.P:
self._nuke(dir)
if not self.opts.P:
self._nuke(self.temp)
def __execLogged(self, cmd, check_returncode):
'''Execute a command logging all output. Output sent to the console is
buffered until the command has finished execution.'''
self.log.debug(' '.join(cmd))
try:
c = Popen(cmd, stdout = PIPE, stderr = STDOUT, env = self.env,
close_fds = True, preexec_fn=restore_sigpipe)
cout = c.communicate()[0]
retv = c.returncode
except KeyboardInterrupt:
raise FllError
except:
self.log.exception('problem executing command: %s' % ' '.join(cmd))
raise FllError
for line in cout.splitlines():
if self.opts.q:
self.log.debug(line.rstrip())
else:
self.log.info(line.rstrip())
if retv != 0 and check_returncode:
self.log.critical('command failed with return value: %d' %
c.returncode)
raise FllError
def __exec(self, cmd, check_returncode):
'''Execute subprocess without buffering output in a pipe.'''
self.log.debug(' '.join(cmd))
try:
if self.opts.q:
retv = call(cmd, stdout = open(os.devnull, 'w'),
stderr = STDOUT, env = self.env,
close_fds = True, preexec_fn=restore_sigpipe)
else:
retv = call(cmd, env = self.env, close_fds = True,
preexec_fn=restore_sigpipe)
except KeyboardInterrupt:
raise FllError
except:
self.log.exception('problem executing command: %s' % ' '.join(cmd))
raise FllError
if retv != 0 and check_returncode:
self.log.critical('command failed with return value: %d' % retv)
raise FllError
def _execCmd(self, cmd, check_returncode = True):
'''Convenience wrapper for subprocess execution.'''
if self.opts.l:
self.__execLogged(cmd, check_returncode)
else:
self.__exec(cmd, check_returncode)
def _execInChroot(self, arch, args, check_returncode = True):
'''Run command in a chroot.'''
chroot = os.path.join(self.temp, arch)
cmd = ['chroot', chroot]
cmd.extend(args)
self._mount(chroot)
if self.opts.l:
self.__execLogged(cmd, check_returncode)
else:
self.__exec(cmd, check_returncode)
self._umount(chroot)
def _aptGetInstall(self, arch, pkgs, download_only = False):
'''An apt-get install wrapper. Automatic installation of recommended
packages defaults to disabled.'''
aptget = ['apt-get', '--yes']
if download_only:
aptget.append('--download-only')
if self.conf['options']['apt_recommends'] == 'no':
aptget.extend(['-o', 'APT::Install-Recommends=0'])
if self.opts.d:
aptget.extend(['-o', 'APT::Get::Show-Versions=1'])
aptget.append('install')
aptget.extend(pkgs)
self._execInChroot(arch, aptget)
def __cdebBootStrap(self, arch, dir, mirror, codename):
'''Bootstrap a debian system with cdebootstrap.'''
cmd = ['cdebootstrap', '--arch=%s' % arch,
'--include=apt-utils,bzip2,gnupg,xz-utils',
'--flavour=minimal', codename, dir, mirror]
if self.opts.d:
cmd.append('--debug')
elif self.opts.v:
cmd.append('--verbose')
self._execCmd(cmd)
cmd = 'dpkg --purge cdebootstrap-helper-rc.d'
self._execInChroot(arch, cmd.split())
def __debBootStrap(self, arch, dir, mirror, codename):
'''Bootstrap a debian system with debootstrap.'''
cmd = ['debootstrap', '--arch=%s' % arch, '--include=apt-utils,gnupg,bzip2,xz-utils',
'--variant=minbase', codename, dir, mirror]
if self.opts.d or self.opts.v:
cmd.insert(1, '--verbose')
self._execCmd(cmd)
def _bootStrap(self, arch):
'''Bootstrap a debian system with cdebootstrap.'''
distro = self.opts.N
debian = self.conf['repos'][distro]
codename = self.opts.C
if debian.get('cached'):
mirror = debian['cached']
else:
mirror = debian['uri']
dir = os.path.join(self.temp, arch)
self.log.info('bootstrapping %s %s %s...' % (distro,codename,arch))
bootstrapper = self.conf['options'].get('bootstrapper')
if bootstrapper == 'debootstrap':
self.__debBootStrap(arch, dir, mirror, codename)
else:
self.__cdebBootStrap(arch, dir, mirror, codename)
shutil.copy('/etc/hosts', os.path.join(dir, 'etc'))
shutil.copy('/etc/resolv.conf', os.path.join(dir, 'etc'))
os.mkdir(os.path.join(dir, 'disks'), 0755)
def _writeAptLists(self, arch, cached = False, src_uri = False):
'''Write apt source lists to /etc/apt/sources.list.d/*.'''
chroot = os.path.join(self.temp, arch)
for repo in self.conf['repos'].keys():
r = self.conf['repos'][repo]
file = os.path.join(chroot, 'etc/apt/sources.list.d',
r['label'] + '.list')
if os.path.isfile(os.path.join(chroot, 'etc/apt/sources.list')):
s = None
try:
s = open(os.path.join(chroot, 'etc/apt/sources.list'), 'a')
s.write('# %-74s#\n' % file.partition(chroot)[2])
except IOError:
self.log.exception('failed to open /etc/apt/sources.list')
raise FllError
finally:
if s:
s.close()