forked from readthedocs/readthedocs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
querysets.py
281 lines (228 loc) · 8.99 KB
/
querysets.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
"""Build and Version QuerySet classes."""
import datetime
import logging
from django.db import models
from django.db.models import Q
from django.utils import timezone
from readthedocs.builds.constants import (
BUILD_STATE_FINISHED,
BUILD_STATE_TRIGGERED,
EXTERNAL,
)
from readthedocs.core.permissions import AdminPermission
from readthedocs.core.utils.extend import SettingsOverrideObject
from readthedocs.projects import constants
from readthedocs.projects.models import Project
log = logging.getLogger(__name__)
__all__ = ['VersionQuerySet', 'BuildQuerySet', 'RelatedBuildQuerySet']
class VersionQuerySetBase(models.QuerySet):
"""Versions take into account their own privacy_level setting."""
use_for_related_fields = True
def __init__(self, *args, internal_only=False, external_only=False, **kwargs):
"""
Overridden to pass extra arguments from the manager.
Usage:
import functools
ManagerClass.from_queryset(
functools.partial(VersionQuerySet, internal_only=True)
)
:param bool internal_only: If this queryset is being used to query internal versions only.
:param bool external_only: If this queryset is being used to query external versions only.
"""
self.internal_only = internal_only
self.external_only = external_only
super().__init__(*args, **kwargs)
def _add_from_user_projects(self, queryset, user, admin=False, member=False):
"""Add related objects from projects where `user` is an `admin` or a `member`."""
if user and user.is_authenticated:
projects_pk = (
AdminPermission.projects(
user=user,
admin=admin,
member=member,
)
.values_list('pk', flat=True)
)
user_queryset = self.filter(project__in=projects_pk)
queryset = user_queryset | queryset
return queryset
def _public_only(self):
if self.internal_only:
# Since internal versions are already filtered,
# don't do anything special.
queryset = self.filter(privacy_level=constants.PUBLIC)
elif self.external_only:
# Since external versions are already filtered,
# don't filter them again.
queryset = self.filter(
project__external_builds_privacy_level=constants.PUBLIC,
)
else:
queryset = self.filter(privacy_level=constants.PUBLIC).exclude(type=EXTERNAL)
queryset |= self.filter(
type=EXTERNAL,
project__external_builds_privacy_level=constants.PUBLIC,
)
return queryset
def public(
self,
user=None,
project=None,
only_active=True,
include_hidden=True,
only_built=False,
):
"""
Get all allowed versions.
.. note::
External versions use the `Project.external_builds_privacy_level`
field instead of its `privacy_level` field.
"""
queryset = self._public_only()
if user:
if user.is_superuser:
queryset = self.all()
else:
queryset = self._add_from_user_projects(queryset, user)
if project:
queryset = queryset.filter(project=project)
if only_active:
queryset = queryset.filter(active=True)
if only_built:
queryset = queryset.filter(built=True)
if not include_hidden:
queryset = queryset.filter(hidden=False)
return queryset.distinct()
def api(self, user=None):
return self.public(user, only_active=False)
class VersionQuerySet(SettingsOverrideObject):
_default_class = VersionQuerySetBase
class BuildQuerySet(models.QuerySet):
"""
Build objects that are privacy aware.
i.e. they take into account the privacy of the Version that they relate to.
"""
use_for_related_fields = True
def _add_from_user_projects(self, queryset, user, admin=False, member=False):
"""Add related objects from projects where `user` is an `admin` or a `member`."""
if user and user.is_authenticated:
projects_pk = (
AdminPermission.projects(
user=user,
admin=admin,
member=member,
)
.values_list('pk', flat=True)
)
user_queryset = self.filter(project__in=projects_pk)
queryset = user_queryset | queryset
return queryset
def public(self, user=None, project=None):
"""
Get all allowed builds.
Builds are public if the linked version and project are public.
.. note::
External versions use the `Project.external_builds_privacy_level`
field instead of its `privacy_level` field.
"""
queryset = (
self.filter(
version__privacy_level=constants.PUBLIC,
version__project__privacy_level=constants.PUBLIC,
)
.exclude(version__type=EXTERNAL)
)
queryset |= self.filter(
version__type=EXTERNAL,
project__external_builds_privacy_level=constants.PUBLIC,
project__privacy_level=constants.PUBLIC,
)
if user:
if user.is_superuser:
queryset = self.all()
else:
queryset = self._add_from_user_projects(
queryset,
user,
admin=True,
member=True,
)
if project:
queryset = queryset.filter(project=project)
return queryset.distinct()
def api(self, user=None):
return self.public(user)
def concurrent(self, project):
"""
Check if the max build concurrency for this project was reached.
- regular project: counts concurrent builds
- translation: concurrent builds of all the translations + builds of main project
.. note::
If the project/translation belongs to an organization, we count all concurrent
builds for all the projects from the organization.
:rtype: tuple
:returns: limit_reached, number of concurrent builds, number of max concurrent
"""
limit_reached = False
query = Q(
project__slug=project.slug,
# Limit builds to 5 hours ago to speed up the query
date__gte=timezone.now() - datetime.timedelta(hours=5),
)
if project.main_language_project:
# Project is a translation, counts all builds of all the translations
query |= Q(project__main_language_project=project.main_language_project)
query |= Q(project__slug=project.main_language_project.slug)
elif project.translations.exists():
# The project has translations, counts their builds as well
query |= Q(project__in=project.translations.all())
# If the project belongs to an organization, count all the projects
# from this organization as well
organization = project.organizations.first()
if organization:
query |= Q(project__in=organization.projects.all())
concurrent = (
self.filter(query)
.exclude(state__in=[BUILD_STATE_TRIGGERED, BUILD_STATE_FINISHED])
).distinct().count()
max_concurrent = Project.objects.max_concurrent_builds(project)
log.info(
'Concurrent builds. project=%s running=%s max=%s',
project.slug,
concurrent,
max_concurrent,
)
if concurrent >= max_concurrent:
limit_reached = True
return (limit_reached, concurrent, max_concurrent)
class RelatedBuildQuerySet(models.QuerySet):
"""
For models with association to a project through :py:class:`Build`.
.. note::
This is only used for ``BuildCommandViewSet`` from api v2.
Which is being used to upload build command results from the builders.
"""
use_for_related_fields = True
def _add_from_user_projects(self, queryset, user):
if user and user.is_authenticated:
projects_pk = (
AdminPermission.projects(
user=user,
admin=True,
member=True,
)
.values_list('pk', flat=True)
)
user_queryset = self.filter(build__project__in=projects_pk)
queryset = user_queryset | queryset
return queryset
def public(self, user=None):
queryset = self.filter(build__version__privacy_level=constants.PUBLIC)
if user:
if user.is_superuser:
queryset = self.all()
else:
queryset = self._add_from_user_projects(queryset, user)
return queryset.distinct()
def api(self, user=None):
return self.public(user)