blob: dcb62b6b52a13e45dac0febde177fa9fc3f62c6f [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
almagiacdd20ae2024-12-13 09:45:45 +010025from osm_lcm.n2vc.k8s_helm3_conn import K8sHelm3Connector
26from osm_lcm.n2vc.k8s_juju_conn import K8sJujuConnector
27from osm_lcm.n2vc.n2vc_juju_conn import N2VCJujuConnector
28from osm_lcm.n2vc.exceptions import K8sException, N2VCException
tierno59d22d22018-09-25 18:10:19 +020029from osm_common.dbbase import DbException
30from copy import deepcopy
tiernofa076c32020-08-13 14:25:47 +000031from time import time
tierno59d22d22018-09-25 18:10:19 +020032
33__author__ = "Alfonso Tierno"
34
35
36class VimLcm(LcmBase):
tierno17a612f2018-10-23 11:30:42 +020037 # values that are encrypted at vim config because they are passwords
garciadeblas5697b8b2021-03-24 09:17:02 +010038 vim_config_encrypted = {
39 "1.1": ("admin_password", "nsx_password", "vcenter_password"),
40 "default": (
41 "admin_password",
42 "nsx_password",
43 "vcenter_password",
44 "vrops_password",
45 ),
46 }
tierno59d22d22018-09-25 18:10:19 +020047
Gabriel Cubae7898982023-05-11 01:57:21 -050048 def __init__(self, msg, lcm_tasks, config):
tierno59d22d22018-09-25 18:10:19 +020049 """
50 Init, Connect to database, filesystem storage, and messaging
51 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
52 :return: None
53 """
54
garciadeblas5697b8b2021-03-24 09:17:02 +010055 self.logger = logging.getLogger("lcm.vim")
tierno59d22d22018-09-25 18:10:19 +020056 self.lcm_tasks = lcm_tasks
Luis Vegaa27dc532022-11-11 20:10:49 +000057 self.ro_config = config["RO"]
tierno59d22d22018-09-25 18:10:19 +020058
bravof922c4172020-11-24 21:21:43 -030059 super().__init__(msg, self.logger)
tierno59d22d22018-09-25 18:10:19 +020060
61 async def create(self, vim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +020062 # HA tasks and backward compatibility:
63 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
64 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
65 # Register 'create' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +010066 op_id = vim_content.pop("op_id", None)
67 if not self.lcm_tasks.lock_HA("vim", "create", op_id):
kuuse6a470c62019-07-10 13:52:45 +020068 return
69
tierno59d22d22018-09-25 18:10:19 +020070 vim_id = vim_content["_id"]
71 logging_text = "Task vim_create={} ".format(vim_id)
72 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +020073
tierno59d22d22018-09-25 18:10:19 +020074 db_vim = None
75 db_vim_update = {}
76 exc = None
77 RO_sdn_id = None
78 try:
79 step = "Getting vim-id='{}' from db".format(vim_id)
80 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
garciadeblas5697b8b2021-03-24 09:17:02 +010081 if vim_content.get("config") and vim_content["config"].get(
82 "sdn-controller"
83 ):
84 step = "Getting sdn-controller-id='{}' from db".format(
85 vim_content["config"]["sdn-controller"]
86 )
87 db_sdn = self.db.get_one(
88 "sdns", {"_id": vim_content["config"]["sdn-controller"]}
89 )
kuuse6a470c62019-07-10 13:52:45 +020090
91 # If the VIM account has an associated SDN account, also
92 # wait for any previous tasks in process for the SDN
garciadeblas5697b8b2021-03-24 09:17:02 +010093 await self.lcm_tasks.waitfor_related_HA("sdn", "ANY", db_sdn["_id"])
kuuse6a470c62019-07-10 13:52:45 +020094
garciadeblas5697b8b2021-03-24 09:17:02 +010095 if (
96 db_sdn.get("_admin")
97 and db_sdn["_admin"].get("deployed")
98 and db_sdn["_admin"]["deployed"].get("RO")
99 ):
tierno59d22d22018-09-25 18:10:19 +0200100 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
101 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100102 raise LcmException(
103 "sdn-controller={} is not available. Not deployed at RO".format(
104 vim_content["config"]["sdn-controller"]
105 )
106 )
tierno59d22d22018-09-25 18:10:19 +0200107
108 step = "Creating vim at RO"
tiernobaa51102018-12-14 13:16:18 +0000109 db_vim_update["_admin.deployed.RO"] = None
tierno59d22d22018-09-25 18:10:19 +0200110 db_vim_update["_admin.detailed-status"] = step
111 self.update_db_2("vim_accounts", vim_id, db_vim_update)
Gabriel Cubae7898982023-05-11 01:57:21 -0500112 RO = ROclient.ROClient(**self.ro_config)
tierno59d22d22018-09-25 18:10:19 +0200113 vim_RO = deepcopy(vim_content)
114 vim_RO.pop("_id", None)
115 vim_RO.pop("_admin", None)
tierno17a612f2018-10-23 11:30:42 +0200116 schema_version = vim_RO.pop("schema_version", None)
tierno59d22d22018-09-25 18:10:19 +0200117 vim_RO.pop("schema_type", None)
118 vim_RO.pop("vim_tenant_name", None)
119 vim_RO["type"] = vim_RO.pop("vim_type")
120 vim_RO.pop("vim_user", None)
121 vim_RO.pop("vim_password", None)
122 if RO_sdn_id:
123 vim_RO["config"]["sdn-controller"] = RO_sdn_id
124 desc = await RO.create("vim", descriptor=vim_RO)
125 RO_vim_id = desc["uuid"]
126 db_vim_update["_admin.deployed.RO"] = RO_vim_id
garciadeblas5697b8b2021-03-24 09:17:02 +0100127 self.logger.debug(
128 logging_text + "VIM created at RO_vim_id={}".format(RO_vim_id)
129 )
tierno59d22d22018-09-25 18:10:19 +0200130
131 step = "Creating vim_account at RO"
132 db_vim_update["_admin.detailed-status"] = step
133 self.update_db_2("vim_accounts", vim_id, db_vim_update)
134
tierno17a612f2018-10-23 11:30:42 +0200135 if vim_content.get("vim_password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100136 vim_content["vim_password"] = self.db.decrypt(
137 vim_content["vim_password"],
138 schema_version=schema_version,
139 salt=vim_id,
140 )
141 vim_account_RO = {
142 "vim_tenant_name": vim_content["vim_tenant_name"],
143 "vim_username": vim_content["vim_user"],
144 "vim_password": vim_content["vim_password"],
145 }
tierno59d22d22018-09-25 18:10:19 +0200146 if vim_RO.get("config"):
147 vim_account_RO["config"] = vim_RO["config"]
148 if "sdn-controller" in vim_account_RO["config"]:
149 del vim_account_RO["config"]["sdn-controller"]
150 if "sdn-port-mapping" in vim_account_RO["config"]:
151 del vim_account_RO["config"]["sdn-port-mapping"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100152 vim_config_encrypted_keys = self.vim_config_encrypted.get(
153 schema_version
154 ) or self.vim_config_encrypted.get("default")
tierno2d9f6f52019-08-01 16:32:56 +0000155 for p in vim_config_encrypted_keys:
tierno17a612f2018-10-23 11:30:42 +0200156 if vim_account_RO["config"].get(p):
garciadeblas5697b8b2021-03-24 09:17:02 +0100157 vim_account_RO["config"][p] = self.db.decrypt(
158 vim_account_RO["config"][p],
159 schema_version=schema_version,
160 salt=vim_id,
161 )
tierno17a612f2018-10-23 11:30:42 +0200162
tiernoe37b57d2018-12-11 17:22:51 +0000163 desc = await RO.attach("vim_account", RO_vim_id, descriptor=vim_account_RO)
tierno59d22d22018-09-25 18:10:19 +0200164 db_vim_update["_admin.deployed.RO-account"] = desc["uuid"]
165 db_vim_update["_admin.operationalState"] = "ENABLED"
166 db_vim_update["_admin.detailed-status"] = "Done"
kuuse6a470c62019-07-10 13:52:45 +0200167 # Mark the VIM 'create' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100168 operation_state = "COMPLETED"
169 operation_details = "Done"
tierno59d22d22018-09-25 18:10:19 +0200170
garciadeblas5697b8b2021-03-24 09:17:02 +0100171 self.logger.debug(
172 logging_text
173 + "Exit Ok VIM account created at RO_vim_account_id={}".format(
174 desc["uuid"]
175 )
176 )
tierno59d22d22018-09-25 18:10:19 +0200177 return
178
tiernocc29b592020-09-18 10:33:18 +0000179 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200180 self.logger.error(logging_text + "Exit Exception {}".format(e))
181 exc = e
182 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100183 self.logger.critical(
184 logging_text + "Exit Exception {}".format(e), exc_info=True
185 )
tierno59d22d22018-09-25 18:10:19 +0200186 exc = e
187 finally:
188 if exc and db_vim:
189 db_vim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100190 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
191 step, exc
192 )
kuuse6a470c62019-07-10 13:52:45 +0200193 # Mark the VIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100194 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000195 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000196 try:
197 if db_vim_update:
198 self.update_db_2("vim_accounts", vim_id, db_vim_update)
kuuse6a470c62019-07-10 13:52:45 +0200199 # Register the VIM 'create' HA task either
200 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100201 self.lcm_tasks.unlock_HA(
202 "vim",
203 "create",
204 op_id,
205 operationState=operation_state,
206 detailed_status=operation_details,
207 )
tiernobaa51102018-12-14 13:16:18 +0000208 except DbException as e:
209 self.logger.error(logging_text + "Cannot update database: {}".format(e))
210
tierno59d22d22018-09-25 18:10:19 +0200211 self.lcm_tasks.remove("vim_account", vim_id, order_id)
212
213 async def edit(self, vim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200214 # HA tasks and backward compatibility:
215 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
216 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100217 op_id = vim_content.pop("op_id", None)
218 if not self.lcm_tasks.lock_HA("vim", "edit", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200219 return
220
tierno59d22d22018-09-25 18:10:19 +0200221 vim_id = vim_content["_id"]
222 logging_text = "Task vim_edit={} ".format(vim_id)
223 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200224
tierno59d22d22018-09-25 18:10:19 +0200225 db_vim = None
226 exc = None
227 RO_sdn_id = None
228 RO_vim_id = None
229 db_vim_update = {}
230 step = "Getting vim-id='{}' from db".format(vim_id)
231 try:
kuuse6a470c62019-07-10 13:52:45 +0200232 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100233 await self.lcm_tasks.waitfor_related_HA("vim", "edit", op_id)
tierno59d22d22018-09-25 18:10:19 +0200234
kuuse6a470c62019-07-10 13:52:45 +0200235 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
tierno59d22d22018-09-25 18:10:19 +0200236
garciadeblas5697b8b2021-03-24 09:17:02 +0100237 if (
238 db_vim.get("_admin")
239 and db_vim["_admin"].get("deployed")
240 and db_vim["_admin"]["deployed"].get("RO")
241 ):
242 if vim_content.get("config") and vim_content["config"].get(
243 "sdn-controller"
244 ):
245 step = "Getting sdn-controller-id='{}' from db".format(
246 vim_content["config"]["sdn-controller"]
247 )
248 db_sdn = self.db.get_one(
249 "sdns", {"_id": vim_content["config"]["sdn-controller"]}
250 )
tierno59d22d22018-09-25 18:10:19 +0200251
kuuse6a470c62019-07-10 13:52:45 +0200252 # If the VIM account has an associated SDN account, also
253 # wait for any previous tasks in process for the SDN
garciadeblas5697b8b2021-03-24 09:17:02 +0100254 await self.lcm_tasks.waitfor_related_HA("sdn", "ANY", db_sdn["_id"])
tierno59d22d22018-09-25 18:10:19 +0200255
garciadeblas5697b8b2021-03-24 09:17:02 +0100256 if (
257 db_sdn.get("_admin")
258 and db_sdn["_admin"].get("deployed")
259 and db_sdn["_admin"]["deployed"].get("RO")
260 ):
tierno59d22d22018-09-25 18:10:19 +0200261 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
262 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100263 raise LcmException(
264 "sdn-controller={} is not available. Not deployed at RO".format(
265 vim_content["config"]["sdn-controller"]
266 )
267 )
tierno59d22d22018-09-25 18:10:19 +0200268
269 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
270 step = "Editing vim at RO"
Gabriel Cubae7898982023-05-11 01:57:21 -0500271 RO = ROclient.ROClient(**self.ro_config)
tierno59d22d22018-09-25 18:10:19 +0200272 vim_RO = deepcopy(vim_content)
273 vim_RO.pop("_id", None)
274 vim_RO.pop("_admin", None)
tierno17a612f2018-10-23 11:30:42 +0200275 schema_version = vim_RO.pop("schema_version", None)
tierno59d22d22018-09-25 18:10:19 +0200276 vim_RO.pop("schema_type", None)
277 vim_RO.pop("vim_tenant_name", None)
278 if "vim_type" in vim_RO:
279 vim_RO["type"] = vim_RO.pop("vim_type")
280 vim_RO.pop("vim_user", None)
281 vim_RO.pop("vim_password", None)
282 if RO_sdn_id:
283 vim_RO["config"]["sdn-controller"] = RO_sdn_id
tierno2357f4e2020-10-19 16:38:59 +0000284 # TODO make a deep update of sdn-port-mapping
tierno59d22d22018-09-25 18:10:19 +0200285 if vim_RO:
286 await RO.edit("vim", RO_vim_id, descriptor=vim_RO)
287
288 step = "Editing vim-account at RO tenant"
289 vim_account_RO = {}
290 if "config" in vim_content:
291 if "sdn-controller" in vim_content["config"]:
292 del vim_content["config"]["sdn-controller"]
293 if "sdn-port-mapping" in vim_content["config"]:
294 del vim_content["config"]["sdn-port-mapping"]
295 if not vim_content["config"]:
296 del vim_content["config"]
tierno17a612f2018-10-23 11:30:42 +0200297 if "vim_tenant_name" in vim_content:
298 vim_account_RO["vim_tenant_name"] = vim_content["vim_tenant_name"]
299 if "vim_password" in vim_content:
300 vim_account_RO["vim_password"] = vim_content["vim_password"]
301 if vim_content.get("vim_password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100302 vim_account_RO["vim_password"] = self.db.decrypt(
303 vim_content["vim_password"],
304 schema_version=schema_version,
305 salt=vim_id,
306 )
tierno17a612f2018-10-23 11:30:42 +0200307 if "config" in vim_content:
308 vim_account_RO["config"] = vim_content["config"]
309 if vim_content.get("config"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100310 vim_config_encrypted_keys = self.vim_config_encrypted.get(
311 schema_version
312 ) or self.vim_config_encrypted.get("default")
tierno2d9f6f52019-08-01 16:32:56 +0000313 for p in vim_config_encrypted_keys:
tierno17a612f2018-10-23 11:30:42 +0200314 if vim_content["config"].get(p):
garciadeblas5697b8b2021-03-24 09:17:02 +0100315 vim_account_RO["config"][p] = self.db.decrypt(
316 vim_content["config"][p],
317 schema_version=schema_version,
318 salt=vim_id,
319 )
tierno17a612f2018-10-23 11:30:42 +0200320
tierno59d22d22018-09-25 18:10:19 +0200321 if "vim_user" in vim_content:
322 vim_content["vim_username"] = vim_content["vim_user"]
323 # vim_account must be edited always even if empty in order to ensure changes are translated to RO
324 # vim_thread. RO will remove and relaunch a new thread for this vim_account
325 await RO.edit("vim_account", RO_vim_id, descriptor=vim_account_RO)
326 db_vim_update["_admin.operationalState"] = "ENABLED"
kuuse6a470c62019-07-10 13:52:45 +0200327 # Mark the VIM 'edit' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100328 operation_state = "COMPLETED"
329 operation_details = "Done"
tierno59d22d22018-09-25 18:10:19 +0200330
331 self.logger.debug(logging_text + "Exit Ok RO_vim_id={}".format(RO_vim_id))
332 return
333
tiernocc29b592020-09-18 10:33:18 +0000334 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200335 self.logger.error(logging_text + "Exit Exception {}".format(e))
336 exc = e
337 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100338 self.logger.critical(
339 logging_text + "Exit Exception {}".format(e), exc_info=True
340 )
tierno59d22d22018-09-25 18:10:19 +0200341 exc = e
342 finally:
343 if exc and db_vim:
344 db_vim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100345 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
346 step, exc
347 )
kuuse6a470c62019-07-10 13:52:45 +0200348 # Mark the VIM 'edit' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100349 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000350 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000351 try:
352 if db_vim_update:
353 self.update_db_2("vim_accounts", vim_id, db_vim_update)
kuuse6a470c62019-07-10 13:52:45 +0200354 # Register the VIM 'edit' HA task either
355 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100356 self.lcm_tasks.unlock_HA(
357 "vim",
358 "edit",
359 op_id,
360 operationState=operation_state,
361 detailed_status=operation_details,
362 )
tiernobaa51102018-12-14 13:16:18 +0000363 except DbException as e:
364 self.logger.error(logging_text + "Cannot update database: {}".format(e))
365
tierno59d22d22018-09-25 18:10:19 +0200366 self.lcm_tasks.remove("vim_account", vim_id, order_id)
367
kuuse6a470c62019-07-10 13:52:45 +0200368 async def delete(self, vim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200369 # HA tasks and backward compatibility:
370 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
371 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100372 op_id = vim_content.pop("op_id", None)
373 if not self.lcm_tasks.lock_HA("vim", "delete", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200374 return
375
376 vim_id = vim_content["_id"]
tierno59d22d22018-09-25 18:10:19 +0200377 logging_text = "Task vim_delete={} ".format(vim_id)
378 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200379
tierno59d22d22018-09-25 18:10:19 +0200380 db_vim = None
381 db_vim_update = {}
382 exc = None
383 step = "Getting vim from db"
384 try:
kuuse6a470c62019-07-10 13:52:45 +0200385 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100386 await self.lcm_tasks.waitfor_related_HA("vim", "delete", op_id)
tierno2357f4e2020-10-19 16:38:59 +0000387 if not self.ro_config.get("ng"):
388 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100389 if (
390 db_vim.get("_admin")
391 and db_vim["_admin"].get("deployed")
392 and db_vim["_admin"]["deployed"].get("RO")
393 ):
tierno2357f4e2020-10-19 16:38:59 +0000394 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
Gabriel Cubae7898982023-05-11 01:57:21 -0500395 RO = ROclient.ROClient(**self.ro_config)
tierno2357f4e2020-10-19 16:38:59 +0000396 step = "Detaching vim from RO tenant"
397 try:
398 await RO.detach("vim_account", RO_vim_id)
399 except ROclient.ROClientException as e:
400 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +0100401 self.logger.debug(
402 logging_text
403 + "RO_vim_id={} already detached".format(RO_vim_id)
404 )
tierno2357f4e2020-10-19 16:38:59 +0000405 else:
406 raise
kuuse6a470c62019-07-10 13:52:45 +0200407
tierno2357f4e2020-10-19 16:38:59 +0000408 step = "Deleting vim from RO"
409 try:
410 await RO.delete("vim", RO_vim_id)
411 except ROclient.ROClientException as e:
412 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +0100413 self.logger.debug(
414 logging_text
415 + "RO_vim_id={} already deleted".format(RO_vim_id)
416 )
tierno2357f4e2020-10-19 16:38:59 +0000417 else:
418 raise
419 else:
420 # nothing to delete
421 self.logger.debug(logging_text + "Nothing to remove at RO")
tierno59d22d22018-09-25 18:10:19 +0200422 self.db.del_one("vim_accounts", {"_id": vim_id})
tiernobaa51102018-12-14 13:16:18 +0000423 db_vim = None
tierno59d22d22018-09-25 18:10:19 +0200424 self.logger.debug(logging_text + "Exit Ok")
425 return
426
tiernocc29b592020-09-18 10:33:18 +0000427 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200428 self.logger.error(logging_text + "Exit Exception {}".format(e))
429 exc = e
430 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100431 self.logger.critical(
432 logging_text + "Exit Exception {}".format(e), exc_info=True
433 )
tierno59d22d22018-09-25 18:10:19 +0200434 exc = e
435 finally:
436 self.lcm_tasks.remove("vim_account", vim_id, order_id)
437 if exc and db_vim:
438 db_vim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100439 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
440 step, exc
441 )
kuuse6a470c62019-07-10 13:52:45 +0200442 # Mark the VIM 'delete' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100443 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000444 operation_details = "ERROR {}: {}".format(step, exc)
garciadeblas5697b8b2021-03-24 09:17:02 +0100445 self.lcm_tasks.unlock_HA(
446 "vim",
447 "delete",
448 op_id,
449 operationState=operation_state,
450 detailed_status=operation_details,
451 )
tiernobaa51102018-12-14 13:16:18 +0000452 try:
453 if db_vim and db_vim_update:
454 self.update_db_2("vim_accounts", vim_id, db_vim_update)
kuuse6a470c62019-07-10 13:52:45 +0200455 # If the VIM 'delete' HA task was succesful, the DB entry has been deleted,
456 # which means that there is nowhere to register this task, so do nothing here.
tiernobaa51102018-12-14 13:16:18 +0000457 except DbException as e:
458 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +0200459 self.lcm_tasks.remove("vim_account", vim_id, order_id)
460
461
tiernoe37b57d2018-12-11 17:22:51 +0000462class WimLcm(LcmBase):
463 # values that are encrypted at wim config because they are passwords
464 wim_config_encrypted = ()
465
Gabriel Cubae7898982023-05-11 01:57:21 -0500466 def __init__(self, msg, lcm_tasks, config):
tiernoe37b57d2018-12-11 17:22:51 +0000467 """
468 Init, Connect to database, filesystem storage, and messaging
469 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
470 :return: None
471 """
472
garciadeblas5697b8b2021-03-24 09:17:02 +0100473 self.logger = logging.getLogger("lcm.vim")
tiernoe37b57d2018-12-11 17:22:51 +0000474 self.lcm_tasks = lcm_tasks
Luis Vegaa27dc532022-11-11 20:10:49 +0000475 self.ro_config = config["RO"]
tiernoe37b57d2018-12-11 17:22:51 +0000476
bravof922c4172020-11-24 21:21:43 -0300477 super().__init__(msg, self.logger)
tiernoe37b57d2018-12-11 17:22:51 +0000478
479 async def create(self, wim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200480 # HA tasks and backward compatibility:
481 # If 'wim_content' does not include 'op_id', we a running a legacy NBI version.
482 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
483 # Register 'create' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +0100484 op_id = wim_content.pop("op_id", None)
485 self.lcm_tasks.lock_HA("wim", "create", op_id)
kuuse6a470c62019-07-10 13:52:45 +0200486
tiernoe37b57d2018-12-11 17:22:51 +0000487 wim_id = wim_content["_id"]
488 logging_text = "Task wim_create={} ".format(wim_id)
489 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200490
tiernoe37b57d2018-12-11 17:22:51 +0000491 db_wim = None
492 db_wim_update = {}
493 exc = None
494 try:
495 step = "Getting wim-id='{}' from db".format(wim_id)
496 db_wim = self.db.get_one("wim_accounts", {"_id": wim_id})
497 db_wim_update["_admin.deployed.RO"] = None
498
499 step = "Creating wim at RO"
500 db_wim_update["_admin.detailed-status"] = step
501 self.update_db_2("wim_accounts", wim_id, db_wim_update)
Gabriel Cubae7898982023-05-11 01:57:21 -0500502 RO = ROclient.ROClient(**self.ro_config)
tiernoe37b57d2018-12-11 17:22:51 +0000503 wim_RO = deepcopy(wim_content)
504 wim_RO.pop("_id", None)
505 wim_RO.pop("_admin", None)
506 schema_version = wim_RO.pop("schema_version", None)
507 wim_RO.pop("schema_type", None)
508 wim_RO.pop("wim_tenant_name", None)
509 wim_RO["type"] = wim_RO.pop("wim_type")
510 wim_RO.pop("wim_user", None)
511 wim_RO.pop("wim_password", None)
512 desc = await RO.create("wim", descriptor=wim_RO)
513 RO_wim_id = desc["uuid"]
514 db_wim_update["_admin.deployed.RO"] = RO_wim_id
garciadeblas5697b8b2021-03-24 09:17:02 +0100515 self.logger.debug(
516 logging_text + "WIM created at RO_wim_id={}".format(RO_wim_id)
517 )
tiernoe37b57d2018-12-11 17:22:51 +0000518
519 step = "Creating wim_account at RO"
520 db_wim_update["_admin.detailed-status"] = step
521 self.update_db_2("wim_accounts", wim_id, db_wim_update)
522
523 if wim_content.get("wim_password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100524 wim_content["wim_password"] = self.db.decrypt(
525 wim_content["wim_password"],
526 schema_version=schema_version,
527 salt=wim_id,
528 )
529 wim_account_RO = {
530 "name": wim_content["name"],
531 "user": wim_content["user"],
532 "password": wim_content["password"],
533 }
tiernoe37b57d2018-12-11 17:22:51 +0000534 if wim_RO.get("config"):
535 wim_account_RO["config"] = wim_RO["config"]
536 if "wim_port_mapping" in wim_account_RO["config"]:
537 del wim_account_RO["config"]["wim_port_mapping"]
538 for p in self.wim_config_encrypted:
539 if wim_account_RO["config"].get(p):
garciadeblas5697b8b2021-03-24 09:17:02 +0100540 wim_account_RO["config"][p] = self.db.decrypt(
541 wim_account_RO["config"][p],
542 schema_version=schema_version,
543 salt=wim_id,
544 )
tiernoe37b57d2018-12-11 17:22:51 +0000545
546 desc = await RO.attach("wim_account", RO_wim_id, descriptor=wim_account_RO)
547 db_wim_update["_admin.deployed.RO-account"] = desc["uuid"]
548 db_wim_update["_admin.operationalState"] = "ENABLED"
549 db_wim_update["_admin.detailed-status"] = "Done"
kuuse6a470c62019-07-10 13:52:45 +0200550 # Mark the WIM 'create' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100551 operation_state = "COMPLETED"
552 operation_details = "Done"
tiernoe37b57d2018-12-11 17:22:51 +0000553
garciadeblas5697b8b2021-03-24 09:17:02 +0100554 self.logger.debug(
555 logging_text
556 + "Exit Ok WIM account created at RO_wim_account_id={}".format(
557 desc["uuid"]
558 )
559 )
tiernoe37b57d2018-12-11 17:22:51 +0000560 return
561
tiernocc29b592020-09-18 10:33:18 +0000562 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tiernoe37b57d2018-12-11 17:22:51 +0000563 self.logger.error(logging_text + "Exit Exception {}".format(e))
564 exc = e
565 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100566 self.logger.critical(
567 logging_text + "Exit Exception {}".format(e), exc_info=True
568 )
tiernoe37b57d2018-12-11 17:22:51 +0000569 exc = e
570 finally:
571 if exc and db_wim:
572 db_wim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100573 db_wim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
574 step, exc
575 )
kuuse6a470c62019-07-10 13:52:45 +0200576 # Mark the WIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100577 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000578 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000579 try:
580 if db_wim_update:
581 self.update_db_2("wim_accounts", wim_id, db_wim_update)
kuuse6a470c62019-07-10 13:52:45 +0200582 # Register the WIM 'create' HA task either
583 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100584 self.lcm_tasks.unlock_HA(
585 "wim",
586 "create",
587 op_id,
588 operationState=operation_state,
589 detailed_status=operation_details,
590 )
tiernobaa51102018-12-14 13:16:18 +0000591 except DbException as e:
592 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tiernoe37b57d2018-12-11 17:22:51 +0000593 self.lcm_tasks.remove("wim_account", wim_id, order_id)
594
595 async def edit(self, wim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200596 # HA tasks and backward compatibility:
597 # If 'wim_content' does not include 'op_id', we a running a legacy NBI version.
598 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100599 op_id = wim_content.pop("op_id", None)
600 if not self.lcm_tasks.lock_HA("wim", "edit", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200601 return
602
tiernoe37b57d2018-12-11 17:22:51 +0000603 wim_id = wim_content["_id"]
604 logging_text = "Task wim_edit={} ".format(wim_id)
605 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200606
tiernoe37b57d2018-12-11 17:22:51 +0000607 db_wim = None
608 exc = None
609 RO_wim_id = None
610 db_wim_update = {}
611 step = "Getting wim-id='{}' from db".format(wim_id)
612 try:
kuuse6a470c62019-07-10 13:52:45 +0200613 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100614 await self.lcm_tasks.waitfor_related_HA("wim", "edit", op_id)
tiernoe37b57d2018-12-11 17:22:51 +0000615
kuuse6a470c62019-07-10 13:52:45 +0200616 db_wim = self.db.get_one("wim_accounts", {"_id": wim_id})
tiernoe37b57d2018-12-11 17:22:51 +0000617
garciadeblas5697b8b2021-03-24 09:17:02 +0100618 if (
619 db_wim.get("_admin")
620 and db_wim["_admin"].get("deployed")
621 and db_wim["_admin"]["deployed"].get("RO")
622 ):
tiernoe37b57d2018-12-11 17:22:51 +0000623 RO_wim_id = db_wim["_admin"]["deployed"]["RO"]
624 step = "Editing wim at RO"
Gabriel Cubae7898982023-05-11 01:57:21 -0500625 RO = ROclient.ROClient(**self.ro_config)
tiernoe37b57d2018-12-11 17:22:51 +0000626 wim_RO = deepcopy(wim_content)
627 wim_RO.pop("_id", None)
628 wim_RO.pop("_admin", None)
629 schema_version = wim_RO.pop("schema_version", None)
630 wim_RO.pop("schema_type", None)
631 wim_RO.pop("wim_tenant_name", None)
632 if "wim_type" in wim_RO:
633 wim_RO["type"] = wim_RO.pop("wim_type")
634 wim_RO.pop("wim_user", None)
635 wim_RO.pop("wim_password", None)
636 # TODO make a deep update of wim_port_mapping
637 if wim_RO:
638 await RO.edit("wim", RO_wim_id, descriptor=wim_RO)
639
640 step = "Editing wim-account at RO tenant"
641 wim_account_RO = {}
642 if "config" in wim_content:
643 if "wim_port_mapping" in wim_content["config"]:
644 del wim_content["config"]["wim_port_mapping"]
645 if not wim_content["config"]:
646 del wim_content["config"]
647 if "wim_tenant_name" in wim_content:
648 wim_account_RO["wim_tenant_name"] = wim_content["wim_tenant_name"]
649 if "wim_password" in wim_content:
650 wim_account_RO["wim_password"] = wim_content["wim_password"]
651 if wim_content.get("wim_password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100652 wim_account_RO["wim_password"] = self.db.decrypt(
653 wim_content["wim_password"],
654 schema_version=schema_version,
655 salt=wim_id,
656 )
tiernoe37b57d2018-12-11 17:22:51 +0000657 if "config" in wim_content:
658 wim_account_RO["config"] = wim_content["config"]
659 if wim_content.get("config"):
660 for p in self.wim_config_encrypted:
661 if wim_content["config"].get(p):
garciadeblas5697b8b2021-03-24 09:17:02 +0100662 wim_account_RO["config"][p] = self.db.decrypt(
663 wim_content["config"][p],
664 schema_version=schema_version,
665 salt=wim_id,
666 )
tiernoe37b57d2018-12-11 17:22:51 +0000667
668 if "wim_user" in wim_content:
669 wim_content["wim_username"] = wim_content["wim_user"]
670 # wim_account must be edited always even if empty in order to ensure changes are translated to RO
671 # wim_thread. RO will remove and relaunch a new thread for this wim_account
672 await RO.edit("wim_account", RO_wim_id, descriptor=wim_account_RO)
673 db_wim_update["_admin.operationalState"] = "ENABLED"
kuuse6a470c62019-07-10 13:52:45 +0200674 # Mark the WIM 'edit' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100675 operation_state = "COMPLETED"
676 operation_details = "Done"
tiernoe37b57d2018-12-11 17:22:51 +0000677
678 self.logger.debug(logging_text + "Exit Ok RO_wim_id={}".format(RO_wim_id))
679 return
680
tiernocc29b592020-09-18 10:33:18 +0000681 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tiernoe37b57d2018-12-11 17:22:51 +0000682 self.logger.error(logging_text + "Exit Exception {}".format(e))
683 exc = e
684 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100685 self.logger.critical(
686 logging_text + "Exit Exception {}".format(e), exc_info=True
687 )
tiernoe37b57d2018-12-11 17:22:51 +0000688 exc = e
689 finally:
690 if exc and db_wim:
691 db_wim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100692 db_wim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
693 step, exc
694 )
kuuse6a470c62019-07-10 13:52:45 +0200695 # Mark the WIM 'edit' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100696 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000697 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000698 try:
699 if db_wim_update:
700 self.update_db_2("wim_accounts", wim_id, db_wim_update)
kuuse6a470c62019-07-10 13:52:45 +0200701 # Register the WIM 'edit' HA task either
702 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100703 self.lcm_tasks.unlock_HA(
704 "wim",
705 "edit",
706 op_id,
707 operationState=operation_state,
708 detailed_status=operation_details,
709 )
tiernobaa51102018-12-14 13:16:18 +0000710 except DbException as e:
711 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tiernoe37b57d2018-12-11 17:22:51 +0000712 self.lcm_tasks.remove("wim_account", wim_id, order_id)
713
kuuse6a470c62019-07-10 13:52:45 +0200714 async def delete(self, wim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200715 # HA tasks and backward compatibility:
716 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
717 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100718 op_id = wim_content.pop("op_id", None)
719 if not self.lcm_tasks.lock_HA("wim", "delete", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200720 return
721
722 wim_id = wim_content["_id"]
tiernoe37b57d2018-12-11 17:22:51 +0000723 logging_text = "Task wim_delete={} ".format(wim_id)
724 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200725
tiernoe37b57d2018-12-11 17:22:51 +0000726 db_wim = None
727 db_wim_update = {}
728 exc = None
729 step = "Getting wim from db"
730 try:
kuuse6a470c62019-07-10 13:52:45 +0200731 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100732 await self.lcm_tasks.waitfor_related_HA("wim", "delete", op_id)
kuuse6a470c62019-07-10 13:52:45 +0200733
tiernoe37b57d2018-12-11 17:22:51 +0000734 db_wim = self.db.get_one("wim_accounts", {"_id": wim_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100735 if (
736 db_wim.get("_admin")
737 and db_wim["_admin"].get("deployed")
738 and db_wim["_admin"]["deployed"].get("RO")
739 ):
tiernoe37b57d2018-12-11 17:22:51 +0000740 RO_wim_id = db_wim["_admin"]["deployed"]["RO"]
Gabriel Cubae7898982023-05-11 01:57:21 -0500741 RO = ROclient.ROClient(**self.ro_config)
tiernoe37b57d2018-12-11 17:22:51 +0000742 step = "Detaching wim from RO tenant"
743 try:
744 await RO.detach("wim_account", RO_wim_id)
745 except ROclient.ROClientException as e:
746 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +0100747 self.logger.debug(
748 logging_text
749 + "RO_wim_id={} already detached".format(RO_wim_id)
750 )
tiernoe37b57d2018-12-11 17:22:51 +0000751 else:
752 raise
753
754 step = "Deleting wim from RO"
755 try:
756 await RO.delete("wim", RO_wim_id)
757 except ROclient.ROClientException as e:
758 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +0100759 self.logger.debug(
760 logging_text
761 + "RO_wim_id={} already deleted".format(RO_wim_id)
762 )
tiernoe37b57d2018-12-11 17:22:51 +0000763 else:
764 raise
765 else:
766 # nothing to delete
aktas61f61922021-07-29 07:56:27 +0300767 self.logger.error(logging_text + "Nothing to remove at RO")
tiernoe37b57d2018-12-11 17:22:51 +0000768 self.db.del_one("wim_accounts", {"_id": wim_id})
tiernobaa51102018-12-14 13:16:18 +0000769 db_wim = None
tiernoe37b57d2018-12-11 17:22:51 +0000770 self.logger.debug(logging_text + "Exit Ok")
771 return
772
tiernocc29b592020-09-18 10:33:18 +0000773 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tiernoe37b57d2018-12-11 17:22:51 +0000774 self.logger.error(logging_text + "Exit Exception {}".format(e))
775 exc = e
776 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100777 self.logger.critical(
778 logging_text + "Exit Exception {}".format(e), exc_info=True
779 )
tiernoe37b57d2018-12-11 17:22:51 +0000780 exc = e
781 finally:
782 self.lcm_tasks.remove("wim_account", wim_id, order_id)
783 if exc and db_wim:
784 db_wim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100785 db_wim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
786 step, exc
787 )
kuuse6a470c62019-07-10 13:52:45 +0200788 # Mark the WIM 'delete' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100789 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000790 operation_details = "ERROR {}: {}".format(step, exc)
garciadeblas5697b8b2021-03-24 09:17:02 +0100791 self.lcm_tasks.unlock_HA(
792 "wim",
793 "delete",
794 op_id,
795 operationState=operation_state,
796 detailed_status=operation_details,
797 )
tiernobaa51102018-12-14 13:16:18 +0000798 try:
799 if db_wim and db_wim_update:
800 self.update_db_2("wim_accounts", wim_id, db_wim_update)
kuuse6a470c62019-07-10 13:52:45 +0200801 # If the WIM 'delete' HA task was succesful, the DB entry has been deleted,
802 # which means that there is nowhere to register this task, so do nothing here.
tiernobaa51102018-12-14 13:16:18 +0000803 except DbException as e:
804 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tiernoe37b57d2018-12-11 17:22:51 +0000805 self.lcm_tasks.remove("wim_account", wim_id, order_id)
806
807
tierno59d22d22018-09-25 18:10:19 +0200808class SdnLcm(LcmBase):
Gabriel Cubae7898982023-05-11 01:57:21 -0500809 def __init__(self, msg, lcm_tasks, config):
tierno59d22d22018-09-25 18:10:19 +0200810 """
811 Init, Connect to database, filesystem storage, and messaging
812 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
813 :return: None
814 """
815
garciadeblas5697b8b2021-03-24 09:17:02 +0100816 self.logger = logging.getLogger("lcm.sdn")
tierno59d22d22018-09-25 18:10:19 +0200817 self.lcm_tasks = lcm_tasks
Luis Vegaa27dc532022-11-11 20:10:49 +0000818 self.ro_config = config["RO"]
tierno59d22d22018-09-25 18:10:19 +0200819
bravof922c4172020-11-24 21:21:43 -0300820 super().__init__(msg, self.logger)
tierno59d22d22018-09-25 18:10:19 +0200821
822 async def create(self, sdn_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200823 # HA tasks and backward compatibility:
824 # If 'sdn_content' does not include 'op_id', we a running a legacy NBI version.
825 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
826 # Register 'create' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +0100827 op_id = sdn_content.pop("op_id", None)
828 self.lcm_tasks.lock_HA("sdn", "create", op_id)
kuuse6a470c62019-07-10 13:52:45 +0200829
tierno59d22d22018-09-25 18:10:19 +0200830 sdn_id = sdn_content["_id"]
831 logging_text = "Task sdn_create={} ".format(sdn_id)
832 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200833
tierno59d22d22018-09-25 18:10:19 +0200834 db_sdn = None
835 db_sdn_update = {}
836 RO_sdn_id = None
837 exc = None
838 try:
839 step = "Getting sdn from db"
840 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
841 db_sdn_update["_admin.deployed.RO"] = None
842
843 step = "Creating sdn at RO"
tiernobaa51102018-12-14 13:16:18 +0000844 db_sdn_update["_admin.detailed-status"] = step
845 self.update_db_2("sdns", sdn_id, db_sdn_update)
846
Gabriel Cubae7898982023-05-11 01:57:21 -0500847 RO = ROclient.ROClient(**self.ro_config)
tierno59d22d22018-09-25 18:10:19 +0200848 sdn_RO = deepcopy(sdn_content)
849 sdn_RO.pop("_id", None)
850 sdn_RO.pop("_admin", None)
tierno17a612f2018-10-23 11:30:42 +0200851 schema_version = sdn_RO.pop("schema_version", None)
tierno59d22d22018-09-25 18:10:19 +0200852 sdn_RO.pop("schema_type", None)
853 sdn_RO.pop("description", None)
tierno17a612f2018-10-23 11:30:42 +0200854 if sdn_RO.get("password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100855 sdn_RO["password"] = self.db.decrypt(
856 sdn_RO["password"], schema_version=schema_version, salt=sdn_id
857 )
tierno17a612f2018-10-23 11:30:42 +0200858
tierno59d22d22018-09-25 18:10:19 +0200859 desc = await RO.create("sdn", descriptor=sdn_RO)
860 RO_sdn_id = desc["uuid"]
861 db_sdn_update["_admin.deployed.RO"] = RO_sdn_id
862 db_sdn_update["_admin.operationalState"] = "ENABLED"
863 self.logger.debug(logging_text + "Exit Ok RO_sdn_id={}".format(RO_sdn_id))
kuuse6a470c62019-07-10 13:52:45 +0200864 # Mark the SDN 'create' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100865 operation_state = "COMPLETED"
866 operation_details = "Done"
tierno59d22d22018-09-25 18:10:19 +0200867 return
868
tiernocc29b592020-09-18 10:33:18 +0000869 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200870 self.logger.error(logging_text + "Exit Exception {}".format(e))
871 exc = e
872 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100873 self.logger.critical(
874 logging_text + "Exit Exception {}".format(e), exc_info=True
875 )
tierno59d22d22018-09-25 18:10:19 +0200876 exc = e
877 finally:
878 if exc and db_sdn:
879 db_sdn_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100880 db_sdn_update["_admin.detailed-status"] = "ERROR {}: {}".format(
881 step, exc
882 )
kuuse6a470c62019-07-10 13:52:45 +0200883 # Mark the SDN 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100884 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000885 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000886 try:
887 if db_sdn and db_sdn_update:
888 self.update_db_2("sdns", sdn_id, db_sdn_update)
kuuse6a470c62019-07-10 13:52:45 +0200889 # Register the SDN 'create' HA task either
890 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100891 self.lcm_tasks.unlock_HA(
892 "sdn",
893 "create",
894 op_id,
895 operationState=operation_state,
896 detailed_status=operation_details,
897 )
tiernobaa51102018-12-14 13:16:18 +0000898 except DbException as e:
899 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +0200900 self.lcm_tasks.remove("sdn", sdn_id, order_id)
901
902 async def edit(self, sdn_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200903 # HA tasks and backward compatibility:
904 # If 'sdn_content' does not include 'op_id', we a running a legacy NBI version.
905 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100906 op_id = sdn_content.pop("op_id", None)
907 if not self.lcm_tasks.lock_HA("sdn", "edit", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200908 return
909
tierno59d22d22018-09-25 18:10:19 +0200910 sdn_id = sdn_content["_id"]
911 logging_text = "Task sdn_edit={} ".format(sdn_id)
912 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200913
tierno59d22d22018-09-25 18:10:19 +0200914 db_sdn = None
915 db_sdn_update = {}
916 exc = None
917 step = "Getting sdn from db"
918 try:
kuuse6a470c62019-07-10 13:52:45 +0200919 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100920 await self.lcm_tasks.waitfor_related_HA("sdn", "edit", op_id)
kuuse6a470c62019-07-10 13:52:45 +0200921
tierno59d22d22018-09-25 18:10:19 +0200922 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
tiernoe37b57d2018-12-11 17:22:51 +0000923 RO_sdn_id = None
garciadeblas5697b8b2021-03-24 09:17:02 +0100924 if (
925 db_sdn.get("_admin")
926 and db_sdn["_admin"].get("deployed")
927 and db_sdn["_admin"]["deployed"].get("RO")
928 ):
tierno59d22d22018-09-25 18:10:19 +0200929 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
Gabriel Cubae7898982023-05-11 01:57:21 -0500930 RO = ROclient.ROClient(**self.ro_config)
tierno59d22d22018-09-25 18:10:19 +0200931 step = "Editing sdn at RO"
932 sdn_RO = deepcopy(sdn_content)
933 sdn_RO.pop("_id", None)
934 sdn_RO.pop("_admin", None)
tierno17a612f2018-10-23 11:30:42 +0200935 schema_version = sdn_RO.pop("schema_version", None)
tierno59d22d22018-09-25 18:10:19 +0200936 sdn_RO.pop("schema_type", None)
937 sdn_RO.pop("description", None)
tierno17a612f2018-10-23 11:30:42 +0200938 if sdn_RO.get("password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100939 sdn_RO["password"] = self.db.decrypt(
940 sdn_RO["password"], schema_version=schema_version, salt=sdn_id
941 )
tierno59d22d22018-09-25 18:10:19 +0200942 if sdn_RO:
943 await RO.edit("sdn", RO_sdn_id, descriptor=sdn_RO)
944 db_sdn_update["_admin.operationalState"] = "ENABLED"
kuuse6a470c62019-07-10 13:52:45 +0200945 # Mark the SDN 'edit' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100946 operation_state = "COMPLETED"
947 operation_details = "Done"
tierno59d22d22018-09-25 18:10:19 +0200948
tiernoe37b57d2018-12-11 17:22:51 +0000949 self.logger.debug(logging_text + "Exit Ok RO_sdn_id={}".format(RO_sdn_id))
tierno59d22d22018-09-25 18:10:19 +0200950 return
951
tiernocc29b592020-09-18 10:33:18 +0000952 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200953 self.logger.error(logging_text + "Exit Exception {}".format(e))
954 exc = e
955 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100956 self.logger.critical(
957 logging_text + "Exit Exception {}".format(e), exc_info=True
958 )
tierno59d22d22018-09-25 18:10:19 +0200959 exc = e
960 finally:
961 if exc and db_sdn:
962 db_sdn["_admin.operationalState"] = "ERROR"
963 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
kuuse6a470c62019-07-10 13:52:45 +0200964 # Mark the SDN 'edit' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100965 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000966 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000967 try:
968 if db_sdn_update:
969 self.update_db_2("sdns", sdn_id, db_sdn_update)
kuuse6a470c62019-07-10 13:52:45 +0200970 # Register the SDN 'edit' HA task either
971 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100972 self.lcm_tasks.unlock_HA(
973 "sdn",
974 "edit",
975 op_id,
976 operationState=operation_state,
977 detailed_status=operation_details,
978 )
tiernobaa51102018-12-14 13:16:18 +0000979 except DbException as e:
980 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +0200981 self.lcm_tasks.remove("sdn", sdn_id, order_id)
982
kuuse6a470c62019-07-10 13:52:45 +0200983 async def delete(self, sdn_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200984 # HA tasks and backward compatibility:
985 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
986 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100987 op_id = sdn_content.pop("op_id", None)
988 if not self.lcm_tasks.lock_HA("sdn", "delete", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200989 return
990
991 sdn_id = sdn_content["_id"]
tierno59d22d22018-09-25 18:10:19 +0200992 logging_text = "Task sdn_delete={} ".format(sdn_id)
993 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200994
Gabriel Cuba411af2e2023-01-06 17:23:22 -0500995 db_sdn = {}
tierno59d22d22018-09-25 18:10:19 +0200996 db_sdn_update = {}
997 exc = None
998 step = "Getting sdn from db"
999 try:
kuuse6a470c62019-07-10 13:52:45 +02001000 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01001001 await self.lcm_tasks.waitfor_related_HA("sdn", "delete", op_id)
kuuse6a470c62019-07-10 13:52:45 +02001002
tierno59d22d22018-09-25 18:10:19 +02001003 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001004 if (
1005 db_sdn.get("_admin")
1006 and db_sdn["_admin"].get("deployed")
1007 and db_sdn["_admin"]["deployed"].get("RO")
1008 ):
tierno59d22d22018-09-25 18:10:19 +02001009 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
Gabriel Cubae7898982023-05-11 01:57:21 -05001010 RO = ROclient.ROClient(**self.ro_config)
tierno59d22d22018-09-25 18:10:19 +02001011 step = "Deleting sdn from RO"
1012 try:
1013 await RO.delete("sdn", RO_sdn_id)
1014 except ROclient.ROClientException as e:
1015 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +01001016 self.logger.debug(
1017 logging_text
1018 + "RO_sdn_id={} already deleted".format(RO_sdn_id)
1019 )
tierno59d22d22018-09-25 18:10:19 +02001020 else:
1021 raise
1022 else:
1023 # nothing to delete
garciadeblas5697b8b2021-03-24 09:17:02 +01001024 self.logger.error(
1025 logging_text + "Skipping. There is not RO information at database"
1026 )
tierno59d22d22018-09-25 18:10:19 +02001027 self.db.del_one("sdns", {"_id": sdn_id})
Gabriel Cuba411af2e2023-01-06 17:23:22 -05001028 db_sdn = {}
tierno59d22d22018-09-25 18:10:19 +02001029 self.logger.debug("sdn_delete task sdn_id={} Exit Ok".format(sdn_id))
1030 return
1031
tiernocc29b592020-09-18 10:33:18 +00001032 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +02001033 self.logger.error(logging_text + "Exit Exception {}".format(e))
1034 exc = e
1035 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001036 self.logger.critical(
1037 logging_text + "Exit Exception {}".format(e), exc_info=True
1038 )
tierno59d22d22018-09-25 18:10:19 +02001039 exc = e
1040 finally:
1041 if exc and db_sdn:
1042 db_sdn["_admin.operationalState"] = "ERROR"
1043 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
kuuse6a470c62019-07-10 13:52:45 +02001044 # Mark the SDN 'delete' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +01001045 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001046 operation_details = "ERROR {}: {}".format(step, exc)
garciadeblas5697b8b2021-03-24 09:17:02 +01001047 self.lcm_tasks.unlock_HA(
1048 "sdn",
1049 "delete",
1050 op_id,
1051 operationState=operation_state,
1052 detailed_status=operation_details,
1053 )
tiernobaa51102018-12-14 13:16:18 +00001054 try:
1055 if db_sdn and db_sdn_update:
1056 self.update_db_2("sdns", sdn_id, db_sdn_update)
kuuse6a470c62019-07-10 13:52:45 +02001057 # If the SDN 'delete' HA task was succesful, the DB entry has been deleted,
1058 # which means that there is nowhere to register this task, so do nothing here.
tiernobaa51102018-12-14 13:16:18 +00001059 except DbException as e:
1060 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +02001061 self.lcm_tasks.remove("sdn", sdn_id, order_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001062
1063
1064class K8sClusterLcm(LcmBase):
tierno0d7f9372020-09-30 07:56:29 +00001065 timeout_create = 300
calvinosanch9f9c6f22019-11-04 13:37:39 +01001066
Gabriel Cubae7898982023-05-11 01:57:21 -05001067 def __init__(self, msg, lcm_tasks, config):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001068 """
1069 Init, Connect to database, filesystem storage, and messaging
1070 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
1071 :return: None
1072 """
1073
garciadeblas5697b8b2021-03-24 09:17:02 +01001074 self.logger = logging.getLogger("lcm.k8scluster")
calvinosanch9f9c6f22019-11-04 13:37:39 +01001075 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +00001076 self.vca_config = config["VCA"]
bravof922c4172020-11-24 21:21:43 -03001077
1078 super().__init__(msg, self.logger)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001079
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001080 self.helm3_k8scluster = K8sHelm3Connector(
1081 kubectl_command=self.vca_config.get("kubectlpath"),
1082 helm_command=self.vca_config.get("helm3path"),
1083 fs=self.fs,
1084 log=self.logger,
1085 db=self.db,
garciadeblas5697b8b2021-03-24 09:17:02 +01001086 on_update_db=None,
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001087 )
1088
Adam Israelbaacc302019-12-01 12:41:39 -05001089 self.juju_k8scluster = K8sJujuConnector(
1090 kubectl_command=self.vca_config.get("kubectlpath"),
1091 juju_command=self.vca_config.get("jujupath"),
Adam Israelbaacc302019-12-01 12:41:39 -05001092 log=self.logger,
David Garciaba89cbb2020-10-16 13:05:34 +02001093 on_update_db=None,
bravof922c4172020-11-24 21:21:43 -03001094 db=self.db,
garciadeblas5697b8b2021-03-24 09:17:02 +01001095 fs=self.fs,
Adam Israelbaacc302019-12-01 12:41:39 -05001096 )
bravof922c4172020-11-24 21:21:43 -03001097
tiernofa076c32020-08-13 14:25:47 +00001098 self.k8s_map = {
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001099 "helm-chart-v3": self.helm3_k8scluster,
tiernofa076c32020-08-13 14:25:47 +00001100 "juju-bundle": self.juju_k8scluster,
1101 }
Adam Israelbaacc302019-12-01 12:41:39 -05001102
calvinosanch9f9c6f22019-11-04 13:37:39 +01001103 async def create(self, k8scluster_content, order_id):
garciadeblas5697b8b2021-03-24 09:17:02 +01001104 op_id = k8scluster_content.pop("op_id", None)
1105 if not self.lcm_tasks.lock_HA("k8scluster", "create", op_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001106 return
1107
1108 k8scluster_id = k8scluster_content["_id"]
calvinosanch9f9c6f22019-11-04 13:37:39 +01001109 logging_text = "Task k8scluster_create={} ".format(k8scluster_id)
1110 self.logger.debug(logging_text + "Enter")
1111
1112 db_k8scluster = None
1113 db_k8scluster_update = {}
calvinosanch9f9c6f22019-11-04 13:37:39 +01001114 exc = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001115 try:
1116 step = "Getting k8scluster-id='{}' from db".format(k8scluster_id)
1117 self.logger.debug(logging_text + step)
1118 db_k8scluster = self.db.get_one("k8sclusters", {"_id": k8scluster_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001119 self.db.encrypt_decrypt_fields(
1120 db_k8scluster.get("credentials"),
1121 "decrypt",
1122 ["password", "secret"],
1123 schema_version=db_k8scluster["schema_version"],
1124 salt=db_k8scluster["_id"],
1125 )
tiernoe19bd742019-12-05 16:09:08 +00001126 k8s_credentials = yaml.safe_dump(db_k8scluster.get("credentials"))
tiernofa076c32020-08-13 14:25:47 +00001127 pending_tasks = []
1128 task2name = {}
tierno78e3ec62020-07-14 10:46:57 +00001129 init_target = deep_get(db_k8scluster, ("_admin", "init"))
tiernofa076c32020-08-13 14:25:47 +00001130 step = "Launching k8scluster init tasks"
Gabriel Cuba1b2b8402022-03-22 11:12:12 -05001131
1132 k8s_deploy_methods = db_k8scluster.get("deployment_methods", {})
1133 # for backwards compatibility and all-false case
1134 if not any(k8s_deploy_methods.values()):
preethika.p28b0bf82022-09-23 07:36:28 +00001135 k8s_deploy_methods = {
preethika.p28b0bf82022-09-23 07:36:28 +00001136 "juju-bundle": True,
1137 "helm-chart-v3": True,
1138 }
Gabriel Cuba1b2b8402022-03-22 11:12:12 -05001139 deploy_methods = tuple(filter(k8s_deploy_methods.get, k8s_deploy_methods))
1140
1141 for task_name in deploy_methods:
tiernofa076c32020-08-13 14:25:47 +00001142 if init_target and task_name not in init_target:
1143 continue
David Garciac1fe90a2021-03-31 19:12:02 +02001144 task = asyncio.ensure_future(
1145 self.k8s_map[task_name].init_env(
1146 k8s_credentials,
1147 reuse_cluster_uuid=k8scluster_id,
1148 vca_id=db_k8scluster.get("vca_id"),
1149 )
1150 )
tiernofa076c32020-08-13 14:25:47 +00001151 pending_tasks.append(task)
1152 task2name[task] = task_name
Adam Israelbaacc302019-12-01 12:41:39 -05001153
tiernofa076c32020-08-13 14:25:47 +00001154 error_text_list = []
1155 tasks_name_ok = []
1156 reached_timeout = False
1157 now = time()
Adam Israelbaacc302019-12-01 12:41:39 -05001158
tiernofa076c32020-08-13 14:25:47 +00001159 while pending_tasks:
garciadeblas5697b8b2021-03-24 09:17:02 +01001160 _timeout = max(
1161 1, self.timeout_create - (time() - now)
1162 ) # ensure not negative with max
tiernofa076c32020-08-13 14:25:47 +00001163 step = "Waiting for k8scluster init tasks"
garciadeblas5697b8b2021-03-24 09:17:02 +01001164 done, pending_tasks = await asyncio.wait(
1165 pending_tasks, timeout=_timeout, return_when=asyncio.FIRST_COMPLETED
1166 )
tiernofa076c32020-08-13 14:25:47 +00001167 if not done:
1168 # timeout. Set timeout is reached and process pending as if they hase been finished
1169 done = pending_tasks
1170 pending_tasks = None
1171 reached_timeout = True
1172 for task in done:
1173 task_name = task2name[task]
1174 if reached_timeout:
1175 exc = "Timeout"
1176 elif task.cancelled():
1177 exc = "Cancelled"
1178 else:
1179 exc = task.exception()
1180
1181 if exc:
garciadeblas5697b8b2021-03-24 09:17:02 +01001182 error_text_list.append(
1183 "Failing init {}: {}".format(task_name, exc)
1184 )
1185 db_k8scluster_update[
1186 "_admin.{}.error_msg".format(task_name)
1187 ] = str(exc)
tiernofa076c32020-08-13 14:25:47 +00001188 db_k8scluster_update["_admin.{}.id".format(task_name)] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001189 db_k8scluster_update[
1190 "_admin.{}.operationalState".format(task_name)
1191 ] = "ERROR"
1192 self.logger.error(
1193 logging_text + "{} init fail: {}".format(task_name, exc),
1194 exc_info=not isinstance(exc, (N2VCException, str)),
1195 )
tiernofa076c32020-08-13 14:25:47 +00001196 else:
1197 k8s_id, uninstall_sw = task.result()
1198 tasks_name_ok.append(task_name)
garciadeblas5697b8b2021-03-24 09:17:02 +01001199 self.logger.debug(
1200 logging_text
1201 + "{} init success. id={} created={}".format(
1202 task_name, k8s_id, uninstall_sw
1203 )
1204 )
1205 db_k8scluster_update[
1206 "_admin.{}.error_msg".format(task_name)
1207 ] = None
tiernofa076c32020-08-13 14:25:47 +00001208 db_k8scluster_update["_admin.{}.id".format(task_name)] = k8s_id
garciadeblas5697b8b2021-03-24 09:17:02 +01001209 db_k8scluster_update[
1210 "_admin.{}.created".format(task_name)
1211 ] = uninstall_sw
1212 db_k8scluster_update[
1213 "_admin.{}.operationalState".format(task_name)
1214 ] = "ENABLED"
tiernofa076c32020-08-13 14:25:47 +00001215 # update database
1216 step = "Updating database for " + task_name
1217 self.update_db_2("k8sclusters", k8scluster_id, db_k8scluster_update)
tiernocc29b592020-09-18 10:33:18 +00001218 if tasks_name_ok:
1219 operation_details = "ready for " + ", ".join(tasks_name_ok)
1220 operation_state = "COMPLETED"
garciadeblas5697b8b2021-03-24 09:17:02 +01001221 db_k8scluster_update["_admin.operationalState"] = (
1222 "ENABLED" if not error_text_list else "DEGRADED"
1223 )
tiernocc29b592020-09-18 10:33:18 +00001224 operation_details += "; " + ";".join(error_text_list)
1225 else:
tiernoe19bd742019-12-05 16:09:08 +00001226 db_k8scluster_update["_admin.operationalState"] = "ERROR"
tiernofa076c32020-08-13 14:25:47 +00001227 operation_state = "FAILED"
tiernocc29b592020-09-18 10:33:18 +00001228 operation_details = ";".join(error_text_list)
1229 db_k8scluster_update["_admin.detailed-status"] = operation_details
tiernofa076c32020-08-13 14:25:47 +00001230 self.logger.debug(logging_text + "Done. Result: " + operation_state)
1231 exc = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001232
1233 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001234 if isinstance(
1235 e,
1236 (
1237 LcmException,
1238 DbException,
1239 K8sException,
1240 N2VCException,
1241 asyncio.CancelledError,
1242 ),
1243 ):
tiernocc29b592020-09-18 10:33:18 +00001244 self.logger.error(logging_text + "Exit Exception {}".format(e))
1245 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001246 self.logger.critical(
1247 logging_text + "Exit Exception {}".format(e), exc_info=True
1248 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001249 exc = e
1250 finally:
1251 if exc and db_k8scluster:
1252 db_k8scluster_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +01001253 db_k8scluster_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1254 step, exc
1255 )
1256 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001257 operation_details = "ERROR {}: {}".format(step, exc)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001258 try:
tiernofa076c32020-08-13 14:25:47 +00001259 if db_k8scluster and db_k8scluster_update:
calvinosanch9f9c6f22019-11-04 13:37:39 +01001260 self.update_db_2("k8sclusters", k8scluster_id, db_k8scluster_update)
Adam Israelbaacc302019-12-01 12:41:39 -05001261
tiernofa076c32020-08-13 14:25:47 +00001262 # Register the operation and unlock
garciadeblas5697b8b2021-03-24 09:17:02 +01001263 self.lcm_tasks.unlock_HA(
1264 "k8scluster",
1265 "create",
1266 op_id,
1267 operationState=operation_state,
1268 detailed_status=operation_details,
1269 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001270 except DbException as e:
1271 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno0fedb032020-03-12 17:19:06 +00001272 self.lcm_tasks.remove("k8scluster", k8scluster_id, order_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001273
dariofaccin8bbeeb02023-01-23 18:13:27 +01001274 async def edit(self, k8scluster_content, order_id):
dariofaccin8bbeeb02023-01-23 18:13:27 +01001275 op_id = k8scluster_content.pop("op_id", None)
1276 if not self.lcm_tasks.lock_HA("k8scluster", "edit", op_id):
1277 return
1278
1279 k8scluster_id = k8scluster_content["_id"]
Gulsum Atici4d209f02023-02-06 22:06:44 +03001280
dariofaccin8bbeeb02023-01-23 18:13:27 +01001281 logging_text = "Task k8scluster_edit={} ".format(k8scluster_id)
1282 self.logger.debug(logging_text + "Enter")
1283
1284 # TODO the implementation is pending and will be part of a new feature
1285 # It will support rotation of certificates, update of credentials and K8S API endpoint
1286 # At the moment the operation is set as completed
1287
1288 operation_state = "COMPLETED"
1289 operation_details = "Not implemented"
1290
1291 self.lcm_tasks.unlock_HA(
1292 "k8scluster",
1293 "edit",
1294 op_id,
1295 operationState=operation_state,
1296 detailed_status=operation_details,
1297 )
1298 self.lcm_tasks.remove("k8scluster", k8scluster_id, order_id)
1299
calvinosanch9f9c6f22019-11-04 13:37:39 +01001300 async def delete(self, k8scluster_content, order_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001301 # HA tasks and backward compatibility:
1302 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
1303 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
1304 # Register 'delete' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +01001305 op_id = k8scluster_content.pop("op_id", None)
1306 if not self.lcm_tasks.lock_HA("k8scluster", "delete", op_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001307 return
1308
1309 k8scluster_id = k8scluster_content["_id"]
calvinosanch9f9c6f22019-11-04 13:37:39 +01001310 logging_text = "Task k8scluster_delete={} ".format(k8scluster_id)
1311 self.logger.debug(logging_text + "Enter")
1312
1313 db_k8scluster = None
1314 db_k8scluster_update = {}
1315 exc = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001316 try:
1317 step = "Getting k8scluster='{}' from db".format(k8scluster_id)
1318 self.logger.debug(logging_text + step)
1319 db_k8scluster = self.db.get_one("k8sclusters", {"_id": k8scluster_id})
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001320 k8s_h3c_id = deep_get(db_k8scluster, ("_admin", "helm-chart-v3", "id"))
Adam Israelbaacc302019-12-01 12:41:39 -05001321 k8s_jb_id = deep_get(db_k8scluster, ("_admin", "juju-bundle", "id"))
1322
tierno626e0152019-11-29 14:16:16 +00001323 cluster_removed = True
tierno78e3ec62020-07-14 10:46:57 +00001324 if k8s_jb_id: # delete in reverse order of creation
1325 step = "Removing juju-bundle '{}'".format(k8s_jb_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01001326 uninstall_sw = (
1327 deep_get(db_k8scluster, ("_admin", "juju-bundle", "created"))
1328 or False
1329 )
David Garciac1fe90a2021-03-31 19:12:02 +02001330 cluster_removed = await self.juju_k8scluster.reset(
1331 cluster_uuid=k8s_jb_id,
1332 uninstall_sw=uninstall_sw,
1333 vca_id=db_k8scluster.get("vca_id"),
1334 )
tierno78e3ec62020-07-14 10:46:57 +00001335 db_k8scluster_update["_admin.juju-bundle.id"] = None
tiernocc29b592020-09-18 10:33:18 +00001336 db_k8scluster_update["_admin.juju-bundle.operationalState"] = "DISABLED"
tierno78e3ec62020-07-14 10:46:57 +00001337
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001338 if k8s_h3c_id:
k4.rahul63f9af62023-04-27 16:38:28 +05301339 step = "Removing helm-chart-v3 '{}'".format(k8s_h3c_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01001340 uninstall_sw = (
1341 deep_get(db_k8scluster, ("_admin", "helm-chart-v3", "created"))
1342 or False
1343 )
1344 cluster_removed = await self.helm3_k8scluster.reset(
1345 cluster_uuid=k8s_h3c_id, uninstall_sw=uninstall_sw
1346 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001347 db_k8scluster_update["_admin.helm-chart-v3.id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001348 db_k8scluster_update[
1349 "_admin.helm-chart-v3.operationalState"
1350 ] = "DISABLED"
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001351
lloretgallegedc5f332020-02-20 11:50:50 +01001352 # Try to remove from cluster_inserted to clean old versions
Luis Vegae11384e2023-10-10 22:36:33 +00001353 if k8s_h3c_id and cluster_removed:
tiernoe19bd742019-12-05 16:09:08 +00001354 step = "Removing k8scluster='{}' from k8srepos".format(k8scluster_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001355 self.logger.debug(logging_text + step)
garciadeblas5697b8b2021-03-24 09:17:02 +01001356 db_k8srepo_list = self.db.get_list(
Luis Vegae11384e2023-10-10 22:36:33 +00001357 "k8srepos", {"_admin.cluster-inserted": k8s_h3c_id}
garciadeblas5697b8b2021-03-24 09:17:02 +01001358 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001359 for k8srepo in db_k8srepo_list:
tiernoe19bd742019-12-05 16:09:08 +00001360 try:
1361 cluster_list = k8srepo["_admin"]["cluster-inserted"]
Luis Vegae11384e2023-10-10 22:36:33 +00001362 cluster_list.remove(k8s_h3c_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01001363 self.update_db_2(
1364 "k8srepos",
1365 k8srepo["_id"],
1366 {"_admin.cluster-inserted": cluster_list},
1367 )
tiernoe19bd742019-12-05 16:09:08 +00001368 except Exception as e:
1369 self.logger.error("{}: {}".format(step, e))
tiernod58995a2020-05-20 14:35:19 +00001370 self.db.del_one("k8sclusters", {"_id": k8scluster_id})
tierno78e3ec62020-07-14 10:46:57 +00001371 db_k8scluster_update = None
1372 self.logger.debug(logging_text + "Done")
calvinosanch9f9c6f22019-11-04 13:37:39 +01001373
1374 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001375 if isinstance(
1376 e,
1377 (
1378 LcmException,
1379 DbException,
1380 K8sException,
1381 N2VCException,
1382 asyncio.CancelledError,
1383 ),
1384 ):
tierno0fedb032020-03-12 17:19:06 +00001385 self.logger.error(logging_text + "Exit Exception {}".format(e))
1386 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001387 self.logger.critical(
1388 logging_text + "Exit Exception {}".format(e), exc_info=True
1389 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001390 exc = e
1391 finally:
1392 if exc and db_k8scluster:
1393 db_k8scluster_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +01001394 db_k8scluster_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1395 step, exc
1396 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001397 # Mark the WIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +01001398 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001399 operation_details = "ERROR {}: {}".format(step, exc)
1400 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001401 operation_state = "COMPLETED"
tiernofa076c32020-08-13 14:25:47 +00001402 operation_details = "deleted"
1403
calvinosanch9f9c6f22019-11-04 13:37:39 +01001404 try:
1405 if db_k8scluster_update:
1406 self.update_db_2("k8sclusters", k8scluster_id, db_k8scluster_update)
1407 # Register the K8scluster 'delete' HA task either
1408 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +01001409 self.lcm_tasks.unlock_HA(
1410 "k8scluster",
1411 "delete",
1412 op_id,
1413 operationState=operation_state,
1414 detailed_status=operation_details,
1415 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001416 except DbException as e:
1417 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno0fedb032020-03-12 17:19:06 +00001418 self.lcm_tasks.remove("k8scluster", k8scluster_id, order_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001419
1420
David Garciac1fe90a2021-03-31 19:12:02 +02001421class VcaLcm(LcmBase):
1422 timeout_create = 30
1423
Gabriel Cubae7898982023-05-11 01:57:21 -05001424 def __init__(self, msg, lcm_tasks, config):
David Garciac1fe90a2021-03-31 19:12:02 +02001425 """
1426 Init, Connect to database, filesystem storage, and messaging
1427 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
1428 :return: None
1429 """
1430
1431 self.logger = logging.getLogger("lcm.vca")
David Garciac1fe90a2021-03-31 19:12:02 +02001432 self.lcm_tasks = lcm_tasks
1433
1434 super().__init__(msg, self.logger)
1435
1436 # create N2VC connector
Gabriel Cubae7898982023-05-11 01:57:21 -05001437 self.n2vc = N2VCJujuConnector(log=self.logger, fs=self.fs, db=self.db)
David Garciac1fe90a2021-03-31 19:12:02 +02001438
1439 def _get_vca_by_id(self, vca_id: str) -> dict:
1440 db_vca = self.db.get_one("vca", {"_id": vca_id})
1441 self.db.encrypt_decrypt_fields(
1442 db_vca,
1443 "decrypt",
1444 ["secret", "cacert"],
garciadeblas5697b8b2021-03-24 09:17:02 +01001445 schema_version=db_vca["schema_version"],
1446 salt=db_vca["_id"],
David Garciac1fe90a2021-03-31 19:12:02 +02001447 )
1448 return db_vca
1449
Dario Faccin8e53c6d2023-01-10 10:38:41 +00001450 async def _validate_vca(self, db_vca_id: str) -> None:
1451 task = asyncio.ensure_future(
1452 asyncio.wait_for(
1453 self.n2vc.validate_vca(db_vca_id),
1454 timeout=self.timeout_create,
1455 )
1456 )
1457 await asyncio.wait([task], return_when=asyncio.FIRST_COMPLETED)
1458 if task.exception():
1459 raise task.exception()
1460
1461 def _is_vca_config_update(self, update_options) -> bool:
1462 return any(
1463 word in update_options.keys()
1464 for word in [
1465 "cacert",
1466 "endpoints",
1467 "lxd-cloud",
1468 "lxd-credentials",
1469 "k8s-cloud",
1470 "k8s-credentials",
1471 "model-config",
1472 "user",
1473 "secret",
1474 ]
1475 )
1476
David Garciac1fe90a2021-03-31 19:12:02 +02001477 async def create(self, vca_content, order_id):
1478 op_id = vca_content.pop("op_id", None)
1479 if not self.lcm_tasks.lock_HA("vca", "create", op_id):
1480 return
1481
1482 vca_id = vca_content["_id"]
1483 self.logger.debug("Task vca_create={} {}".format(vca_id, "Enter"))
1484
David Garciac1fe90a2021-03-31 19:12:02 +02001485 db_vca_update = {}
1486
Gabriel Cuba411af2e2023-01-06 17:23:22 -05001487 operation_state = "FAILED"
1488 operation_details = ""
David Garciac1fe90a2021-03-31 19:12:02 +02001489 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01001490 self.logger.debug(
1491 "Task vca_create={} {}".format(vca_id, "Getting vca from db")
1492 )
David Garciac1fe90a2021-03-31 19:12:02 +02001493 db_vca = self._get_vca_by_id(vca_id)
1494
Dario Faccin8e53c6d2023-01-10 10:38:41 +00001495 await self._validate_vca(db_vca["_id"])
garciadeblas5697b8b2021-03-24 09:17:02 +01001496 self.logger.debug(
1497 "Task vca_create={} {}".format(
1498 vca_id, "vca registered and validated successfully"
1499 )
1500 )
David Garciac1fe90a2021-03-31 19:12:02 +02001501 db_vca_update["_admin.operationalState"] = "ENABLED"
1502 db_vca_update["_admin.detailed-status"] = "Connectivity: ok"
1503 operation_details = "VCA validated"
1504 operation_state = "COMPLETED"
1505
garciadeblas5697b8b2021-03-24 09:17:02 +01001506 self.logger.debug(
1507 "Task vca_create={} {}".format(
1508 vca_id, "Done. Result: {}".format(operation_state)
1509 )
1510 )
David Garciac1fe90a2021-03-31 19:12:02 +02001511
1512 except Exception as e:
1513 error_msg = "Failed with exception: {}".format(e)
1514 self.logger.error("Task vca_create={} {}".format(vca_id, error_msg))
1515 db_vca_update["_admin.operationalState"] = "ERROR"
1516 db_vca_update["_admin.detailed-status"] = error_msg
David Garciac1fe90a2021-03-31 19:12:02 +02001517 operation_details = error_msg
1518 finally:
1519 try:
1520 self.update_db_2("vca", vca_id, db_vca_update)
1521
1522 # Register the operation and unlock
1523 self.lcm_tasks.unlock_HA(
1524 "vca",
1525 "create",
1526 op_id,
1527 operationState=operation_state,
garciadeblas5697b8b2021-03-24 09:17:02 +01001528 detailed_status=operation_details,
David Garciac1fe90a2021-03-31 19:12:02 +02001529 )
1530 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001531 self.logger.error(
1532 "Task vca_create={} {}".format(
1533 vca_id, "Cannot update database: {}".format(e)
1534 )
1535 )
David Garciac1fe90a2021-03-31 19:12:02 +02001536 self.lcm_tasks.remove("vca", vca_id, order_id)
1537
Dario Faccin8e53c6d2023-01-10 10:38:41 +00001538 async def edit(self, vca_content, order_id):
1539 op_id = vca_content.pop("op_id", None)
1540 if not self.lcm_tasks.lock_HA("vca", "edit", op_id):
1541 return
1542
1543 vca_id = vca_content["_id"]
1544 self.logger.debug("Task vca_edit={} {}".format(vca_id, "Enter"))
1545
1546 db_vca = None
1547 db_vca_update = {}
1548
1549 operation_state = "FAILED"
1550 operation_details = ""
1551 try:
1552 self.logger.debug(
1553 "Task vca_edit={} {}".format(vca_id, "Getting vca from db")
1554 )
1555 db_vca = self._get_vca_by_id(vca_id)
1556 if self._is_vca_config_update(vca_content):
1557 await self._validate_vca(db_vca["_id"])
1558 self.logger.debug(
1559 "Task vca_edit={} {}".format(
1560 vca_id, "vca registered and validated successfully"
1561 )
1562 )
1563 db_vca_update["_admin.operationalState"] = "ENABLED"
1564 db_vca_update["_admin.detailed-status"] = "Connectivity: ok"
1565
1566 operation_details = "Edited"
1567 operation_state = "COMPLETED"
1568
1569 self.logger.debug(
1570 "Task vca_edit={} {}".format(
1571 vca_id, "Done. Result: {}".format(operation_state)
1572 )
1573 )
1574
1575 except Exception as e:
1576 error_msg = "Failed with exception: {}".format(e)
1577 self.logger.error("Task vca_edit={} {}".format(vca_id, error_msg))
1578 db_vca_update["_admin.operationalState"] = "ERROR"
1579 db_vca_update["_admin.detailed-status"] = error_msg
1580 operation_state = "FAILED"
1581 operation_details = error_msg
1582 finally:
1583 try:
1584 self.update_db_2("vca", vca_id, db_vca_update)
1585
1586 # Register the operation and unlock
1587 self.lcm_tasks.unlock_HA(
1588 "vca",
1589 "edit",
1590 op_id,
1591 operationState=operation_state,
1592 detailed_status=operation_details,
1593 )
1594 except DbException as e:
1595 self.logger.error(
1596 "Task vca_edit={} {}".format(
1597 vca_id, "Cannot update database: {}".format(e)
1598 )
1599 )
1600 self.lcm_tasks.remove("vca", vca_id, order_id)
1601
David Garciac1fe90a2021-03-31 19:12:02 +02001602 async def delete(self, vca_content, order_id):
David Garciac1fe90a2021-03-31 19:12:02 +02001603 # HA tasks and backward compatibility:
1604 # If "vim_content" does not include "op_id", we a running a legacy NBI version.
1605 # In such a case, HA is not supported by NBI, "op_id" is None, and lock_HA() will do nothing.
1606 # Register "delete" task here for related future HA operations
1607 op_id = vca_content.pop("op_id", None)
1608 if not self.lcm_tasks.lock_HA("vca", "delete", op_id):
1609 return
1610
1611 db_vca_update = {}
1612 vca_id = vca_content["_id"]
1613
Gabriel Cuba411af2e2023-01-06 17:23:22 -05001614 operation_state = "FAILED"
1615 operation_details = ""
1616
David Garciac1fe90a2021-03-31 19:12:02 +02001617 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01001618 self.logger.debug(
1619 "Task vca_delete={} {}".format(vca_id, "Deleting vca from db")
1620 )
David Garciac1fe90a2021-03-31 19:12:02 +02001621 self.db.del_one("vca", {"_id": vca_id})
1622 db_vca_update = None
1623 operation_details = "deleted"
1624 operation_state = "COMPLETED"
1625
garciadeblas5697b8b2021-03-24 09:17:02 +01001626 self.logger.debug(
1627 "Task vca_delete={} {}".format(
1628 vca_id, "Done. Result: {}".format(operation_state)
1629 )
1630 )
David Garciac1fe90a2021-03-31 19:12:02 +02001631 except Exception as e:
1632 error_msg = "Failed with exception: {}".format(e)
1633 self.logger.error("Task vca_delete={} {}".format(vca_id, error_msg))
1634 db_vca_update["_admin.operationalState"] = "ERROR"
1635 db_vca_update["_admin.detailed-status"] = error_msg
David Garciac1fe90a2021-03-31 19:12:02 +02001636 operation_details = error_msg
1637 finally:
1638 try:
1639 self.update_db_2("vca", vca_id, db_vca_update)
1640 self.lcm_tasks.unlock_HA(
1641 "vca",
1642 "delete",
1643 op_id,
1644 operationState=operation_state,
1645 detailed_status=operation_details,
1646 )
1647 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001648 self.logger.error(
1649 "Task vca_delete={} {}".format(
1650 vca_id, "Cannot update database: {}".format(e)
1651 )
1652 )
David Garciac1fe90a2021-03-31 19:12:02 +02001653 self.lcm_tasks.remove("vca", vca_id, order_id)
1654
1655
calvinosanch9f9c6f22019-11-04 13:37:39 +01001656class K8sRepoLcm(LcmBase):
Gabriel Cubae7898982023-05-11 01:57:21 -05001657 def __init__(self, msg, lcm_tasks, config):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001658 """
1659 Init, Connect to database, filesystem storage, and messaging
1660 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
1661 :return: None
1662 """
1663
garciadeblas5697b8b2021-03-24 09:17:02 +01001664 self.logger = logging.getLogger("lcm.k8srepo")
calvinosanch9f9c6f22019-11-04 13:37:39 +01001665 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +00001666 self.vca_config = config["VCA"]
calvinosanch9f9c6f22019-11-04 13:37:39 +01001667
bravof922c4172020-11-24 21:21:43 -03001668 super().__init__(msg, self.logger)
1669
Luis Vegae11384e2023-10-10 22:36:33 +00001670 self.k8srepo = K8sHelm3Connector(
bravof922c4172020-11-24 21:21:43 -03001671 kubectl_command=self.vca_config.get("kubectlpath"),
1672 helm_command=self.vca_config.get("helmpath"),
1673 fs=self.fs,
1674 log=self.logger,
1675 db=self.db,
garciadeblas5697b8b2021-03-24 09:17:02 +01001676 on_update_db=None,
bravof922c4172020-11-24 21:21:43 -03001677 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001678
1679 async def create(self, k8srepo_content, order_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001680 # HA tasks and backward compatibility:
1681 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
1682 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
1683 # Register 'create' task here for related future HA operations
1684
garciadeblas5697b8b2021-03-24 09:17:02 +01001685 op_id = k8srepo_content.pop("op_id", None)
1686 if not self.lcm_tasks.lock_HA("k8srepo", "create", op_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001687 return
1688
1689 k8srepo_id = k8srepo_content.get("_id")
1690 logging_text = "Task k8srepo_create={} ".format(k8srepo_id)
1691 self.logger.debug(logging_text + "Enter")
1692
1693 db_k8srepo = None
1694 db_k8srepo_update = {}
1695 exc = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001696 operation_state = "COMPLETED"
1697 operation_details = ""
calvinosanch9f9c6f22019-11-04 13:37:39 +01001698 try:
1699 step = "Getting k8srepo-id='{}' from db".format(k8srepo_id)
1700 self.logger.debug(logging_text + step)
1701 db_k8srepo = self.db.get_one("k8srepos", {"_id": k8srepo_id})
calvinosanch9f9c6f22019-11-04 13:37:39 +01001702 db_k8srepo_update["_admin.operationalState"] = "ENABLED"
1703 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001704 self.logger.error(
1705 logging_text + "Exit Exception {}".format(e),
1706 exc_info=not isinstance(
1707 e,
1708 (
1709 LcmException,
1710 DbException,
1711 K8sException,
1712 N2VCException,
1713 asyncio.CancelledError,
1714 ),
1715 ),
1716 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001717 exc = e
1718 finally:
1719 if exc and db_k8srepo:
1720 db_k8srepo_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +01001721 db_k8srepo_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1722 step, exc
1723 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001724 # Mark the WIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +01001725 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001726 operation_details = "ERROR {}: {}".format(step, exc)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001727 try:
1728 if db_k8srepo_update:
1729 self.update_db_2("k8srepos", k8srepo_id, db_k8srepo_update)
1730 # Register the K8srepo 'create' HA task either
1731 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +01001732 self.lcm_tasks.unlock_HA(
1733 "k8srepo",
1734 "create",
1735 op_id,
1736 operationState=operation_state,
1737 detailed_status=operation_details,
1738 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001739 except DbException as e:
1740 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1741 self.lcm_tasks.remove("k8srepo", k8srepo_id, order_id)
1742
1743 async def delete(self, k8srepo_content, order_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001744 # HA tasks and backward compatibility:
1745 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
1746 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
1747 # Register 'delete' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +01001748 op_id = k8srepo_content.pop("op_id", None)
1749 if not self.lcm_tasks.lock_HA("k8srepo", "delete", op_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001750 return
1751
1752 k8srepo_id = k8srepo_content.get("_id")
1753 logging_text = "Task k8srepo_delete={} ".format(k8srepo_id)
1754 self.logger.debug(logging_text + "Enter")
1755
1756 db_k8srepo = None
1757 db_k8srepo_update = {}
1758
tierno28c63da2020-04-20 16:28:56 +00001759 exc = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001760 operation_state = "COMPLETED"
1761 operation_details = ""
calvinosanch9f9c6f22019-11-04 13:37:39 +01001762 try:
1763 step = "Getting k8srepo-id='{}' from db".format(k8srepo_id)
1764 self.logger.debug(logging_text + step)
1765 db_k8srepo = self.db.get_one("k8srepos", {"_id": k8srepo_id})
calvinosanch9f9c6f22019-11-04 13:37:39 +01001766
1767 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001768 self.logger.error(
1769 logging_text + "Exit Exception {}".format(e),
1770 exc_info=not isinstance(
1771 e,
1772 (
1773 LcmException,
1774 DbException,
1775 K8sException,
1776 N2VCException,
1777 asyncio.CancelledError,
1778 ),
1779 ),
1780 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001781 exc = e
1782 finally:
1783 if exc and db_k8srepo:
1784 db_k8srepo_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +01001785 db_k8srepo_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1786 step, exc
1787 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001788 # Mark the WIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +01001789 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001790 operation_details = "ERROR {}: {}".format(step, exc)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001791 try:
1792 if db_k8srepo_update:
1793 self.update_db_2("k8srepos", k8srepo_id, db_k8srepo_update)
1794 # Register the K8srepo 'delete' HA task either
1795 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +01001796 self.lcm_tasks.unlock_HA(
1797 "k8srepo",
1798 "delete",
1799 op_id,
1800 operationState=operation_state,
1801 detailed_status=operation_details,
1802 )
tierno28c63da2020-04-20 16:28:56 +00001803 self.db.del_one("k8srepos", {"_id": k8srepo_id})
calvinosanch9f9c6f22019-11-04 13:37:39 +01001804 except DbException as e:
1805 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1806 self.lcm_tasks.remove("k8srepo", k8srepo_id, order_id)