-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathproject.py
297 lines (264 loc) · 9.4 KB
/
project.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
# Copyright 2023 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import redis
from ansible_base.rbac.api.related import check_related_permissions
from ansible_base.rbac.models import RoleDefinition
from django.db import transaction
from django.forms import model_to_dict
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import (
OpenApiResponse,
extend_schema,
extend_schema_view,
)
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from aap_eda import tasks
from aap_eda.api import exceptions as api_exc, filters, serializers
from aap_eda.core import models
from aap_eda.core.enums import Action
from aap_eda.core.utils import logging_utils
from .mixins import RedisDependencyMixin, ResponseSerializerMixin
logger = logging.getLogger(__name__)
resource_name = "Project"
class DestroyProjectMixin(mixins.DestroyModelMixin):
def destroy(self, request, *args, **kwargs):
project = self.get_object()
response = super().destroy(request, *args, **kwargs)
logger.info(
logging_utils.generate_simple_audit_log(
"Delete",
resource_name,
project.name,
project.id,
project.organization,
)
)
return response
@extend_schema_view(
list=extend_schema(
description="List all projects",
responses={
status.HTTP_200_OK: OpenApiResponse(
serializers.ProjectSerializer,
description="Return a list of projects.",
),
},
),
destroy=extend_schema(
description="Delete a project by id",
responses={
status.HTTP_204_NO_CONTENT: OpenApiResponse(
None,
description="Delete successful.",
),
},
),
)
class ProjectViewSet(
ResponseSerializerMixin,
mixins.CreateModelMixin,
DestroyProjectMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet,
RedisDependencyMixin,
):
queryset = models.Project.objects.order_by("id")
serializer_class = serializers.ProjectSerializer
filter_backends = (DjangoFilterBackend,)
filterset_class = filters.ProjectFilter
rbac_action = None
def filter_queryset(self, queryset):
return super().filter_queryset(
queryset.model.access_qs(self.request.user, queryset=queryset)
)
@extend_schema(
description="Import a project.",
request=serializers.ProjectCreateRequestSerializer,
responses={
status.HTTP_201_CREATED: OpenApiResponse(
serializers.ProjectSerializer,
description="Return a created project.",
)
}
| RedisDependencyMixin.redis_unavailable_response(),
)
def create(self, request):
serializer = serializers.ProjectCreateRequestSerializer(
data=request.data
)
serializer.is_valid(raise_exception=True)
# Catch Redis connection error and translate, as appropriate, to the
# Redis unavailable response.
try:
with transaction.atomic():
project = serializer.save()
check_related_permissions(
request.user,
serializer.Meta.model,
{},
model_to_dict(serializer.instance),
)
RoleDefinition.objects.give_creator_permissions(
request.user, serializer.instance
)
job = tasks.import_project.delay(project_id=project.id)
except redis.ConnectionError:
# If Redis isn't available we'll generate a Conflict (409).
# Anything else we re-raise the exception.
self.redis_is_available()
raise
# Atomically update `import_task_id` field only.
models.Project.objects.filter(pk=project.id).update(
import_task_id=job.id
)
project.import_task_id = job.id
serializer = self.get_serializer(project)
headers = self.get_success_headers(serializer.data)
logger.info(
logging_utils.generate_simple_audit_log(
"Create",
resource_name,
project.name,
project.id,
project.organization,
)
)
return Response(
serializer.data, status=status.HTTP_201_CREATED, headers=headers
)
@extend_schema(
description="Get a project by id",
responses={
status.HTTP_200_OK: OpenApiResponse(
serializers.ProjectReadSerializer,
description="Return a project by id.",
),
},
)
def retrieve(self, request, pk):
project = self.get_object()
logger.info(
logging_utils.generate_simple_audit_log(
"Read",
resource_name,
project.name,
project.id,
project.organization.name,
)
)
return Response(serializers.ProjectReadSerializer(project).data)
@extend_schema(
description="Partial update of a project",
request=serializers.ProjectUpdateRequestSerializer,
responses={
status.HTTP_200_OK: OpenApiResponse(
serializers.ProjectSerializer,
description="Update successful. Return an updated project.",
),
status.HTTP_400_BAD_REQUEST: OpenApiResponse(
None,
description="Update failed with bad request.",
),
status.HTTP_409_CONFLICT: OpenApiResponse(
None,
description="Update failed with integrity checking.",
),
},
)
def partial_update(self, request, pk):
project = self.get_object()
serializer = serializers.ProjectUpdateRequestSerializer(
instance=project, data=request.data, partial=True
)
serializer.is_valid(raise_exception=True)
update_fields = []
old_data = model_to_dict(project)
for key, value in serializer.validated_data.items():
setattr(project, key, value)
update_fields.append(key)
with transaction.atomic():
project.save(update_fields=update_fields)
check_related_permissions(
request.user,
serializer.Meta.model,
old_data,
model_to_dict(project),
)
logger.info(
logging_utils.generate_simple_audit_log(
"Update",
resource_name,
project.name,
project.id,
project.organization,
)
)
return Response(serializers.ProjectSerializer(project).data)
@extend_schema(
responses={status.HTTP_202_ACCEPTED: serializers.ProjectSerializer}
| RedisDependencyMixin.redis_unavailable_response(),
request=None,
description="Sync a project",
)
@action(
methods=["post"],
detail=True,
rbac_action=Action.SYNC,
)
@transaction.atomic
def sync(self, request, pk):
# get only projects user has access to
try:
project = (
models.Project.access_qs(request.user)
.select_for_update()
.get(pk=pk)
)
except models.Project.DoesNotExist:
raise api_exc.NotFound(f"Project with ID={pk} does not exist.")
# user might have only view permission, so we still have to check if
# user has sync permission for this project
self.check_object_permissions(request, project)
if project.import_state in [
models.Project.ImportState.PENDING,
models.Project.ImportState.RUNNING,
]:
raise api_exc.Conflict(
detail="Project import or sync is already running."
)
try:
job = tasks.sync_project.delay(project_id=project.id)
except redis.ConnectionError:
# If Redis isn't available we'll generate a Conflict (409).
# Anything else we re-raise the exception.
self.redis_is_available()
raise
project.import_state = models.Project.ImportState.PENDING
project.import_task_id = job.id
project.import_error = None
project.save()
logger.info(
logging_utils.generate_simple_audit_log(
"Sync",
resource_name,
project.name,
project.id,
project.organization,
)
)
serializer = serializers.ProjectSerializer(project)
return Response(status=status.HTTP_202_ACCEPTED, data=serializer.data)