-
-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
tasks.py
675 lines (598 loc) · 23 KB
/
tasks.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
import json
from io import BytesIO
import requests
import structlog
from django.conf import settings
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from readthedocs import __version__
from readthedocs.api.v2.serializers import BuildCommandSerializer
from readthedocs.api.v2.utils import (
delete_versions_from_db,
get_deleted_active_versions,
run_automation_rules,
sync_versions_to_db,
)
from readthedocs.builds.constants import (
BRANCH,
BUILD_STATUS_FAILURE,
BUILD_STATUS_PENDING,
BUILD_STATUS_SUCCESS,
EXTERNAL,
EXTERNAL_VERSION_STATE_CLOSED,
LOCK_EXPIRE,
MAX_BUILD_COMMAND_SIZE,
TAG,
)
from readthedocs.builds.models import Build, Version
from readthedocs.builds.utils import memcache_lock
from readthedocs.core.permissions import AdminPermission
from readthedocs.core.utils import send_email, trigger_build
from readthedocs.integrations.models import HttpExchange
from readthedocs.oauth.notifications import GitBuildStatusFailureNotification
from readthedocs.projects.constants import GITHUB_BRAND, GITLAB_BRAND
from readthedocs.projects.models import Project, WebHookEvent
from readthedocs.storage import build_commands_storage
from readthedocs.worker import app
log = structlog.get_logger(__name__)
class TaskRouter:
"""
Celery tasks router.
It allows us to decide which queue is where we want to execute the task
based on project's settings.
1. the project is using conda
2. new project with less than N successful builds
3. version to be built is external
It ignores projects that have already set ``build_queue`` attribute.
https://docs.celeryproject.org/en/stable/userguide/routing.html#manual-routing
https://docs.celeryproject.org/en/stable/userguide/configuration.html#std:setting-task_routes
"""
MIN_SUCCESSFUL_BUILDS = 5
N_LAST_BUILDS = 15
TIME_AVERAGE = 350
BUILD_DEFAULT_QUEUE = 'build:default'
BUILD_LARGE_QUEUE = 'build:large'
def route_for_task(self, task, args, kwargs, **__):
log.debug('Executing TaskRouter.', task=task)
if task not in (
'readthedocs.projects.tasks.builds.update_docs_task',
'readthedocs.projects.tasks.builds.sync_repository_task',
):
log.debug('Skipping routing non-build task.', task=task)
return
version = self._get_version(task, args, kwargs)
if not version:
log.debug('No Build/Version found. No routing task.', task=task)
return
project = version.project
# Do not override the queue defined in the project itself
if project.build_queue:
log.info(
'Skipping routing task because project has a custom queue.',
project_slug=project.slug,
queue=project.build_queue,
)
return project.build_queue
# Use last queue used by the default version for external versions
# We always want the same queue as the previous default version,
# so that users will have the same outcome for PR's as normal builds.
if version.type == EXTERNAL:
last_build_for_default_version = (
project.builds
.filter(version__slug=project.get_default_version(), builder__isnull=False)
.order_by('-date')
.first()
)
if last_build_for_default_version:
if 'default' in last_build_for_default_version.builder:
routing_queue = self.BUILD_DEFAULT_QUEUE
else:
routing_queue = self.BUILD_LARGE_QUEUE
log.info(
'Routing task because is a external version.',
project_slug=project.slug,
queue=routing_queue,
)
return routing_queue
last_builds = version.builds.order_by('-date')[:self.N_LAST_BUILDS]
# Version has used conda in previous builds
for build in last_builds.iterator():
build_tools_python = ''
conda = None
if build.config:
build_tools_python = (
build.config
.get('build', {})
.get('tools', {})
.get('python', {})
.get('version', '')
)
conda = build.config.get('conda', None)
uses_conda = any([
conda,
build_tools_python.startswith('miniconda'),
])
if uses_conda:
log.info(
'Routing task because project uses conda.',
project_slug=project.slug,
queue=self.BUILD_LARGE_QUEUE,
)
return self.BUILD_LARGE_QUEUE
successful_builds_count = (
version.builds
.filter(success=True)
.order_by('-date')
.count()
)
# We do not have enough builds for this version yet
if successful_builds_count < self.MIN_SUCCESSFUL_BUILDS:
log.info(
'Routing task because it does not have enough successful builds yet.',
project_slug=project.slug,
queue=self.BUILD_LARGE_QUEUE,
)
return self.BUILD_LARGE_QUEUE
log.debug(
'No routing task because no conditions were met.',
project_slug=project.slug,
)
return
def _get_version(self, task, args, kwargs):
tasks = [
'readthedocs.projects.tasks.builds.update_docs_task',
'readthedocs.projects.tasks.builds.sync_repository_task',
]
version = None
if task in tasks:
version_pk = args[0]
try:
version = Version.objects.get(pk=version_pk)
except Version.DoesNotExist:
log.debug(
'Version does not exist. Routing task to default queue.',
version_id=version_pk,
)
return version
@app.task(queue='web', bind=True)
def archive_builds_task(self, days=14, limit=200, delete=False):
"""
Task to archive old builds to cold storage.
:arg days: Find builds older than `days` days.
:arg delete: If True, deletes BuildCommand objects after archiving them
"""
if not settings.RTD_SAVE_BUILD_COMMANDS_TO_STORAGE:
return
lock_id = '{0}-lock'.format(self.name)
with memcache_lock(lock_id, LOCK_EXPIRE, self.app.oid) as acquired:
if not acquired:
log.warning('Archive Builds Task still locked')
return False
max_date = timezone.now() - timezone.timedelta(days=days)
queryset = (
Build.objects
.exclude(cold_storage=True)
.filter(
date__lt=max_date,
date__gt=max_date - timezone.timedelta(days=90),
)
.prefetch_related('commands')
.only('date', 'cold_storage')
[:limit]
)
for build in queryset:
commands = BuildCommandSerializer(build.commands, many=True).data
if commands:
for cmd in commands:
if len(cmd["output"]) > MAX_BUILD_COMMAND_SIZE:
cmd["output"] = cmd["output"][-MAX_BUILD_COMMAND_SIZE:]
cmd["output"] = (
"\n\n"
"... (truncated) ..."
"\n\n"
"Command output too long. Truncated to last 1MB."
"\n\n" + cmd["output"]
) # noqa
log.debug(
"Truncating build command for build.", build_id=build.id
)
output = BytesIO(json.dumps(commands).encode("utf8"))
filename = "{date}/{id}.json".format(
date=str(build.date.date()), id=build.id
)
try:
build_commands_storage.save(name=filename, content=output)
if delete:
build.commands.all().delete()
except IOError:
log.exception('Cold Storage save failure')
continue
build.cold_storage = True
build.save()
@app.task(queue='web')
def delete_closed_external_versions(limit=200, days=30 * 3):
"""
Delete external versions that have been marked as closed after ``days``.
The commit status is updated to link to the build page, as the docs are removed.
"""
days_ago = timezone.now() - timezone.timedelta(days=days)
queryset = Version.external.filter(
state=EXTERNAL_VERSION_STATE_CLOSED,
modified__lte=days_ago,
)[:limit]
for version in queryset:
try:
last_build = version.last_build
if last_build:
status = BUILD_STATUS_PENDING
if last_build.finished:
status = BUILD_STATUS_SUCCESS if last_build.success else BUILD_STATUS_FAILURE
send_build_status(
build_pk=last_build.pk,
commit=last_build.commit,
status=status,
)
except Exception:
log.exception(
"Failed to send status",
project_slug=version.project.slug,
version_slug=version.slug,
)
else:
log.info(
"Removing external version.",
project_slug=version.project.slug,
version_slug=version.slug,
)
version.delete()
@app.task(
max_retries=1,
default_retry_delay=60,
queue='web'
)
def sync_versions_task(project_pk, tags_data, branches_data, **kwargs):
"""
Sync the version data in the repo (from build server) into our database.
Creates new Version objects for tags/branches that aren't tracked in the database,
and deletes Version objects for tags/branches that don't exists in the repository.
:param tags_data: List of dictionaries with ``verbose_name`` and ``identifier``
Example: [
{"verbose_name": "v1.0.0",
"identifier": "67a9035990f44cb33091026d7453d51606350519"},
].
:param branches_data: Same as ``tags_data`` but for branches (branch name, branch identifier).
Example: [
{"verbose_name": "latest",
"identifier": "main"},
].
:returns: `True` or `False` if the task succeeded.
"""
project = Project.objects.get(pk=project_pk)
# If the currently highest non-prerelease version is active, then make
# the new latest version active as well.
current_stable = project.get_original_stable_version()
if current_stable is not None:
activate_new_stable = current_stable.active
else:
activate_new_stable = False
try:
# Update All Versions
added_versions = set()
result = sync_versions_to_db(
project=project,
versions=tags_data,
type=TAG,
)
added_versions.update(result)
result = sync_versions_to_db(
project=project,
versions=branches_data,
type=BRANCH,
)
added_versions.update(result)
delete_versions_from_db(
project=project,
tags_data=tags_data,
branches_data=branches_data,
)
deleted_active_versions = get_deleted_active_versions(
project=project,
tags_data=tags_data,
branches_data=branches_data,
)
except Exception:
log.exception('Sync Versions Error')
return False
try:
# The order of added_versions isn't deterministic.
# We don't track the commit time or any other metadata.
# We usually have one version added per webhook.
run_automation_rules(project, added_versions, deleted_active_versions)
except Exception:
# Don't interrupt the request if something goes wrong
# in the automation rules.
log.exception(
'Failed to execute automation rules.',
project_slug=project.slug,
versions=added_versions,
)
# TODO: move this to an automation rule
promoted_version = project.update_stable_version()
new_stable = project.get_stable_version()
if promoted_version and new_stable and new_stable.active:
log.info(
'Triggering new stable build.',
project_slug=project.slug,
version_identifier=new_stable.identifier,
)
trigger_build(project=project, version=new_stable)
# Marking the tag that is considered the new stable version as
# active and building it if it was just added.
if (
activate_new_stable and
promoted_version.slug in added_versions
):
promoted_version.active = True
promoted_version.save()
trigger_build(project=project, version=promoted_version)
return True
@app.task(
max_retries=3,
default_retry_delay=60,
queue='web'
)
def send_build_status(build_pk, commit, status):
"""
Send Build Status to Git Status API for project external versions.
It tries using these services' account in order:
1. user's account that imported the project
2. each user's account from the project's maintainers
:param build_pk: Build primary key
:param commit: commit sha of the pull/merge request
:param status: build status failed, pending, or success to be sent.
"""
# TODO: Send build status for Bitbucket.
build = Build.objects.filter(pk=build_pk).first()
if not build:
return
provider_name = build.project.git_provider_name
log.bind(
build_id=build.pk,
project_slug=build.project.slug,
commit=commit,
status=status,
)
log.debug('Sending build status.')
if provider_name in [GITHUB_BRAND, GITLAB_BRAND]:
# get the service class for the project e.g: GitHubService.
service_class = build.project.git_service_class()
users = AdminPermission.admins(build.project)
if build.project.remote_repository:
remote_repository = build.project.remote_repository
remote_repository_relations = (
remote_repository.remote_repository_relations.filter(
account__isnull=False,
# Use ``user_in=`` instead of ``user__projects=`` here
# because User's are not related to Project's directly in
# Read the Docs for Business
user__in=AdminPermission.members(build.project),
).select_related('account', 'user').only('user', 'account')
)
# Try using any of the users' maintainer accounts
# Try to loop through all remote repository relations for the projects users
for relation in remote_repository_relations:
service = service_class(relation.user, relation.account)
# Send status report using the API.
success = service.send_build_status(
build,
commit,
status,
)
if success:
log.debug(
'Build status report sent correctly.',
user_username=relation.user.username,
)
return True
else:
log.warning('Project does not have a RemoteRepository.')
# Try to send build status for projects with no RemoteRepository
for user in users:
services = service_class.for_user(user)
# Try to loop through services for users all social accounts
# to send successful build status
for service in services:
success = service.send_build_status(
build,
commit,
status,
)
if success:
log.debug(
'Build status report sent correctly using an user account.',
user_username=user.username,
)
return True
for user in users:
# Send Site notification about Build status reporting failure
# to all the users of the project.
notification = GitBuildStatusFailureNotification(
context_object=build.project,
extra_context={'provider_name': provider_name},
user=user,
success=False,
)
notification.send()
log.info('No social account or repository permission available.')
return False
@app.task(queue='web')
def send_build_notifications(version_pk, build_pk, event):
version = Version.objects.get_object_or_log(pk=version_pk)
if not version or version.type == EXTERNAL:
return
build = Build.objects.filter(pk=build_pk).first()
if not build:
return
sender = BuildNotificationSender(
version=version,
build=build,
event=event,
)
sender.send()
class BuildNotificationSender:
webhook_timeout = 2
def __init__(self, version, build, event):
self.version = version
self.build = build
self.project = version.project
self.event = event
def send(self):
"""
Send email and webhook notifications for `project` about the `build`.
Email notifications are only send for build:failed events.
Webhooks choose to what events they subscribe to.
"""
if self.event == WebHookEvent.BUILD_FAILED:
email_addresses = (
self.project.emailhook_notifications.all()
.values_list('email', flat=True)
)
for email in email_addresses:
try:
self.send_email(email)
except Exception:
log.exception(
'Failed to send email notification.',
email=email,
project_slug=self.project.slug,
version_slug=self.version.slug,
build_id=self.build.id,
)
webhooks = (
self.project.webhook_notifications
.filter(events__name=self.event)
)
for webhook in webhooks:
try:
self.send_webhook(webhook)
except Exception:
log.exception(
'Failed to send webhook.',
webhook_id=webhook.id,
project_slug=self.project.slug,
version_slug=self.version.slug,
build_id=self.build.id,
)
def send_email(self, email):
"""Send email notifications for build failures."""
protocol = 'http' if settings.DEBUG else 'https'
context = {
'version': {
'verbose_name': self.version.verbose_name,
},
'project': {
'name': self.project.name,
},
'build': {
'pk': self.build.pk,
'error': self.build.error,
},
'build_url': '{}://{}{}'.format(
protocol,
settings.PRODUCTION_DOMAIN,
self.build.get_absolute_url(),
),
"build_raw": "{}://{}{}".format(
protocol,
settings.PRODUCTION_DOMAIN,
reverse("build-detail", args=[self.build.pk, "txt"]),
),
'unsubscribe_url': '{}://{}{}'.format(
protocol,
settings.PRODUCTION_DOMAIN,
reverse('projects_notifications', args=[self.project.slug]),
),
}
if self.build.commit:
title = _('Failed: {project[name]} ({commit})').format(
commit=self.build.commit[:8],
**context,
)
else:
title = _('Failed: {project[name]} ({version[verbose_name]})').format(
**context
)
log.info(
'Sending email notification.',
email=email,
project_slug=self.project.slug,
version_slug=self.version.slug,
build_id=self.build.id,
)
send_email(
email,
title,
template='projects/email/build_failed.txt',
template_html='projects/email/build_failed.html',
context=context,
)
def send_webhook(self, webhook):
"""
Send webhook notification.
The payload is signed using HMAC-SHA256,
for users to be able to verify the authenticity of the request.
Webhooks that don't have a payload,
are from the old implementation, for those we keep sending the
old default payload.
An HttpExchange object is created for each transaction.
"""
payload = webhook.get_payload(
version=self.version,
build=self.build,
event=self.event,
)
if not payload:
# Default payload from old webhooks.
payload = json.dumps({
'name': self.project.name,
'slug': self.project.slug,
'build': {
'id': self.build.id,
'commit': self.build.commit,
'state': self.build.state,
'success': self.build.success,
'date': self.build.date.strftime('%Y-%m-%d %H:%M:%S'),
},
})
headers = {
'content-type': 'application/json',
'User-Agent': f'Read-the-Docs/{__version__} ({settings.PRODUCTION_DOMAIN})',
'X-RTD-Event': self.event,
}
if webhook.secret:
headers['X-Hub-Signature'] = webhook.sign_payload(payload)
try:
log.info(
'Sending webhook notification.',
webhook_id=webhook.id,
project_slug=self.project.slug,
version_slug=self.version.slug,
build_id=self.build.id,
)
response = requests.post(
webhook.url,
data=payload,
headers=headers,
timeout=self.webhook_timeout,
)
HttpExchange.objects.from_requests_exchange(
response=response,
related_object=webhook,
)
except Exception:
log.exception(
'Failed to POST to webhook url.',
webhook_id=webhook.id,
webhook_url=webhook.url,
)