-
Notifications
You must be signed in to change notification settings - Fork 16
/
ister.py
executable file
·1803 lines (1518 loc) · 64.9 KB
/
ister.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 python3
# -*- coding: utf-8 -*-
# vim: ts=4 sw=4 tw=80 et ai si
"""Linux installation template system"""
#
# This file is part of ister.
#
# Copyright (C) 2014 Intel Corporation
#
# ister 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; version 3 of the License, or (at your
# option) any later version.
#
# You should have received a copy of the GNU General Public License
# along with this program in a file named COPYING; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301 USA
#
# We aren't splitting ister up just yet so ignore too many lines error
# pylint: disable=too-many-lines
# As much as it pains us, global for the LOG handler is reasonable here
# pylint: disable=global-statement
# If we see an exception it is always fatal so the broad exception
# warning isn't helpful.
# pylint: disable=broad-except
# We aren't using classes for anything other than with handling so
# a warning about too few methods being implemented isn't useful.
# pylint: disable=too-few-public-methods
# Too many branches is probably something we'd have hoped to avoid but this
# logic for partition creation was born to be ugly, good spot for cleanup
# though for the adventurous sort
# pylint: disable=too-many-branches
# We aren't worried too much about performance of ister itself here, so using
# .format() for the logging functions (which always formats the string) is ok.
# pylint: disable=logging-format-interpolation
import argparse
import ctypes
import json
import logging
import os
import pwd
import re
import shlex
import shutil
import socket
import stat
import subprocess
import sys
import tempfile
import time
import base64
import binascii
import codecs
import errno
import fcntl
import queue
import select
import threading
import traceback
import urllib.request as request
from urllib.error import URLError, HTTPError
from urllib.parse import urlparse
from contextlib import closing
import netifaces
import pycryptsetup
LOG = None
def extract_full_lines(text):
"""Extract full lines from string 'text'. Return a tuple containing 2 elements
- list of full lines and a string containing the partial line.
"""
full, partial = [], ""
for line_match in re.finditer("(.*)\n|(.+$)", text):
if line_match.group(2):
partial = line_match.group(2)
break
full.append(line_match.group(1))
return (full, partial)
def stream_fetcher(info, streamid):
"""This function runs in a separate thread and fetches data from 'stream',
which is a file associated with the stdout or stderr pipes of a process.
"""
partial = ""
stream = info["streams"][streamid]
try:
# Set non-blocking mode for the stream. We are doing this because we
# want to regularly supply the consumers with the output data and never
# block for too long.
fno = stream.fileno()
fcntl.fcntl(fno, fcntl.F_SETFL,
fcntl.fcntl(fno, fcntl.F_GETFL) | os.O_NONBLOCK)
decoder = codecs.getincrementaldecoder('utf8')(errors="surrogateescape")
while not info["die_now"]:
# Wait for someting to appear in the stream. Wait for longest 1
# second in order to ensure we exit on "die_now".
if not select.select([stream], [], [], 1)[0]:
continue
data = None
try:
data = stream.read(4096)
except OSError as err:
if err.errno == errno.EAGAIN:
continue
raise
if not data:
break
data = decoder.decode(data)
if not data:
continue
data, partial = extract_full_lines(partial + data)
for line in data:
info["queue"].put((streamid, line))
except BaseException as err:
LOG.error(err)
if partial:
info["queue"].put((streamid, partial))
# "End of data stream" marker.
info["queue"].put((streamid, None))
def wait_for_process(proc, log_output, show_output):
"""Wait for process 'proc' to finish."""
info = {"streams" : (proc.stdout, proc.stderr),
"die_now" : False,
"queue" : queue.Queue()}
# Start the stream fetcher threads. They will read the output of the process
# and put to the queue.
threads = []
for streamid in (0, 1):
if info["streams"][streamid]:
threads.append(threading.Thread(target=stream_fetcher,
name='cmd-stream-fetcher',
args=(info, streamid)))
threads[-1].start()
output = ([], [])
try:
while True:
streamid, line = info["queue"].get()
if line is not None:
output[streamid].append(line)
if show_output:
LOG.info(line)
elif log_output:
LOG.debug(line)
else:
# 'None' means "no more output".
threads[streamid].join()
threads[streamid] = None
if all(thread is None for thread in threads):
break
finally:
# Make sure threads always exit.
info["die_now"] = True
# The process closed its stdout and stderr and we expect it to terminate
# soon. This should happen right away in a normal situation.
exitcode = proc.wait(timeout=60)
return output[0], output[1], exitcode
def run_command(cmd, raise_exception=True, log_output=True, environ=None,
show_output=False, shell=False):
"""
Execute given command in a subprocess and return a (stdout, stderr,
exitcode) tuple, where 'stdout' is the standard output of the command,
'stderr' is the standard error, and 'exitcode' is the exit status.
This function will raise an Exception if the command fails unless
raise_exception is False.
"""
result = ([], [], -1)
try:
LOG.debug("Running command {0}".format(cmd))
sys.stdout.flush()
if shell:
full_cmd = cmd
else:
full_cmd = shlex.split(cmd)
proc = subprocess.Popen(full_cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, env=environ,
shell=shell)
result = wait_for_process(proc, log_output, show_output)
_, stderr, exitcode = result
if exitcode and raise_exception:
if stderr:
LOG.debug("\n".join(stderr))
raise Exception("{0}".format(cmd))
except Exception as exep:
if raise_exception:
raise Exception("Error: {0} failed:\n{1}".format(cmd, exep))
return result
def validate_network(url):
"""Validate there is network connection to swupd
"""
LOG.info("Verifying network connection")
url = url if url else "https://update.clearlinux.org"
try:
_ = request.urlopen(url, timeout=3)
except HTTPError as exep:
if hasattr(exep, 'code'):
LOG.info("SWUPD server error: {0}".format(exep.code))
raise exep
except URLError as exep:
if hasattr(exep, 'reason'):
LOG.info("Network error: Cannot reach swupd server: {0}"
.format(exep.reason))
raise exep
def create_virtual_disk(template):
"""Create virtual disk file for install target
"""
LOG.info("Creating virtual disk")
image_size = 0
# number of kilobytes in each of the following
match = {"M": 1024, "G": 1024 ** 2, "T": 1024 ** 3}
for part in template["PartitionLayout"]:
if part["size"] != "rest":
image_size += int(part["size"][:-1]) * match[part["size"][-1]]
# Add extra buffer, note disk sizes should be multiples of 4kb.
# Increase buffer by 1MB to give parted wiggle room due to dd using 1K
# sector sizes and parted is getting partition sizes specified in MiB.
image_size += 1024
command = "dd if=/dev/zero of={0} bs=1024 count=0 seek={1}".\
format(template["PartitionLayout"][0]["disk"], image_size)
run_command(command)
def create_partitions(template, sleep_time=1):
"""Create partitions according to template configuration
"""
LOG.info("Creating partitions")
match = {"M": 1, "G": 1024, "T": 1024 * 1024}
parted = "parted -sa"
alignment = "optimal"
units = "unit MiB"
disks = set()
cdisk = ""
for disk in template["PartitionLayout"]:
disks.add(disk["disk"])
# Setup GPT tables on disks
for disk in sorted(disks):
LOG.debug("Creating GPT label in {0}".format(disk))
if template.get("DestinationType") == "physical":
command = "{0} {1} /dev/{2} {3} mklabel gpt".\
format(parted, alignment, disk, units)
else:
command = "{0} {1} {2} {3} mklabel gpt".\
format(parted, alignment, disk, units)
run_command(command)
time.sleep(sleep_time)
# Create partitions
for part in sorted(template["PartitionLayout"], key=lambda v: v["disk"] +
str(v["partition"])):
if part["disk"] != cdisk:
start = 0
if part["size"] == "rest":
end = "-1M"
else:
mult = match[part["size"][-1]]
end = int(part["size"][:-1]) * mult + start
if part["type"] == "EFI":
ptype = "fat32"
elif part["type"] == "swap":
ptype = "linux-swap"
else:
ptype = "ext2"
if start == 0:
# Using 0% on the first partition to get the first 1MB
# border that is correctly aligned
start = "0%"
LOG.debug("Creating partition {0} in {1}".format(ptype, part["disk"]))
if template.get("DestinationType") == "physical":
command = "{0} {1} -- /dev/{2} {3} mkpart primary {4} {5} {6}"\
.format(parted, alignment, part["disk"], units, ptype,
start, end)
else:
command = "{0} {1} -- {2} {3} mkpart primary {4} {5} {6}"\
.format(parted, alignment, part["disk"], units, ptype,
start, end)
run_command(command)
time.sleep(sleep_time)
if part["type"] == "EFI":
if template.get("DestinationType") == "physical":
command = "parted -s /dev/{0} set {1} boot on"\
.format(part["disk"], part["partition"])
else:
command = "parted -s {0} set {1} boot on"\
.format(part["disk"], part["partition"])
run_command(command)
time.sleep(sleep_time)
start = end
cdisk = part["disk"]
def map_loop_device(template, sleep_time=1):
"""Setup a loop device for the image file
This function will raise an Exception if the command fails.
"""
LOG.info("Mapping loop device")
disk_image = template["PartitionLayout"][0]["disk"]
command = "losetup --partscan --find --show {0}".format(disk_image)
try:
dev = subprocess.check_output(command.split(" ")).decode("utf-8")\
.splitlines()
except Exception:
raise Exception("losetup command failed: {0}: {1}"
.format(command, sys.exc_info()))
if len(dev) != 1:
raise Exception("losetup failed to create loop device")
time.sleep(sleep_time)
run_command("partprobe {0}".format(dev[0]))
time.sleep(sleep_time)
template["dev"] = dev[0]
def get_device_name(template, disk):
"""Return /dev/{loopXp, sdX} type device name
"""
# handle loop devices, disk can be None
if template.get("dev"):
return ("{}p".format(template["dev"]), "p")
# if not a loop device, search for partition format in /dev
devices = os.listdir("/dev")
devgen = (name for name in devices if disk in name)
for name in devgen:
part = name.replace(disk, "")
if part:
prefix = "p" if part.startswith("p") else ""
return ("/dev/{}{}".format(disk, prefix), prefix)
# if we got this far, no partitions were found and nothing would be
# returned, resulting in a failed install.
raise Exception("No partitions found on /dev/{}".format(disk))
def create_filesystems(template):
"""Create filesystems according to template configuration
"""
# Filesystem-specific format tool options.
fs_util = {"ext2": {"cmd" : "mkfs.ext2 -F", "label" : "-L"},
"ext3": {"cmd" : "mkfs.ext3 -F", "label" : "-L"},
"ext4": {"cmd" : "mkfs.ext4 -F", "label" : "-L"},
"btrfs": {"cmd" : "mkfs.btrfs -f", "label" : "-L"},
"vfat": {"cmd" : "mkfs.vfat", "label" : "-n"},
"swap": {"cmd" : "mkswap", "label" : "-L"},
"xfs": {"cmd" : "mkfs.xfs -f", "label" : "-L"}}
LOG.info("Creating file systems")
for fst in template["FilesystemTypes"]:
(dev, prefix) = get_device_name(template, fst["disk"])
fsu = fs_util[fst["type"]]
LOG.debug("Creating file system {0} in {1}{2}"
.format(fst["type"], dev, fst["partition"]))
opts = fst.get("options", "")
if opts:
opts = " " + opts
if "label" in fst:
opts += " {0} {1}".format(fsu["label"], fst["label"])
command = "{0}{1} {2}{3}".format(fsu["cmd"], opts, dev,
fst["partition"])
if fst["type"] == "swap":
if prefix:
base_dev = dev[:-1]
else:
base_dev = dev
run_command("sgdisk {0} --typecode={1}:\
0657fd6d-a4ab-43c4-84e5-0933c84b4f4f"
.format(base_dev, fst["partition"]))
if "disable_format" not in fst:
if "encryption" in fst:
encr = fst["encryption"]
c_dev = "{0}{1}".format(dev, fst["partition"])
crs = pycryptsetup.CryptSetup(device=c_dev)
crs.luksFormat(cipher="aes", cipherMode="xts-plain64",
keysize=512, hashMode="sha256")
crs.addKeyByPassphrase(encr["passphrase"], encr["passphrase"])
crs.activate(name=encr["name"], passphrase=encr["passphrase"])
command = "{0}{1} /dev/mapper/{2}".format(fsu["cmd"], opts,
encr["name"])
run_command(command)
if fst["type"] == "swap":
run_command("swapon {0}{1}".format(dev, fst["partition"]),
raise_exception=False)
def create_target_dir(args, template):
"""Create the target root directory
"""
if args.target_dir:
target_dir = args.target_dir
if not os.path.isdir(target_dir):
raise Exception("Target directory {0} does not exist".format(target_dir))
else:
try:
prefix = "ister-" + str(template["Version"]) + "-"
target_dir = tempfile.mkdtemp(prefix=prefix)
except Exception:
raise Exception("Failed to setup mounts for install")
LOG.debug("Installation target directory: {0}".format(target_dir))
return target_dir
def setup_mounts(target_dir, template):
"""Mount target folder
Returns target folder name
This function will raise an Exception on finding an error.
"""
def get_uuid(part_num, dev):
"""Get the uuid for a partition on a device"""
result = run_command("sgdisk --info={0} {1}".format(part_num, dev))
return result[0][1].split()[-1].lower()
def create_mount_unit(unit_dir, wants_dir, filename, uuid, mount, fs_type):
"""Create mount unit file for systemd
"""
LOG.debug("Creating mount unit for UUID: {0}".format(uuid))
unit = "[Unit]\nDescription = Mount for %s\n\n" % mount
unit += "[Mount]\nWhat = /dev/disk/by-partuuid/{0}\nWhere = {1}\n" \
"Type = {2}\n\n".format(uuid, mount, fs_type)
unit += "[Install]\nWantedBy = multi-user.target\n"
unit_path = os.path.join(unit_dir, filename)
symlink_path = os.path.join(wants_dir, filename)
with open(unit_path, 'w') as unit_fobj:
unit_fobj.write(unit)
os.symlink(os.path.relpath(unit_path, wants_dir), symlink_path)
LOG.info("Setting up mount points")
units_dir = os.path.join(target_dir, "etc", "systemd", "system")
wants_dir = os.path.join(units_dir, "local-fs.target.wants")
parts = sorted(template["PartitionMountPoints"], key=lambda v: v["mount"])
has_boot = False
for part in parts:
if part["mount"] == "/boot":
has_boot = True
for part in parts:
pnum = part["partition"]
dev, prefix = get_device_name(template, part["disk"])
if prefix:
base_dev = dev[:-1]
else:
base_dev = dev
LOG.debug("Mounting {0}{1} in {2}".format(dev, pnum, part["mount"]))
fs_type = [x["type"] for x in template["FilesystemTypes"]
if x['disk'] == part['disk'] and x['partition'] == pnum][-1]
if part["mount"] == "/":
uuid = "4f68bce3-e8cd-4db1-96e7-fbcaf984b709"
cmd = "sgdisk {0} --typecode={1}:{2}".format(base_dev, pnum, uuid)
run_command(cmd)
if not has_boot and template.get("LegacyBios"):
cmd = "sgdisk {0} --attributes={1}:set:2".format(base_dev, pnum)
run_command(cmd)
if part["mount"] == "/boot" and not template.get("LegacyBios"):
uuid = "c12a7328-f81f-11d2-ba4b-00a0c93ec93b"
cmd = "sgdisk {0} --typecode={1}:{2}".format(base_dev, pnum, uuid)
run_command(cmd)
if part["mount"] == "/boot" and template.get("LegacyBios"):
cmd = "sgdisk {0} --attributes={1}:set:2".format(base_dev, pnum)
run_command(cmd)
if part["mount"] == "/srv":
uuid = "3B8F8425-20E0-4F3B-907F-1A25A76F98E8"
cmd = "sgdisk {0} --typecode={1}:{2}".format(base_dev, pnum, uuid)
run_command(cmd)
if part["mount"] == "/home":
uuid = "933AC7E1-2EB4-4F13-B844-0E14E2AEF915"
cmd = "sgdisk {0} --typecode={1}:{2}".format(base_dev, pnum, uuid)
run_command(cmd)
if part["mount"] != "/":
cmd = "mkdir -p {0}{1}".format(target_dir, part["mount"])
run_command(cmd)
if "encryption" in part:
cmd = "mount /dev/mapper/{0} {1}{2}" \
.format(part["encryption"]["name"], target_dir, part["mount"])
run_command(cmd)
else:
cmd = "mount {0}{1} {2}{3}".format(dev, pnum, target_dir,
part["mount"])
run_command(cmd)
# Create mount units for the partitions, except for those having standard
# GPT type GUIDs, because the standard systemd 'systemd-gpt-auto-generator'
# tool will generate the mount points. However, in some rare cases the
# systemd tool may fail to generate a mount unit, in which case users
# have a possibility to force ister creating it by specifying 'forcemu'
# option.
if not part.get("forcemu"):
if part["mount"] in ["/", "/boot", "/srv", "/home", "/usr"]:
continue
if part["mount"].startswith("/usr/"):
continue
if not os.path.exists(wants_dir):
os.makedirs(wants_dir)
filename = part["mount"][1:].replace("/", "-") + ".mount"
create_mount_unit(units_dir, wants_dir, filename,
get_uuid(pnum, base_dev), part["mount"], fs_type)
def add_bundles(template, target_dir):
"""Create bundle subscription file
"""
bundles_dir = "/usr/share/clear/bundles/"
os.makedirs(target_dir + bundles_dir)
for index, bundle in enumerate(template["Bundles"]):
open(target_dir + bundles_dir + bundle, "w").close()
# pylint: disable=undefined-loop-variable
# since we never reach this point with an empty Bundles list
LOG.info("Installing {} bundles (and dependencies)...".format(index + 1))
def copy_os(args, template, target_dir):
"""Wrapper for running install command
"""
package_manager = template["SoftwareManager"]
LOG.info("Starting {0}. May take several minutes".format(package_manager))
if package_manager == "swupd":
copy_os_swupd(args, template, target_dir)
elif package_manager == "dnf":
copy_os_dnf(args, template, target_dir)
def copy_os_swupd(args, template, target_dir):
"""Wrapper for running install command with swupd
"""
add_bundles(template, target_dir)
if args.fast_install:
args.statedir = "{0}/tmp/swupd".format(target_dir)
if template["DestinationType"] == "physical":
os.makedirs(args.statedir, exist_ok=True)
os.chmod(args.statedir, stat.S_IRWXU)
os.makedirs("{0}/var/tmp".format(target_dir))
os.chmod("{0}/var/tmp".format(target_dir), stat.S_IRWXU)
run_command("mount --bind {0}/var/tmp {1}"
.format(target_dir, args.statedir))
cmd = "swupd verify --install"
cmd += " --path={0}".format(target_dir)
cmd += " --manifest={0}".format(template["Version"])
if args.contenturl:
cmd += " --contenturl={0}".format(args.contenturl)
if args.versionurl:
cmd += " --versionurl={0}".format(args.versionurl)
if args.format:
cmd += " --format={0}".format(args.format)
cmd += " --statedir={0}".format(args.statedir)
if args.cert_file:
cmd += " --certpath={0}".format(args.cert_file)
if shutil.which("stdbuf"):
cmd = "stdbuf -o 0 {0}".format(cmd)
cmd_env = get_cmd_env(template)
run_command(cmd, environ=cmd_env, show_output=True)
if args.fast_install:
run_command("rm -rf {0}".format(args.statedir))
def copy_os_dnf(args, template, target_dir):
"""Wrapper for running install command with dnf
"""
cmd = "dnf install --assumeyes"
if args.dnf_config:
cmd += " --config {0}".format(args.dnf_config)
cmd += " --installroot {0}".format(target_dir)
cmd += " {0}".format(" ".join(template["Bundles"]))
if shutil.which("stdbuf"):
cmd = "stdbuf -o 0 {0}".format(cmd)
cmd_env = get_cmd_env(template)
run_command(cmd, environ=cmd_env, show_output=True)
def get_cmd_env(template):
"""Get the environment variables with which commands will execute
"""
cmd_env = os.environ
if template.get("HTTPSProxy"):
cmd_env["https_proxy"] = template["HTTPSProxy"]
LOG.debug("https_proxy: {}".format(template["HTTPSProxy"]))
return cmd_env
class ChrootOpen(object):
"""Class encapsulating chroot setup and teardown
"""
def __init__(self, target_dir):
"""Stores the target directory for the chroot
"""
self.target_dir = target_dir
self.old_root = -1
def __enter__(self):
"""Using the target directory, setup the chroot
This function will raise an Exception on finding an error.
"""
try:
self.old_root = os.open("/", os.O_RDONLY)
os.chroot(self.target_dir)
os.chdir("/")
except Exception:
raise Exception("Unable to setup chroot to create users")
return self.target_dir
def __exit__(self, *args):
"""Using the old root, teardown the chroot
This function will raise an Exception on finding an error.
"""
try:
os.chdir(self.old_root)
os.chroot(".")
os.close(self.old_root)
except Exception:
raise Exception("Unable to restore real root after chroot")
def get_user_homedir(username):
"""Returns user's home directory path."""
if username == "root":
return os.path.join(os.sep, "root")
return os.path.join(os.sep, "home", username)
def create_account(user, target_dir):
"""Add user to the system
Create a new account on the system with a home directory and one time
passwordless login. Also add a new group with same name as the user
"""
opts = user["username"]
if user.get("uid"):
opts = "-u {0} ".format(user["uid"]) + opts
if "password" in user:
opts = "-p '{0}' ".format(user["password"]) + opts
command = "useradd -U -m {0}".format(opts)
with ChrootOpen(target_dir) as _:
_, stderr, ret = run_command(command, raise_exception=False)
if ret == 9:
# '9' is a documented exit code for the "user already exists" case.
# In this case just modify the existing user settings (if there is
# something to modify).
if opts != user["username"]:
command = "usermod {0}".format(opts)
run_command(command)
elif ret != 0:
if stderr:
LOG.debug(stderr)
raise Exception("failed to create user '{0}', 'useradd' returned "
"exit status '{1}'".format(user["username"], ret))
def add_user_fullname(user, target_dir):
"""Add user's full name to /etc/passwd
If the user's full name is set in the template, use chfn to set their full
name in the GECOS field of the /etc/passwd file
"""
try:
command = ["chfn", "-f", user["fullname"], user["username"]]
with ChrootOpen(target_dir) as _:
subprocess.call(command)
except Exception as exep:
print(exep)
LOG.info("Unable to set user {} full name: {}".format(user["username"],
exep))
def add_user_key(user, target_dir):
"""Append public key to user's ssh authorized_keys file
This function will raise an Exception on finding an error.
"""
# Must run pwd.getpwnam outside of chroot to load installer shared
# lib instead of target which prevents umount on cleanup
pwd.getpwnam("root")
sshdir = os.path.join(get_user_homedir(user["username"]), ".ssh")
akey_path = os.path.join(sshdir, "authorized_keys")
with ChrootOpen(target_dir) as _:
try:
os.makedirs(sshdir, mode=0o0700, exist_ok=True)
pwinfo = pwd.getpwnam(user["username"])
uid = pwinfo[2]
gid = pwinfo[3]
os.chown(sshdir, uid, gid)
with open(akey_path, "a") as akey_fobj:
akey_fobj.write(user["key"])
os.chown(akey_path, uid, gid)
except Exception as exep:
raise Exception("Unable to add {0}'s ssh key to authorized "
"keys: {1}".format(user["username"], exep))
def disable_root_login(target_dir):
"""Disables the login for root if there is a user with sudo active
It reads the line of /etc/shadow for the user previously created and
then it changes the username to root and the password to !. Finally, it
writes the result at the end.
"""
line = ''
with open("{0}/etc/shadow".format(target_dir)) as file:
line = file.read().split('\n')[0]
line = line.split(':')
line[0] = 'root'
line[1] = '!'
line = ':'.join(line)
with open("{0}/etc/shadow".format(target_dir), "a") as file:
file.write(line)
def setup_sudo(user, target_dir):
"""Add user to sudo (wheel) group
This function will raise an Exception on finding an error.
"""
try:
command = ["usermod", "-a", "-G", "wheel", user["username"]]
with ChrootOpen(target_dir) as _:
subprocess.call(command)
except Exception:
raise Exception("Unable to add sudo group for {}"
.format(user["username"]))
def add_users(template, target_dir):
"""Create user accounts with no password one time logins
Will setup sudo and ssh key access if specified in template.
"""
users = template.get("Users")
if not users:
return
LOG.info("Adding new user")
for user in users:
create_account(user, target_dir)
if user.get("key"):
add_user_key(user, target_dir)
if user.get("sudo") and user["sudo"]:
setup_sudo(user, target_dir)
disable_root_login(target_dir)
if user.get("fullname"):
add_user_fullname(user, target_dir)
def set_hostname(template, target_dir):
"""Writes the hostname to /etc/hostname
"""
hostname = template.get("Hostname")
if not hostname:
return
LOG.info("Setting up hostname")
path = '{0}/etc/'.format(target_dir)
if not os.path.exists(path):
os.makedirs(path)
with open(path + "hostname", "w") as file:
file.write(hostname)
def set_mirror_url(template, target_dir):
"""Writes custom mirror url to <target disk>/etc/swupd/mirror_contenturl
"""
target_mirror_url = template.get("MirrorURL")
if not target_mirror_url:
return
LOG.info("Setting custom mirror url")
path = '{0}/etc/swupd/'.format(target_dir)
if not os.path.exists(path):
os.makedirs(path)
with open(path + "mirror_contenturl", "w") as file:
file.write(target_mirror_url)
def set_mirror_version_url(template, target_dir):
"""Writes custom mirror version url to <target disk>/etc/swupd/mirror_versionurl
"""
target_mirror_version_url = template.get("VersionURL")
if not target_mirror_version_url:
return
LOG.info("Setting custom mirror version url")
path = '{0}/etc/swupd/'.format(target_dir)
if not os.path.exists(path):
os.makedirs(path)
with open(path + "mirror_versionurl", "w") as file:
file.write(target_mirror_version_url)
def set_static_configuration(template, target_dir):
"""Writes the configuration on /etc/systemd/network/10-en-static.network
"""
static_conf = template.get("Static_IP")
if not static_conf:
return
path = '{0}/etc/systemd/network/'.format(target_dir)
if not os.path.exists(path):
os.makedirs(path)
with open(path + "10-en-static.network", "w") as file:
file.write("[Match]\n")
file.write("Name={}\n\n".format(static_conf["iface"]))
file.write("[Network]\n")
file.write("Address={0}\n".format(static_conf["address"]))
file.write("Gateway={0}\n".format(static_conf["gateway"]))
if "dns" in static_conf:
file.write("DNS={0}\n".format(static_conf["dns"]))
def set_kernel_cmdline_appends(template, target_dir):
"""Write template['cmdline'] to /etc/kernel/cmdline
"""
if not template.get("cmdline"):
return
cmdline_path = os.path.join(target_dir, "etc/kernel/")
if not os.path.exists(cmdline_path):
os.makedirs(cmdline_path)
with open(os.path.join(cmdline_path, "cmdline"), "w") as cmdline_f:
cmdline_f.write(template["cmdline"])
run_command("{0}/usr/bin/clr-boot-manager update --path {0}"
.format(target_dir))
def pre_install_shell(template):
"""Run pre install commands
"""
if not template.get("PreInstallShell"):
return
LOG.info("Running pre install commands")
for cmdl in template["PreInstallShell"]:
run_command(cmdl, shell=True)
def post_install_nonchroot(template, target_dir):
"""Run non chroot post install scripts
All post scripts must be executable.
The mount root for the install is passed as an argument to each script.
"""
if not template.get("PostNonChroot"):
return
LOG.info("Running post non-chroot scripts")
for script in template["PostNonChroot"]:
run_command(script + " {}".format(target_dir))
def post_install_nonchroot_shell(template, target_dir):
"""Run non chroot post install commands
The mount root for the install is passed as the ISTER_CHROOT environment
variable.
"""
if not template.get("PostNonChrootShell"):
return
LOG.info("Running post non-chroot commands")
script_env = os.environ
script_env["ISTER_CHROOT"] = target_dir
for cmdl in template["PostNonChrootShell"]:
run_command(cmdl, shell=True, environ=script_env)
def post_install_chroot(template, target_dir):
"""Run chroot post install scripts
All post scripts must be executable.
"""
if not template.get("PostChroot"):
return
LOG.info("Running post scripts")
with ChrootOpen(target_dir) as _:
for script in template["PostChroot"]:
run_command(script)
def post_install_chroot_shell(template, target_dir):
"""Run chroot post install commands
"""
if not template.get("PostChrootShell"):
return
LOG.info("Running post commands")
with ChrootOpen(target_dir) as _:
for cmdl in template["PostChrootShell"]:
run_command(cmdl, shell=True)
def cleanup(args, template, target_dir, raise_exception=True):
"""Unmount and remove temporary files
"""
if args.no_unmount:
LOG.info("Skip unmounting target image at {0}".format(target_dir))
return
LOG.info("Cleaning up")
if target_dir:
if os.path.isdir("{0}/var/tmp".format(target_dir)):
run_command("umount {0}".format(args.statedir),
raise_exception=raise_exception)
run_command("rm -fr {0}/var/tmp".format(target_dir),
raise_exception=raise_exception)
try:
run_command("umount -R {}".format(target_dir))
except Exception:
run_command("lsof {}/boot".format(target_dir),
raise_exception=raise_exception)
if not args.target_dir:
# --target-dir was not used.
run_command("rm -fr {}".format(target_dir),
raise_exception=raise_exception)
# Turn off any swap devices we enabled
for fst in template["FilesystemTypes"]:
(dev, _) = get_device_name(template, fst["disk"])
if fst["type"] == "swap":
run_command("swapoff {0}{1}".format(dev, fst["partition"]),
raise_exception=raise_exception)
if template.get("dev"):
run_command("losetup --detach {0}".format(template["dev"]),
raise_exception=raise_exception)
for dev_entry in template['PartitionMountPoints']:
if 'encryption' in dev_entry:
crs = pycryptsetup.CryptSetup(name=dev_entry['encryption']['name'])
crs.deactivate()
def get_template_location(path):
"""Read the installer configuration file for the template location
This function will raise an Exception on finding an error.
"""
with open(path, "r") as conf_file:
contents = conf_file.readline().rstrip().split('=')
if contents[0] != "template" or len(contents) != 2:
# This does not look like a valid configuration file. Let's assume this
# is the template.
return "file://" + path
return contents[1]
def get_template(template_location):
"""Fetch JSON template file for installer
"""
json_file = request.urlopen(template_location)
parsed_json = json.loads(json_file.read().decode("utf-8"))
# Supply default SoftwareManager value if not defined for backwards compatibility
if not parsed_json.get("SoftwareManager"):
parsed_json["SoftwareManager"] = "swupd"
return parsed_json
def validate_layout(template):
"""Validate partition layout is sane
Returns mapping of layout to disk partitions.