Code Coverage

Cobertura Coverage Report > osm_lcm >

vim_sdn.py

Trend

File Coverage summary

NameClassesLinesConditionals
vim_sdn.py
100%
1/1
12%
111/934
100%
0/0

Coverage Breakdown by Class

NameLinesConditionals
vim_sdn.py
12%
111/934
N/A

Source

osm_lcm/vim_sdn.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2018 Telefonica S.A.
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
9 #
10 #         http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
16 # under the License.
17 ##
18
19 1 import yaml
20 1 import asyncio
21 1 import logging
22 1 import logging.handlers
23 1 from osm_lcm import ROclient
24 1 from osm_lcm.lcm_utils import LcmException, LcmBase, deep_get
25 1 from n2vc.k8s_helm_conn import K8sHelmConnector
26 1 from n2vc.k8s_helm3_conn import K8sHelm3Connector
27 1 from n2vc.k8s_juju_conn import K8sJujuConnector
28 1 from n2vc.n2vc_juju_conn import N2VCJujuConnector
29 1 from n2vc.exceptions import K8sException, N2VCException
30 1 from osm_common.dbbase import DbException
31 1 from copy import deepcopy
32 1 from time import time
33
34 1 __author__ = "Alfonso Tierno"
35
36
37 1 class VimLcm(LcmBase):
38     # values that are encrypted at vim config because they are passwords
39 1     vim_config_encrypted = {
40         "1.1": ("admin_password", "nsx_password", "vcenter_password"),
41         "default": (
42             "admin_password",
43             "nsx_password",
44             "vcenter_password",
45             "vrops_password",
46         ),
47     }
48
49 1     def __init__(self, msg, lcm_tasks, config, loop):
50         """
51         Init, Connect to database, filesystem storage, and messaging
52         :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
53         :return: None
54         """
55
56 0         self.logger = logging.getLogger("lcm.vim")
57 0         self.loop = loop
58 0         self.lcm_tasks = lcm_tasks
59 0         self.ro_config = config["RO"]
60
61 0         super().__init__(msg, self.logger)
62
63 1     async def create(self, vim_content, order_id):
64         # HA tasks and backward compatibility:
65         # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
66         # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
67         # Register 'create' task here for related future HA operations
68 0         op_id = vim_content.pop("op_id", None)
69 0         if not self.lcm_tasks.lock_HA("vim", "create", op_id):
70 0             return
71
72 0         vim_id = vim_content["_id"]
73 0         logging_text = "Task vim_create={} ".format(vim_id)
74 0         self.logger.debug(logging_text + "Enter")
75
76 0         db_vim = None
77 0         db_vim_update = {}
78 0         exc = None
79 0         RO_sdn_id = None
80 0         try:
81 0             step = "Getting vim-id='{}' from db".format(vim_id)
82 0             db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
83 0             if vim_content.get("config") and vim_content["config"].get(
84                 "sdn-controller"
85             ):
86 0                 step = "Getting sdn-controller-id='{}' from db".format(
87                     vim_content["config"]["sdn-controller"]
88                 )
89 0                 db_sdn = self.db.get_one(
90                     "sdns", {"_id": vim_content["config"]["sdn-controller"]}
91                 )
92
93                 # If the VIM account has an associated SDN account, also
94                 # wait for any previous tasks in process for the SDN
95 0                 await self.lcm_tasks.waitfor_related_HA("sdn", "ANY", db_sdn["_id"])
96
97 0                 if (
98                     db_sdn.get("_admin")
99                     and db_sdn["_admin"].get("deployed")
100                     and db_sdn["_admin"]["deployed"].get("RO")
101                 ):
102 0                     RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
103                 else:
104 0                     raise LcmException(
105                         "sdn-controller={} is not available. Not deployed at RO".format(
106                             vim_content["config"]["sdn-controller"]
107                         )
108                     )
109
110 0             step = "Creating vim at RO"
111 0             db_vim_update["_admin.deployed.RO"] = None
112 0             db_vim_update["_admin.detailed-status"] = step
113 0             self.update_db_2("vim_accounts", vim_id, db_vim_update)
114 0             RO = ROclient.ROClient(self.loop, **self.ro_config)
115 0             vim_RO = deepcopy(vim_content)
116 0             vim_RO.pop("_id", None)
117 0             vim_RO.pop("_admin", None)
118 0             schema_version = vim_RO.pop("schema_version", None)
119 0             vim_RO.pop("schema_type", None)
120 0             vim_RO.pop("vim_tenant_name", None)
121 0             vim_RO["type"] = vim_RO.pop("vim_type")
122 0             vim_RO.pop("vim_user", None)
123 0             vim_RO.pop("vim_password", None)
124 0             if RO_sdn_id:
125 0                 vim_RO["config"]["sdn-controller"] = RO_sdn_id
126 0             desc = await RO.create("vim", descriptor=vim_RO)
127 0             RO_vim_id = desc["uuid"]
128 0             db_vim_update["_admin.deployed.RO"] = RO_vim_id
129 0             self.logger.debug(
130                 logging_text + "VIM created at RO_vim_id={}".format(RO_vim_id)
131             )
132
133 0             step = "Creating vim_account at RO"
134 0             db_vim_update["_admin.detailed-status"] = step
135 0             self.update_db_2("vim_accounts", vim_id, db_vim_update)
136
137 0             if vim_content.get("vim_password"):
138 0                 vim_content["vim_password"] = self.db.decrypt(
139                     vim_content["vim_password"],
140                     schema_version=schema_version,
141                     salt=vim_id,
142                 )
143 0             vim_account_RO = {
144                 "vim_tenant_name": vim_content["vim_tenant_name"],
145                 "vim_username": vim_content["vim_user"],
146                 "vim_password": vim_content["vim_password"],
147             }
148 0             if vim_RO.get("config"):
149 0                 vim_account_RO["config"] = vim_RO["config"]
150 0                 if "sdn-controller" in vim_account_RO["config"]:
151 0                     del vim_account_RO["config"]["sdn-controller"]
152 0                 if "sdn-port-mapping" in vim_account_RO["config"]:
153 0                     del vim_account_RO["config"]["sdn-port-mapping"]
154 0                 vim_config_encrypted_keys = self.vim_config_encrypted.get(
155                     schema_version
156                 ) or self.vim_config_encrypted.get("default")
157 0                 for p in vim_config_encrypted_keys:
158 0                     if vim_account_RO["config"].get(p):
159 0                         vim_account_RO["config"][p] = self.db.decrypt(
160                             vim_account_RO["config"][p],
161                             schema_version=schema_version,
162                             salt=vim_id,
163                         )
164
165 0             desc = await RO.attach("vim_account", RO_vim_id, descriptor=vim_account_RO)
166 0             db_vim_update["_admin.deployed.RO-account"] = desc["uuid"]
167 0             db_vim_update["_admin.operationalState"] = "ENABLED"
168 0             db_vim_update["_admin.detailed-status"] = "Done"
169             # Mark the VIM 'create' HA task as successful
170 0             operation_state = "COMPLETED"
171 0             operation_details = "Done"
172
173 0             self.logger.debug(
174                 logging_text
175                 + "Exit Ok VIM account created at RO_vim_account_id={}".format(
176                     desc["uuid"]
177                 )
178             )
179 0             return
180
181 0         except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
182 0             self.logger.error(logging_text + "Exit Exception {}".format(e))
183 0             exc = e
184 0         except Exception as e:
185 0             self.logger.critical(
186                 logging_text + "Exit Exception {}".format(e), exc_info=True
187             )
188 0             exc = e
189         finally:
190 0             if exc and db_vim:
191 0                 db_vim_update["_admin.operationalState"] = "ERROR"
192 0                 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
193                     step, exc
194                 )
195                 # Mark the VIM 'create' HA task as erroneous
196 0                 operation_state = "FAILED"
197 0                 operation_details = "ERROR {}: {}".format(step, exc)
198 0             try:
199 0                 if db_vim_update:
200 0                     self.update_db_2("vim_accounts", vim_id, db_vim_update)
201                 # Register the VIM 'create' HA task either
202                 # succesful or erroneous, or do nothing (if legacy NBI)
203 0                 self.lcm_tasks.unlock_HA(
204                     "vim",
205                     "create",
206                     op_id,
207                     operationState=operation_state,
208                     detailed_status=operation_details,
209                 )
210 0             except DbException as e:
211 0                 self.logger.error(logging_text + "Cannot update database: {}".format(e))
212
213 0             self.lcm_tasks.remove("vim_account", vim_id, order_id)
214
215 1     async def edit(self, vim_content, order_id):
216         # HA tasks and backward compatibility:
217         # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
218         # In such a case, HA is not supported by NBI, and the HA check always returns True
219 0         op_id = vim_content.pop("op_id", None)
220 0         if not self.lcm_tasks.lock_HA("vim", "edit", op_id):
221 0             return
222
223 0         vim_id = vim_content["_id"]
224 0         logging_text = "Task vim_edit={} ".format(vim_id)
225 0         self.logger.debug(logging_text + "Enter")
226
227 0         db_vim = None
228 0         exc = None
229 0         RO_sdn_id = None
230 0         RO_vim_id = None
231 0         db_vim_update = {}
232 0         step = "Getting vim-id='{}' from db".format(vim_id)
233 0         try:
234             # wait for any previous tasks in process
235 0             await self.lcm_tasks.waitfor_related_HA("vim", "edit", op_id)
236
237 0             db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
238
239 0             if (
240                 db_vim.get("_admin")
241                 and db_vim["_admin"].get("deployed")
242                 and db_vim["_admin"]["deployed"].get("RO")
243             ):
244 0                 if vim_content.get("config") and vim_content["config"].get(
245                     "sdn-controller"
246                 ):
247 0                     step = "Getting sdn-controller-id='{}' from db".format(
248                         vim_content["config"]["sdn-controller"]
249                     )
250 0                     db_sdn = self.db.get_one(
251                         "sdns", {"_id": vim_content["config"]["sdn-controller"]}
252                     )
253
254                     # If the VIM account has an associated SDN account, also
255                     # wait for any previous tasks in process for the SDN
256 0                     await self.lcm_tasks.waitfor_related_HA("sdn", "ANY", db_sdn["_id"])
257
258 0                     if (
259                         db_sdn.get("_admin")
260                         and db_sdn["_admin"].get("deployed")
261                         and db_sdn["_admin"]["deployed"].get("RO")
262                     ):
263 0                         RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
264                     else:
265 0                         raise LcmException(
266                             "sdn-controller={} is not available. Not deployed at RO".format(
267                                 vim_content["config"]["sdn-controller"]
268                             )
269                         )
270
271 0                 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
272 0                 step = "Editing vim at RO"
273 0                 RO = ROclient.ROClient(self.loop, **self.ro_config)
274 0                 vim_RO = deepcopy(vim_content)
275 0                 vim_RO.pop("_id", None)
276 0                 vim_RO.pop("_admin", None)
277 0                 schema_version = vim_RO.pop("schema_version", None)
278 0                 vim_RO.pop("schema_type", None)
279 0                 vim_RO.pop("vim_tenant_name", None)
280 0                 if "vim_type" in vim_RO:
281 0                     vim_RO["type"] = vim_RO.pop("vim_type")
282 0                 vim_RO.pop("vim_user", None)
283 0                 vim_RO.pop("vim_password", None)
284 0                 if RO_sdn_id:
285 0                     vim_RO["config"]["sdn-controller"] = RO_sdn_id
286                 # TODO make a deep update of sdn-port-mapping
287 0                 if vim_RO:
288 0                     await RO.edit("vim", RO_vim_id, descriptor=vim_RO)
289
290 0                 step = "Editing vim-account at RO tenant"
291 0                 vim_account_RO = {}
292 0                 if "config" in vim_content:
293 0                     if "sdn-controller" in vim_content["config"]:
294 0                         del vim_content["config"]["sdn-controller"]
295 0                     if "sdn-port-mapping" in vim_content["config"]:
296 0                         del vim_content["config"]["sdn-port-mapping"]
297 0                     if not vim_content["config"]:
298 0                         del vim_content["config"]
299 0                 if "vim_tenant_name" in vim_content:
300 0                     vim_account_RO["vim_tenant_name"] = vim_content["vim_tenant_name"]
301 0                 if "vim_password" in vim_content:
302 0                     vim_account_RO["vim_password"] = vim_content["vim_password"]
303 0                 if vim_content.get("vim_password"):
304 0                     vim_account_RO["vim_password"] = self.db.decrypt(
305                         vim_content["vim_password"],
306                         schema_version=schema_version,
307                         salt=vim_id,
308                     )
309 0                 if "config" in vim_content:
310 0                     vim_account_RO["config"] = vim_content["config"]
311 0                 if vim_content.get("config"):
312 0                     vim_config_encrypted_keys = self.vim_config_encrypted.get(
313                         schema_version
314                     ) or self.vim_config_encrypted.get("default")
315 0                     for p in vim_config_encrypted_keys:
316 0                         if vim_content["config"].get(p):
317 0                             vim_account_RO["config"][p] = self.db.decrypt(
318                                 vim_content["config"][p],
319                                 schema_version=schema_version,
320                                 salt=vim_id,
321                             )
322
323 0                 if "vim_user" in vim_content:
324 0                     vim_content["vim_username"] = vim_content["vim_user"]
325                 # vim_account must be edited always even if empty in order to ensure changes are translated to RO
326                 # vim_thread. RO will remove and relaunch a new thread for this vim_account
327 0                 await RO.edit("vim_account", RO_vim_id, descriptor=vim_account_RO)
328 0                 db_vim_update["_admin.operationalState"] = "ENABLED"
329                 # Mark the VIM 'edit' HA task as successful
330 0             operation_state = "COMPLETED"
331 0             operation_details = "Done"
332
333 0             self.logger.debug(logging_text + "Exit Ok RO_vim_id={}".format(RO_vim_id))
334 0             return
335
336 0         except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
337 0             self.logger.error(logging_text + "Exit Exception {}".format(e))
338 0             exc = e
339 0         except Exception as e:
340 0             self.logger.critical(
341                 logging_text + "Exit Exception {}".format(e), exc_info=True
342             )
343 0             exc = e
344         finally:
345 0             if exc and db_vim:
346 0                 db_vim_update["_admin.operationalState"] = "ERROR"
347 0                 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
348                     step, exc
349                 )
350                 # Mark the VIM 'edit' HA task as erroneous
351 0                 operation_state = "FAILED"
352 0                 operation_details = "ERROR {}: {}".format(step, exc)
353 0             try:
354 0                 if db_vim_update:
355 0                     self.update_db_2("vim_accounts", vim_id, db_vim_update)
356                 # Register the VIM 'edit' HA task either
357                 # succesful or erroneous, or do nothing (if legacy NBI)
358 0                 self.lcm_tasks.unlock_HA(
359                     "vim",
360                     "edit",
361                     op_id,
362                     operationState=operation_state,
363                     detailed_status=operation_details,
364                 )
365 0             except DbException as e:
366 0                 self.logger.error(logging_text + "Cannot update database: {}".format(e))
367
368 0             self.lcm_tasks.remove("vim_account", vim_id, order_id)
369
370 1     async def delete(self, vim_content, order_id):
371         # HA tasks and backward compatibility:
372         # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
373         # In such a case, HA is not supported by NBI, and the HA check always returns True
374 0         op_id = vim_content.pop("op_id", None)
375 0         if not self.lcm_tasks.lock_HA("vim", "delete", op_id):
376 0             return
377
378 0         vim_id = vim_content["_id"]
379 0         logging_text = "Task vim_delete={} ".format(vim_id)
380 0         self.logger.debug(logging_text + "Enter")
381
382 0         db_vim = None
383 0         db_vim_update = {}
384 0         exc = None
385 0         step = "Getting vim from db"
386 0         try:
387             # wait for any previous tasks in process
388 0             await self.lcm_tasks.waitfor_related_HA("vim", "delete", op_id)
389 0             if not self.ro_config.get("ng"):
390 0                 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
391 0                 if (
392                     db_vim.get("_admin")
393                     and db_vim["_admin"].get("deployed")
394                     and db_vim["_admin"]["deployed"].get("RO")
395                 ):
396 0                     RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
397 0                     RO = ROclient.ROClient(self.loop, **self.ro_config)
398 0                     step = "Detaching vim from RO tenant"
399 0                     try:
400 0                         await RO.detach("vim_account", RO_vim_id)
401 0                     except ROclient.ROClientException as e:
402 0                         if e.http_code == 404:  # not found
403 0                             self.logger.debug(
404                                 logging_text
405                                 + "RO_vim_id={} already detached".format(RO_vim_id)
406                             )
407                         else:
408 0                             raise
409
410 0                     step = "Deleting vim from RO"
411 0                     try:
412 0                         await RO.delete("vim", RO_vim_id)
413 0                     except ROclient.ROClientException as e:
414 0                         if e.http_code == 404:  # not found
415 0                             self.logger.debug(
416                                 logging_text
417                                 + "RO_vim_id={} already deleted".format(RO_vim_id)
418                             )
419                         else:
420 0                             raise
421                 else:
422                     # nothing to delete
423 0                     self.logger.debug(logging_text + "Nothing to remove at RO")
424 0             self.db.del_one("vim_accounts", {"_id": vim_id})
425 0             db_vim = None
426 0             self.logger.debug(logging_text + "Exit Ok")
427 0             return
428
429 0         except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
430 0             self.logger.error(logging_text + "Exit Exception {}".format(e))
431 0             exc = e
432 0         except Exception as e:
433 0             self.logger.critical(
434                 logging_text + "Exit Exception {}".format(e), exc_info=True
435             )
436 0             exc = e
437         finally:
438 0             self.lcm_tasks.remove("vim_account", vim_id, order_id)
439 0             if exc and db_vim:
440 0                 db_vim_update["_admin.operationalState"] = "ERROR"
441 0                 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
442                     step, exc
443                 )
444                 # Mark the VIM 'delete' HA task as erroneous
445 0                 operation_state = "FAILED"
446 0                 operation_details = "ERROR {}: {}".format(step, exc)
447 0                 self.lcm_tasks.unlock_HA(
448                     "vim",
449                     "delete",
450                     op_id,
451                     operationState=operation_state,
452                     detailed_status=operation_details,
453                 )
454 0             try:
455 0                 if db_vim and db_vim_update:
456 0                     self.update_db_2("vim_accounts", vim_id, db_vim_update)
457                 # If the VIM 'delete' HA task was succesful, the DB entry has been deleted,
458                 # which means that there is nowhere to register this task, so do nothing here.
459 0             except DbException as e:
460 0                 self.logger.error(logging_text + "Cannot update database: {}".format(e))
461 0             self.lcm_tasks.remove("vim_account", vim_id, order_id)
462
463
464 1 class WimLcm(LcmBase):
465     # values that are encrypted at wim config because they are passwords
466 1     wim_config_encrypted = ()
467
468 1     def __init__(self, msg, lcm_tasks, config, loop):
469         """
470         Init, Connect to database, filesystem storage, and messaging
471         :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
472         :return: None
473         """
474
475 0         self.logger = logging.getLogger("lcm.vim")
476 0         self.loop = loop
477 0         self.lcm_tasks = lcm_tasks
478 0         self.ro_config = config["RO"]
479
480 0         super().__init__(msg, self.logger)
481
482 1     async def create(self, wim_content, order_id):
483         # HA tasks and backward compatibility:
484         # If 'wim_content' does not include 'op_id', we a running a legacy NBI version.
485         # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
486         # Register 'create' task here for related future HA operations
487 0         op_id = wim_content.pop("op_id", None)
488 0         self.lcm_tasks.lock_HA("wim", "create", op_id)
489
490 0         wim_id = wim_content["_id"]
491 0         logging_text = "Task wim_create={} ".format(wim_id)
492 0         self.logger.debug(logging_text + "Enter")
493
494 0         db_wim = None
495 0         db_wim_update = {}
496 0         exc = None
497 0         try:
498 0             step = "Getting wim-id='{}' from db".format(wim_id)
499 0             db_wim = self.db.get_one("wim_accounts", {"_id": wim_id})
500 0             db_wim_update["_admin.deployed.RO"] = None
501
502 0             step = "Creating wim at RO"
503 0             db_wim_update["_admin.detailed-status"] = step
504 0             self.update_db_2("wim_accounts", wim_id, db_wim_update)
505 0             RO = ROclient.ROClient(self.loop, **self.ro_config)
506 0             wim_RO = deepcopy(wim_content)
507 0             wim_RO.pop("_id", None)
508 0             wim_RO.pop("_admin", None)
509 0             schema_version = wim_RO.pop("schema_version", None)
510 0             wim_RO.pop("schema_type", None)
511 0             wim_RO.pop("wim_tenant_name", None)
512 0             wim_RO["type"] = wim_RO.pop("wim_type")
513 0             wim_RO.pop("wim_user", None)
514 0             wim_RO.pop("wim_password", None)
515 0             desc = await RO.create("wim", descriptor=wim_RO)
516 0             RO_wim_id = desc["uuid"]
517 0             db_wim_update["_admin.deployed.RO"] = RO_wim_id
518 0             self.logger.debug(
519                 logging_text + "WIM created at RO_wim_id={}".format(RO_wim_id)
520             )
521
522 0             step = "Creating wim_account at RO"
523 0             db_wim_update["_admin.detailed-status"] = step
524 0             self.update_db_2("wim_accounts", wim_id, db_wim_update)
525
526 0             if wim_content.get("wim_password"):
527 0                 wim_content["wim_password"] = self.db.decrypt(
528                     wim_content["wim_password"],
529                     schema_version=schema_version,
530                     salt=wim_id,
531                 )
532 0             wim_account_RO = {
533                 "name": wim_content["name"],
534                 "user": wim_content["user"],
535                 "password": wim_content["password"],
536             }
537 0             if wim_RO.get("config"):
538 0                 wim_account_RO["config"] = wim_RO["config"]
539 0                 if "wim_port_mapping" in wim_account_RO["config"]:
540 0                     del wim_account_RO["config"]["wim_port_mapping"]
541 0                 for p in self.wim_config_encrypted:
542 0                     if wim_account_RO["config"].get(p):
543 0                         wim_account_RO["config"][p] = self.db.decrypt(
544                             wim_account_RO["config"][p],
545                             schema_version=schema_version,
546                             salt=wim_id,
547                         )
548
549 0             desc = await RO.attach("wim_account", RO_wim_id, descriptor=wim_account_RO)
550 0             db_wim_update["_admin.deployed.RO-account"] = desc["uuid"]
551 0             db_wim_update["_admin.operationalState"] = "ENABLED"
552 0             db_wim_update["_admin.detailed-status"] = "Done"
553             # Mark the WIM 'create' HA task as successful
554 0             operation_state = "COMPLETED"
555 0             operation_details = "Done"
556
557 0             self.logger.debug(
558                 logging_text
559                 + "Exit Ok WIM account created at RO_wim_account_id={}".format(
560                     desc["uuid"]
561                 )
562             )
563 0             return
564
565 0         except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
566 0             self.logger.error(logging_text + "Exit Exception {}".format(e))
567 0             exc = e
568 0         except Exception as e:
569 0             self.logger.critical(
570                 logging_text + "Exit Exception {}".format(e), exc_info=True
571             )
572 0             exc = e
573         finally:
574 0             if exc and db_wim:
575 0                 db_wim_update["_admin.operationalState"] = "ERROR"
576 0                 db_wim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
577                     step, exc
578                 )
579                 # Mark the WIM 'create' HA task as erroneous
580 0                 operation_state = "FAILED"
581 0                 operation_details = "ERROR {}: {}".format(step, exc)
582 0             try:
583 0                 if db_wim_update:
584 0                     self.update_db_2("wim_accounts", wim_id, db_wim_update)
585                 # Register the WIM 'create' HA task either
586                 # succesful or erroneous, or do nothing (if legacy NBI)
587 0                 self.lcm_tasks.unlock_HA(
588                     "wim",
589                     "create",
590                     op_id,
591                     operationState=operation_state,
592                     detailed_status=operation_details,
593                 )
594 0             except DbException as e:
595 0                 self.logger.error(logging_text + "Cannot update database: {}".format(e))
596 0             self.lcm_tasks.remove("wim_account", wim_id, order_id)
597
598 1     async def edit(self, wim_content, order_id):
599         # HA tasks and backward compatibility:
600         # If 'wim_content' does not include 'op_id', we a running a legacy NBI version.
601         # In such a case, HA is not supported by NBI, and the HA check always returns True
602 0         op_id = wim_content.pop("op_id", None)
603 0         if not self.lcm_tasks.lock_HA("wim", "edit", op_id):
604 0             return
605
606 0         wim_id = wim_content["_id"]
607 0         logging_text = "Task wim_edit={} ".format(wim_id)
608 0         self.logger.debug(logging_text + "Enter")
609
610 0         db_wim = None
611 0         exc = None
612 0         RO_wim_id = None
613 0         db_wim_update = {}
614 0         step = "Getting wim-id='{}' from db".format(wim_id)
615 0         try:
616             # wait for any previous tasks in process
617 0             await self.lcm_tasks.waitfor_related_HA("wim", "edit", op_id)
618
619 0             db_wim = self.db.get_one("wim_accounts", {"_id": wim_id})
620
621 0             if (
622                 db_wim.get("_admin")
623                 and db_wim["_admin"].get("deployed")
624                 and db_wim["_admin"]["deployed"].get("RO")
625             ):
626 0                 RO_wim_id = db_wim["_admin"]["deployed"]["RO"]
627 0                 step = "Editing wim at RO"
628 0                 RO = ROclient.ROClient(self.loop, **self.ro_config)
629 0                 wim_RO = deepcopy(wim_content)
630 0                 wim_RO.pop("_id", None)
631 0                 wim_RO.pop("_admin", None)
632 0                 schema_version = wim_RO.pop("schema_version", None)
633 0                 wim_RO.pop("schema_type", None)
634 0                 wim_RO.pop("wim_tenant_name", None)
635 0                 if "wim_type" in wim_RO:
636 0                     wim_RO["type"] = wim_RO.pop("wim_type")
637 0                 wim_RO.pop("wim_user", None)
638 0                 wim_RO.pop("wim_password", None)
639                 # TODO make a deep update of wim_port_mapping
640 0                 if wim_RO:
641 0                     await RO.edit("wim", RO_wim_id, descriptor=wim_RO)
642
643 0                 step = "Editing wim-account at RO tenant"
644 0                 wim_account_RO = {}
645 0                 if "config" in wim_content:
646 0                     if "wim_port_mapping" in wim_content["config"]:
647 0                         del wim_content["config"]["wim_port_mapping"]
648 0                     if not wim_content["config"]:
649 0                         del wim_content["config"]
650 0                 if "wim_tenant_name" in wim_content:
651 0                     wim_account_RO["wim_tenant_name"] = wim_content["wim_tenant_name"]
652 0                 if "wim_password" in wim_content:
653 0                     wim_account_RO["wim_password"] = wim_content["wim_password"]
654 0                 if wim_content.get("wim_password"):
655 0                     wim_account_RO["wim_password"] = self.db.decrypt(
656                         wim_content["wim_password"],
657                         schema_version=schema_version,
658                         salt=wim_id,
659                     )
660 0                 if "config" in wim_content:
661 0                     wim_account_RO["config"] = wim_content["config"]
662 0                 if wim_content.get("config"):
663 0                     for p in self.wim_config_encrypted:
664 0                         if wim_content["config"].get(p):
665 0                             wim_account_RO["config"][p] = self.db.decrypt(
666                                 wim_content["config"][p],
667                                 schema_version=schema_version,
668                                 salt=wim_id,
669                             )
670
671 0                 if "wim_user" in wim_content:
672 0                     wim_content["wim_username"] = wim_content["wim_user"]
673                 # wim_account must be edited always even if empty in order to ensure changes are translated to RO
674                 # wim_thread. RO will remove and relaunch a new thread for this wim_account
675 0                 await RO.edit("wim_account", RO_wim_id, descriptor=wim_account_RO)
676 0                 db_wim_update["_admin.operationalState"] = "ENABLED"
677                 # Mark the WIM 'edit' HA task as successful
678 0             operation_state = "COMPLETED"
679 0             operation_details = "Done"
680
681 0             self.logger.debug(logging_text + "Exit Ok RO_wim_id={}".format(RO_wim_id))
682 0             return
683
684 0         except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
685 0             self.logger.error(logging_text + "Exit Exception {}".format(e))
686 0             exc = e
687 0         except Exception as e:
688 0             self.logger.critical(
689                 logging_text + "Exit Exception {}".format(e), exc_info=True
690             )
691 0             exc = e
692         finally:
693 0             if exc and db_wim:
694 0                 db_wim_update["_admin.operationalState"] = "ERROR"
695 0                 db_wim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
696                     step, exc
697                 )
698                 # Mark the WIM 'edit' HA task as erroneous
699 0                 operation_state = "FAILED"
700 0                 operation_details = "ERROR {}: {}".format(step, exc)
701 0             try:
702 0                 if db_wim_update:
703 0                     self.update_db_2("wim_accounts", wim_id, db_wim_update)
704                 # Register the WIM 'edit' HA task either
705                 # succesful or erroneous, or do nothing (if legacy NBI)
706 0                 self.lcm_tasks.unlock_HA(
707                     "wim",
708                     "edit",
709                     op_id,
710                     operationState=operation_state,
711                     detailed_status=operation_details,
712                 )
713 0             except DbException as e:
714 0                 self.logger.error(logging_text + "Cannot update database: {}".format(e))
715 0             self.lcm_tasks.remove("wim_account", wim_id, order_id)
716
717 1     async def delete(self, wim_content, order_id):
718         # HA tasks and backward compatibility:
719         # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
720         # In such a case, HA is not supported by NBI, and the HA check always returns True
721 0         op_id = wim_content.pop("op_id", None)
722 0         if not self.lcm_tasks.lock_HA("wim", "delete", op_id):
723 0             return
724
725 0         wim_id = wim_content["_id"]
726 0         logging_text = "Task wim_delete={} ".format(wim_id)
727 0         self.logger.debug(logging_text + "Enter")
728
729 0         db_wim = None
730 0         db_wim_update = {}
731 0         exc = None
732 0         step = "Getting wim from db"
733 0         try:
734             # wait for any previous tasks in process
735 0             await self.lcm_tasks.waitfor_related_HA("wim", "delete", op_id)
736
737 0             db_wim = self.db.get_one("wim_accounts", {"_id": wim_id})
738 0             if (
739                 db_wim.get("_admin")
740                 and db_wim["_admin"].get("deployed")
741                 and db_wim["_admin"]["deployed"].get("RO")
742             ):
743 0                 RO_wim_id = db_wim["_admin"]["deployed"]["RO"]
744 0                 RO = ROclient.ROClient(self.loop, **self.ro_config)
745 0                 step = "Detaching wim from RO tenant"
746 0                 try:
747 0                     await RO.detach("wim_account", RO_wim_id)
748 0                 except ROclient.ROClientException as e:
749 0                     if e.http_code == 404:  # not found
750 0                         self.logger.debug(
751                             logging_text
752                             + "RO_wim_id={} already detached".format(RO_wim_id)
753                         )
754                     else:
755 0                         raise
756
757 0                 step = "Deleting wim from RO"
758 0                 try:
759 0                     await RO.delete("wim", RO_wim_id)
760 0                 except ROclient.ROClientException as e:
761 0                     if e.http_code == 404:  # not found
762 0                         self.logger.debug(
763                             logging_text
764                             + "RO_wim_id={} already deleted".format(RO_wim_id)
765                         )
766                     else:
767 0                         raise
768             else:
769                 # nothing to delete
770 0                 self.logger.error(logging_text + "Nothing to remove at RO")
771 0             self.db.del_one("wim_accounts", {"_id": wim_id})
772 0             db_wim = None
773 0             self.logger.debug(logging_text + "Exit Ok")
774 0             return
775
776 0         except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
777 0             self.logger.error(logging_text + "Exit Exception {}".format(e))
778 0             exc = e
779 0         except Exception as e:
780 0             self.logger.critical(
781                 logging_text + "Exit Exception {}".format(e), exc_info=True
782             )
783 0             exc = e
784         finally:
785 0             self.lcm_tasks.remove("wim_account", wim_id, order_id)
786 0             if exc and db_wim:
787 0                 db_wim_update["_admin.operationalState"] = "ERROR"
788 0                 db_wim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
789                     step, exc
790                 )
791                 # Mark the WIM 'delete' HA task as erroneous
792 0                 operation_state = "FAILED"
793 0                 operation_details = "ERROR {}: {}".format(step, exc)
794 0                 self.lcm_tasks.unlock_HA(
795                     "wim",
796                     "delete",
797                     op_id,
798                     operationState=operation_state,
799                     detailed_status=operation_details,
800                 )
801 0             try:
802 0                 if db_wim and db_wim_update:
803 0                     self.update_db_2("wim_accounts", wim_id, db_wim_update)
804                 # If the WIM 'delete' HA task was succesful, the DB entry has been deleted,
805                 # which means that there is nowhere to register this task, so do nothing here.
806 0             except DbException as e:
807 0                 self.logger.error(logging_text + "Cannot update database: {}".format(e))
808 0             self.lcm_tasks.remove("wim_account", wim_id, order_id)
809
810
811 1 class SdnLcm(LcmBase):
812 1     def __init__(self, msg, lcm_tasks, config, loop):
813         """
814         Init, Connect to database, filesystem storage, and messaging
815         :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
816         :return: None
817         """
818
819 0         self.logger = logging.getLogger("lcm.sdn")
820 0         self.loop = loop
821 0         self.lcm_tasks = lcm_tasks
822 0         self.ro_config = config["RO"]
823
824 0         super().__init__(msg, self.logger)
825
826 1     async def create(self, sdn_content, order_id):
827         # HA tasks and backward compatibility:
828         # If 'sdn_content' does not include 'op_id', we a running a legacy NBI version.
829         # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
830         # Register 'create' task here for related future HA operations
831 0         op_id = sdn_content.pop("op_id", None)
832 0         self.lcm_tasks.lock_HA("sdn", "create", op_id)
833
834 0         sdn_id = sdn_content["_id"]
835 0         logging_text = "Task sdn_create={} ".format(sdn_id)
836 0         self.logger.debug(logging_text + "Enter")
837
838 0         db_sdn = None
839 0         db_sdn_update = {}
840 0         RO_sdn_id = None
841 0         exc = None
842 0         try:
843 0             step = "Getting sdn from db"
844 0             db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
845 0             db_sdn_update["_admin.deployed.RO"] = None
846
847 0             step = "Creating sdn at RO"
848 0             db_sdn_update["_admin.detailed-status"] = step
849 0             self.update_db_2("sdns", sdn_id, db_sdn_update)
850
851 0             RO = ROclient.ROClient(self.loop, **self.ro_config)
852 0             sdn_RO = deepcopy(sdn_content)
853 0             sdn_RO.pop("_id", None)
854 0             sdn_RO.pop("_admin", None)
855 0             schema_version = sdn_RO.pop("schema_version", None)
856 0             sdn_RO.pop("schema_type", None)
857 0             sdn_RO.pop("description", None)
858 0             if sdn_RO.get("password"):
859 0                 sdn_RO["password"] = self.db.decrypt(
860                     sdn_RO["password"], schema_version=schema_version, salt=sdn_id
861                 )
862
863 0             desc = await RO.create("sdn", descriptor=sdn_RO)
864 0             RO_sdn_id = desc["uuid"]
865 0             db_sdn_update["_admin.deployed.RO"] = RO_sdn_id
866 0             db_sdn_update["_admin.operationalState"] = "ENABLED"
867 0             self.logger.debug(logging_text + "Exit Ok RO_sdn_id={}".format(RO_sdn_id))
868             # Mark the SDN 'create' HA task as successful
869 0             operation_state = "COMPLETED"
870 0             operation_details = "Done"
871 0             return
872
873 0         except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
874 0             self.logger.error(logging_text + "Exit Exception {}".format(e))
875 0             exc = e
876 0         except Exception as e:
877 0             self.logger.critical(
878                 logging_text + "Exit Exception {}".format(e), exc_info=True
879             )
880 0             exc = e
881         finally:
882 0             if exc and db_sdn:
883 0                 db_sdn_update["_admin.operationalState"] = "ERROR"
884 0                 db_sdn_update["_admin.detailed-status"] = "ERROR {}: {}".format(
885                     step, exc
886                 )
887                 # Mark the SDN 'create' HA task as erroneous
888 0                 operation_state = "FAILED"
889 0                 operation_details = "ERROR {}: {}".format(step, exc)
890 0             try:
891 0                 if db_sdn and db_sdn_update:
892 0                     self.update_db_2("sdns", sdn_id, db_sdn_update)
893                 # Register the SDN 'create' HA task either
894                 # succesful or erroneous, or do nothing (if legacy NBI)
895 0                 self.lcm_tasks.unlock_HA(
896                     "sdn",
897                     "create",
898                     op_id,
899                     operationState=operation_state,
900                     detailed_status=operation_details,
901                 )
902 0             except DbException as e:
903 0                 self.logger.error(logging_text + "Cannot update database: {}".format(e))
904 0             self.lcm_tasks.remove("sdn", sdn_id, order_id)
905
906 1     async def edit(self, sdn_content, order_id):
907         # HA tasks and backward compatibility:
908         # If 'sdn_content' does not include 'op_id', we a running a legacy NBI version.
909         # In such a case, HA is not supported by NBI, and the HA check always returns True
910 0         op_id = sdn_content.pop("op_id", None)
911 0         if not self.lcm_tasks.lock_HA("sdn", "edit", op_id):
912 0             return
913
914 0         sdn_id = sdn_content["_id"]
915 0         logging_text = "Task sdn_edit={} ".format(sdn_id)
916 0         self.logger.debug(logging_text + "Enter")
917
918 0         db_sdn = None
919 0         db_sdn_update = {}
920 0         exc = None
921 0         step = "Getting sdn from db"
922 0         try:
923             # wait for any previous tasks in process
924 0             await self.lcm_tasks.waitfor_related_HA("sdn", "edit", op_id)
925
926 0             db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
927 0             RO_sdn_id = None
928 0             if (
929                 db_sdn.get("_admin")
930                 and db_sdn["_admin"].get("deployed")
931                 and db_sdn["_admin"]["deployed"].get("RO")
932             ):
933 0                 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
934 0                 RO = ROclient.ROClient(self.loop, **self.ro_config)
935 0                 step = "Editing sdn at RO"
936 0                 sdn_RO = deepcopy(sdn_content)
937 0                 sdn_RO.pop("_id", None)
938 0                 sdn_RO.pop("_admin", None)
939 0                 schema_version = sdn_RO.pop("schema_version", None)
940 0                 sdn_RO.pop("schema_type", None)
941 0                 sdn_RO.pop("description", None)
942 0                 if sdn_RO.get("password"):
943 0                     sdn_RO["password"] = self.db.decrypt(
944                         sdn_RO["password"], schema_version=schema_version, salt=sdn_id
945                     )
946 0                 if sdn_RO:
947 0                     await RO.edit("sdn", RO_sdn_id, descriptor=sdn_RO)
948 0                 db_sdn_update["_admin.operationalState"] = "ENABLED"
949                 # Mark the SDN 'edit' HA task as successful
950 0             operation_state = "COMPLETED"
951 0             operation_details = "Done"
952
953 0             self.logger.debug(logging_text + "Exit Ok RO_sdn_id={}".format(RO_sdn_id))
954 0             return
955
956 0         except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
957 0             self.logger.error(logging_text + "Exit Exception {}".format(e))
958 0             exc = e
959 0         except Exception as e:
960 0             self.logger.critical(
961                 logging_text + "Exit Exception {}".format(e), exc_info=True
962             )
963 0             exc = e
964         finally:
965 0             if exc and db_sdn:
966 0                 db_sdn["_admin.operationalState"] = "ERROR"
967 0                 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
968                 # Mark the SDN 'edit' HA task as erroneous
969 0                 operation_state = "FAILED"
970 0                 operation_details = "ERROR {}: {}".format(step, exc)
971 0             try:
972 0                 if db_sdn_update:
973 0                     self.update_db_2("sdns", sdn_id, db_sdn_update)
974                 # Register the SDN 'edit' HA task either
975                 # succesful or erroneous, or do nothing (if legacy NBI)
976 0                 self.lcm_tasks.unlock_HA(
977                     "sdn",
978                     "edit",
979                     op_id,
980                     operationState=operation_state,
981                     detailed_status=operation_details,
982                 )
983 0             except DbException as e:
984 0                 self.logger.error(logging_text + "Cannot update database: {}".format(e))
985 0             self.lcm_tasks.remove("sdn", sdn_id, order_id)
986
987 1     async def delete(self, sdn_content, order_id):
988         # HA tasks and backward compatibility:
989         # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
990         # In such a case, HA is not supported by NBI, and the HA check always returns True
991 0         op_id = sdn_content.pop("op_id", None)
992 0         if not self.lcm_tasks.lock_HA("sdn", "delete", op_id):
993 0             return
994
995 0         sdn_id = sdn_content["_id"]
996 0         logging_text = "Task sdn_delete={} ".format(sdn_id)
997 0         self.logger.debug(logging_text + "Enter")
998
999 0         db_sdn = None
1000 0         db_sdn_update = {}
1001 0         exc = None
1002 0         step = "Getting sdn from db"
1003 0         try:
1004             # wait for any previous tasks in process
1005 0             await self.lcm_tasks.waitfor_related_HA("sdn", "delete", op_id)
1006
1007 0             db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
1008 0             if (
1009                 db_sdn.get("_admin")
1010                 and db_sdn["_admin"].get("deployed")
1011                 and db_sdn["_admin"]["deployed"].get("RO")
1012             ):
1013 0                 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
1014 0                 RO = ROclient.ROClient(self.loop, **self.ro_config)
1015 0                 step = "Deleting sdn from RO"
1016 0                 try:
1017 0                     await RO.delete("sdn", RO_sdn_id)
1018 0                 except ROclient.ROClientException as e:
1019 0                     if e.http_code == 404:  # not found
1020 0                         self.logger.debug(
1021                             logging_text
1022                             + "RO_sdn_id={} already deleted".format(RO_sdn_id)
1023                         )
1024                     else:
1025 0                         raise
1026             else:
1027                 # nothing to delete
1028 0                 self.logger.error(
1029                     logging_text + "Skipping. There is not RO information at database"
1030                 )
1031 0             self.db.del_one("sdns", {"_id": sdn_id})
1032 0             db_sdn = None
1033 0             self.logger.debug("sdn_delete task sdn_id={} Exit Ok".format(sdn_id))
1034 0             return
1035
1036 0         except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
1037 0             self.logger.error(logging_text + "Exit Exception {}".format(e))
1038 0             exc = e
1039 0         except Exception as e:
1040 0             self.logger.critical(
1041                 logging_text + "Exit Exception {}".format(e), exc_info=True
1042             )
1043 0             exc = e
1044         finally:
1045 0             if exc and db_sdn:
1046 0                 db_sdn["_admin.operationalState"] = "ERROR"
1047 0                 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
1048                 # Mark the SDN 'delete' HA task as erroneous
1049 0                 operation_state = "FAILED"
1050 0                 operation_details = "ERROR {}: {}".format(step, exc)
1051 0                 self.lcm_tasks.unlock_HA(
1052                     "sdn",
1053                     "delete",
1054                     op_id,
1055                     operationState=operation_state,
1056                     detailed_status=operation_details,
1057                 )
1058 0             try:
1059 0                 if db_sdn and db_sdn_update:
1060 0                     self.update_db_2("sdns", sdn_id, db_sdn_update)
1061                 # If the SDN 'delete' HA task was succesful, the DB entry has been deleted,
1062                 # which means that there is nowhere to register this task, so do nothing here.
1063 0             except DbException as e:
1064 0                 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1065 0             self.lcm_tasks.remove("sdn", sdn_id, order_id)
1066
1067
1068 1 class K8sClusterLcm(LcmBase):
1069 1     timeout_create = 300
1070
1071 1     def __init__(self, msg, lcm_tasks, config, loop):
1072         """
1073         Init, Connect to database, filesystem storage, and messaging
1074         :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
1075         :return: None
1076         """
1077
1078 0         self.logger = logging.getLogger("lcm.k8scluster")
1079 0         self.loop = loop
1080 0         self.lcm_tasks = lcm_tasks
1081 0         self.vca_config = config["VCA"]
1082
1083 0         super().__init__(msg, self.logger)
1084
1085 0         self.helm2_k8scluster = K8sHelmConnector(
1086             kubectl_command=self.vca_config.get("kubectlpath"),
1087             helm_command=self.vca_config.get("helmpath"),
1088             log=self.logger,
1089             on_update_db=None,
1090             db=self.db,
1091             fs=self.fs,
1092         )
1093
1094 0         self.helm3_k8scluster = K8sHelm3Connector(
1095             kubectl_command=self.vca_config.get("kubectlpath"),
1096             helm_command=self.vca_config.get("helm3path"),
1097             fs=self.fs,
1098             log=self.logger,
1099             db=self.db,
1100             on_update_db=None,
1101         )
1102
1103 0         self.juju_k8scluster = K8sJujuConnector(
1104             kubectl_command=self.vca_config.get("kubectlpath"),
1105             juju_command=self.vca_config.get("jujupath"),
1106             log=self.logger,
1107             loop=self.loop,
1108             on_update_db=None,
1109             db=self.db,
1110             fs=self.fs,
1111         )
1112
1113 0         self.k8s_map = {
1114             "helm-chart": self.helm2_k8scluster,
1115             "helm-chart-v3": self.helm3_k8scluster,
1116             "juju-bundle": self.juju_k8scluster,
1117         }
1118
1119 1     async def create(self, k8scluster_content, order_id):
1120 0         op_id = k8scluster_content.pop("op_id", None)
1121 0         if not self.lcm_tasks.lock_HA("k8scluster", "create", op_id):
1122 0             return
1123
1124 0         k8scluster_id = k8scluster_content["_id"]
1125 0         logging_text = "Task k8scluster_create={} ".format(k8scluster_id)
1126 0         self.logger.debug(logging_text + "Enter")
1127
1128 0         db_k8scluster = None
1129 0         db_k8scluster_update = {}
1130 0         exc = None
1131 0         try:
1132 0             step = "Getting k8scluster-id='{}' from db".format(k8scluster_id)
1133 0             self.logger.debug(logging_text + step)
1134 0             db_k8scluster = self.db.get_one("k8sclusters", {"_id": k8scluster_id})
1135 0             self.db.encrypt_decrypt_fields(
1136                 db_k8scluster.get("credentials"),
1137                 "decrypt",
1138                 ["password", "secret"],
1139                 schema_version=db_k8scluster["schema_version"],
1140                 salt=db_k8scluster["_id"],
1141             )
1142 0             k8s_credentials = yaml.safe_dump(db_k8scluster.get("credentials"))
1143 0             pending_tasks = []
1144 0             task2name = {}
1145 0             init_target = deep_get(db_k8scluster, ("_admin", "init"))
1146 0             step = "Launching k8scluster init tasks"
1147
1148 0             k8s_deploy_methods = db_k8scluster.get("deployment_methods", {})
1149             # for backwards compatibility and all-false case
1150 0             if not any(k8s_deploy_methods.values()):
1151 0                 k8s_deploy_methods = {
1152                     "helm-chart": True,
1153                     "juju-bundle": True,
1154                     "helm-chart-v3": True,
1155                 }
1156 0             deploy_methods = tuple(filter(k8s_deploy_methods.get, k8s_deploy_methods))
1157
1158 0             for task_name in deploy_methods:
1159 0                 if init_target and task_name not in init_target:
1160 0                     continue
1161 0                 task = asyncio.ensure_future(
1162                     self.k8s_map[task_name].init_env(
1163                         k8s_credentials,
1164                         reuse_cluster_uuid=k8scluster_id,
1165                         vca_id=db_k8scluster.get("vca_id"),
1166                     )
1167                 )
1168 0                 pending_tasks.append(task)
1169 0                 task2name[task] = task_name
1170
1171 0             error_text_list = []
1172 0             tasks_name_ok = []
1173 0             reached_timeout = False
1174 0             now = time()
1175
1176 0             while pending_tasks:
1177 0                 _timeout = max(
1178                     1, self.timeout_create - (time() - now)
1179                 )  # ensure not negative with max
1180 0                 step = "Waiting for k8scluster init tasks"
1181 0                 done, pending_tasks = await asyncio.wait(
1182                     pending_tasks, timeout=_timeout, return_when=asyncio.FIRST_COMPLETED
1183                 )
1184 0                 if not done:
1185                     # timeout. Set timeout is reached and process pending as if they hase been finished
1186 0                     done = pending_tasks
1187 0                     pending_tasks = None
1188 0                     reached_timeout = True
1189 0                 for task in done:
1190 0                     task_name = task2name[task]
1191 0                     if reached_timeout:
1192 0                         exc = "Timeout"
1193 0                     elif task.cancelled():
1194 0                         exc = "Cancelled"
1195                     else:
1196 0                         exc = task.exception()
1197
1198 0                     if exc:
1199 0                         error_text_list.append(
1200                             "Failing init {}: {}".format(task_name, exc)
1201                         )
1202 0                         db_k8scluster_update[
1203                             "_admin.{}.error_msg".format(task_name)
1204                         ] = str(exc)
1205 0                         db_k8scluster_update["_admin.{}.id".format(task_name)] = None
1206 0                         db_k8scluster_update[
1207                             "_admin.{}.operationalState".format(task_name)
1208                         ] = "ERROR"
1209 0                         self.logger.error(
1210                             logging_text + "{} init fail: {}".format(task_name, exc),
1211                             exc_info=not isinstance(exc, (N2VCException, str)),
1212                         )
1213                     else:
1214 0                         k8s_id, uninstall_sw = task.result()
1215 0                         tasks_name_ok.append(task_name)
1216 0                         self.logger.debug(
1217                             logging_text
1218                             + "{} init success. id={} created={}".format(
1219                                 task_name, k8s_id, uninstall_sw
1220                             )
1221                         )
1222 0                         db_k8scluster_update[
1223                             "_admin.{}.error_msg".format(task_name)
1224                         ] = None
1225 0                         db_k8scluster_update["_admin.{}.id".format(task_name)] = k8s_id
1226 0                         db_k8scluster_update[
1227                             "_admin.{}.created".format(task_name)
1228                         ] = uninstall_sw
1229 0                         db_k8scluster_update[
1230                             "_admin.{}.operationalState".format(task_name)
1231                         ] = "ENABLED"
1232                 # update database
1233 0                 step = "Updating database for " + task_name
1234 0                 self.update_db_2("k8sclusters", k8scluster_id, db_k8scluster_update)
1235 0             if tasks_name_ok:
1236 0                 operation_details = "ready for " + ", ".join(tasks_name_ok)
1237 0                 operation_state = "COMPLETED"
1238 0                 db_k8scluster_update["_admin.operationalState"] = (
1239                     "ENABLED" if not error_text_list else "DEGRADED"
1240                 )
1241 0                 operation_details += "; " + ";".join(error_text_list)
1242             else:
1243 0                 db_k8scluster_update["_admin.operationalState"] = "ERROR"
1244 0                 operation_state = "FAILED"
1245 0                 operation_details = ";".join(error_text_list)
1246 0             db_k8scluster_update["_admin.detailed-status"] = operation_details
1247 0             self.logger.debug(logging_text + "Done. Result: " + operation_state)
1248 0             exc = None
1249
1250 0         except Exception as e:
1251 0             if isinstance(
1252                 e,
1253                 (
1254                     LcmException,
1255                     DbException,
1256                     K8sException,
1257                     N2VCException,
1258                     asyncio.CancelledError,
1259                 ),
1260             ):
1261 0                 self.logger.error(logging_text + "Exit Exception {}".format(e))
1262             else:
1263 0                 self.logger.critical(
1264                     logging_text + "Exit Exception {}".format(e), exc_info=True
1265                 )
1266 0             exc = e
1267         finally:
1268 0             if exc and db_k8scluster:
1269 0                 db_k8scluster_update["_admin.operationalState"] = "ERROR"
1270 0                 db_k8scluster_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1271                     step, exc
1272                 )
1273 0                 operation_state = "FAILED"
1274 0                 operation_details = "ERROR {}: {}".format(step, exc)
1275 0             try:
1276 0                 if db_k8scluster and db_k8scluster_update:
1277 0                     self.update_db_2("k8sclusters", k8scluster_id, db_k8scluster_update)
1278
1279                 # Register the operation and unlock
1280 0                 self.lcm_tasks.unlock_HA(
1281                     "k8scluster",
1282                     "create",
1283                     op_id,
1284                     operationState=operation_state,
1285                     detailed_status=operation_details,
1286                 )
1287 0             except DbException as e:
1288 0                 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1289 0             self.lcm_tasks.remove("k8scluster", k8scluster_id, order_id)
1290
1291 1     async def delete(self, k8scluster_content, order_id):
1292         # HA tasks and backward compatibility:
1293         # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
1294         # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
1295         # Register 'delete' task here for related future HA operations
1296 0         op_id = k8scluster_content.pop("op_id", None)
1297 0         if not self.lcm_tasks.lock_HA("k8scluster", "delete", op_id):
1298 0             return
1299
1300 0         k8scluster_id = k8scluster_content["_id"]
1301 0         logging_text = "Task k8scluster_delete={} ".format(k8scluster_id)
1302 0         self.logger.debug(logging_text + "Enter")
1303
1304 0         db_k8scluster = None
1305 0         db_k8scluster_update = {}
1306 0         exc = None
1307 0         try:
1308 0             step = "Getting k8scluster='{}' from db".format(k8scluster_id)
1309 0             self.logger.debug(logging_text + step)
1310 0             db_k8scluster = self.db.get_one("k8sclusters", {"_id": k8scluster_id})
1311 0             k8s_hc_id = deep_get(db_k8scluster, ("_admin", "helm-chart", "id"))
1312 0             k8s_h3c_id = deep_get(db_k8scluster, ("_admin", "helm-chart-v3", "id"))
1313 0             k8s_jb_id = deep_get(db_k8scluster, ("_admin", "juju-bundle", "id"))
1314
1315 0             cluster_removed = True
1316 0             if k8s_jb_id:  # delete in reverse order of creation
1317 0                 step = "Removing juju-bundle '{}'".format(k8s_jb_id)
1318 0                 uninstall_sw = (
1319                     deep_get(db_k8scluster, ("_admin", "juju-bundle", "created"))
1320                     or False
1321                 )
1322 0                 cluster_removed = await self.juju_k8scluster.reset(
1323                     cluster_uuid=k8s_jb_id,
1324                     uninstall_sw=uninstall_sw,
1325                     vca_id=db_k8scluster.get("vca_id"),
1326                 )
1327 0                 db_k8scluster_update["_admin.juju-bundle.id"] = None
1328 0                 db_k8scluster_update["_admin.juju-bundle.operationalState"] = "DISABLED"
1329
1330 0             if k8s_hc_id:
1331 0                 step = "Removing helm-chart '{}'".format(k8s_hc_id)
1332 0                 uninstall_sw = (
1333                     deep_get(db_k8scluster, ("_admin", "helm-chart", "created"))
1334                     or False
1335                 )
1336 0                 cluster_removed = await self.helm2_k8scluster.reset(
1337                     cluster_uuid=k8s_hc_id, uninstall_sw=uninstall_sw
1338                 )
1339 0                 db_k8scluster_update["_admin.helm-chart.id"] = None
1340 0                 db_k8scluster_update["_admin.helm-chart.operationalState"] = "DISABLED"
1341
1342 0             if k8s_h3c_id:
1343 0                 step = "Removing helm-chart-v3 '{}'".format(k8s_hc_id)
1344 0                 uninstall_sw = (
1345                     deep_get(db_k8scluster, ("_admin", "helm-chart-v3", "created"))
1346                     or False
1347                 )
1348 0                 cluster_removed = await self.helm3_k8scluster.reset(
1349                     cluster_uuid=k8s_h3c_id, uninstall_sw=uninstall_sw
1350                 )
1351 0                 db_k8scluster_update["_admin.helm-chart-v3.id"] = None
1352 0                 db_k8scluster_update[
1353                     "_admin.helm-chart-v3.operationalState"
1354                 ] = "DISABLED"
1355
1356             # Try to remove from cluster_inserted to clean old versions
1357 0             if k8s_hc_id and cluster_removed:
1358 0                 step = "Removing k8scluster='{}' from k8srepos".format(k8scluster_id)
1359 0                 self.logger.debug(logging_text + step)
1360 0                 db_k8srepo_list = self.db.get_list(
1361                     "k8srepos", {"_admin.cluster-inserted": k8s_hc_id}
1362                 )
1363 0                 for k8srepo in db_k8srepo_list:
1364 0                     try:
1365 0                         cluster_list = k8srepo["_admin"]["cluster-inserted"]
1366 0                         cluster_list.remove(k8s_hc_id)
1367 0                         self.update_db_2(
1368                             "k8srepos",
1369                             k8srepo["_id"],
1370                             {"_admin.cluster-inserted": cluster_list},
1371                         )
1372 0                     except Exception as e:
1373 0                         self.logger.error("{}: {}".format(step, e))
1374 0             self.db.del_one("k8sclusters", {"_id": k8scluster_id})
1375 0             db_k8scluster_update = None
1376 0             self.logger.debug(logging_text + "Done")
1377
1378 0         except Exception as e:
1379 0             if isinstance(
1380                 e,
1381                 (
1382                     LcmException,
1383                     DbException,
1384                     K8sException,
1385                     N2VCException,
1386                     asyncio.CancelledError,
1387                 ),
1388             ):
1389 0                 self.logger.error(logging_text + "Exit Exception {}".format(e))
1390             else:
1391 0                 self.logger.critical(
1392                     logging_text + "Exit Exception {}".format(e), exc_info=True
1393                 )
1394 0             exc = e
1395         finally:
1396 0             if exc and db_k8scluster:
1397 0                 db_k8scluster_update["_admin.operationalState"] = "ERROR"
1398 0                 db_k8scluster_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1399                     step, exc
1400                 )
1401                 # Mark the WIM 'create' HA task as erroneous
1402 0                 operation_state = "FAILED"
1403 0                 operation_details = "ERROR {}: {}".format(step, exc)
1404             else:
1405 0                 operation_state = "COMPLETED"
1406 0                 operation_details = "deleted"
1407
1408 0             try:
1409 0                 if db_k8scluster_update:
1410 0                     self.update_db_2("k8sclusters", k8scluster_id, db_k8scluster_update)
1411                 # Register the K8scluster 'delete' HA task either
1412                 # succesful or erroneous, or do nothing (if legacy NBI)
1413 0                 self.lcm_tasks.unlock_HA(
1414                     "k8scluster",
1415                     "delete",
1416                     op_id,
1417                     operationState=operation_state,
1418                     detailed_status=operation_details,
1419                 )
1420 0             except DbException as e:
1421 0                 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1422 0             self.lcm_tasks.remove("k8scluster", k8scluster_id, order_id)
1423
1424
1425 1 class VcaLcm(LcmBase):
1426 1     timeout_create = 30
1427
1428 1     def __init__(self, msg, lcm_tasks, config, loop):
1429         """
1430         Init, Connect to database, filesystem storage, and messaging
1431         :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
1432         :return: None
1433         """
1434
1435 1         self.logger = logging.getLogger("lcm.vca")
1436 1         self.loop = loop
1437 1         self.lcm_tasks = lcm_tasks
1438
1439 1         super().__init__(msg, self.logger)
1440
1441         # create N2VC connector
1442 1         self.n2vc = N2VCJujuConnector(
1443             log=self.logger, loop=self.loop, fs=self.fs, db=self.db
1444         )
1445
1446 1     def _get_vca_by_id(self, vca_id: str) -> dict:
1447 1         db_vca = self.db.get_one("vca", {"_id": vca_id})
1448 1         self.db.encrypt_decrypt_fields(
1449             db_vca,
1450             "decrypt",
1451             ["secret", "cacert"],
1452             schema_version=db_vca["schema_version"],
1453             salt=db_vca["_id"],
1454         )
1455 1         return db_vca
1456
1457 1     async def create(self, vca_content, order_id):
1458 1         op_id = vca_content.pop("op_id", None)
1459 1         if not self.lcm_tasks.lock_HA("vca", "create", op_id):
1460 0             return
1461
1462 1         vca_id = vca_content["_id"]
1463 1         self.logger.debug("Task vca_create={} {}".format(vca_id, "Enter"))
1464
1465 1         db_vca = None
1466 1         db_vca_update = {}
1467
1468 1         try:
1469 1             self.logger.debug(
1470                 "Task vca_create={} {}".format(vca_id, "Getting vca from db")
1471             )
1472 1             db_vca = self._get_vca_by_id(vca_id)
1473
1474 1             task = asyncio.ensure_future(
1475                 asyncio.wait_for(
1476                     self.n2vc.validate_vca(db_vca["_id"]),
1477                     timeout=self.timeout_create,
1478                 )
1479             )
1480
1481 1             await asyncio.wait([task], return_when=asyncio.FIRST_COMPLETED)
1482 1             if task.exception():
1483 1                 raise task.exception()
1484 1             self.logger.debug(
1485                 "Task vca_create={} {}".format(
1486                     vca_id, "vca registered and validated successfully"
1487                 )
1488             )
1489 1             db_vca_update["_admin.operationalState"] = "ENABLED"
1490 1             db_vca_update["_admin.detailed-status"] = "Connectivity: ok"
1491 1             operation_details = "VCA validated"
1492 1             operation_state = "COMPLETED"
1493
1494 1             self.logger.debug(
1495                 "Task vca_create={} {}".format(
1496                     vca_id, "Done. Result: {}".format(operation_state)
1497                 )
1498             )
1499
1500 1         except Exception as e:
1501 1             error_msg = "Failed with exception: {}".format(e)
1502 1             self.logger.error("Task vca_create={} {}".format(vca_id, error_msg))
1503 1             db_vca_update["_admin.operationalState"] = "ERROR"
1504 1             db_vca_update["_admin.detailed-status"] = error_msg
1505 1             operation_state = "FAILED"
1506 1             operation_details = error_msg
1507         finally:
1508 1             try:
1509 1                 self.update_db_2("vca", vca_id, db_vca_update)
1510
1511                 # Register the operation and unlock
1512 1                 self.lcm_tasks.unlock_HA(
1513                     "vca",
1514                     "create",
1515                     op_id,
1516                     operationState=operation_state,
1517                     detailed_status=operation_details,
1518                 )
1519 1             except DbException as e:
1520 1                 self.logger.error(
1521                     "Task vca_create={} {}".format(
1522                         vca_id, "Cannot update database: {}".format(e)
1523                     )
1524                 )
1525 1             self.lcm_tasks.remove("vca", vca_id, order_id)
1526
1527 1     async def delete(self, vca_content, order_id):
1528         # HA tasks and backward compatibility:
1529         # If "vim_content" does not include "op_id", we a running a legacy NBI version.
1530         # In such a case, HA is not supported by NBI, "op_id" is None, and lock_HA() will do nothing.
1531         # Register "delete" task here for related future HA operations
1532 1         op_id = vca_content.pop("op_id", None)
1533 1         if not self.lcm_tasks.lock_HA("vca", "delete", op_id):
1534 0             return
1535
1536 1         db_vca_update = {}
1537 1         vca_id = vca_content["_id"]
1538
1539 1         try:
1540 1             self.logger.debug(
1541                 "Task vca_delete={} {}".format(vca_id, "Deleting vca from db")
1542             )
1543 1             self.db.del_one("vca", {"_id": vca_id})
1544 1             db_vca_update = None
1545 1             operation_details = "deleted"
1546 1             operation_state = "COMPLETED"
1547
1548 1             self.logger.debug(
1549                 "Task vca_delete={} {}".format(
1550                     vca_id, "Done. Result: {}".format(operation_state)
1551                 )
1552             )
1553 1         except Exception as e:
1554 1             error_msg = "Failed with exception: {}".format(e)
1555 1             self.logger.error("Task vca_delete={} {}".format(vca_id, error_msg))
1556 1             db_vca_update["_admin.operationalState"] = "ERROR"
1557 1             db_vca_update["_admin.detailed-status"] = error_msg
1558 1             operation_state = "FAILED"
1559 1             operation_details = error_msg
1560         finally:
1561 1             try:
1562 1                 self.update_db_2("vca", vca_id, db_vca_update)
1563 1                 self.lcm_tasks.unlock_HA(
1564                     "vca",
1565                     "delete",
1566                     op_id,
1567                     operationState=operation_state,
1568                     detailed_status=operation_details,
1569                 )
1570 1             except DbException as e:
1571 1                 self.logger.error(
1572                     "Task vca_delete={} {}".format(
1573                         vca_id, "Cannot update database: {}".format(e)
1574                     )
1575                 )
1576 1             self.lcm_tasks.remove("vca", vca_id, order_id)
1577
1578
1579 1 class K8sRepoLcm(LcmBase):
1580 1     def __init__(self, msg, lcm_tasks, config, loop):
1581         """
1582         Init, Connect to database, filesystem storage, and messaging
1583         :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
1584         :return: None
1585         """
1586
1587 0         self.logger = logging.getLogger("lcm.k8srepo")
1588 0         self.loop = loop
1589 0         self.lcm_tasks = lcm_tasks
1590 0         self.vca_config = config["VCA"]
1591
1592 0         super().__init__(msg, self.logger)
1593
1594 0         self.k8srepo = K8sHelmConnector(
1595             kubectl_command=self.vca_config.get("kubectlpath"),
1596             helm_command=self.vca_config.get("helmpath"),
1597             fs=self.fs,
1598             log=self.logger,
1599             db=self.db,
1600             on_update_db=None,
1601         )
1602
1603 1     async def create(self, k8srepo_content, order_id):
1604         # HA tasks and backward compatibility:
1605         # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
1606         # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
1607         # Register 'create' task here for related future HA operations
1608
1609 0         op_id = k8srepo_content.pop("op_id", None)
1610 0         if not self.lcm_tasks.lock_HA("k8srepo", "create", op_id):
1611 0             return
1612
1613 0         k8srepo_id = k8srepo_content.get("_id")
1614 0         logging_text = "Task k8srepo_create={} ".format(k8srepo_id)
1615 0         self.logger.debug(logging_text + "Enter")
1616
1617 0         db_k8srepo = None
1618 0         db_k8srepo_update = {}
1619 0         exc = None
1620 0         operation_state = "COMPLETED"
1621 0         operation_details = ""
1622 0         try:
1623 0             step = "Getting k8srepo-id='{}' from db".format(k8srepo_id)
1624 0             self.logger.debug(logging_text + step)
1625 0             db_k8srepo = self.db.get_one("k8srepos", {"_id": k8srepo_id})
1626 0             db_k8srepo_update["_admin.operationalState"] = "ENABLED"
1627 0         except Exception as e:
1628 0             self.logger.error(
1629                 logging_text + "Exit Exception {}".format(e),
1630                 exc_info=not isinstance(
1631                     e,
1632                     (
1633                         LcmException,
1634                         DbException,
1635                         K8sException,
1636                         N2VCException,
1637                         asyncio.CancelledError,
1638                     ),
1639                 ),
1640             )
1641 0             exc = e
1642         finally:
1643 0             if exc and db_k8srepo:
1644 0                 db_k8srepo_update["_admin.operationalState"] = "ERROR"
1645 0                 db_k8srepo_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1646                     step, exc
1647                 )
1648                 # Mark the WIM 'create' HA task as erroneous
1649 0                 operation_state = "FAILED"
1650 0                 operation_details = "ERROR {}: {}".format(step, exc)
1651 0             try:
1652 0                 if db_k8srepo_update:
1653 0                     self.update_db_2("k8srepos", k8srepo_id, db_k8srepo_update)
1654                 # Register the K8srepo 'create' HA task either
1655                 # succesful or erroneous, or do nothing (if legacy NBI)
1656 0                 self.lcm_tasks.unlock_HA(
1657                     "k8srepo",
1658                     "create",
1659                     op_id,
1660                     operationState=operation_state,
1661                     detailed_status=operation_details,
1662                 )
1663 0             except DbException as e:
1664 0                 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1665 0             self.lcm_tasks.remove("k8srepo", k8srepo_id, order_id)
1666
1667 1     async def delete(self, k8srepo_content, order_id):
1668         # HA tasks and backward compatibility:
1669         # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
1670         # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
1671         # Register 'delete' task here for related future HA operations
1672 0         op_id = k8srepo_content.pop("op_id", None)
1673 0         if not self.lcm_tasks.lock_HA("k8srepo", "delete", op_id):
1674 0             return
1675
1676 0         k8srepo_id = k8srepo_content.get("_id")
1677 0         logging_text = "Task k8srepo_delete={} ".format(k8srepo_id)
1678 0         self.logger.debug(logging_text + "Enter")
1679
1680 0         db_k8srepo = None
1681 0         db_k8srepo_update = {}
1682
1683 0         exc = None
1684 0         operation_state = "COMPLETED"
1685 0         operation_details = ""
1686 0         try:
1687 0             step = "Getting k8srepo-id='{}' from db".format(k8srepo_id)
1688 0             self.logger.debug(logging_text + step)
1689 0             db_k8srepo = self.db.get_one("k8srepos", {"_id": k8srepo_id})
1690
1691 0         except Exception as e:
1692 0             self.logger.error(
1693                 logging_text + "Exit Exception {}".format(e),
1694                 exc_info=not isinstance(
1695                     e,
1696                     (
1697                         LcmException,
1698                         DbException,
1699                         K8sException,
1700                         N2VCException,
1701                         asyncio.CancelledError,
1702                     ),
1703                 ),
1704             )
1705 0             exc = e
1706         finally:
1707 0             if exc and db_k8srepo:
1708 0                 db_k8srepo_update["_admin.operationalState"] = "ERROR"
1709 0                 db_k8srepo_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1710                     step, exc
1711                 )
1712                 # Mark the WIM 'create' HA task as erroneous
1713 0                 operation_state = "FAILED"
1714 0                 operation_details = "ERROR {}: {}".format(step, exc)
1715 0             try:
1716 0                 if db_k8srepo_update:
1717 0                     self.update_db_2("k8srepos", k8srepo_id, db_k8srepo_update)
1718                 # Register the K8srepo 'delete' HA task either
1719                 # succesful or erroneous, or do nothing (if legacy NBI)
1720 0                 self.lcm_tasks.unlock_HA(
1721                     "k8srepo",
1722                     "delete",
1723                     op_id,
1724                     operationState=operation_state,
1725                     detailed_status=operation_details,
1726                 )
1727 0                 self.db.del_one("k8srepos", {"_id": k8srepo_id})
1728 0             except DbException as e:
1729 0                 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1730 0             self.lcm_tasks.remove("k8srepo", k8srepo_id, order_id)