blob: 3f323d65c07189afdb5c7c0985b30e9f088ff98f [file] [log] [blame]
tierno59d22d22018-09-25 18:10:19 +02001# -*- coding: utf-8 -*-
2
tierno2e215512018-11-28 09:37:52 +00003##
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
calvinosanch9f9c6f22019-11-04 13:37:39 +010019import yaml
tiernofa076c32020-08-13 14:25:47 +000020import asyncio
tierno59d22d22018-09-25 18:10:19 +020021import logging
22import logging.handlers
tierno8069ce52019-08-28 15:34:33 +000023from osm_lcm import ROclient
tierno626e0152019-11-29 14:16:16 +000024from osm_lcm.lcm_utils import LcmException, LcmBase, deep_get
calvinosanch9f9c6f22019-11-04 13:37:39 +010025from n2vc.k8s_helm_conn import K8sHelmConnector
lloretgalleg18ebc3a2020-10-22 09:54:51 +000026from n2vc.k8s_helm3_conn import K8sHelm3Connector
Adam Israelbaacc302019-12-01 12:41:39 -050027from n2vc.k8s_juju_conn import K8sJujuConnector
David Garciac1fe90a2021-03-31 19:12:02 +020028from n2vc.n2vc_juju_conn import N2VCJujuConnector
tiernoe19bd742019-12-05 16:09:08 +000029from n2vc.exceptions import K8sException, N2VCException
tierno59d22d22018-09-25 18:10:19 +020030from osm_common.dbbase import DbException
31from copy import deepcopy
tiernofa076c32020-08-13 14:25:47 +000032from time import time
tierno59d22d22018-09-25 18:10:19 +020033
34__author__ = "Alfonso Tierno"
35
36
37class VimLcm(LcmBase):
tierno17a612f2018-10-23 11:30:42 +020038 # values that are encrypted at vim config because they are passwords
garciadeblas5697b8b2021-03-24 09:17:02 +010039 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 }
tierno59d22d22018-09-25 18:10:19 +020048
bravof922c4172020-11-24 21:21:43 -030049 def __init__(self, msg, lcm_tasks, config, loop):
tierno59d22d22018-09-25 18:10:19 +020050 """
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
garciadeblas5697b8b2021-03-24 09:17:02 +010056 self.logger = logging.getLogger("lcm.vim")
tierno59d22d22018-09-25 18:10:19 +020057 self.loop = loop
58 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +000059 self.ro_config = config["ro_config"]
tierno59d22d22018-09-25 18:10:19 +020060
bravof922c4172020-11-24 21:21:43 -030061 super().__init__(msg, self.logger)
tierno59d22d22018-09-25 18:10:19 +020062
63 async def create(self, vim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +020064
65 # HA tasks and backward compatibility:
66 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
67 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
68 # Register 'create' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +010069 op_id = vim_content.pop("op_id", None)
70 if not self.lcm_tasks.lock_HA("vim", "create", op_id):
kuuse6a470c62019-07-10 13:52:45 +020071 return
72
tierno59d22d22018-09-25 18:10:19 +020073 vim_id = vim_content["_id"]
74 logging_text = "Task vim_create={} ".format(vim_id)
75 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +020076
tierno59d22d22018-09-25 18:10:19 +020077 db_vim = None
78 db_vim_update = {}
79 exc = None
80 RO_sdn_id = None
81 try:
82 step = "Getting vim-id='{}' from db".format(vim_id)
83 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
garciadeblas5697b8b2021-03-24 09:17:02 +010084 if vim_content.get("config") and vim_content["config"].get(
85 "sdn-controller"
86 ):
87 step = "Getting sdn-controller-id='{}' from db".format(
88 vim_content["config"]["sdn-controller"]
89 )
90 db_sdn = self.db.get_one(
91 "sdns", {"_id": vim_content["config"]["sdn-controller"]}
92 )
kuuse6a470c62019-07-10 13:52:45 +020093
94 # If the VIM account has an associated SDN account, also
95 # wait for any previous tasks in process for the SDN
garciadeblas5697b8b2021-03-24 09:17:02 +010096 await self.lcm_tasks.waitfor_related_HA("sdn", "ANY", db_sdn["_id"])
kuuse6a470c62019-07-10 13:52:45 +020097
garciadeblas5697b8b2021-03-24 09:17:02 +010098 if (
99 db_sdn.get("_admin")
100 and db_sdn["_admin"].get("deployed")
101 and db_sdn["_admin"]["deployed"].get("RO")
102 ):
tierno59d22d22018-09-25 18:10:19 +0200103 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
104 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100105 raise LcmException(
106 "sdn-controller={} is not available. Not deployed at RO".format(
107 vim_content["config"]["sdn-controller"]
108 )
109 )
tierno59d22d22018-09-25 18:10:19 +0200110
111 step = "Creating vim at RO"
tiernobaa51102018-12-14 13:16:18 +0000112 db_vim_update["_admin.deployed.RO"] = None
tierno59d22d22018-09-25 18:10:19 +0200113 db_vim_update["_admin.detailed-status"] = step
114 self.update_db_2("vim_accounts", vim_id, db_vim_update)
115 RO = ROclient.ROClient(self.loop, **self.ro_config)
116 vim_RO = deepcopy(vim_content)
117 vim_RO.pop("_id", None)
118 vim_RO.pop("_admin", None)
tierno17a612f2018-10-23 11:30:42 +0200119 schema_version = vim_RO.pop("schema_version", None)
tierno59d22d22018-09-25 18:10:19 +0200120 vim_RO.pop("schema_type", None)
121 vim_RO.pop("vim_tenant_name", None)
122 vim_RO["type"] = vim_RO.pop("vim_type")
123 vim_RO.pop("vim_user", None)
124 vim_RO.pop("vim_password", None)
125 if RO_sdn_id:
126 vim_RO["config"]["sdn-controller"] = RO_sdn_id
127 desc = await RO.create("vim", descriptor=vim_RO)
128 RO_vim_id = desc["uuid"]
129 db_vim_update["_admin.deployed.RO"] = RO_vim_id
garciadeblas5697b8b2021-03-24 09:17:02 +0100130 self.logger.debug(
131 logging_text + "VIM created at RO_vim_id={}".format(RO_vim_id)
132 )
tierno59d22d22018-09-25 18:10:19 +0200133
134 step = "Creating vim_account at RO"
135 db_vim_update["_admin.detailed-status"] = step
136 self.update_db_2("vim_accounts", vim_id, db_vim_update)
137
tierno17a612f2018-10-23 11:30:42 +0200138 if vim_content.get("vim_password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100139 vim_content["vim_password"] = self.db.decrypt(
140 vim_content["vim_password"],
141 schema_version=schema_version,
142 salt=vim_id,
143 )
144 vim_account_RO = {
145 "vim_tenant_name": vim_content["vim_tenant_name"],
146 "vim_username": vim_content["vim_user"],
147 "vim_password": vim_content["vim_password"],
148 }
tierno59d22d22018-09-25 18:10:19 +0200149 if vim_RO.get("config"):
150 vim_account_RO["config"] = vim_RO["config"]
151 if "sdn-controller" in vim_account_RO["config"]:
152 del vim_account_RO["config"]["sdn-controller"]
153 if "sdn-port-mapping" in vim_account_RO["config"]:
154 del vim_account_RO["config"]["sdn-port-mapping"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100155 vim_config_encrypted_keys = self.vim_config_encrypted.get(
156 schema_version
157 ) or self.vim_config_encrypted.get("default")
tierno2d9f6f52019-08-01 16:32:56 +0000158 for p in vim_config_encrypted_keys:
tierno17a612f2018-10-23 11:30:42 +0200159 if vim_account_RO["config"].get(p):
garciadeblas5697b8b2021-03-24 09:17:02 +0100160 vim_account_RO["config"][p] = self.db.decrypt(
161 vim_account_RO["config"][p],
162 schema_version=schema_version,
163 salt=vim_id,
164 )
tierno17a612f2018-10-23 11:30:42 +0200165
tiernoe37b57d2018-12-11 17:22:51 +0000166 desc = await RO.attach("vim_account", RO_vim_id, descriptor=vim_account_RO)
tierno59d22d22018-09-25 18:10:19 +0200167 db_vim_update["_admin.deployed.RO-account"] = desc["uuid"]
168 db_vim_update["_admin.operationalState"] = "ENABLED"
169 db_vim_update["_admin.detailed-status"] = "Done"
kuuse6a470c62019-07-10 13:52:45 +0200170 # Mark the VIM 'create' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100171 operation_state = "COMPLETED"
172 operation_details = "Done"
tierno59d22d22018-09-25 18:10:19 +0200173
garciadeblas5697b8b2021-03-24 09:17:02 +0100174 self.logger.debug(
175 logging_text
176 + "Exit Ok VIM account created at RO_vim_account_id={}".format(
177 desc["uuid"]
178 )
179 )
tierno59d22d22018-09-25 18:10:19 +0200180 return
181
tiernocc29b592020-09-18 10:33:18 +0000182 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200183 self.logger.error(logging_text + "Exit Exception {}".format(e))
184 exc = e
185 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100186 self.logger.critical(
187 logging_text + "Exit Exception {}".format(e), exc_info=True
188 )
tierno59d22d22018-09-25 18:10:19 +0200189 exc = e
190 finally:
191 if exc and db_vim:
192 db_vim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100193 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
194 step, exc
195 )
kuuse6a470c62019-07-10 13:52:45 +0200196 # Mark the VIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100197 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000198 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000199 try:
200 if db_vim_update:
201 self.update_db_2("vim_accounts", vim_id, db_vim_update)
kuuse6a470c62019-07-10 13:52:45 +0200202 # Register the VIM 'create' HA task either
203 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100204 self.lcm_tasks.unlock_HA(
205 "vim",
206 "create",
207 op_id,
208 operationState=operation_state,
209 detailed_status=operation_details,
210 )
tiernobaa51102018-12-14 13:16:18 +0000211 except DbException as e:
212 self.logger.error(logging_text + "Cannot update database: {}".format(e))
213
tierno59d22d22018-09-25 18:10:19 +0200214 self.lcm_tasks.remove("vim_account", vim_id, order_id)
215
216 async def edit(self, vim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200217
218 # HA tasks and backward compatibility:
219 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
220 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100221 op_id = vim_content.pop("op_id", None)
222 if not self.lcm_tasks.lock_HA("vim", "edit", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200223 return
224
tierno59d22d22018-09-25 18:10:19 +0200225 vim_id = vim_content["_id"]
226 logging_text = "Task vim_edit={} ".format(vim_id)
227 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200228
tierno59d22d22018-09-25 18:10:19 +0200229 db_vim = None
230 exc = None
231 RO_sdn_id = None
232 RO_vim_id = None
233 db_vim_update = {}
234 step = "Getting vim-id='{}' from db".format(vim_id)
235 try:
kuuse6a470c62019-07-10 13:52:45 +0200236 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100237 await self.lcm_tasks.waitfor_related_HA("vim", "edit", op_id)
tierno59d22d22018-09-25 18:10:19 +0200238
kuuse6a470c62019-07-10 13:52:45 +0200239 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
tierno59d22d22018-09-25 18:10:19 +0200240
garciadeblas5697b8b2021-03-24 09:17:02 +0100241 if (
242 db_vim.get("_admin")
243 and db_vim["_admin"].get("deployed")
244 and db_vim["_admin"]["deployed"].get("RO")
245 ):
246 if vim_content.get("config") and vim_content["config"].get(
247 "sdn-controller"
248 ):
249 step = "Getting sdn-controller-id='{}' from db".format(
250 vim_content["config"]["sdn-controller"]
251 )
252 db_sdn = self.db.get_one(
253 "sdns", {"_id": vim_content["config"]["sdn-controller"]}
254 )
tierno59d22d22018-09-25 18:10:19 +0200255
kuuse6a470c62019-07-10 13:52:45 +0200256 # If the VIM account has an associated SDN account, also
257 # wait for any previous tasks in process for the SDN
garciadeblas5697b8b2021-03-24 09:17:02 +0100258 await self.lcm_tasks.waitfor_related_HA("sdn", "ANY", db_sdn["_id"])
tierno59d22d22018-09-25 18:10:19 +0200259
garciadeblas5697b8b2021-03-24 09:17:02 +0100260 if (
261 db_sdn.get("_admin")
262 and db_sdn["_admin"].get("deployed")
263 and db_sdn["_admin"]["deployed"].get("RO")
264 ):
tierno59d22d22018-09-25 18:10:19 +0200265 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
266 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100267 raise LcmException(
268 "sdn-controller={} is not available. Not deployed at RO".format(
269 vim_content["config"]["sdn-controller"]
270 )
271 )
tierno59d22d22018-09-25 18:10:19 +0200272
273 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
274 step = "Editing vim at RO"
275 RO = ROclient.ROClient(self.loop, **self.ro_config)
276 vim_RO = deepcopy(vim_content)
277 vim_RO.pop("_id", None)
278 vim_RO.pop("_admin", None)
tierno17a612f2018-10-23 11:30:42 +0200279 schema_version = vim_RO.pop("schema_version", None)
tierno59d22d22018-09-25 18:10:19 +0200280 vim_RO.pop("schema_type", None)
281 vim_RO.pop("vim_tenant_name", None)
282 if "vim_type" in vim_RO:
283 vim_RO["type"] = vim_RO.pop("vim_type")
284 vim_RO.pop("vim_user", None)
285 vim_RO.pop("vim_password", None)
286 if RO_sdn_id:
287 vim_RO["config"]["sdn-controller"] = RO_sdn_id
tierno2357f4e2020-10-19 16:38:59 +0000288 # TODO make a deep update of sdn-port-mapping
tierno59d22d22018-09-25 18:10:19 +0200289 if vim_RO:
290 await RO.edit("vim", RO_vim_id, descriptor=vim_RO)
291
292 step = "Editing vim-account at RO tenant"
293 vim_account_RO = {}
294 if "config" in vim_content:
295 if "sdn-controller" in vim_content["config"]:
296 del vim_content["config"]["sdn-controller"]
297 if "sdn-port-mapping" in vim_content["config"]:
298 del vim_content["config"]["sdn-port-mapping"]
299 if not vim_content["config"]:
300 del vim_content["config"]
tierno17a612f2018-10-23 11:30:42 +0200301 if "vim_tenant_name" in vim_content:
302 vim_account_RO["vim_tenant_name"] = vim_content["vim_tenant_name"]
303 if "vim_password" in vim_content:
304 vim_account_RO["vim_password"] = vim_content["vim_password"]
305 if vim_content.get("vim_password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100306 vim_account_RO["vim_password"] = self.db.decrypt(
307 vim_content["vim_password"],
308 schema_version=schema_version,
309 salt=vim_id,
310 )
tierno17a612f2018-10-23 11:30:42 +0200311 if "config" in vim_content:
312 vim_account_RO["config"] = vim_content["config"]
313 if vim_content.get("config"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100314 vim_config_encrypted_keys = self.vim_config_encrypted.get(
315 schema_version
316 ) or self.vim_config_encrypted.get("default")
tierno2d9f6f52019-08-01 16:32:56 +0000317 for p in vim_config_encrypted_keys:
tierno17a612f2018-10-23 11:30:42 +0200318 if vim_content["config"].get(p):
garciadeblas5697b8b2021-03-24 09:17:02 +0100319 vim_account_RO["config"][p] = self.db.decrypt(
320 vim_content["config"][p],
321 schema_version=schema_version,
322 salt=vim_id,
323 )
tierno17a612f2018-10-23 11:30:42 +0200324
tierno59d22d22018-09-25 18:10:19 +0200325 if "vim_user" in vim_content:
326 vim_content["vim_username"] = vim_content["vim_user"]
327 # vim_account must be edited always even if empty in order to ensure changes are translated to RO
328 # vim_thread. RO will remove and relaunch a new thread for this vim_account
329 await RO.edit("vim_account", RO_vim_id, descriptor=vim_account_RO)
330 db_vim_update["_admin.operationalState"] = "ENABLED"
kuuse6a470c62019-07-10 13:52:45 +0200331 # Mark the VIM 'edit' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100332 operation_state = "COMPLETED"
333 operation_details = "Done"
tierno59d22d22018-09-25 18:10:19 +0200334
335 self.logger.debug(logging_text + "Exit Ok RO_vim_id={}".format(RO_vim_id))
336 return
337
tiernocc29b592020-09-18 10:33:18 +0000338 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200339 self.logger.error(logging_text + "Exit Exception {}".format(e))
340 exc = e
341 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100342 self.logger.critical(
343 logging_text + "Exit Exception {}".format(e), exc_info=True
344 )
tierno59d22d22018-09-25 18:10:19 +0200345 exc = e
346 finally:
347 if exc and db_vim:
348 db_vim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100349 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
350 step, exc
351 )
kuuse6a470c62019-07-10 13:52:45 +0200352 # Mark the VIM 'edit' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100353 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000354 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000355 try:
356 if db_vim_update:
357 self.update_db_2("vim_accounts", vim_id, db_vim_update)
kuuse6a470c62019-07-10 13:52:45 +0200358 # Register the VIM 'edit' HA task either
359 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100360 self.lcm_tasks.unlock_HA(
361 "vim",
362 "edit",
363 op_id,
364 operationState=operation_state,
365 detailed_status=operation_details,
366 )
tiernobaa51102018-12-14 13:16:18 +0000367 except DbException as e:
368 self.logger.error(logging_text + "Cannot update database: {}".format(e))
369
tierno59d22d22018-09-25 18:10:19 +0200370 self.lcm_tasks.remove("vim_account", vim_id, order_id)
371
kuuse6a470c62019-07-10 13:52:45 +0200372 async def delete(self, vim_content, order_id):
373
374 # HA tasks and backward compatibility:
375 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
376 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100377 op_id = vim_content.pop("op_id", None)
378 if not self.lcm_tasks.lock_HA("vim", "delete", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200379 return
380
381 vim_id = vim_content["_id"]
tierno59d22d22018-09-25 18:10:19 +0200382 logging_text = "Task vim_delete={} ".format(vim_id)
383 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200384
tierno59d22d22018-09-25 18:10:19 +0200385 db_vim = None
386 db_vim_update = {}
387 exc = None
388 step = "Getting vim from db"
389 try:
kuuse6a470c62019-07-10 13:52:45 +0200390 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100391 await self.lcm_tasks.waitfor_related_HA("vim", "delete", op_id)
tierno2357f4e2020-10-19 16:38:59 +0000392 if not self.ro_config.get("ng"):
393 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100394 if (
395 db_vim.get("_admin")
396 and db_vim["_admin"].get("deployed")
397 and db_vim["_admin"]["deployed"].get("RO")
398 ):
tierno2357f4e2020-10-19 16:38:59 +0000399 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
400 RO = ROclient.ROClient(self.loop, **self.ro_config)
401 step = "Detaching vim from RO tenant"
402 try:
403 await RO.detach("vim_account", RO_vim_id)
404 except ROclient.ROClientException as e:
405 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +0100406 self.logger.debug(
407 logging_text
408 + "RO_vim_id={} already detached".format(RO_vim_id)
409 )
tierno2357f4e2020-10-19 16:38:59 +0000410 else:
411 raise
kuuse6a470c62019-07-10 13:52:45 +0200412
tierno2357f4e2020-10-19 16:38:59 +0000413 step = "Deleting vim from RO"
414 try:
415 await RO.delete("vim", RO_vim_id)
416 except ROclient.ROClientException as e:
417 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +0100418 self.logger.debug(
419 logging_text
420 + "RO_vim_id={} already deleted".format(RO_vim_id)
421 )
tierno2357f4e2020-10-19 16:38:59 +0000422 else:
423 raise
424 else:
425 # nothing to delete
426 self.logger.debug(logging_text + "Nothing to remove at RO")
tierno59d22d22018-09-25 18:10:19 +0200427 self.db.del_one("vim_accounts", {"_id": vim_id})
tiernobaa51102018-12-14 13:16:18 +0000428 db_vim = None
tierno59d22d22018-09-25 18:10:19 +0200429 self.logger.debug(logging_text + "Exit Ok")
430 return
431
tiernocc29b592020-09-18 10:33:18 +0000432 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200433 self.logger.error(logging_text + "Exit Exception {}".format(e))
434 exc = e
435 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100436 self.logger.critical(
437 logging_text + "Exit Exception {}".format(e), exc_info=True
438 )
tierno59d22d22018-09-25 18:10:19 +0200439 exc = e
440 finally:
441 self.lcm_tasks.remove("vim_account", vim_id, order_id)
442 if exc and db_vim:
443 db_vim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100444 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
445 step, exc
446 )
kuuse6a470c62019-07-10 13:52:45 +0200447 # Mark the VIM 'delete' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100448 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000449 operation_details = "ERROR {}: {}".format(step, exc)
garciadeblas5697b8b2021-03-24 09:17:02 +0100450 self.lcm_tasks.unlock_HA(
451 "vim",
452 "delete",
453 op_id,
454 operationState=operation_state,
455 detailed_status=operation_details,
456 )
tiernobaa51102018-12-14 13:16:18 +0000457 try:
458 if db_vim and db_vim_update:
459 self.update_db_2("vim_accounts", vim_id, db_vim_update)
kuuse6a470c62019-07-10 13:52:45 +0200460 # If the VIM 'delete' HA task was succesful, the DB entry has been deleted,
461 # which means that there is nowhere to register this task, so do nothing here.
tiernobaa51102018-12-14 13:16:18 +0000462 except DbException as e:
463 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +0200464 self.lcm_tasks.remove("vim_account", vim_id, order_id)
465
466
tiernoe37b57d2018-12-11 17:22:51 +0000467class WimLcm(LcmBase):
468 # values that are encrypted at wim config because they are passwords
469 wim_config_encrypted = ()
470
bravof922c4172020-11-24 21:21:43 -0300471 def __init__(self, msg, lcm_tasks, config, loop):
tiernoe37b57d2018-12-11 17:22:51 +0000472 """
473 Init, Connect to database, filesystem storage, and messaging
474 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
475 :return: None
476 """
477
garciadeblas5697b8b2021-03-24 09:17:02 +0100478 self.logger = logging.getLogger("lcm.vim")
tiernoe37b57d2018-12-11 17:22:51 +0000479 self.loop = loop
480 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +0000481 self.ro_config = config["ro_config"]
tiernoe37b57d2018-12-11 17:22:51 +0000482
bravof922c4172020-11-24 21:21:43 -0300483 super().__init__(msg, self.logger)
tiernoe37b57d2018-12-11 17:22:51 +0000484
485 async def create(self, wim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200486
487 # HA tasks and backward compatibility:
488 # If 'wim_content' does not include 'op_id', we a running a legacy NBI version.
489 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
490 # Register 'create' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +0100491 op_id = wim_content.pop("op_id", None)
492 self.lcm_tasks.lock_HA("wim", "create", op_id)
kuuse6a470c62019-07-10 13:52:45 +0200493
tiernoe37b57d2018-12-11 17:22:51 +0000494 wim_id = wim_content["_id"]
495 logging_text = "Task wim_create={} ".format(wim_id)
496 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200497
tiernoe37b57d2018-12-11 17:22:51 +0000498 db_wim = None
499 db_wim_update = {}
500 exc = None
501 try:
502 step = "Getting wim-id='{}' from db".format(wim_id)
503 db_wim = self.db.get_one("wim_accounts", {"_id": wim_id})
504 db_wim_update["_admin.deployed.RO"] = None
505
506 step = "Creating wim at RO"
507 db_wim_update["_admin.detailed-status"] = step
508 self.update_db_2("wim_accounts", wim_id, db_wim_update)
509 RO = ROclient.ROClient(self.loop, **self.ro_config)
510 wim_RO = deepcopy(wim_content)
511 wim_RO.pop("_id", None)
512 wim_RO.pop("_admin", None)
513 schema_version = wim_RO.pop("schema_version", None)
514 wim_RO.pop("schema_type", None)
515 wim_RO.pop("wim_tenant_name", None)
516 wim_RO["type"] = wim_RO.pop("wim_type")
517 wim_RO.pop("wim_user", None)
518 wim_RO.pop("wim_password", None)
519 desc = await RO.create("wim", descriptor=wim_RO)
520 RO_wim_id = desc["uuid"]
521 db_wim_update["_admin.deployed.RO"] = RO_wim_id
garciadeblas5697b8b2021-03-24 09:17:02 +0100522 self.logger.debug(
523 logging_text + "WIM created at RO_wim_id={}".format(RO_wim_id)
524 )
tiernoe37b57d2018-12-11 17:22:51 +0000525
526 step = "Creating wim_account at RO"
527 db_wim_update["_admin.detailed-status"] = step
528 self.update_db_2("wim_accounts", wim_id, db_wim_update)
529
530 if wim_content.get("wim_password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100531 wim_content["wim_password"] = self.db.decrypt(
532 wim_content["wim_password"],
533 schema_version=schema_version,
534 salt=wim_id,
535 )
536 wim_account_RO = {
537 "name": wim_content["name"],
538 "user": wim_content["user"],
539 "password": wim_content["password"],
540 }
tiernoe37b57d2018-12-11 17:22:51 +0000541 if wim_RO.get("config"):
542 wim_account_RO["config"] = wim_RO["config"]
543 if "wim_port_mapping" in wim_account_RO["config"]:
544 del wim_account_RO["config"]["wim_port_mapping"]
545 for p in self.wim_config_encrypted:
546 if wim_account_RO["config"].get(p):
garciadeblas5697b8b2021-03-24 09:17:02 +0100547 wim_account_RO["config"][p] = self.db.decrypt(
548 wim_account_RO["config"][p],
549 schema_version=schema_version,
550 salt=wim_id,
551 )
tiernoe37b57d2018-12-11 17:22:51 +0000552
553 desc = await RO.attach("wim_account", RO_wim_id, descriptor=wim_account_RO)
554 db_wim_update["_admin.deployed.RO-account"] = desc["uuid"]
555 db_wim_update["_admin.operationalState"] = "ENABLED"
556 db_wim_update["_admin.detailed-status"] = "Done"
kuuse6a470c62019-07-10 13:52:45 +0200557 # Mark the WIM 'create' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100558 operation_state = "COMPLETED"
559 operation_details = "Done"
tiernoe37b57d2018-12-11 17:22:51 +0000560
garciadeblas5697b8b2021-03-24 09:17:02 +0100561 self.logger.debug(
562 logging_text
563 + "Exit Ok WIM account created at RO_wim_account_id={}".format(
564 desc["uuid"]
565 )
566 )
tiernoe37b57d2018-12-11 17:22:51 +0000567 return
568
tiernocc29b592020-09-18 10:33:18 +0000569 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tiernoe37b57d2018-12-11 17:22:51 +0000570 self.logger.error(logging_text + "Exit Exception {}".format(e))
571 exc = e
572 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100573 self.logger.critical(
574 logging_text + "Exit Exception {}".format(e), exc_info=True
575 )
tiernoe37b57d2018-12-11 17:22:51 +0000576 exc = e
577 finally:
578 if exc and db_wim:
579 db_wim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100580 db_wim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
581 step, exc
582 )
kuuse6a470c62019-07-10 13:52:45 +0200583 # Mark the WIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100584 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000585 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000586 try:
587 if db_wim_update:
588 self.update_db_2("wim_accounts", wim_id, db_wim_update)
kuuse6a470c62019-07-10 13:52:45 +0200589 # Register the WIM 'create' HA task either
590 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100591 self.lcm_tasks.unlock_HA(
592 "wim",
593 "create",
594 op_id,
595 operationState=operation_state,
596 detailed_status=operation_details,
597 )
tiernobaa51102018-12-14 13:16:18 +0000598 except DbException as e:
599 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tiernoe37b57d2018-12-11 17:22:51 +0000600 self.lcm_tasks.remove("wim_account", wim_id, order_id)
601
602 async def edit(self, wim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200603
604 # HA tasks and backward compatibility:
605 # If 'wim_content' does not include 'op_id', we a running a legacy NBI version.
606 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100607 op_id = wim_content.pop("op_id", None)
608 if not self.lcm_tasks.lock_HA("wim", "edit", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200609 return
610
tiernoe37b57d2018-12-11 17:22:51 +0000611 wim_id = wim_content["_id"]
612 logging_text = "Task wim_edit={} ".format(wim_id)
613 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200614
tiernoe37b57d2018-12-11 17:22:51 +0000615 db_wim = None
616 exc = None
617 RO_wim_id = None
618 db_wim_update = {}
619 step = "Getting wim-id='{}' from db".format(wim_id)
620 try:
kuuse6a470c62019-07-10 13:52:45 +0200621 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100622 await self.lcm_tasks.waitfor_related_HA("wim", "edit", op_id)
tiernoe37b57d2018-12-11 17:22:51 +0000623
kuuse6a470c62019-07-10 13:52:45 +0200624 db_wim = self.db.get_one("wim_accounts", {"_id": wim_id})
tiernoe37b57d2018-12-11 17:22:51 +0000625
garciadeblas5697b8b2021-03-24 09:17:02 +0100626 if (
627 db_wim.get("_admin")
628 and db_wim["_admin"].get("deployed")
629 and db_wim["_admin"]["deployed"].get("RO")
630 ):
tiernoe37b57d2018-12-11 17:22:51 +0000631
632 RO_wim_id = db_wim["_admin"]["deployed"]["RO"]
633 step = "Editing wim at RO"
634 RO = ROclient.ROClient(self.loop, **self.ro_config)
635 wim_RO = deepcopy(wim_content)
636 wim_RO.pop("_id", None)
637 wim_RO.pop("_admin", None)
638 schema_version = wim_RO.pop("schema_version", None)
639 wim_RO.pop("schema_type", None)
640 wim_RO.pop("wim_tenant_name", None)
641 if "wim_type" in wim_RO:
642 wim_RO["type"] = wim_RO.pop("wim_type")
643 wim_RO.pop("wim_user", None)
644 wim_RO.pop("wim_password", None)
645 # TODO make a deep update of wim_port_mapping
646 if wim_RO:
647 await RO.edit("wim", RO_wim_id, descriptor=wim_RO)
648
649 step = "Editing wim-account at RO tenant"
650 wim_account_RO = {}
651 if "config" in wim_content:
652 if "wim_port_mapping" in wim_content["config"]:
653 del wim_content["config"]["wim_port_mapping"]
654 if not wim_content["config"]:
655 del wim_content["config"]
656 if "wim_tenant_name" in wim_content:
657 wim_account_RO["wim_tenant_name"] = wim_content["wim_tenant_name"]
658 if "wim_password" in wim_content:
659 wim_account_RO["wim_password"] = wim_content["wim_password"]
660 if wim_content.get("wim_password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100661 wim_account_RO["wim_password"] = self.db.decrypt(
662 wim_content["wim_password"],
663 schema_version=schema_version,
664 salt=wim_id,
665 )
tiernoe37b57d2018-12-11 17:22:51 +0000666 if "config" in wim_content:
667 wim_account_RO["config"] = wim_content["config"]
668 if wim_content.get("config"):
669 for p in self.wim_config_encrypted:
670 if wim_content["config"].get(p):
garciadeblas5697b8b2021-03-24 09:17:02 +0100671 wim_account_RO["config"][p] = self.db.decrypt(
672 wim_content["config"][p],
673 schema_version=schema_version,
674 salt=wim_id,
675 )
tiernoe37b57d2018-12-11 17:22:51 +0000676
677 if "wim_user" in wim_content:
678 wim_content["wim_username"] = wim_content["wim_user"]
679 # wim_account must be edited always even if empty in order to ensure changes are translated to RO
680 # wim_thread. RO will remove and relaunch a new thread for this wim_account
681 await RO.edit("wim_account", RO_wim_id, descriptor=wim_account_RO)
682 db_wim_update["_admin.operationalState"] = "ENABLED"
kuuse6a470c62019-07-10 13:52:45 +0200683 # Mark the WIM 'edit' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100684 operation_state = "COMPLETED"
685 operation_details = "Done"
tiernoe37b57d2018-12-11 17:22:51 +0000686
687 self.logger.debug(logging_text + "Exit Ok RO_wim_id={}".format(RO_wim_id))
688 return
689
tiernocc29b592020-09-18 10:33:18 +0000690 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tiernoe37b57d2018-12-11 17:22:51 +0000691 self.logger.error(logging_text + "Exit Exception {}".format(e))
692 exc = e
693 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100694 self.logger.critical(
695 logging_text + "Exit Exception {}".format(e), exc_info=True
696 )
tiernoe37b57d2018-12-11 17:22:51 +0000697 exc = e
698 finally:
699 if exc and db_wim:
700 db_wim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100701 db_wim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
702 step, exc
703 )
kuuse6a470c62019-07-10 13:52:45 +0200704 # Mark the WIM 'edit' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100705 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000706 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000707 try:
708 if db_wim_update:
709 self.update_db_2("wim_accounts", wim_id, db_wim_update)
kuuse6a470c62019-07-10 13:52:45 +0200710 # Register the WIM 'edit' HA task either
711 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100712 self.lcm_tasks.unlock_HA(
713 "wim",
714 "edit",
715 op_id,
716 operationState=operation_state,
717 detailed_status=operation_details,
718 )
tiernobaa51102018-12-14 13:16:18 +0000719 except DbException as e:
720 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tiernoe37b57d2018-12-11 17:22:51 +0000721 self.lcm_tasks.remove("wim_account", wim_id, order_id)
722
kuuse6a470c62019-07-10 13:52:45 +0200723 async def delete(self, wim_content, order_id):
724
725 # HA tasks and backward compatibility:
726 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
727 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100728 op_id = wim_content.pop("op_id", None)
729 if not self.lcm_tasks.lock_HA("wim", "delete", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200730 return
731
732 wim_id = wim_content["_id"]
tiernoe37b57d2018-12-11 17:22:51 +0000733 logging_text = "Task wim_delete={} ".format(wim_id)
734 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200735
tiernoe37b57d2018-12-11 17:22:51 +0000736 db_wim = None
737 db_wim_update = {}
738 exc = None
739 step = "Getting wim from db"
740 try:
kuuse6a470c62019-07-10 13:52:45 +0200741 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100742 await self.lcm_tasks.waitfor_related_HA("wim", "delete", op_id)
kuuse6a470c62019-07-10 13:52:45 +0200743
tiernoe37b57d2018-12-11 17:22:51 +0000744 db_wim = self.db.get_one("wim_accounts", {"_id": wim_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100745 if (
746 db_wim.get("_admin")
747 and db_wim["_admin"].get("deployed")
748 and db_wim["_admin"]["deployed"].get("RO")
749 ):
tiernoe37b57d2018-12-11 17:22:51 +0000750 RO_wim_id = db_wim["_admin"]["deployed"]["RO"]
751 RO = ROclient.ROClient(self.loop, **self.ro_config)
752 step = "Detaching wim from RO tenant"
753 try:
754 await RO.detach("wim_account", RO_wim_id)
755 except ROclient.ROClientException as e:
756 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +0100757 self.logger.debug(
758 logging_text
759 + "RO_wim_id={} already detached".format(RO_wim_id)
760 )
tiernoe37b57d2018-12-11 17:22:51 +0000761 else:
762 raise
763
764 step = "Deleting wim from RO"
765 try:
766 await RO.delete("wim", RO_wim_id)
767 except ROclient.ROClientException as e:
768 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +0100769 self.logger.debug(
770 logging_text
771 + "RO_wim_id={} already deleted".format(RO_wim_id)
772 )
tiernoe37b57d2018-12-11 17:22:51 +0000773 else:
774 raise
775 else:
776 # nothing to delete
aktas61f61922021-07-29 07:56:27 +0300777 self.logger.error(logging_text + "Nothing to remove at RO")
tiernoe37b57d2018-12-11 17:22:51 +0000778 self.db.del_one("wim_accounts", {"_id": wim_id})
tiernobaa51102018-12-14 13:16:18 +0000779 db_wim = None
tiernoe37b57d2018-12-11 17:22:51 +0000780 self.logger.debug(logging_text + "Exit Ok")
781 return
782
tiernocc29b592020-09-18 10:33:18 +0000783 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tiernoe37b57d2018-12-11 17:22:51 +0000784 self.logger.error(logging_text + "Exit Exception {}".format(e))
785 exc = e
786 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100787 self.logger.critical(
788 logging_text + "Exit Exception {}".format(e), exc_info=True
789 )
tiernoe37b57d2018-12-11 17:22:51 +0000790 exc = e
791 finally:
792 self.lcm_tasks.remove("wim_account", wim_id, order_id)
793 if exc and db_wim:
794 db_wim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100795 db_wim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
796 step, exc
797 )
kuuse6a470c62019-07-10 13:52:45 +0200798 # Mark the WIM 'delete' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100799 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000800 operation_details = "ERROR {}: {}".format(step, exc)
garciadeblas5697b8b2021-03-24 09:17:02 +0100801 self.lcm_tasks.unlock_HA(
802 "wim",
803 "delete",
804 op_id,
805 operationState=operation_state,
806 detailed_status=operation_details,
807 )
tiernobaa51102018-12-14 13:16:18 +0000808 try:
809 if db_wim and db_wim_update:
810 self.update_db_2("wim_accounts", wim_id, db_wim_update)
kuuse6a470c62019-07-10 13:52:45 +0200811 # If the WIM 'delete' HA task was succesful, the DB entry has been deleted,
812 # which means that there is nowhere to register this task, so do nothing here.
tiernobaa51102018-12-14 13:16:18 +0000813 except DbException as e:
814 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tiernoe37b57d2018-12-11 17:22:51 +0000815 self.lcm_tasks.remove("wim_account", wim_id, order_id)
816
817
tierno59d22d22018-09-25 18:10:19 +0200818class SdnLcm(LcmBase):
bravof922c4172020-11-24 21:21:43 -0300819 def __init__(self, msg, lcm_tasks, config, loop):
tierno59d22d22018-09-25 18:10:19 +0200820 """
821 Init, Connect to database, filesystem storage, and messaging
822 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
823 :return: None
824 """
825
garciadeblas5697b8b2021-03-24 09:17:02 +0100826 self.logger = logging.getLogger("lcm.sdn")
tierno59d22d22018-09-25 18:10:19 +0200827 self.loop = loop
828 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +0000829 self.ro_config = config["ro_config"]
tierno59d22d22018-09-25 18:10:19 +0200830
bravof922c4172020-11-24 21:21:43 -0300831 super().__init__(msg, self.logger)
tierno59d22d22018-09-25 18:10:19 +0200832
833 async def create(self, sdn_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200834
835 # HA tasks and backward compatibility:
836 # If 'sdn_content' does not include 'op_id', we a running a legacy NBI version.
837 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
838 # Register 'create' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +0100839 op_id = sdn_content.pop("op_id", None)
840 self.lcm_tasks.lock_HA("sdn", "create", op_id)
kuuse6a470c62019-07-10 13:52:45 +0200841
tierno59d22d22018-09-25 18:10:19 +0200842 sdn_id = sdn_content["_id"]
843 logging_text = "Task sdn_create={} ".format(sdn_id)
844 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200845
tierno59d22d22018-09-25 18:10:19 +0200846 db_sdn = None
847 db_sdn_update = {}
848 RO_sdn_id = None
849 exc = None
850 try:
851 step = "Getting sdn from db"
852 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
853 db_sdn_update["_admin.deployed.RO"] = None
854
855 step = "Creating sdn at RO"
tiernobaa51102018-12-14 13:16:18 +0000856 db_sdn_update["_admin.detailed-status"] = step
857 self.update_db_2("sdns", sdn_id, db_sdn_update)
858
tierno59d22d22018-09-25 18:10:19 +0200859 RO = ROclient.ROClient(self.loop, **self.ro_config)
860 sdn_RO = deepcopy(sdn_content)
861 sdn_RO.pop("_id", None)
862 sdn_RO.pop("_admin", None)
tierno17a612f2018-10-23 11:30:42 +0200863 schema_version = sdn_RO.pop("schema_version", None)
tierno59d22d22018-09-25 18:10:19 +0200864 sdn_RO.pop("schema_type", None)
865 sdn_RO.pop("description", None)
tierno17a612f2018-10-23 11:30:42 +0200866 if sdn_RO.get("password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100867 sdn_RO["password"] = self.db.decrypt(
868 sdn_RO["password"], schema_version=schema_version, salt=sdn_id
869 )
tierno17a612f2018-10-23 11:30:42 +0200870
tierno59d22d22018-09-25 18:10:19 +0200871 desc = await RO.create("sdn", descriptor=sdn_RO)
872 RO_sdn_id = desc["uuid"]
873 db_sdn_update["_admin.deployed.RO"] = RO_sdn_id
874 db_sdn_update["_admin.operationalState"] = "ENABLED"
875 self.logger.debug(logging_text + "Exit Ok RO_sdn_id={}".format(RO_sdn_id))
kuuse6a470c62019-07-10 13:52:45 +0200876 # Mark the SDN 'create' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100877 operation_state = "COMPLETED"
878 operation_details = "Done"
tierno59d22d22018-09-25 18:10:19 +0200879 return
880
tiernocc29b592020-09-18 10:33:18 +0000881 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200882 self.logger.error(logging_text + "Exit Exception {}".format(e))
883 exc = e
884 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100885 self.logger.critical(
886 logging_text + "Exit Exception {}".format(e), exc_info=True
887 )
tierno59d22d22018-09-25 18:10:19 +0200888 exc = e
889 finally:
890 if exc and db_sdn:
891 db_sdn_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100892 db_sdn_update["_admin.detailed-status"] = "ERROR {}: {}".format(
893 step, exc
894 )
kuuse6a470c62019-07-10 13:52:45 +0200895 # Mark the SDN 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100896 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000897 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000898 try:
899 if db_sdn and db_sdn_update:
900 self.update_db_2("sdns", sdn_id, db_sdn_update)
kuuse6a470c62019-07-10 13:52:45 +0200901 # Register the SDN 'create' HA task either
902 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100903 self.lcm_tasks.unlock_HA(
904 "sdn",
905 "create",
906 op_id,
907 operationState=operation_state,
908 detailed_status=operation_details,
909 )
tiernobaa51102018-12-14 13:16:18 +0000910 except DbException as e:
911 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +0200912 self.lcm_tasks.remove("sdn", sdn_id, order_id)
913
914 async def edit(self, sdn_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200915
916 # HA tasks and backward compatibility:
917 # If 'sdn_content' does not include 'op_id', we a running a legacy NBI version.
918 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100919 op_id = sdn_content.pop("op_id", None)
920 if not self.lcm_tasks.lock_HA("sdn", "edit", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200921 return
922
tierno59d22d22018-09-25 18:10:19 +0200923 sdn_id = sdn_content["_id"]
924 logging_text = "Task sdn_edit={} ".format(sdn_id)
925 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200926
tierno59d22d22018-09-25 18:10:19 +0200927 db_sdn = None
928 db_sdn_update = {}
929 exc = None
930 step = "Getting sdn from db"
931 try:
kuuse6a470c62019-07-10 13:52:45 +0200932 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100933 await self.lcm_tasks.waitfor_related_HA("sdn", "edit", op_id)
kuuse6a470c62019-07-10 13:52:45 +0200934
tierno59d22d22018-09-25 18:10:19 +0200935 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
tiernoe37b57d2018-12-11 17:22:51 +0000936 RO_sdn_id = None
garciadeblas5697b8b2021-03-24 09:17:02 +0100937 if (
938 db_sdn.get("_admin")
939 and db_sdn["_admin"].get("deployed")
940 and db_sdn["_admin"]["deployed"].get("RO")
941 ):
tierno59d22d22018-09-25 18:10:19 +0200942 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
943 RO = ROclient.ROClient(self.loop, **self.ro_config)
944 step = "Editing sdn at RO"
945 sdn_RO = deepcopy(sdn_content)
946 sdn_RO.pop("_id", None)
947 sdn_RO.pop("_admin", None)
tierno17a612f2018-10-23 11:30:42 +0200948 schema_version = sdn_RO.pop("schema_version", None)
tierno59d22d22018-09-25 18:10:19 +0200949 sdn_RO.pop("schema_type", None)
950 sdn_RO.pop("description", None)
tierno17a612f2018-10-23 11:30:42 +0200951 if sdn_RO.get("password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100952 sdn_RO["password"] = self.db.decrypt(
953 sdn_RO["password"], schema_version=schema_version, salt=sdn_id
954 )
tierno59d22d22018-09-25 18:10:19 +0200955 if sdn_RO:
956 await RO.edit("sdn", RO_sdn_id, descriptor=sdn_RO)
957 db_sdn_update["_admin.operationalState"] = "ENABLED"
kuuse6a470c62019-07-10 13:52:45 +0200958 # Mark the SDN 'edit' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100959 operation_state = "COMPLETED"
960 operation_details = "Done"
tierno59d22d22018-09-25 18:10:19 +0200961
tiernoe37b57d2018-12-11 17:22:51 +0000962 self.logger.debug(logging_text + "Exit Ok RO_sdn_id={}".format(RO_sdn_id))
tierno59d22d22018-09-25 18:10:19 +0200963 return
964
tiernocc29b592020-09-18 10:33:18 +0000965 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200966 self.logger.error(logging_text + "Exit Exception {}".format(e))
967 exc = e
968 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100969 self.logger.critical(
970 logging_text + "Exit Exception {}".format(e), exc_info=True
971 )
tierno59d22d22018-09-25 18:10:19 +0200972 exc = e
973 finally:
974 if exc and db_sdn:
975 db_sdn["_admin.operationalState"] = "ERROR"
976 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
kuuse6a470c62019-07-10 13:52:45 +0200977 # Mark the SDN 'edit' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100978 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000979 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000980 try:
981 if db_sdn_update:
982 self.update_db_2("sdns", sdn_id, db_sdn_update)
kuuse6a470c62019-07-10 13:52:45 +0200983 # Register the SDN 'edit' HA task either
984 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100985 self.lcm_tasks.unlock_HA(
986 "sdn",
987 "edit",
988 op_id,
989 operationState=operation_state,
990 detailed_status=operation_details,
991 )
tiernobaa51102018-12-14 13:16:18 +0000992 except DbException as e:
993 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +0200994 self.lcm_tasks.remove("sdn", sdn_id, order_id)
995
kuuse6a470c62019-07-10 13:52:45 +0200996 async def delete(self, sdn_content, order_id):
997
998 # HA tasks and backward compatibility:
999 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
1000 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +01001001 op_id = sdn_content.pop("op_id", None)
1002 if not self.lcm_tasks.lock_HA("sdn", "delete", op_id):
kuuse6a470c62019-07-10 13:52:45 +02001003 return
1004
1005 sdn_id = sdn_content["_id"]
tierno59d22d22018-09-25 18:10:19 +02001006 logging_text = "Task sdn_delete={} ".format(sdn_id)
1007 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +02001008
tierno59d22d22018-09-25 18:10:19 +02001009 db_sdn = None
1010 db_sdn_update = {}
1011 exc = None
1012 step = "Getting sdn from db"
1013 try:
kuuse6a470c62019-07-10 13:52:45 +02001014 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01001015 await self.lcm_tasks.waitfor_related_HA("sdn", "delete", op_id)
kuuse6a470c62019-07-10 13:52:45 +02001016
tierno59d22d22018-09-25 18:10:19 +02001017 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001018 if (
1019 db_sdn.get("_admin")
1020 and db_sdn["_admin"].get("deployed")
1021 and db_sdn["_admin"]["deployed"].get("RO")
1022 ):
tierno59d22d22018-09-25 18:10:19 +02001023 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
1024 RO = ROclient.ROClient(self.loop, **self.ro_config)
1025 step = "Deleting sdn from RO"
1026 try:
1027 await RO.delete("sdn", RO_sdn_id)
1028 except ROclient.ROClientException as e:
1029 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +01001030 self.logger.debug(
1031 logging_text
1032 + "RO_sdn_id={} already deleted".format(RO_sdn_id)
1033 )
tierno59d22d22018-09-25 18:10:19 +02001034 else:
1035 raise
1036 else:
1037 # nothing to delete
garciadeblas5697b8b2021-03-24 09:17:02 +01001038 self.logger.error(
1039 logging_text + "Skipping. There is not RO information at database"
1040 )
tierno59d22d22018-09-25 18:10:19 +02001041 self.db.del_one("sdns", {"_id": sdn_id})
tiernobaa51102018-12-14 13:16:18 +00001042 db_sdn = None
tierno59d22d22018-09-25 18:10:19 +02001043 self.logger.debug("sdn_delete task sdn_id={} Exit Ok".format(sdn_id))
1044 return
1045
tiernocc29b592020-09-18 10:33:18 +00001046 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +02001047 self.logger.error(logging_text + "Exit Exception {}".format(e))
1048 exc = e
1049 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001050 self.logger.critical(
1051 logging_text + "Exit Exception {}".format(e), exc_info=True
1052 )
tierno59d22d22018-09-25 18:10:19 +02001053 exc = e
1054 finally:
1055 if exc and db_sdn:
1056 db_sdn["_admin.operationalState"] = "ERROR"
1057 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
kuuse6a470c62019-07-10 13:52:45 +02001058 # Mark the SDN 'delete' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +01001059 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001060 operation_details = "ERROR {}: {}".format(step, exc)
garciadeblas5697b8b2021-03-24 09:17:02 +01001061 self.lcm_tasks.unlock_HA(
1062 "sdn",
1063 "delete",
1064 op_id,
1065 operationState=operation_state,
1066 detailed_status=operation_details,
1067 )
tiernobaa51102018-12-14 13:16:18 +00001068 try:
1069 if db_sdn and db_sdn_update:
1070 self.update_db_2("sdns", sdn_id, db_sdn_update)
kuuse6a470c62019-07-10 13:52:45 +02001071 # If the SDN 'delete' HA task was succesful, the DB entry has been deleted,
1072 # which means that there is nowhere to register this task, so do nothing here.
tiernobaa51102018-12-14 13:16:18 +00001073 except DbException as e:
1074 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +02001075 self.lcm_tasks.remove("sdn", sdn_id, order_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001076
1077
1078class K8sClusterLcm(LcmBase):
tierno0d7f9372020-09-30 07:56:29 +00001079 timeout_create = 300
calvinosanch9f9c6f22019-11-04 13:37:39 +01001080
bravof922c4172020-11-24 21:21:43 -03001081 def __init__(self, msg, lcm_tasks, config, loop):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001082 """
1083 Init, Connect to database, filesystem storage, and messaging
1084 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
1085 :return: None
1086 """
1087
garciadeblas5697b8b2021-03-24 09:17:02 +01001088 self.logger = logging.getLogger("lcm.k8scluster")
calvinosanch9f9c6f22019-11-04 13:37:39 +01001089 self.loop = loop
1090 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +00001091 self.vca_config = config["VCA"]
bravof922c4172020-11-24 21:21:43 -03001092
1093 super().__init__(msg, self.logger)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001094
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001095 self.helm2_k8scluster = K8sHelmConnector(
calvinosanch9f9c6f22019-11-04 13:37:39 +01001096 kubectl_command=self.vca_config.get("kubectlpath"),
1097 helm_command=self.vca_config.get("helmpath"),
calvinosanch9f9c6f22019-11-04 13:37:39 +01001098 log=self.logger,
bravof922c4172020-11-24 21:21:43 -03001099 on_update_db=None,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001100 db=self.db,
garciadeblas5697b8b2021-03-24 09:17:02 +01001101 fs=self.fs,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001102 )
1103
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001104 self.helm3_k8scluster = K8sHelm3Connector(
1105 kubectl_command=self.vca_config.get("kubectlpath"),
1106 helm_command=self.vca_config.get("helm3path"),
1107 fs=self.fs,
1108 log=self.logger,
1109 db=self.db,
garciadeblas5697b8b2021-03-24 09:17:02 +01001110 on_update_db=None,
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001111 )
1112
Adam Israelbaacc302019-12-01 12:41:39 -05001113 self.juju_k8scluster = K8sJujuConnector(
1114 kubectl_command=self.vca_config.get("kubectlpath"),
1115 juju_command=self.vca_config.get("jujupath"),
Adam Israelbaacc302019-12-01 12:41:39 -05001116 log=self.logger,
David Garciaba89cbb2020-10-16 13:05:34 +02001117 loop=self.loop,
1118 on_update_db=None,
bravof922c4172020-11-24 21:21:43 -03001119 db=self.db,
garciadeblas5697b8b2021-03-24 09:17:02 +01001120 fs=self.fs,
Adam Israelbaacc302019-12-01 12:41:39 -05001121 )
bravof922c4172020-11-24 21:21:43 -03001122
tiernofa076c32020-08-13 14:25:47 +00001123 self.k8s_map = {
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001124 "helm-chart": self.helm2_k8scluster,
1125 "helm-chart-v3": self.helm3_k8scluster,
tiernofa076c32020-08-13 14:25:47 +00001126 "juju-bundle": self.juju_k8scluster,
1127 }
Adam Israelbaacc302019-12-01 12:41:39 -05001128
calvinosanch9f9c6f22019-11-04 13:37:39 +01001129 async def create(self, k8scluster_content, order_id):
1130
garciadeblas5697b8b2021-03-24 09:17:02 +01001131 op_id = k8scluster_content.pop("op_id", None)
1132 if not self.lcm_tasks.lock_HA("k8scluster", "create", op_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001133 return
1134
1135 k8scluster_id = k8scluster_content["_id"]
calvinosanch9f9c6f22019-11-04 13:37:39 +01001136 logging_text = "Task k8scluster_create={} ".format(k8scluster_id)
1137 self.logger.debug(logging_text + "Enter")
1138
1139 db_k8scluster = None
1140 db_k8scluster_update = {}
calvinosanch9f9c6f22019-11-04 13:37:39 +01001141 exc = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001142 try:
1143 step = "Getting k8scluster-id='{}' from db".format(k8scluster_id)
1144 self.logger.debug(logging_text + step)
1145 db_k8scluster = self.db.get_one("k8sclusters", {"_id": k8scluster_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001146 self.db.encrypt_decrypt_fields(
1147 db_k8scluster.get("credentials"),
1148 "decrypt",
1149 ["password", "secret"],
1150 schema_version=db_k8scluster["schema_version"],
1151 salt=db_k8scluster["_id"],
1152 )
tiernoe19bd742019-12-05 16:09:08 +00001153 k8s_credentials = yaml.safe_dump(db_k8scluster.get("credentials"))
tiernofa076c32020-08-13 14:25:47 +00001154 pending_tasks = []
1155 task2name = {}
tierno78e3ec62020-07-14 10:46:57 +00001156 init_target = deep_get(db_k8scluster, ("_admin", "init"))
tiernofa076c32020-08-13 14:25:47 +00001157 step = "Launching k8scluster init tasks"
Gabriel Cuba1b2b8402022-03-22 11:12:12 -05001158
1159 k8s_deploy_methods = db_k8scluster.get("deployment_methods", {})
1160 # for backwards compatibility and all-false case
1161 if not any(k8s_deploy_methods.values()):
1162 k8s_deploy_methods = {"helm-chart": True, "juju-bundle": True, "helm-chart-v3": True}
1163 deploy_methods = tuple(filter(k8s_deploy_methods.get, k8s_deploy_methods))
1164
1165 for task_name in deploy_methods:
tiernofa076c32020-08-13 14:25:47 +00001166 if init_target and task_name not in init_target:
1167 continue
David Garciac1fe90a2021-03-31 19:12:02 +02001168 task = asyncio.ensure_future(
1169 self.k8s_map[task_name].init_env(
1170 k8s_credentials,
1171 reuse_cluster_uuid=k8scluster_id,
1172 vca_id=db_k8scluster.get("vca_id"),
1173 )
1174 )
tiernofa076c32020-08-13 14:25:47 +00001175 pending_tasks.append(task)
1176 task2name[task] = task_name
Adam Israelbaacc302019-12-01 12:41:39 -05001177
tiernofa076c32020-08-13 14:25:47 +00001178 error_text_list = []
1179 tasks_name_ok = []
1180 reached_timeout = False
1181 now = time()
Adam Israelbaacc302019-12-01 12:41:39 -05001182
tiernofa076c32020-08-13 14:25:47 +00001183 while pending_tasks:
garciadeblas5697b8b2021-03-24 09:17:02 +01001184 _timeout = max(
1185 1, self.timeout_create - (time() - now)
1186 ) # ensure not negative with max
tiernofa076c32020-08-13 14:25:47 +00001187 step = "Waiting for k8scluster init tasks"
garciadeblas5697b8b2021-03-24 09:17:02 +01001188 done, pending_tasks = await asyncio.wait(
1189 pending_tasks, timeout=_timeout, return_when=asyncio.FIRST_COMPLETED
1190 )
tiernofa076c32020-08-13 14:25:47 +00001191 if not done:
1192 # timeout. Set timeout is reached and process pending as if they hase been finished
1193 done = pending_tasks
1194 pending_tasks = None
1195 reached_timeout = True
1196 for task in done:
1197 task_name = task2name[task]
1198 if reached_timeout:
1199 exc = "Timeout"
1200 elif task.cancelled():
1201 exc = "Cancelled"
1202 else:
1203 exc = task.exception()
1204
1205 if exc:
garciadeblas5697b8b2021-03-24 09:17:02 +01001206 error_text_list.append(
1207 "Failing init {}: {}".format(task_name, exc)
1208 )
1209 db_k8scluster_update[
1210 "_admin.{}.error_msg".format(task_name)
1211 ] = str(exc)
tiernofa076c32020-08-13 14:25:47 +00001212 db_k8scluster_update["_admin.{}.id".format(task_name)] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001213 db_k8scluster_update[
1214 "_admin.{}.operationalState".format(task_name)
1215 ] = "ERROR"
1216 self.logger.error(
1217 logging_text + "{} init fail: {}".format(task_name, exc),
1218 exc_info=not isinstance(exc, (N2VCException, str)),
1219 )
tiernofa076c32020-08-13 14:25:47 +00001220 else:
1221 k8s_id, uninstall_sw = task.result()
1222 tasks_name_ok.append(task_name)
garciadeblas5697b8b2021-03-24 09:17:02 +01001223 self.logger.debug(
1224 logging_text
1225 + "{} init success. id={} created={}".format(
1226 task_name, k8s_id, uninstall_sw
1227 )
1228 )
1229 db_k8scluster_update[
1230 "_admin.{}.error_msg".format(task_name)
1231 ] = None
tiernofa076c32020-08-13 14:25:47 +00001232 db_k8scluster_update["_admin.{}.id".format(task_name)] = k8s_id
garciadeblas5697b8b2021-03-24 09:17:02 +01001233 db_k8scluster_update[
1234 "_admin.{}.created".format(task_name)
1235 ] = uninstall_sw
1236 db_k8scluster_update[
1237 "_admin.{}.operationalState".format(task_name)
1238 ] = "ENABLED"
tiernofa076c32020-08-13 14:25:47 +00001239 # update database
1240 step = "Updating database for " + task_name
1241 self.update_db_2("k8sclusters", k8scluster_id, db_k8scluster_update)
tiernocc29b592020-09-18 10:33:18 +00001242 if tasks_name_ok:
1243 operation_details = "ready for " + ", ".join(tasks_name_ok)
1244 operation_state = "COMPLETED"
garciadeblas5697b8b2021-03-24 09:17:02 +01001245 db_k8scluster_update["_admin.operationalState"] = (
1246 "ENABLED" if not error_text_list else "DEGRADED"
1247 )
tiernocc29b592020-09-18 10:33:18 +00001248 operation_details += "; " + ";".join(error_text_list)
1249 else:
tiernoe19bd742019-12-05 16:09:08 +00001250 db_k8scluster_update["_admin.operationalState"] = "ERROR"
tiernofa076c32020-08-13 14:25:47 +00001251 operation_state = "FAILED"
tiernocc29b592020-09-18 10:33:18 +00001252 operation_details = ";".join(error_text_list)
1253 db_k8scluster_update["_admin.detailed-status"] = operation_details
tiernofa076c32020-08-13 14:25:47 +00001254 self.logger.debug(logging_text + "Done. Result: " + operation_state)
1255 exc = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001256
1257 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001258 if isinstance(
1259 e,
1260 (
1261 LcmException,
1262 DbException,
1263 K8sException,
1264 N2VCException,
1265 asyncio.CancelledError,
1266 ),
1267 ):
tiernocc29b592020-09-18 10:33:18 +00001268 self.logger.error(logging_text + "Exit Exception {}".format(e))
1269 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001270 self.logger.critical(
1271 logging_text + "Exit Exception {}".format(e), exc_info=True
1272 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001273 exc = e
1274 finally:
1275 if exc and db_k8scluster:
1276 db_k8scluster_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +01001277 db_k8scluster_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1278 step, exc
1279 )
1280 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001281 operation_details = "ERROR {}: {}".format(step, exc)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001282 try:
tiernofa076c32020-08-13 14:25:47 +00001283 if db_k8scluster and db_k8scluster_update:
calvinosanch9f9c6f22019-11-04 13:37:39 +01001284 self.update_db_2("k8sclusters", k8scluster_id, db_k8scluster_update)
Adam Israelbaacc302019-12-01 12:41:39 -05001285
tiernofa076c32020-08-13 14:25:47 +00001286 # Register the operation and unlock
garciadeblas5697b8b2021-03-24 09:17:02 +01001287 self.lcm_tasks.unlock_HA(
1288 "k8scluster",
1289 "create",
1290 op_id,
1291 operationState=operation_state,
1292 detailed_status=operation_details,
1293 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001294 except DbException as e:
1295 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno0fedb032020-03-12 17:19:06 +00001296 self.lcm_tasks.remove("k8scluster", k8scluster_id, order_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001297
dariofaccin015edaa2023-01-23 18:13:27 +01001298 async def edit(self, k8scluster_content, order_id):
1299
1300 op_id = k8scluster_content.pop("op_id", None)
1301 if not self.lcm_tasks.lock_HA("k8scluster", "edit", op_id):
1302 return
1303
1304 k8scluster_id = k8scluster_content["_id"]
1305 logging_text = "Task k8scluster_edit={} ".format(k8scluster_id)
1306 self.logger.debug(logging_text + "Enter")
1307
1308 # TODO the implementation is pending and will be part of a new feature
1309 # It will support rotation of certificates, update of credentials and K8S API endpoint
1310 # At the moment the operation is set as completed
1311
1312 operation_state = "COMPLETED"
1313 operation_details = "Not implemented"
1314
1315 self.lcm_tasks.unlock_HA(
1316 "k8scluster",
1317 "edit",
1318 op_id,
1319 operationState=operation_state,
1320 detailed_status=operation_details,
1321 )
1322 self.lcm_tasks.remove("k8scluster", k8scluster_id, order_id)
1323
calvinosanch9f9c6f22019-11-04 13:37:39 +01001324 async def delete(self, k8scluster_content, order_id):
1325
1326 # HA tasks and backward compatibility:
1327 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
1328 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
1329 # Register 'delete' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +01001330 op_id = k8scluster_content.pop("op_id", None)
1331 if not self.lcm_tasks.lock_HA("k8scluster", "delete", op_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001332 return
1333
1334 k8scluster_id = k8scluster_content["_id"]
calvinosanch9f9c6f22019-11-04 13:37:39 +01001335 logging_text = "Task k8scluster_delete={} ".format(k8scluster_id)
1336 self.logger.debug(logging_text + "Enter")
1337
1338 db_k8scluster = None
1339 db_k8scluster_update = {}
1340 exc = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001341 try:
1342 step = "Getting k8scluster='{}' from db".format(k8scluster_id)
1343 self.logger.debug(logging_text + step)
1344 db_k8scluster = self.db.get_one("k8sclusters", {"_id": k8scluster_id})
tierno626e0152019-11-29 14:16:16 +00001345 k8s_hc_id = deep_get(db_k8scluster, ("_admin", "helm-chart", "id"))
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001346 k8s_h3c_id = deep_get(db_k8scluster, ("_admin", "helm-chart-v3", "id"))
Adam Israelbaacc302019-12-01 12:41:39 -05001347 k8s_jb_id = deep_get(db_k8scluster, ("_admin", "juju-bundle", "id"))
1348
tierno626e0152019-11-29 14:16:16 +00001349 cluster_removed = True
tierno78e3ec62020-07-14 10:46:57 +00001350 if k8s_jb_id: # delete in reverse order of creation
1351 step = "Removing juju-bundle '{}'".format(k8s_jb_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01001352 uninstall_sw = (
1353 deep_get(db_k8scluster, ("_admin", "juju-bundle", "created"))
1354 or False
1355 )
David Garciac1fe90a2021-03-31 19:12:02 +02001356 cluster_removed = await self.juju_k8scluster.reset(
1357 cluster_uuid=k8s_jb_id,
1358 uninstall_sw=uninstall_sw,
1359 vca_id=db_k8scluster.get("vca_id"),
1360 )
tierno78e3ec62020-07-14 10:46:57 +00001361 db_k8scluster_update["_admin.juju-bundle.id"] = None
tiernocc29b592020-09-18 10:33:18 +00001362 db_k8scluster_update["_admin.juju-bundle.operationalState"] = "DISABLED"
tierno78e3ec62020-07-14 10:46:57 +00001363
tierno626e0152019-11-29 14:16:16 +00001364 if k8s_hc_id:
tiernod58995a2020-05-20 14:35:19 +00001365 step = "Removing helm-chart '{}'".format(k8s_hc_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01001366 uninstall_sw = (
1367 deep_get(db_k8scluster, ("_admin", "helm-chart", "created"))
1368 or False
1369 )
1370 cluster_removed = await self.helm2_k8scluster.reset(
1371 cluster_uuid=k8s_hc_id, uninstall_sw=uninstall_sw
1372 )
tiernod58995a2020-05-20 14:35:19 +00001373 db_k8scluster_update["_admin.helm-chart.id"] = None
tiernocc29b592020-09-18 10:33:18 +00001374 db_k8scluster_update["_admin.helm-chart.operationalState"] = "DISABLED"
Adam Israelbaacc302019-12-01 12:41:39 -05001375
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001376 if k8s_h3c_id:
1377 step = "Removing helm-chart-v3 '{}'".format(k8s_hc_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01001378 uninstall_sw = (
1379 deep_get(db_k8scluster, ("_admin", "helm-chart-v3", "created"))
1380 or False
1381 )
1382 cluster_removed = await self.helm3_k8scluster.reset(
1383 cluster_uuid=k8s_h3c_id, uninstall_sw=uninstall_sw
1384 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001385 db_k8scluster_update["_admin.helm-chart-v3.id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001386 db_k8scluster_update[
1387 "_admin.helm-chart-v3.operationalState"
1388 ] = "DISABLED"
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001389
lloretgallegedc5f332020-02-20 11:50:50 +01001390 # Try to remove from cluster_inserted to clean old versions
tiernoe19bd742019-12-05 16:09:08 +00001391 if k8s_hc_id and cluster_removed:
1392 step = "Removing k8scluster='{}' from k8srepos".format(k8scluster_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001393 self.logger.debug(logging_text + step)
garciadeblas5697b8b2021-03-24 09:17:02 +01001394 db_k8srepo_list = self.db.get_list(
1395 "k8srepos", {"_admin.cluster-inserted": k8s_hc_id}
1396 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001397 for k8srepo in db_k8srepo_list:
tiernoe19bd742019-12-05 16:09:08 +00001398 try:
1399 cluster_list = k8srepo["_admin"]["cluster-inserted"]
1400 cluster_list.remove(k8s_hc_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01001401 self.update_db_2(
1402 "k8srepos",
1403 k8srepo["_id"],
1404 {"_admin.cluster-inserted": cluster_list},
1405 )
tiernoe19bd742019-12-05 16:09:08 +00001406 except Exception as e:
1407 self.logger.error("{}: {}".format(step, e))
tiernod58995a2020-05-20 14:35:19 +00001408 self.db.del_one("k8sclusters", {"_id": k8scluster_id})
tierno78e3ec62020-07-14 10:46:57 +00001409 db_k8scluster_update = None
1410 self.logger.debug(logging_text + "Done")
calvinosanch9f9c6f22019-11-04 13:37:39 +01001411
1412 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001413 if isinstance(
1414 e,
1415 (
1416 LcmException,
1417 DbException,
1418 K8sException,
1419 N2VCException,
1420 asyncio.CancelledError,
1421 ),
1422 ):
tierno0fedb032020-03-12 17:19:06 +00001423 self.logger.error(logging_text + "Exit Exception {}".format(e))
1424 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001425 self.logger.critical(
1426 logging_text + "Exit Exception {}".format(e), exc_info=True
1427 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001428 exc = e
1429 finally:
1430 if exc and db_k8scluster:
1431 db_k8scluster_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +01001432 db_k8scluster_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1433 step, exc
1434 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001435 # Mark the WIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +01001436 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001437 operation_details = "ERROR {}: {}".format(step, exc)
1438 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001439 operation_state = "COMPLETED"
tiernofa076c32020-08-13 14:25:47 +00001440 operation_details = "deleted"
1441
calvinosanch9f9c6f22019-11-04 13:37:39 +01001442 try:
1443 if db_k8scluster_update:
1444 self.update_db_2("k8sclusters", k8scluster_id, db_k8scluster_update)
1445 # Register the K8scluster 'delete' HA task either
1446 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +01001447 self.lcm_tasks.unlock_HA(
1448 "k8scluster",
1449 "delete",
1450 op_id,
1451 operationState=operation_state,
1452 detailed_status=operation_details,
1453 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001454 except DbException as e:
1455 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno0fedb032020-03-12 17:19:06 +00001456 self.lcm_tasks.remove("k8scluster", k8scluster_id, order_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001457
1458
David Garciac1fe90a2021-03-31 19:12:02 +02001459class VcaLcm(LcmBase):
1460 timeout_create = 30
1461
1462 def __init__(self, msg, lcm_tasks, config, loop):
1463 """
1464 Init, Connect to database, filesystem storage, and messaging
1465 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
1466 :return: None
1467 """
1468
1469 self.logger = logging.getLogger("lcm.vca")
1470 self.loop = loop
1471 self.lcm_tasks = lcm_tasks
1472
1473 super().__init__(msg, self.logger)
1474
1475 # create N2VC connector
1476 self.n2vc = N2VCJujuConnector(
garciadeblas5697b8b2021-03-24 09:17:02 +01001477 log=self.logger, loop=self.loop, fs=self.fs, db=self.db
David Garciac1fe90a2021-03-31 19:12:02 +02001478 )
1479
1480 def _get_vca_by_id(self, vca_id: str) -> dict:
1481 db_vca = self.db.get_one("vca", {"_id": vca_id})
1482 self.db.encrypt_decrypt_fields(
1483 db_vca,
1484 "decrypt",
1485 ["secret", "cacert"],
garciadeblas5697b8b2021-03-24 09:17:02 +01001486 schema_version=db_vca["schema_version"],
1487 salt=db_vca["_id"],
David Garciac1fe90a2021-03-31 19:12:02 +02001488 )
1489 return db_vca
1490
1491 async def create(self, vca_content, order_id):
1492 op_id = vca_content.pop("op_id", None)
1493 if not self.lcm_tasks.lock_HA("vca", "create", op_id):
1494 return
1495
1496 vca_id = vca_content["_id"]
1497 self.logger.debug("Task vca_create={} {}".format(vca_id, "Enter"))
1498
1499 db_vca = None
1500 db_vca_update = {}
1501
1502 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01001503 self.logger.debug(
1504 "Task vca_create={} {}".format(vca_id, "Getting vca from db")
1505 )
David Garciac1fe90a2021-03-31 19:12:02 +02001506 db_vca = self._get_vca_by_id(vca_id)
1507
1508 task = asyncio.ensure_future(
1509 asyncio.wait_for(
1510 self.n2vc.validate_vca(db_vca["_id"]),
1511 timeout=self.timeout_create,
1512 )
1513 )
1514
1515 await asyncio.wait([task], return_when=asyncio.FIRST_COMPLETED)
1516 if task.exception():
1517 raise task.exception()
garciadeblas5697b8b2021-03-24 09:17:02 +01001518 self.logger.debug(
1519 "Task vca_create={} {}".format(
1520 vca_id, "vca registered and validated successfully"
1521 )
1522 )
David Garciac1fe90a2021-03-31 19:12:02 +02001523 db_vca_update["_admin.operationalState"] = "ENABLED"
1524 db_vca_update["_admin.detailed-status"] = "Connectivity: ok"
1525 operation_details = "VCA validated"
1526 operation_state = "COMPLETED"
1527
garciadeblas5697b8b2021-03-24 09:17:02 +01001528 self.logger.debug(
1529 "Task vca_create={} {}".format(
1530 vca_id, "Done. Result: {}".format(operation_state)
1531 )
1532 )
David Garciac1fe90a2021-03-31 19:12:02 +02001533
1534 except Exception as e:
1535 error_msg = "Failed with exception: {}".format(e)
1536 self.logger.error("Task vca_create={} {}".format(vca_id, error_msg))
1537 db_vca_update["_admin.operationalState"] = "ERROR"
1538 db_vca_update["_admin.detailed-status"] = error_msg
1539 operation_state = "FAILED"
1540 operation_details = error_msg
1541 finally:
1542 try:
1543 self.update_db_2("vca", vca_id, db_vca_update)
1544
1545 # Register the operation and unlock
1546 self.lcm_tasks.unlock_HA(
1547 "vca",
1548 "create",
1549 op_id,
1550 operationState=operation_state,
garciadeblas5697b8b2021-03-24 09:17:02 +01001551 detailed_status=operation_details,
David Garciac1fe90a2021-03-31 19:12:02 +02001552 )
1553 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001554 self.logger.error(
1555 "Task vca_create={} {}".format(
1556 vca_id, "Cannot update database: {}".format(e)
1557 )
1558 )
David Garciac1fe90a2021-03-31 19:12:02 +02001559 self.lcm_tasks.remove("vca", vca_id, order_id)
1560
1561 async def delete(self, vca_content, order_id):
1562
1563 # HA tasks and backward compatibility:
1564 # If "vim_content" does not include "op_id", we a running a legacy NBI version.
1565 # In such a case, HA is not supported by NBI, "op_id" is None, and lock_HA() will do nothing.
1566 # Register "delete" task here for related future HA operations
1567 op_id = vca_content.pop("op_id", None)
1568 if not self.lcm_tasks.lock_HA("vca", "delete", op_id):
1569 return
1570
1571 db_vca_update = {}
1572 vca_id = vca_content["_id"]
1573
1574 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01001575 self.logger.debug(
1576 "Task vca_delete={} {}".format(vca_id, "Deleting vca from db")
1577 )
David Garciac1fe90a2021-03-31 19:12:02 +02001578 self.db.del_one("vca", {"_id": vca_id})
1579 db_vca_update = None
1580 operation_details = "deleted"
1581 operation_state = "COMPLETED"
1582
garciadeblas5697b8b2021-03-24 09:17:02 +01001583 self.logger.debug(
1584 "Task vca_delete={} {}".format(
1585 vca_id, "Done. Result: {}".format(operation_state)
1586 )
1587 )
David Garciac1fe90a2021-03-31 19:12:02 +02001588 except Exception as e:
1589 error_msg = "Failed with exception: {}".format(e)
1590 self.logger.error("Task vca_delete={} {}".format(vca_id, error_msg))
1591 db_vca_update["_admin.operationalState"] = "ERROR"
1592 db_vca_update["_admin.detailed-status"] = error_msg
1593 operation_state = "FAILED"
1594 operation_details = error_msg
1595 finally:
1596 try:
1597 self.update_db_2("vca", vca_id, db_vca_update)
1598 self.lcm_tasks.unlock_HA(
1599 "vca",
1600 "delete",
1601 op_id,
1602 operationState=operation_state,
1603 detailed_status=operation_details,
1604 )
1605 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001606 self.logger.error(
1607 "Task vca_delete={} {}".format(
1608 vca_id, "Cannot update database: {}".format(e)
1609 )
1610 )
David Garciac1fe90a2021-03-31 19:12:02 +02001611 self.lcm_tasks.remove("vca", vca_id, order_id)
1612
1613
calvinosanch9f9c6f22019-11-04 13:37:39 +01001614class K8sRepoLcm(LcmBase):
bravof922c4172020-11-24 21:21:43 -03001615 def __init__(self, msg, lcm_tasks, config, loop):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001616 """
1617 Init, Connect to database, filesystem storage, and messaging
1618 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
1619 :return: None
1620 """
1621
garciadeblas5697b8b2021-03-24 09:17:02 +01001622 self.logger = logging.getLogger("lcm.k8srepo")
calvinosanch9f9c6f22019-11-04 13:37:39 +01001623 self.loop = loop
1624 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +00001625 self.vca_config = config["VCA"]
calvinosanch9f9c6f22019-11-04 13:37:39 +01001626
bravof922c4172020-11-24 21:21:43 -03001627 super().__init__(msg, self.logger)
1628
1629 self.k8srepo = K8sHelmConnector(
1630 kubectl_command=self.vca_config.get("kubectlpath"),
1631 helm_command=self.vca_config.get("helmpath"),
1632 fs=self.fs,
1633 log=self.logger,
1634 db=self.db,
garciadeblas5697b8b2021-03-24 09:17:02 +01001635 on_update_db=None,
bravof922c4172020-11-24 21:21:43 -03001636 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001637
1638 async def create(self, k8srepo_content, order_id):
1639
1640 # HA tasks and backward compatibility:
1641 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
1642 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
1643 # Register 'create' task here for related future HA operations
1644
garciadeblas5697b8b2021-03-24 09:17:02 +01001645 op_id = k8srepo_content.pop("op_id", None)
1646 if not self.lcm_tasks.lock_HA("k8srepo", "create", op_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001647 return
1648
1649 k8srepo_id = k8srepo_content.get("_id")
1650 logging_text = "Task k8srepo_create={} ".format(k8srepo_id)
1651 self.logger.debug(logging_text + "Enter")
1652
1653 db_k8srepo = None
1654 db_k8srepo_update = {}
1655 exc = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001656 operation_state = "COMPLETED"
1657 operation_details = ""
calvinosanch9f9c6f22019-11-04 13:37:39 +01001658 try:
1659 step = "Getting k8srepo-id='{}' from db".format(k8srepo_id)
1660 self.logger.debug(logging_text + step)
1661 db_k8srepo = self.db.get_one("k8srepos", {"_id": k8srepo_id})
calvinosanch9f9c6f22019-11-04 13:37:39 +01001662 db_k8srepo_update["_admin.operationalState"] = "ENABLED"
1663 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001664 self.logger.error(
1665 logging_text + "Exit Exception {}".format(e),
1666 exc_info=not isinstance(
1667 e,
1668 (
1669 LcmException,
1670 DbException,
1671 K8sException,
1672 N2VCException,
1673 asyncio.CancelledError,
1674 ),
1675 ),
1676 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001677 exc = e
1678 finally:
1679 if exc and db_k8srepo:
1680 db_k8srepo_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +01001681 db_k8srepo_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1682 step, exc
1683 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001684 # Mark the WIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +01001685 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001686 operation_details = "ERROR {}: {}".format(step, exc)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001687 try:
1688 if db_k8srepo_update:
1689 self.update_db_2("k8srepos", k8srepo_id, db_k8srepo_update)
1690 # Register the K8srepo 'create' HA task either
1691 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +01001692 self.lcm_tasks.unlock_HA(
1693 "k8srepo",
1694 "create",
1695 op_id,
1696 operationState=operation_state,
1697 detailed_status=operation_details,
1698 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001699 except DbException as e:
1700 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1701 self.lcm_tasks.remove("k8srepo", k8srepo_id, order_id)
1702
1703 async def delete(self, k8srepo_content, order_id):
1704
1705 # HA tasks and backward compatibility:
1706 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
1707 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
1708 # Register 'delete' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +01001709 op_id = k8srepo_content.pop("op_id", None)
1710 if not self.lcm_tasks.lock_HA("k8srepo", "delete", op_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001711 return
1712
1713 k8srepo_id = k8srepo_content.get("_id")
1714 logging_text = "Task k8srepo_delete={} ".format(k8srepo_id)
1715 self.logger.debug(logging_text + "Enter")
1716
1717 db_k8srepo = None
1718 db_k8srepo_update = {}
1719
tierno28c63da2020-04-20 16:28:56 +00001720 exc = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001721 operation_state = "COMPLETED"
1722 operation_details = ""
calvinosanch9f9c6f22019-11-04 13:37:39 +01001723 try:
1724 step = "Getting k8srepo-id='{}' from db".format(k8srepo_id)
1725 self.logger.debug(logging_text + step)
1726 db_k8srepo = self.db.get_one("k8srepos", {"_id": k8srepo_id})
calvinosanch9f9c6f22019-11-04 13:37:39 +01001727
1728 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001729 self.logger.error(
1730 logging_text + "Exit Exception {}".format(e),
1731 exc_info=not isinstance(
1732 e,
1733 (
1734 LcmException,
1735 DbException,
1736 K8sException,
1737 N2VCException,
1738 asyncio.CancelledError,
1739 ),
1740 ),
1741 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001742 exc = e
1743 finally:
1744 if exc and db_k8srepo:
1745 db_k8srepo_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +01001746 db_k8srepo_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1747 step, exc
1748 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001749 # Mark the WIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +01001750 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001751 operation_details = "ERROR {}: {}".format(step, exc)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001752 try:
1753 if db_k8srepo_update:
1754 self.update_db_2("k8srepos", k8srepo_id, db_k8srepo_update)
1755 # Register the K8srepo 'delete' HA task either
1756 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +01001757 self.lcm_tasks.unlock_HA(
1758 "k8srepo",
1759 "delete",
1760 op_id,
1761 operationState=operation_state,
1762 detailed_status=operation_details,
1763 )
tierno28c63da2020-04-20 16:28:56 +00001764 self.db.del_one("k8srepos", {"_id": k8srepo_id})
calvinosanch9f9c6f22019-11-04 13:37:39 +01001765 except DbException as e:
1766 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1767 self.lcm_tasks.remove("k8srepo", k8srepo_id, order_id)