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
|
# Copyright 2021 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2
import os
import re
import json
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from portage.versions import catpkgsplit, cpv_getversion
from portage.dep import dep_getcpv, dep_getslot, dep_getrepo
from twisted.internet import defer
from twisted.python import log
from buildbot.process.buildstep import BuildStep
from buildbot.process.results import SUCCESS
from buildbot.process.results import FAILURE
from buildbot.process.results import SKIPPED
from buildbot.plugins import steps, util
from buildbot_gentoo_ci.steps import portage as portage_steps
from buildbot_gentoo_ci.steps import repos as repos_steps
class SetupPropertys(BuildStep):
name = 'Setup propertys for images build'
description = 'Running'
descriptionSuffix = None
haltOnFailure = True
flunkOnFailure = True
def __init__(self, **kwargs):
super().__init__(**kwargs)
@defer.inlineCallbacks
def run(self):
# we need project uuid and worker uuid
self.gentooci = self.master.namedServices['services'].namedServices['gentooci']
project_data = yield self.gentooci.db.projects.getProjectByUuid(self.getProperty('project_uuid'))
self.setProperty('project_data', project_data, 'project_data')
#FIXME: set it in node config
self.workerbase = yield os.path.join('/', 'srv', 'gentoo')
#self.workerdest = yield os.path.join(self.workerbase, self.getProperty('project_uuid'))
self.setProperty('workerbase', self.workerbase, 'workerbase')
#self.setProperty('workerdest', self.workerdest, 'workerdest')
node_info = {}
workers = yield self.gentooci.db.projects.getWorkersByProjectUuid(project_data['uuid'])
print(workers)
for worker in workers:
worker_data = yield self.gentooci.db.workers.getWorkerByUuid(worker['worker_uuid'])
print(worker_data)
node_data = yield self.gentooci.db.workers.getNodeByWorkerUuid(worker['worker_uuid'])
print(node_data)
if node_info == {} or node_info['uuid'] != node_data['node_uuid']:
node_info = yield self.gentooci.db.workers.getNodeByUuid(node_data['node_uuid'])
image_info = yield self.gentooci.db.workers.getImageById(worker_data['image_id'])
print(node_info)
print(image_info)
self.setProperty('node_data', node_info, 'node_data')
self.setProperty('image_data', image_info, 'image_data')
return SUCCESS
class SetupBuildStepsForDocker(BuildStep):
name = 'Setup build steps for building docker images'
description = 'Running'
descriptionSuffix = None
haltOnFailure = True
flunkOnFailure = True
def __init__(self, **kwargs):
super().__init__(**kwargs)
@defer.inlineCallbacks
def run(self):
self.gentooci = self.master.namedServices['services'].namedServices['gentooci']
node_data = self.getProperty("node_data")
image_data = self.getProperty("image_data")
dockerfile = os.path.join('Project', self.getProperty("project_data")['uuid'],'docker', image_data['dockerfile'] + '.Dockerfile')
repository_data = yield self.gentooci.db.repositorys.getRepositoryByUuid(self.getProperty("project_data")['settings_repository_uuid'])
dockerfile_path = os.path.join(self.master.basedir, 'docker')
#FIXME: Set build timeout in config
self.build_timeout = 6600
aftersteps_list = []
aftersteps_list.append(steps.GitLab(repourl=repository_data['url'],
name = 'RunGit',
descriptionDone=repository_data['name'],
mode=repository_data['mode'],
method=repository_data['method'],
submodules=True,
alwaysUseLatest=repository_data['alwaysuselatest']
))
# build the gentoo docker buildbot-worker image
# set the build args
self.buildargs = {}
# set PROJECTUUID and PROJECTNAME
self.buildargs['PROJECTUUID'] = self.getProperty("project_data")['uuid']
self.buildargs['PROJECTNAME'] = self.getProperty("project_data")['name']
# set MAKEOPTS
# set USE
# set CFLAGS
# set BINHOSTURL
self.buildargs['BINHOSTURL'] = node_data['bin_host_url']
# set bootstrap image
self.buildargs['BOOTSTRAPTAG'] = image_data['bootstrap_tag']
# get the latest portage and bootstrap_tag images
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Pull ' + image_data['bootstrap_tag'],
command=['docker',
'image',
'pull',
image_data['bootstrap_tag']
]
))
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Pull gentoo/portage:latest',
command=['docker',
'image',
'pull',
'gentoo/portage:latest'
]
))
# build the gentoo docker buildbot-worker image
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Build docker buildbot-worker image',
command=['docker',
'build',
'--file', dockerfile,
'--build-arg', 'PROJECTUUID='+ self.buildargs['PROJECTUUID'],
'--build-arg', 'PROJECTNAME='+ self.buildargs['PROJECTNAME'],
'--build-arg', 'BINHOSTURL=' + self.buildargs['BINHOSTURL'],
'--build-arg', 'BOOTSTRAPTAG=' + self.buildargs['BOOTSTRAPTAG'],
'--tag', image_data['tag'],
'.'],
timeout=self.build_timeout
))
if aftersteps_list != []:
yield self.build.addStepsAfterCurrentStep(aftersteps_list)
return SUCCESS
class SetupBuildTypeAndSteps(BuildStep):
name = 'Check build type for building images'
description = 'Running'
descriptionSuffix = None
haltOnFailure = True
flunkOnFailure = True
def __init__(self, **kwargs):
super().__init__(**kwargs)
@defer.inlineCallbacks
def run(self):
aftersteps_list = []
if self.getProperty("image_data")['type'] == 'docker':
aftersteps_list.append(SetupBuildStepsForDocker())
if aftersteps_list != []:
yield self.build.addStepsAfterCurrentStep(aftersteps_list)
return SUCCESS
class SetupStage4Steps(BuildStep):
name = 'Setup steps for stage4 image'
description = 'Running'
descriptionSuffix = None
haltOnFailure = True
flunkOnFailure = True
def __init__(self, **kwargs):
super().__init__(**kwargs)
@defer.inlineCallbacks
def run(self):
self.gentooci = self.master.namedServices['services'].namedServices['gentooci']
self.setProperty('portage_repos_path', self.gentooci.config.project['project']['worker_portage_repos_path'], 'portage_repos_path')
aftersteps_list = []
separator = '\n'
log = yield self.addLog('makeing_stage4')
if self.getProperty("type") == 'docker':
print('build this stage4 %s on %s for %s' % (self.getProperty('project_uuid'), self.getProperty('workername'), self.getProperty('project_data')['name']))
self.descriptionDone = ' '.join(['build this stage4', self.getProperty('project_uuid'), 'on', self.getProperty('workername'), 'for', self.getProperty('project_data')['name']])
#FIXME: package list should be in the db project
package_list = ['dev-vcs/git', 'app-text/ansifilter', 'dev-util/pkgcheck', 'dev-lang/rust-bin', 'app-admin/eclean-kernel', 'app-portage/gentoolkit', 'sys-kernel/gentoo-kernel-bin', 'app-editors/nano']
if 'systemd' or 'openrc' in self.getProperty('project_data')['image']:
workerdest = yield os.path.join(self.getProperty("workerbase"), self.getProperty('project_uuid'))
workerdest_etc = yield os.path.join(workerdest, 'etc')
print(workerdest_etc)
self.setProperty('rootworkdir', workerdest, 'rootworkdir')
# create dir
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Create stage4 dir',
command=['mkdir', self.getProperty('project_uuid')],
workdir=self.getProperty("workerbase")
))
# download stage3
aftersteps_list.append(GetSteg3())
# setup portage
aftersteps_list.append(repos_steps.UpdateRepos())
aftersteps_list.append(portage_steps.SetReposConf())
aftersteps_list.append(portage_steps.SetMakeConf())
# add localegen
#FIXME: set that in config
locale_conf = []
locale_conf.append('en_US.UTF-8 UTF-8')
locale_conf.append('en_US ISO-8859-1')
locale_conf.append('C.UTF8 UTF-8')
locale_conf_string = separator.join(locale_conf)
aftersteps_list.append(
steps.StringDownload(locale_conf_string + separator,
workerdest="locale.gen",
workdir=self.getProperty("workerdest") + '/etc'
))
yield log.addStdout('File: ' + 'locale.gen' + '\n')
for line in locale_conf:
yield log.addStdout(line + '\n')
aftersteps_list.append(
steps.StringDownload('LANG="en_US.utf8"' + separator,
workerdest="locale.conf",
workdir=self.getProperty("workerdest") + '/etc'
))
yield log.addStdout('Setting LANG to: ' + 'en_US.utf8' + '\n')
aftersteps_list.append(SetSystemdNspawnConf())
# run localgen
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Run locale-gen on the chroot',
command=['systemd-nspawn', '-D', self.getProperty('project_uuid'), 'locale-gen'],
workdir=self.getProperty("workerbase")
))
# update timezone
# add the world file
package_list_string = separator.join(package_list)
aftersteps_list.append(
steps.StringDownload(package_list_string + separator,
workerdest="var/lib/portage/world",
workdir=self.getProperty("workerdest")
))
# update container
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Run update on the chroot',
command=['systemd-nspawn', '-D', self.getProperty('project_uuid'), 'emerge', '--update', '--deep', '--newuse', '@world'],
workdir=self.getProperty("workerbase")
))
# install buildbot-worker
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Install buildbot worker on the chroot',
command=['systemd-nspawn', '-D', self.getProperty('project_uuid'), 'emerge', 'buildbot-worker'],
workdir=self.getProperty("workerbase")
))
if self.getProperty("type") == 'docker':
# copy docker_buildbot.tac to worker dir
buildbot_worker_config_file = yield os.path.join(self.master.basedir, 'files', 'docker_buildbot_worker.tac')
aftersteps_list.append(steps.FileDownload(
flunkOnFailure=True,
name='Upload buildbot worker config to the stage4',
mastersrc=buildbot_worker_config_file,
workerdest='var/lib/buildbot_worker/buildbot.tac',
workdir=self.getProperty("workerdest")
))
# add info to the buildbot worker
worker_info_list = []
worker_info_list.append(self.getProperty('project_data')['name'])
worker_info_list.append(self.getProperty("stage3"))
#FIXME: worker name of self.getProperty('workername') from node table
worker_info_list.append('node1')
print(worker_info_list)
worker_info = ' '.join(worker_info_list)
aftersteps_list.append(steps.StringDownload(
worker_info + separator,
workerdest='var/lib/buildbot_worker/info/host',
workdir=self.getProperty("workerdest")
))
#FIXME: add admin info
# depclean
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Depclean on the chroot',
command=['systemd-nspawn', '-D', self.getProperty('project_uuid'), 'emerge', '--depclean'],
workdir=self.getProperty("workerbase")
))
# remove the gentoo repo
#aftersteps_list.append(steps.ShellCommand(
# flunkOnFailure=True,
# name='Remove the repo dir',
# command=['rm', '-R', self.getProperty('project_uuid') + '/var/db/repos/gentoo'],
# workdir=self.getProperty("workerbase")
#))
# compress it
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Compress the stage4',
command=['tar', '-cf', '../stage4-' + self.getProperty('project_uuid') + '.tar', '.'],
workdir=self.getProperty("workerbase") + '/' + self.getProperty('project_uuid')
))
# signing the stage4
# remove the dir
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Remove the stage4 dir',
command=['rm', '-R', self.getProperty('project_uuid')],
workdir=self.getProperty("workerbase")
))
# build docker stage4 image and buildbot-worker image
# FIXME: Use the python docker api
# FIXME: add date tags
if self.getProperty("type") == 'docker':
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Build docker stage4 image',
command=['docker', 'import', 'stage4-' + self.getProperty('project_uuid') + '.tar', 'stage4-' + self.getProperty('project_uuid') + ':latest'],
workdir=self.getProperty("workerbase")
))
if aftersteps_list != []:
yield self.build.addStepsAfterCurrentStep(aftersteps_list)
return SUCCESS
class GetSteg3(BuildStep):
name = 'Get the steg3 image'
description = 'Running'
descriptionSuffix = None
haltOnFailure = True
flunkOnFailure = True
def __init__(self, **kwargs):
super().__init__(**kwargs)
@defer.inlineCallbacks
def run(self):
self.gentooci = self.master.namedServices['services'].namedServices['gentooci']
compresstype = '.tar.xz'
downloadbaseurl = 'https://gentoo.osuosl.org/releases'
#downloadbaseurl = 'https://bouncer.gentoo.org/fetch/root/all/releases'
aftersteps_list = []
project_data = self.getProperty('project_data')
project_keyword_data = yield self.gentooci.db.keywords.getKeywordById(project_data['keyword_id'])
keyword = project_keyword_data['name']
# if the stage3 end with latest we neeed to get the date
if project_data['image'].endswith('latest'):
stage3latest = 'latest' + '-' + project_data['image'].replace('-latest', '') + '.txt'
downloadurllatest = '/'.join([downloadbaseurl, keyword, 'autobuilds', stage3latest])
print(downloadurllatest)
session = requests.Session()
retry = Retry(connect=3, backoff_factor=0.5)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
r = session.get(downloadurllatest, timeout=5)
if r.status_code == requests.codes.ok:
urltext = r.text.split('\n')[2]
print(urltext)
date = urltext.split('/')[0]
image = urltext.split('/')[1].split(' ')[0]
else:
r.raise_for_status()
return FAILURE
else:
image = project_data['image'] + compresstype
date = project_data['image'].split('-')[-1]
self.descriptionDone = image
self.setProperty('stage3', image, 'stage3')
downloadurlstage3 = '/'.join([downloadbaseurl, keyword, 'autobuilds', date, image])
print(downloadurlstage3)
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Download the stage3 file',
command=['wget', '-N', '-nv', downloadurlstage3],
workdir=self.getProperty("workerbase")
))
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Download the stage3 DIGESTS file',
command=['wget', '-N', '-nv', downloadurlstage3 + '.asc'],
workdir=self.getProperty("workerbase")
))
#FIXME: validate the stage3 file
aftersteps_list.append(steps.ShellCommand(
flunkOnFailure=True,
name='Unpack the stage3 file',
command=['tar', 'xpf', image, '--xattrs-include=\'*.*\'', '--numeric-owner', '-C', self.getProperty('project_uuid')],
workdir=self.getProperty("workerbase")
))
if aftersteps_list != []:
yield self.build.addStepsAfterCurrentStep(aftersteps_list)
return SUCCESS
class SetSystemdNspawnConf(BuildStep):
name = 'SetSystemdNspawnConf'
description = 'Running'
descriptionDone = 'Ran'
descriptionSuffix = None
haltOnFailure = True
flunkOnFailure = True
def __init__(self, **kwargs):
super().__init__(**kwargs)
@defer.inlineCallbacks
def run(self):
self.gentooci = self.master.namedServices['services'].namedServices['gentooci']
nspawn_conf_path = '/etc/systemd/nspawn/'
log = yield self.addLog(self.getProperty('project_uuid') + '.nspawn')
#FIXME: set it in config
separator = '\n'
nspawn_conf = []
nspawn_conf.append('[Files]')
nspawn_conf.append('TemporaryFileSystem=/run/lock')
# db node config portage cache bind
src_dir = '/srv/gentoo/portage/' + self.getProperty('project_uuid')
dest_dir = '/var/cache/portage'
nspawn_conf.append('Bind=' + src_dir + '/distfiles' + ':' + dest_dir + '/distfiles')
nspawn_conf.append('Bind=' + src_dir + '/packages' + ':' + dest_dir + '/packages')
nspawn_conf.append('[Exec]')
nspawn_conf.append('Capability=CAP_NET_ADMIN')
nspawn_conf.append('[Network]')
nspawn_conf.append('VirtualEthernet=no')
nspawn_conf_string = separator.join(nspawn_conf)
yield self.build.addStepsAfterCurrentStep([
steps.StringDownload(nspawn_conf_string + separator,
workerdest=self.getProperty('project_uuid') + '.nspawn',
workdir=nspawn_conf_path)
])
yield log.addStdout('File: ' + self.getProperty('project_uuid') + '.nspawn' + '\n')
for line in nspawn_conf:
yield log.addStdout(line + '\n')
return SUCCESS
|