This repository has been archived by the owner on Jun 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
plugininstall-wily.py
executable file
·1774 lines (1561 loc) · 70.9 KB
/
plugininstall-wily.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
# -*- coding: utf-8; Mode: Python; indent-tabs-mode: nil; tab-width: 4 -*-
# Copyright (C) 2005 Javier Carranza and others for Guadalinex
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd.
# Copyright (C) 2007 Mario Limonciello
#
# 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 St, Fifth Floor, Boston, MA 02110-1301 USA
from __future__ import print_function
import fcntl
import gzip
import os
import platform
import pwd
import re
import shutil
import socket
import stat
import struct
import subprocess
import sys
import syslog
import textwrap
import traceback
import apt_pkg
from apt.cache import Cache
import debconf
sys.path.insert(0, '/usr/lib/ubiquity')
from ubiquity import install_misc, misc, osextras, plugin_manager
from ubiquity.components import apt_setup, check_kernels, hw_detect
INTERFACES_TEXT = """\
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
# The loopback network interface
auto lo
iface lo inet loopback"""
HOSTS_TEXT = """\
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters"""
IFTAB_TEXT = """\
# This file assigns persistent names to network interfaces.
# See iftab(5) for syntax.
"""
def cleanup_after(func):
def wrapper(self):
try:
func(self)
finally:
self.cleanup()
try:
self.db.progress('STOP')
except (KeyboardInterrupt, SystemExit):
raise
except:
pass
return wrapper
class PluginProgress:
def __init__(self, db):
self._db = db
def info(self, title):
self._db.progress('INFO', title)
def get(self, question):
return self._db.get(question)
def substitute(self, template, substr, data):
self._db.subst(template, substr, data)
class Install(install_misc.InstallBase):
def __init__(self):
install_misc.InstallBase.__init__(self)
self.db = debconf.Debconf()
self.kernel_version = platform.release()
# Get langpacks from install
self.langpacks = []
if os.path.exists('/var/lib/ubiquity/langpacks'):
with open('/var/lib/ubiquity/langpacks') as langpacks:
for line in langpacks:
self.langpacks.append(line.strip())
# Load plugins
modules = plugin_manager.load_plugins()
modules = plugin_manager.order_plugins(modules)
self.plugins = [x for x in modules if hasattr(x, 'Install')]
if 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
self.target = '/'
return
apt_pkg.init_config()
apt_pkg.config.set("Dir", self.target)
apt_pkg.config.set("Dir::State::status",
self.target_file('var/lib/dpkg/status'))
apt_pkg.config.set("APT::GPGV::TrustedKeyring",
self.target_file('etc/apt/trusted.gpg'))
# Keep this in sync with configure_apt.
# TODO cjwatson 2011-03-03: consolidate this.
try:
if self.db.get('base-installer/install-recommends') == 'false':
apt_pkg.config.set("APT::Install-Recommends", "false")
except debconf.DebconfError:
pass
apt_pkg.config.set("APT::Authentication::TrustCDROM", "true")
apt_pkg.config.set("Acquire::gpgv::Options::",
"--ignore-time-conflict")
try:
if self.db.get('debian-installer/allow_unauthenticated') == 'true':
apt_pkg.config.set("APT::Get::AllowUnauthenticated", "true")
apt_pkg.config.set(
"Aptitude::CmdLine::Ignore-Trust-Violations", "true")
except debconf.DebconfError:
pass
apt_pkg.config.set("APT::CDROM::NoMount", "true")
apt_pkg.config.set("Acquire::cdrom::mount", "/cdrom")
apt_pkg.config.set("Acquire::cdrom::/cdrom/::Mount", "true")
apt_pkg.config.set("Acquire::cdrom::/cdrom/::UMount", "true")
apt_pkg.config.set("Acquire::cdrom::AutoDetect", "false")
apt_pkg.config.set("Dir::Media::MountPath", "/cdrom")
apt_pkg.config.set("DPkg::Options::", "--root=%s" % self.target)
# We don't want apt-listchanges or dpkg-preconfigure, so just clear
# out the list of pre-installation hooks.
apt_pkg.config.clear("DPkg::Pre-Install-Pkgs")
apt_pkg.init_system()
use_restricted = True
try:
if self.db.get('apt-setup/restricted') == 'false':
use_restricted = False
except debconf.DebconfError:
pass
if not use_restricted:
self.restricted_cache = Cache()
# TODO can we really pick up where install.py left off? They're using two
# separate databases, which means two progress states. Might need to
# record the progress position in find_next_step and pick up from there.
# Ask Colin.
@cleanup_after
def run(self):
"""Main entry point."""
# We pick up where install.py left off.
if 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
self.prev_count = 0
else:
self.prev_count = 74
self.count = self.prev_count
self.start = self.prev_count
self.end = self.start + 22 + len(self.plugins)
self.db.progress(
'START', self.start, self.end, 'ubiquity/install/title')
self.configure_python()
self.next_region()
self.db.progress('INFO', 'ubiquity/install/network')
self.configure_network()
self.configure_locale()
self.next_region()
self.db.progress('INFO', 'ubiquity/install/apt')
self.configure_apt()
self.configure_plugins()
self.next_region()
self.run_target_config_hooks()
self.next_region(size=5)
# Ignore failures from language pack installation.
try:
self.install_language_packs()
except install_misc.InstallStepError:
pass
except IOError:
pass
except SystemError:
pass
self.next_region()
#self.remove_unusable_kernels()
self.next_region(size=4)
self.db.progress('INFO', 'ubiquity/install/hardware')
self.configure_hardware()
# Tell apt-install to install packages directly from now on.
with open('/var/lib/ubiquity/apt-install-direct', 'w'):
pass
self.next_region()
self.db.progress('INFO', 'ubiquity/install/installing')
if 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
self.install_oem_extras()
else:
self.install_extras()
self.next_region()
self.db.progress('INFO', 'ubiquity/install/bootloader')
self.configure_bootloader()
self.next_region(size=4)
self.db.progress('INFO', 'ubiquity/install/removing')
if 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
try:
if misc.create_bool(self.db.get('oem-config/remove_extras')):
self.remove_oem_extras()
except debconf.DebconfError:
pass
else:
self.remove_extras()
self.next_region()
if 'UBIQUITY_OEM_USER_CONFIG' not in os.environ:
self.install_restricted_extras()
self.db.progress('INFO', 'ubiquity/install/apt_clone_restore')
try:
self.apt_clone_restore()
except:
syslog.syslog(
syslog.LOG_WARNING,
'Could not restore packages from the previous install:')
for line in traceback.format_exc().split('\n'):
syslog.syslog(syslog.LOG_WARNING, line)
self.db.input('critical', 'ubiquity/install/broken_apt_clone')
self.db.go()
try:
self.copy_network_config()
except:
syslog.syslog(
syslog.LOG_WARNING,
'Could not copy the network configuration:')
for line in traceback.format_exc().split('\n'):
syslog.syslog(syslog.LOG_WARNING, line)
self.db.input('critical', 'ubiquity/install/broken_network_copy')
self.db.go()
try:
self.copy_bluetooth_config()
except:
syslog.syslog(
syslog.LOG_WARNING,
'Could not copy the bluetooth configuration:')
for line in traceback.format_exc().split('\n'):
syslog.syslog(syslog.LOG_WARNING, line)
self.db.input('critical', 'ubiquity/install/broken_bluetooth_copy')
self.db.go()
try:
self.recache_apparmor()
except:
syslog.syslog(
syslog.LOG_WARNING, 'Could not create an Apparmor cache:')
for line in traceback.format_exc().split('\n'):
syslog.syslog(syslog.LOG_WARNING, line)
try:
self.copy_wallpaper_cache()
except:
syslog.syslog(
syslog.LOG_WARNING, 'Could not copy wallpaper cache:')
for line in traceback.format_exc().split('\n'):
syslog.syslog(syslog.LOG_WARNING, line)
self.copy_dcd()
self.db.progress('SET', self.count)
self.db.progress('INFO', 'ubiquity/install/log_files')
self.copy_logs()
self.save_random_seed()
self.db.progress('SET', self.end)
def _get_uid_gid_on_target(self, target_user):
"""Helper that gets the uid/gid of the username in the target chroot"""
uid = subprocess.Popen(
['chroot', self.target, 'sudo', '-u', target_user, '--',
'id', '-u'], stdout=subprocess.PIPE, universal_newlines=True)
uid = uid.communicate()[0].strip('\n')
gid = subprocess.Popen(
['chroot', self.target, 'sudo', '-u', target_user, '--',
'id', '-g'], stdout=subprocess.PIPE, universal_newlines=True)
gid = gid.communicate()[0].strip('\n')
try:
uid = int(uid)
gid = int(gid)
except ValueError:
return (None, None)
return uid, gid
def configure_python(self):
"""Byte-compile Python modules.
To save space, Ubuntu excludes .pyc files from the live filesystem.
Recreate them now to restore the appearance of a system installed
from .debs.
"""
cache = Cache()
# Python standard library.
re_minimal = re.compile('^python\d+\.\d+-minimal$')
python_installed = sorted([
pkg[:-8] for pkg in cache.keys()
if re_minimal.match(pkg) and cache[pkg].is_installed])
for python in python_installed:
re_file = re.compile('^/usr/lib/%s/.*\.py$' % python)
files = [
f for f in cache['%s-minimal' % python].installed_files
if (re_file.match(f) and
not os.path.exists(self.target_file('%sc' % f[1:])))]
install_misc.chrex(self.target, python,
'/usr/lib/%s/py_compile.py' % python, *files)
files = [
f for f in cache[python].installed_files
if (re_file.match(f) and
not os.path.exists(self.target_file('%sc' % f[1:])))]
install_misc.chrex(self.target, python,
'/usr/lib/%s/py_compile.py' % python, *files)
# Modules provided by the core Debian Python packages.
default = subprocess.Popen(
['chroot', self.target, 'pyversions', '-d'],
stdout=subprocess.PIPE,
universal_newlines=True).communicate()[0].rstrip('\n')
if default:
install_misc.chrex(self.target, default, '-m', 'compileall',
'/usr/share/python/')
if osextras.find_on_path_root(self.target, 'py3compile'):
install_misc.chrex(self.target, 'py3compile', '-p', 'python3',
'/usr/share/python3/')
def run_hooks(path, *args):
for hook in osextras.glob_root(self.target, path):
if not os.access(self.target_file(hook[1:]), os.X_OK):
continue
install_misc.chrex(self.target, hook, *args)
# Public and private modules provided by other packages.
install_misc.chroot_setup(self.target)
try:
if osextras.find_on_path_root(self.target, 'pyversions'):
supported = subprocess.Popen(
['chroot', self.target, 'pyversions', '-s'],
stdout=subprocess.PIPE,
universal_newlines=True).communicate()[0].rstrip('\n')
for python in supported.split():
try:
cachedpython = cache['%s-minimal' % python]
except KeyError:
continue
if not cachedpython.is_installed:
continue
version = cachedpython.installed.version
run_hooks('/usr/share/python/runtime.d/*.rtinstall',
'rtinstall', python, '', version)
run_hooks('/usr/share/python/runtime.d/*.rtupdate',
'pre-rtupdate', python, python)
run_hooks('/usr/share/python/runtime.d/*.rtupdate',
'rtupdate', python, python)
run_hooks('/usr/share/python/runtime.d/*.rtupdate',
'post-rtupdate', python, python)
if osextras.find_on_path_root(self.target, 'py3versions'):
supported = subprocess.Popen(
['chroot', self.target, 'py3versions', '-s'],
stdout=subprocess.PIPE,
universal_newlines=True).communicate()[0].rstrip('\n')
for python in supported.split():
try:
cachedpython = cache['%s-minimal' % python]
except KeyError:
continue
if not cachedpython.is_installed:
continue
version = cachedpython.installed.version
run_hooks('/usr/share/python3/runtime.d/*.rtinstall',
'rtinstall', python, '', version)
run_hooks('/usr/share/python3/runtime.d/*.rtupdate',
'pre-rtupdate', python, python)
run_hooks('/usr/share/python3/runtime.d/*.rtupdate',
'rtupdate', python, python)
run_hooks('/usr/share/python3/runtime.d/*.rtupdate',
'post-rtupdate', python, python)
finally:
install_misc.chroot_cleanup(self.target)
def configure_network(self):
"""Automatically configure the network.
At present, the only thing the user gets to tweak in the UI is the
hostname. Some other things will be copied from the live filesystem,
so changes made there will be reflected in the installed system.
Unfortunately, at present we have to duplicate a fair bit of netcfg
here, because it's hard to drive netcfg in a way that won't try to
bring interfaces up and down.
"""
# TODO cjwatson 2006-03-30: just call netcfg instead of doing all
# this; requires a netcfg binary that doesn't bring interfaces up
# and down
if self.target != '/':
for path in ('/etc/network/interfaces', '/etc/resolv.conf'):
if os.path.exists(path):
targetpath = self.target_file(path[1:])
st = os.lstat(path)
if stat.S_ISLNK(st.st_mode):
if os.path.lexists(targetpath):
os.unlink(targetpath)
linkto = os.readlink(path)
os.symlink(linkto, targetpath)
else:
shutil.copy2(path, targetpath)
else:
if not os.path.exists('/etc/network/interfaces'):
# Make sure there's at least something here so that ifupdown
# doesn't get upset at boot.
with open('/etc/network/interfaces', 'w') as interfaces:
print(INTERFACES_TEXT, file=interfaces)
try:
hostname = self.db.get('netcfg/get_hostname')
except debconf.DebconfError:
hostname = ''
try:
domain = self.db.get('netcfg/get_domain').rstrip('.')
except debconf.DebconfError:
domain = ''
if hostname == '':
hostname = 'ubuntu'
with open(self.target_file('etc/hosts'), 'w') as hosts:
print("127.0.0.1\tlocalhost", file=hosts)
if domain:
print("127.0.1.1\t%s.%s\t%s" % (hostname, domain, hostname),
file=hosts)
else:
print("127.0.1.1\t%s" % hostname, file=hosts)
print(HOSTS_TEXT, file=hosts)
# Network Manager's ifupdown plugin has an inotify watch on
# /etc/hostname, which can trigger a race condition if /etc/hostname is
# written and immediately followed with /etc/hosts.
with open(self.target_file('etc/hostname'), 'w') as fp:
print(hostname, file=fp)
if 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
os.system("hostname %s" % hostname)
persistent_net = '/etc/udev/rules.d/70-persistent-net.rules'
if os.path.exists(persistent_net):
if self.target != '/':
shutil.copy2(
persistent_net, self.target_file(persistent_net[1:]))
else:
# TODO cjwatson 2006-03-30: from <bits/ioctls.h>; ugh, but no
# binding available
SIOCGIFHWADDR = 0x8927
# <net/if_arp.h>
ARPHRD_ETHER = 1
if_names = {}
sock = socket.socket(socket.SOCK_DGRAM)
interfaces = install_misc.get_all_interfaces()
for i in range(len(interfaces)):
if_names[interfaces[i]] = struct.unpack(
'H6s', fcntl.ioctl(
sock.fileno(), SIOCGIFHWADDR,
struct.pack('256s', interfaces[i].encode()))[16:24])
sock.close()
with open(self.target_file('etc/iftab'), 'w') as iftab:
print(IFTAB_TEXT, file=iftab)
for i in range(len(interfaces)):
dup = False
if_name = if_names[interfaces[i]]
if if_name is None or if_name[0] != ARPHRD_ETHER:
continue
for j in range(len(interfaces)):
if i == j or if_names[interfaces[j]] is None:
continue
if if_name[1] != if_names[interfaces[j]][1]:
continue
if if_names[interfaces[j]][0] == ARPHRD_ETHER:
dup = True
if dup:
continue
line = (interfaces[i] + " mac " +
':'.join(['%02x' % if_name[1][c]
for c in range(6)]))
line += " arp %d" % if_name[0]
print(line, file=iftab)
def run_plugin(self, plugin):
"""Run a single install plugin."""
self.next_region()
# set a generic info message in case plugin doesn't provide one
self.db.progress('INFO', 'ubiquity/install/title')
inst = plugin.Install(None, db=self.db)
ret = inst.install(self.target, PluginProgress(self.db))
if ret:
raise install_misc.InstallStepError(
"Plugin %s failed with code %s" % (plugin.NAME, ret))
def configure_locale(self):
"""Configure the locale by running the language plugin.
We need to do this as early as possible so that apt can emit
properly-localised messages when running in the target system.
"""
try:
language_plugin = [
plugin for plugin in self.plugins
if (plugin_manager.get_mod_string(plugin, "NAME") ==
"language")][0]
except IndexError:
return
self.run_plugin(language_plugin)
# Don't run this plugin again.
self.plugins = [
plugin for plugin in self.plugins if plugin != language_plugin]
def configure_plugins(self):
"""Apply plugin settings to installed system."""
for plugin in self.plugins:
self.run_plugin(plugin)
def configure_apt(self):
"""Configure /etc/apt/sources.list."""
if 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
return # apt will already be setup as the OEM wants
# TODO cjwatson 2007-07-06: Much of the following is
# cloned-and-hacked from base-installer/debian/postinst. Perhaps we
# should come up with a way to avoid this.
# Keep this in sync with __init__.
try:
if self.db.get('base-installer/install-recommends') == 'false':
tf = self.target_file('etc/apt/apt.conf.d/00InstallRecommends')
with open(tf, 'w') as apt_conf_ir:
print('APT::Install-Recommends "false";', file=apt_conf_ir)
except debconf.DebconfError:
pass
# Make apt trust CDs. This is not on by default (we think).
# This will be left in place on the installed system.
tf = self.target_file('etc/apt/apt.conf.d/00trustcdrom')
with open(tf, 'w') as apt_conf_tc:
print('APT::Authentication::TrustCDROM "true";', file=apt_conf_tc)
# Avoid clock skew causing gpg verification issues.
# This file will be left in place until the end of the install.
tf = self.target_file('etc/apt/apt.conf.d/00IgnoreTimeConflict')
with open(tf, 'w') as apt_conf_itc:
print('Acquire::gpgv::Options { "--ignore-time-conflict"; };',
file=apt_conf_itc)
try:
if self.db.get('debian-installer/allow_unauthenticated') == 'true':
tf = self.target_file(
'etc/apt/apt.conf.d/00AllowUnauthenticated')
with open(tf, 'w') as apt_conf_au:
print('APT::Get::AllowUnauthenticated "true";',
file=apt_conf_au)
print('Aptitude::CmdLine::Ignore-Trust-Violations "true";',
file=apt_conf_au)
except debconf.DebconfError:
pass
# let apt inside the chroot see the cdrom
if self.target != "/":
target_cdrom = self.target_file('cdrom')
misc.execute('umount', target_cdrom)
if not os.path.exists(target_cdrom):
if os.path.lexists(target_cdrom):
os.unlink(target_cdrom)
os.mkdir(target_cdrom)
misc.execute('mount', '--bind', '/cdrom', target_cdrom)
# Make apt-cdrom and apt not unmount/mount CD-ROMs.
# This file will be left in place until the end of the install.
tf = self.target_file('etc/apt/apt.conf.d/00NoMountCDROM')
with open(tf, 'w') as apt_conf_nmc:
print(textwrap.dedent("""\
APT::CDROM::NoMount "true";
Acquire::cdrom {
mount "/cdrom";
"/cdrom/" {
Mount "true";
UMount "true";
};
AutoDetect "false";
};
Dir::Media::MountPath "/cdrom";"""), file=apt_conf_nmc)
# This will be reindexed after installation based on the full
# installed sources.list.
try:
shutil.rmtree(
self.target_file('var/lib/apt-xapian-index'),
ignore_errors=True)
except OSError:
pass
dbfilter = apt_setup.AptSetup(None, self.db)
ret = dbfilter.run_command(auto_process=True)
if ret != 0:
raise install_misc.InstallStepError(
"AptSetup failed with code %d" % ret)
def run_target_config_hooks(self):
"""Run hook scripts from /usr/lib/ubiquity/target-config.
This allows casper to hook into us and repeat bits of its
configuration in the target system.
"""
if 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
return # These were already run once during install
hookdir = '/usr/lib/ubiquity/target-config'
if os.path.isdir(hookdir):
# Exclude hooks containing '.', so that *.dpkg-* et al are avoided.
hooks = [entry for entry in os.listdir(hookdir)
if '.' not in entry]
self.db.progress('START', 0, len(hooks), 'ubiquity/install/title')
self.db.progress('INFO', 'ubiquity/install/target_hooks')
for hookentry in hooks:
hook = os.path.join(hookdir, hookentry)
syslog.syslog('running %s' % hook)
if not os.access(hook, os.X_OK):
self.db.progress('STEP', 1)
continue
# Errors are ignored at present, although this may change.
subprocess.call(['log-output', '-t', 'ubiquity',
'--pass-stdout', hook])
self.db.progress('STEP', 1)
self.db.progress('STOP')
def install_language_packs(self):
if not self.langpacks:
return
self.do_install(self.langpacks, langpacks=True)
self.verify_language_packs()
def verify_language_packs(self):
if os.path.exists('/var/lib/ubiquity/no-install-langpacks'):
return # always complete enough
if self.db.get('pkgsel/ignore-incomplete-language-support') == 'true':
return
cache = Cache()
incomplete = False
for pkg in self.langpacks:
if pkg.startswith('gimp-help-'):
# gimp-help-common is far too big to fit on CDs, so don't
# worry about it.
continue
cachedpkg = install_misc.get_cache_pkg(cache, pkg)
if cachedpkg is None or not cachedpkg.is_installed:
syslog.syslog('incomplete language support: %s missing' % pkg)
incomplete = True
break
if incomplete:
language_support_dir = \
self.target_file('usr/share/language-support')
update_notifier_dir = \
self.target_file('var/lib/update-notifier/user.d')
for note in ('incomplete-language-support-gnome.note',
'incomplete-language-support-qt.note'):
notepath = os.path.join(language_support_dir, note)
if os.path.exists(notepath):
if not os.path.exists(update_notifier_dir):
os.makedirs(update_notifier_dir)
shutil.copy(notepath,
os.path.join(update_notifier_dir, note))
break
def traverse_for_kernel(self, cache, pkg):
kern = install_misc.get_cache_pkg(cache, pkg)
if kern is None:
return None
pkc = cache._depcache.get_candidate_ver(kern._pkg)
if 'Depends' in pkc.depends_list:
dependencies = pkc.depends_list['Depends']
else:
# Didn't find.
return None
for dep in dependencies:
name = dep[0].target_pkg.name
if name.startswith('linux-image-2.'):
return name
elif name.startswith('linux-'):
return self.traverse_for_kernel(cache, name)
def remove_unusable_kernels(self):
"""Remove unusable kernels.
Keeping these may cause us to be unable to boot.
"""
if 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
return
self.db.progress('START', 0, 5, 'ubiquity/install/title')
self.db.progress('INFO', 'ubiquity/install/find_removables')
# Check for kernel packages to remove.
dbfilter = check_kernels.CheckKernels(None, self.db)
dbfilter.run_command(auto_process=True)
install_kernels = set()
new_kernel_pkg = None
new_kernel_version = None
install_kernels_path = "/var/lib/ubiquity/install-kernels"
if os.path.exists(install_kernels_path):
with open(install_kernels_path) as install_kernels_file:
for line in install_kernels_file:
kernel = line.strip()
install_kernels.add(kernel)
# If we decided to actively install a particular kernel
# like this, it's probably because we prefer it to the
# default one, so we'd better update kernel_version to
# match.
if kernel.startswith('linux-image-2.'):
new_kernel_pkg = kernel
new_kernel_version = kernel[12:]
elif kernel.startswith('linux-generic-'):
# Traverse dependencies to find the real kernel image.
cache = Cache()
kernel = self.traverse_for_kernel(cache, kernel)
if kernel:
new_kernel_pkg = kernel
new_kernel_version = kernel[12:]
install_kernels_file.close()
remove_kernels = set()
remove_kernels_path = "/var/lib/ubiquity/remove-kernels"
if os.path.exists(remove_kernels_path):
with open(remove_kernels_path) as remove_kernels_file:
for line in remove_kernels_file:
remove_kernels.add(line.strip())
if len(install_kernels) == 0 and len(remove_kernels) == 0:
self.db.progress('STOP')
return
# TODO cjwatson 2009-10-19: These regions are rather crude and
# should be improved.
self.db.progress('SET', 1)
self.progress_region(1, 2)
if install_kernels:
self.do_install(install_kernels)
install_misc.record_installed(install_kernels)
if new_kernel_pkg:
cache = Cache()
cached_pkg = install_misc.get_cache_pkg(cache, new_kernel_pkg)
if cached_pkg is not None and cached_pkg.is_installed:
self.kernel_version = new_kernel_version
else:
remove_kernels = []
del cache
else:
remove_kernels = []
self.db.progress('SET', 2)
self.progress_region(2, 5)
try:
if remove_kernels:
install_misc.record_removed(remove_kernels, recursive=True)
except:
self.db.progress('STOP')
raise
self.db.progress('SET', 5)
self.db.progress('STOP')
def get_resume_partition(self):
biggest_size = 0
biggest_partition = None
try:
with open('/proc/swaps') as swaps:
for line in swaps:
words = line.split()
if words[1] != 'partition':
continue
if not os.path.exists(words[0]):
continue
if words[0].startswith('/dev/ramzswap'):
continue
size = int(words[2])
if size > biggest_size:
biggest_size = size
biggest_partition = words[0]
except Exception:
return None
return biggest_partition
def configure_hardware(self):
"""Reconfigure several hardware-specific packages.
These packages depend on the hardware of the system where the live
filesystem was built, and must be reconfigured to work properly on
the installed system.
"""
self.nested_progress_start()
install_misc.chroot_setup(self.target)
try:
dbfilter = hw_detect.HwDetect(None, self.db)
ret = dbfilter.run_command(auto_process=True)
if ret != 0:
raise install_misc.InstallStepError(
"HwDetect failed with code %d" % ret)
finally:
install_misc.chroot_cleanup(self.target)
self.nested_progress_end()
self.db.progress('INFO', 'ubiquity/install/hardware')
script = '/usr/lib/ubiquity/debian-installer-utils' \
'/register-module.post-base-installer'
if 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
script += '-oem'
misc.execute(script)
resume = self.get_resume_partition()
if resume is not None:
resume_uuid = None
try:
resume_uuid = subprocess.Popen(
['block-attr', '--uuid', resume],
stdout=subprocess.PIPE,
universal_newlines=True).communicate()[0].rstrip('\n')
except OSError:
pass
if resume_uuid:
resume = "UUID=%s" % resume_uuid
if os.path.exists(self.target_file('etc/initramfs-tools/conf.d')):
configdir = self.target_file('etc/initramfs-tools/conf.d')
elif os.path.exists(self.target_file('etc/mkinitramfs/conf.d')):
configdir = self.target_file('etc/mkinitramfs/conf.d')
else:
configdir = None
if configdir is not None:
resume_path = os.path.join(configdir, 'resume')
with open(resume_path, 'w') as configfile:
print("RESUME=%s" % resume, file=configfile)
osextras.unlink_force(self.target_file('etc/popularity-contest.conf'))
try:
participate = self.db.get('popularity-contest/participate')
install_misc.set_debconf(
self.target, 'popularity-contest/participate', participate,
self.db)
except debconf.DebconfError:
pass
osextras.unlink_force(self.target_file('etc/papersize'))
subprocess.call(['log-output', '-t', 'ubiquity', 'chroot', self.target,
'ucf', '--purge', '/etc/papersize'],
preexec_fn=install_misc.debconf_disconnect,
close_fds=True)
try:
install_misc.set_debconf(
self.target, 'libpaper/defaultpaper', '', self.db)
except debconf.DebconfError:
pass
osextras.unlink_force(
self.target_file('etc/ssl/certs/ssl-cert-snakeoil.pem'))
osextras.unlink_force(
self.target_file('etc/ssl/private/ssl-cert-snakeoil.key'))
install_misc.chroot_setup(self.target, x11=True)
#install_misc.chrex(
# self.target, 'dpkg-divert', '--package', 'ubiquity', '--rename',
# '--quiet', '--add', '/usr/sbin/update-initramfs')
#try:
# os.symlink(
# '/bin/true', self.target_file('usr/sbin/update-initramfs'))
#except OSError:
# pass
#packages = ['linux-image-' + self.kernel_version,
packages = ['popularity-contest',
'libpaper1',
'ssl-cert']
try:
for package in packages:
install_misc.reconfigure(self.target, package)
finally:
#osextras.unlink_force(
# self.target_file('usr/sbin/update-initramfs'))
#install_misc.chrex(
# self.target, 'dpkg-divert', '--package', 'ubiquity',
# '--rename', '--quiet', '--remove',
# '/usr/sbin/update-initramfs')
#install_misc.chrex(
# self.target, 'update-initramfs', '-c',
# '-k', self.kernel_version)
install_misc.chroot_cleanup(self.target, x11=True)
# Fix up kernel symlinks now that the initrd exists. Depending on
# the architecture, these may be in / or in /boot.
bootdir = self.target_file('boot')
if self.db.get('base-installer/kernel/linux/link_in_boot') == 'true':
linkdir = bootdir
linkprefix = ''
else:
linkdir = self.target
linkprefix = 'boot'
return
# Remove old symlinks. We'll set them up from scratch.
re_symlink = re.compile('vmlinu[xz]|initrd.img$')
for entry in os.listdir(linkdir):
if re_symlink.match(entry) is not None:
filename = os.path.join(linkdir, entry)
if os.path.islink(filename):
os.unlink(filename)
if linkdir != self.target:
# Remove symlinks in /target too, which may have been created on
# the live filesystem. This isn't necessary, but it may help
# avoid confusion.
for entry in os.listdir(self.target):
if re_symlink.match(entry) is not None:
filename = self.target_file(entry)
if os.path.islink(filename):
os.unlink(filename)
# Create symlinks. Prefer our current kernel version if possible,
# but if not (perhaps due to a customised live filesystem image),
# it's better to create some symlinks than none at all.
re_image = re.compile('(vmlinu[xz]|initrd.img)-')
for entry in os.listdir(bootdir):
match = re_image.match(entry)
if match is not None:
imagetype = match.group(1)
linksrc = os.path.join(linkprefix, entry)
linkdst = os.path.join(linkdir, imagetype)
if os.path.exists(linkdst):
if entry.endswith('-' + self.kernel_version):
os.unlink(linkdst)
else:
continue
os.symlink(linksrc, linkdst)
def configure_bootloader(self):
"""Configure and install the boot loader."""
if 'UBIQUITY_OEM_USER_CONFIG' in os.environ:
# the language might be different than initial install.