-
Notifications
You must be signed in to change notification settings - Fork 12
/
build.py
278 lines (211 loc) · 10.6 KB
/
build.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
#!/usr/bin/python3
'''
siapp-sdk
SPDX-License-Identifier: MIT
Copyright 2022 Siemens AG
Author:
Armin Tirala <[email protected]>
'''
import os
import shutil
import tarfile
import json
import subprocess
import pathlib
from time import sleep
import uuid
import datetime
from helper import (BuildArgs, Platform, error_handler, parse_arguments,
run_subprocess, remove_container, warning,
init_multiarch_qemu)
def _max_rootfs_size_in_mb():
return 350
def _copy_if_exists(src, dst):
if os.path.exists(src):
shutil.copytree(src, dst)
def _initialize_directory(dir):
tmp_dir = os.path.join(dir, 'tmp')
if os.path.exists(tmp_dir):
shutil.rmtree(tmp_dir, ignore_errors=False)
# required, because the rmtree subprocess may be too slow
while os.path.exists(tmp_dir):
print(f"Info: Waiting for directory {dir} to be deleted")
sleep(1)
pass
os.makedirs(os.path.join(tmp_dir, 'meta-inf.pmf'))
os.makedirs(os.path.join(tmp_dir, 'siapp'))
os.makedirs(os.path.join(tmp_dir, 'out'))
def _byte_to_mb(size):
return int((size / 1024 / 1024) + 1)
def _recommended_siapp_slot_size_in_mb(size):
return int(((size / 7 / 1024 / 1024) * 10) + 31)
def _create_rootfs_container(src_dir, build_dir, container_name, version,
platform: Platform):
'''
Creates the rootfs container based on the container file.
'''
container_file = os.path.join(src_dir, "Dockerfile")
container_image = f"{container_name}-{version}"
tar_file = os.path.join(build_dir, 'tmp', 'siapp', 'rootfs.tar')
if not os.path.exists(container_file):
error_handler(f"File does not exist: {container_file}")
command_list = [BuildArgs.tool, 'build', '--platform',
platform.image,
'-f', container_file, '-t', container_image, src_dir]
result = run_subprocess(command_list)
if result.returncode != 0:
error_handler("Could not build docker image!")
command_list = [BuildArgs.tool, 'create', '--name', container_name,
'--platform', platform.image,
container_image]
result = run_subprocess(command_list)
if result.returncode != 0:
remove_container(container_name, True)
error_handler("Could not create docker container!")
command_list = [BuildArgs.tool, 'export', '--output=' + tar_file,
container_name]
result = run_subprocess(command_list)
if result.returncode != 0:
remove_container(container_name, True)
error_handler("Could not export root filesystem out of "
"docker container!")
file_size = os.path.getsize(tar_file)
return file_size
def _create_oci_file(project_path, build_dir, container_name):
'''
Creates the config.json file. If the file does not exist in the project,
directory use the template file.
'''
config_file = os.path.join(project_path, 'config.json')
common_config_file = os.path.join(pathlib.Path(__file__).parent.resolve(),
'templates', 'config.json')
temp_config_file = os.path.join(build_dir, 'tmp', 'siapp', 'config.json')
if os.path.exists(config_file):
with open(config_file, 'r') as f:
config_json = json.load(f)
else:
print(f'Info: OCI file {config_file} not found. OCI file is generated by template file!')
with open(common_config_file, 'r') as f:
config_json = json.load(f)
command_output = subprocess.check_output([BuildArgs.tool, 'inspect',
container_name])
output_str = command_output.decode('utf-8')
json_start_index = output_str.find('[')
json_data = output_str[json_start_index:]
container_json = json.loads(json_data)[0]
config_json['process']['args'] = []
config_json['root']['path'] = 'rootfs'
if container_json.get('Config', False):
config_obj = container_json['Config']
if config_obj.get('Entrypoint', False):
if config_obj['Entrypoint']:
if isinstance(config_obj['Entrypoint'], list):
config_json['process']['args'].extend(
config_obj['Entrypoint'])
else:
config_json['process']['args'].append(
config_obj['Entrypoint'])
if config_obj.get('Cmd', False):
if isinstance(config_obj['Cmd'], list):
config_json['process']['args'].extend(config_obj['Cmd'])
else:
config_json['process']['args'].append(config_obj['Cmd'])
if config_obj.get('Env', False):
config_json['process']['env'] = config_obj['Env']
if config_obj.get('WorkingDir', False):
config_json['process']['cwd'] = config_obj['WorkingDir']
if len(config_json['process']['args']) == 0:
error_handler("Could not find ENTRYPOINT OR CMD in Dockerfile")
if len(config_json['process']['args']) == 1 and config_json['process']['args'][0] == "/bin/sh":
warning(f"Could not find a valid ENTRYPOINT or CMD option in Dockerfile")
with open(temp_config_file, 'w', newline='\r\n') as f:
json.dump(config_json, f, indent=4)
def _create_meta_info_file(
build_dir, container_name, size, platform: Platform):
date = datetime.datetime.now()
command_output = subprocess.check_output([BuildArgs.tool, 'inspect',
container_name])
output_str = command_output.decode('utf-8')
json_start_index = output_str.find('[')
json_data = output_str[json_start_index:]
container_json = json.loads(json_data)[0]
pim_pid_file = os.path.join(build_dir, 'tmp', 'meta-inf.pmf', 'pim.pid')
pim_pid = f'ies_pkgname={BuildArgs.name}\n'
pim_pid += f'ies_pkgid={uuid.uuid4()}\n'
pim_pid += f'ies_pkgrev={BuildArgs.version}\n'
pim_pid += f'ies_pkgtype=SIAPP\n'
pim_pid += f'ies_pkgarch={platform.arch}\n'
pim_pid += f'ies_pkgrootfs_size_mb={_byte_to_mb(size)}\n'
pim_pid += f'ies_pkgcontainerid={container_json["Id"]}\n'
pim_pid += f'ies_pkgimageid={container_json["Image"]}\n'
# BUG SICAM Device Manager 4.70 workaround
# pim_pid += 'ies_pkgbuildtime=\"' + date.strftime("%d.%m.%Y %H:%M") + '\"\n'
pim_pid += 'ies_pkgbuildtime=' + date.strftime("%d.%m.%Y %H:%M")+ '\n'
with open(pim_pid_file, 'w', newline='\r\n') as f:
f.write(pim_pid)
def _package_siapp(dir, container_name):
out_dir = os.path.join(dir, 'tmp', 'out')
scr_dir = os.path.join(dir, 'tmp')
with tarfile.open(os.path.join(out_dir, 'meta-inf.pmf'), "w:", format=tarfile.GNU_FORMAT) as tar:
tar.add(os.path.join(scr_dir, 'meta-inf.pmf'), arcname='')
with tarfile.open(os.path.join(out_dir, 'siapp.tar.gz'), "w:gz", format=tarfile.GNU_FORMAT) as tar:
tar.add(os.path.join(scr_dir, 'siapp'), arcname='')
if os.path.exists(os.path.join(scr_dir, 'cmd')):
with tarfile.open(os.path.join(out_dir, 'cmd.tar.gz'), "w:gz", format=tarfile.GNU_FORMAT) as tar:
tar.add(os.path.join(scr_dir, 'cmd'), arcname='')
os.rename(os.path.join(out_dir, 'cmd.tar.gz'), os.path.join(out_dir, 'cmd.tgz'))
if os.path.exists(os.path.join(scr_dir, 'app-doc')):
with tarfile.open(os.path.join(out_dir, 'app-doc.tar.gz'), "w:gz", format=tarfile.GNU_FORMAT) as tar:
tar.add(os.path.join(scr_dir, 'app-doc'), arcname='')
os.rename(os.path.join(out_dir, 'app-doc.tar.gz'), os.path.join(out_dir, 'app-doc.tgz'))
with tarfile.open(os.path.join(dir, container_name + '.siapp'), "w:", format=tarfile.GNU_FORMAT) as tar:
tar.add(out_dir, arcname='')
file_size = os.path.getsize(os.path.join(dir, container_name + '.siapp'))
return file_size
def _print_result(siapp_size, rootfs_size, siapp):
name = os.path.basename(__file__)
print(f"{name} - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(f"{name} - Size of unzipped root file system: {_byte_to_mb(rootfs_size):>8} MB")
if _byte_to_mb(rootfs_size) > _max_rootfs_size_in_mb():
print(f"{name} - Warning max. supported root file system size of {_max_rootfs_size_in_mb():>8} MB is reached")
print(f"{name} - Recommended configured siapp slot size: {_recommended_siapp_slot_size_in_mb(rootfs_size):>8} MB")
print(f"{name} - Size of generated siapp installation file: {_byte_to_mb(siapp_size):>8} MB")
print(f"{name} - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print(f"{name} - Successfully generated {siapp}")
def generate_container(platform: Platform):
container_name = BuildArgs.name + '-' + platform.name
container_file = "Dockerfile"
# look for the container file relative to this script file or use the current working dir
if os.path.exists(os.path.join(pathlib.Path(__file__).parent.resolve(),
BuildArgs.dir, container_file)):
root_path = pathlib.Path(__file__).parent.resolve()
elif os.path.exists(os.path.join(os.getcwd(), BuildArgs.dir, container_file)):
root_path = os.getcwd()
else:
error_handler(f"File does not exist: {container_file}")
project_path = os.path.normpath(os.path.join(root_path, BuildArgs.dir))
build_path = os.path.join(root_path, 'build', BuildArgs.name + '-' + BuildArgs.version)
_initialize_directory(build_path)
remove_container(container_name, True)
_copy_if_exists(os.path.join(project_path, 'cmd'), os.path.join(build_path, 'tmp', 'cmd'))
_copy_if_exists(os.path.join(project_path, 'app-doc'), os.path.join(build_path, 'tmp', 'app-doc'))
rootfs_size = _create_rootfs_container(project_path,
build_path,
container_name,
BuildArgs.version,
platform)
if rootfs_size <= 0:
error_handler("Could not read rootfs file size!")
_create_oci_file(project_path, build_path, container_name)
_create_meta_info_file(build_path, container_name, rootfs_size, platform)
siapp_size = _package_siapp(build_path, container_name)
if siapp_size <= 0:
error_handler("Could not read siapp file size!")
shutil.rmtree(os.path.join(build_path, 'tmp'))
_print_result(siapp_size, rootfs_size,
str(os.path.join(build_path, container_name)))
if __name__ == "__main__":
parse_arguments('build')
init_multiarch_qemu()
for platform in BuildArgs.platforms:
generate_container(platform)