blob: 272aad1cc4948528fc1522c01f4255f8639498e0 [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
Luis Vegaa27dc532022-11-11 20:10:49 +000059 self.ro_config = config["RO"]
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 # HA tasks and backward compatibility:
65 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
66 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
67 # Register 'create' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +010068 op_id = vim_content.pop("op_id", None)
69 if not self.lcm_tasks.lock_HA("vim", "create", op_id):
kuuse6a470c62019-07-10 13:52:45 +020070 return
71
tierno59d22d22018-09-25 18:10:19 +020072 vim_id = vim_content["_id"]
73 logging_text = "Task vim_create={} ".format(vim_id)
74 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +020075
tierno59d22d22018-09-25 18:10:19 +020076 db_vim = None
77 db_vim_update = {}
78 exc = None
79 RO_sdn_id = None
80 try:
81 step = "Getting vim-id='{}' from db".format(vim_id)
82 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
garciadeblas5697b8b2021-03-24 09:17:02 +010083 if vim_content.get("config") and vim_content["config"].get(
84 "sdn-controller"
85 ):
86 step = "Getting sdn-controller-id='{}' from db".format(
87 vim_content["config"]["sdn-controller"]
88 )
89 db_sdn = self.db.get_one(
90 "sdns", {"_id": vim_content["config"]["sdn-controller"]}
91 )
kuuse6a470c62019-07-10 13:52:45 +020092
93 # If the VIM account has an associated SDN account, also
94 # wait for any previous tasks in process for the SDN
garciadeblas5697b8b2021-03-24 09:17:02 +010095 await self.lcm_tasks.waitfor_related_HA("sdn", "ANY", db_sdn["_id"])
kuuse6a470c62019-07-10 13:52:45 +020096
garciadeblas5697b8b2021-03-24 09:17:02 +010097 if (
98 db_sdn.get("_admin")
99 and db_sdn["_admin"].get("deployed")
100 and db_sdn["_admin"]["deployed"].get("RO")
101 ):
tierno59d22d22018-09-25 18:10:19 +0200102 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
103 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100104 raise LcmException(
105 "sdn-controller={} is not available. Not deployed at RO".format(
106 vim_content["config"]["sdn-controller"]
107 )
108 )
tierno59d22d22018-09-25 18:10:19 +0200109
110 step = "Creating vim at RO"
tiernobaa51102018-12-14 13:16:18 +0000111 db_vim_update["_admin.deployed.RO"] = None
tierno59d22d22018-09-25 18:10:19 +0200112 db_vim_update["_admin.detailed-status"] = step
113 self.update_db_2("vim_accounts", vim_id, db_vim_update)
114 RO = ROclient.ROClient(self.loop, **self.ro_config)
115 vim_RO = deepcopy(vim_content)
116 vim_RO.pop("_id", None)
117 vim_RO.pop("_admin", None)
tierno17a612f2018-10-23 11:30:42 +0200118 schema_version = vim_RO.pop("schema_version", None)
tierno59d22d22018-09-25 18:10:19 +0200119 vim_RO.pop("schema_type", None)
120 vim_RO.pop("vim_tenant_name", None)
121 vim_RO["type"] = vim_RO.pop("vim_type")
122 vim_RO.pop("vim_user", None)
123 vim_RO.pop("vim_password", None)
124 if RO_sdn_id:
125 vim_RO["config"]["sdn-controller"] = RO_sdn_id
126 desc = await RO.create("vim", descriptor=vim_RO)
127 RO_vim_id = desc["uuid"]
128 db_vim_update["_admin.deployed.RO"] = RO_vim_id
garciadeblas5697b8b2021-03-24 09:17:02 +0100129 self.logger.debug(
130 logging_text + "VIM created at RO_vim_id={}".format(RO_vim_id)
131 )
tierno59d22d22018-09-25 18:10:19 +0200132
133 step = "Creating vim_account at RO"
134 db_vim_update["_admin.detailed-status"] = step
135 self.update_db_2("vim_accounts", vim_id, db_vim_update)
136
tierno17a612f2018-10-23 11:30:42 +0200137 if vim_content.get("vim_password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100138 vim_content["vim_password"] = self.db.decrypt(
139 vim_content["vim_password"],
140 schema_version=schema_version,
141 salt=vim_id,
142 )
143 vim_account_RO = {
144 "vim_tenant_name": vim_content["vim_tenant_name"],
145 "vim_username": vim_content["vim_user"],
146 "vim_password": vim_content["vim_password"],
147 }
tierno59d22d22018-09-25 18:10:19 +0200148 if vim_RO.get("config"):
149 vim_account_RO["config"] = vim_RO["config"]
150 if "sdn-controller" in vim_account_RO["config"]:
151 del vim_account_RO["config"]["sdn-controller"]
152 if "sdn-port-mapping" in vim_account_RO["config"]:
153 del vim_account_RO["config"]["sdn-port-mapping"]
garciadeblas5697b8b2021-03-24 09:17:02 +0100154 vim_config_encrypted_keys = self.vim_config_encrypted.get(
155 schema_version
156 ) or self.vim_config_encrypted.get("default")
tierno2d9f6f52019-08-01 16:32:56 +0000157 for p in vim_config_encrypted_keys:
tierno17a612f2018-10-23 11:30:42 +0200158 if vim_account_RO["config"].get(p):
garciadeblas5697b8b2021-03-24 09:17:02 +0100159 vim_account_RO["config"][p] = self.db.decrypt(
160 vim_account_RO["config"][p],
161 schema_version=schema_version,
162 salt=vim_id,
163 )
tierno17a612f2018-10-23 11:30:42 +0200164
tiernoe37b57d2018-12-11 17:22:51 +0000165 desc = await RO.attach("vim_account", RO_vim_id, descriptor=vim_account_RO)
tierno59d22d22018-09-25 18:10:19 +0200166 db_vim_update["_admin.deployed.RO-account"] = desc["uuid"]
167 db_vim_update["_admin.operationalState"] = "ENABLED"
168 db_vim_update["_admin.detailed-status"] = "Done"
kuuse6a470c62019-07-10 13:52:45 +0200169 # Mark the VIM 'create' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100170 operation_state = "COMPLETED"
171 operation_details = "Done"
tierno59d22d22018-09-25 18:10:19 +0200172
garciadeblas5697b8b2021-03-24 09:17:02 +0100173 self.logger.debug(
174 logging_text
175 + "Exit Ok VIM account created at RO_vim_account_id={}".format(
176 desc["uuid"]
177 )
178 )
tierno59d22d22018-09-25 18:10:19 +0200179 return
180
tiernocc29b592020-09-18 10:33:18 +0000181 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200182 self.logger.error(logging_text + "Exit Exception {}".format(e))
183 exc = e
184 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100185 self.logger.critical(
186 logging_text + "Exit Exception {}".format(e), exc_info=True
187 )
tierno59d22d22018-09-25 18:10:19 +0200188 exc = e
189 finally:
190 if exc and db_vim:
191 db_vim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100192 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
193 step, exc
194 )
kuuse6a470c62019-07-10 13:52:45 +0200195 # Mark the VIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100196 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000197 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000198 try:
199 if db_vim_update:
200 self.update_db_2("vim_accounts", vim_id, db_vim_update)
kuuse6a470c62019-07-10 13:52:45 +0200201 # Register the VIM 'create' HA task either
202 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100203 self.lcm_tasks.unlock_HA(
204 "vim",
205 "create",
206 op_id,
207 operationState=operation_state,
208 detailed_status=operation_details,
209 )
tiernobaa51102018-12-14 13:16:18 +0000210 except DbException as e:
211 self.logger.error(logging_text + "Cannot update database: {}".format(e))
212
tierno59d22d22018-09-25 18:10:19 +0200213 self.lcm_tasks.remove("vim_account", vim_id, order_id)
214
215 async def edit(self, vim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200216 # HA tasks and backward compatibility:
217 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
218 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100219 op_id = vim_content.pop("op_id", None)
220 if not self.lcm_tasks.lock_HA("vim", "edit", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200221 return
222
tierno59d22d22018-09-25 18:10:19 +0200223 vim_id = vim_content["_id"]
224 logging_text = "Task vim_edit={} ".format(vim_id)
225 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200226
tierno59d22d22018-09-25 18:10:19 +0200227 db_vim = None
228 exc = None
229 RO_sdn_id = None
230 RO_vim_id = None
231 db_vim_update = {}
232 step = "Getting vim-id='{}' from db".format(vim_id)
233 try:
kuuse6a470c62019-07-10 13:52:45 +0200234 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100235 await self.lcm_tasks.waitfor_related_HA("vim", "edit", op_id)
tierno59d22d22018-09-25 18:10:19 +0200236
kuuse6a470c62019-07-10 13:52:45 +0200237 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
tierno59d22d22018-09-25 18:10:19 +0200238
garciadeblas5697b8b2021-03-24 09:17:02 +0100239 if (
240 db_vim.get("_admin")
241 and db_vim["_admin"].get("deployed")
242 and db_vim["_admin"]["deployed"].get("RO")
243 ):
244 if vim_content.get("config") and vim_content["config"].get(
245 "sdn-controller"
246 ):
247 step = "Getting sdn-controller-id='{}' from db".format(
248 vim_content["config"]["sdn-controller"]
249 )
250 db_sdn = self.db.get_one(
251 "sdns", {"_id": vim_content["config"]["sdn-controller"]}
252 )
tierno59d22d22018-09-25 18:10:19 +0200253
kuuse6a470c62019-07-10 13:52:45 +0200254 # If the VIM account has an associated SDN account, also
255 # wait for any previous tasks in process for the SDN
garciadeblas5697b8b2021-03-24 09:17:02 +0100256 await self.lcm_tasks.waitfor_related_HA("sdn", "ANY", db_sdn["_id"])
tierno59d22d22018-09-25 18:10:19 +0200257
garciadeblas5697b8b2021-03-24 09:17:02 +0100258 if (
259 db_sdn.get("_admin")
260 and db_sdn["_admin"].get("deployed")
261 and db_sdn["_admin"]["deployed"].get("RO")
262 ):
tierno59d22d22018-09-25 18:10:19 +0200263 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
264 else:
garciadeblas5697b8b2021-03-24 09:17:02 +0100265 raise LcmException(
266 "sdn-controller={} is not available. Not deployed at RO".format(
267 vim_content["config"]["sdn-controller"]
268 )
269 )
tierno59d22d22018-09-25 18:10:19 +0200270
271 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
272 step = "Editing vim at RO"
273 RO = ROclient.ROClient(self.loop, **self.ro_config)
274 vim_RO = deepcopy(vim_content)
275 vim_RO.pop("_id", None)
276 vim_RO.pop("_admin", None)
tierno17a612f2018-10-23 11:30:42 +0200277 schema_version = vim_RO.pop("schema_version", None)
tierno59d22d22018-09-25 18:10:19 +0200278 vim_RO.pop("schema_type", None)
279 vim_RO.pop("vim_tenant_name", None)
280 if "vim_type" in vim_RO:
281 vim_RO["type"] = vim_RO.pop("vim_type")
282 vim_RO.pop("vim_user", None)
283 vim_RO.pop("vim_password", None)
284 if RO_sdn_id:
285 vim_RO["config"]["sdn-controller"] = RO_sdn_id
tierno2357f4e2020-10-19 16:38:59 +0000286 # TODO make a deep update of sdn-port-mapping
tierno59d22d22018-09-25 18:10:19 +0200287 if vim_RO:
288 await RO.edit("vim", RO_vim_id, descriptor=vim_RO)
289
290 step = "Editing vim-account at RO tenant"
291 vim_account_RO = {}
292 if "config" in vim_content:
293 if "sdn-controller" in vim_content["config"]:
294 del vim_content["config"]["sdn-controller"]
295 if "sdn-port-mapping" in vim_content["config"]:
296 del vim_content["config"]["sdn-port-mapping"]
297 if not vim_content["config"]:
298 del vim_content["config"]
tierno17a612f2018-10-23 11:30:42 +0200299 if "vim_tenant_name" in vim_content:
300 vim_account_RO["vim_tenant_name"] = vim_content["vim_tenant_name"]
301 if "vim_password" in vim_content:
302 vim_account_RO["vim_password"] = vim_content["vim_password"]
303 if vim_content.get("vim_password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100304 vim_account_RO["vim_password"] = self.db.decrypt(
305 vim_content["vim_password"],
306 schema_version=schema_version,
307 salt=vim_id,
308 )
tierno17a612f2018-10-23 11:30:42 +0200309 if "config" in vim_content:
310 vim_account_RO["config"] = vim_content["config"]
311 if vim_content.get("config"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100312 vim_config_encrypted_keys = self.vim_config_encrypted.get(
313 schema_version
314 ) or self.vim_config_encrypted.get("default")
tierno2d9f6f52019-08-01 16:32:56 +0000315 for p in vim_config_encrypted_keys:
tierno17a612f2018-10-23 11:30:42 +0200316 if vim_content["config"].get(p):
garciadeblas5697b8b2021-03-24 09:17:02 +0100317 vim_account_RO["config"][p] = self.db.decrypt(
318 vim_content["config"][p],
319 schema_version=schema_version,
320 salt=vim_id,
321 )
tierno17a612f2018-10-23 11:30:42 +0200322
tierno59d22d22018-09-25 18:10:19 +0200323 if "vim_user" in vim_content:
324 vim_content["vim_username"] = vim_content["vim_user"]
325 # vim_account must be edited always even if empty in order to ensure changes are translated to RO
326 # vim_thread. RO will remove and relaunch a new thread for this vim_account
327 await RO.edit("vim_account", RO_vim_id, descriptor=vim_account_RO)
328 db_vim_update["_admin.operationalState"] = "ENABLED"
kuuse6a470c62019-07-10 13:52:45 +0200329 # Mark the VIM 'edit' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100330 operation_state = "COMPLETED"
331 operation_details = "Done"
tierno59d22d22018-09-25 18:10:19 +0200332
333 self.logger.debug(logging_text + "Exit Ok RO_vim_id={}".format(RO_vim_id))
334 return
335
tiernocc29b592020-09-18 10:33:18 +0000336 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200337 self.logger.error(logging_text + "Exit Exception {}".format(e))
338 exc = e
339 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100340 self.logger.critical(
341 logging_text + "Exit Exception {}".format(e), exc_info=True
342 )
tierno59d22d22018-09-25 18:10:19 +0200343 exc = e
344 finally:
345 if exc and db_vim:
346 db_vim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100347 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
348 step, exc
349 )
kuuse6a470c62019-07-10 13:52:45 +0200350 # Mark the VIM 'edit' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100351 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000352 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000353 try:
354 if db_vim_update:
355 self.update_db_2("vim_accounts", vim_id, db_vim_update)
kuuse6a470c62019-07-10 13:52:45 +0200356 # Register the VIM 'edit' HA task either
357 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100358 self.lcm_tasks.unlock_HA(
359 "vim",
360 "edit",
361 op_id,
362 operationState=operation_state,
363 detailed_status=operation_details,
364 )
tiernobaa51102018-12-14 13:16:18 +0000365 except DbException as e:
366 self.logger.error(logging_text + "Cannot update database: {}".format(e))
367
tierno59d22d22018-09-25 18:10:19 +0200368 self.lcm_tasks.remove("vim_account", vim_id, order_id)
369
kuuse6a470c62019-07-10 13:52:45 +0200370 async def delete(self, vim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200371 # HA tasks and backward compatibility:
372 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
373 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100374 op_id = vim_content.pop("op_id", None)
375 if not self.lcm_tasks.lock_HA("vim", "delete", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200376 return
377
378 vim_id = vim_content["_id"]
tierno59d22d22018-09-25 18:10:19 +0200379 logging_text = "Task vim_delete={} ".format(vim_id)
380 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200381
tierno59d22d22018-09-25 18:10:19 +0200382 db_vim = None
383 db_vim_update = {}
384 exc = None
385 step = "Getting vim from db"
386 try:
kuuse6a470c62019-07-10 13:52:45 +0200387 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100388 await self.lcm_tasks.waitfor_related_HA("vim", "delete", op_id)
tierno2357f4e2020-10-19 16:38:59 +0000389 if not self.ro_config.get("ng"):
390 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100391 if (
392 db_vim.get("_admin")
393 and db_vim["_admin"].get("deployed")
394 and db_vim["_admin"]["deployed"].get("RO")
395 ):
tierno2357f4e2020-10-19 16:38:59 +0000396 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
397 RO = ROclient.ROClient(self.loop, **self.ro_config)
398 step = "Detaching vim from RO tenant"
399 try:
400 await RO.detach("vim_account", RO_vim_id)
401 except ROclient.ROClientException as e:
402 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +0100403 self.logger.debug(
404 logging_text
405 + "RO_vim_id={} already detached".format(RO_vim_id)
406 )
tierno2357f4e2020-10-19 16:38:59 +0000407 else:
408 raise
kuuse6a470c62019-07-10 13:52:45 +0200409
tierno2357f4e2020-10-19 16:38:59 +0000410 step = "Deleting vim from RO"
411 try:
412 await RO.delete("vim", RO_vim_id)
413 except ROclient.ROClientException as e:
414 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +0100415 self.logger.debug(
416 logging_text
417 + "RO_vim_id={} already deleted".format(RO_vim_id)
418 )
tierno2357f4e2020-10-19 16:38:59 +0000419 else:
420 raise
421 else:
422 # nothing to delete
423 self.logger.debug(logging_text + "Nothing to remove at RO")
tierno59d22d22018-09-25 18:10:19 +0200424 self.db.del_one("vim_accounts", {"_id": vim_id})
tiernobaa51102018-12-14 13:16:18 +0000425 db_vim = None
tierno59d22d22018-09-25 18:10:19 +0200426 self.logger.debug(logging_text + "Exit Ok")
427 return
428
tiernocc29b592020-09-18 10:33:18 +0000429 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200430 self.logger.error(logging_text + "Exit Exception {}".format(e))
431 exc = e
432 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100433 self.logger.critical(
434 logging_text + "Exit Exception {}".format(e), exc_info=True
435 )
tierno59d22d22018-09-25 18:10:19 +0200436 exc = e
437 finally:
438 self.lcm_tasks.remove("vim_account", vim_id, order_id)
439 if exc and db_vim:
440 db_vim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100441 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
442 step, exc
443 )
kuuse6a470c62019-07-10 13:52:45 +0200444 # Mark the VIM 'delete' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100445 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000446 operation_details = "ERROR {}: {}".format(step, exc)
garciadeblas5697b8b2021-03-24 09:17:02 +0100447 self.lcm_tasks.unlock_HA(
448 "vim",
449 "delete",
450 op_id,
451 operationState=operation_state,
452 detailed_status=operation_details,
453 )
tiernobaa51102018-12-14 13:16:18 +0000454 try:
455 if db_vim and db_vim_update:
456 self.update_db_2("vim_accounts", vim_id, db_vim_update)
kuuse6a470c62019-07-10 13:52:45 +0200457 # If the VIM 'delete' HA task was succesful, the DB entry has been deleted,
458 # which means that there is nowhere to register this task, so do nothing here.
tiernobaa51102018-12-14 13:16:18 +0000459 except DbException as e:
460 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +0200461 self.lcm_tasks.remove("vim_account", vim_id, order_id)
462
463
tiernoe37b57d2018-12-11 17:22:51 +0000464class WimLcm(LcmBase):
465 # values that are encrypted at wim config because they are passwords
466 wim_config_encrypted = ()
467
bravof922c4172020-11-24 21:21:43 -0300468 def __init__(self, msg, lcm_tasks, config, loop):
tiernoe37b57d2018-12-11 17:22:51 +0000469 """
470 Init, Connect to database, filesystem storage, and messaging
471 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
472 :return: None
473 """
474
garciadeblas5697b8b2021-03-24 09:17:02 +0100475 self.logger = logging.getLogger("lcm.vim")
tiernoe37b57d2018-12-11 17:22:51 +0000476 self.loop = loop
477 self.lcm_tasks = lcm_tasks
Luis Vegaa27dc532022-11-11 20:10:49 +0000478 self.ro_config = config["RO"]
tiernoe37b57d2018-12-11 17:22:51 +0000479
bravof922c4172020-11-24 21:21:43 -0300480 super().__init__(msg, self.logger)
tiernoe37b57d2018-12-11 17:22:51 +0000481
482 async def create(self, wim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200483 # HA tasks and backward compatibility:
484 # If 'wim_content' does not include 'op_id', we a running a legacy NBI version.
485 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
486 # Register 'create' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +0100487 op_id = wim_content.pop("op_id", None)
488 self.lcm_tasks.lock_HA("wim", "create", op_id)
kuuse6a470c62019-07-10 13:52:45 +0200489
tiernoe37b57d2018-12-11 17:22:51 +0000490 wim_id = wim_content["_id"]
491 logging_text = "Task wim_create={} ".format(wim_id)
492 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200493
tiernoe37b57d2018-12-11 17:22:51 +0000494 db_wim = None
495 db_wim_update = {}
496 exc = None
497 try:
498 step = "Getting wim-id='{}' from db".format(wim_id)
499 db_wim = self.db.get_one("wim_accounts", {"_id": wim_id})
500 db_wim_update["_admin.deployed.RO"] = None
501
502 step = "Creating wim at RO"
503 db_wim_update["_admin.detailed-status"] = step
504 self.update_db_2("wim_accounts", wim_id, db_wim_update)
505 RO = ROclient.ROClient(self.loop, **self.ro_config)
506 wim_RO = deepcopy(wim_content)
507 wim_RO.pop("_id", None)
508 wim_RO.pop("_admin", None)
509 schema_version = wim_RO.pop("schema_version", None)
510 wim_RO.pop("schema_type", None)
511 wim_RO.pop("wim_tenant_name", None)
512 wim_RO["type"] = wim_RO.pop("wim_type")
513 wim_RO.pop("wim_user", None)
514 wim_RO.pop("wim_password", None)
515 desc = await RO.create("wim", descriptor=wim_RO)
516 RO_wim_id = desc["uuid"]
517 db_wim_update["_admin.deployed.RO"] = RO_wim_id
garciadeblas5697b8b2021-03-24 09:17:02 +0100518 self.logger.debug(
519 logging_text + "WIM created at RO_wim_id={}".format(RO_wim_id)
520 )
tiernoe37b57d2018-12-11 17:22:51 +0000521
522 step = "Creating wim_account at RO"
523 db_wim_update["_admin.detailed-status"] = step
524 self.update_db_2("wim_accounts", wim_id, db_wim_update)
525
526 if wim_content.get("wim_password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100527 wim_content["wim_password"] = self.db.decrypt(
528 wim_content["wim_password"],
529 schema_version=schema_version,
530 salt=wim_id,
531 )
532 wim_account_RO = {
533 "name": wim_content["name"],
534 "user": wim_content["user"],
535 "password": wim_content["password"],
536 }
tiernoe37b57d2018-12-11 17:22:51 +0000537 if wim_RO.get("config"):
538 wim_account_RO["config"] = wim_RO["config"]
539 if "wim_port_mapping" in wim_account_RO["config"]:
540 del wim_account_RO["config"]["wim_port_mapping"]
541 for p in self.wim_config_encrypted:
542 if wim_account_RO["config"].get(p):
garciadeblas5697b8b2021-03-24 09:17:02 +0100543 wim_account_RO["config"][p] = self.db.decrypt(
544 wim_account_RO["config"][p],
545 schema_version=schema_version,
546 salt=wim_id,
547 )
tiernoe37b57d2018-12-11 17:22:51 +0000548
549 desc = await RO.attach("wim_account", RO_wim_id, descriptor=wim_account_RO)
550 db_wim_update["_admin.deployed.RO-account"] = desc["uuid"]
551 db_wim_update["_admin.operationalState"] = "ENABLED"
552 db_wim_update["_admin.detailed-status"] = "Done"
kuuse6a470c62019-07-10 13:52:45 +0200553 # Mark the WIM 'create' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100554 operation_state = "COMPLETED"
555 operation_details = "Done"
tiernoe37b57d2018-12-11 17:22:51 +0000556
garciadeblas5697b8b2021-03-24 09:17:02 +0100557 self.logger.debug(
558 logging_text
559 + "Exit Ok WIM account created at RO_wim_account_id={}".format(
560 desc["uuid"]
561 )
562 )
tiernoe37b57d2018-12-11 17:22:51 +0000563 return
564
tiernocc29b592020-09-18 10:33:18 +0000565 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tiernoe37b57d2018-12-11 17:22:51 +0000566 self.logger.error(logging_text + "Exit Exception {}".format(e))
567 exc = e
568 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100569 self.logger.critical(
570 logging_text + "Exit Exception {}".format(e), exc_info=True
571 )
tiernoe37b57d2018-12-11 17:22:51 +0000572 exc = e
573 finally:
574 if exc and db_wim:
575 db_wim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100576 db_wim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
577 step, exc
578 )
kuuse6a470c62019-07-10 13:52:45 +0200579 # Mark the WIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100580 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000581 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000582 try:
583 if db_wim_update:
584 self.update_db_2("wim_accounts", wim_id, db_wim_update)
kuuse6a470c62019-07-10 13:52:45 +0200585 # Register the WIM 'create' HA task either
586 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100587 self.lcm_tasks.unlock_HA(
588 "wim",
589 "create",
590 op_id,
591 operationState=operation_state,
592 detailed_status=operation_details,
593 )
tiernobaa51102018-12-14 13:16:18 +0000594 except DbException as e:
595 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tiernoe37b57d2018-12-11 17:22:51 +0000596 self.lcm_tasks.remove("wim_account", wim_id, order_id)
597
598 async def edit(self, wim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200599 # HA tasks and backward compatibility:
600 # If 'wim_content' does not include 'op_id', we a running a legacy NBI version.
601 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100602 op_id = wim_content.pop("op_id", None)
603 if not self.lcm_tasks.lock_HA("wim", "edit", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200604 return
605
tiernoe37b57d2018-12-11 17:22:51 +0000606 wim_id = wim_content["_id"]
607 logging_text = "Task wim_edit={} ".format(wim_id)
608 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200609
tiernoe37b57d2018-12-11 17:22:51 +0000610 db_wim = None
611 exc = None
612 RO_wim_id = None
613 db_wim_update = {}
614 step = "Getting wim-id='{}' from db".format(wim_id)
615 try:
kuuse6a470c62019-07-10 13:52:45 +0200616 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100617 await self.lcm_tasks.waitfor_related_HA("wim", "edit", op_id)
tiernoe37b57d2018-12-11 17:22:51 +0000618
kuuse6a470c62019-07-10 13:52:45 +0200619 db_wim = self.db.get_one("wim_accounts", {"_id": wim_id})
tiernoe37b57d2018-12-11 17:22:51 +0000620
garciadeblas5697b8b2021-03-24 09:17:02 +0100621 if (
622 db_wim.get("_admin")
623 and db_wim["_admin"].get("deployed")
624 and db_wim["_admin"]["deployed"].get("RO")
625 ):
tiernoe37b57d2018-12-11 17:22:51 +0000626 RO_wim_id = db_wim["_admin"]["deployed"]["RO"]
627 step = "Editing wim at RO"
628 RO = ROclient.ROClient(self.loop, **self.ro_config)
629 wim_RO = deepcopy(wim_content)
630 wim_RO.pop("_id", None)
631 wim_RO.pop("_admin", None)
632 schema_version = wim_RO.pop("schema_version", None)
633 wim_RO.pop("schema_type", None)
634 wim_RO.pop("wim_tenant_name", None)
635 if "wim_type" in wim_RO:
636 wim_RO["type"] = wim_RO.pop("wim_type")
637 wim_RO.pop("wim_user", None)
638 wim_RO.pop("wim_password", None)
639 # TODO make a deep update of wim_port_mapping
640 if wim_RO:
641 await RO.edit("wim", RO_wim_id, descriptor=wim_RO)
642
643 step = "Editing wim-account at RO tenant"
644 wim_account_RO = {}
645 if "config" in wim_content:
646 if "wim_port_mapping" in wim_content["config"]:
647 del wim_content["config"]["wim_port_mapping"]
648 if not wim_content["config"]:
649 del wim_content["config"]
650 if "wim_tenant_name" in wim_content:
651 wim_account_RO["wim_tenant_name"] = wim_content["wim_tenant_name"]
652 if "wim_password" in wim_content:
653 wim_account_RO["wim_password"] = wim_content["wim_password"]
654 if wim_content.get("wim_password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100655 wim_account_RO["wim_password"] = self.db.decrypt(
656 wim_content["wim_password"],
657 schema_version=schema_version,
658 salt=wim_id,
659 )
tiernoe37b57d2018-12-11 17:22:51 +0000660 if "config" in wim_content:
661 wim_account_RO["config"] = wim_content["config"]
662 if wim_content.get("config"):
663 for p in self.wim_config_encrypted:
664 if wim_content["config"].get(p):
garciadeblas5697b8b2021-03-24 09:17:02 +0100665 wim_account_RO["config"][p] = self.db.decrypt(
666 wim_content["config"][p],
667 schema_version=schema_version,
668 salt=wim_id,
669 )
tiernoe37b57d2018-12-11 17:22:51 +0000670
671 if "wim_user" in wim_content:
672 wim_content["wim_username"] = wim_content["wim_user"]
673 # wim_account must be edited always even if empty in order to ensure changes are translated to RO
674 # wim_thread. RO will remove and relaunch a new thread for this wim_account
675 await RO.edit("wim_account", RO_wim_id, descriptor=wim_account_RO)
676 db_wim_update["_admin.operationalState"] = "ENABLED"
kuuse6a470c62019-07-10 13:52:45 +0200677 # Mark the WIM 'edit' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100678 operation_state = "COMPLETED"
679 operation_details = "Done"
tiernoe37b57d2018-12-11 17:22:51 +0000680
681 self.logger.debug(logging_text + "Exit Ok RO_wim_id={}".format(RO_wim_id))
682 return
683
tiernocc29b592020-09-18 10:33:18 +0000684 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tiernoe37b57d2018-12-11 17:22:51 +0000685 self.logger.error(logging_text + "Exit Exception {}".format(e))
686 exc = e
687 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100688 self.logger.critical(
689 logging_text + "Exit Exception {}".format(e), exc_info=True
690 )
tiernoe37b57d2018-12-11 17:22:51 +0000691 exc = e
692 finally:
693 if exc and db_wim:
694 db_wim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100695 db_wim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
696 step, exc
697 )
kuuse6a470c62019-07-10 13:52:45 +0200698 # Mark the WIM 'edit' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100699 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000700 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000701 try:
702 if db_wim_update:
703 self.update_db_2("wim_accounts", wim_id, db_wim_update)
kuuse6a470c62019-07-10 13:52:45 +0200704 # Register the WIM 'edit' HA task either
705 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100706 self.lcm_tasks.unlock_HA(
707 "wim",
708 "edit",
709 op_id,
710 operationState=operation_state,
711 detailed_status=operation_details,
712 )
tiernobaa51102018-12-14 13:16:18 +0000713 except DbException as e:
714 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tiernoe37b57d2018-12-11 17:22:51 +0000715 self.lcm_tasks.remove("wim_account", wim_id, order_id)
716
kuuse6a470c62019-07-10 13:52:45 +0200717 async def delete(self, wim_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200718 # HA tasks and backward compatibility:
719 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
720 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100721 op_id = wim_content.pop("op_id", None)
722 if not self.lcm_tasks.lock_HA("wim", "delete", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200723 return
724
725 wim_id = wim_content["_id"]
tiernoe37b57d2018-12-11 17:22:51 +0000726 logging_text = "Task wim_delete={} ".format(wim_id)
727 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200728
tiernoe37b57d2018-12-11 17:22:51 +0000729 db_wim = None
730 db_wim_update = {}
731 exc = None
732 step = "Getting wim from db"
733 try:
kuuse6a470c62019-07-10 13:52:45 +0200734 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100735 await self.lcm_tasks.waitfor_related_HA("wim", "delete", op_id)
kuuse6a470c62019-07-10 13:52:45 +0200736
tiernoe37b57d2018-12-11 17:22:51 +0000737 db_wim = self.db.get_one("wim_accounts", {"_id": wim_id})
garciadeblas5697b8b2021-03-24 09:17:02 +0100738 if (
739 db_wim.get("_admin")
740 and db_wim["_admin"].get("deployed")
741 and db_wim["_admin"]["deployed"].get("RO")
742 ):
tiernoe37b57d2018-12-11 17:22:51 +0000743 RO_wim_id = db_wim["_admin"]["deployed"]["RO"]
744 RO = ROclient.ROClient(self.loop, **self.ro_config)
745 step = "Detaching wim from RO tenant"
746 try:
747 await RO.detach("wim_account", RO_wim_id)
748 except ROclient.ROClientException as e:
749 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +0100750 self.logger.debug(
751 logging_text
752 + "RO_wim_id={} already detached".format(RO_wim_id)
753 )
tiernoe37b57d2018-12-11 17:22:51 +0000754 else:
755 raise
756
757 step = "Deleting wim from RO"
758 try:
759 await RO.delete("wim", RO_wim_id)
760 except ROclient.ROClientException as e:
761 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +0100762 self.logger.debug(
763 logging_text
764 + "RO_wim_id={} already deleted".format(RO_wim_id)
765 )
tiernoe37b57d2018-12-11 17:22:51 +0000766 else:
767 raise
768 else:
769 # nothing to delete
aktas61f61922021-07-29 07:56:27 +0300770 self.logger.error(logging_text + "Nothing to remove at RO")
tiernoe37b57d2018-12-11 17:22:51 +0000771 self.db.del_one("wim_accounts", {"_id": wim_id})
tiernobaa51102018-12-14 13:16:18 +0000772 db_wim = None
tiernoe37b57d2018-12-11 17:22:51 +0000773 self.logger.debug(logging_text + "Exit Ok")
774 return
775
tiernocc29b592020-09-18 10:33:18 +0000776 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tiernoe37b57d2018-12-11 17:22:51 +0000777 self.logger.error(logging_text + "Exit Exception {}".format(e))
778 exc = e
779 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100780 self.logger.critical(
781 logging_text + "Exit Exception {}".format(e), exc_info=True
782 )
tiernoe37b57d2018-12-11 17:22:51 +0000783 exc = e
784 finally:
785 self.lcm_tasks.remove("wim_account", wim_id, order_id)
786 if exc and db_wim:
787 db_wim_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100788 db_wim_update["_admin.detailed-status"] = "ERROR {}: {}".format(
789 step, exc
790 )
kuuse6a470c62019-07-10 13:52:45 +0200791 # Mark the WIM 'delete' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100792 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000793 operation_details = "ERROR {}: {}".format(step, exc)
garciadeblas5697b8b2021-03-24 09:17:02 +0100794 self.lcm_tasks.unlock_HA(
795 "wim",
796 "delete",
797 op_id,
798 operationState=operation_state,
799 detailed_status=operation_details,
800 )
tiernobaa51102018-12-14 13:16:18 +0000801 try:
802 if db_wim and db_wim_update:
803 self.update_db_2("wim_accounts", wim_id, db_wim_update)
kuuse6a470c62019-07-10 13:52:45 +0200804 # If the WIM 'delete' HA task was succesful, the DB entry has been deleted,
805 # which means that there is nowhere to register this task, so do nothing here.
tiernobaa51102018-12-14 13:16:18 +0000806 except DbException as e:
807 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tiernoe37b57d2018-12-11 17:22:51 +0000808 self.lcm_tasks.remove("wim_account", wim_id, order_id)
809
810
tierno59d22d22018-09-25 18:10:19 +0200811class SdnLcm(LcmBase):
bravof922c4172020-11-24 21:21:43 -0300812 def __init__(self, msg, lcm_tasks, config, loop):
tierno59d22d22018-09-25 18:10:19 +0200813 """
814 Init, Connect to database, filesystem storage, and messaging
815 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
816 :return: None
817 """
818
garciadeblas5697b8b2021-03-24 09:17:02 +0100819 self.logger = logging.getLogger("lcm.sdn")
tierno59d22d22018-09-25 18:10:19 +0200820 self.loop = loop
821 self.lcm_tasks = lcm_tasks
Luis Vegaa27dc532022-11-11 20:10:49 +0000822 self.ro_config = config["RO"]
tierno59d22d22018-09-25 18:10:19 +0200823
bravof922c4172020-11-24 21:21:43 -0300824 super().__init__(msg, self.logger)
tierno59d22d22018-09-25 18:10:19 +0200825
826 async def create(self, sdn_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200827 # HA tasks and backward compatibility:
828 # If 'sdn_content' does not include 'op_id', we a running a legacy NBI version.
829 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
830 # Register 'create' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +0100831 op_id = sdn_content.pop("op_id", None)
832 self.lcm_tasks.lock_HA("sdn", "create", op_id)
kuuse6a470c62019-07-10 13:52:45 +0200833
tierno59d22d22018-09-25 18:10:19 +0200834 sdn_id = sdn_content["_id"]
835 logging_text = "Task sdn_create={} ".format(sdn_id)
836 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200837
tierno59d22d22018-09-25 18:10:19 +0200838 db_sdn = None
839 db_sdn_update = {}
840 RO_sdn_id = None
841 exc = None
842 try:
843 step = "Getting sdn from db"
844 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
845 db_sdn_update["_admin.deployed.RO"] = None
846
847 step = "Creating sdn at RO"
tiernobaa51102018-12-14 13:16:18 +0000848 db_sdn_update["_admin.detailed-status"] = step
849 self.update_db_2("sdns", sdn_id, db_sdn_update)
850
tierno59d22d22018-09-25 18:10:19 +0200851 RO = ROclient.ROClient(self.loop, **self.ro_config)
852 sdn_RO = deepcopy(sdn_content)
853 sdn_RO.pop("_id", None)
854 sdn_RO.pop("_admin", None)
tierno17a612f2018-10-23 11:30:42 +0200855 schema_version = sdn_RO.pop("schema_version", None)
tierno59d22d22018-09-25 18:10:19 +0200856 sdn_RO.pop("schema_type", None)
857 sdn_RO.pop("description", None)
tierno17a612f2018-10-23 11:30:42 +0200858 if sdn_RO.get("password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100859 sdn_RO["password"] = self.db.decrypt(
860 sdn_RO["password"], schema_version=schema_version, salt=sdn_id
861 )
tierno17a612f2018-10-23 11:30:42 +0200862
tierno59d22d22018-09-25 18:10:19 +0200863 desc = await RO.create("sdn", descriptor=sdn_RO)
864 RO_sdn_id = desc["uuid"]
865 db_sdn_update["_admin.deployed.RO"] = RO_sdn_id
866 db_sdn_update["_admin.operationalState"] = "ENABLED"
867 self.logger.debug(logging_text + "Exit Ok RO_sdn_id={}".format(RO_sdn_id))
kuuse6a470c62019-07-10 13:52:45 +0200868 # Mark the SDN 'create' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100869 operation_state = "COMPLETED"
870 operation_details = "Done"
tierno59d22d22018-09-25 18:10:19 +0200871 return
872
tiernocc29b592020-09-18 10:33:18 +0000873 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200874 self.logger.error(logging_text + "Exit Exception {}".format(e))
875 exc = e
876 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100877 self.logger.critical(
878 logging_text + "Exit Exception {}".format(e), exc_info=True
879 )
tierno59d22d22018-09-25 18:10:19 +0200880 exc = e
881 finally:
882 if exc and db_sdn:
883 db_sdn_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +0100884 db_sdn_update["_admin.detailed-status"] = "ERROR {}: {}".format(
885 step, exc
886 )
kuuse6a470c62019-07-10 13:52:45 +0200887 # Mark the SDN 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100888 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000889 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000890 try:
891 if db_sdn and db_sdn_update:
892 self.update_db_2("sdns", sdn_id, db_sdn_update)
kuuse6a470c62019-07-10 13:52:45 +0200893 # Register the SDN 'create' HA task either
894 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100895 self.lcm_tasks.unlock_HA(
896 "sdn",
897 "create",
898 op_id,
899 operationState=operation_state,
900 detailed_status=operation_details,
901 )
tiernobaa51102018-12-14 13:16:18 +0000902 except DbException as e:
903 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +0200904 self.lcm_tasks.remove("sdn", sdn_id, order_id)
905
906 async def edit(self, sdn_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200907 # HA tasks and backward compatibility:
908 # If 'sdn_content' does not include 'op_id', we a running a legacy NBI version.
909 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100910 op_id = sdn_content.pop("op_id", None)
911 if not self.lcm_tasks.lock_HA("sdn", "edit", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200912 return
913
tierno59d22d22018-09-25 18:10:19 +0200914 sdn_id = sdn_content["_id"]
915 logging_text = "Task sdn_edit={} ".format(sdn_id)
916 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200917
tierno59d22d22018-09-25 18:10:19 +0200918 db_sdn = None
919 db_sdn_update = {}
920 exc = None
921 step = "Getting sdn from db"
922 try:
kuuse6a470c62019-07-10 13:52:45 +0200923 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +0100924 await self.lcm_tasks.waitfor_related_HA("sdn", "edit", op_id)
kuuse6a470c62019-07-10 13:52:45 +0200925
tierno59d22d22018-09-25 18:10:19 +0200926 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
tiernoe37b57d2018-12-11 17:22:51 +0000927 RO_sdn_id = None
garciadeblas5697b8b2021-03-24 09:17:02 +0100928 if (
929 db_sdn.get("_admin")
930 and db_sdn["_admin"].get("deployed")
931 and db_sdn["_admin"]["deployed"].get("RO")
932 ):
tierno59d22d22018-09-25 18:10:19 +0200933 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
934 RO = ROclient.ROClient(self.loop, **self.ro_config)
935 step = "Editing sdn at RO"
936 sdn_RO = deepcopy(sdn_content)
937 sdn_RO.pop("_id", None)
938 sdn_RO.pop("_admin", None)
tierno17a612f2018-10-23 11:30:42 +0200939 schema_version = sdn_RO.pop("schema_version", None)
tierno59d22d22018-09-25 18:10:19 +0200940 sdn_RO.pop("schema_type", None)
941 sdn_RO.pop("description", None)
tierno17a612f2018-10-23 11:30:42 +0200942 if sdn_RO.get("password"):
garciadeblas5697b8b2021-03-24 09:17:02 +0100943 sdn_RO["password"] = self.db.decrypt(
944 sdn_RO["password"], schema_version=schema_version, salt=sdn_id
945 )
tierno59d22d22018-09-25 18:10:19 +0200946 if sdn_RO:
947 await RO.edit("sdn", RO_sdn_id, descriptor=sdn_RO)
948 db_sdn_update["_admin.operationalState"] = "ENABLED"
kuuse6a470c62019-07-10 13:52:45 +0200949 # Mark the SDN 'edit' HA task as successful
garciadeblas5697b8b2021-03-24 09:17:02 +0100950 operation_state = "COMPLETED"
951 operation_details = "Done"
tierno59d22d22018-09-25 18:10:19 +0200952
tiernoe37b57d2018-12-11 17:22:51 +0000953 self.logger.debug(logging_text + "Exit Ok RO_sdn_id={}".format(RO_sdn_id))
tierno59d22d22018-09-25 18:10:19 +0200954 return
955
tiernocc29b592020-09-18 10:33:18 +0000956 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +0200957 self.logger.error(logging_text + "Exit Exception {}".format(e))
958 exc = e
959 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +0100960 self.logger.critical(
961 logging_text + "Exit Exception {}".format(e), exc_info=True
962 )
tierno59d22d22018-09-25 18:10:19 +0200963 exc = e
964 finally:
965 if exc and db_sdn:
966 db_sdn["_admin.operationalState"] = "ERROR"
967 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
kuuse6a470c62019-07-10 13:52:45 +0200968 # Mark the SDN 'edit' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +0100969 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +0000970 operation_details = "ERROR {}: {}".format(step, exc)
tiernobaa51102018-12-14 13:16:18 +0000971 try:
972 if db_sdn_update:
973 self.update_db_2("sdns", sdn_id, db_sdn_update)
kuuse6a470c62019-07-10 13:52:45 +0200974 # Register the SDN 'edit' HA task either
975 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +0100976 self.lcm_tasks.unlock_HA(
977 "sdn",
978 "edit",
979 op_id,
980 operationState=operation_state,
981 detailed_status=operation_details,
982 )
tiernobaa51102018-12-14 13:16:18 +0000983 except DbException as e:
984 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +0200985 self.lcm_tasks.remove("sdn", sdn_id, order_id)
986
kuuse6a470c62019-07-10 13:52:45 +0200987 async def delete(self, sdn_content, order_id):
kuuse6a470c62019-07-10 13:52:45 +0200988 # HA tasks and backward compatibility:
989 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
990 # In such a case, HA is not supported by NBI, and the HA check always returns True
garciadeblas5697b8b2021-03-24 09:17:02 +0100991 op_id = sdn_content.pop("op_id", None)
992 if not self.lcm_tasks.lock_HA("sdn", "delete", op_id):
kuuse6a470c62019-07-10 13:52:45 +0200993 return
994
995 sdn_id = sdn_content["_id"]
tierno59d22d22018-09-25 18:10:19 +0200996 logging_text = "Task sdn_delete={} ".format(sdn_id)
997 self.logger.debug(logging_text + "Enter")
kuuse6a470c62019-07-10 13:52:45 +0200998
tierno59d22d22018-09-25 18:10:19 +0200999 db_sdn = None
1000 db_sdn_update = {}
1001 exc = None
1002 step = "Getting sdn from db"
1003 try:
kuuse6a470c62019-07-10 13:52:45 +02001004 # wait for any previous tasks in process
garciadeblas5697b8b2021-03-24 09:17:02 +01001005 await self.lcm_tasks.waitfor_related_HA("sdn", "delete", op_id)
kuuse6a470c62019-07-10 13:52:45 +02001006
tierno59d22d22018-09-25 18:10:19 +02001007 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001008 if (
1009 db_sdn.get("_admin")
1010 and db_sdn["_admin"].get("deployed")
1011 and db_sdn["_admin"]["deployed"].get("RO")
1012 ):
tierno59d22d22018-09-25 18:10:19 +02001013 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
1014 RO = ROclient.ROClient(self.loop, **self.ro_config)
1015 step = "Deleting sdn from RO"
1016 try:
1017 await RO.delete("sdn", RO_sdn_id)
1018 except ROclient.ROClientException as e:
1019 if e.http_code == 404: # not found
garciadeblas5697b8b2021-03-24 09:17:02 +01001020 self.logger.debug(
1021 logging_text
1022 + "RO_sdn_id={} already deleted".format(RO_sdn_id)
1023 )
tierno59d22d22018-09-25 18:10:19 +02001024 else:
1025 raise
1026 else:
1027 # nothing to delete
garciadeblas5697b8b2021-03-24 09:17:02 +01001028 self.logger.error(
1029 logging_text + "Skipping. There is not RO information at database"
1030 )
tierno59d22d22018-09-25 18:10:19 +02001031 self.db.del_one("sdns", {"_id": sdn_id})
tiernobaa51102018-12-14 13:16:18 +00001032 db_sdn = None
tierno59d22d22018-09-25 18:10:19 +02001033 self.logger.debug("sdn_delete task sdn_id={} Exit Ok".format(sdn_id))
1034 return
1035
tiernocc29b592020-09-18 10:33:18 +00001036 except (ROclient.ROClientException, DbException, asyncio.CancelledError) as e:
tierno59d22d22018-09-25 18:10:19 +02001037 self.logger.error(logging_text + "Exit Exception {}".format(e))
1038 exc = e
1039 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001040 self.logger.critical(
1041 logging_text + "Exit Exception {}".format(e), exc_info=True
1042 )
tierno59d22d22018-09-25 18:10:19 +02001043 exc = e
1044 finally:
1045 if exc and db_sdn:
1046 db_sdn["_admin.operationalState"] = "ERROR"
1047 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
kuuse6a470c62019-07-10 13:52:45 +02001048 # Mark the SDN 'delete' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +01001049 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001050 operation_details = "ERROR {}: {}".format(step, exc)
garciadeblas5697b8b2021-03-24 09:17:02 +01001051 self.lcm_tasks.unlock_HA(
1052 "sdn",
1053 "delete",
1054 op_id,
1055 operationState=operation_state,
1056 detailed_status=operation_details,
1057 )
tiernobaa51102018-12-14 13:16:18 +00001058 try:
1059 if db_sdn and db_sdn_update:
1060 self.update_db_2("sdns", sdn_id, db_sdn_update)
kuuse6a470c62019-07-10 13:52:45 +02001061 # If the SDN 'delete' HA task was succesful, the DB entry has been deleted,
1062 # which means that there is nowhere to register this task, so do nothing here.
tiernobaa51102018-12-14 13:16:18 +00001063 except DbException as e:
1064 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno59d22d22018-09-25 18:10:19 +02001065 self.lcm_tasks.remove("sdn", sdn_id, order_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001066
1067
1068class K8sClusterLcm(LcmBase):
tierno0d7f9372020-09-30 07:56:29 +00001069 timeout_create = 300
calvinosanch9f9c6f22019-11-04 13:37:39 +01001070
bravof922c4172020-11-24 21:21:43 -03001071 def __init__(self, msg, lcm_tasks, config, loop):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001072 """
1073 Init, Connect to database, filesystem storage, and messaging
1074 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
1075 :return: None
1076 """
1077
garciadeblas5697b8b2021-03-24 09:17:02 +01001078 self.logger = logging.getLogger("lcm.k8scluster")
calvinosanch9f9c6f22019-11-04 13:37:39 +01001079 self.loop = loop
1080 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +00001081 self.vca_config = config["VCA"]
bravof922c4172020-11-24 21:21:43 -03001082
1083 super().__init__(msg, self.logger)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001084
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001085 self.helm2_k8scluster = K8sHelmConnector(
calvinosanch9f9c6f22019-11-04 13:37:39 +01001086 kubectl_command=self.vca_config.get("kubectlpath"),
1087 helm_command=self.vca_config.get("helmpath"),
calvinosanch9f9c6f22019-11-04 13:37:39 +01001088 log=self.logger,
bravof922c4172020-11-24 21:21:43 -03001089 on_update_db=None,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001090 db=self.db,
garciadeblas5697b8b2021-03-24 09:17:02 +01001091 fs=self.fs,
calvinosanch9f9c6f22019-11-04 13:37:39 +01001092 )
1093
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001094 self.helm3_k8scluster = K8sHelm3Connector(
1095 kubectl_command=self.vca_config.get("kubectlpath"),
1096 helm_command=self.vca_config.get("helm3path"),
1097 fs=self.fs,
1098 log=self.logger,
1099 db=self.db,
garciadeblas5697b8b2021-03-24 09:17:02 +01001100 on_update_db=None,
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001101 )
1102
Adam Israelbaacc302019-12-01 12:41:39 -05001103 self.juju_k8scluster = K8sJujuConnector(
1104 kubectl_command=self.vca_config.get("kubectlpath"),
1105 juju_command=self.vca_config.get("jujupath"),
Adam Israelbaacc302019-12-01 12:41:39 -05001106 log=self.logger,
David Garciaba89cbb2020-10-16 13:05:34 +02001107 loop=self.loop,
1108 on_update_db=None,
bravof922c4172020-11-24 21:21:43 -03001109 db=self.db,
garciadeblas5697b8b2021-03-24 09:17:02 +01001110 fs=self.fs,
Adam Israelbaacc302019-12-01 12:41:39 -05001111 )
bravof922c4172020-11-24 21:21:43 -03001112
tiernofa076c32020-08-13 14:25:47 +00001113 self.k8s_map = {
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001114 "helm-chart": self.helm2_k8scluster,
1115 "helm-chart-v3": self.helm3_k8scluster,
tiernofa076c32020-08-13 14:25:47 +00001116 "juju-bundle": self.juju_k8scluster,
1117 }
Adam Israelbaacc302019-12-01 12:41:39 -05001118
calvinosanch9f9c6f22019-11-04 13:37:39 +01001119 async def create(self, k8scluster_content, order_id):
garciadeblas5697b8b2021-03-24 09:17:02 +01001120 op_id = k8scluster_content.pop("op_id", None)
1121 if not self.lcm_tasks.lock_HA("k8scluster", "create", op_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001122 return
1123
1124 k8scluster_id = k8scluster_content["_id"]
calvinosanch9f9c6f22019-11-04 13:37:39 +01001125 logging_text = "Task k8scluster_create={} ".format(k8scluster_id)
1126 self.logger.debug(logging_text + "Enter")
1127
1128 db_k8scluster = None
1129 db_k8scluster_update = {}
calvinosanch9f9c6f22019-11-04 13:37:39 +01001130 exc = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001131 try:
1132 step = "Getting k8scluster-id='{}' from db".format(k8scluster_id)
1133 self.logger.debug(logging_text + step)
1134 db_k8scluster = self.db.get_one("k8sclusters", {"_id": k8scluster_id})
garciadeblas5697b8b2021-03-24 09:17:02 +01001135 self.db.encrypt_decrypt_fields(
1136 db_k8scluster.get("credentials"),
1137 "decrypt",
1138 ["password", "secret"],
1139 schema_version=db_k8scluster["schema_version"],
1140 salt=db_k8scluster["_id"],
1141 )
tiernoe19bd742019-12-05 16:09:08 +00001142 k8s_credentials = yaml.safe_dump(db_k8scluster.get("credentials"))
tiernofa076c32020-08-13 14:25:47 +00001143 pending_tasks = []
1144 task2name = {}
tierno78e3ec62020-07-14 10:46:57 +00001145 init_target = deep_get(db_k8scluster, ("_admin", "init"))
tiernofa076c32020-08-13 14:25:47 +00001146 step = "Launching k8scluster init tasks"
Gabriel Cuba1b2b8402022-03-22 11:12:12 -05001147
1148 k8s_deploy_methods = db_k8scluster.get("deployment_methods", {})
1149 # for backwards compatibility and all-false case
1150 if not any(k8s_deploy_methods.values()):
preethika.p28b0bf82022-09-23 07:36:28 +00001151 k8s_deploy_methods = {
1152 "helm-chart": True,
1153 "juju-bundle": True,
1154 "helm-chart-v3": True,
1155 }
Gabriel Cuba1b2b8402022-03-22 11:12:12 -05001156 deploy_methods = tuple(filter(k8s_deploy_methods.get, k8s_deploy_methods))
1157
1158 for task_name in deploy_methods:
tiernofa076c32020-08-13 14:25:47 +00001159 if init_target and task_name not in init_target:
1160 continue
David Garciac1fe90a2021-03-31 19:12:02 +02001161 task = asyncio.ensure_future(
1162 self.k8s_map[task_name].init_env(
1163 k8s_credentials,
1164 reuse_cluster_uuid=k8scluster_id,
1165 vca_id=db_k8scluster.get("vca_id"),
1166 )
1167 )
tiernofa076c32020-08-13 14:25:47 +00001168 pending_tasks.append(task)
1169 task2name[task] = task_name
Adam Israelbaacc302019-12-01 12:41:39 -05001170
tiernofa076c32020-08-13 14:25:47 +00001171 error_text_list = []
1172 tasks_name_ok = []
1173 reached_timeout = False
1174 now = time()
Adam Israelbaacc302019-12-01 12:41:39 -05001175
tiernofa076c32020-08-13 14:25:47 +00001176 while pending_tasks:
garciadeblas5697b8b2021-03-24 09:17:02 +01001177 _timeout = max(
1178 1, self.timeout_create - (time() - now)
1179 ) # ensure not negative with max
tiernofa076c32020-08-13 14:25:47 +00001180 step = "Waiting for k8scluster init tasks"
garciadeblas5697b8b2021-03-24 09:17:02 +01001181 done, pending_tasks = await asyncio.wait(
1182 pending_tasks, timeout=_timeout, return_when=asyncio.FIRST_COMPLETED
1183 )
tiernofa076c32020-08-13 14:25:47 +00001184 if not done:
1185 # timeout. Set timeout is reached and process pending as if they hase been finished
1186 done = pending_tasks
1187 pending_tasks = None
1188 reached_timeout = True
1189 for task in done:
1190 task_name = task2name[task]
1191 if reached_timeout:
1192 exc = "Timeout"
1193 elif task.cancelled():
1194 exc = "Cancelled"
1195 else:
1196 exc = task.exception()
1197
1198 if exc:
garciadeblas5697b8b2021-03-24 09:17:02 +01001199 error_text_list.append(
1200 "Failing init {}: {}".format(task_name, exc)
1201 )
1202 db_k8scluster_update[
1203 "_admin.{}.error_msg".format(task_name)
1204 ] = str(exc)
tiernofa076c32020-08-13 14:25:47 +00001205 db_k8scluster_update["_admin.{}.id".format(task_name)] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001206 db_k8scluster_update[
1207 "_admin.{}.operationalState".format(task_name)
1208 ] = "ERROR"
1209 self.logger.error(
1210 logging_text + "{} init fail: {}".format(task_name, exc),
1211 exc_info=not isinstance(exc, (N2VCException, str)),
1212 )
tiernofa076c32020-08-13 14:25:47 +00001213 else:
1214 k8s_id, uninstall_sw = task.result()
1215 tasks_name_ok.append(task_name)
garciadeblas5697b8b2021-03-24 09:17:02 +01001216 self.logger.debug(
1217 logging_text
1218 + "{} init success. id={} created={}".format(
1219 task_name, k8s_id, uninstall_sw
1220 )
1221 )
1222 db_k8scluster_update[
1223 "_admin.{}.error_msg".format(task_name)
1224 ] = None
tiernofa076c32020-08-13 14:25:47 +00001225 db_k8scluster_update["_admin.{}.id".format(task_name)] = k8s_id
garciadeblas5697b8b2021-03-24 09:17:02 +01001226 db_k8scluster_update[
1227 "_admin.{}.created".format(task_name)
1228 ] = uninstall_sw
1229 db_k8scluster_update[
1230 "_admin.{}.operationalState".format(task_name)
1231 ] = "ENABLED"
tiernofa076c32020-08-13 14:25:47 +00001232 # update database
1233 step = "Updating database for " + task_name
1234 self.update_db_2("k8sclusters", k8scluster_id, db_k8scluster_update)
tiernocc29b592020-09-18 10:33:18 +00001235 if tasks_name_ok:
1236 operation_details = "ready for " + ", ".join(tasks_name_ok)
1237 operation_state = "COMPLETED"
garciadeblas5697b8b2021-03-24 09:17:02 +01001238 db_k8scluster_update["_admin.operationalState"] = (
1239 "ENABLED" if not error_text_list else "DEGRADED"
1240 )
tiernocc29b592020-09-18 10:33:18 +00001241 operation_details += "; " + ";".join(error_text_list)
1242 else:
tiernoe19bd742019-12-05 16:09:08 +00001243 db_k8scluster_update["_admin.operationalState"] = "ERROR"
tiernofa076c32020-08-13 14:25:47 +00001244 operation_state = "FAILED"
tiernocc29b592020-09-18 10:33:18 +00001245 operation_details = ";".join(error_text_list)
1246 db_k8scluster_update["_admin.detailed-status"] = operation_details
tiernofa076c32020-08-13 14:25:47 +00001247 self.logger.debug(logging_text + "Done. Result: " + operation_state)
1248 exc = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001249
1250 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001251 if isinstance(
1252 e,
1253 (
1254 LcmException,
1255 DbException,
1256 K8sException,
1257 N2VCException,
1258 asyncio.CancelledError,
1259 ),
1260 ):
tiernocc29b592020-09-18 10:33:18 +00001261 self.logger.error(logging_text + "Exit Exception {}".format(e))
1262 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001263 self.logger.critical(
1264 logging_text + "Exit Exception {}".format(e), exc_info=True
1265 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001266 exc = e
1267 finally:
1268 if exc and db_k8scluster:
1269 db_k8scluster_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +01001270 db_k8scluster_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1271 step, exc
1272 )
1273 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001274 operation_details = "ERROR {}: {}".format(step, exc)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001275 try:
tiernofa076c32020-08-13 14:25:47 +00001276 if db_k8scluster and db_k8scluster_update:
calvinosanch9f9c6f22019-11-04 13:37:39 +01001277 self.update_db_2("k8sclusters", k8scluster_id, db_k8scluster_update)
Adam Israelbaacc302019-12-01 12:41:39 -05001278
tiernofa076c32020-08-13 14:25:47 +00001279 # Register the operation and unlock
garciadeblas5697b8b2021-03-24 09:17:02 +01001280 self.lcm_tasks.unlock_HA(
1281 "k8scluster",
1282 "create",
1283 op_id,
1284 operationState=operation_state,
1285 detailed_status=operation_details,
1286 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001287 except DbException as e:
1288 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno0fedb032020-03-12 17:19:06 +00001289 self.lcm_tasks.remove("k8scluster", k8scluster_id, order_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001290
1291 async def delete(self, k8scluster_content, order_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001292 # HA tasks and backward compatibility:
1293 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
1294 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
1295 # Register 'delete' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +01001296 op_id = k8scluster_content.pop("op_id", None)
1297 if not self.lcm_tasks.lock_HA("k8scluster", "delete", op_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001298 return
1299
1300 k8scluster_id = k8scluster_content["_id"]
calvinosanch9f9c6f22019-11-04 13:37:39 +01001301 logging_text = "Task k8scluster_delete={} ".format(k8scluster_id)
1302 self.logger.debug(logging_text + "Enter")
1303
1304 db_k8scluster = None
1305 db_k8scluster_update = {}
1306 exc = None
calvinosanch9f9c6f22019-11-04 13:37:39 +01001307 try:
1308 step = "Getting k8scluster='{}' from db".format(k8scluster_id)
1309 self.logger.debug(logging_text + step)
1310 db_k8scluster = self.db.get_one("k8sclusters", {"_id": k8scluster_id})
tierno626e0152019-11-29 14:16:16 +00001311 k8s_hc_id = deep_get(db_k8scluster, ("_admin", "helm-chart", "id"))
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001312 k8s_h3c_id = deep_get(db_k8scluster, ("_admin", "helm-chart-v3", "id"))
Adam Israelbaacc302019-12-01 12:41:39 -05001313 k8s_jb_id = deep_get(db_k8scluster, ("_admin", "juju-bundle", "id"))
1314
tierno626e0152019-11-29 14:16:16 +00001315 cluster_removed = True
tierno78e3ec62020-07-14 10:46:57 +00001316 if k8s_jb_id: # delete in reverse order of creation
1317 step = "Removing juju-bundle '{}'".format(k8s_jb_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01001318 uninstall_sw = (
1319 deep_get(db_k8scluster, ("_admin", "juju-bundle", "created"))
1320 or False
1321 )
David Garciac1fe90a2021-03-31 19:12:02 +02001322 cluster_removed = await self.juju_k8scluster.reset(
1323 cluster_uuid=k8s_jb_id,
1324 uninstall_sw=uninstall_sw,
1325 vca_id=db_k8scluster.get("vca_id"),
1326 )
tierno78e3ec62020-07-14 10:46:57 +00001327 db_k8scluster_update["_admin.juju-bundle.id"] = None
tiernocc29b592020-09-18 10:33:18 +00001328 db_k8scluster_update["_admin.juju-bundle.operationalState"] = "DISABLED"
tierno78e3ec62020-07-14 10:46:57 +00001329
tierno626e0152019-11-29 14:16:16 +00001330 if k8s_hc_id:
tiernod58995a2020-05-20 14:35:19 +00001331 step = "Removing helm-chart '{}'".format(k8s_hc_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01001332 uninstall_sw = (
1333 deep_get(db_k8scluster, ("_admin", "helm-chart", "created"))
1334 or False
1335 )
1336 cluster_removed = await self.helm2_k8scluster.reset(
1337 cluster_uuid=k8s_hc_id, uninstall_sw=uninstall_sw
1338 )
tiernod58995a2020-05-20 14:35:19 +00001339 db_k8scluster_update["_admin.helm-chart.id"] = None
tiernocc29b592020-09-18 10:33:18 +00001340 db_k8scluster_update["_admin.helm-chart.operationalState"] = "DISABLED"
Adam Israelbaacc302019-12-01 12:41:39 -05001341
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001342 if k8s_h3c_id:
1343 step = "Removing helm-chart-v3 '{}'".format(k8s_hc_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01001344 uninstall_sw = (
1345 deep_get(db_k8scluster, ("_admin", "helm-chart-v3", "created"))
1346 or False
1347 )
1348 cluster_removed = await self.helm3_k8scluster.reset(
1349 cluster_uuid=k8s_h3c_id, uninstall_sw=uninstall_sw
1350 )
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001351 db_k8scluster_update["_admin.helm-chart-v3.id"] = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001352 db_k8scluster_update[
1353 "_admin.helm-chart-v3.operationalState"
1354 ] = "DISABLED"
lloretgalleg18ebc3a2020-10-22 09:54:51 +00001355
lloretgallegedc5f332020-02-20 11:50:50 +01001356 # Try to remove from cluster_inserted to clean old versions
tiernoe19bd742019-12-05 16:09:08 +00001357 if k8s_hc_id and cluster_removed:
1358 step = "Removing k8scluster='{}' from k8srepos".format(k8scluster_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001359 self.logger.debug(logging_text + step)
garciadeblas5697b8b2021-03-24 09:17:02 +01001360 db_k8srepo_list = self.db.get_list(
1361 "k8srepos", {"_admin.cluster-inserted": k8s_hc_id}
1362 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001363 for k8srepo in db_k8srepo_list:
tiernoe19bd742019-12-05 16:09:08 +00001364 try:
1365 cluster_list = k8srepo["_admin"]["cluster-inserted"]
1366 cluster_list.remove(k8s_hc_id)
garciadeblas5697b8b2021-03-24 09:17:02 +01001367 self.update_db_2(
1368 "k8srepos",
1369 k8srepo["_id"],
1370 {"_admin.cluster-inserted": cluster_list},
1371 )
tiernoe19bd742019-12-05 16:09:08 +00001372 except Exception as e:
1373 self.logger.error("{}: {}".format(step, e))
tiernod58995a2020-05-20 14:35:19 +00001374 self.db.del_one("k8sclusters", {"_id": k8scluster_id})
tierno78e3ec62020-07-14 10:46:57 +00001375 db_k8scluster_update = None
1376 self.logger.debug(logging_text + "Done")
calvinosanch9f9c6f22019-11-04 13:37:39 +01001377
1378 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001379 if isinstance(
1380 e,
1381 (
1382 LcmException,
1383 DbException,
1384 K8sException,
1385 N2VCException,
1386 asyncio.CancelledError,
1387 ),
1388 ):
tierno0fedb032020-03-12 17:19:06 +00001389 self.logger.error(logging_text + "Exit Exception {}".format(e))
1390 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001391 self.logger.critical(
1392 logging_text + "Exit Exception {}".format(e), exc_info=True
1393 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001394 exc = e
1395 finally:
1396 if exc and db_k8scluster:
1397 db_k8scluster_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +01001398 db_k8scluster_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1399 step, exc
1400 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001401 # Mark the WIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +01001402 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001403 operation_details = "ERROR {}: {}".format(step, exc)
1404 else:
garciadeblas5697b8b2021-03-24 09:17:02 +01001405 operation_state = "COMPLETED"
tiernofa076c32020-08-13 14:25:47 +00001406 operation_details = "deleted"
1407
calvinosanch9f9c6f22019-11-04 13:37:39 +01001408 try:
1409 if db_k8scluster_update:
1410 self.update_db_2("k8sclusters", k8scluster_id, db_k8scluster_update)
1411 # Register the K8scluster 'delete' HA task either
1412 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +01001413 self.lcm_tasks.unlock_HA(
1414 "k8scluster",
1415 "delete",
1416 op_id,
1417 operationState=operation_state,
1418 detailed_status=operation_details,
1419 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001420 except DbException as e:
1421 self.logger.error(logging_text + "Cannot update database: {}".format(e))
tierno0fedb032020-03-12 17:19:06 +00001422 self.lcm_tasks.remove("k8scluster", k8scluster_id, order_id)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001423
1424
David Garciac1fe90a2021-03-31 19:12:02 +02001425class VcaLcm(LcmBase):
1426 timeout_create = 30
1427
1428 def __init__(self, msg, lcm_tasks, config, loop):
1429 """
1430 Init, Connect to database, filesystem storage, and messaging
1431 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
1432 :return: None
1433 """
1434
1435 self.logger = logging.getLogger("lcm.vca")
1436 self.loop = loop
1437 self.lcm_tasks = lcm_tasks
1438
1439 super().__init__(msg, self.logger)
1440
1441 # create N2VC connector
1442 self.n2vc = N2VCJujuConnector(
garciadeblas5697b8b2021-03-24 09:17:02 +01001443 log=self.logger, loop=self.loop, fs=self.fs, db=self.db
David Garciac1fe90a2021-03-31 19:12:02 +02001444 )
1445
1446 def _get_vca_by_id(self, vca_id: str) -> dict:
1447 db_vca = self.db.get_one("vca", {"_id": vca_id})
1448 self.db.encrypt_decrypt_fields(
1449 db_vca,
1450 "decrypt",
1451 ["secret", "cacert"],
garciadeblas5697b8b2021-03-24 09:17:02 +01001452 schema_version=db_vca["schema_version"],
1453 salt=db_vca["_id"],
David Garciac1fe90a2021-03-31 19:12:02 +02001454 )
1455 return db_vca
1456
1457 async def create(self, vca_content, order_id):
1458 op_id = vca_content.pop("op_id", None)
1459 if not self.lcm_tasks.lock_HA("vca", "create", op_id):
1460 return
1461
1462 vca_id = vca_content["_id"]
1463 self.logger.debug("Task vca_create={} {}".format(vca_id, "Enter"))
1464
1465 db_vca = None
1466 db_vca_update = {}
1467
1468 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01001469 self.logger.debug(
1470 "Task vca_create={} {}".format(vca_id, "Getting vca from db")
1471 )
David Garciac1fe90a2021-03-31 19:12:02 +02001472 db_vca = self._get_vca_by_id(vca_id)
1473
1474 task = asyncio.ensure_future(
1475 asyncio.wait_for(
1476 self.n2vc.validate_vca(db_vca["_id"]),
1477 timeout=self.timeout_create,
1478 )
1479 )
1480
1481 await asyncio.wait([task], return_when=asyncio.FIRST_COMPLETED)
1482 if task.exception():
1483 raise task.exception()
garciadeblas5697b8b2021-03-24 09:17:02 +01001484 self.logger.debug(
1485 "Task vca_create={} {}".format(
1486 vca_id, "vca registered and validated successfully"
1487 )
1488 )
David Garciac1fe90a2021-03-31 19:12:02 +02001489 db_vca_update["_admin.operationalState"] = "ENABLED"
1490 db_vca_update["_admin.detailed-status"] = "Connectivity: ok"
1491 operation_details = "VCA validated"
1492 operation_state = "COMPLETED"
1493
garciadeblas5697b8b2021-03-24 09:17:02 +01001494 self.logger.debug(
1495 "Task vca_create={} {}".format(
1496 vca_id, "Done. Result: {}".format(operation_state)
1497 )
1498 )
David Garciac1fe90a2021-03-31 19:12:02 +02001499
1500 except Exception as e:
1501 error_msg = "Failed with exception: {}".format(e)
1502 self.logger.error("Task vca_create={} {}".format(vca_id, error_msg))
1503 db_vca_update["_admin.operationalState"] = "ERROR"
1504 db_vca_update["_admin.detailed-status"] = error_msg
1505 operation_state = "FAILED"
1506 operation_details = error_msg
1507 finally:
1508 try:
1509 self.update_db_2("vca", vca_id, db_vca_update)
1510
1511 # Register the operation and unlock
1512 self.lcm_tasks.unlock_HA(
1513 "vca",
1514 "create",
1515 op_id,
1516 operationState=operation_state,
garciadeblas5697b8b2021-03-24 09:17:02 +01001517 detailed_status=operation_details,
David Garciac1fe90a2021-03-31 19:12:02 +02001518 )
1519 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001520 self.logger.error(
1521 "Task vca_create={} {}".format(
1522 vca_id, "Cannot update database: {}".format(e)
1523 )
1524 )
David Garciac1fe90a2021-03-31 19:12:02 +02001525 self.lcm_tasks.remove("vca", vca_id, order_id)
1526
1527 async def delete(self, vca_content, order_id):
David Garciac1fe90a2021-03-31 19:12:02 +02001528 # HA tasks and backward compatibility:
1529 # If "vim_content" does not include "op_id", we a running a legacy NBI version.
1530 # In such a case, HA is not supported by NBI, "op_id" is None, and lock_HA() will do nothing.
1531 # Register "delete" task here for related future HA operations
1532 op_id = vca_content.pop("op_id", None)
1533 if not self.lcm_tasks.lock_HA("vca", "delete", op_id):
1534 return
1535
1536 db_vca_update = {}
1537 vca_id = vca_content["_id"]
1538
1539 try:
garciadeblas5697b8b2021-03-24 09:17:02 +01001540 self.logger.debug(
1541 "Task vca_delete={} {}".format(vca_id, "Deleting vca from db")
1542 )
David Garciac1fe90a2021-03-31 19:12:02 +02001543 self.db.del_one("vca", {"_id": vca_id})
1544 db_vca_update = None
1545 operation_details = "deleted"
1546 operation_state = "COMPLETED"
1547
garciadeblas5697b8b2021-03-24 09:17:02 +01001548 self.logger.debug(
1549 "Task vca_delete={} {}".format(
1550 vca_id, "Done. Result: {}".format(operation_state)
1551 )
1552 )
David Garciac1fe90a2021-03-31 19:12:02 +02001553 except Exception as e:
1554 error_msg = "Failed with exception: {}".format(e)
1555 self.logger.error("Task vca_delete={} {}".format(vca_id, error_msg))
1556 db_vca_update["_admin.operationalState"] = "ERROR"
1557 db_vca_update["_admin.detailed-status"] = error_msg
1558 operation_state = "FAILED"
1559 operation_details = error_msg
1560 finally:
1561 try:
1562 self.update_db_2("vca", vca_id, db_vca_update)
1563 self.lcm_tasks.unlock_HA(
1564 "vca",
1565 "delete",
1566 op_id,
1567 operationState=operation_state,
1568 detailed_status=operation_details,
1569 )
1570 except DbException as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001571 self.logger.error(
1572 "Task vca_delete={} {}".format(
1573 vca_id, "Cannot update database: {}".format(e)
1574 )
1575 )
David Garciac1fe90a2021-03-31 19:12:02 +02001576 self.lcm_tasks.remove("vca", vca_id, order_id)
1577
1578
calvinosanch9f9c6f22019-11-04 13:37:39 +01001579class K8sRepoLcm(LcmBase):
bravof922c4172020-11-24 21:21:43 -03001580 def __init__(self, msg, lcm_tasks, config, loop):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001581 """
1582 Init, Connect to database, filesystem storage, and messaging
1583 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
1584 :return: None
1585 """
1586
garciadeblas5697b8b2021-03-24 09:17:02 +01001587 self.logger = logging.getLogger("lcm.k8srepo")
calvinosanch9f9c6f22019-11-04 13:37:39 +01001588 self.loop = loop
1589 self.lcm_tasks = lcm_tasks
tierno744303e2020-01-13 16:46:31 +00001590 self.vca_config = config["VCA"]
calvinosanch9f9c6f22019-11-04 13:37:39 +01001591
bravof922c4172020-11-24 21:21:43 -03001592 super().__init__(msg, self.logger)
1593
1594 self.k8srepo = K8sHelmConnector(
1595 kubectl_command=self.vca_config.get("kubectlpath"),
1596 helm_command=self.vca_config.get("helmpath"),
1597 fs=self.fs,
1598 log=self.logger,
1599 db=self.db,
garciadeblas5697b8b2021-03-24 09:17:02 +01001600 on_update_db=None,
bravof922c4172020-11-24 21:21:43 -03001601 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001602
1603 async def create(self, k8srepo_content, order_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001604 # HA tasks and backward compatibility:
1605 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
1606 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
1607 # Register 'create' task here for related future HA operations
1608
garciadeblas5697b8b2021-03-24 09:17:02 +01001609 op_id = k8srepo_content.pop("op_id", None)
1610 if not self.lcm_tasks.lock_HA("k8srepo", "create", op_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001611 return
1612
1613 k8srepo_id = k8srepo_content.get("_id")
1614 logging_text = "Task k8srepo_create={} ".format(k8srepo_id)
1615 self.logger.debug(logging_text + "Enter")
1616
1617 db_k8srepo = None
1618 db_k8srepo_update = {}
1619 exc = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001620 operation_state = "COMPLETED"
1621 operation_details = ""
calvinosanch9f9c6f22019-11-04 13:37:39 +01001622 try:
1623 step = "Getting k8srepo-id='{}' from db".format(k8srepo_id)
1624 self.logger.debug(logging_text + step)
1625 db_k8srepo = self.db.get_one("k8srepos", {"_id": k8srepo_id})
calvinosanch9f9c6f22019-11-04 13:37:39 +01001626 db_k8srepo_update["_admin.operationalState"] = "ENABLED"
1627 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001628 self.logger.error(
1629 logging_text + "Exit Exception {}".format(e),
1630 exc_info=not isinstance(
1631 e,
1632 (
1633 LcmException,
1634 DbException,
1635 K8sException,
1636 N2VCException,
1637 asyncio.CancelledError,
1638 ),
1639 ),
1640 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001641 exc = e
1642 finally:
1643 if exc and db_k8srepo:
1644 db_k8srepo_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +01001645 db_k8srepo_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1646 step, exc
1647 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001648 # Mark the WIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +01001649 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001650 operation_details = "ERROR {}: {}".format(step, exc)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001651 try:
1652 if db_k8srepo_update:
1653 self.update_db_2("k8srepos", k8srepo_id, db_k8srepo_update)
1654 # Register the K8srepo 'create' HA task either
1655 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +01001656 self.lcm_tasks.unlock_HA(
1657 "k8srepo",
1658 "create",
1659 op_id,
1660 operationState=operation_state,
1661 detailed_status=operation_details,
1662 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001663 except DbException as e:
1664 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1665 self.lcm_tasks.remove("k8srepo", k8srepo_id, order_id)
1666
1667 async def delete(self, k8srepo_content, order_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001668 # HA tasks and backward compatibility:
1669 # If 'vim_content' does not include 'op_id', we a running a legacy NBI version.
1670 # In such a case, HA is not supported by NBI, 'op_id' is None, and lock_HA() will do nothing.
1671 # Register 'delete' task here for related future HA operations
garciadeblas5697b8b2021-03-24 09:17:02 +01001672 op_id = k8srepo_content.pop("op_id", None)
1673 if not self.lcm_tasks.lock_HA("k8srepo", "delete", op_id):
calvinosanch9f9c6f22019-11-04 13:37:39 +01001674 return
1675
1676 k8srepo_id = k8srepo_content.get("_id")
1677 logging_text = "Task k8srepo_delete={} ".format(k8srepo_id)
1678 self.logger.debug(logging_text + "Enter")
1679
1680 db_k8srepo = None
1681 db_k8srepo_update = {}
1682
tierno28c63da2020-04-20 16:28:56 +00001683 exc = None
garciadeblas5697b8b2021-03-24 09:17:02 +01001684 operation_state = "COMPLETED"
1685 operation_details = ""
calvinosanch9f9c6f22019-11-04 13:37:39 +01001686 try:
1687 step = "Getting k8srepo-id='{}' from db".format(k8srepo_id)
1688 self.logger.debug(logging_text + step)
1689 db_k8srepo = self.db.get_one("k8srepos", {"_id": k8srepo_id})
calvinosanch9f9c6f22019-11-04 13:37:39 +01001690
1691 except Exception as e:
garciadeblas5697b8b2021-03-24 09:17:02 +01001692 self.logger.error(
1693 logging_text + "Exit Exception {}".format(e),
1694 exc_info=not isinstance(
1695 e,
1696 (
1697 LcmException,
1698 DbException,
1699 K8sException,
1700 N2VCException,
1701 asyncio.CancelledError,
1702 ),
1703 ),
1704 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001705 exc = e
1706 finally:
1707 if exc and db_k8srepo:
1708 db_k8srepo_update["_admin.operationalState"] = "ERROR"
garciadeblas5697b8b2021-03-24 09:17:02 +01001709 db_k8srepo_update["_admin.detailed-status"] = "ERROR {}: {}".format(
1710 step, exc
1711 )
calvinosanch9f9c6f22019-11-04 13:37:39 +01001712 # Mark the WIM 'create' HA task as erroneous
garciadeblas5697b8b2021-03-24 09:17:02 +01001713 operation_state = "FAILED"
tiernofa076c32020-08-13 14:25:47 +00001714 operation_details = "ERROR {}: {}".format(step, exc)
calvinosanch9f9c6f22019-11-04 13:37:39 +01001715 try:
1716 if db_k8srepo_update:
1717 self.update_db_2("k8srepos", k8srepo_id, db_k8srepo_update)
1718 # Register the K8srepo 'delete' HA task either
1719 # succesful or erroneous, or do nothing (if legacy NBI)
garciadeblas5697b8b2021-03-24 09:17:02 +01001720 self.lcm_tasks.unlock_HA(
1721 "k8srepo",
1722 "delete",
1723 op_id,
1724 operationState=operation_state,
1725 detailed_status=operation_details,
1726 )
tierno28c63da2020-04-20 16:28:56 +00001727 self.db.del_one("k8srepos", {"_id": k8srepo_id})
calvinosanch9f9c6f22019-11-04 13:37:39 +01001728 except DbException as e:
1729 self.logger.error(logging_text + "Cannot update database: {}".format(e))
1730 self.lcm_tasks.remove("k8srepo", k8srepo_id, order_id)