blob: cfd36ec0dc4b11e35c935ecc13a1dc49b44dc2cc [file] [log] [blame]
tierno1d213f42020-04-24 14:02:51 +00001# -*- coding: utf-8 -*-
2
3##
4# Copyright 2020 Telefonica Investigacion y Desarrollo, S.A.U.
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License. You may obtain
8# a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15# License for the specific language governing permissions and limitations
16# under the License.
17#
18##
19
20""""
21This is thread that interacts with a VIM. It processes TASKs sequentially against a single VIM.
22The tasks are stored at database in table ro_tasks
23A single ro_task refers to a VIM element (flavor, image, network, ...).
24A ro_task can contain several 'tasks', each one with a target, where to store the results
25"""
26
sousaedu80135b92021-02-17 15:05:18 +010027from copy import deepcopy
28from http import HTTPStatus
sousaedu049cbb12022-01-05 11:39:35 +000029import logging
sousaedu80135b92021-02-17 15:05:18 +010030from os import mkdir
sousaedu049cbb12022-01-05 11:39:35 +000031import queue
sousaedu80135b92021-02-17 15:05:18 +010032from shutil import rmtree
sousaedu049cbb12022-01-05 11:39:35 +000033import threading
34import time
aticige5d78422022-05-16 23:03:54 +030035import traceback
sousaedu80135b92021-02-17 15:05:18 +010036from unittest.mock import Mock
37
sousaedu049cbb12022-01-05 11:39:35 +000038from importlib_metadata import entry_points
tierno1d213f42020-04-24 14:02:51 +000039from osm_common.dbbase import DbException
tiernof1b640f2020-12-09 15:06:01 +000040from osm_ng_ro.vim_admin import LockRenew
sousaedu049cbb12022-01-05 11:39:35 +000041from osm_ro_plugin import sdnconn, vimconn
42from osm_ro_plugin.sdn_dummy import SdnDummyConnector
43from osm_ro_plugin.vim_dummy import VimDummyConnector
44import yaml
tierno1d213f42020-04-24 14:02:51 +000045
46__author__ = "Alfonso Tierno"
47__date__ = "$28-Sep-2017 12:07:15$"
48
49
50def deep_get(target_dict, *args, **kwargs):
51 """
52 Get a value from target_dict entering in the nested keys. If keys does not exist, it returns None
53 Example target_dict={a: {b: 5}}; key_list=[a,b] returns 5; both key_list=[a,b,c] and key_list=[f,h] return None
54 :param target_dict: dictionary to be read
55 :param args: list of keys to read from target_dict
56 :param kwargs: only can contain default=value to return if key is not present in the nested dictionary
57 :return: The wanted value if exist, None or default otherwise
58 """
59 for key in args:
60 if not isinstance(target_dict, dict) or key not in target_dict:
61 return kwargs.get("default")
62 target_dict = target_dict[key]
63 return target_dict
64
65
66class NsWorkerException(Exception):
67 pass
68
69
70class FailingConnector:
71 def __init__(self, error_msg):
72 self.error_msg = error_msg
sousaedu80135b92021-02-17 15:05:18 +010073
tierno1d213f42020-04-24 14:02:51 +000074 for method in dir(vimconn.VimConnector):
75 if method[0] != "_":
sousaedu80135b92021-02-17 15:05:18 +010076 setattr(
77 self, method, Mock(side_effect=vimconn.VimConnException(error_msg))
78 )
79
tierno70eeb182020-10-19 16:38:00 +000080 for method in dir(sdnconn.SdnConnectorBase):
81 if method[0] != "_":
sousaedu80135b92021-02-17 15:05:18 +010082 setattr(
83 self, method, Mock(side_effect=sdnconn.SdnConnectorError(error_msg))
84 )
tierno1d213f42020-04-24 14:02:51 +000085
86
87class NsWorkerExceptionNotFound(NsWorkerException):
88 pass
89
90
tierno70eeb182020-10-19 16:38:00 +000091class VimInteractionBase:
sousaedu80135b92021-02-17 15:05:18 +010092 """Base class to call VIM/SDN for creating, deleting and refresh networks, VMs, flavors, ...
tierno70eeb182020-10-19 16:38:00 +000093 It implements methods that does nothing and return ok"""
sousaedu80135b92021-02-17 15:05:18 +010094
tierno70eeb182020-10-19 16:38:00 +000095 def __init__(self, db, my_vims, db_vims, logger):
tierno1d213f42020-04-24 14:02:51 +000096 self.db = db
tierno70eeb182020-10-19 16:38:00 +000097 self.logger = logger
98 self.my_vims = my_vims
99 self.db_vims = db_vims
tierno1d213f42020-04-24 14:02:51 +0000100
tierno70eeb182020-10-19 16:38:00 +0000101 def new(self, ro_task, task_index, task_depends):
102 return "BUILD", {}
tierno1d213f42020-04-24 14:02:51 +0000103
tierno70eeb182020-10-19 16:38:00 +0000104 def refresh(self, ro_task):
105 """skip calling VIM to get image, flavor status. Assumes ok"""
tierno1d213f42020-04-24 14:02:51 +0000106 if ro_task["vim_info"]["vim_status"] == "VIM_ERROR":
107 return "FAILED", {}
sousaedu80135b92021-02-17 15:05:18 +0100108
tierno1d213f42020-04-24 14:02:51 +0000109 return "DONE", {}
110
tierno70eeb182020-10-19 16:38:00 +0000111 def delete(self, ro_task, task_index):
112 """skip calling VIM to delete image. Assumes ok"""
tierno1d213f42020-04-24 14:02:51 +0000113 return "DONE", {}
114
tierno70eeb182020-10-19 16:38:00 +0000115 def exec(self, ro_task, task_index, task_depends):
116 return "DONE", None, None
tierno1d213f42020-04-24 14:02:51 +0000117
tierno1d213f42020-04-24 14:02:51 +0000118
tierno70eeb182020-10-19 16:38:00 +0000119class VimInteractionNet(VimInteractionBase):
tierno70eeb182020-10-19 16:38:00 +0000120 def new(self, ro_task, task_index, task_depends):
tierno1d213f42020-04-24 14:02:51 +0000121 vim_net_id = None
122 task = ro_task["tasks"][task_index]
123 task_id = task["task_id"]
124 created = False
125 created_items = {}
126 target_vim = self.my_vims[ro_task["target_id"]]
aticige9a26f22021-12-10 12:59:20 +0300127 mgmtnet = False
128 mgmtnet_defined_in_vim = False
sousaedu80135b92021-02-17 15:05:18 +0100129
tierno1d213f42020-04-24 14:02:51 +0000130 try:
131 # FIND
132 if task.get("find_params"):
133 # if management, get configuration of VIM
134 if task["find_params"].get("filter_dict"):
135 vim_filter = task["find_params"]["filter_dict"]
aticige9a26f22021-12-10 12:59:20 +0300136 # management network
sousaedu80135b92021-02-17 15:05:18 +0100137 elif task["find_params"].get("mgmt"):
aticige9a26f22021-12-10 12:59:20 +0300138 mgmtnet = True
sousaedu80135b92021-02-17 15:05:18 +0100139 if deep_get(
140 self.db_vims[ro_task["target_id"]],
141 "config",
142 "management_network_id",
143 ):
aticige9a26f22021-12-10 12:59:20 +0300144 mgmtnet_defined_in_vim = True
sousaedu80135b92021-02-17 15:05:18 +0100145 vim_filter = {
146 "id": self.db_vims[ro_task["target_id"]]["config"][
147 "management_network_id"
148 ]
149 }
150 elif deep_get(
151 self.db_vims[ro_task["target_id"]],
152 "config",
153 "management_network_name",
154 ):
aticige9a26f22021-12-10 12:59:20 +0300155 mgmtnet_defined_in_vim = True
sousaedu80135b92021-02-17 15:05:18 +0100156 vim_filter = {
157 "name": self.db_vims[ro_task["target_id"]]["config"][
158 "management_network_name"
159 ]
160 }
tierno1d213f42020-04-24 14:02:51 +0000161 else:
162 vim_filter = {"name": task["find_params"]["name"]}
163 else:
sousaedu80135b92021-02-17 15:05:18 +0100164 raise NsWorkerExceptionNotFound(
165 "Invalid find_params for new_net {}".format(task["find_params"])
166 )
tierno1d213f42020-04-24 14:02:51 +0000167
168 vim_nets = target_vim.get_network_list(vim_filter)
169 if not vim_nets and not task.get("params"):
aticige9a26f22021-12-10 12:59:20 +0300170 # If there is mgmt-network in the descriptor,
171 # there is no mapping of that network to a VIM network in the descriptor,
172 # also there is no mapping in the "--config" parameter or at VIM creation;
173 # that mgmt-network will be created.
174 if mgmtnet and not mgmtnet_defined_in_vim:
175 net_name = (
176 vim_filter.get("name")
177 if vim_filter.get("name")
178 else vim_filter.get("id")[:16]
sousaedu80135b92021-02-17 15:05:18 +0100179 )
aticige9a26f22021-12-10 12:59:20 +0300180 vim_net_id, created_items = target_vim.new_network(
181 net_name, None
182 )
183 self.logger.debug(
184 "Created mgmt network vim_net_id: {}".format(vim_net_id)
185 )
186 created = True
187 else:
188 raise NsWorkerExceptionNotFound(
189 "Network not found with this criteria: '{}'".format(
190 task.get("find_params")
191 )
192 )
tierno1d213f42020-04-24 14:02:51 +0000193 elif len(vim_nets) > 1:
194 raise NsWorkerException(
sousaedu80135b92021-02-17 15:05:18 +0100195 "More than one network found with this criteria: '{}'".format(
196 task["find_params"]
197 )
198 )
199
tierno1d213f42020-04-24 14:02:51 +0000200 if vim_nets:
201 vim_net_id = vim_nets[0]["id"]
202 else:
203 # CREATE
204 params = task["params"]
205 vim_net_id, created_items = target_vim.new_network(**params)
206 created = True
207
sousaedu80135b92021-02-17 15:05:18 +0100208 ro_vim_item_update = {
209 "vim_id": vim_net_id,
210 "vim_status": "BUILD",
211 "created": created,
212 "created_items": created_items,
213 "vim_details": None,
aticig79ac6df2022-05-06 16:09:52 +0300214 "vim_message": None,
sousaedu80135b92021-02-17 15:05:18 +0100215 }
tierno1d213f42020-04-24 14:02:51 +0000216 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +0100217 "task={} {} new-net={} created={}".format(
218 task_id, ro_task["target_id"], vim_net_id, created
219 )
220 )
221
tierno1d213f42020-04-24 14:02:51 +0000222 return "BUILD", ro_vim_item_update
223 except (vimconn.VimConnException, NsWorkerException) as e:
sousaedu80135b92021-02-17 15:05:18 +0100224 self.logger.error(
225 "task={} vim={} new-net: {}".format(task_id, ro_task["target_id"], e)
226 )
227 ro_vim_item_update = {
228 "vim_status": "VIM_ERROR",
229 "created": created,
aticig79ac6df2022-05-06 16:09:52 +0300230 "vim_message": str(e),
sousaedu80135b92021-02-17 15:05:18 +0100231 }
232
tierno1d213f42020-04-24 14:02:51 +0000233 return "FAILED", ro_vim_item_update
234
tierno70eeb182020-10-19 16:38:00 +0000235 def refresh(self, ro_task):
tierno1d213f42020-04-24 14:02:51 +0000236 """Call VIM to get network status"""
237 ro_task_id = ro_task["_id"]
238 target_vim = self.my_vims[ro_task["target_id"]]
tierno1d213f42020-04-24 14:02:51 +0000239 vim_id = ro_task["vim_info"]["vim_id"]
240 net_to_refresh_list = [vim_id]
sousaedu80135b92021-02-17 15:05:18 +0100241
tierno1d213f42020-04-24 14:02:51 +0000242 try:
243 vim_dict = target_vim.refresh_nets_status(net_to_refresh_list)
244 vim_info = vim_dict[vim_id]
sousaedu80135b92021-02-17 15:05:18 +0100245
tierno1d213f42020-04-24 14:02:51 +0000246 if vim_info["status"] == "ACTIVE":
247 task_status = "DONE"
248 elif vim_info["status"] == "BUILD":
249 task_status = "BUILD"
250 else:
251 task_status = "FAILED"
252 except vimconn.VimConnException as e:
253 # Mark all tasks at VIM_ERROR status
sousaedu80135b92021-02-17 15:05:18 +0100254 self.logger.error(
255 "ro_task={} vim={} get-net={}: {}".format(
256 ro_task_id, ro_task["target_id"], vim_id, e
257 )
258 )
tierno1d213f42020-04-24 14:02:51 +0000259 vim_info = {"status": "VIM_ERROR", "error_msg": str(e)}
260 task_status = "FAILED"
261
262 ro_vim_item_update = {}
263 if ro_task["vim_info"]["vim_status"] != vim_info["status"]:
264 ro_vim_item_update["vim_status"] = vim_info["status"]
sousaedu80135b92021-02-17 15:05:18 +0100265
tierno1d213f42020-04-24 14:02:51 +0000266 if ro_task["vim_info"]["vim_name"] != vim_info.get("name"):
267 ro_vim_item_update["vim_name"] = vim_info.get("name")
sousaedu80135b92021-02-17 15:05:18 +0100268
tierno1d213f42020-04-24 14:02:51 +0000269 if vim_info["status"] in ("ERROR", "VIM_ERROR"):
aticig79ac6df2022-05-06 16:09:52 +0300270 if ro_task["vim_info"]["vim_message"] != vim_info.get("error_msg"):
271 ro_vim_item_update["vim_message"] = vim_info.get("error_msg")
tierno1d213f42020-04-24 14:02:51 +0000272 elif vim_info["status"] == "DELETED":
273 ro_vim_item_update["vim_id"] = None
aticig79ac6df2022-05-06 16:09:52 +0300274 ro_vim_item_update["vim_message"] = "Deleted externally"
tierno1d213f42020-04-24 14:02:51 +0000275 else:
276 if ro_task["vim_info"]["vim_details"] != vim_info["vim_info"]:
277 ro_vim_item_update["vim_details"] = vim_info["vim_info"]
sousaedu80135b92021-02-17 15:05:18 +0100278
tierno1d213f42020-04-24 14:02:51 +0000279 if ro_vim_item_update:
sousaedu80135b92021-02-17 15:05:18 +0100280 self.logger.debug(
281 "ro_task={} {} get-net={}: status={} {}".format(
282 ro_task_id,
283 ro_task["target_id"],
284 vim_id,
285 ro_vim_item_update.get("vim_status"),
aticig79ac6df2022-05-06 16:09:52 +0300286 ro_vim_item_update.get("vim_message")
sousaedu80135b92021-02-17 15:05:18 +0100287 if ro_vim_item_update.get("vim_status") != "ACTIVE"
288 else "",
289 )
290 )
291
tierno1d213f42020-04-24 14:02:51 +0000292 return task_status, ro_vim_item_update
293
tierno70eeb182020-10-19 16:38:00 +0000294 def delete(self, ro_task, task_index):
tierno1d213f42020-04-24 14:02:51 +0000295 task = ro_task["tasks"][task_index]
296 task_id = task["task_id"]
297 net_vim_id = ro_task["vim_info"]["vim_id"]
sousaedu80135b92021-02-17 15:05:18 +0100298 ro_vim_item_update_ok = {
299 "vim_status": "DELETED",
300 "created": False,
aticig79ac6df2022-05-06 16:09:52 +0300301 "vim_message": "DELETED",
sousaedu80135b92021-02-17 15:05:18 +0100302 "vim_id": None,
303 }
304
tierno1d213f42020-04-24 14:02:51 +0000305 try:
306 if net_vim_id or ro_task["vim_info"]["created_items"]:
307 target_vim = self.my_vims[ro_task["target_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100308 target_vim.delete_network(
309 net_vim_id, ro_task["vim_info"]["created_items"]
310 )
tierno1d213f42020-04-24 14:02:51 +0000311 except vimconn.VimConnNotFoundException:
aticig79ac6df2022-05-06 16:09:52 +0300312 ro_vim_item_update_ok["vim_message"] = "already deleted"
tierno1d213f42020-04-24 14:02:51 +0000313 except vimconn.VimConnException as e:
sousaedu80135b92021-02-17 15:05:18 +0100314 self.logger.error(
315 "ro_task={} vim={} del-net={}: {}".format(
316 ro_task["_id"], ro_task["target_id"], net_vim_id, e
317 )
318 )
319 ro_vim_item_update = {
320 "vim_status": "VIM_ERROR",
aticig79ac6df2022-05-06 16:09:52 +0300321 "vim_message": "Error while deleting: {}".format(e),
sousaedu80135b92021-02-17 15:05:18 +0100322 }
323
tierno1d213f42020-04-24 14:02:51 +0000324 return "FAILED", ro_vim_item_update
325
sousaedu80135b92021-02-17 15:05:18 +0100326 self.logger.debug(
327 "task={} {} del-net={} {}".format(
328 task_id,
329 ro_task["target_id"],
330 net_vim_id,
aticig79ac6df2022-05-06 16:09:52 +0300331 ro_vim_item_update_ok.get("vim_message", ""),
sousaedu80135b92021-02-17 15:05:18 +0100332 )
333 )
334
tierno1d213f42020-04-24 14:02:51 +0000335 return "DONE", ro_vim_item_update_ok
336
tierno70eeb182020-10-19 16:38:00 +0000337
338class VimInteractionVdu(VimInteractionBase):
sousaedu80135b92021-02-17 15:05:18 +0100339 max_retries_inject_ssh_key = 20 # 20 times
340 time_retries_inject_ssh_key = 30 # wevery 30 seconds
tierno70eeb182020-10-19 16:38:00 +0000341
342 def new(self, ro_task, task_index, task_depends):
tierno1d213f42020-04-24 14:02:51 +0000343 task = ro_task["tasks"][task_index]
344 task_id = task["task_id"]
345 created = False
346 created_items = {}
347 target_vim = self.my_vims[ro_task["target_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100348
tierno1d213f42020-04-24 14:02:51 +0000349 try:
350 created = True
351 params = task["params"]
352 params_copy = deepcopy(params)
353 net_list = params_copy["net_list"]
sousaedu80135b92021-02-17 15:05:18 +0100354
tierno1d213f42020-04-24 14:02:51 +0000355 for net in net_list:
sousaedu80135b92021-02-17 15:05:18 +0100356 # change task_id into network_id
357 if "net_id" in net and net["net_id"].startswith("TASK-"):
tierno1d213f42020-04-24 14:02:51 +0000358 network_id = task_depends[net["net_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100359
tierno1d213f42020-04-24 14:02:51 +0000360 if not network_id:
sousaedu80135b92021-02-17 15:05:18 +0100361 raise NsWorkerException(
362 "Cannot create VM because depends on a network not created or found "
363 "for {}".format(net["net_id"])
364 )
365
tierno1d213f42020-04-24 14:02:51 +0000366 net["net_id"] = network_id
sousaedu80135b92021-02-17 15:05:18 +0100367
tierno1d213f42020-04-24 14:02:51 +0000368 if params_copy["image_id"].startswith("TASK-"):
369 params_copy["image_id"] = task_depends[params_copy["image_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100370
tierno1d213f42020-04-24 14:02:51 +0000371 if params_copy["flavor_id"].startswith("TASK-"):
372 params_copy["flavor_id"] = task_depends[params_copy["flavor_id"]]
373
Alexis Romerob70f4ed2022-03-11 18:00:49 +0100374 affinity_group_list = params_copy["affinity_group_list"]
375 for affinity_group in affinity_group_list:
376 # change task_id into affinity_group_id
377 if "affinity_group_id" in affinity_group and affinity_group[
378 "affinity_group_id"
379 ].startswith("TASK-"):
380 affinity_group_id = task_depends[
381 affinity_group["affinity_group_id"]
382 ]
383
384 if not affinity_group_id:
385 raise NsWorkerException(
386 "found for {}".format(affinity_group["affinity_group_id"])
387 )
388
389 affinity_group["affinity_group_id"] = affinity_group_id
390
tierno1d213f42020-04-24 14:02:51 +0000391 vim_vm_id, created_items = target_vim.new_vminstance(**params_copy)
392 interfaces = [iface["vim_id"] for iface in params_copy["net_list"]]
393
sousaedu80135b92021-02-17 15:05:18 +0100394 ro_vim_item_update = {
395 "vim_id": vim_vm_id,
396 "vim_status": "BUILD",
397 "created": created,
398 "created_items": created_items,
399 "vim_details": None,
aticig79ac6df2022-05-06 16:09:52 +0300400 "vim_message": None,
sousaedu80135b92021-02-17 15:05:18 +0100401 "interfaces_vim_ids": interfaces,
402 "interfaces": [],
403 }
tierno1d213f42020-04-24 14:02:51 +0000404 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +0100405 "task={} {} new-vm={} created={}".format(
406 task_id, ro_task["target_id"], vim_vm_id, created
407 )
408 )
409
tierno1d213f42020-04-24 14:02:51 +0000410 return "BUILD", ro_vim_item_update
411 except (vimconn.VimConnException, NsWorkerException) as e:
sousaedu80135b92021-02-17 15:05:18 +0100412 self.logger.error(
413 "task={} {} new-vm: {}".format(task_id, ro_task["target_id"], e)
414 )
415 ro_vim_item_update = {
416 "vim_status": "VIM_ERROR",
417 "created": created,
aticig79ac6df2022-05-06 16:09:52 +0300418 "vim_message": str(e),
sousaedu80135b92021-02-17 15:05:18 +0100419 }
420
tierno1d213f42020-04-24 14:02:51 +0000421 return "FAILED", ro_vim_item_update
422
tierno70eeb182020-10-19 16:38:00 +0000423 def delete(self, ro_task, task_index):
tierno1d213f42020-04-24 14:02:51 +0000424 task = ro_task["tasks"][task_index]
425 task_id = task["task_id"]
426 vm_vim_id = ro_task["vim_info"]["vim_id"]
sousaedu80135b92021-02-17 15:05:18 +0100427 ro_vim_item_update_ok = {
428 "vim_status": "DELETED",
429 "created": False,
aticig79ac6df2022-05-06 16:09:52 +0300430 "vim_message": "DELETED",
sousaedu80135b92021-02-17 15:05:18 +0100431 "vim_id": None,
432 }
433
tierno1d213f42020-04-24 14:02:51 +0000434 try:
palaciosj8f2060b2022-02-24 12:05:59 +0000435 self.logger.debug(
436 "delete_vminstance: vm_vim_id={} created_items={}".format(
437 vm_vim_id, ro_task["vim_info"]["created_items"]
438 )
439 )
tierno1d213f42020-04-24 14:02:51 +0000440 if vm_vim_id or ro_task["vim_info"]["created_items"]:
441 target_vim = self.my_vims[ro_task["target_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100442 target_vim.delete_vminstance(
palaciosj8f2060b2022-02-24 12:05:59 +0000443 vm_vim_id,
444 ro_task["vim_info"]["created_items"],
445 ro_task["vim_info"].get("volumes_to_hold", []),
sousaedu80135b92021-02-17 15:05:18 +0100446 )
tierno1d213f42020-04-24 14:02:51 +0000447 except vimconn.VimConnNotFoundException:
aticig79ac6df2022-05-06 16:09:52 +0300448 ro_vim_item_update_ok["vim_message"] = "already deleted"
tierno1d213f42020-04-24 14:02:51 +0000449 except vimconn.VimConnException as e:
sousaedu80135b92021-02-17 15:05:18 +0100450 self.logger.error(
451 "ro_task={} vim={} del-vm={}: {}".format(
452 ro_task["_id"], ro_task["target_id"], vm_vim_id, e
453 )
454 )
455 ro_vim_item_update = {
456 "vim_status": "VIM_ERROR",
aticig79ac6df2022-05-06 16:09:52 +0300457 "vim_message": "Error while deleting: {}".format(e),
sousaedu80135b92021-02-17 15:05:18 +0100458 }
459
tierno1d213f42020-04-24 14:02:51 +0000460 return "FAILED", ro_vim_item_update
461
sousaedu80135b92021-02-17 15:05:18 +0100462 self.logger.debug(
463 "task={} {} del-vm={} {}".format(
464 task_id,
465 ro_task["target_id"],
466 vm_vim_id,
aticig79ac6df2022-05-06 16:09:52 +0300467 ro_vim_item_update_ok.get("vim_message", ""),
sousaedu80135b92021-02-17 15:05:18 +0100468 )
469 )
470
tierno1d213f42020-04-24 14:02:51 +0000471 return "DONE", ro_vim_item_update_ok
472
tierno70eeb182020-10-19 16:38:00 +0000473 def refresh(self, ro_task):
tierno1d213f42020-04-24 14:02:51 +0000474 """Call VIM to get vm status"""
475 ro_task_id = ro_task["_id"]
476 target_vim = self.my_vims[ro_task["target_id"]]
tierno1d213f42020-04-24 14:02:51 +0000477 vim_id = ro_task["vim_info"]["vim_id"]
sousaedu80135b92021-02-17 15:05:18 +0100478
tierno1d213f42020-04-24 14:02:51 +0000479 if not vim_id:
480 return None, None
sousaedu80135b92021-02-17 15:05:18 +0100481
tierno1d213f42020-04-24 14:02:51 +0000482 vm_to_refresh_list = [vim_id]
483 try:
484 vim_dict = target_vim.refresh_vms_status(vm_to_refresh_list)
485 vim_info = vim_dict[vim_id]
sousaedu80135b92021-02-17 15:05:18 +0100486
tierno1d213f42020-04-24 14:02:51 +0000487 if vim_info["status"] == "ACTIVE":
488 task_status = "DONE"
489 elif vim_info["status"] == "BUILD":
490 task_status = "BUILD"
491 else:
492 task_status = "FAILED"
sousaedu80135b92021-02-17 15:05:18 +0100493
tierno70eeb182020-10-19 16:38:00 +0000494 # try to load and parse vim_information
495 try:
496 vim_info_info = yaml.safe_load(vim_info["vim_info"])
497 if vim_info_info.get("name"):
498 vim_info["name"] = vim_info_info["name"]
499 except Exception:
500 pass
tierno1d213f42020-04-24 14:02:51 +0000501 except vimconn.VimConnException as e:
502 # Mark all tasks at VIM_ERROR status
sousaedu80135b92021-02-17 15:05:18 +0100503 self.logger.error(
504 "ro_task={} vim={} get-vm={}: {}".format(
505 ro_task_id, ro_task["target_id"], vim_id, e
506 )
507 )
tierno1d213f42020-04-24 14:02:51 +0000508 vim_info = {"status": "VIM_ERROR", "error_msg": str(e)}
509 task_status = "FAILED"
510
511 ro_vim_item_update = {}
sousaedu80135b92021-02-17 15:05:18 +0100512
tierno70eeb182020-10-19 16:38:00 +0000513 # Interfaces cannot be present if e.g. VM is not present, that is status=DELETED
tierno1d213f42020-04-24 14:02:51 +0000514 vim_interfaces = []
tierno70eeb182020-10-19 16:38:00 +0000515 if vim_info.get("interfaces"):
516 for vim_iface_id in ro_task["vim_info"]["interfaces_vim_ids"]:
sousaedu80135b92021-02-17 15:05:18 +0100517 iface = next(
518 (
519 iface
520 for iface in vim_info["interfaces"]
521 if vim_iface_id == iface["vim_interface_id"]
522 ),
523 None,
524 )
tierno70eeb182020-10-19 16:38:00 +0000525 # if iface:
526 # iface.pop("vim_info", None)
527 vim_interfaces.append(iface)
tierno1d213f42020-04-24 14:02:51 +0000528
sousaedu80135b92021-02-17 15:05:18 +0100529 task_create = next(
530 t
531 for t in ro_task["tasks"]
532 if t and t["action"] == "CREATE" and t["status"] != "FINISHED"
533 )
tierno70eeb182020-10-19 16:38:00 +0000534 if vim_interfaces and task_create.get("mgmt_vnf_interface") is not None:
sousaedu80135b92021-02-17 15:05:18 +0100535 vim_interfaces[task_create["mgmt_vnf_interface"]][
536 "mgmt_vnf_interface"
537 ] = True
538
539 mgmt_vdu_iface = task_create.get(
540 "mgmt_vdu_interface", task_create.get("mgmt_vnf_interface", 0)
541 )
tierno70eeb182020-10-19 16:38:00 +0000542 if vim_interfaces:
543 vim_interfaces[mgmt_vdu_iface]["mgmt_vdu_interface"] = True
tierno1d213f42020-04-24 14:02:51 +0000544
545 if ro_task["vim_info"]["interfaces"] != vim_interfaces:
546 ro_vim_item_update["interfaces"] = vim_interfaces
sousaedu80135b92021-02-17 15:05:18 +0100547
tierno1d213f42020-04-24 14:02:51 +0000548 if ro_task["vim_info"]["vim_status"] != vim_info["status"]:
549 ro_vim_item_update["vim_status"] = vim_info["status"]
sousaedu80135b92021-02-17 15:05:18 +0100550
tierno1d213f42020-04-24 14:02:51 +0000551 if ro_task["vim_info"]["vim_name"] != vim_info.get("name"):
552 ro_vim_item_update["vim_name"] = vim_info.get("name")
sousaedu80135b92021-02-17 15:05:18 +0100553
tierno1d213f42020-04-24 14:02:51 +0000554 if vim_info["status"] in ("ERROR", "VIM_ERROR"):
aticig79ac6df2022-05-06 16:09:52 +0300555 if ro_task["vim_info"]["vim_message"] != vim_info.get("error_msg"):
556 ro_vim_item_update["vim_message"] = vim_info.get("error_msg")
tierno1d213f42020-04-24 14:02:51 +0000557 elif vim_info["status"] == "DELETED":
558 ro_vim_item_update["vim_id"] = None
aticig79ac6df2022-05-06 16:09:52 +0300559 ro_vim_item_update["vim_message"] = "Deleted externally"
tierno1d213f42020-04-24 14:02:51 +0000560 else:
561 if ro_task["vim_info"]["vim_details"] != vim_info["vim_info"]:
562 ro_vim_item_update["vim_details"] = vim_info["vim_info"]
sousaedu80135b92021-02-17 15:05:18 +0100563
tierno1d213f42020-04-24 14:02:51 +0000564 if ro_vim_item_update:
sousaedu80135b92021-02-17 15:05:18 +0100565 self.logger.debug(
566 "ro_task={} {} get-vm={}: status={} {}".format(
567 ro_task_id,
568 ro_task["target_id"],
569 vim_id,
570 ro_vim_item_update.get("vim_status"),
aticig79ac6df2022-05-06 16:09:52 +0300571 ro_vim_item_update.get("vim_message")
sousaedu80135b92021-02-17 15:05:18 +0100572 if ro_vim_item_update.get("vim_status") != "ACTIVE"
573 else "",
574 )
575 )
576
tierno1d213f42020-04-24 14:02:51 +0000577 return task_status, ro_vim_item_update
578
tierno70eeb182020-10-19 16:38:00 +0000579 def exec(self, ro_task, task_index, task_depends):
tierno1d213f42020-04-24 14:02:51 +0000580 task = ro_task["tasks"][task_index]
581 task_id = task["task_id"]
582 target_vim = self.my_vims[ro_task["target_id"]]
tierno70eeb182020-10-19 16:38:00 +0000583 db_task_update = {"retries": 0}
584 retries = task.get("retries", 0)
sousaedu80135b92021-02-17 15:05:18 +0100585
tierno1d213f42020-04-24 14:02:51 +0000586 try:
587 params = task["params"]
588 params_copy = deepcopy(params)
sousaedu80135b92021-02-17 15:05:18 +0100589 params_copy["ro_key"] = self.db.decrypt(
590 params_copy.pop("private_key"),
591 params_copy.pop("schema_version"),
592 params_copy.pop("salt"),
593 )
tierno70eeb182020-10-19 16:38:00 +0000594 params_copy["ip_addr"] = params_copy.pop("ip_address")
tierno1d213f42020-04-24 14:02:51 +0000595 target_vim.inject_user_key(**params_copy)
596 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +0100597 "task={} {} action-vm=inject_key".format(task_id, ro_task["target_id"])
598 )
599
600 return (
601 "DONE",
602 None,
603 db_task_update,
604 ) # params_copy["key"]
tierno1d213f42020-04-24 14:02:51 +0000605 except (vimconn.VimConnException, NsWorkerException) as e:
tierno70eeb182020-10-19 16:38:00 +0000606 retries += 1
sousaedu80135b92021-02-17 15:05:18 +0100607
aticige5d78422022-05-16 23:03:54 +0300608 self.logger.debug(traceback.format_exc())
tierno70eeb182020-10-19 16:38:00 +0000609 if retries < self.max_retries_inject_ssh_key:
sousaedu80135b92021-02-17 15:05:18 +0100610 return (
611 "BUILD",
612 None,
613 {
614 "retries": retries,
615 "next_retry": self.time_retries_inject_ssh_key,
616 },
617 )
618
619 self.logger.error(
620 "task={} {} inject-ssh-key: {}".format(task_id, ro_task["target_id"], e)
621 )
aticig79ac6df2022-05-06 16:09:52 +0300622 ro_vim_item_update = {"vim_message": str(e)}
sousaedu80135b92021-02-17 15:05:18 +0100623
tierno70eeb182020-10-19 16:38:00 +0000624 return "FAILED", ro_vim_item_update, db_task_update
625
626
627class VimInteractionImage(VimInteractionBase):
tierno70eeb182020-10-19 16:38:00 +0000628 def new(self, ro_task, task_index, task_depends):
629 task = ro_task["tasks"][task_index]
630 task_id = task["task_id"]
631 created = False
632 created_items = {}
633 target_vim = self.my_vims[ro_task["target_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100634
tierno70eeb182020-10-19 16:38:00 +0000635 try:
636 # FIND
637 if task.get("find_params"):
638 vim_images = target_vim.get_image_list(**task["find_params"])
sousaedu80135b92021-02-17 15:05:18 +0100639
tierno70eeb182020-10-19 16:38:00 +0000640 if not vim_images:
sousaedu80135b92021-02-17 15:05:18 +0100641 raise NsWorkerExceptionNotFound(
642 "Image not found with this criteria: '{}'".format(
643 task["find_params"]
644 )
645 )
tierno70eeb182020-10-19 16:38:00 +0000646 elif len(vim_images) > 1:
647 raise NsWorkerException(
sousaeduee6a6202021-05-11 13:22:37 +0200648 "More than one image found with this criteria: '{}'".format(
sousaedu80135b92021-02-17 15:05:18 +0100649 task["find_params"]
650 )
651 )
tierno70eeb182020-10-19 16:38:00 +0000652 else:
653 vim_image_id = vim_images[0]["id"]
654
sousaedu80135b92021-02-17 15:05:18 +0100655 ro_vim_item_update = {
656 "vim_id": vim_image_id,
657 "vim_status": "DONE",
658 "created": created,
659 "created_items": created_items,
660 "vim_details": None,
aticig79ac6df2022-05-06 16:09:52 +0300661 "vim_message": None,
sousaedu80135b92021-02-17 15:05:18 +0100662 }
tierno70eeb182020-10-19 16:38:00 +0000663 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +0100664 "task={} {} new-image={} created={}".format(
665 task_id, ro_task["target_id"], vim_image_id, created
666 )
667 )
668
tierno70eeb182020-10-19 16:38:00 +0000669 return "DONE", ro_vim_item_update
670 except (NsWorkerException, vimconn.VimConnException) as e:
sousaedu80135b92021-02-17 15:05:18 +0100671 self.logger.error(
672 "task={} {} new-image: {}".format(task_id, ro_task["target_id"], e)
673 )
674 ro_vim_item_update = {
675 "vim_status": "VIM_ERROR",
676 "created": created,
aticig79ac6df2022-05-06 16:09:52 +0300677 "vim_message": str(e),
sousaedu80135b92021-02-17 15:05:18 +0100678 }
679
tierno1d213f42020-04-24 14:02:51 +0000680 return "FAILED", ro_vim_item_update
681
tierno70eeb182020-10-19 16:38:00 +0000682
683class VimInteractionFlavor(VimInteractionBase):
tierno70eeb182020-10-19 16:38:00 +0000684 def delete(self, ro_task, task_index):
685 task = ro_task["tasks"][task_index]
686 task_id = task["task_id"]
687 flavor_vim_id = ro_task["vim_info"]["vim_id"]
sousaedu80135b92021-02-17 15:05:18 +0100688 ro_vim_item_update_ok = {
689 "vim_status": "DELETED",
690 "created": False,
aticig79ac6df2022-05-06 16:09:52 +0300691 "vim_message": "DELETED",
sousaedu80135b92021-02-17 15:05:18 +0100692 "vim_id": None,
693 }
694
tierno70eeb182020-10-19 16:38:00 +0000695 try:
696 if flavor_vim_id:
697 target_vim = self.my_vims[ro_task["target_id"]]
698 target_vim.delete_flavor(flavor_vim_id)
tierno70eeb182020-10-19 16:38:00 +0000699 except vimconn.VimConnNotFoundException:
aticig79ac6df2022-05-06 16:09:52 +0300700 ro_vim_item_update_ok["vim_message"] = "already deleted"
tierno70eeb182020-10-19 16:38:00 +0000701 except vimconn.VimConnException as e:
sousaedu80135b92021-02-17 15:05:18 +0100702 self.logger.error(
703 "ro_task={} vim={} del-flavor={}: {}".format(
704 ro_task["_id"], ro_task["target_id"], flavor_vim_id, e
705 )
706 )
707 ro_vim_item_update = {
708 "vim_status": "VIM_ERROR",
aticig79ac6df2022-05-06 16:09:52 +0300709 "vim_message": "Error while deleting: {}".format(e),
sousaedu80135b92021-02-17 15:05:18 +0100710 }
711
tierno70eeb182020-10-19 16:38:00 +0000712 return "FAILED", ro_vim_item_update
713
sousaedu80135b92021-02-17 15:05:18 +0100714 self.logger.debug(
715 "task={} {} del-flavor={} {}".format(
716 task_id,
717 ro_task["target_id"],
718 flavor_vim_id,
aticig79ac6df2022-05-06 16:09:52 +0300719 ro_vim_item_update_ok.get("vim_message", ""),
sousaedu80135b92021-02-17 15:05:18 +0100720 )
721 )
722
tierno70eeb182020-10-19 16:38:00 +0000723 return "DONE", ro_vim_item_update_ok
724
725 def new(self, ro_task, task_index, task_depends):
726 task = ro_task["tasks"][task_index]
727 task_id = task["task_id"]
728 created = False
729 created_items = {}
730 target_vim = self.my_vims[ro_task["target_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100731
tierno70eeb182020-10-19 16:38:00 +0000732 try:
733 # FIND
734 vim_flavor_id = None
sousaedu80135b92021-02-17 15:05:18 +0100735
tierno70eeb182020-10-19 16:38:00 +0000736 if task.get("find_params"):
737 try:
738 flavor_data = task["find_params"]["flavor_data"]
739 vim_flavor_id = target_vim.get_flavor_id_from_data(flavor_data)
740 except vimconn.VimConnNotFoundException:
741 pass
742
743 if not vim_flavor_id and task.get("params"):
744 # CREATE
745 flavor_data = task["params"]["flavor_data"]
746 vim_flavor_id = target_vim.new_flavor(flavor_data)
747 created = True
748
sousaedu80135b92021-02-17 15:05:18 +0100749 ro_vim_item_update = {
750 "vim_id": vim_flavor_id,
751 "vim_status": "DONE",
752 "created": created,
753 "created_items": created_items,
754 "vim_details": None,
aticig79ac6df2022-05-06 16:09:52 +0300755 "vim_message": None,
sousaedu80135b92021-02-17 15:05:18 +0100756 }
tierno70eeb182020-10-19 16:38:00 +0000757 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +0100758 "task={} {} new-flavor={} created={}".format(
759 task_id, ro_task["target_id"], vim_flavor_id, created
760 )
761 )
762
tierno70eeb182020-10-19 16:38:00 +0000763 return "DONE", ro_vim_item_update
764 except (vimconn.VimConnException, NsWorkerException) as e:
sousaedu80135b92021-02-17 15:05:18 +0100765 self.logger.error(
766 "task={} vim={} new-flavor: {}".format(task_id, ro_task["target_id"], e)
767 )
768 ro_vim_item_update = {
769 "vim_status": "VIM_ERROR",
770 "created": created,
aticig79ac6df2022-05-06 16:09:52 +0300771 "vim_message": str(e),
sousaedu80135b92021-02-17 15:05:18 +0100772 }
773
tierno70eeb182020-10-19 16:38:00 +0000774 return "FAILED", ro_vim_item_update
775
776
Alexis Romerob70f4ed2022-03-11 18:00:49 +0100777class VimInteractionAffinityGroup(VimInteractionBase):
778 def delete(self, ro_task, task_index):
779 task = ro_task["tasks"][task_index]
780 task_id = task["task_id"]
781 affinity_group_vim_id = ro_task["vim_info"]["vim_id"]
782 ro_vim_item_update_ok = {
783 "vim_status": "DELETED",
784 "created": False,
aticig79ac6df2022-05-06 16:09:52 +0300785 "vim_message": "DELETED",
Alexis Romerob70f4ed2022-03-11 18:00:49 +0100786 "vim_id": None,
787 }
788
789 try:
790 if affinity_group_vim_id:
791 target_vim = self.my_vims[ro_task["target_id"]]
792 target_vim.delete_affinity_group(affinity_group_vim_id)
793 except vimconn.VimConnNotFoundException:
aticig79ac6df2022-05-06 16:09:52 +0300794 ro_vim_item_update_ok["vim_message"] = "already deleted"
Alexis Romerob70f4ed2022-03-11 18:00:49 +0100795 except vimconn.VimConnException as e:
796 self.logger.error(
797 "ro_task={} vim={} del-affinity-or-anti-affinity-group={}: {}".format(
798 ro_task["_id"], ro_task["target_id"], affinity_group_vim_id, e
799 )
800 )
801 ro_vim_item_update = {
802 "vim_status": "VIM_ERROR",
aticig79ac6df2022-05-06 16:09:52 +0300803 "vim_message": "Error while deleting: {}".format(e),
Alexis Romerob70f4ed2022-03-11 18:00:49 +0100804 }
805
806 return "FAILED", ro_vim_item_update
807
808 self.logger.debug(
809 "task={} {} del-affinity-or-anti-affinity-group={} {}".format(
810 task_id,
811 ro_task["target_id"],
812 affinity_group_vim_id,
aticig79ac6df2022-05-06 16:09:52 +0300813 ro_vim_item_update_ok.get("vim_message", ""),
Alexis Romerob70f4ed2022-03-11 18:00:49 +0100814 )
815 )
816
817 return "DONE", ro_vim_item_update_ok
818
819 def new(self, ro_task, task_index, task_depends):
820 task = ro_task["tasks"][task_index]
821 task_id = task["task_id"]
822 created = False
823 created_items = {}
824 target_vim = self.my_vims[ro_task["target_id"]]
825
826 try:
827 affinity_group_vim_id = None
Alexis Romero123de182022-04-26 19:24:40 +0200828 affinity_group_data = None
Alexis Romerob70f4ed2022-03-11 18:00:49 +0100829
830 if task.get("params"):
Alexis Romero123de182022-04-26 19:24:40 +0200831 affinity_group_data = task["params"].get("affinity_group_data")
832
833 if affinity_group_data and affinity_group_data.get("vim-affinity-group-id"):
834 try:
835 param_affinity_group_id = task["params"]["affinity_group_data"].get(
836 "vim-affinity-group-id"
837 )
838 affinity_group_vim_id = target_vim.get_affinity_group(
839 param_affinity_group_id
840 ).get("id")
841 except vimconn.VimConnNotFoundException:
842 self.logger.error(
843 "task={} {} new-affinity-or-anti-affinity-group. Provided VIM Affinity Group ID {}"
844 "could not be found at VIM. Creating a new one.".format(
845 task_id, ro_task["target_id"], param_affinity_group_id
846 )
847 )
848
849 if not affinity_group_vim_id and affinity_group_data:
Alexis Romerob70f4ed2022-03-11 18:00:49 +0100850 affinity_group_vim_id = target_vim.new_affinity_group(
851 affinity_group_data
852 )
853 created = True
854
855 ro_vim_item_update = {
856 "vim_id": affinity_group_vim_id,
857 "vim_status": "DONE",
858 "created": created,
859 "created_items": created_items,
860 "vim_details": None,
aticig79ac6df2022-05-06 16:09:52 +0300861 "vim_message": None,
Alexis Romerob70f4ed2022-03-11 18:00:49 +0100862 }
863 self.logger.debug(
864 "task={} {} new-affinity-or-anti-affinity-group={} created={}".format(
865 task_id, ro_task["target_id"], affinity_group_vim_id, created
866 )
867 )
868
869 return "DONE", ro_vim_item_update
870 except (vimconn.VimConnException, NsWorkerException) as e:
871 self.logger.error(
872 "task={} vim={} new-affinity-or-anti-affinity-group:"
873 " {}".format(task_id, ro_task["target_id"], e)
874 )
875 ro_vim_item_update = {
876 "vim_status": "VIM_ERROR",
877 "created": created,
aticig79ac6df2022-05-06 16:09:52 +0300878 "vim_message": str(e),
Alexis Romerob70f4ed2022-03-11 18:00:49 +0100879 }
880
881 return "FAILED", ro_vim_item_update
882
883
tierno70eeb182020-10-19 16:38:00 +0000884class VimInteractionSdnNet(VimInteractionBase):
tierno70eeb182020-10-19 16:38:00 +0000885 @staticmethod
886 def _match_pci(port_pci, mapping):
887 """
888 Check if port_pci matches with mapping
889 mapping can have brackets to indicate that several chars are accepted. e.g
890 pci '0000:af:10.1' matches with '0000:af:1[01].[1357]'
891 :param port_pci: text
892 :param mapping: text, can contain brackets to indicate several chars are available
893 :return: True if matches, False otherwise
894 """
895 if not port_pci or not mapping:
896 return False
897 if port_pci == mapping:
898 return True
899
900 mapping_index = 0
901 pci_index = 0
902 while True:
903 bracket_start = mapping.find("[", mapping_index)
sousaedu80135b92021-02-17 15:05:18 +0100904
tierno70eeb182020-10-19 16:38:00 +0000905 if bracket_start == -1:
906 break
sousaedu80135b92021-02-17 15:05:18 +0100907
tierno70eeb182020-10-19 16:38:00 +0000908 bracket_end = mapping.find("]", bracket_start)
909 if bracket_end == -1:
910 break
sousaedu80135b92021-02-17 15:05:18 +0100911
tierno70eeb182020-10-19 16:38:00 +0000912 length = bracket_start - mapping_index
sousaedu80135b92021-02-17 15:05:18 +0100913 if (
914 length
915 and port_pci[pci_index : pci_index + length]
916 != mapping[mapping_index:bracket_start]
917 ):
tierno70eeb182020-10-19 16:38:00 +0000918 return False
sousaedu80135b92021-02-17 15:05:18 +0100919
920 if (
921 port_pci[pci_index + length]
922 not in mapping[bracket_start + 1 : bracket_end]
923 ):
tierno70eeb182020-10-19 16:38:00 +0000924 return False
sousaedu80135b92021-02-17 15:05:18 +0100925
tierno70eeb182020-10-19 16:38:00 +0000926 pci_index += length + 1
927 mapping_index = bracket_end + 1
928
929 if port_pci[pci_index:] != mapping[mapping_index:]:
930 return False
sousaedu80135b92021-02-17 15:05:18 +0100931
tierno70eeb182020-10-19 16:38:00 +0000932 return True
933
934 def _get_interfaces(self, vlds_to_connect, vim_account_id):
935 """
936 :param vlds_to_connect: list with format vnfrs:<id>:vld.<vld_id> or nsrs:<id>:vld.<vld_id>
937 :param vim_account_id:
938 :return:
939 """
940 interfaces = []
sousaedu80135b92021-02-17 15:05:18 +0100941
tierno70eeb182020-10-19 16:38:00 +0000942 for vld in vlds_to_connect:
943 table, _, db_id = vld.partition(":")
944 db_id, _, vld = db_id.partition(":")
945 _, _, vld_id = vld.partition(".")
sousaedu80135b92021-02-17 15:05:18 +0100946
tierno70eeb182020-10-19 16:38:00 +0000947 if table == "vnfrs":
948 q_filter = {"vim-account-id": vim_account_id, "_id": db_id}
949 iface_key = "vnf-vld-id"
950 else: # table == "nsrs"
951 q_filter = {"vim-account-id": vim_account_id, "nsr-id-ref": db_id}
952 iface_key = "ns-vld-id"
sousaedu80135b92021-02-17 15:05:18 +0100953
tierno70eeb182020-10-19 16:38:00 +0000954 db_vnfrs = self.db.get_list("vnfrs", q_filter=q_filter)
sousaedu80135b92021-02-17 15:05:18 +0100955
tierno70eeb182020-10-19 16:38:00 +0000956 for db_vnfr in db_vnfrs:
957 for vdu_index, vdur in enumerate(db_vnfr.get("vdur", ())):
958 for iface_index, interface in enumerate(vdur["interfaces"]):
sousaedu80135b92021-02-17 15:05:18 +0100959 if interface.get(iface_key) == vld_id and interface.get(
960 "type"
961 ) in ("SR-IOV", "PCI-PASSTHROUGH"):
tierno70eeb182020-10-19 16:38:00 +0000962 # only SR-IOV o PT
963 interface_ = interface.copy()
sousaedu80135b92021-02-17 15:05:18 +0100964 interface_["id"] = "vnfrs:{}:vdu.{}.interfaces.{}".format(
965 db_vnfr["_id"], vdu_index, iface_index
966 )
967
tierno70eeb182020-10-19 16:38:00 +0000968 if vdur.get("status") == "ERROR":
969 interface_["status"] = "ERROR"
sousaedu80135b92021-02-17 15:05:18 +0100970
tierno70eeb182020-10-19 16:38:00 +0000971 interfaces.append(interface_)
sousaedu80135b92021-02-17 15:05:18 +0100972
tierno70eeb182020-10-19 16:38:00 +0000973 return interfaces
974
975 def refresh(self, ro_task):
976 # look for task create
sousaedu80135b92021-02-17 15:05:18 +0100977 task_create_index, _ = next(
978 i_t
979 for i_t in enumerate(ro_task["tasks"])
980 if i_t[1]
981 and i_t[1]["action"] == "CREATE"
982 and i_t[1]["status"] != "FINISHED"
983 )
tierno70eeb182020-10-19 16:38:00 +0000984
985 return self.new(ro_task, task_create_index, None)
986
987 def new(self, ro_task, task_index, task_depends):
988
989 task = ro_task["tasks"][task_index]
990 task_id = task["task_id"]
991 target_vim = self.my_vims[ro_task["target_id"]]
992
993 sdn_net_id = ro_task["vim_info"]["vim_id"]
994
995 created_items = ro_task["vim_info"].get("created_items")
996 connected_ports = ro_task["vim_info"].get("connected_ports", [])
997 new_connected_ports = []
998 last_update = ro_task["vim_info"].get("last_update", 0)
999 sdn_status = ro_task["vim_info"].get("vim_status", "BUILD") or "BUILD"
1000 error_list = []
1001 created = ro_task["vim_info"].get("created", False)
1002
1003 try:
tierno70eeb182020-10-19 16:38:00 +00001004 # CREATE
1005 params = task["params"]
1006 vlds_to_connect = params["vlds"]
1007 associated_vim = params["target_vim"]
sousaedu80135b92021-02-17 15:05:18 +01001008 # external additional ports
1009 additional_ports = params.get("sdn-ports") or ()
tierno70eeb182020-10-19 16:38:00 +00001010 _, _, vim_account_id = associated_vim.partition(":")
sousaedu80135b92021-02-17 15:05:18 +01001011
tierno70eeb182020-10-19 16:38:00 +00001012 if associated_vim:
1013 # get associated VIM
1014 if associated_vim not in self.db_vims:
sousaedu80135b92021-02-17 15:05:18 +01001015 self.db_vims[associated_vim] = self.db.get_one(
1016 "vim_accounts", {"_id": vim_account_id}
1017 )
1018
tierno70eeb182020-10-19 16:38:00 +00001019 db_vim = self.db_vims[associated_vim]
1020
1021 # look for ports to connect
1022 ports = self._get_interfaces(vlds_to_connect, vim_account_id)
1023 # print(ports)
1024
1025 sdn_ports = []
1026 pending_ports = error_ports = 0
1027 vlan_used = None
1028 sdn_need_update = False
sousaedu80135b92021-02-17 15:05:18 +01001029
tierno70eeb182020-10-19 16:38:00 +00001030 for port in ports:
1031 vlan_used = port.get("vlan") or vlan_used
sousaedu80135b92021-02-17 15:05:18 +01001032
tierno70eeb182020-10-19 16:38:00 +00001033 # TODO. Do not connect if already done
1034 if not port.get("compute_node") or not port.get("pci"):
1035 if port.get("status") == "ERROR":
1036 error_ports += 1
1037 else:
1038 pending_ports += 1
1039 continue
sousaedu80135b92021-02-17 15:05:18 +01001040
tierno70eeb182020-10-19 16:38:00 +00001041 pmap = None
sousaedu80135b92021-02-17 15:05:18 +01001042 compute_node_mappings = next(
1043 (
1044 c
1045 for c in db_vim["config"].get("sdn-port-mapping", ())
1046 if c and c["compute_node"] == port["compute_node"]
1047 ),
1048 None,
1049 )
1050
tierno70eeb182020-10-19 16:38:00 +00001051 if compute_node_mappings:
1052 # process port_mapping pci of type 0000:af:1[01].[1357]
sousaedu80135b92021-02-17 15:05:18 +01001053 pmap = next(
1054 (
1055 p
1056 for p in compute_node_mappings["ports"]
1057 if self._match_pci(port["pci"], p.get("pci"))
1058 ),
1059 None,
1060 )
1061
tierno70eeb182020-10-19 16:38:00 +00001062 if not pmap:
1063 if not db_vim["config"].get("mapping_not_needed"):
sousaedu80135b92021-02-17 15:05:18 +01001064 error_list.append(
1065 "Port mapping not found for compute_node={} pci={}".format(
1066 port["compute_node"], port["pci"]
1067 )
1068 )
tierno70eeb182020-10-19 16:38:00 +00001069 continue
sousaedu80135b92021-02-17 15:05:18 +01001070
tierno70eeb182020-10-19 16:38:00 +00001071 pmap = {}
1072
1073 service_endpoint_id = "{}:{}".format(port["compute_node"], port["pci"])
1074 new_port = {
sousaedu80135b92021-02-17 15:05:18 +01001075 "service_endpoint_id": pmap.get("service_endpoint_id")
1076 or service_endpoint_id,
1077 "service_endpoint_encapsulation_type": "dot1q"
1078 if port["type"] == "SR-IOV"
1079 else None,
tierno70eeb182020-10-19 16:38:00 +00001080 "service_endpoint_encapsulation_info": {
1081 "vlan": port.get("vlan"),
lloretgalleg160fcad2021-02-19 10:57:50 +00001082 "mac": port.get("mac-address"),
sousaedu80135b92021-02-17 15:05:18 +01001083 "device_id": pmap.get("device_id") or port["compute_node"],
1084 "device_interface_id": pmap.get("device_interface_id")
1085 or port["pci"],
tierno70eeb182020-10-19 16:38:00 +00001086 "switch_dpid": pmap.get("switch_id") or pmap.get("switch_dpid"),
1087 "switch_port": pmap.get("switch_port"),
1088 "service_mapping_info": pmap.get("service_mapping_info"),
sousaedu80135b92021-02-17 15:05:18 +01001089 },
tierno70eeb182020-10-19 16:38:00 +00001090 }
1091
1092 # TODO
1093 # if port["modified_at"] > last_update:
1094 # sdn_need_update = True
1095 new_connected_ports.append(port["id"]) # TODO
1096 sdn_ports.append(new_port)
1097
1098 if error_ports:
sousaedu80135b92021-02-17 15:05:18 +01001099 error_list.append(
1100 "{} interfaces have not been created as VDU is on ERROR status".format(
1101 error_ports
1102 )
1103 )
tierno70eeb182020-10-19 16:38:00 +00001104
1105 # connect external ports
1106 for index, additional_port in enumerate(additional_ports):
sousaedu80135b92021-02-17 15:05:18 +01001107 additional_port_id = additional_port.get(
1108 "service_endpoint_id"
1109 ) or "external-{}".format(index)
1110 sdn_ports.append(
1111 {
1112 "service_endpoint_id": additional_port_id,
1113 "service_endpoint_encapsulation_type": additional_port.get(
1114 "service_endpoint_encapsulation_type", "dot1q"
1115 ),
1116 "service_endpoint_encapsulation_info": {
1117 "vlan": additional_port.get("vlan") or vlan_used,
1118 "mac": additional_port.get("mac_address"),
1119 "device_id": additional_port.get("device_id"),
1120 "device_interface_id": additional_port.get(
1121 "device_interface_id"
1122 ),
1123 "switch_dpid": additional_port.get("switch_dpid")
1124 or additional_port.get("switch_id"),
1125 "switch_port": additional_port.get("switch_port"),
1126 "service_mapping_info": additional_port.get(
1127 "service_mapping_info"
1128 ),
1129 },
1130 }
1131 )
tierno70eeb182020-10-19 16:38:00 +00001132 new_connected_ports.append(additional_port_id)
1133 sdn_info = ""
sousaedu80135b92021-02-17 15:05:18 +01001134
tierno70eeb182020-10-19 16:38:00 +00001135 # if there are more ports to connect or they have been modified, call create/update
1136 if error_list:
1137 sdn_status = "ERROR"
1138 sdn_info = "; ".join(error_list)
1139 elif set(connected_ports) != set(new_connected_ports) or sdn_need_update:
1140 last_update = time.time()
sousaedu80135b92021-02-17 15:05:18 +01001141
tierno70eeb182020-10-19 16:38:00 +00001142 if not sdn_net_id:
1143 if len(sdn_ports) < 2:
1144 sdn_status = "ACTIVE"
sousaedu80135b92021-02-17 15:05:18 +01001145
tierno70eeb182020-10-19 16:38:00 +00001146 if not pending_ports:
sousaedu80135b92021-02-17 15:05:18 +01001147 self.logger.debug(
1148 "task={} {} new-sdn-net done, less than 2 ports".format(
1149 task_id, ro_task["target_id"]
1150 )
1151 )
tierno70eeb182020-10-19 16:38:00 +00001152 else:
1153 net_type = params.get("type") or "ELAN"
sousaedu80135b92021-02-17 15:05:18 +01001154 (
1155 sdn_net_id,
1156 created_items,
1157 ) = target_vim.create_connectivity_service(net_type, sdn_ports)
tierno70eeb182020-10-19 16:38:00 +00001158 created = True
sousaedu80135b92021-02-17 15:05:18 +01001159 self.logger.debug(
1160 "task={} {} new-sdn-net={} created={}".format(
1161 task_id, ro_task["target_id"], sdn_net_id, created
1162 )
1163 )
tierno70eeb182020-10-19 16:38:00 +00001164 else:
1165 created_items = target_vim.edit_connectivity_service(
sousaedu80135b92021-02-17 15:05:18 +01001166 sdn_net_id, conn_info=created_items, connection_points=sdn_ports
1167 )
tierno70eeb182020-10-19 16:38:00 +00001168 created = True
sousaedu80135b92021-02-17 15:05:18 +01001169 self.logger.debug(
1170 "task={} {} update-sdn-net={} created={}".format(
1171 task_id, ro_task["target_id"], sdn_net_id, created
1172 )
1173 )
1174
tierno70eeb182020-10-19 16:38:00 +00001175 connected_ports = new_connected_ports
1176 elif sdn_net_id:
sousaedu80135b92021-02-17 15:05:18 +01001177 wim_status_dict = target_vim.get_connectivity_service_status(
1178 sdn_net_id, conn_info=created_items
1179 )
tierno70eeb182020-10-19 16:38:00 +00001180 sdn_status = wim_status_dict["sdn_status"]
sousaedu80135b92021-02-17 15:05:18 +01001181
tierno70eeb182020-10-19 16:38:00 +00001182 if wim_status_dict.get("sdn_info"):
1183 sdn_info = str(wim_status_dict.get("sdn_info")) or ""
sousaedu80135b92021-02-17 15:05:18 +01001184
tierno70eeb182020-10-19 16:38:00 +00001185 if wim_status_dict.get("error_msg"):
1186 sdn_info = wim_status_dict.get("error_msg") or ""
1187
1188 if pending_ports:
1189 if sdn_status != "ERROR":
1190 sdn_info = "Waiting for getting interfaces location from VIM. Obtained '{}' of {}".format(
sousaedu80135b92021-02-17 15:05:18 +01001191 len(ports) - pending_ports, len(ports)
1192 )
1193
tierno70eeb182020-10-19 16:38:00 +00001194 if sdn_status == "ACTIVE":
1195 sdn_status = "BUILD"
1196
sousaedu80135b92021-02-17 15:05:18 +01001197 ro_vim_item_update = {
1198 "vim_id": sdn_net_id,
1199 "vim_status": sdn_status,
1200 "created": created,
1201 "created_items": created_items,
1202 "connected_ports": connected_ports,
1203 "vim_details": sdn_info,
aticig79ac6df2022-05-06 16:09:52 +03001204 "vim_message": None,
sousaedu80135b92021-02-17 15:05:18 +01001205 "last_update": last_update,
1206 }
1207
tierno70eeb182020-10-19 16:38:00 +00001208 return sdn_status, ro_vim_item_update
1209 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001210 self.logger.error(
1211 "task={} vim={} new-net: {}".format(task_id, ro_task["target_id"], e),
1212 exc_info=not isinstance(
1213 e, (sdnconn.SdnConnectorError, vimconn.VimConnException)
1214 ),
1215 )
1216 ro_vim_item_update = {
1217 "vim_status": "VIM_ERROR",
1218 "created": created,
aticig79ac6df2022-05-06 16:09:52 +03001219 "vim_message": str(e),
sousaedu80135b92021-02-17 15:05:18 +01001220 }
1221
tierno70eeb182020-10-19 16:38:00 +00001222 return "FAILED", ro_vim_item_update
1223
1224 def delete(self, ro_task, task_index):
1225 task = ro_task["tasks"][task_index]
1226 task_id = task["task_id"]
1227 sdn_vim_id = ro_task["vim_info"].get("vim_id")
sousaedu80135b92021-02-17 15:05:18 +01001228 ro_vim_item_update_ok = {
1229 "vim_status": "DELETED",
1230 "created": False,
aticig79ac6df2022-05-06 16:09:52 +03001231 "vim_message": "DELETED",
sousaedu80135b92021-02-17 15:05:18 +01001232 "vim_id": None,
1233 }
1234
tierno70eeb182020-10-19 16:38:00 +00001235 try:
1236 if sdn_vim_id:
1237 target_vim = self.my_vims[ro_task["target_id"]]
sousaedu80135b92021-02-17 15:05:18 +01001238 target_vim.delete_connectivity_service(
1239 sdn_vim_id, ro_task["vim_info"].get("created_items")
1240 )
tierno70eeb182020-10-19 16:38:00 +00001241
1242 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001243 if (
1244 isinstance(e, sdnconn.SdnConnectorError)
1245 and e.http_code == HTTPStatus.NOT_FOUND.value
1246 ):
aticig79ac6df2022-05-06 16:09:52 +03001247 ro_vim_item_update_ok["vim_message"] = "already deleted"
tierno70eeb182020-10-19 16:38:00 +00001248 else:
sousaedu80135b92021-02-17 15:05:18 +01001249 self.logger.error(
1250 "ro_task={} vim={} del-sdn-net={}: {}".format(
1251 ro_task["_id"], ro_task["target_id"], sdn_vim_id, e
1252 ),
1253 exc_info=not isinstance(
1254 e, (sdnconn.SdnConnectorError, vimconn.VimConnException)
1255 ),
1256 )
1257 ro_vim_item_update = {
1258 "vim_status": "VIM_ERROR",
aticig79ac6df2022-05-06 16:09:52 +03001259 "vim_message": "Error while deleting: {}".format(e),
sousaedu80135b92021-02-17 15:05:18 +01001260 }
1261
tierno70eeb182020-10-19 16:38:00 +00001262 return "FAILED", ro_vim_item_update
1263
sousaedu80135b92021-02-17 15:05:18 +01001264 self.logger.debug(
1265 "task={} {} del-sdn-net={} {}".format(
1266 task_id,
1267 ro_task["target_id"],
1268 sdn_vim_id,
aticig79ac6df2022-05-06 16:09:52 +03001269 ro_vim_item_update_ok.get("vim_message", ""),
sousaedu80135b92021-02-17 15:05:18 +01001270 )
1271 )
1272
tierno70eeb182020-10-19 16:38:00 +00001273 return "DONE", ro_vim_item_update_ok
1274
1275
1276class NsWorker(threading.Thread):
1277 REFRESH_BUILD = 5 # 5 seconds
1278 REFRESH_ACTIVE = 60 # 1 minute
1279 REFRESH_ERROR = 600
1280 REFRESH_IMAGE = 3600 * 10
1281 REFRESH_DELETE = 3600 * 10
tiernof1b640f2020-12-09 15:06:01 +00001282 QUEUE_SIZE = 100
tierno70eeb182020-10-19 16:38:00 +00001283 terminate = False
tierno70eeb182020-10-19 16:38:00 +00001284
1285 def __init__(self, worker_index, config, plugins, db):
1286 """
1287
1288 :param worker_index: thread index
1289 :param config: general configuration of RO, among others the process_id with the docker id where it runs
1290 :param plugins: global shared dict with the loaded plugins
1291 :param db: database class instance to use
1292 """
1293 threading.Thread.__init__(self)
1294 self.config = config
1295 self.plugins = plugins
1296 self.plugin_name = "unknown"
sousaedu80135b92021-02-17 15:05:18 +01001297 self.logger = logging.getLogger("ro.worker{}".format(worker_index))
tierno70eeb182020-10-19 16:38:00 +00001298 self.worker_index = worker_index
1299 self.task_queue = queue.Queue(self.QUEUE_SIZE)
sousaedu80135b92021-02-17 15:05:18 +01001300 # targetvim: vimplugin class
1301 self.my_vims = {}
1302 # targetvim: vim information from database
1303 self.db_vims = {}
1304 # targetvim list
1305 self.vim_targets = []
tierno70eeb182020-10-19 16:38:00 +00001306 self.my_id = config["process_id"] + ":" + str(worker_index)
1307 self.db = db
1308 self.item2class = {
1309 "net": VimInteractionNet(self.db, self.my_vims, self.db_vims, self.logger),
1310 "vdu": VimInteractionVdu(self.db, self.my_vims, self.db_vims, self.logger),
sousaedu80135b92021-02-17 15:05:18 +01001311 "image": VimInteractionImage(
1312 self.db, self.my_vims, self.db_vims, self.logger
1313 ),
1314 "flavor": VimInteractionFlavor(
1315 self.db, self.my_vims, self.db_vims, self.logger
1316 ),
1317 "sdn_net": VimInteractionSdnNet(
1318 self.db, self.my_vims, self.db_vims, self.logger
1319 ),
Alexis Romerob70f4ed2022-03-11 18:00:49 +01001320 "affinity-or-anti-affinity-group": VimInteractionAffinityGroup(
1321 self.db, self.my_vims, self.db_vims, self.logger
1322 ),
tierno70eeb182020-10-19 16:38:00 +00001323 }
1324 self.time_last_task_processed = None
sousaedu80135b92021-02-17 15:05:18 +01001325 # lists of tasks to delete because nsrs or vnfrs has been deleted from db
1326 self.tasks_to_delete = []
1327 # it is idle when there are not vim_targets associated
1328 self.idle = True
tiernof1b640f2020-12-09 15:06:01 +00001329 self.task_locked_time = config["global"]["task_locked_time"]
tierno70eeb182020-10-19 16:38:00 +00001330
1331 def insert_task(self, task):
1332 try:
1333 self.task_queue.put(task, False)
1334 return None
1335 except queue.Full:
1336 raise NsWorkerException("timeout inserting a task")
1337
1338 def terminate(self):
1339 self.insert_task("exit")
1340
1341 def del_task(self, task):
1342 with self.task_lock:
1343 if task["status"] == "SCHEDULED":
1344 task["status"] = "SUPERSEDED"
1345 return True
1346 else: # task["status"] == "processing"
1347 self.task_lock.release()
1348 return False
1349
1350 def _process_vim_config(self, target_id, db_vim):
1351 """
1352 Process vim config, creating vim configuration files as ca_cert
1353 :param target_id: vim/sdn/wim + id
1354 :param db_vim: Vim dictionary obtained from database
1355 :return: None. Modifies vim. Creates a folder target_id:worker_index and several files
1356 """
1357 if not db_vim.get("config"):
1358 return
sousaedu80135b92021-02-17 15:05:18 +01001359
tierno70eeb182020-10-19 16:38:00 +00001360 file_name = ""
sousaedu80135b92021-02-17 15:05:18 +01001361
tierno70eeb182020-10-19 16:38:00 +00001362 try:
1363 if db_vim["config"].get("ca_cert_content"):
1364 file_name = "{}:{}".format(target_id, self.worker_index)
sousaedu80135b92021-02-17 15:05:18 +01001365
tierno70eeb182020-10-19 16:38:00 +00001366 try:
1367 mkdir(file_name)
1368 except FileExistsError:
1369 pass
sousaedu80135b92021-02-17 15:05:18 +01001370
tierno70eeb182020-10-19 16:38:00 +00001371 file_name = file_name + "/ca_cert"
sousaedu80135b92021-02-17 15:05:18 +01001372
tierno70eeb182020-10-19 16:38:00 +00001373 with open(file_name, "w") as f:
1374 f.write(db_vim["config"]["ca_cert_content"])
1375 del db_vim["config"]["ca_cert_content"]
1376 db_vim["config"]["ca_cert"] = file_name
1377 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001378 raise NsWorkerException(
1379 "Error writing to file '{}': {}".format(file_name, e)
1380 )
tierno70eeb182020-10-19 16:38:00 +00001381
1382 def _load_plugin(self, name, type="vim"):
1383 # type can be vim or sdn
1384 if "rovim_dummy" not in self.plugins:
1385 self.plugins["rovim_dummy"] = VimDummyConnector
sousaedu80135b92021-02-17 15:05:18 +01001386
tierno70eeb182020-10-19 16:38:00 +00001387 if "rosdn_dummy" not in self.plugins:
1388 self.plugins["rosdn_dummy"] = SdnDummyConnector
sousaedu80135b92021-02-17 15:05:18 +01001389
tierno70eeb182020-10-19 16:38:00 +00001390 if name in self.plugins:
1391 return self.plugins[name]
sousaedu80135b92021-02-17 15:05:18 +01001392
tierno70eeb182020-10-19 16:38:00 +00001393 try:
sousaedubecd0832021-04-08 00:16:18 +02001394 for ep in entry_points(group="osm_ro{}.plugins".format(type), name=name):
1395 self.plugins[name] = ep.load()
tierno70eeb182020-10-19 16:38:00 +00001396 except Exception as e:
1397 raise NsWorkerException("Cannot load plugin osm_{}: {}".format(name, e))
sousaedu80135b92021-02-17 15:05:18 +01001398
tierno70eeb182020-10-19 16:38:00 +00001399 if name and name not in self.plugins:
sousaedu80135b92021-02-17 15:05:18 +01001400 raise NsWorkerException(
1401 "Plugin 'osm_{n}' has not been installed".format(n=name)
1402 )
1403
tierno70eeb182020-10-19 16:38:00 +00001404 return self.plugins[name]
1405
1406 def _unload_vim(self, target_id):
1407 """
1408 Unload a vim_account. Removes it from self db_vims dictionary, my_vims dictionary and vim_targets list
1409 :param target_id: Contains type:_id; where type can be 'vim', ...
1410 :return: None.
1411 """
1412 try:
tierno70eeb182020-10-19 16:38:00 +00001413 self.db_vims.pop(target_id, None)
1414 self.my_vims.pop(target_id, None)
sousaedu80135b92021-02-17 15:05:18 +01001415
tierno86153522020-12-06 18:27:16 +00001416 if target_id in self.vim_targets:
1417 self.vim_targets.remove(target_id)
sousaedu80135b92021-02-17 15:05:18 +01001418
tierno86153522020-12-06 18:27:16 +00001419 self.logger.info("Unloaded {}".format(target_id))
tierno70eeb182020-10-19 16:38:00 +00001420 rmtree("{}:{}".format(target_id, self.worker_index))
1421 except FileNotFoundError:
1422 pass # this is raised by rmtree if folder does not exist
1423 except Exception as e:
1424 self.logger.error("Cannot unload {}: {}".format(target_id, e))
1425
1426 def _check_vim(self, target_id):
1427 """
1428 Load a VIM/SDN/WIM (if not loaded) and check connectivity, updating database with ENABLE or ERROR
1429 :param target_id: Contains type:_id; type can be 'vim', 'sdn' or 'wim'
1430 :return: None.
1431 """
1432 target, _, _id = target_id.partition(":")
1433 now = time.time()
1434 update_dict = {}
1435 unset_dict = {}
1436 op_text = ""
1437 step = ""
tierno86153522020-12-06 18:27:16 +00001438 loaded = target_id in self.vim_targets
sousaedu80135b92021-02-17 15:05:18 +01001439 target_database = (
1440 "vim_accounts"
1441 if target == "vim"
1442 else "wim_accounts"
1443 if target == "wim"
1444 else "sdns"
1445 )
1446
tierno70eeb182020-10-19 16:38:00 +00001447 try:
1448 step = "Getting {} from db".format(target_id)
1449 db_vim = self.db.get_one(target_database, {"_id": _id})
sousaedu80135b92021-02-17 15:05:18 +01001450
1451 for op_index, operation in enumerate(
1452 db_vim["_admin"].get("operations", ())
1453 ):
tierno70eeb182020-10-19 16:38:00 +00001454 if operation["operationState"] != "PROCESSING":
1455 continue
sousaedu80135b92021-02-17 15:05:18 +01001456
tierno70eeb182020-10-19 16:38:00 +00001457 locked_at = operation.get("locked_at")
sousaedu80135b92021-02-17 15:05:18 +01001458
tiernof1b640f2020-12-09 15:06:01 +00001459 if locked_at is not None and locked_at >= now - self.task_locked_time:
tierno70eeb182020-10-19 16:38:00 +00001460 # some other thread is doing this operation
1461 return
sousaedu80135b92021-02-17 15:05:18 +01001462
tierno70eeb182020-10-19 16:38:00 +00001463 # lock
1464 op_text = "_admin.operations.{}.".format(op_index)
sousaedu80135b92021-02-17 15:05:18 +01001465
1466 if not self.db.set_one(
1467 target_database,
1468 q_filter={
1469 "_id": _id,
1470 op_text + "operationState": "PROCESSING",
1471 op_text + "locked_at": locked_at,
1472 },
1473 update_dict={
1474 op_text + "locked_at": now,
1475 "admin.current_operation": op_index,
1476 },
1477 fail_on_empty=False,
1478 ):
tierno70eeb182020-10-19 16:38:00 +00001479 return
sousaedu80135b92021-02-17 15:05:18 +01001480
tierno70eeb182020-10-19 16:38:00 +00001481 unset_dict[op_text + "locked_at"] = None
1482 unset_dict["current_operation"] = None
1483 step = "Loading " + target_id
1484 error_text = self._load_vim(target_id)
sousaedu80135b92021-02-17 15:05:18 +01001485
tierno70eeb182020-10-19 16:38:00 +00001486 if not error_text:
1487 step = "Checking connectivity"
sousaedu80135b92021-02-17 15:05:18 +01001488
1489 if target == "vim":
tierno70eeb182020-10-19 16:38:00 +00001490 self.my_vims[target_id].check_vim_connectivity()
1491 else:
1492 self.my_vims[target_id].check_credentials()
sousaedu80135b92021-02-17 15:05:18 +01001493
tierno70eeb182020-10-19 16:38:00 +00001494 update_dict["_admin.operationalState"] = "ENABLED"
1495 update_dict["_admin.detailed-status"] = ""
1496 unset_dict[op_text + "detailed-status"] = None
1497 update_dict[op_text + "operationState"] = "COMPLETED"
sousaedu80135b92021-02-17 15:05:18 +01001498
tierno70eeb182020-10-19 16:38:00 +00001499 return
1500
1501 except Exception as e:
1502 error_text = "{}: {}".format(step, e)
1503 self.logger.error("{} for {}: {}".format(step, target_id, e))
1504
1505 finally:
1506 if update_dict or unset_dict:
1507 if error_text:
1508 update_dict[op_text + "operationState"] = "FAILED"
1509 update_dict[op_text + "detailed-status"] = error_text
1510 unset_dict.pop(op_text + "detailed-status", None)
1511 update_dict["_admin.operationalState"] = "ERROR"
1512 update_dict["_admin.detailed-status"] = error_text
sousaedu80135b92021-02-17 15:05:18 +01001513
tierno70eeb182020-10-19 16:38:00 +00001514 if op_text:
1515 update_dict[op_text + "statusEnteredTime"] = now
sousaedu80135b92021-02-17 15:05:18 +01001516
1517 self.db.set_one(
1518 target_database,
1519 q_filter={"_id": _id},
1520 update_dict=update_dict,
1521 unset=unset_dict,
1522 fail_on_empty=False,
1523 )
1524
tierno70eeb182020-10-19 16:38:00 +00001525 if not loaded:
1526 self._unload_vim(target_id)
1527
1528 def _reload_vim(self, target_id):
1529 if target_id in self.vim_targets:
1530 self._load_vim(target_id)
1531 else:
1532 # if the vim is not loaded, but database information of VIM is cached at self.db_vims,
1533 # just remove it to force load again next time it is needed
1534 self.db_vims.pop(target_id, None)
1535
1536 def _load_vim(self, target_id):
1537 """
1538 Load or reload a vim_account, sdn_controller or wim_account.
1539 Read content from database, load the plugin if not loaded.
1540 In case of error loading the plugin, it load a failing VIM_connector
1541 It fills self db_vims dictionary, my_vims dictionary and vim_targets list
1542 :param target_id: Contains type:_id; where type can be 'vim', ...
1543 :return: None if ok, descriptive text if error
1544 """
1545 target, _, _id = target_id.partition(":")
sousaedu80135b92021-02-17 15:05:18 +01001546 target_database = (
1547 "vim_accounts"
1548 if target == "vim"
1549 else "wim_accounts"
1550 if target == "wim"
1551 else "sdns"
1552 )
tierno70eeb182020-10-19 16:38:00 +00001553 plugin_name = ""
1554 vim = None
sousaedu80135b92021-02-17 15:05:18 +01001555
tierno70eeb182020-10-19 16:38:00 +00001556 try:
1557 step = "Getting {}={} from db".format(target, _id)
1558 # TODO process for wim, sdnc, ...
1559 vim = self.db.get_one(target_database, {"_id": _id})
1560
1561 # if deep_get(vim, "config", "sdn-controller"):
1562 # step = "Getting sdn-controller-id='{}' from db".format(vim["config"]["sdn-controller"])
1563 # db_sdn = self.db.get_one("sdns", {"_id": vim["config"]["sdn-controller"]})
1564
1565 step = "Decrypting password"
1566 schema_version = vim.get("schema_version")
sousaedu80135b92021-02-17 15:05:18 +01001567 self.db.encrypt_decrypt_fields(
1568 vim,
1569 "decrypt",
1570 fields=("password", "secret"),
1571 schema_version=schema_version,
1572 salt=_id,
1573 )
tierno70eeb182020-10-19 16:38:00 +00001574 self._process_vim_config(target_id, vim)
sousaedu80135b92021-02-17 15:05:18 +01001575
tierno70eeb182020-10-19 16:38:00 +00001576 if target == "vim":
1577 plugin_name = "rovim_" + vim["vim_type"]
1578 step = "Loading plugin '{}'".format(plugin_name)
1579 vim_module_conn = self._load_plugin(plugin_name)
1580 step = "Loading {}'".format(target_id)
1581 self.my_vims[target_id] = vim_module_conn(
sousaedu80135b92021-02-17 15:05:18 +01001582 uuid=vim["_id"],
1583 name=vim["name"],
1584 tenant_id=vim.get("vim_tenant_id"),
1585 tenant_name=vim.get("vim_tenant_name"),
1586 url=vim["vim_url"],
1587 url_admin=None,
1588 user=vim["vim_user"],
1589 passwd=vim["vim_password"],
1590 config=vim.get("config") or {},
1591 persistent_info={},
tierno70eeb182020-10-19 16:38:00 +00001592 )
1593 else: # sdn
1594 plugin_name = "rosdn_" + vim["type"]
1595 step = "Loading plugin '{}'".format(plugin_name)
1596 vim_module_conn = self._load_plugin(plugin_name, "sdn")
1597 step = "Loading {}'".format(target_id)
1598 wim = deepcopy(vim)
1599 wim_config = wim.pop("config", {}) or {}
1600 wim["uuid"] = wim["_id"]
1601 wim["wim_url"] = wim["url"]
sousaedu80135b92021-02-17 15:05:18 +01001602
tierno70eeb182020-10-19 16:38:00 +00001603 if wim.get("dpid"):
1604 wim_config["dpid"] = wim.pop("dpid")
sousaedu80135b92021-02-17 15:05:18 +01001605
tierno70eeb182020-10-19 16:38:00 +00001606 if wim.get("switch_id"):
1607 wim_config["switch_id"] = wim.pop("switch_id")
sousaedu80135b92021-02-17 15:05:18 +01001608
1609 # wim, wim_account, config
1610 self.my_vims[target_id] = vim_module_conn(wim, wim, wim_config)
tierno70eeb182020-10-19 16:38:00 +00001611 self.db_vims[target_id] = vim
1612 self.error_status = None
sousaedu80135b92021-02-17 15:05:18 +01001613
1614 self.logger.info(
1615 "Connector loaded for {}, plugin={}".format(target_id, plugin_name)
1616 )
tierno70eeb182020-10-19 16:38:00 +00001617 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001618 self.logger.error(
1619 "Cannot load {} plugin={}: {} {}".format(
1620 target_id, plugin_name, step, e
1621 )
1622 )
1623
tierno70eeb182020-10-19 16:38:00 +00001624 self.db_vims[target_id] = vim or {}
1625 self.db_vims[target_id] = FailingConnector(str(e))
1626 error_status = "{} Error: {}".format(step, e)
sousaedu80135b92021-02-17 15:05:18 +01001627
tierno70eeb182020-10-19 16:38:00 +00001628 return error_status
1629 finally:
1630 if target_id not in self.vim_targets:
1631 self.vim_targets.append(target_id)
1632
1633 def _get_db_task(self):
1634 """
1635 Read actions from database and reload them at memory. Fill self.refresh_list, pending_list, vim_actions
1636 :return: None
1637 """
1638 now = time.time()
sousaedu80135b92021-02-17 15:05:18 +01001639
tierno70eeb182020-10-19 16:38:00 +00001640 if not self.time_last_task_processed:
1641 self.time_last_task_processed = now
sousaedu80135b92021-02-17 15:05:18 +01001642
tierno70eeb182020-10-19 16:38:00 +00001643 try:
1644 while True:
gallardo2f4aaaa2022-01-31 16:50:48 +00001645 """
1646 # Log RO tasks only when loglevel is DEBUG
1647 if self.logger.getEffectiveLevel() == logging.DEBUG:
1648 self._log_ro_task(
1649 None,
1650 None,
1651 None,
1652 "TASK_WF",
1653 "task_locked_time="
1654 + str(self.task_locked_time)
1655 + " "
1656 + "time_last_task_processed="
1657 + str(self.time_last_task_processed)
1658 + " "
1659 + "now="
1660 + str(now),
1661 )
1662 """
tierno70eeb182020-10-19 16:38:00 +00001663 locked = self.db.set_one(
1664 "ro_tasks",
sousaedu80135b92021-02-17 15:05:18 +01001665 q_filter={
1666 "target_id": self.vim_targets,
1667 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
1668 "locked_at.lt": now - self.task_locked_time,
1669 "to_check_at.lt": self.time_last_task_processed,
1670 },
tierno70eeb182020-10-19 16:38:00 +00001671 update_dict={"locked_by": self.my_id, "locked_at": now},
sousaedu80135b92021-02-17 15:05:18 +01001672 fail_on_empty=False,
1673 )
1674
tierno70eeb182020-10-19 16:38:00 +00001675 if locked:
1676 # read and return
1677 ro_task = self.db.get_one(
1678 "ro_tasks",
sousaedu80135b92021-02-17 15:05:18 +01001679 q_filter={
1680 "target_id": self.vim_targets,
1681 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
1682 "locked_at": now,
1683 },
1684 )
tierno70eeb182020-10-19 16:38:00 +00001685 return ro_task
sousaedu80135b92021-02-17 15:05:18 +01001686
tierno70eeb182020-10-19 16:38:00 +00001687 if self.time_last_task_processed == now:
1688 self.time_last_task_processed = None
1689 return None
1690 else:
1691 self.time_last_task_processed = now
1692 # self.time_last_task_processed = min(self.time_last_task_processed + 1000, now)
1693
1694 except DbException as e:
1695 self.logger.error("Database exception at _get_db_task: {}".format(e))
1696 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001697 self.logger.critical(
1698 "Unexpected exception at _get_db_task: {}".format(e), exc_info=True
1699 )
1700
tierno70eeb182020-10-19 16:38:00 +00001701 return None
1702
gallardo2f4aaaa2022-01-31 16:50:48 +00001703 def _get_db_all_tasks(self):
1704 """
1705 Read all content of table ro_tasks to log it
1706 :return: None
1707 """
1708 try:
1709 # Checking the content of the BD:
1710
1711 # read and return
1712 ro_task = self.db.get_list("ro_tasks")
1713 for rt in ro_task:
1714 self._log_ro_task(rt, None, None, "TASK_WF", "GET_ALL_TASKS")
1715 return ro_task
1716
1717 except DbException as e:
1718 self.logger.error("Database exception at _get_db_all_tasks: {}".format(e))
1719 except Exception as e:
1720 self.logger.critical(
1721 "Unexpected exception at _get_db_all_tasks: {}".format(e), exc_info=True
1722 )
1723
1724 return None
1725
1726 def _log_ro_task(self, ro_task, db_ro_task_update, db_ro_task_delete, mark, event):
1727 """
1728 Generate a log with the following format:
1729
1730 Mark;Event;ro_task_id;locked_at;modified_at;created_at;to_check_at;locked_by;
1731 target_id;vim_info.refresh_at;vim_info;no_of_tasks;task_status;action_id;
1732 task_array_index;task_id;task_action;task_item;task_args
1733
1734 Example:
1735
1736 TASK_WF;GET_TASK;888f1864-749a-4fc2-bc1a-97c0fffd6a6f:2;1642158724.8210013;
1737 1642158640.7986135;1642158640.7986135;1642158640.7986135;b134c9494e75:0a
1738 ;vim:b7ff9e24-8868-4d68-8a57-a59dc11d0327;None;{'created': False,
1739 'created_items': None, 'vim_id': None, 'vim_name': None, 'vim_status': None,
aticig79ac6df2022-05-06 16:09:52 +03001740 'vim_details': None, 'vim_message': None, 'refresh_at': None};1;SCHEDULED;
gallardo2f4aaaa2022-01-31 16:50:48 +00001741 888f1864-749a-4fc2-bc1a-97c0fffd6a6f;0;888f1864-749a-4fc2-bc1a-97c0fffd6a6f:2;
1742 CREATE;image;{'filter_dict': {'name': 'ubuntu-os-cloud:image-family:ubuntu-1804-lts'}}
1743 """
1744 try:
1745 line = []
1746 i = 0
1747 if ro_task is not None and isinstance(ro_task, dict):
1748 for t in ro_task["tasks"]:
1749 line.clear()
1750 line.append(mark)
1751 line.append(event)
1752 line.append(ro_task.get("_id", ""))
1753 line.append(str(ro_task.get("locked_at", "")))
1754 line.append(str(ro_task.get("modified_at", "")))
1755 line.append(str(ro_task.get("created_at", "")))
1756 line.append(str(ro_task.get("to_check_at", "")))
1757 line.append(str(ro_task.get("locked_by", "")))
1758 line.append(str(ro_task.get("target_id", "")))
1759 line.append(str(ro_task.get("vim_info", {}).get("refresh_at", "")))
1760 line.append(str(ro_task.get("vim_info", "")))
1761 line.append(str(ro_task.get("tasks", "")))
1762 if isinstance(t, dict):
1763 line.append(str(t.get("status", "")))
1764 line.append(str(t.get("action_id", "")))
1765 line.append(str(i))
1766 line.append(str(t.get("task_id", "")))
1767 line.append(str(t.get("action", "")))
1768 line.append(str(t.get("item", "")))
1769 line.append(str(t.get("find_params", "")))
1770 line.append(str(t.get("params", "")))
1771 else:
1772 line.extend([""] * 2)
1773 line.append(str(i))
1774 line.extend([""] * 5)
1775
1776 i += 1
1777 self.logger.debug(";".join(line))
1778 elif db_ro_task_update is not None and isinstance(db_ro_task_update, dict):
1779 i = 0
1780 while True:
1781 st = "tasks.{}.status".format(i)
1782 if st not in db_ro_task_update:
1783 break
1784 line.clear()
1785 line.append(mark)
1786 line.append(event)
1787 line.append(db_ro_task_update.get("_id", ""))
1788 line.append(str(db_ro_task_update.get("locked_at", "")))
1789 line.append(str(db_ro_task_update.get("modified_at", "")))
1790 line.append("")
1791 line.append(str(db_ro_task_update.get("to_check_at", "")))
1792 line.append(str(db_ro_task_update.get("locked_by", "")))
1793 line.append("")
1794 line.append(str(db_ro_task_update.get("vim_info.refresh_at", "")))
1795 line.append("")
1796 line.append(str(db_ro_task_update.get("vim_info", "")))
1797 line.append(str(str(db_ro_task_update).count(".status")))
1798 line.append(db_ro_task_update.get(st, ""))
1799 line.append("")
1800 line.append(str(i))
1801 line.extend([""] * 3)
1802 i += 1
1803 self.logger.debug(";".join(line))
1804
1805 elif db_ro_task_delete is not None and isinstance(db_ro_task_delete, dict):
1806 line.clear()
1807 line.append(mark)
1808 line.append(event)
1809 line.append(db_ro_task_delete.get("_id", ""))
1810 line.append("")
1811 line.append(db_ro_task_delete.get("modified_at", ""))
1812 line.extend([""] * 13)
1813 self.logger.debug(";".join(line))
1814
1815 else:
1816 line.clear()
1817 line.append(mark)
1818 line.append(event)
1819 line.extend([""] * 16)
1820 self.logger.debug(";".join(line))
1821
1822 except Exception as e:
1823 self.logger.error("Error logging ro_task: {}".format(e))
1824
tierno70eeb182020-10-19 16:38:00 +00001825 def _delete_task(self, ro_task, task_index, task_depends, db_update):
1826 """
1827 Determine if this task need to be done or superseded
1828 :return: None
1829 """
1830 my_task = ro_task["tasks"][task_index]
1831 task_id = my_task["task_id"]
sousaedu80135b92021-02-17 15:05:18 +01001832 needed_delete = ro_task["vim_info"]["created"] or ro_task["vim_info"].get(
1833 "created_items", False
1834 )
1835
palaciosj8f2060b2022-02-24 12:05:59 +00001836 self.logger.warning("Needed delete: {}".format(needed_delete))
tierno70eeb182020-10-19 16:38:00 +00001837 if my_task["status"] == "FAILED":
1838 return None, None # TODO need to be retry??
sousaedu80135b92021-02-17 15:05:18 +01001839
tierno70eeb182020-10-19 16:38:00 +00001840 try:
1841 for index, task in enumerate(ro_task["tasks"]):
1842 if index == task_index or not task:
1843 continue # own task
sousaedu80135b92021-02-17 15:05:18 +01001844
1845 if (
1846 my_task["target_record"] == task["target_record"]
1847 and task["action"] == "CREATE"
1848 ):
tierno70eeb182020-10-19 16:38:00 +00001849 # set to finished
sousaedu80135b92021-02-17 15:05:18 +01001850 db_update["tasks.{}.status".format(index)] = task[
1851 "status"
1852 ] = "FINISHED"
1853 elif task["action"] == "CREATE" and task["status"] not in (
1854 "FINISHED",
1855 "SUPERSEDED",
1856 ):
tierno70eeb182020-10-19 16:38:00 +00001857 needed_delete = False
sousaedu80135b92021-02-17 15:05:18 +01001858
tierno70eeb182020-10-19 16:38:00 +00001859 if needed_delete:
aticig285185e2022-05-02 21:23:48 +03001860 self.logger.warning(
1861 "Deleting ro_task={} task_index={}".format(ro_task, task_index)
1862 )
tierno70eeb182020-10-19 16:38:00 +00001863 return self.item2class[my_task["item"]].delete(ro_task, task_index)
1864 else:
1865 return "SUPERSEDED", None
1866 except Exception as e:
1867 if not isinstance(e, NsWorkerException):
sousaedu80135b92021-02-17 15:05:18 +01001868 self.logger.critical(
1869 "Unexpected exception at _delete_task task={}: {}".format(
1870 task_id, e
1871 ),
1872 exc_info=True,
1873 )
1874
aticig79ac6df2022-05-06 16:09:52 +03001875 return "FAILED", {"vim_status": "VIM_ERROR", "vim_message": str(e)}
tierno70eeb182020-10-19 16:38:00 +00001876
1877 def _create_task(self, ro_task, task_index, task_depends, db_update):
1878 """
1879 Determine if this task need to create something at VIM
1880 :return: None
1881 """
1882 my_task = ro_task["tasks"][task_index]
1883 task_id = my_task["task_id"]
1884 task_status = None
sousaedu80135b92021-02-17 15:05:18 +01001885
tierno70eeb182020-10-19 16:38:00 +00001886 if my_task["status"] == "FAILED":
1887 return None, None # TODO need to be retry??
1888 elif my_task["status"] == "SCHEDULED":
1889 # check if already created by another task
1890 for index, task in enumerate(ro_task["tasks"]):
1891 if index == task_index or not task:
1892 continue # own task
sousaedu80135b92021-02-17 15:05:18 +01001893
1894 if task["action"] == "CREATE" and task["status"] not in (
1895 "SCHEDULED",
1896 "FINISHED",
1897 "SUPERSEDED",
1898 ):
tierno70eeb182020-10-19 16:38:00 +00001899 return task["status"], "COPY_VIM_INFO"
1900
1901 try:
1902 task_status, ro_vim_item_update = self.item2class[my_task["item"]].new(
sousaedu80135b92021-02-17 15:05:18 +01001903 ro_task, task_index, task_depends
1904 )
tierno70eeb182020-10-19 16:38:00 +00001905 # TODO update other CREATE tasks
1906 except Exception as e:
1907 if not isinstance(e, NsWorkerException):
sousaedu80135b92021-02-17 15:05:18 +01001908 self.logger.error(
1909 "Error executing task={}: {}".format(task_id, e), exc_info=True
1910 )
1911
tierno70eeb182020-10-19 16:38:00 +00001912 task_status = "FAILED"
aticig79ac6df2022-05-06 16:09:52 +03001913 ro_vim_item_update = {"vim_status": "VIM_ERROR", "vim_message": str(e)}
tierno70eeb182020-10-19 16:38:00 +00001914 # TODO update ro_vim_item_update
sousaedu80135b92021-02-17 15:05:18 +01001915
tierno70eeb182020-10-19 16:38:00 +00001916 return task_status, ro_vim_item_update
1917 else:
1918 return None, None
1919
1920 def _get_dependency(self, task_id, ro_task=None, target_id=None):
1921 """
1922 Look for dependency task
1923 :param task_id: Can be one of
1924 1. target_vim+blank+task.target_record_id: "(vim|sdn|wim):<id> (vnfrs|nsrs):(vld|vdu|flavor|image).<id>"
1925 2. task.target_record_id: "(vnfrs|nsrs):(vld|vdu|flavor|image).<id>"
1926 3. task.task_id: "<action_id>:number"
1927 :param ro_task:
1928 :param target_id:
1929 :return: database ro_task plus index of task
1930 """
sousaedu80135b92021-02-17 15:05:18 +01001931 if (
1932 task_id.startswith("vim:")
1933 or task_id.startswith("sdn:")
1934 or task_id.startswith("wim:")
1935 ):
tierno70eeb182020-10-19 16:38:00 +00001936 target_id, _, task_id = task_id.partition(" ")
1937
1938 if task_id.startswith("nsrs:") or task_id.startswith("vnfrs:"):
1939 ro_task_dependency = self.db.get_one(
1940 "ro_tasks",
sousaedu80135b92021-02-17 15:05:18 +01001941 q_filter={"target_id": target_id, "tasks.target_record_id": task_id},
1942 fail_on_empty=False,
1943 )
1944
tierno70eeb182020-10-19 16:38:00 +00001945 if ro_task_dependency:
1946 for task_index, task in enumerate(ro_task_dependency["tasks"]):
1947 if task["target_record_id"] == task_id:
1948 return ro_task_dependency, task_index
1949
1950 else:
1951 if ro_task:
1952 for task_index, task in enumerate(ro_task["tasks"]):
1953 if task and task["task_id"] == task_id:
1954 return ro_task, task_index
sousaedu80135b92021-02-17 15:05:18 +01001955
tierno70eeb182020-10-19 16:38:00 +00001956 ro_task_dependency = self.db.get_one(
1957 "ro_tasks",
sousaedu80135b92021-02-17 15:05:18 +01001958 q_filter={
1959 "tasks.ANYINDEX.task_id": task_id,
1960 "tasks.ANYINDEX.target_record.ne": None,
1961 },
1962 fail_on_empty=False,
1963 )
1964
palaciosj8f2060b2022-02-24 12:05:59 +00001965 self.logger.warning("ro_task_dependency={}".format(ro_task_dependency))
tierno70eeb182020-10-19 16:38:00 +00001966 if ro_task_dependency:
palaciosj8f2060b2022-02-24 12:05:59 +00001967 for task_index, task in enumerate(ro_task_dependency["tasks"]):
tierno70eeb182020-10-19 16:38:00 +00001968 if task["task_id"] == task_id:
1969 return ro_task_dependency, task_index
1970 raise NsWorkerException("Cannot get depending task {}".format(task_id))
1971
1972 def _process_pending_tasks(self, ro_task):
1973 ro_task_id = ro_task["_id"]
1974 now = time.time()
sousaedu80135b92021-02-17 15:05:18 +01001975 # one day
1976 next_check_at = now + (24 * 60 * 60)
tierno70eeb182020-10-19 16:38:00 +00001977 db_ro_task_update = {}
1978
1979 def _update_refresh(new_status):
1980 # compute next_refresh
1981 nonlocal task
1982 nonlocal next_check_at
1983 nonlocal db_ro_task_update
1984 nonlocal ro_task
1985
1986 next_refresh = time.time()
sousaedu80135b92021-02-17 15:05:18 +01001987
tierno70eeb182020-10-19 16:38:00 +00001988 if task["item"] in ("image", "flavor"):
1989 next_refresh += self.REFRESH_IMAGE
1990 elif new_status == "BUILD":
1991 next_refresh += self.REFRESH_BUILD
1992 elif new_status == "DONE":
1993 next_refresh += self.REFRESH_ACTIVE
1994 else:
1995 next_refresh += self.REFRESH_ERROR
sousaedu80135b92021-02-17 15:05:18 +01001996
tierno70eeb182020-10-19 16:38:00 +00001997 next_check_at = min(next_check_at, next_refresh)
1998 db_ro_task_update["vim_info.refresh_at"] = next_refresh
1999 ro_task["vim_info"]["refresh_at"] = next_refresh
2000
2001 try:
gallardo2f4aaaa2022-01-31 16:50:48 +00002002 """
2003 # Log RO tasks only when loglevel is DEBUG
2004 if self.logger.getEffectiveLevel() == logging.DEBUG:
2005 self._log_ro_task(ro_task, None, None, "TASK_WF", "GET_TASK")
2006 """
tiernof1b640f2020-12-09 15:06:01 +00002007 # 0: get task_status_create
2008 lock_object = None
tierno70eeb182020-10-19 16:38:00 +00002009 task_status_create = None
sousaedu80135b92021-02-17 15:05:18 +01002010 task_create = next(
2011 (
2012 t
2013 for t in ro_task["tasks"]
2014 if t
2015 and t["action"] == "CREATE"
2016 and t["status"] in ("BUILD", "DONE")
2017 ),
2018 None,
2019 )
2020
tierno70eeb182020-10-19 16:38:00 +00002021 if task_create:
2022 task_status_create = task_create["status"]
sousaedu80135b92021-02-17 15:05:18 +01002023
tiernof1b640f2020-12-09 15:06:01 +00002024 # 1: look for tasks in status SCHEDULED, or in status CREATE if action is DONE or BUILD
tierno70eeb182020-10-19 16:38:00 +00002025 for task_action in ("DELETE", "CREATE", "EXEC"):
2026 db_vim_update = None
2027 new_status = None
sousaedu80135b92021-02-17 15:05:18 +01002028
tierno70eeb182020-10-19 16:38:00 +00002029 for task_index, task in enumerate(ro_task["tasks"]):
2030 if not task:
2031 continue # task deleted
sousaedu80135b92021-02-17 15:05:18 +01002032
tierno55fa0bb2020-12-08 23:11:53 +00002033 task_depends = {}
tierno70eeb182020-10-19 16:38:00 +00002034 target_update = None
sousaedu80135b92021-02-17 15:05:18 +01002035
2036 if (
2037 (
2038 task_action in ("DELETE", "EXEC")
2039 and task["status"] not in ("SCHEDULED", "BUILD")
2040 )
2041 or task["action"] != task_action
2042 or (
2043 task_action == "CREATE"
2044 and task["status"] in ("FINISHED", "SUPERSEDED")
2045 )
2046 ):
tierno70eeb182020-10-19 16:38:00 +00002047 continue
sousaedu80135b92021-02-17 15:05:18 +01002048
tierno70eeb182020-10-19 16:38:00 +00002049 task_path = "tasks.{}.status".format(task_index)
2050 try:
2051 db_vim_info_update = None
sousaedu80135b92021-02-17 15:05:18 +01002052
tierno70eeb182020-10-19 16:38:00 +00002053 if task["status"] == "SCHEDULED":
tierno70eeb182020-10-19 16:38:00 +00002054 # check if tasks that this depends on have been completed
2055 dependency_not_completed = False
sousaedu80135b92021-02-17 15:05:18 +01002056
2057 for dependency_task_id in task.get("depends_on") or ():
2058 (
2059 dependency_ro_task,
2060 dependency_task_index,
2061 ) = self._get_dependency(
2062 dependency_task_id, target_id=ro_task["target_id"]
2063 )
2064 dependency_task = dependency_ro_task["tasks"][
2065 dependency_task_index
2066 ]
aticig285185e2022-05-02 21:23:48 +03002067 self.logger.warning(
2068 "dependency_ro_task={} dependency_task_index={}".format(
2069 dependency_ro_task, dependency_task_index
2070 )
2071 )
sousaedu80135b92021-02-17 15:05:18 +01002072
tierno70eeb182020-10-19 16:38:00 +00002073 if dependency_task["status"] == "SCHEDULED":
2074 dependency_not_completed = True
sousaedu80135b92021-02-17 15:05:18 +01002075 next_check_at = min(
2076 next_check_at, dependency_ro_task["to_check_at"]
2077 )
lloretgalleg88486222021-02-19 12:06:52 +00002078 # must allow dependent task to be processed first
2079 # to do this set time after last_task_processed
2080 next_check_at = max(
2081 self.time_last_task_processed, next_check_at
2082 )
tierno70eeb182020-10-19 16:38:00 +00002083 break
2084 elif dependency_task["status"] == "FAILED":
2085 error_text = "Cannot {} {} because depends on failed {} {} id={}): {}".format(
sousaedu80135b92021-02-17 15:05:18 +01002086 task["action"],
2087 task["item"],
2088 dependency_task["action"],
2089 dependency_task["item"],
2090 dependency_task_id,
2091 dependency_ro_task["vim_info"].get(
aticig79ac6df2022-05-06 16:09:52 +03002092 "vim_message"
sousaedu80135b92021-02-17 15:05:18 +01002093 ),
2094 )
2095 self.logger.error(
2096 "task={} {}".format(task["task_id"], error_text)
2097 )
tierno70eeb182020-10-19 16:38:00 +00002098 raise NsWorkerException(error_text)
2099
sousaedu80135b92021-02-17 15:05:18 +01002100 task_depends[dependency_task_id] = dependency_ro_task[
2101 "vim_info"
2102 ]["vim_id"]
2103 task_depends[
2104 "TASK-{}".format(dependency_task_id)
2105 ] = dependency_ro_task["vim_info"]["vim_id"]
2106
tierno70eeb182020-10-19 16:38:00 +00002107 if dependency_not_completed:
aticig285185e2022-05-02 21:23:48 +03002108 self.logger.warning(
2109 "DEPENDENCY NOT COMPLETED {}".format(
2110 dependency_ro_task["vim_info"]["vim_id"]
2111 )
2112 )
tierno70eeb182020-10-19 16:38:00 +00002113 # TODO set at vim_info.vim_details that it is waiting
2114 continue
sousaedu80135b92021-02-17 15:05:18 +01002115
tiernof1b640f2020-12-09 15:06:01 +00002116 # before calling VIM-plugin as it can take more than task_locked_time, insert to LockRenew
2117 # the task of renew this locking. It will update database locket_at periodically
2118 if not lock_object:
sousaedu80135b92021-02-17 15:05:18 +01002119 lock_object = LockRenew.add_lock_object(
2120 "ro_tasks", ro_task, self
2121 )
2122
tierno70eeb182020-10-19 16:38:00 +00002123 if task["action"] == "DELETE":
sousaedu80135b92021-02-17 15:05:18 +01002124 (new_status, db_vim_info_update,) = self._delete_task(
2125 ro_task, task_index, task_depends, db_ro_task_update
2126 )
2127 new_status = (
2128 "FINISHED" if new_status == "DONE" else new_status
2129 )
tierno70eeb182020-10-19 16:38:00 +00002130 # ^with FINISHED instead of DONE it will not be refreshing
sousaedu80135b92021-02-17 15:05:18 +01002131
tierno70eeb182020-10-19 16:38:00 +00002132 if new_status in ("FINISHED", "SUPERSEDED"):
2133 target_update = "DELETE"
2134 elif task["action"] == "EXEC":
sousaedu80135b92021-02-17 15:05:18 +01002135 (
2136 new_status,
2137 db_vim_info_update,
2138 db_task_update,
2139 ) = self.item2class[task["item"]].exec(
2140 ro_task, task_index, task_depends
2141 )
2142 new_status = (
2143 "FINISHED" if new_status == "DONE" else new_status
2144 )
tierno70eeb182020-10-19 16:38:00 +00002145 # ^with FINISHED instead of DONE it will not be refreshing
sousaedu80135b92021-02-17 15:05:18 +01002146
tierno70eeb182020-10-19 16:38:00 +00002147 if db_task_update:
2148 # load into database the modified db_task_update "retries" and "next_retry"
2149 if db_task_update.get("retries"):
sousaedu80135b92021-02-17 15:05:18 +01002150 db_ro_task_update[
2151 "tasks.{}.retries".format(task_index)
2152 ] = db_task_update["retries"]
2153
2154 next_check_at = time.time() + db_task_update.get(
2155 "next_retry", 60
2156 )
tierno70eeb182020-10-19 16:38:00 +00002157 target_update = None
2158 elif task["action"] == "CREATE":
2159 if task["status"] == "SCHEDULED":
2160 if task_status_create:
2161 new_status = task_status_create
2162 target_update = "COPY_VIM_INFO"
2163 else:
sousaedu80135b92021-02-17 15:05:18 +01002164 new_status, db_vim_info_update = self.item2class[
2165 task["item"]
2166 ].new(ro_task, task_index, task_depends)
tierno70eeb182020-10-19 16:38:00 +00002167 # self._create_task(ro_task, task_index, task_depends, db_ro_task_update)
2168 _update_refresh(new_status)
2169 else:
sousaedu80135b92021-02-17 15:05:18 +01002170 if (
2171 ro_task["vim_info"]["refresh_at"]
2172 and now > ro_task["vim_info"]["refresh_at"]
2173 ):
2174 new_status, db_vim_info_update = self.item2class[
2175 task["item"]
2176 ].refresh(ro_task)
tierno70eeb182020-10-19 16:38:00 +00002177 _update_refresh(new_status)
gallardo7788f692022-01-20 09:07:08 +00002178 else:
2179 # The refresh is updated to avoid set the value of "refresh_at" to
2180 # default value (next_check_at = now + (24 * 60 * 60)) when status is BUILD,
2181 # because it can happen that in this case the task is never processed
2182 _update_refresh(task["status"])
sousaedu80135b92021-02-17 15:05:18 +01002183
tierno70eeb182020-10-19 16:38:00 +00002184 except Exception as e:
2185 new_status = "FAILED"
sousaedu80135b92021-02-17 15:05:18 +01002186 db_vim_info_update = {
2187 "vim_status": "VIM_ERROR",
aticig79ac6df2022-05-06 16:09:52 +03002188 "vim_message": str(e),
sousaedu80135b92021-02-17 15:05:18 +01002189 }
2190
2191 if not isinstance(
2192 e, (NsWorkerException, vimconn.VimConnException)
2193 ):
2194 self.logger.error(
2195 "Unexpected exception at _delete_task task={}: {}".format(
2196 task["task_id"], e
2197 ),
2198 exc_info=True,
2199 )
tierno70eeb182020-10-19 16:38:00 +00002200
2201 try:
2202 if db_vim_info_update:
2203 db_vim_update = db_vim_info_update.copy()
sousaedu80135b92021-02-17 15:05:18 +01002204 db_ro_task_update.update(
2205 {
2206 "vim_info." + k: v
2207 for k, v in db_vim_info_update.items()
2208 }
2209 )
tierno70eeb182020-10-19 16:38:00 +00002210 ro_task["vim_info"].update(db_vim_info_update)
2211
2212 if new_status:
2213 if task_action == "CREATE":
2214 task_status_create = new_status
2215 db_ro_task_update[task_path] = new_status
tierno70eeb182020-10-19 16:38:00 +00002216
sousaedu80135b92021-02-17 15:05:18 +01002217 if target_update or db_vim_update:
tierno70eeb182020-10-19 16:38:00 +00002218 if target_update == "DELETE":
2219 self._update_target(task, None)
2220 elif target_update == "COPY_VIM_INFO":
2221 self._update_target(task, ro_task["vim_info"])
2222 else:
2223 self._update_target(task, db_vim_update)
2224
2225 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002226 if (
2227 isinstance(e, DbException)
2228 and e.http_code == HTTPStatus.NOT_FOUND
2229 ):
tierno70eeb182020-10-19 16:38:00 +00002230 # if the vnfrs or nsrs has been removed from database, this task must be removed
sousaedu80135b92021-02-17 15:05:18 +01002231 self.logger.debug(
2232 "marking to delete task={}".format(task["task_id"])
2233 )
tierno70eeb182020-10-19 16:38:00 +00002234 self.tasks_to_delete.append(task)
2235 else:
sousaedu80135b92021-02-17 15:05:18 +01002236 self.logger.error(
2237 "Unexpected exception at _update_target task={}: {}".format(
2238 task["task_id"], e
2239 ),
2240 exc_info=True,
2241 )
tierno70eeb182020-10-19 16:38:00 +00002242
tiernof1b640f2020-12-09 15:06:01 +00002243 locked_at = ro_task["locked_at"]
sousaedu80135b92021-02-17 15:05:18 +01002244
tiernof1b640f2020-12-09 15:06:01 +00002245 if lock_object:
sousaedu80135b92021-02-17 15:05:18 +01002246 locked_at = [
2247 lock_object["locked_at"],
2248 lock_object["locked_at"] + self.task_locked_time,
2249 ]
tiernof1b640f2020-12-09 15:06:01 +00002250 # locked_at contains two times to avoid race condition. In case the lock has been renew, it will
2251 # contain exactly locked_at + self.task_locked_time
2252 LockRenew.remove_lock_object(lock_object)
sousaedu80135b92021-02-17 15:05:18 +01002253
2254 q_filter = {
2255 "_id": ro_task["_id"],
2256 "to_check_at": ro_task["to_check_at"],
2257 "locked_at": locked_at,
2258 }
tierno70eeb182020-10-19 16:38:00 +00002259 # modify own task. Try filtering by to_next_check. For race condition if to_check_at has been modified,
2260 # outside this task (by ro_nbi) do not update it
2261 db_ro_task_update["locked_by"] = None
2262 # locked_at converted to int only for debugging. When has not decimals it means it has been unlocked
tiernof1b640f2020-12-09 15:06:01 +00002263 db_ro_task_update["locked_at"] = int(now - self.task_locked_time)
2264 db_ro_task_update["modified_at"] = now
tierno70eeb182020-10-19 16:38:00 +00002265 db_ro_task_update["to_check_at"] = next_check_at
sousaedu80135b92021-02-17 15:05:18 +01002266
gallardo2f4aaaa2022-01-31 16:50:48 +00002267 """
2268 # Log RO tasks only when loglevel is DEBUG
2269 if self.logger.getEffectiveLevel() == logging.DEBUG:
2270 db_ro_task_update_log = db_ro_task_update.copy()
2271 db_ro_task_update_log["_id"] = q_filter["_id"]
2272 self._log_ro_task(None, db_ro_task_update_log, None, "TASK_WF", "SET_TASK")
2273 """
2274
sousaedu80135b92021-02-17 15:05:18 +01002275 if not self.db.set_one(
2276 "ro_tasks",
2277 update_dict=db_ro_task_update,
2278 q_filter=q_filter,
2279 fail_on_empty=False,
2280 ):
tierno70eeb182020-10-19 16:38:00 +00002281 del db_ro_task_update["to_check_at"]
2282 del q_filter["to_check_at"]
gallardo2f4aaaa2022-01-31 16:50:48 +00002283 """
2284 # Log RO tasks only when loglevel is DEBUG
2285 if self.logger.getEffectiveLevel() == logging.DEBUG:
2286 self._log_ro_task(
2287 None,
2288 db_ro_task_update_log,
2289 None,
2290 "TASK_WF",
2291 "SET_TASK " + str(q_filter),
2292 )
2293 """
sousaedu80135b92021-02-17 15:05:18 +01002294 self.db.set_one(
2295 "ro_tasks",
2296 q_filter=q_filter,
2297 update_dict=db_ro_task_update,
2298 fail_on_empty=True,
2299 )
tierno70eeb182020-10-19 16:38:00 +00002300 except DbException as e:
sousaedu80135b92021-02-17 15:05:18 +01002301 self.logger.error(
2302 "ro_task={} Error updating database {}".format(ro_task_id, e)
2303 )
tierno70eeb182020-10-19 16:38:00 +00002304 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002305 self.logger.error(
2306 "Error executing ro_task={}: {}".format(ro_task_id, e), exc_info=True
2307 )
tierno70eeb182020-10-19 16:38:00 +00002308
2309 def _update_target(self, task, ro_vim_item_update):
2310 table, _, temp = task["target_record"].partition(":")
2311 _id, _, path_vim_status = temp.partition(":")
sousaedu80135b92021-02-17 15:05:18 +01002312 path_item = path_vim_status[: path_vim_status.rfind(".")]
2313 path_item = path_item[: path_item.rfind(".")]
tierno70eeb182020-10-19 16:38:00 +00002314 # path_vim_status: dot separated list targeting vim information, e.g. "vdur.10.vim_info.vim:id"
2315 # path_item: dot separated list targeting record information, e.g. "vdur.10"
sousaedu80135b92021-02-17 15:05:18 +01002316
tierno70eeb182020-10-19 16:38:00 +00002317 if ro_vim_item_update:
sousaedu80135b92021-02-17 15:05:18 +01002318 update_dict = {
2319 path_vim_status + "." + k: v
2320 for k, v in ro_vim_item_update.items()
2321 if k
aticig79ac6df2022-05-06 16:09:52 +03002322 in (
2323 "vim_id",
2324 "vim_details",
2325 "vim_message",
2326 "vim_name",
2327 "vim_status",
2328 "interfaces",
2329 )
sousaedu80135b92021-02-17 15:05:18 +01002330 }
2331
tierno70eeb182020-10-19 16:38:00 +00002332 if path_vim_status.startswith("vdur."):
2333 # for backward compatibility, add vdur.name apart from vdur.vim_name
2334 if ro_vim_item_update.get("vim_name"):
2335 update_dict[path_item + ".name"] = ro_vim_item_update["vim_name"]
sousaedu80135b92021-02-17 15:05:18 +01002336
tierno70eeb182020-10-19 16:38:00 +00002337 # for backward compatibility, add vdur.vim-id apart from vdur.vim_id
2338 if ro_vim_item_update.get("vim_id"):
2339 update_dict[path_item + ".vim-id"] = ro_vim_item_update["vim_id"]
sousaedu80135b92021-02-17 15:05:18 +01002340
tierno70eeb182020-10-19 16:38:00 +00002341 # update general status
2342 if ro_vim_item_update.get("vim_status"):
sousaedu80135b92021-02-17 15:05:18 +01002343 update_dict[path_item + ".status"] = ro_vim_item_update[
2344 "vim_status"
2345 ]
2346
tierno70eeb182020-10-19 16:38:00 +00002347 if ro_vim_item_update.get("interfaces"):
2348 path_interfaces = path_item + ".interfaces"
sousaedu80135b92021-02-17 15:05:18 +01002349
tierno70eeb182020-10-19 16:38:00 +00002350 for i, iface in enumerate(ro_vim_item_update.get("interfaces")):
2351 if iface:
sousaedu80135b92021-02-17 15:05:18 +01002352 update_dict.update(
2353 {
2354 path_interfaces + ".{}.".format(i) + k: v
2355 for k, v in iface.items()
2356 if k in ("vlan", "compute_node", "pci")
2357 }
2358 )
2359
tierno70eeb182020-10-19 16:38:00 +00002360 # put ip_address and mac_address with ip-address and mac-address
sousaedu80135b92021-02-17 15:05:18 +01002361 if iface.get("ip_address"):
2362 update_dict[
2363 path_interfaces + ".{}.".format(i) + "ip-address"
2364 ] = iface["ip_address"]
2365
2366 if iface.get("mac_address"):
2367 update_dict[
2368 path_interfaces + ".{}.".format(i) + "mac-address"
2369 ] = iface["mac_address"]
2370
tierno70eeb182020-10-19 16:38:00 +00002371 if iface.get("mgmt_vnf_interface") and iface.get("ip_address"):
sousaedu80135b92021-02-17 15:05:18 +01002372 update_dict["ip-address"] = iface.get("ip_address").split(
2373 ";"
2374 )[0]
2375
tierno70eeb182020-10-19 16:38:00 +00002376 if iface.get("mgmt_vdu_interface") and iface.get("ip_address"):
sousaedu80135b92021-02-17 15:05:18 +01002377 update_dict[path_item + ".ip-address"] = iface.get(
2378 "ip_address"
2379 ).split(";")[0]
tierno70eeb182020-10-19 16:38:00 +00002380
2381 self.db.set_one(table, q_filter={"_id": _id}, update_dict=update_dict)
2382 else:
2383 update_dict = {path_item + ".status": "DELETED"}
sousaedu80135b92021-02-17 15:05:18 +01002384 self.db.set_one(
2385 table,
2386 q_filter={"_id": _id},
2387 update_dict=update_dict,
2388 unset={path_vim_status: None},
2389 )
tierno70eeb182020-10-19 16:38:00 +00002390
2391 def _process_delete_db_tasks(self):
2392 """
2393 Delete task from database because vnfrs or nsrs or both have been deleted
2394 :return: None. Uses and modify self.tasks_to_delete
2395 """
2396 while self.tasks_to_delete:
2397 task = self.tasks_to_delete[0]
2398 vnfrs_deleted = None
2399 nsr_id = task["nsr_id"]
sousaedu80135b92021-02-17 15:05:18 +01002400
tierno70eeb182020-10-19 16:38:00 +00002401 if task["target_record"].startswith("vnfrs:"):
2402 # check if nsrs is present
2403 if self.db.get_one("nsrs", {"_id": nsr_id}, fail_on_empty=False):
2404 vnfrs_deleted = task["target_record"].split(":")[1]
sousaedu80135b92021-02-17 15:05:18 +01002405
tierno70eeb182020-10-19 16:38:00 +00002406 try:
2407 self.delete_db_tasks(self.db, nsr_id, vnfrs_deleted)
2408 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002409 self.logger.error(
2410 "Error deleting task={}: {}".format(task["task_id"], e)
2411 )
tierno70eeb182020-10-19 16:38:00 +00002412 self.tasks_to_delete.pop(0)
2413
2414 @staticmethod
2415 def delete_db_tasks(db, nsr_id, vnfrs_deleted):
2416 """
2417 Static method because it is called from osm_ng_ro.ns
2418 :param db: instance of database to use
2419 :param nsr_id: affected nsrs id
2420 :param vnfrs_deleted: only tasks with this vnfr id. If None, all affected by nsr_id
2421 :return: None, exception is fails
2422 """
2423 retries = 5
2424 for retry in range(retries):
2425 ro_tasks = db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2426 now = time.time()
2427 conflict = False
sousaedu80135b92021-02-17 15:05:18 +01002428
tierno70eeb182020-10-19 16:38:00 +00002429 for ro_task in ro_tasks:
2430 db_update = {}
2431 to_delete_ro_task = True
sousaedu80135b92021-02-17 15:05:18 +01002432
tierno70eeb182020-10-19 16:38:00 +00002433 for index, task in enumerate(ro_task["tasks"]):
2434 if not task:
2435 pass
sousaedu80135b92021-02-17 15:05:18 +01002436 elif (not vnfrs_deleted and task["nsr_id"] == nsr_id) or (
2437 vnfrs_deleted
2438 and task["target_record"].startswith("vnfrs:" + vnfrs_deleted)
2439 ):
tierno70eeb182020-10-19 16:38:00 +00002440 db_update["tasks.{}".format(index)] = None
2441 else:
sousaedu80135b92021-02-17 15:05:18 +01002442 # used by other nsr, ro_task cannot be deleted
2443 to_delete_ro_task = False
2444
tierno70eeb182020-10-19 16:38:00 +00002445 # delete or update if nobody has changed ro_task meanwhile. Used modified_at for known if changed
2446 if to_delete_ro_task:
sousaedu80135b92021-02-17 15:05:18 +01002447 if not db.del_one(
2448 "ro_tasks",
2449 q_filter={
2450 "_id": ro_task["_id"],
2451 "modified_at": ro_task["modified_at"],
2452 },
2453 fail_on_empty=False,
2454 ):
tierno70eeb182020-10-19 16:38:00 +00002455 conflict = True
2456 elif db_update:
2457 db_update["modified_at"] = now
sousaedu80135b92021-02-17 15:05:18 +01002458 if not db.set_one(
2459 "ro_tasks",
2460 q_filter={
2461 "_id": ro_task["_id"],
2462 "modified_at": ro_task["modified_at"],
2463 },
2464 update_dict=db_update,
2465 fail_on_empty=False,
2466 ):
tierno70eeb182020-10-19 16:38:00 +00002467 conflict = True
2468 if not conflict:
2469 return
2470 else:
2471 raise NsWorkerException("Exceeded {} retries".format(retries))
2472
tierno1d213f42020-04-24 14:02:51 +00002473 def run(self):
2474 # load database
tierno86153522020-12-06 18:27:16 +00002475 self.logger.info("Starting")
tierno1d213f42020-04-24 14:02:51 +00002476 while True:
tierno70eeb182020-10-19 16:38:00 +00002477 # step 1: get commands from queue
tierno1d213f42020-04-24 14:02:51 +00002478 try:
tierno86153522020-12-06 18:27:16 +00002479 if self.vim_targets:
2480 task = self.task_queue.get(block=False)
2481 else:
2482 if not self.idle:
2483 self.logger.debug("enters in idle state")
2484 self.idle = True
2485 task = self.task_queue.get(block=True)
2486 self.idle = False
2487
tierno1d213f42020-04-24 14:02:51 +00002488 if task[0] == "terminate":
2489 break
tierno70eeb182020-10-19 16:38:00 +00002490 elif task[0] == "load_vim":
tierno86153522020-12-06 18:27:16 +00002491 self.logger.info("order to load vim {}".format(task[1]))
tierno1d213f42020-04-24 14:02:51 +00002492 self._load_vim(task[1])
tierno70eeb182020-10-19 16:38:00 +00002493 elif task[0] == "unload_vim":
tierno86153522020-12-06 18:27:16 +00002494 self.logger.info("order to unload vim {}".format(task[1]))
tierno70eeb182020-10-19 16:38:00 +00002495 self._unload_vim(task[1])
2496 elif task[0] == "reload_vim":
2497 self._reload_vim(task[1])
2498 elif task[0] == "check_vim":
tierno86153522020-12-06 18:27:16 +00002499 self.logger.info("order to check vim {}".format(task[1]))
tierno70eeb182020-10-19 16:38:00 +00002500 self._check_vim(task[1])
tierno1d213f42020-04-24 14:02:51 +00002501 continue
tierno70eeb182020-10-19 16:38:00 +00002502 except Exception as e:
2503 if isinstance(e, queue.Empty):
2504 pass
2505 else:
sousaedu80135b92021-02-17 15:05:18 +01002506 self.logger.critical(
2507 "Error processing task: {}".format(e), exc_info=True
2508 )
tierno1d213f42020-04-24 14:02:51 +00002509
tierno70eeb182020-10-19 16:38:00 +00002510 # step 2: process pending_tasks, delete not needed tasks
tierno1d213f42020-04-24 14:02:51 +00002511 try:
tierno70eeb182020-10-19 16:38:00 +00002512 if self.tasks_to_delete:
2513 self._process_delete_db_tasks()
tierno1d213f42020-04-24 14:02:51 +00002514 busy = False
gallardo2f4aaaa2022-01-31 16:50:48 +00002515 """
2516 # Log RO tasks only when loglevel is DEBUG
2517 if self.logger.getEffectiveLevel() == logging.DEBUG:
2518 _ = self._get_db_all_tasks()
2519 """
tierno1d213f42020-04-24 14:02:51 +00002520 ro_task = self._get_db_task()
2521 if ro_task:
palaciosj8f2060b2022-02-24 12:05:59 +00002522 self.logger.warning("Task to process: {}".format(ro_task))
2523 time.sleep(1)
tierno70eeb182020-10-19 16:38:00 +00002524 self._process_pending_tasks(ro_task)
tierno1d213f42020-04-24 14:02:51 +00002525 busy = True
2526 if not busy:
2527 time.sleep(5)
2528 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002529 self.logger.critical(
2530 "Unexpected exception at run: " + str(e), exc_info=True
2531 )
tierno1d213f42020-04-24 14:02:51 +00002532
tierno86153522020-12-06 18:27:16 +00002533 self.logger.info("Finishing")