This repository has been archived by the owner on May 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 101
/
process.py
1445 lines (1201 loc) · 58.7 KB
/
process.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/env python
# -*- coding: utf-8 -*-
#
# process.py
#
# Copyright © 2013-2015 Antergos
#
# This file is part of Cnchi.
#
# Cnchi 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.
#
# Cnchi 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 Cnchi; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
""" Installation thread module. """
import crypt
import logging
import multiprocessing
import os
import queue
import shutil
import subprocess
import sys
import time
import urllib.request
import urllib.error
import traceback
from mako.template import Template
import desktop_environments as desktops
import parted3.fs_module as fs
import misc.misc as misc
import pacman.pac as pac
import info
import encfs
from download import download
from installation import auto_partition
from installation import chroot
from installation import mkinitcpio
from installation import firewall
from misc.misc import InstallError
try:
import xml.etree.cElementTree as eTree
except ImportError as err:
import xml.etree.ElementTree as eTree
try:
import pyalpm
except ImportError as err:
logging.error(err)
POSTINSTALL_SCRIPT = 'postinstall.sh'
DEST_DIR = "/install"
def chroot_run(cmd):
chroot.run(cmd, DEST_DIR)
def write_file(filecontents, filename):
""" writes a string of data to disk """
if not os.path.exists(os.path.dirname(filename)):
os.makedirs(os.path.dirname(filename))
with open(filename, "w") as fh:
fh.write(filecontents)
class InstallationProcess(multiprocessing.Process):
""" Installation process thread class """
def __init__(self, settings, callback_queue, mount_devices,
fs_devices, alternate_package_list="", ssd=None, blvm=False):
""" Initialize installation class """
multiprocessing.Process.__init__(self)
self.alternate_package_list = alternate_package_list
self.callback_queue = callback_queue
self.settings = settings
self.method = self.settings.get('partition_mode')
msg = _("Installing using the '{0}' method").format(self.method)
self.queue_event('info', msg)
# Check desktop selected to load packages needed
self.desktop = self.settings.get('desktop')
# This flag tells us if there is a lvm partition (from advanced install)
# If it's true we'll have to add the 'lvm2' hook to mkinitcpio
self.blvm = blvm
if ssd is not None:
self.ssd = ssd
else:
self.ssd = {}
self.mount_devices = mount_devices
# Set defaults
self.desktop_manager = 'lightdm'
self.network_manager = 'NetworkManager'
# Packages to be removed
self.conflicts = []
self.fs_devices = fs_devices
self.running = True
self.error = False
# Initialize some vars that are correctly initialized elsewhere
# (pylint complains if we don't do it here)
self.auto_device = ""
self.packages = []
self.pacman = None
self.vbox = False
def queue_fatal_event(self, txt):
""" Queues the fatal event and exits process """
self.error = True
self.running = False
self.queue_event('error', txt)
self.callback_queue.join()
# Is this really necessary?
sys.exit(0)
def queue_event(self, event_type, event_text=""):
if self.callback_queue is not None:
try:
self.callback_queue.put_nowait((event_type, event_text))
except queue.Full:
pass
else:
print("{0}: {1}".format(event_type, event_text))
def wait_for_empty_queue(self, timeout):
if self.callback_queue is not None:
tries = 0
if timeout < 1:
timeout = 1
while tries < timeout and not self.callback_queue.empty():
time.sleep(1)
tries += 1
def run(self):
""" Calls run_installation and takes care of exceptions """
try:
self.run_installation()
except subprocess.CalledProcessError as process_error:
exc_type, exc_value, exc_traceback = sys.exc_info()
trace = repr(traceback.format_exception(exc_type, exc_value, exc_traceback))
logging.error(_("Error running command %s"), process_error.cmd)
logging.error(_("Output: %s"), process_error.output)
logging.error(trace)
self.queue_fatal_event(process_error.output)
except (
InstallError, pyalpm.error, KeyboardInterrupt, TypeError, AttributeError, OSError,
IOError) as install_error:
exc_type, exc_value, exc_traceback = sys.exc_info()
trace = repr(traceback.format_exception(exc_type, exc_value, exc_traceback))
logging.error(install_error)
logging.error(trace)
self.queue_fatal_event(install_error)
@misc.raise_privileges
def run_installation(self):
""" Run installation """
'''
From this point, on a warning situation, Cnchi should try to continue, so we need to catch the exception here.
If we don't catch the exception here, it will be catched in run() and managed as a fatal error.
On the other hand, if we want to clarify the exception message we can catch it here
and then raise an InstallError exception.
'''
# Common vars
self.packages = []
if not os.path.exists(DEST_DIR):
with misc.raised_privileges():
os.makedirs(DEST_DIR)
else:
# If we're recovering from a failed/stoped install, there'll be
# some mounted directories. Try to unmount them first.
# We use unmount_all from auto_partition to do this.
auto_partition.unmount_all(DEST_DIR)
# Create and format partitions
if self.method == 'automatic':
self.auto_device = self.settings.get('auto_device')
logging.debug(_("Creating partitions and their filesystems in %s"), self.auto_device)
# If no key password is given a key file is generated and stored in /boot
# (see auto_partition.py)
auto = auto_partition.AutoPartition(dest_dir=DEST_DIR,
auto_device=self.auto_device,
use_luks=self.settings.get("use_luks"),
luks_password=self.settings.get("luks_root_password"),
use_lvm=self.settings.get("use_lvm"),
use_home=self.settings.get("use_home"),
callback_queue=self.callback_queue)
auto.run()
# Get mount_devices and fs_devices
# (mount_devices will be used when configuring GRUB in modify_grub_default)
# (fs_devices will be used when configuring the fstab file)
self.mount_devices = auto.get_mount_devices()
self.fs_devices = auto.get_fs_devices()
# Create the directory where we will mount our new root partition
if not os.path.exists(DEST_DIR):
os.mkdir(DEST_DIR)
if self.method == 'alongside' or self.method == 'advanced':
root_partition = self.mount_devices["/"]
# NOTE: Advanced method formats root by default in installation_advanced
# if root_partition in self.fs_devices:
# root_fs = self.fs_devices[root_partition]
# else:
# root_fs = "ext4"
if "/boot" in self.mount_devices:
boot_partition = self.mount_devices["/boot"]
else:
boot_partition = ""
if "swap" in self.mount_devices:
swap_partition = self.mount_devices["swap"]
else:
swap_partition = ""
# Mount root and boot partitions (only if it's needed)
# Not doing this in automatic mode as AutoPartition class mounts the root and boot devices itself.
txt = _("Mounting partition {0} into {1} directory").format(root_partition, DEST_DIR)
logging.debug(txt)
subprocess.check_call(['mount', root_partition, DEST_DIR])
# We also mount the boot partition if it's needed
boot_path = os.path.join(DEST_DIR, "boot")
if not os.path.exists(boot_path):
os.makedirs(boot_path)
if "/boot" in self.mount_devices:
txt = _("Mounting partition {0} into {1}/boot directory")
txt = txt.format(boot_partition, boot_path)
logging.debug(txt)
subprocess.check_call(['mount', boot_partition, boot_path])
# In advanced mode, mount all partitions (root and boot are already mounted)
if self.method == 'advanced':
for path in self.mount_devices:
# Ignore devices without a mount path (or they will be mounted at "DEST_DIR")
if path == "":
continue
mount_part = self.mount_devices[path]
if mount_part != root_partition and mount_part != boot_partition and mount_part != swap_partition:
mount_dir = os.path.join(DEST_DIR, path)
try:
if not os.path.exists(mount_dir):
os.makedirs(mount_dir)
txt = _("Mounting partition {0} into {1} directory")
txt = txt.format(mount_part, mount_dir)
logging.debug(txt)
subprocess.check_call(['mount', mount_part, mount_dir])
except subprocess.CalledProcessError as process_error:
# We will continue as root and boot are already mounted
logging.warning(_("Can't mount %s in %s"), mount_part, mount_dir)
logging.warning(_("Command %s has failed."), process_error.cmd)
logging.warning(_("Output : %s"), process_error.output)
elif mount_part == swap_partition:
try:
logging.debug(_("Activating swap in %s"), mount_part)
subprocess.check_call(['swapon', swap_partition])
except subprocess.CalledProcessError as process_error:
# We can continue even if no swap is on
logging.warning(_("Can't activate swap in %s"), mount_part)
logging.warning(_("Command %s has failed."), process_error.cmd)
logging.warning(_("Output : %s"), process_error.output)
# Nasty workaround:
# If pacman was stoped and /var is in another partition than root
# (so as to be able to resume install), database lock file will still be in place.
# We must delete it or this new installation will fail
db_lock = os.path.join(DEST_DIR, "var/lib/pacman/db.lck")
if os.path.exists(db_lock):
with misc.raised_privileges():
os.remove(db_lock)
logging.debug(_("%s deleted"), db_lock)
# Create some needed folders
folders = [
os.path.join(DEST_DIR, 'var/lib/pacman'),
os.path.join(DEST_DIR, 'etc/pacman.d/gnupg'),
os.path.join(DEST_DIR, 'var/log')]
for folder in folders:
if not os.path.exists(folder):
os.makedirs(folder)
# If kernel images exists in /boot they are most likely from a failed install attempt and need
# to be removed otherwise pyalpm will raise a fatal exception later on.
kernel_imgs = (
"/install/boot/vmlinuz-linux",
"/install/boot/vmlinuz-linux-lts",
"/install/boot/initramfs-linux.img",
"/install/boot/initramfs-linux-fallback.img",
"/install/boot/initramfs-linux-lts.img",
"/install/boot/initramfs-linux-lts-fallback.img")
for img in kernel_imgs:
if os.path.exists(img):
os.remove(img)
logging.debug(_("Prepare pacman..."))
self.prepare_pacman()
logging.debug(_("Pacman ready"))
logging.debug(_("Selecting packages..."))
self.select_packages()
logging.debug(_("Packages selected"))
# Fix bug #263 (v86d moved from [extra] to AUR)
if "v86d" in self.packages:
self.packages.remove("v86d")
logging.debug(_("Removed 'v86d' package from list"))
logging.debug(_("Downloading packages..."))
self.download_packages()
logging.debug(_("Installing packages..."))
self.install_packages()
logging.debug(_("Configuring system..."))
self.configure_system()
all_ok = True
self.running = False
if all_ok is False:
self.error = True
return False
else:
# Installation finished successfully
self.queue_event('finished', _("Installation finished"))
self.error = False
return True
@staticmethod
def copy_log():
# Copy Cnchi log to new installation
datetime = "{0}-{1}".format(time.strftime("%Y%m%d"), time.strftime("%H%M%S"))
dst = os.path.join(DEST_DIR, "var/log/cnchi-{0}.log".format(datetime))
pidst = os.path.join(DEST_DIR, "var/log/postinstall-{0}.log".format(datetime))
try:
shutil.copy("/tmp/cnchi.log", dst)
shutil.copy("/tmp/postinstall.log", pidst)
except FileNotFoundError:
logging.warning(_("Can't copy Cnchi log to %s"), dst)
except FileExistsError:
pass
def download_packages(self):
""" Downloads necessary packages using urllib or Aria2 """
pacman_conf_file = "/tmp/pacman.conf"
pacman_cache_dir = os.path.join(DEST_DIR, "var/cache/pacman/pkg")
if self.settings.get("cache") != '':
cache_dir = self.settings.get("cache")
else:
cache_dir = '/var/cache/pacman/pkg'
if self.settings.get("use_aria2"):
use_aria2 = True
else:
use_aria2 = False
download.DownloadPackages(
self.packages, use_aria2, pacman_conf_file, pacman_cache_dir, cache_dir, self.callback_queue, self.settings)
def create_pacman_conf_file(self):
""" Creates a temporary pacman.conf """
myarch = os.uname()[-1]
msg = _("Creating a temporary pacman.conf for {0} architecture").format(myarch)
logging.debug(msg)
# Template functionality. Needs Mako (see http://www.makotemplates.org/)
template_file_name = os.path.join(self.settings.get('data'), 'pacman.tmpl')
file_template = Template(filename=template_file_name)
file_rendered = file_template.render(destDir=DEST_DIR, arch=myarch, desktop=self.desktop)
write_file(file_rendered, os.path.join("/tmp", "pacman.conf"))
def prepare_pacman(self):
""" Configures pacman and syncs db on destination system """
self.create_pacman_conf_file()
dirs = ["var/cache/pacman/pkg", "var/lib/pacman"]
for pacman_dir in dirs:
mydir = os.path.join(DEST_DIR, pacman_dir)
if not os.path.exists(mydir):
os.makedirs(mydir)
self.prepare_pacman_keyring()
# Init pyalpm
try:
self.pacman = pac.Pac("/tmp/pacman.conf", self.callback_queue)
except Exception:
self.pacman = None
raise InstallError(_("Can't initialize pyalpm."))
# If we failed to download any packages earlier, try refreshing our mirrorlist
# before ALPM attempts to download them.
if self.settings.get('failed_download'):
from rank_mirrors import AutoRankmirrorsThread
retry = AutoRankmirrorsThread()
retry.start()
retry.join()
# Refresh pacman databases
result = self.pacman.refresh()
if not result:
txt = _("Can't refresh pacman databases.")
logging.error(txt)
raise InstallError(txt)
@staticmethod
def prepare_pacman_keyring():
""" Add gnupg pacman files to installed system """
# Be sure that haveged is running (liveCD)
# haveged is a daemon that generates system entropy; this speeds up
# critical operations in cryptographic programs such as gnupg
# (including the generation of new keyrings)
try:
cmd = ["systemctl", "start", "haveged"]
subprocess.check_call(cmd)
except subprocess.CalledProcessError as process_error:
logging.warning(_("Can't start haveged service"))
logging.warning(_("Command %s failed"), process_error.cmd)
logging.warning(_("Output: %s"), process_error.output)
# Delete old gnupg files
dest_path = os.path.join(DEST_DIR, "etc/pacman.d/gnupg")
try:
cmd = ["rm", "-rf", dest_path]
subprocess.check_call(cmd)
os.mkdir(dest_path)
except subprocess.CalledProcessError as process_error:
logging.warning(_("Error deleting old gnupg files"))
logging.warning(_("Command %s failed"), process_error.cmd)
logging.warning(_("Output: %s"), process_error.output)
# Tell pacman-key to regenerate gnupg files
try:
cmd = ["pacman-key", "--init", "--gpgdir", dest_path]
subprocess.check_call(cmd)
cmd = ["pacman-key", "--populate", "--gpgdir", dest_path, "archlinux", "antergos"]
subprocess.check_call(cmd)
except subprocess.CalledProcessError as process_error:
logging.warning(_("Error regenerating gnupg files with pacman-key"))
logging.warning(_("Command %s failed"), process_error.cmd)
logging.warning(_("Output: %s"), process_error.output)
def select_packages(self):
""" Get package list from the Internet """
self.packages = []
if len(self.alternate_package_list) > 0:
packages_xml = self.alternate_package_list
else:
# The list of packages is retrieved from an online XML to let us
# control the pkgname in case of any modification
self.queue_event('info', _("Getting package list..."))
try:
url = 'http://install.antergos.com/packages-{0}.xml'.format(info.CNCHI_VERSION[:3])
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
packages_xml = urllib.request.urlopen(req, timeout=45)
except urllib.error.URLError as url_error:
# If the installer can't retrieve the remote file, try to install with a local
# copy, that may not be updated
# logging.warning(url_error) # This bails out of the entire installation
logging.debug(_("Can't retrieve remote package list, using a local file instead."))
data_dir = self.settings.get("data")
packages_xml = os.path.join(data_dir, 'packages.xml')
xml_tree = eTree.parse(packages_xml)
xml_root = xml_tree.getroot()
lib = desktops.LIBS
for editions in xml_root.iter('editions'):
for edition in editions.iter('edition'):
# Add common packages to all desktops (including base)
if edition.attrib.get("name").lower() == "common":
for pkg in edition.iter('pkgname'):
self.packages.append(pkg.text)
# Add common graphical packages
if self.desktop != "base":
if edition.attrib.get("name").lower() == "graphic":
for pkg in edition.iter('pkgname'):
# If package is Desktop Manager, save the name to activate the correct service later
if pkg.attrib.get('dm'):
self.desktop_manager = pkg.attrib.get('name')
plib = pkg.attrib.get('lib')
if plib is None or (plib is not None and self.desktop in lib[plib]):
self.packages.append(pkg.text)
# Add specific desktop packages
if edition.attrib.get("name").lower() == self.desktop:
logging.debug(_("Adding '%s' desktop packages"), self.desktop)
for pkg in edition.iter('pkgname'):
# If package is Network Manager, save the name to activate the correct service later
if pkg.attrib.get('nm'):
self.network_manager = pkg.attrib.get('name')
if pkg.attrib.get('conflicts'):
self.conflicts.append(pkg.attrib.get('conflicts'))
self.packages.append(pkg.text)
# Set KDE language pack
if self.desktop == 'kde4' or self.desktop == 'plasma5':
pkg = ""
base_name = 'kde-l10n-'
lang_name = self.settings.get("language_name").lower()
if lang_name == "english":
# There're some English variants available but not all of them.
lang_packs = ['en_gb']
locale = self.settings.get('locale').split('.')[0]
if locale in lang_packs:
pkg = base_name + locale
else:
# All the other language packs use their language code
lang_code = self.settings.get('language_code')
pkg = base_name + lang_code
if len(pkg) > 0:
logging.debug(_("Selected kde language pack: %s"), pkg)
self.packages.append(pkg)
# Add ntp package if user selected it in timezone screen
if self.settings.get('use_ntp'):
for child in xml_root.iter('ntp'):
for pkg in child.iter('pkgname'):
self.packages.append(pkg.text)
# Get packages needed for detected hardware
try:
import hardware.hardware as hardware
hardware_install = hardware.HardwareInstall()
driver_names = hardware_install.get_found_driver_names()
if len(driver_names) > 0:
logging.debug(_("Hardware module detected this drivers: %s"), driver_names)
hardware_pkgs = hardware_install.get_packages()
if len(hardware_pkgs) > 0:
txt = " ".join(hardware_pkgs)
logging.debug(_("Hardware module added these packages : %s"), txt)
if 'virtualbox-guest-utils' in hardware_pkgs:
self.vbox = True
# By default, hardware module adds modesetting driver
# but in a 'base' install we don't want it
if self.desktop == "base" and "xf86-video-modesetting" in hardware_pkgs:
hardware_pkgs.remove("xf86-video-modesetting")
self.packages.extend(hardware_pkgs)
except ImportError:
logging.warning(_("Can't import hardware module."))
except Exception as general_error:
logging.warning(_("Unknown error in hardware module. Output: %s"), general_error)
# Add filesystem packages
logging.debug(_("Adding filesystem packages"))
cmd = ["blkid", "-c", "/dev/null", "-o", "value", "-s", "TYPE"]
fs_types = subprocess.check_output(cmd).decode()
fs_lib = (
'btrfs', 'ext', 'ext2', 'ext3', 'ext4', 'fat', 'fat16', 'fat32', 'vfat',
'f2fs', 'jfs', 'nfs', 'nilfs2', 'ntfs', 'reiserfs', 'xfs')
for fs_index in self.fs_devices:
fs_types = fs_types + self.fs_devices[fs_index]
for fsys in fs_lib:
if fsys in fs_types:
if fsys == 'ext2' or fsys == 'ext3' or fsys == 'ext4':
fsys = 'ext'
if fsys == 'fat16' or fsys == 'fat32':
fsys = 'vfat'
for child in xml_root.iter(fsys):
for pkg in child.iter('pkgname'):
self.packages.append(pkg.text)
# Check for user desired features and add them to our installation
logging.debug(_("Check for user desired features and add them to our installation"))
self.add_features_packages(xml_root)
logging.debug(_("All features needed packages have been added"))
# Add chinese fonts
lang_code = self.settings.get("language_code")
if lang_code == "zh_TW" or lang_code == "zh_CN":
logging.debug(_("Selecting chinese fonts."))
for child in xml_root.iter('chinese'):
for pkg in child.iter('pkgname'):
self.packages.append(pkg.text)
# Add bootloader packages if needed
if self.settings.get('bootloader_install'):
boot_loader = self.settings.get('bootloader')
# Search boot_loader in packages.xml
bootloader_found = False
for child in xml_root.iter('bootloader'):
if child.attrib.get('name') == boot_loader:
txt = _("Adding '%s' bootloader packages")
logging.debug(txt, boot_loader)
bootloader_found = True
for pkg in child.iter('pkgname'):
self.packages.append(pkg.text)
if not bootloader_found:
txt = _("Couldn't find %s bootloader packages!")
logging.warning(txt, boot_loader)
# Check the list of packages for empty strings and remove any that we find.
self.packages = [pkg for pkg in self.packages if pkg != '']
logging.debug(self.packages)
def add_features_packages(self, xml_root):
""" Selects packages based on user selected features """
desktop = self.settings.get("desktop")
lib = desktops.LIBS
# Add necessary packages for user desired features to our install list
for xml_features in xml_root.iter('features'):
for xml_feature in xml_features.iter('feature'):
feature = xml_feature.attrib.get("name")
if self.settings.get("feature_" + feature):
logging.debug(_("Adding packages for '%s' feature."), feature)
for pkg in xml_feature.iter('pkgname'):
# If it's a specific gtk or qt package we have to check it
# against our chosen desktop.
plib = pkg.attrib.get('lib')
qt5 = pkg.attrib.get('qt5')
if plib is None or (plib is not None and desktop in lib[plib]):
if self.desktop is "plasma5" and pkg.text in ["bluedevil"]:
continue
elif self.desktop is not "plasma5" and qt5 == "True":
continue
else:
logging.debug(_("Selecting package %s for feature %s"), pkg.text, feature)
self.packages.append(pkg.text)
if pkg.attrib.get('conflicts'):
self.conflicts.append(pkg.attrib.get('conflicts'))
# Add libreoffice language package
if self.settings.get('feature_office'):
logging.debug(_("Add libreoffice language package"))
pkg = ""
lang_name = self.settings.get("language_name").lower()
if lang_name == "english":
# There're some English variants available but not all of them.
lang_packs = ['en-GB', 'en-ZA']
locale = self.settings.get('locale').split('.')[0]
locale = locale.replace('_', '-')
if locale in lang_packs:
pkg = "libreoffice-fresh-{0}".format(locale)
else:
# All the other language packs use their language code
lang_code = self.settings.get('language_code')
lang_code = lang_code.replace('_', '-')
pkg = "libreoffice-fresh-{0}".format(lang_code)
# This shouldn't be necessary but I want to be sure
if pkg != "":
self.packages.append(pkg)
def install_packages(self):
""" Start pacman installation of packages """
logging.debug(_("Installing packages..."))
pacman_options = {}
result = self.pacman.install(
pkgs=self.packages,
conflicts=self.conflicts,
options=pacman_options)
if not result:
txt = _("Can't install necessary packages. Cnchi can't continue.")
raise InstallError(txt)
# All downloading and installing has been done, so we hide progress bar
self.queue_event('progress_bar', 'hide')
def is_running(self):
""" Checks if thread is running """
return self.running
def is_ok(self):
""" Checks if an error has been issued """
return not self.error
@staticmethod
def copy_network_config():
""" Copies Network Manager configuration """
source_nm = "/etc/NetworkManager/system-connections/"
target_nm = os.path.join(DEST_DIR, "etc/NetworkManager/system-connections")
# Sanity checks. We don't want to do anything if a network
# configuration already exists on the target
if os.path.exists(source_nm) and os.path.exists(target_nm):
for network in os.listdir(source_nm):
# Skip LTSP live
if network == "LTSP":
continue
source_network = os.path.join(source_nm, network)
target_network = os.path.join(target_nm, network)
if os.path.exists(target_network):
continue
try:
shutil.copy(source_network, target_network)
except FileNotFoundError:
logging.warning(_("Can't copy network configuration files"))
except FileExistsError:
pass
def auto_fstab(self):
""" Create /etc/fstab file """
all_lines = ["# /etc/fstab: static file system information.",
"#",
"# Use 'blkid' to print the universally unique identifier for a",
"# device; this may be used with UUID= as a more robust way to name devices",
"# that works even if disks are added and removed. See fstab(5).",
"#",
"# <file system> <mount point> <type> <options> <dump> <pass>",
"#"]
use_luks = self.settings.get("use_luks")
use_lvm = self.settings.get("use_lvm")
for mount_point in self.mount_devices:
partition_path = self.mount_devices[mount_point]
part_info = fs.get_info(partition_path)
uuid = part_info['UUID']
if partition_path in self.fs_devices:
myfmt = self.fs_devices[partition_path]
else:
# It hasn't any filesystem defined, skip it.
continue
# Take care of swap partitions
if "swap" in myfmt:
# If using a TRIM supported SSD, discard is a valid mount option for swap
if partition_path in self.ssd:
opts = "defaults,discard"
else:
opts = "defaults"
txt = "UUID={0} swap swap {1} 0 0".format(uuid, opts)
all_lines.append(txt)
logging.debug(_("Added to fstab : %s"), txt)
continue
crypttab_path = os.path.join(DEST_DIR, 'etc/crypttab')
# Fix for home + luks, no lvm (from Automatic Install)
if "/home" in mount_point and self.method == "automatic" and use_luks and not use_lvm:
# Modify the crypttab file
luks_root_password = self.settings.get("luks_root_password")
if luks_root_password and len(luks_root_password) > 0:
# Use password and not a keyfile
home_keyfile = "none"
else:
# Use a keyfile
home_keyfile = "/etc/luks-keys/home"
os.chmod(crypttab_path, 0o666)
with open(crypttab_path, 'a') as crypttab_file:
line = "cryptAntergosHome /dev/disk/by-uuid/{0} {1} luks\n".format(uuid, home_keyfile)
crypttab_file.write(line)
logging.debug(_("Added to crypttab : %s"), line)
os.chmod(crypttab_path, 0o600)
# Add line to fstab
txt = "/dev/mapper/cryptAntergosHome {0} {1} defaults 0 0".format(mount_point, myfmt)
all_lines.append(txt)
logging.debug(_("Added to fstab : %s"), txt)
continue
# Add all LUKS partitions from Advanced Install (except root).
if self.method == "advanced" and mount_point is not "/" and use_luks and "/dev/mapper" in partition_path:
os.chmod(crypttab_path, 0o666)
vol_name = partition_path[len("/dev/mapper/"):]
with open(crypttab_path, 'a') as crypttab_file:
line = "{0} /dev/disk/by-uuid/{1} none luks\n".format(vol_name, uuid)
crypttab_file.write(line)
logging.debug(_("Added to crypttab : %s"), line)
os.chmod(crypttab_path, 0o600)
txt = "{0} {1} {2} defaults 0 0".format(partition_path, mount_point, myfmt)
all_lines.append(txt)
logging.debug(_("Added to fstab : %s"), txt)
continue
# fstab uses vfat to mount fat16 and fat32 partitions
if "fat" in myfmt:
myfmt = 'vfat'
if "btrfs" in myfmt:
self.settings.set('btrfs', True)
# Avoid adding a partition to fstab when it has no mount point (swap has been checked above)
if mount_point == "":
continue
# Create mount point on destination system if it yet doesn't exist
full_path = os.path.join(DEST_DIR, mount_point)
if not os.path.exists(full_path):
os.makedirs(full_path)
# Is ssd ?
is_ssd = False
for ssd_device in self.ssd:
if ssd_device in partition_path:
is_ssd = True
# Add mount options parameters
if not is_ssd:
if "btrfs" in myfmt:
opts = 'defaults,rw,relatime,space_cache,autodefrag,inode_cache'
elif "f2fs" in myfmt:
opts = 'defaults,rw,noatime'
elif "ext3" in myfmt or "ext4" in myfmt:
opts = 'defaults,rw,relatime,data=ordered'
else:
opts = "defaults,rw,relatime"
else:
# As of linux kernel version 3.7, the following
# filesystems support TRIM: ext4, btrfs, JFS, and XFS.
if myfmt == 'ext4' or myfmt == 'jfs' or myfmt == 'xfs':
opts = 'defaults,rw,noatime,discard'
elif myfmt == 'btrfs':
opts = 'defaults,rw,noatime,compress=lzo,ssd,discard,space_cache,autodefrag,inode_cache'
else:
opts = 'defaults,rw,noatime'
no_check = ["btrfs", "f2fs"]
if mount_point == "/" and myfmt not in no_check:
chk = '1'
else:
chk = '0'
if mount_point == "/":
self.settings.set('ruuid', uuid)
txt = "UUID={0} {1} {2} {3} 0 {4}".format(uuid, mount_point, myfmt, opts, chk)
all_lines.append(txt)
logging.debug(_("Added to fstab : %s"), txt)
# Create tmpfs line in fstab
tmpfs = "tmpfs /tmp tmpfs defaults,noatime,mode=1777 0 0"
all_lines.append(tmpfs)
logging.debug(_("Added to fstab : %s"), tmpfs)
full_text = '\n'.join(all_lines) + '\n'
fstab_path = os.path.join(DEST_DIR, 'etc/fstab')
with open(fstab_path, 'w') as fstab_file:
fstab_file.write(full_text)
logging.debug(_("fstab written."))
def set_scheduler(self):
rule_src = os.path.join(self.settings.get('cnchi'), 'scripts/60-schedulers.rules')
rule_dst = os.path.join(DEST_DIR, "etc/udev/rules.d/60-schedulers.rules")
try:
shutil.copy2(rule_src, rule_dst)
os.chmod(rule_dst, 0o755)
except FileNotFoundError:
logging.debug(_("Could not copy udev rule for SSDs"))
except FileExistsError:
pass
@staticmethod
def enable_services(services):
""" Enables all services that are in the list 'services' """
for name in services:
path = os.path.join(DEST_DIR, "usr/lib/systemd/system/{0}.service".format(name))
if os.path.exists(path):
chroot_run(['systemctl', '-f', 'enable', name])
logging.debug(_("Enabled %s service."), name)
else:
logging.warning(_("Can't find service %s"), name)
@staticmethod
def change_user_password(user, new_password):
""" Changes the user's password """
try:
shadow_password = crypt.crypt(new_password, "$6${0}$".format(user))
except:
logging.warning(_("Error creating password hash for user %s"), user)
return False
try:
chroot_run(['usermod', '-p', shadow_password, user])
except:
logging.warning(_("Error changing password for user %s"), user)
return False
return True
@staticmethod
def auto_timesetting():
""" Set hardware clock """
subprocess.check_call(["hwclock", "--systohc", "--utc"])
shutil.copy2("/etc/adjtime", os.path.join(DEST_DIR, "etc/"))
@staticmethod
def update_pacman_conf():
""" Add Antergos repo """
path = os.path.join(DEST_DIR, "etc/pacman.conf")
if os.path.exists(path):
with open(path, "a") as pacman_conf:
pacman_conf.write("\n\n")
pacman_conf.write("[antergos]\n")
pacman_conf.write("SigLevel = PackageRequired\n")
pacman_conf.write("Include = /etc/pacman.d/antergos-mirrorlist\n")
else:
logging.warning(_("Can't find pacman configuration file"))
@staticmethod
def uncomment_locale_gen(locale):
""" Uncomment selected locale in /etc/locale.gen """
path = os.path.join(DEST_DIR, "etc/locale.gen")
if os.path.exists(path):
with open(path) as gen:
text = gen.readlines()
with open(path, "w") as gen:
for line in text:
if locale in line and line[0] == "#":
# remove trailing '#'
line = line[1:]
gen.write(line)
else:
logging.warning(_("Can't find locale.gen file"))
@staticmethod
def check_output(command):
""" Helper function to run a command """
return subprocess.check_output(command.split()).decode().strip("\n")
def copy_cached_packages(self, cache_dir):
""" Copy all packages from specified directory to install's target """
# Check in case user has given a wrong folder
if not os.path.exists(cache_dir):
return
self.queue_event('info', _('Copying xz files from cache...'))
dest_dir = os.path.join(DEST_DIR, "var/cache/pacman/pkg")
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
self.copy_files_progress(cache_dir, dest_dir)
def copy_files_progress(self, src, dst):
""" Copy files updating the slides' progress bar """
percent = 0.0
items = os.listdir(src)
if len(items) > 0:
step = 1.0 / len(items)
for item in items:
self.queue_event('percent', percent)