/
build.py
368 lines (289 loc) · 11.3 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
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
import json
from datetime import timedelta, datetime
from peewee import JOIN
from data.database import (
BuildTriggerService,
RepositoryBuildTrigger,
Repository,
Namespace,
User,
RepositoryBuild,
BUILD_PHASE,
db_random_func,
UseThenDisconnect,
TRIGGER_DISABLE_REASON,
)
from data.model import (
InvalidBuildTriggerException,
InvalidRepositoryBuildException,
db_transaction,
user as user_model,
config,
)
from data.fields import DecryptedValue
PRESUMED_DEAD_BUILD_AGE = timedelta(days=15)
PHASES_NOT_ALLOWED_TO_CANCEL_FROM = (
BUILD_PHASE.PUSHING,
BUILD_PHASE.COMPLETE,
BUILD_PHASE.ERROR,
BUILD_PHASE.INTERNAL_ERROR,
)
ARCHIVABLE_BUILD_PHASES = [BUILD_PHASE.COMPLETE, BUILD_PHASE.ERROR, BUILD_PHASE.CANCELLED]
def update_build_trigger(trigger, config, auth_token=None, write_token=None):
trigger.config = json.dumps(config or {})
if auth_token is not None:
trigger.secure_auth_token = DecryptedValue(auth_token)
if write_token is not None:
trigger.write_token = write_token
trigger.save()
def create_build_trigger(repo, service_name, auth_token, user, pull_robot=None, config=None):
service = BuildTriggerService.get(name=service_name)
secure_auth_token = DecryptedValue(auth_token) if auth_token else None
trigger = RepositoryBuildTrigger.create(
repository=repo,
service=service,
secure_auth_token=secure_auth_token,
connected_user=user,
pull_robot=pull_robot,
config=json.dumps(config or {}),
)
return trigger
def get_build_trigger(trigger_uuid):
try:
return (
RepositoryBuildTrigger.select(
RepositoryBuildTrigger, BuildTriggerService, Repository, Namespace
)
.join(BuildTriggerService)
.switch(RepositoryBuildTrigger)
.join(Repository)
.join(Namespace, on=(Repository.namespace_user == Namespace.id))
.switch(RepositoryBuildTrigger)
.join(User, on=(RepositoryBuildTrigger.connected_user == User.id))
.where(RepositoryBuildTrigger.uuid == trigger_uuid)
.get()
)
except RepositoryBuildTrigger.DoesNotExist:
msg = "No build trigger with uuid: %s" % trigger_uuid
raise InvalidBuildTriggerException(msg)
def list_build_triggers(namespace_name, repository_name):
return (
RepositoryBuildTrigger.select(RepositoryBuildTrigger, BuildTriggerService, Repository)
.join(BuildTriggerService)
.switch(RepositoryBuildTrigger)
.join(Repository)
.join(Namespace, on=(Repository.namespace_user == Namespace.id))
.where(Namespace.username == namespace_name, Repository.name == repository_name)
)
def list_trigger_builds(namespace_name, repository_name, trigger_uuid, limit):
return list_repository_builds(namespace_name, repository_name, limit).where(
RepositoryBuildTrigger.uuid == trigger_uuid
)
def get_repository_for_resource(resource_key):
try:
return (
Repository.select(Repository, Namespace)
.join(Namespace, on=(Repository.namespace_user == Namespace.id))
.switch(Repository)
.join(RepositoryBuild)
.where(RepositoryBuild.resource_key == resource_key)
.get()
)
except Repository.DoesNotExist:
return None
def _get_build_base_query():
return (
RepositoryBuild.select(
RepositoryBuild,
RepositoryBuildTrigger,
BuildTriggerService,
Repository,
Namespace,
User,
)
.join(Repository)
.join(Namespace, on=(Repository.namespace_user == Namespace.id))
.switch(RepositoryBuild)
.join(User, JOIN.LEFT_OUTER)
.switch(RepositoryBuild)
.join(RepositoryBuildTrigger, JOIN.LEFT_OUTER)
.join(BuildTriggerService, JOIN.LEFT_OUTER)
.order_by(RepositoryBuild.started.desc())
)
def get_repository_build(build_uuid):
try:
return _get_build_base_query().where(RepositoryBuild.uuid == build_uuid).get()
except RepositoryBuild.DoesNotExist:
msg = "Unable to locate a build by id: %s" % build_uuid
raise InvalidRepositoryBuildException(msg)
def list_repository_builds(
namespace_name, repository_name, limit, include_inactive=True, since=None
):
query = (
_get_build_base_query()
.where(Repository.name == repository_name, Namespace.username == namespace_name)
.limit(limit)
)
if since is not None:
query = query.where(RepositoryBuild.started >= since)
if not include_inactive:
query = query.where(
RepositoryBuild.phase != BUILD_PHASE.ERROR,
RepositoryBuild.phase != BUILD_PHASE.COMPLETE,
)
return query
def get_recent_repository_build(namespace_name, repository_name):
query = list_repository_builds(namespace_name, repository_name, 1)
try:
return query.get()
except RepositoryBuild.DoesNotExist:
return None
def create_repository_build(
repo,
access_token,
job_config_obj,
dockerfile_id,
display_name,
trigger=None,
pull_robot_name=None,
):
pull_robot = None
if pull_robot_name:
pull_robot = user_model.lookup_robot(pull_robot_name)
return RepositoryBuild.create(
repository=repo,
access_token=access_token,
job_config=json.dumps(job_config_obj),
display_name=display_name,
trigger=trigger,
resource_key=dockerfile_id,
pull_robot=pull_robot,
)
def get_pull_robot_name(trigger):
if not trigger.pull_robot:
return None
return trigger.pull_robot.username
def _get_build_row(build_uuid):
return RepositoryBuild.select().where(RepositoryBuild.uuid == build_uuid).get()
def update_phase_then_close(build_uuid, phase):
""" A function to change the phase of a build """
with UseThenDisconnect(config.app_config):
try:
build = _get_build_row(build_uuid)
except RepositoryBuild.DoesNotExist:
return False
# Can't update a cancelled build
if build.phase == BUILD_PHASE.CANCELLED:
return False
updated = (
RepositoryBuild.update(phase=phase)
.where(RepositoryBuild.id == build.id, RepositoryBuild.phase == build.phase)
.execute()
)
return updated > 0
def create_cancel_build_in_queue(build_phase, build_queue_id, build_queue):
""" A function to cancel a build before it leaves the queue """
def cancel_build():
cancelled = False
if build_queue_id is not None:
cancelled = build_queue.cancel(build_queue_id)
if build_phase != BUILD_PHASE.WAITING:
return False
return cancelled
return cancel_build
def create_cancel_build_in_manager(build_phase, build_uuid, build_canceller):
""" A function to cancel the build before it starts to push """
def cancel_build():
if build_phase in PHASES_NOT_ALLOWED_TO_CANCEL_FROM:
return False
return build_canceller.try_cancel_build(build_uuid)
return cancel_build
def cancel_repository_build(build, build_queue):
""" This tries to cancel the build returns true if request is successful false
if it can't be cancelled """
from app import build_canceller
from buildman.jobutil.buildjob import BuildJobNotifier
cancel_builds = [
create_cancel_build_in_queue(build.phase, build.queue_id, build_queue),
create_cancel_build_in_manager(build.phase, build.uuid, build_canceller),
]
for cancelled in cancel_builds:
if cancelled():
updated = update_phase_then_close(build.uuid, BUILD_PHASE.CANCELLED)
if updated:
BuildJobNotifier(build.uuid).send_notification("build_cancelled")
return updated
return False
def get_archivable_build():
presumed_dead_date = datetime.utcnow() - PRESUMED_DEAD_BUILD_AGE
candidates = (
RepositoryBuild.select(RepositoryBuild.id)
.where(
(RepositoryBuild.phase << ARCHIVABLE_BUILD_PHASES)
| (RepositoryBuild.started < presumed_dead_date),
RepositoryBuild.logs_archived == False,
)
.limit(50)
.alias("candidates")
)
try:
found_id = (
RepositoryBuild.select(candidates.c.id)
.from_(candidates)
.order_by(db_random_func())
.get()
)
return RepositoryBuild.get(id=found_id)
except RepositoryBuild.DoesNotExist:
return None
def mark_build_archived(build_uuid):
""" Mark a build as archived, and return True if we were the ones who actually
updated the row. """
return (
RepositoryBuild.update(logs_archived=True)
.where(RepositoryBuild.uuid == build_uuid, RepositoryBuild.logs_archived == False)
.execute()
) > 0
def toggle_build_trigger(trigger, enabled, reason=TRIGGER_DISABLE_REASON.USER_TOGGLED):
""" Toggles the enabled status of a build trigger. """
trigger.enabled = enabled
if not enabled:
trigger.disabled_reason = RepositoryBuildTrigger.disabled_reason.get_id(reason)
trigger.disabled_datetime = datetime.utcnow()
trigger.save()
def update_trigger_disable_status(trigger, final_phase):
""" Updates the disable status of the given build trigger. If the build trigger had a
failure, then the counter is increased and, if we've reached the limit, the trigger is
automatically disabled. Otherwise, if the trigger succeeded, it's counter is reset. This
ensures that triggers that continue to error are eventually automatically disabled.
"""
with db_transaction():
try:
trigger = RepositoryBuildTrigger.get(id=trigger.id)
except RepositoryBuildTrigger.DoesNotExist:
# Already deleted.
return
# If the build completed successfully, then reset the successive counters.
if final_phase == BUILD_PHASE.COMPLETE:
trigger.successive_failure_count = 0
trigger.successive_internal_error_count = 0
trigger.save()
return
# Otherwise, increment the counters and check for trigger disable.
if final_phase == BUILD_PHASE.ERROR:
trigger.successive_failure_count = trigger.successive_failure_count + 1
trigger.successive_internal_error_count = 0
elif final_phase == BUILD_PHASE.INTERNAL_ERROR:
trigger.successive_internal_error_count = trigger.successive_internal_error_count + 1
# Check if we need to disable the trigger.
failure_threshold = config.app_config.get("SUCCESSIVE_TRIGGER_FAILURE_DISABLE_THRESHOLD")
error_threshold = config.app_config.get(
"SUCCESSIVE_TRIGGER_INTERNAL_ERROR_DISABLE_THRESHOLD"
)
if failure_threshold and trigger.successive_failure_count >= failure_threshold:
toggle_build_trigger(trigger, False, TRIGGER_DISABLE_REASON.BUILD_FALURES)
elif error_threshold and trigger.successive_internal_error_count >= error_threshold:
toggle_build_trigger(trigger, False, TRIGGER_DISABLE_REASON.INTERNAL_ERRORS)
else:
# Save the trigger changes.
trigger.save()