-
Notifications
You must be signed in to change notification settings - Fork 11
/
run-build
executable file
·785 lines (682 loc) · 30.6 KB
/
run-build
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
#!/usr/bin/python3 -u
# -*- mode: Python; coding: utf-8 -*-
# Endless image builder
#
# Copyright (C) 2014-2015 Endless Mobile, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
from argparse import ArgumentParser
from collections import OrderedDict
import datetime
import fnmatch
import glob
import itertools
import logging
import os
import shutil
import subprocess
import sys
from textwrap import dedent
SRCDIR = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(1, os.path.join(SRCDIR, 'lib'))
import eib # noqa: E402
log = logging.getLogger(os.path.basename(__file__))
class ImageBuildRoot(object):
"""Build root for performing actual image build
A temporary build root is created with ostree at builddir. The
options in the config section buildroot control what gets installed
and mounted in the buildroot.
"""
def __init__(self, builddir, config):
self.builddir = builddir
# Get the config parameters
packages = config['buildroot']['packages'].split()
config_mounts = config['buildroot']['mounts'].split()
aptcache_dir = config['buildroot']['aptcache_dir']
aptcache_max_size = int(config['buildroot']['aptcache_max_size'])
# Build a list of required mounts using configuration values
required_mounts = [
# Typical kernel filesystems
'/sys',
'/proc',
'/dev',
'/dev/pts',
# Udev control socket and queue for `udevadm settle`
'/run/udev',
'/etc/resolv.conf',
# Required builder directories
config['build']['cachedir'],
config['build']['srcdir'],
aptcache_dir,
]
# Optional mounts dependent on existence on the host
optional_mounts = [
config['build']['sysconfdir'],
]
# Include local settings directory if provided
if 'localdir' in config['build']:
required_mounts.append(config['build']['localdir'])
# Wipe the apt cache directory if it's grown too large.
if os.path.exists(aptcache_dir):
aptcache_size = eib.disk_usage(aptcache_dir)
if aptcache_size >= aptcache_max_size:
log.info('Apt cache directory uses %d bytes, removing',
aptcache_size)
shutil.rmtree(aptcache_dir)
os.makedirs(aptcache_dir, exist_ok=True)
# Pull the ostree. Ideally the eosminbase ostree would be used to
# minimize the buildroot, but that's not released and would fail with
# --use-production-ostree.
repo_path = config['ostree']['repodir']
remote = config['ostree']['remote']
ref = config['ostree']['ref']
# If we are on an OSTree system, use the system repo as an additional cache.
# In the case of an Endless OS developer system booted into the same or similar
# ref as we are building an image of, this saves pulling over the network. In
# other cases it is harmless.
system_ostree_repo = '/ostree/repo'
if os.path.isdir(system_ostree_repo):
extra_pull_args = ['--localcache-repo', system_ostree_repo]
else:
extra_pull_args = []
log.info(f'Pulling OSTree ref {remote}:{ref}')
eib.retry(subprocess.check_call, [
'ostree',
f'--repo={repo_path}',
'pull',
*extra_pull_args,
remote,
ref,
])
# Checkout the commit. The checkout is going to be mutated, so copy the
# objects instead of hardlinking to ensure they aren't corrupted.
log.info(f'Checking out OSTree ref {remote}:{ref} to {self.builddir}')
shutil.rmtree(self.builddir)
subprocess.check_call([
'ostree',
f'--repo={repo_path}',
'checkout',
'--force-copy',
f'{remote}:{ref}',
self.builddir,
])
# Adjust the checkout a bit so it works for execution.
#
# /home, /root, /opt and /usr/local are all symlinks into persistent
# storage that aren't needed here and may mess with bind mounts.
log.debug(
f'Moving OSTree {self.builddir}/usr/etc to {self.builddir}/etc'
)
os.rename(
os.path.join(self.builddir, 'usr/etc'),
os.path.join(self.builddir, 'etc'),
)
for path in ('home', 'root', 'opt', 'usr/local'):
build_path = os.path.join(self.builddir, path)
if os.path.islink(build_path):
log.debug(f'Replacing {build_path} symlink with directory')
os.unlink(build_path)
os.makedirs(build_path, exist_ok=True)
if path == 'root':
os.chmod(build_path, 0o0700)
# Make the buildroot a private mount point. This ensures that
# mounts from the host that happen during the build don't
# propagate into our bind mounts. Some tools also expect / to be
# a private mount like it would be on the host.
subprocess.check_call(['mount', '--bind', self.builddir,
self.builddir])
subprocess.check_call(['mount', '--make-private', self.builddir])
# Mount all the desired paths. Sort the list of needed mounts so
# the shortest paths (parents) come before longer paths
# (children). Avoid superfluous mounts when a parent on the same
# device is already being mounted.
to_mount = OrderedDict()
for path in sorted(required_mounts + optional_mounts + config_mounts):
if path in optional_mounts and not os.path.exists(path):
log.info('Skipping non-existent optional mount %s', path)
continue
dev = os.stat(path).st_dev
for parent, parent_dev in to_mount.items():
if dev == parent_dev and \
os.path.commonprefix((path, parent)) == parent:
# No need to mount this path as a parent directory
# on the same device will already be mounted
log.info('Skipping mount of %s since it is a '
'subdirectory of %s', path, parent)
break
else:
# Unique path, add it for mounting
to_mount[path] = dev
# Really mount the directories
for path in to_mount:
self.mount(path)
# Remove the tmpfiles.d snippet that sets up symlinks for changes we have
# just reversed, and for the dpkg database we are about to move back
os.unlink(os.path.join(self.builddir, 'usr/lib/tmpfiles.d/ostree.conf'))
# Create any files that would normally be handled at runtime. This is
# particularly important for /var since it's likely that it was removed
# from the ostree commit. Run this inside the chroot to avoid depending on
# systemd-tmpfiles on the host system.
self._run(['systemd-tmpfiles', '--create', '--remove', '--boot', '-E'])
# Move the dpkg database back to its normal location
os.rename(
os.path.join(self.builddir, 'usr/share/dpkg/database'),
os.path.join(self.builddir, 'var/lib/dpkg'),
)
# update-catalog requires /var/lib/sgml-base to exist
os.makedirs(os.path.join(self.builddir, 'var/lib/sgml-base'))
# update-xmlcatalog requires /var/lib/xml-core to exist
os.makedirs(os.path.join(self.builddir, 'var/lib/xml-core'))
log.info('Installing buildroot packages')
apt_env = os.environ.copy()
apt_env['DEBIAN_FRONTEND'] = 'noninteractive'
apt_conf_path = os.path.join(self.builddir, 'etc/apt/apt.conf.d/99eib.conf')
os.makedirs(os.path.dirname(apt_conf_path), exist_ok=True)
with open(apt_conf_path, 'w') as f:
f.write(dedent(f"""\
# Assume yes for all apt questions.
APT::Get::Assume-Yes "true";
# Disable recommends like when building the OS.
APT::Install-Recommends "false";
# Ignore changes in the sources Release file.
Acquire::AllowReleaseInfoChange "true";
# Don't fetch any translations.
Acquire::Languages "none";
# Use our apt archive cache.
Dir::Cache::archives "{aptcache_dir}/";
DPkg::Options {{
# Always use the new version of a config file when upgrading.
"--force-confnew";
}};
"""))
self._run(['apt-get', 'update'], env=apt_env)
apt_cmd = ['apt-get', 'install', '-y']
apt_cmd += packages
self._run(apt_cmd, env=apt_env)
def _run(self, cmd, env=None):
subprocess.check_call(['chroot', self.builddir] + cmd, env=env)
def mount(self, path, target=None):
"""Bind mount path in the build directory"""
if not os.path.isabs(path):
raise eib.ImageBuildError('Buildroot mount path', path,
'is not an absolute path')
if not os.path.exists(path):
raise eib.ImageBuildError('Buildroot mount path', path,
'does not exist')
# Where it should be mounted
if target is None:
target = path
elif not os.path.isabs(target):
raise eib.ImageBuildError('Buildroot mount target', target,
'is not an absolute path')
mount_path = self.builddir + target
log.info('Mounting %s at %s', path, mount_path)
if os.path.isdir(path):
os.makedirs(mount_path, exist_ok=True)
else:
os.makedirs(os.path.dirname(mount_path), exist_ok=True)
with open(mount_path, 'w'):
pass
subprocess.check_call(['mount', '--bind', path, mount_path])
def __enter__(self):
return self
def __exit__(self, exc, value, tb):
# Kill all processes and unmount all filesystems
eib.cleanup_root(self.builddir)
log.info('Removing buildroot %s', self.builddir)
shutil.rmtree(self.builddir)
class ImageBuilder(object):
# Attributes to be exported to environment
CONFIG_ATTRS = [
'product', 'branch', 'arch', 'platform', 'personality',
'dry_run', 'series', 'srcdir', 'cachedir',
'sysconfdir', 'build_version',
'use_production_ostree',
]
BOOLEAN_ATTRS = [
'dry_run', 'use_production_ostree',
]
def __getattr__(self, attr):
"""Proxy this object's attributes into the config object"""
if attr in self.CONFIG_ATTRS:
# Proxy through to the config object's build section
if attr in self.BOOLEAN_ATTRS:
return self.config.getboolean(self.config.BUILD_SECTION,
attr)
return self.config.get(self.config.BUILD_SECTION, attr)
else:
# Chain up for normal attribute access
return super().__getattribute__(attr)
def __setattr__(self, attr, value):
"""Proxy the value to the config object"""
if attr in self.CONFIG_ATTRS:
# Proxy through to the config object's build section
if attr in self.BOOLEAN_ATTRS:
self.config.setboolean(self.config.BUILD_SECTION, attr, value)
else:
self.config.set(self.config.BUILD_SECTION, attr, value)
else:
# Chain up for normal attribute setting
super().__setattr__(attr, value)
def __init__(self, product, branch, arch, platform, personality,
localdir=None,
show_config=False,
show_apps=False,
show_apps_trim=0,
show_apps_group_by=None,
dry_run=False,
use_production_ostree=False,
configdir=None):
# Create the config option first to allow the proxying between
# it and this object's attributes.
self.config = eib.ImageConfigParser()
self.product = product
self.branch = branch
self.personality = personality
self.show_config = show_config
self.show_apps = show_apps
self.show_apps_trim = show_apps_trim
self.show_apps_group_by = show_apps_group_by
self.dry_run = dry_run
self.use_production_ostree = use_production_ostree
# Config instance without private settings
self._public_config = eib.ImageConfigParser()
# Release series. E.g., eos2.4 is in series eos2 while master is
# in series master.
self.series = self.branch.rsplit('.', 1)[0]
# Detect architecture and platform if not provided
if arch:
self.arch = arch
else:
machine = os.uname().machine
if machine == 'x86_64':
self.arch = 'amd64'
elif machine == 'aarch64':
self.arch = 'arm64'
elif fnmatch.fnmatch(machine, 'i?86'):
self.arch = 'i386'
else:
raise eib.ImageBuildError('Machine', machine, 'not supported')
if self.arch not in eib.SUPPORTED_ARCHES:
raise eib.ImageBuildError(
'Architecture', self.arch, 'not supported'
)
if platform:
self.platform = platform
else:
# Assume platform neutral arch
self.platform = self.arch
# Common paths
self.builddir = eib.BUILDDIR
self.configdir = configdir or os.path.join(SRCDIR, 'config')
if localdir:
self.localdir = os.path.abspath(localdir)
self.local_configdir = os.path.join(self.localdir, 'config')
# Expose the local directory in the configuration for use in
# interpolation
self.set_build_option('localdir', self.localdir)
self.set_build_option('localdatadir', '${localdir}/data')
else:
self.localdir = self.local_configdir = None
# Load other common settings so they're availavle to use in
# configparser interpolation.
self.srcdir = SRCDIR
self.cachedir = eib.CACHEDIR
self.sysconfdir = eib.SYSCONFDIR
self.build_version = (
datetime.datetime.utcnow().strftime('%y%m%d-%H%M%S')
)
@staticmethod
def _get_prefixes(value):
"""Yields all prefixes of value split by _, including the whole string.
>>> list(ImageBuilder._get_prefixes("en_GB_orkney"))
["en", "en_GB", "en_GB_orkney"]
"""
parts = value.split("_")
for i in range(1, len(parts) + 1):
yield "_".join(parts[:i])
def _get_attr_values(self, attr):
"""Yields one or more values for attr. For most properties this is a single
value, but for "personality" this yields a series of values to implement
inheritance."""
value = getattr(self, attr)
if attr == "personality":
yield from self._get_prefixes(value)
else:
yield value
def _get_config_paths(self, dir_path, dir_ns):
config_files = []
# Default configuration
config_files.append((os.path.join(dir_path, 'defaults.ini'),
dir_ns + 'defaults'))
# Add per-attribute config directories
config_attrs = ('product', 'branch', 'arch', 'platform',
'personality')
for attr in config_attrs:
for value in self._get_attr_values(attr):
path = os.path.join(dir_path, attr, value + '.ini')
namespace = dir_ns + '_'.join((attr, value))
config_files.append((path, namespace))
# Add combinations of per-attribute config directories
for attr1, attr2 in itertools.combinations(config_attrs, 2):
for (value1, value2) in itertools.product(self._get_attr_values(attr1),
self._get_attr_values(attr2)):
ini_name = (value1 + '-' + value2 + '.ini')
path = os.path.join(dir_path, attr1 + '-' + attr2, ini_name)
namespace = (dir_ns +
'_'.join((attr1, attr2, value1, value2)))
config_files.append((path, namespace))
return config_files
def configure(self):
"""Build settings from configuration files
Read configuration files to build the instance settings. The
files loaded are:
1. In each of $srcdir/config:
a. Default settings - defaults.ini.
b. Product, branch, arch, platform and personality settings.
These are in config subdirectories. For example,
product/$product.ini.
c. Product, branch, etc combination settings from the config
subdirectories. For example,
product-personality/$product-$personality.ini.
2. System config settings - $sysconfdir/config.ini.
3. In $localdir/config if $localdir is provided:
a. Default settings - defaults.ini.
b. Product, branch, arch, platform and personality settings.
These are in config subdirectories. For example,
product/$product.ini.
c. Product, branch, etc combination settings from the config
subdirectories. For example,
product-personality/$product-$personality.ini.
4. Checkout settings - $srcdir/config/local.ini.
These settings will be displayed in the output merged
configuration file. Additional private configuration files are
read whose settings will not be displayed in the merged
configuration file. These files are:
1. System private settings - $sysconfdir/private.ini
2. Local private settings - $localdir/config/private.ini
3. Checkout private settings - $srcdir/config/private.ini
"""
# Source config directory
config_files = self._get_config_paths(self.configdir, '')
# System configuration file
config_files.append(
(os.path.join(self.sysconfdir, 'config.ini'), 'system_config')
)
# Local config directory
if self.local_configdir:
config_files += self._get_config_paths(self.local_configdir,
'local_')
# Checkout configuration file
config_files.append(
(os.path.join(self.configdir, 'local.ini'), 'local')
)
# Read the config files
for path, namespace in config_files:
if self.config.read_config_file(path, namespace):
log.info('Loaded configuration file %s', path)
# Copy the configuration to the public instance and merge the
# options.
self._public_config = self.config.copy()
self._public_config.merge()
# Private configuration files
private_config_files = [
(os.path.join(self.sysconfdir, 'private.ini'), 'system_private'),
]
if self.local_configdir:
private_config_files.append(
(os.path.join(self.local_configdir, 'private.ini'),
'local_private')
)
private_config_files.append(
(os.path.join(self.configdir, 'private.ini'), 'private')
)
for path, namespace in private_config_files:
if self.config.read_config_file(path, namespace):
log.info('Loaded private configuration file %s', path)
# Merge the key prefixes for the real configuration
self.config.merge()
def check_value(self, section, option, value):
# Sections and key names match the config files, with suffixes as
# follows:
# _required = true means that the key must be set
# _values means the config value, if set, must be within the
# space-separated list of values in the schema
if option.endswith('_required'):
option = option[:-len('_required')]
if value.lower() == 'true' and option not in self.config[section]:
raise eib.ImageBuildError(
'Required configuration key [%s] %s is missing'
% (section, option))
elif option.endswith('_values'):
option = option[:-len('_values')]
if option in self.config[section] and \
self.config[section][option] not in value.split():
raise eib.ImageBuildError(
'Configuration key [%s] %s has invalid value: %s'
% (section, option, self.config[section][option]))
elif option.endswith('_type'):
real_option = option[:-len('_type')]
if real_option in self.config[section]:
real_value = self.config[section][real_option].strip()
if value == "path":
paths = [real_value] if real_value else []
elif value == "paths":
paths = real_value.split()
else:
raise eib.ImageBuildError(
f'Schema key [{section}] {option} has invalid value: '
f'{value}'
)
for path in paths:
if not os.path.exists(path):
raise eib.ImageBuildError(
f'Configuration key [{section}] {real_option} refers to '
f'nonexistent path: {path}'
)
def check_config(self):
"""Check loaded configuration against schema for validity."""
schema_file = os.path.join(self.configdir, 'schema.ini')
schema = eib.ImageConfigParser()
schema.read_config_file(schema_file, 'schema')
if self.local_configdir:
local_schema_file = os.path.join(self.local_configdir,
'schema.ini')
schema.read_config_file(local_schema_file, 'local_schema')
for sect in schema.sections():
for option, value in schema.items(sect):
self.check_value(sect, option, value)
def get_build_option(self, option, **kwargs):
"""Get an option from the configuration build section"""
return self.config.get(self.config.BUILD_SECTION, option, **kwargs)
def set_build_option(self, option, value):
"""Set an option in the configuration build section"""
return self.config.set(self.config.BUILD_SECTION, option, value)
def get_environment(self):
"""Get environment variables for stages and hooks
Provide the current environment with the configuration provided
environment variables.
"""
log.info('Exporting configuration to environment')
env = os.environ.copy()
env.update(self.config.get_environment())
return env
def prep_builddir(self):
"""Cleanup the scratch space and prep for a new build"""
ostree_co_dir = self.config['ostree']['checkout']
# If the scratch space exists, cleanup any resources from a
# previous build.
for path in (self.builddir, self.cachedir):
if os.path.isdir(path):
log.info('Cleaning up %s', path)
eib.cleanup_root(os.path.realpath(path))
# Make ostree checkouts mutable
log.info('Ensuring all ostree checkouts mutable in %s', ostree_co_dir)
ostree_checkouts = os.path.join(ostree_co_dir,
'ostree/deploy/*/deploy/*')
for path in glob.iglob(ostree_checkouts):
# Only directories are checkouts
if os.path.isdir(path):
eib.mutable_path(path)
# Cleanup files from previous build
log.info('Recreating build specific temporary directories')
eib.recreate_dir(self.builddir)
eib.recreate_dir(self.get_build_option('tmpdir'))
eib.recreate_dir(self.get_build_option('manifestdir'))
eib.recreate_dir(ostree_co_dir)
# Create the content directory
os.makedirs(self.get_build_option('contentdir'), exist_ok=True)
def create_tmp_config(self):
"""Take the merged public configuration and output it to a single file
in the tmp directory.
"""
tmpconfig = self.get_build_option('tmpconfig')
log.info('Output merged configuration file to %s', tmpconfig)
with open(tmpconfig, 'w') as out:
out.write('# Configuration for %s\n'
% self.get_build_option('outversion'))
self._public_config.write(out)
def create_tmp_full_config(self):
"""Take the merged full configuration and output it to a single file in
the tmp directory.
"""
tmpfullconfig = self.get_build_option('tmpfullconfig')
log.info('Output full merged configuration file to %s', tmpfullconfig)
with open(tmpfullconfig, 'w') as out:
out.write('# Full configuration for %s\n'
% self.get_build_option('outversion'))
self.config.write(out)
def setup_ostree_content_repo(self):
repo_path = self.config['ostree']['repodir']
# Create the repo if needed. Use a normal bare repo to speed up later
# deployment.
repo_config_path = os.path.join(repo_path, 'config')
if not os.path.exists(repo_config_path):
log.info(f'Creating OSTree repo {repo_path}')
os.makedirs(repo_path, exist_ok=True)
subprocess.check_call([
'ostree',
f'--repo={repo_path}',
'init',
'--mode=bare',
])
# Optionally use the production ostree repo rather than staging.
if self.use_production_ostree:
remote_url = self.config['ostree']['prod_pull_url']
else:
remote_url = self.config['ostree']['dev_pull_url']
# Get the list of ostree trusted keys.
keys = eib.get_ostree_trusted_keys(self.config)
# Recreate the remote setup to ensure there aren't any stale settings. Don't
# bother GPG verifying the summary if it's being fetched over HTTPS. This often
# fails when the summary is being updated concurrently since the received
# summary and summary signature can be mismatched.
remote = self.config['ostree']['remote']
log.info(f'Adding OSTree repo {repo_path} remote {remote}')
gpg_verify_summary = not remote_url.startswith('https://')
gpg_verify_summary_str = str(gpg_verify_summary).lower()
subprocess.check_call([
'ostree',
f'--repo={repo_path}',
'remote',
'delete',
'--if-exists',
remote,
])
remote_add_cmd = [
'ostree',
f'--repo={repo_path}',
'remote',
'add',
f'--set=gpg-verify-summary={gpg_verify_summary_str}',
]
remote_add_cmd += [f'--gpg-import={key}' for key in keys]
remote_add_cmd += [
remote,
remote_url,
self.config['ostree']['ref'],
]
subprocess.check_call(remote_add_cmd)
# Prune the builder's ostree to keep the local repo from growing unbounded. Only
# the latest commit on each ref is needed to minimize the pull size.
log.info(f'Pruning OSTree repo {repo_path}')
subprocess.check_call([
'ostree',
f'--repo={repo_path}',
'prune',
'--refs-only',
'--depth=0',
])
def run(self):
log.info('Configuring image build')
self.configure()
self.check_config()
if self.show_config:
# Just show the configuration without doing anything
self.config.write(sys.stdout)
return
elif self.show_apps:
# Can't import applist module unconditionally since build
# host likely doesn't have flatpak GIR module
import applist
applist.show_apps(self.config,
self.show_apps_trim,
self.show_apps_group_by,
sys.stdout)
return
if self.use_production_ostree:
log.info('Using production ostree repo')
log.info('Preparing build directory')
self.prep_builddir()
builder_env = self.get_environment()
self.create_tmp_config()
self.create_tmp_full_config()
self.setup_ostree_content_repo()
# Run the buildscript in a buildroot
with ImageBuildRoot(self.builddir, self.config):
log.info('Running image buildscript')
chrootscript = os.path.join(self.get_build_option('helpersdir'),
'eib-chroot')
buildscript = os.path.join(self.srcdir, 'buildscript')
cmd = (chrootscript, self.builddir, buildscript)
subprocess.check_call(cmd, env=builder_env)
log.info('Built assets available in %s',
self.get_build_option('outdir'))
def main():
aparser = ArgumentParser(
description='Build and publish images for Endless',
)
eib.add_cli_options(aparser)
args = aparser.parse_args()
if args.use_production:
args.use_production_ostree = True
if args.debug:
os.environ['EIB_DEBUG'] = '1'
eib.setup_logging()
builder = ImageBuilder(product=args.product,
branch=args.branch,
arch=args.arch,
platform=args.platform,
personality=args.personality,
localdir=args.localdir,
show_config=args.show_config,
show_apps=args.show_apps,
show_apps_trim=args.trim,
show_apps_group_by=args.group_by,
dry_run=args.dry_run,
use_production_ostree=args.use_production_ostree)
builder.run()
if __name__ == '__main__':
main()