blob: a91eaef52c2250e8163a9daa692d77a4cc83961e [file] [log] [blame]
rshri2d386cb2024-07-05 14:35:51 +00001# -*- coding: utf-8 -*-
2
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12# implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
yshah53cc9eb2024-07-05 13:06:31 +000016import logging
17import yaml
yshah53cc9eb2024-07-05 13:06:31 +000018import shutil
19import os
rshri2d386cb2024-07-05 14:35:51 +000020from http import HTTPStatus
21
yshah53cc9eb2024-07-05 13:06:31 +000022from time import time
rshri2d386cb2024-07-05 14:35:51 +000023from osm_nbi.base_topic import BaseTopic, EngineException
24
yshah53cc9eb2024-07-05 13:06:31 +000025from osm_nbi.descriptor_topics import DescriptorTopic
rshri2d386cb2024-07-05 14:35:51 +000026from osm_nbi.validation import (
27 ValidationError,
yshah99122b82024-11-18 07:05:29 +000028 validate_input,
rshri2d386cb2024-07-05 14:35:51 +000029 clustercreation_new_schema,
yshah99122b82024-11-18 07:05:29 +000030 cluster_edit_schema,
31 cluster_update_schema,
rshri2d386cb2024-07-05 14:35:51 +000032 infra_controller_profile_create_new_schema,
33 infra_config_profile_create_new_schema,
34 app_profile_create_new_schema,
35 resource_profile_create_new_schema,
36 infra_controller_profile_create_edit_schema,
37 infra_config_profile_create_edit_schema,
38 app_profile_create_edit_schema,
39 resource_profile_create_edit_schema,
rshri17b09ec2024-11-07 05:48:12 +000040 # k8scluster_new_schema,
41 clusterregistration_new_schema,
rshri2d386cb2024-07-05 14:35:51 +000042 attach_dettach_profile_schema,
yshah53cc9eb2024-07-05 13:06:31 +000043 ksu_schema,
44 oka_schema,
rshri2d386cb2024-07-05 14:35:51 +000045)
yshah53cc9eb2024-07-05 13:06:31 +000046from osm_common.dbbase import deep_update_rfc7396, DbException
rshri2d386cb2024-07-05 14:35:51 +000047from osm_common.msgbase import MsgException
48from osm_common.fsbase import FsException
49
yshah53cc9eb2024-07-05 13:06:31 +000050__author__ = (
51 "Shrinithi R <shrinithi.r@tataelxsi.co.in>",
52 "Shahithya Y <shahithya.y@tataelxsi.co.in>",
53)
rshri2d386cb2024-07-05 14:35:51 +000054
55
56class InfraContTopic(BaseTopic):
57 topic = "k8sinfra_controller"
58 topic_msg = "k8s_infra_controller"
59 schema_new = infra_controller_profile_create_new_schema
60 schema_edit = infra_controller_profile_create_edit_schema
61
62 def __init__(self, db, fs, msg, auth):
63 BaseTopic.__init__(self, db, fs, msg, auth)
rshri2d386cb2024-07-05 14:35:51 +000064
65 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
66 # To create the new infra controller profile
67 return self.new_profile(rollback, session, indata, kwargs, headers)
68
69 def default(self, rollback, session, indata=None, kwargs=None, headers=None):
70 # To create the default infra controller profile while creating the cluster
71 return self.default_profile(rollback, session, indata, kwargs, headers)
72
73 def delete(self, session, _id, dry_run=False, not_send_msg=None):
74 item_content = self.db.get_one(self.topic, {"_id": _id})
75 if item_content.get("default", False):
76 raise EngineException(
77 "Cannot delete item because it is marked as default",
78 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
79 )
80 # Before deleting, detach the profile from the associated clusters.
81 self.detach(session, _id, profile_type="infra_controller_profiles")
82 # To delete the infra controller profile
83 super().delete(session, _id, not_send_msg=not_send_msg)
yshahffcac5f2024-08-19 12:49:07 +000084 return _id
rshri2d386cb2024-07-05 14:35:51 +000085
86
87class InfraConfTopic(BaseTopic):
88 topic = "k8sinfra_config"
89 topic_msg = "k8s_infra_config"
90 schema_new = infra_config_profile_create_new_schema
91 schema_edit = infra_config_profile_create_edit_schema
92
93 def __init__(self, db, fs, msg, auth):
94 BaseTopic.__init__(self, db, fs, msg, auth)
rshri2d386cb2024-07-05 14:35:51 +000095
96 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
97 # To create the new infra config profile
98 return self.new_profile(rollback, session, indata, kwargs, headers)
99
100 def default(self, rollback, session, indata=None, kwargs=None, headers=None):
101 # To create the default infra config profile while creating the cluster
102 return self.default_profile(rollback, session, indata, kwargs, headers)
103
104 def delete(self, session, _id, dry_run=False, not_send_msg=None):
105 item_content = self.db.get_one(self.topic, {"_id": _id})
106 if item_content.get("default", False):
107 raise EngineException(
108 "Cannot delete item because it is marked as default",
109 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
110 )
111 # Before deleting, detach the profile from the associated clusters.
112 self.detach(session, _id, profile_type="infra_config_profiles")
113 # To delete the infra config profile
114 super().delete(session, _id, not_send_msg=not_send_msg)
yshahffcac5f2024-08-19 12:49:07 +0000115 return _id
rshri2d386cb2024-07-05 14:35:51 +0000116
117
118class AppTopic(BaseTopic):
119 topic = "k8sapp"
120 topic_msg = "k8s_app"
121 schema_new = app_profile_create_new_schema
122 schema_edit = app_profile_create_edit_schema
123
124 def __init__(self, db, fs, msg, auth):
125 BaseTopic.__init__(self, db, fs, msg, auth)
rshri2d386cb2024-07-05 14:35:51 +0000126
127 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
128 # To create the new app profile
129 return self.new_profile(rollback, session, indata, kwargs, headers)
130
131 def default(self, rollback, session, indata=None, kwargs=None, headers=None):
132 # To create the default app profile while creating the cluster
133 return self.default_profile(rollback, session, indata, kwargs, headers)
134
135 def delete(self, session, _id, dry_run=False, not_send_msg=None):
136 item_content = self.db.get_one(self.topic, {"_id": _id})
137 if item_content.get("default", False):
138 raise EngineException(
139 "Cannot delete item because it is marked as default",
140 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
141 )
142 # Before deleting, detach the profile from the associated clusters.
143 self.detach(session, _id, profile_type="app_profiles")
144 # To delete the app profile
145 super().delete(session, _id, not_send_msg=not_send_msg)
yshahffcac5f2024-08-19 12:49:07 +0000146 return _id
rshri2d386cb2024-07-05 14:35:51 +0000147
148
149class ResourceTopic(BaseTopic):
150 topic = "k8sresource"
151 topic_msg = "k8s_resource"
152 schema_new = resource_profile_create_new_schema
153 schema_edit = resource_profile_create_edit_schema
154
155 def __init__(self, db, fs, msg, auth):
156 BaseTopic.__init__(self, db, fs, msg, auth)
rshri2d386cb2024-07-05 14:35:51 +0000157
158 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
159 # To create the new resource profile
160 return self.new_profile(rollback, session, indata, kwargs, headers)
161
162 def default(self, rollback, session, indata=None, kwargs=None, headers=None):
163 # To create the default resource profile while creating the cluster
164 return self.default_profile(rollback, session, indata, kwargs, headers)
165
166 def delete(self, session, _id, dry_run=False, not_send_msg=None):
167 item_content = self.db.get_one(self.topic, {"_id": _id})
168 if item_content.get("default", False):
169 raise EngineException(
170 "Cannot delete item because it is marked as default",
171 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
172 )
173 # Before deleting, detach the profile from the associated clusters.
174 self.detach(session, _id, profile_type="resource_profiles")
175 # To delete the resource profile
176 super().delete(session, _id, not_send_msg=not_send_msg)
yshahffcac5f2024-08-19 12:49:07 +0000177 return _id
rshri2d386cb2024-07-05 14:35:51 +0000178
179
180class K8sTopic(BaseTopic):
181 topic = "clusters"
182 topic_msg = "cluster"
183 schema_new = clustercreation_new_schema
184 schema_edit = attach_dettach_profile_schema
185
186 def __init__(self, db, fs, msg, auth):
187 BaseTopic.__init__(self, db, fs, msg, auth)
188 self.infra_contr_topic = InfraContTopic(db, fs, msg, auth)
189 self.infra_conf_topic = InfraConfTopic(db, fs, msg, auth)
190 self.resource_topic = ResourceTopic(db, fs, msg, auth)
191 self.app_topic = AppTopic(db, fs, msg, auth)
rshri2d386cb2024-07-05 14:35:51 +0000192
garciadeblasbecc7052024-11-20 12:04:53 +0100193 @staticmethod
194 def format_on_new(content, project_id=None, make_public=False):
195 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
196 content["current_operation"] = None
197
rshri2d386cb2024-07-05 14:35:51 +0000198 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
199 """
200 Creates a new k8scluster into database.
201 :param rollback: list to append the created items at database in case a rollback must be done
202 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
203 :param indata: params to be used for the k8cluster
204 :param kwargs: used to override the indata
205 :param headers: http request headers
206 :return: the _id of k8scluster created at database. Or an exception of type
207 EngineException, ValidationError, DbException, FsException, MsgException.
208 Note: Exceptions are not captured on purpose. They should be captured at called
209 """
210 step = "checking quotas" # first step must be defined outside try
211 try:
212 self.check_quota(session)
213 step = "name unique check"
214 self.check_unique_name(session, indata["name"])
215 step = "validating input parameters"
216 cls_request = self._remove_envelop(indata)
217 self._update_input_with_kwargs(cls_request, kwargs)
218 cls_request = self._validate_input_new(cls_request, session["force"])
219 operation_params = cls_request
220
221 step = "filling cluster details from input data"
222 cls_create = self._create_cluster(
223 cls_request, rollback, session, indata, kwargs, headers
224 )
225
226 step = "creating cluster at database"
227 self.format_on_new(
228 cls_create, session["project_id"], make_public=session["public"]
229 )
rshri2d386cb2024-07-05 14:35:51 +0000230 op_id = self.format_on_operation(
231 cls_create,
232 "create",
233 operation_params,
234 )
235 _id = self.db.create(self.topic, cls_create)
garciadeblas6e88d9c2024-08-15 10:55:04 +0200236 pubkey, privkey = self._generate_age_key()
237 cls_create["age_pubkey"] = self.db.encrypt(
238 pubkey, schema_version="1.11", salt=_id
239 )
240 cls_create["age_privkey"] = self.db.encrypt(
241 privkey, schema_version="1.11", salt=_id
242 )
243 # TODO: set age_pubkey and age_privkey in the default profiles
rshri2d386cb2024-07-05 14:35:51 +0000244 rollback.append({"topic": self.topic, "_id": _id})
245 self.db.set_one("clusters", {"_id": _id}, cls_create)
246 self._send_msg("create", {"cluster_id": _id, "operation_id": op_id})
247
248 return _id, None
249 except (
250 ValidationError,
251 EngineException,
252 DbException,
253 MsgException,
254 FsException,
255 ) as e:
256 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
257
258 def _create_cluster(self, cls_request, rollback, session, indata, kwargs, headers):
259 # Check whether the region name and resource group have been given
garciadeblasc3a6c492024-08-15 10:00:42 +0200260 region_given = "region_name" in indata
261 resource_group_given = "resource_group" in indata
rshri2d386cb2024-07-05 14:35:51 +0000262
263 # Get the vim_account details
264 vim_account_details = self.db.get_one(
265 "vim_accounts", {"name": cls_request["vim_account"]}
266 )
267
garciadeblasc3a6c492024-08-15 10:00:42 +0200268 # Check whether the region name and resource group have been given
269 if not region_given and not resource_group_given:
rshri2d386cb2024-07-05 14:35:51 +0000270 region_name = vim_account_details["config"]["region_name"]
271 resource_group = vim_account_details["config"]["resource_group"]
garciadeblasc3a6c492024-08-15 10:00:42 +0200272 elif region_given and not resource_group_given:
rshri2d386cb2024-07-05 14:35:51 +0000273 region_name = cls_request["region_name"]
274 resource_group = vim_account_details["config"]["resource_group"]
garciadeblasc3a6c492024-08-15 10:00:42 +0200275 elif not region_given and resource_group_given:
rshri2d386cb2024-07-05 14:35:51 +0000276 region_name = vim_account_details["config"]["region_name"]
277 resource_group = cls_request["resource_group"]
278 else:
279 region_name = cls_request["region_name"]
280 resource_group = cls_request["resource_group"]
281
282 cls_desc = {
283 "name": cls_request["name"],
284 "vim_account": self.check_vim(session, cls_request["vim_account"]),
285 "k8s_version": cls_request["k8s_version"],
286 "node_size": cls_request["node_size"],
287 "node_count": cls_request["node_count"],
rshri17b09ec2024-11-07 05:48:12 +0000288 "bootstrap": cls_request["bootstrap"],
rshri2d386cb2024-07-05 14:35:51 +0000289 "region_name": region_name,
290 "resource_group": resource_group,
291 "infra_controller_profiles": [
292 self._create_default_profiles(
293 rollback, session, indata, kwargs, headers, self.infra_contr_topic
294 )
295 ],
296 "infra_config_profiles": [
297 self._create_default_profiles(
298 rollback, session, indata, kwargs, headers, self.infra_conf_topic
299 )
300 ],
301 "resource_profiles": [
302 self._create_default_profiles(
303 rollback, session, indata, kwargs, headers, self.resource_topic
304 )
305 ],
306 "app_profiles": [
307 self._create_default_profiles(
308 rollback, session, indata, kwargs, headers, self.app_topic
309 )
310 ],
311 "created": "true",
312 "state": "IN_CREATION",
313 "operatingState": "PROCESSING",
314 "git_name": self.create_gitname(cls_request, session),
315 "resourceState": "IN_PROGRESS.REQUEST_RECEIVED",
316 }
rshri17b09ec2024-11-07 05:48:12 +0000317 # Add optional fields if they exist in the request
318 if "description" in cls_request:
319 cls_desc["description"] = cls_request["description"]
rshri2d386cb2024-07-05 14:35:51 +0000320 return cls_desc
321
322 def check_vim(self, session, name):
323 try:
324 vim_account_details = self.db.get_one("vim_accounts", {"name": name})
325 if vim_account_details is not None:
326 return name
327 except ValidationError as e:
328 raise EngineException(
329 e,
330 HTTPStatus.UNPROCESSABLE_ENTITY,
331 )
332
333 def _create_default_profiles(
334 self, rollback, session, indata, kwargs, headers, topic
335 ):
336 topic = self.to_select_topic(topic)
337 default_profiles = topic.default(rollback, session, indata, kwargs, headers)
338 return default_profiles
339
340 def to_select_topic(self, topic):
341 if topic == "infra_controller_profiles":
342 topic = self.infra_contr_topic
343 elif topic == "infra_config_profiles":
344 topic = self.infra_conf_topic
345 elif topic == "resource_profiles":
346 topic = self.resource_topic
347 elif topic == "app_profiles":
348 topic = self.app_topic
349 return topic
350
351 def show_one(self, session, _id, profile, filter_q=None, api_req=False):
352 try:
353 filter_q = self._get_project_filter(session)
354 filter_q[self.id_field(self.topic, _id)] = _id
355 content = self.db.get_one(self.topic, filter_q)
356 existing_profiles = []
357 topic = None
358 topic = self.to_select_topic(profile)
359 for profile_id in content[profile]:
360 data = topic.show(session, profile_id, filter_q, api_req)
361 existing_profiles.append(data)
362 return existing_profiles
363 except ValidationError as e:
364 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
365
366 def state_check(self, profile_id, session, topic):
367 topic = self.to_select_topic(topic)
368 content = topic.show(session, profile_id, filter_q=None, api_req=False)
369 state = content["state"]
370 if state == "CREATED":
371 return
372 else:
373 raise EngineException(
374 f" {profile_id} is not in created state",
375 HTTPStatus.UNPROCESSABLE_ENTITY,
376 )
377
378 def edit(self, session, _id, item, indata=None, kwargs=None):
yshah99122b82024-11-18 07:05:29 +0000379 if item != (
380 "infra_controller_profiles",
381 "infra_config_profiles",
382 "app_profiles",
383 "resource_profiles",
384 ):
385 self.schema_edit = cluster_edit_schema
386 super().edit(session, _id, indata=item, kwargs=kwargs, content=None)
rshri2d386cb2024-07-05 14:35:51 +0000387 else:
yshah99122b82024-11-18 07:05:29 +0000388 indata = self._remove_envelop(indata)
389 indata = self._validate_input_edit(
390 indata, content=None, force=session["force"]
391 )
392 if indata.get("add_profile"):
393 self.add_profile(session, _id, item, indata)
394 elif indata.get("remove_profile"):
395 self.remove_profile(session, _id, item, indata)
396 else:
397 error_msg = "Add / remove operation is only applicable"
398 raise EngineException(error_msg, HTTPStatus.UNPROCESSABLE_ENTITY)
rshri2d386cb2024-07-05 14:35:51 +0000399
400 def add_profile(self, session, _id, item, indata=None):
401 indata = self._remove_envelop(indata)
402 operation_params = indata
403 profile_id = indata["add_profile"][0]["id"]
404 # check state
405 self.state_check(profile_id, session, item)
406 filter_q = self._get_project_filter(session)
407 filter_q[self.id_field(self.topic, _id)] = _id
408 content = self.db.get_one(self.topic, filter_q)
409 profile_list = content[item]
410
411 if profile_id not in profile_list:
412 content["operatingState"] = "PROCESSING"
rshri2d386cb2024-07-05 14:35:51 +0000413 op_id = self.format_on_operation(
414 content,
415 "add",
416 operation_params,
417 )
418 self.db.set_one("clusters", {"_id": content["_id"]}, content)
419 self._send_msg(
420 "add",
421 {
422 "cluster_id": _id,
423 "profile_id": profile_id,
424 "profile_type": item,
425 "operation_id": op_id,
426 },
427 )
428 else:
429 raise EngineException(
430 f"{item} {profile_id} already exists", HTTPStatus.UNPROCESSABLE_ENTITY
431 )
432
433 def _get_default_profiles(self, session, topic):
434 topic = self.to_select_topic(topic)
435 existing_profiles = topic.list(session, filter_q=None, api_req=False)
436 default_profiles = [
437 profile["_id"]
438 for profile in existing_profiles
439 if profile.get("default", False)
440 ]
441 return default_profiles
442
443 def remove_profile(self, session, _id, item, indata):
444 indata = self._remove_envelop(indata)
445 operation_params = indata
446 profile_id = indata["remove_profile"][0]["id"]
447 filter_q = self._get_project_filter(session)
448 filter_q[self.id_field(self.topic, _id)] = _id
449 content = self.db.get_one(self.topic, filter_q)
450 profile_list = content[item]
451
452 default_profiles = self._get_default_profiles(session, item)
453
454 if profile_id in default_profiles:
455 raise EngineException(
456 "Cannot remove default profile", HTTPStatus.UNPROCESSABLE_ENTITY
457 )
458 if profile_id in profile_list:
rshri2d386cb2024-07-05 14:35:51 +0000459 op_id = self.format_on_operation(
460 content,
461 "remove",
462 operation_params,
463 )
464 self.db.set_one("clusters", {"_id": content["_id"]}, content)
465 self._send_msg(
466 "remove",
467 {
468 "cluster_id": _id,
469 "profile_id": profile_id,
470 "profile_type": item,
471 "operation_id": op_id,
472 },
473 )
474 else:
475 raise EngineException(
476 f"{item} {profile_id} does'nt exists", HTTPStatus.UNPROCESSABLE_ENTITY
477 )
478
shahithyab9eb4142024-10-17 05:51:39 +0000479 def get_cluster_creds(self, session, _id, item):
yshah53cc9eb2024-07-05 13:06:31 +0000480 if not self.multiproject:
481 filter_db = {}
482 else:
483 filter_db = self._get_project_filter(session)
yshah53cc9eb2024-07-05 13:06:31 +0000484 filter_db[BaseTopic.id_field(self.topic, _id)] = _id
garciadeblasbecc7052024-11-20 12:04:53 +0100485 operation_params = None
shahithyab9eb4142024-10-17 05:51:39 +0000486 data = self.db.get_one(self.topic, filter_db)
garciadeblasbecc7052024-11-20 12:04:53 +0100487 op_id = self.format_on_operation(data, item, operation_params)
shahithyab9eb4142024-10-17 05:51:39 +0000488 self.db.set_one(self.topic, {"_id": data["_id"]}, data)
489 self._send_msg("get_creds", {"cluster_id": _id, "operation_id": op_id})
490 return op_id
491
492 def get_cluster_creds_file(self, session, _id, item, op_id):
493 if not self.multiproject:
494 filter_db = {}
495 else:
496 filter_db = self._get_project_filter(session)
497 filter_db[BaseTopic.id_field(self.topic, _id)] = _id
shahithya8bded112024-10-15 08:01:44 +0000498
499 data = self.db.get_one(self.topic, filter_db)
shahithyab9eb4142024-10-17 05:51:39 +0000500 creds_flag = None
501 for operations in data["operationHistory"]:
502 if operations["op_id"] == op_id:
503 creds_flag = operations["result"]
504 self.logger.info("Creds Flag: {}".format(creds_flag))
shahithya8bded112024-10-15 08:01:44 +0000505
shahithyab9eb4142024-10-17 05:51:39 +0000506 if creds_flag is True:
507 credentials = data["credentials"]
shahithya8bded112024-10-15 08:01:44 +0000508
shahithyab9eb4142024-10-17 05:51:39 +0000509 file_pkg = None
510 current_path = _id
shahithya8bded112024-10-15 08:01:44 +0000511
shahithyab9eb4142024-10-17 05:51:39 +0000512 self.fs.file_delete(current_path, ignore_non_exist=True)
513 self.fs.mkdir(current_path)
514 filename = "credentials.yaml"
515 file_path = (current_path, filename)
516 self.logger.info("File path: {}".format(file_path))
517 file_pkg = self.fs.file_open(file_path, "a+b")
shahithya8bded112024-10-15 08:01:44 +0000518
shahithyab9eb4142024-10-17 05:51:39 +0000519 credentials_yaml = yaml.safe_dump(
520 credentials, indent=4, default_flow_style=False
521 )
522 file_pkg.write(credentials_yaml.encode(encoding="utf-8"))
shahithya8bded112024-10-15 08:01:44 +0000523
shahithyab9eb4142024-10-17 05:51:39 +0000524 if file_pkg:
525 file_pkg.close()
526 file_pkg = None
527 self.fs.sync(from_path=current_path)
shahithya8bded112024-10-15 08:01:44 +0000528
shahithyab9eb4142024-10-17 05:51:39 +0000529 return (
530 self.fs.file_open((current_path, filename), "rb"),
531 "text/plain",
532 )
533 else:
534 raise EngineException(
535 "Not possible to get the credentials of the cluster",
536 HTTPStatus.UNPROCESSABLE_ENTITY,
537 )
yshah53cc9eb2024-07-05 13:06:31 +0000538
539 def update_cluster(self, session, _id, item, indata):
540 if not self.multiproject:
541 filter_db = {}
542 else:
543 filter_db = self._get_project_filter(session)
544 # To allow project&user addressing by name AS WELL AS _id
545 filter_db[BaseTopic.id_field(self.topic, _id)] = _id
yshah99122b82024-11-18 07:05:29 +0000546 validate_input(indata, cluster_update_schema)
yshah53cc9eb2024-07-05 13:06:31 +0000547 data = self.db.get_one(self.topic, filter_db)
yshah99122b82024-11-18 07:05:29 +0000548 operation_params = {}
yshah53cc9eb2024-07-05 13:06:31 +0000549 data["operatingState"] = "PROCESSING"
550 data["resourceState"] = "IN_PROGRESS"
551 operation_params = indata
yshahd0c876f2024-11-11 09:24:48 +0000552 op_id = self.format_on_operation(
yshah53cc9eb2024-07-05 13:06:31 +0000553 data,
554 item,
555 operation_params,
556 )
557 self.db.set_one(self.topic, {"_id": _id}, data)
yshah53cc9eb2024-07-05 13:06:31 +0000558 data = {"cluster_id": _id, "operation_id": op_id}
559 self._send_msg(item, data)
560 return op_id
561
rshri2d386cb2024-07-05 14:35:51 +0000562
563class K8saddTopic(BaseTopic):
564 topic = "clusters"
565 topic_msg = "cluster"
rshri17b09ec2024-11-07 05:48:12 +0000566 schema_new = clusterregistration_new_schema
rshri2d386cb2024-07-05 14:35:51 +0000567
568 def __init__(self, db, fs, msg, auth):
569 BaseTopic.__init__(self, db, fs, msg, auth)
570
garciadeblasbecc7052024-11-20 12:04:53 +0100571 @staticmethod
572 def format_on_new(content, project_id=None, make_public=False):
573 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
574 content["current_operation"] = None
575
rshri2d386cb2024-07-05 14:35:51 +0000576 def add(self, rollback, session, indata, kwargs=None, headers=None):
577 step = "checking quotas"
578 try:
579 self.check_quota(session)
580 step = "name unique check"
581 self.check_unique_name(session, indata["name"])
582 step = "validating input parameters"
583 cls_add_request = self._remove_envelop(indata)
584 self._update_input_with_kwargs(cls_add_request, kwargs)
585 cls_add_request = self._validate_input_new(
586 cls_add_request, session["force"]
587 )
588 operation_params = cls_add_request
589
590 step = "filling cluster details from input data"
rshri17b09ec2024-11-07 05:48:12 +0000591 cls_add_request = self._add_cluster(cls_add_request, session)
rshri2d386cb2024-07-05 14:35:51 +0000592
rshri17b09ec2024-11-07 05:48:12 +0000593 step = "registering the cluster at database"
rshri2d386cb2024-07-05 14:35:51 +0000594 self.format_on_new(
rshri17b09ec2024-11-07 05:48:12 +0000595 cls_add_request, session["project_id"], make_public=session["public"]
rshri2d386cb2024-07-05 14:35:51 +0000596 )
rshri2d386cb2024-07-05 14:35:51 +0000597 op_id = self.format_on_operation(
rshri17b09ec2024-11-07 05:48:12 +0000598 cls_add_request,
rshri2d386cb2024-07-05 14:35:51 +0000599 "register",
600 operation_params,
601 )
rshri17b09ec2024-11-07 05:48:12 +0000602 _id = self.db.create(self.topic, cls_add_request)
garciadeblas9d9d9262024-09-25 11:25:33 +0200603 pubkey, privkey = self._generate_age_key()
rshri17b09ec2024-11-07 05:48:12 +0000604 cls_add_request["age_pubkey"] = self.db.encrypt(
garciadeblas9d9d9262024-09-25 11:25:33 +0200605 pubkey, schema_version="1.11", salt=_id
606 )
rshri17b09ec2024-11-07 05:48:12 +0000607 cls_add_request["age_privkey"] = self.db.encrypt(
garciadeblas9d9d9262024-09-25 11:25:33 +0200608 privkey, schema_version="1.11", salt=_id
609 )
610 # TODO: set age_pubkey and age_privkey in the default profiles
rshri17b09ec2024-11-07 05:48:12 +0000611 self.db.set_one(self.topic, {"_id": _id}, cls_add_request)
rshri2d386cb2024-07-05 14:35:51 +0000612 rollback.append({"topic": self.topic, "_id": _id})
613 self._send_msg("register", {"cluster_id": _id, "operation_id": op_id})
614 return _id, None
615 except (
616 ValidationError,
617 EngineException,
618 DbException,
619 MsgException,
620 FsException,
621 ) as e:
622 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
623
624 def _add_cluster(self, cls_add_request, session):
625 cls_add = {
626 "name": cls_add_request["name"],
rshri2d386cb2024-07-05 14:35:51 +0000627 "credentials": cls_add_request["credentials"],
628 "vim_account": cls_add_request["vim_account"],
rshri17b09ec2024-11-07 05:48:12 +0000629 "bootstrap": cls_add_request["bootstrap"],
rshri2d386cb2024-07-05 14:35:51 +0000630 "created": "false",
631 "state": "IN_CREATION",
632 "operatingState": "PROCESSING",
633 "git_name": self.create_gitname(cls_add_request, session),
634 "resourceState": "IN_PROGRESS.REQUEST_RECEIVED",
635 }
rshri17b09ec2024-11-07 05:48:12 +0000636 # Add optional fields if they exist in the request
637 if "description" in cls_add_request:
638 cls_add["description"] = cls_add_request["description"]
rshri2d386cb2024-07-05 14:35:51 +0000639 return cls_add
640
641 def remove(self, session, _id, dry_run=False, not_send_msg=None):
642 """
643 Delete item by its internal _id
644 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
645 :param _id: server internal id
646 :param dry_run: make checking but do not delete
647 :param not_send_msg: To not send message (False) or store content (list) instead
648 :return: operation id (None if there is not operation), raise exception if error or not found, conflict, ...
649 """
650
651 # To allow addressing projects and users by name AS WELL AS by _id
652 if not self.multiproject:
653 filter_q = {}
654 else:
655 filter_q = self._get_project_filter(session)
656 filter_q[self.id_field(self.topic, _id)] = _id
657 item_content = self.db.get_one(self.topic, filter_q)
658
rshri2d386cb2024-07-05 14:35:51 +0000659 op_id = self.format_on_operation(
660 item_content,
661 "deregister",
662 None,
663 )
664 self.db.set_one(self.topic, {"_id": _id}, item_content)
665
666 self.check_conflict_on_del(session, _id, item_content)
667 if dry_run:
668 return None
669
670 if self.multiproject and session["project_id"]:
671 # remove reference from project_read if there are more projects referencing it. If it last one,
672 # do not remove reference, but delete
673 other_projects_referencing = next(
674 (
675 p
676 for p in item_content["_admin"]["projects_read"]
677 if p not in session["project_id"] and p != "ANY"
678 ),
679 None,
680 )
681
682 # check if there are projects referencing it (apart from ANY, that means, public)....
683 if other_projects_referencing:
684 # remove references but not delete
685 update_dict_pull = {
686 "_admin.projects_read": session["project_id"],
687 "_admin.projects_write": session["project_id"],
688 }
689 self.db.set_one(
690 self.topic, filter_q, update_dict=None, pull_list=update_dict_pull
691 )
692 return None
693 else:
694 can_write = next(
695 (
696 p
697 for p in item_content["_admin"]["projects_write"]
698 if p == "ANY" or p in session["project_id"]
699 ),
700 None,
701 )
702 if not can_write:
703 raise EngineException(
704 "You have not write permission to delete it",
705 http_code=HTTPStatus.UNAUTHORIZED,
706 )
707
708 # delete
709 self._send_msg(
710 "deregister",
711 {"cluster_id": _id, "operation_id": op_id},
712 not_send_msg=not_send_msg,
713 )
714 return None
yshah53cc9eb2024-07-05 13:06:31 +0000715
716
717class KsusTopic(BaseTopic):
718 topic = "ksus"
719 okapkg_topic = "okas"
720 infra_topic = "k8sinfra"
721 topic_msg = "ksu"
722 schema_new = ksu_schema
723 schema_edit = ksu_schema
724
725 def __init__(self, db, fs, msg, auth):
726 BaseTopic.__init__(self, db, fs, msg, auth)
727 self.logger = logging.getLogger("nbi.ksus")
728
729 @staticmethod
730 def format_on_new(content, project_id=None, make_public=False):
731 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
garciadeblasbecc7052024-11-20 12:04:53 +0100732 content["current_operation"] = None
yshah53cc9eb2024-07-05 13:06:31 +0000733 content["state"] = "IN_CREATION"
734 content["operatingState"] = "PROCESSING"
735 content["resourceState"] = "IN_PROGRESS"
736
737 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
738 _id_list = []
yshah53cc9eb2024-07-05 13:06:31 +0000739 for ksus in indata["ksus"]:
740 content = ksus
741 oka = content["oka"][0]
742 oka_flag = ""
743 if oka["_id"]:
744 oka_flag = "_id"
shahithya8bded112024-10-15 08:01:44 +0000745 oka["sw_catalog_path"] = ""
yshah53cc9eb2024-07-05 13:06:31 +0000746 elif oka["sw_catalog_path"]:
747 oka_flag = "sw_catalog_path"
748
749 for okas in content["oka"]:
750 if okas["_id"] and okas["sw_catalog_path"]:
751 raise EngineException(
752 "Cannot create ksu with both OKA and SW catalog path",
753 HTTPStatus.UNPROCESSABLE_ENTITY,
754 )
755 if not okas["sw_catalog_path"]:
756 okas.pop("sw_catalog_path")
757 elif not okas["_id"]:
758 okas.pop("_id")
759 if oka_flag not in okas.keys():
760 raise EngineException(
761 "Cannot create ksu. Give either OKA or SW catalog path for all oka in a KSU",
762 HTTPStatus.UNPROCESSABLE_ENTITY,
763 )
764
765 # Override descriptor with query string kwargs
766 content = self._remove_envelop(content)
767 self._update_input_with_kwargs(content, kwargs)
768 content = self._validate_input_new(input=content, force=session["force"])
769
770 # Check for unique name
771 self.check_unique_name(session, content["name"])
772
773 self.check_conflict_on_new(session, content)
774
775 operation_params = {}
776 for content_key, content_value in content.items():
777 operation_params[content_key] = content_value
778 self.format_on_new(
779 content, project_id=session["project_id"], make_public=session["public"]
780 )
yshah53cc9eb2024-07-05 13:06:31 +0000781 op_id = self.format_on_operation(
782 content,
783 operation_type="create",
784 operation_params=operation_params,
785 )
786 content["git_name"] = self.create_gitname(content, session)
787
788 # Update Oka_package usage state
789 for okas in content["oka"]:
790 if "_id" in okas.keys():
791 self.update_usage_state(session, okas)
792
793 _id = self.db.create(self.topic, content)
794 rollback.append({"topic": self.topic, "_id": _id})
yshah53cc9eb2024-07-05 13:06:31 +0000795 _id_list.append(_id)
796 data = {"ksus_list": _id_list, "operation_id": op_id}
797 self._send_msg("create", data)
798 return _id_list, op_id
799
800 def clone(self, rollback, session, _id, indata, kwargs, headers):
801 filter_db = self._get_project_filter(session)
802 filter_db[BaseTopic.id_field(self.topic, _id)] = _id
803 data = self.db.get_one(self.topic, filter_db)
804
yshah53cc9eb2024-07-05 13:06:31 +0000805 op_id = self.format_on_operation(
806 data,
807 "clone",
808 indata,
809 )
810 self.db.set_one(self.topic, {"_id": data["_id"]}, data)
811 self._send_msg("clone", {"ksus_list": [data["_id"]], "operation_id": op_id})
812 return op_id
813
814 def update_usage_state(self, session, oka_content):
815 _id = oka_content["_id"]
816 filter_db = self._get_project_filter(session)
817 filter_db[BaseTopic.id_field(self.topic, _id)] = _id
818
819 data = self.db.get_one(self.okapkg_topic, filter_db)
820 if data["_admin"]["usageState"] == "NOT_IN_USE":
821 usage_state_update = {
822 "_admin.usageState": "IN_USE",
823 }
824 self.db.set_one(
825 self.okapkg_topic, {"_id": _id}, update_dict=usage_state_update
826 )
827
828 def move_ksu(self, session, _id, indata=None, kwargs=None, content=None):
829 indata = self._remove_envelop(indata)
830
831 # Override descriptor with query string kwargs
832 if kwargs:
833 self._update_input_with_kwargs(indata, kwargs)
834 try:
835 if indata and session.get("set_project"):
836 raise EngineException(
837 "Cannot edit content and set to project (query string SET_PROJECT) at same time",
838 HTTPStatus.UNPROCESSABLE_ENTITY,
839 )
840 # TODO self._check_edition(session, indata, _id, force)
841 if not content:
842 content = self.show(session, _id)
843 indata = self._validate_input_edit(
844 input=indata, content=content, force=session["force"]
845 )
846 operation_params = indata
847 deep_update_rfc7396(content, indata)
848
849 # To allow project addressing by name AS WELL AS _id. Get the _id, just in case the provided one is a name
850 _id = content.get("_id") or _id
yshahd0c876f2024-11-11 09:24:48 +0000851 op_id = self.format_on_operation(
yshah53cc9eb2024-07-05 13:06:31 +0000852 content,
853 "move",
854 operation_params,
855 )
856 if content.get("_admin"):
857 now = time()
858 content["_admin"]["modified"] = now
859 content["operatingState"] = "PROCESSING"
860 content["resourceState"] = "IN_PROGRESS"
861
862 self.db.replace(self.topic, _id, content)
yshah53cc9eb2024-07-05 13:06:31 +0000863 data = {"ksus_list": [content["_id"]], "operation_id": op_id}
864 self._send_msg("move", data)
865 return op_id
866 except ValidationError as e:
867 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
868
869 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
870 if final_content["name"] != edit_content["name"]:
871 self.check_unique_name(session, edit_content["name"])
872 return final_content
873
874 @staticmethod
875 def format_on_edit(final_content, edit_content):
yshahd0c876f2024-11-11 09:24:48 +0000876 op_id = BaseTopic.format_on_operation(
yshah53cc9eb2024-07-05 13:06:31 +0000877 final_content,
878 "update",
879 edit_content,
880 )
881 final_content["operatingState"] = "PROCESSING"
882 final_content["resourceState"] = "IN_PROGRESS"
883 if final_content.get("_admin"):
884 now = time()
885 final_content["_admin"]["modified"] = now
yshahd0c876f2024-11-11 09:24:48 +0000886 return op_id
yshah53cc9eb2024-07-05 13:06:31 +0000887
888 def edit(self, session, _id, indata, kwargs):
889 _id_list = []
yshah53cc9eb2024-07-05 13:06:31 +0000890 if _id == "update":
891 for ksus in indata["ksus"]:
892 content = ksus
893 _id = content["_id"]
894 _id_list.append(_id)
895 content.pop("_id")
yshahd0c876f2024-11-11 09:24:48 +0000896 op_id = self.edit_ksu(session, _id, content, kwargs)
yshah53cc9eb2024-07-05 13:06:31 +0000897 else:
898 content = indata
899 _id_list.append(_id)
yshahd0c876f2024-11-11 09:24:48 +0000900 op_id = self.edit_ksu(session, _id, content, kwargs)
yshah53cc9eb2024-07-05 13:06:31 +0000901
902 data = {"ksus_list": _id_list, "operation_id": op_id}
903 self._send_msg("edit", data)
yshah53cc9eb2024-07-05 13:06:31 +0000904
yshahd0c876f2024-11-11 09:24:48 +0000905 def edit_ksu(self, session, _id, indata, kwargs):
yshah53cc9eb2024-07-05 13:06:31 +0000906 content = None
907 indata = self._remove_envelop(indata)
908
909 # Override descriptor with query string kwargs
910 if kwargs:
911 self._update_input_with_kwargs(indata, kwargs)
912 try:
913 if indata and session.get("set_project"):
914 raise EngineException(
915 "Cannot edit content and set to project (query string SET_PROJECT) at same time",
916 HTTPStatus.UNPROCESSABLE_ENTITY,
917 )
918 # TODO self._check_edition(session, indata, _id, force)
919 if not content:
920 content = self.show(session, _id)
921
922 for okas in indata["oka"]:
923 if not okas["_id"]:
924 okas.pop("_id")
925 if not okas["sw_catalog_path"]:
926 okas.pop("sw_catalog_path")
927
928 indata = self._validate_input_edit(indata, content, force=session["force"])
929
930 # To allow project addressing by name AS WELL AS _id. Get the _id, just in case the provided one is a name
931 _id = content.get("_id") or _id
932
933 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
yshah53cc9eb2024-07-05 13:06:31 +0000934 op_id = self.format_on_edit(content, indata)
935 self.db.replace(self.topic, _id, content)
936 return op_id
937 except ValidationError as e:
938 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
939
940 def delete_ksu(self, session, _id, indata, dry_run=False, not_send_msg=None):
941 _id_list = []
yshah53cc9eb2024-07-05 13:06:31 +0000942 if _id == "delete":
943 for ksus in indata["ksus"]:
944 content = ksus
945 _id = content["_id"]
946 _id_list.append(_id)
947 content.pop("_id")
yshahd0c876f2024-11-11 09:24:48 +0000948 op_id = self.delete(session, _id)
yshah53cc9eb2024-07-05 13:06:31 +0000949 else:
950 _id_list.append(_id)
yshahd0c876f2024-11-11 09:24:48 +0000951 op_id = self.delete(session, _id)
yshah53cc9eb2024-07-05 13:06:31 +0000952
953 data = {"ksus_list": _id_list, "operation_id": op_id}
954 self._send_msg("delete", data)
955 return op_id
956
yshahd0c876f2024-11-11 09:24:48 +0000957 def delete(self, session, _id):
yshah53cc9eb2024-07-05 13:06:31 +0000958 if not self.multiproject:
959 filter_q = {}
960 else:
961 filter_q = self._get_project_filter(session)
962 filter_q[self.id_field(self.topic, _id)] = _id
963 item_content = self.db.get_one(self.topic, filter_q)
964 item_content["state"] = "IN_DELETION"
965 item_content["operatingState"] = "PROCESSING"
966 item_content["resourceState"] = "IN_PROGRESS"
yshahd0c876f2024-11-11 09:24:48 +0000967 op_id = self.format_on_operation(
yshah53cc9eb2024-07-05 13:06:31 +0000968 item_content,
969 "delete",
970 None,
971 )
972 self.db.set_one(self.topic, {"_id": item_content["_id"]}, item_content)
973
974 if item_content["oka"][0].get("_id"):
975 used_oka = {}
976 existing_oka = []
977 for okas in item_content["oka"]:
978 used_oka["_id"] = okas["_id"]
979
980 filter = self._get_project_filter(session)
981 data = self.db.get_list(self.topic, filter)
982
983 if data:
984 for ksus in data:
985 if ksus["_id"] != _id:
986 for okas in ksus["oka"]:
shahithya8bded112024-10-15 08:01:44 +0000987 self.logger.info("OKA: {}".format(okas))
988 if okas.get("sw_catalog_path", ""):
989 continue
990 elif okas["_id"] not in existing_oka:
yshah53cc9eb2024-07-05 13:06:31 +0000991 existing_oka.append(okas["_id"])
992
993 if used_oka:
994 for oka, oka_id in used_oka.items():
995 if oka_id not in existing_oka:
996 self.db.set_one(
997 self.okapkg_topic,
998 {"_id": oka_id},
999 {"_admin.usageState": "NOT_IN_USE"},
1000 )
1001 return op_id
1002
1003
1004class OkaTopic(DescriptorTopic):
1005 topic = "okas"
1006 topic_msg = "oka"
1007 schema_new = oka_schema
1008 schema_edit = oka_schema
1009
1010 def __init__(self, db, fs, msg, auth):
1011 super().__init__(db, fs, msg, auth)
1012 self.logger = logging.getLogger("nbi.oka")
1013
1014 @staticmethod
1015 def format_on_new(content, project_id=None, make_public=False):
1016 DescriptorTopic.format_on_new(
1017 content, project_id=project_id, make_public=make_public
1018 )
garciadeblasbecc7052024-11-20 12:04:53 +01001019 content["current_operation"] = None
yshah53cc9eb2024-07-05 13:06:31 +00001020 content["state"] = "PENDING_CONTENT"
1021 content["operatingState"] = "PROCESSING"
1022 content["resourceState"] = "IN_PROGRESS"
1023
1024 def check_conflict_on_del(self, session, _id, db_content):
1025 usage_state = db_content["_admin"]["usageState"]
1026 if usage_state == "IN_USE":
1027 raise EngineException(
1028 "There is a KSU using this package",
1029 http_code=HTTPStatus.CONFLICT,
1030 )
1031
1032 def check_conflict_on_edit(self, session, final_content, edit_content, _id):
1033 if (
1034 final_content["name"] == edit_content["name"]
1035 and final_content["description"] == edit_content["description"]
1036 ):
1037 raise EngineException(
1038 "No update",
1039 http_code=HTTPStatus.CONFLICT,
1040 )
1041 if final_content["name"] != edit_content["name"]:
1042 self.check_unique_name(session, edit_content["name"])
1043 return final_content
1044
1045 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1046 indata = self._remove_envelop(indata)
1047
1048 # Override descriptor with query string kwargs
1049 if kwargs:
1050 self._update_input_with_kwargs(indata, kwargs)
1051 try:
1052 if indata and session.get("set_project"):
1053 raise EngineException(
1054 "Cannot edit content and set to project (query string SET_PROJECT) at same time",
1055 HTTPStatus.UNPROCESSABLE_ENTITY,
1056 )
1057 # TODO self._check_edition(session, indata, _id, force)
1058 if not content:
1059 content = self.show(session, _id)
1060
1061 indata = self._validate_input_edit(indata, content, force=session["force"])
1062
1063 # To allow project addressing by name AS WELL AS _id. Get the _id, just in case the provided one is a name
1064 _id = content.get("_id") or _id
1065
1066 content = self.check_conflict_on_edit(session, content, indata, _id=_id)
1067 op_id = self.format_on_edit(content, indata)
1068 deep_update_rfc7396(content, indata)
1069
1070 self.db.replace(self.topic, _id, content)
1071 return op_id
1072 except ValidationError as e:
1073 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
1074
1075 def delete(self, session, _id, dry_run=False, not_send_msg=None):
1076 if not self.multiproject:
1077 filter_q = {}
1078 else:
1079 filter_q = self._get_project_filter(session)
1080 filter_q[self.id_field(self.topic, _id)] = _id
1081 item_content = self.db.get_one(self.topic, filter_q)
1082 item_content["state"] = "IN_DELETION"
1083 item_content["operatingState"] = "PROCESSING"
1084 self.check_conflict_on_del(session, _id, item_content)
yshahd0c876f2024-11-11 09:24:48 +00001085 op_id = self.format_on_operation(
yshah53cc9eb2024-07-05 13:06:31 +00001086 item_content,
1087 "delete",
1088 None,
1089 )
yshah53cc9eb2024-07-05 13:06:31 +00001090 self.db.set_one(self.topic, {"_id": item_content["_id"]}, item_content)
1091 self._send_msg(
1092 "delete", {"oka_id": _id, "operation_id": op_id}, not_send_msg=not_send_msg
1093 )
yshahffcac5f2024-08-19 12:49:07 +00001094 return op_id
yshah53cc9eb2024-07-05 13:06:31 +00001095
1096 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1097 # _remove_envelop
1098 if indata:
1099 if "userDefinedData" in indata:
1100 indata = indata["userDefinedData"]
1101
1102 content = {"_admin": {"userDefinedData": indata, "revision": 0}}
1103
1104 self._update_input_with_kwargs(content, kwargs)
1105 content = BaseTopic._validate_input_new(
1106 self, input=kwargs, force=session["force"]
1107 )
1108
1109 self.check_unique_name(session, content["name"])
1110 operation_params = {}
1111 for content_key, content_value in content.items():
1112 operation_params[content_key] = content_value
1113 self.format_on_new(
1114 content, session["project_id"], make_public=session["public"]
1115 )
yshahd0c876f2024-11-11 09:24:48 +00001116 op_id = self.format_on_operation(
yshah53cc9eb2024-07-05 13:06:31 +00001117 content,
1118 operation_type="create",
1119 operation_params=operation_params,
1120 )
1121 content["git_name"] = self.create_gitname(content, session)
1122 _id = self.db.create(self.topic, content)
1123 rollback.append({"topic": self.topic, "_id": _id})
yshahd0c876f2024-11-11 09:24:48 +00001124 return _id, op_id
yshah53cc9eb2024-07-05 13:06:31 +00001125
1126 def upload_content(self, session, _id, indata, kwargs, headers):
1127 current_desc = self.show(session, _id)
1128
1129 compressed = None
1130 content_type = headers.get("Content-Type")
1131 if (
1132 content_type
1133 and "application/gzip" in content_type
1134 or "application/x-gzip" in content_type
1135 ):
1136 compressed = "gzip"
1137 if content_type and "application/zip" in content_type:
1138 compressed = "zip"
1139 filename = headers.get("Content-Filename")
1140 if not filename and compressed:
1141 filename = "package.tar.gz" if compressed == "gzip" else "package.zip"
1142 elif not filename:
1143 filename = "package"
1144
1145 revision = 1
1146 if "revision" in current_desc["_admin"]:
1147 revision = current_desc["_admin"]["revision"] + 1
1148
1149 file_pkg = None
1150 fs_rollback = []
1151
1152 try:
1153 start = 0
1154 # Rather than using a temp folder, we will store the package in a folder based on
1155 # the current revision.
1156 proposed_revision_path = _id + ":" + str(revision)
1157 # all the content is upload here and if ok, it is rename from id_ to is folder
1158
1159 if start:
1160 if not self.fs.file_exists(proposed_revision_path, "dir"):
1161 raise EngineException(
1162 "invalid Transaction-Id header", HTTPStatus.NOT_FOUND
1163 )
1164 else:
1165 self.fs.file_delete(proposed_revision_path, ignore_non_exist=True)
1166 self.fs.mkdir(proposed_revision_path)
1167 fs_rollback.append(proposed_revision_path)
1168
1169 storage = self.fs.get_params()
1170 storage["folder"] = proposed_revision_path
yshah2c932bd2024-09-24 18:16:07 +00001171 storage["zipfile"] = filename
yshah53cc9eb2024-07-05 13:06:31 +00001172
1173 file_path = (proposed_revision_path, filename)
1174 file_pkg = self.fs.file_open(file_path, "a+b")
1175
yshah53cc9eb2024-07-05 13:06:31 +00001176 if isinstance(indata, dict):
1177 indata_text = yaml.safe_dump(indata, indent=4, default_flow_style=False)
1178 file_pkg.write(indata_text.encode(encoding="utf-8"))
1179 else:
1180 indata_len = 0
1181 indata = indata.file
1182 while True:
1183 indata_text = indata.read(4096)
1184 indata_len += len(indata_text)
1185 if not indata_text:
1186 break
1187 file_pkg.write(indata_text)
1188
yshah53cc9eb2024-07-05 13:06:31 +00001189 # Need to close the file package here so it can be copied from the
1190 # revision to the current, unrevisioned record
1191 if file_pkg:
1192 file_pkg.close()
1193 file_pkg = None
1194
1195 # Fetch both the incoming, proposed revision and the original revision so we
1196 # can call a validate method to compare them
1197 current_revision_path = _id + "/"
1198 self.fs.sync(from_path=current_revision_path)
1199 self.fs.sync(from_path=proposed_revision_path)
1200
garciadeblas807b8bf2024-09-23 13:03:00 +02001201 # Is this required?
yshah53cc9eb2024-07-05 13:06:31 +00001202 if revision > 1:
1203 try:
1204 self._validate_descriptor_changes(
1205 _id,
1206 filename,
1207 current_revision_path,
1208 proposed_revision_path,
1209 )
1210 except Exception as e:
1211 shutil.rmtree(
1212 self.fs.path + current_revision_path, ignore_errors=True
1213 )
1214 shutil.rmtree(
1215 self.fs.path + proposed_revision_path, ignore_errors=True
1216 )
1217 # Only delete the new revision. We need to keep the original version in place
1218 # as it has not been changed.
1219 self.fs.file_delete(proposed_revision_path, ignore_non_exist=True)
1220 raise e
1221
1222 indata = self._remove_envelop(indata)
1223
1224 # Override descriptor with query string kwargs
1225 if kwargs:
1226 self._update_input_with_kwargs(indata, kwargs)
1227
1228 current_desc["_admin"]["storage"] = storage
1229 current_desc["_admin"]["onboardingState"] = "ONBOARDED"
1230 current_desc["_admin"]["operationalState"] = "ENABLED"
1231 current_desc["_admin"]["modified"] = time()
1232 current_desc["_admin"]["revision"] = revision
1233
1234 deep_update_rfc7396(current_desc, indata)
1235
1236 # Copy the revision to the active package name by its original id
1237 shutil.rmtree(self.fs.path + current_revision_path, ignore_errors=True)
1238 os.rename(
1239 self.fs.path + proposed_revision_path,
1240 self.fs.path + current_revision_path,
1241 )
1242 self.fs.file_delete(current_revision_path, ignore_non_exist=True)
1243 self.fs.mkdir(current_revision_path)
1244 self.fs.reverse_sync(from_path=current_revision_path)
1245
1246 shutil.rmtree(self.fs.path + _id)
1247 kwargs = {}
1248 kwargs["package"] = filename
1249 if headers["Method"] == "POST":
1250 current_desc["state"] = "IN_CREATION"
garciadeblasbecc7052024-11-20 12:04:53 +01001251 op_id = current_desc.get("operationHistory", [{"op_id": None}])[-1].get(
1252 "op_id"
1253 )
yshah53cc9eb2024-07-05 13:06:31 +00001254 elif headers["Method"] in ("PUT", "PATCH"):
yshahd0c876f2024-11-11 09:24:48 +00001255 op_id = self.format_on_operation(
yshah53cc9eb2024-07-05 13:06:31 +00001256 current_desc,
1257 "update",
1258 kwargs,
1259 )
1260 current_desc["operatingState"] = "PROCESSING"
1261 current_desc["resourceState"] = "IN_PROGRESS"
1262
1263 self.db.replace(self.topic, _id, current_desc)
1264
1265 # Store a copy of the package as a point in time revision
1266 revision_desc = dict(current_desc)
1267 revision_desc["_id"] = _id + ":" + str(revision_desc["_admin"]["revision"])
1268 self.db.create(self.topic + "_revisions", revision_desc)
1269 fs_rollback = []
1270
yshah53cc9eb2024-07-05 13:06:31 +00001271 if headers["Method"] == "POST":
1272 self._send_msg("create", {"oka_id": _id, "operation_id": op_id})
1273 elif headers["Method"] == "PUT" or "PATCH":
1274 self._send_msg("edit", {"oka_id": _id, "operation_id": op_id})
1275
1276 return True
1277
1278 except EngineException:
1279 raise
1280 finally:
1281 if file_pkg:
1282 file_pkg.close()
1283 for file in fs_rollback:
1284 self.fs.file_delete(file, ignore_non_exist=True)