blob: 8103ea7b1eff6a866839847363387d273a176584 [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
sousaedu0fe84cb2022-01-17 13:48:22 +000029import logging
sousaedu80135b92021-02-17 15:05:18 +010030from os import mkdir
sousaedu0fe84cb2022-01-17 13:48:22 +000031import queue
sousaedu80135b92021-02-17 15:05:18 +010032from shutil import rmtree
sousaedu0fe84cb2022-01-17 13:48:22 +000033import threading
34import time
sousaedu80135b92021-02-17 15:05:18 +010035from unittest.mock import Mock
36
sousaedu0fe84cb2022-01-17 13:48:22 +000037from importlib_metadata import entry_points
tierno1d213f42020-04-24 14:02:51 +000038from osm_common.dbbase import DbException
tiernof1b640f2020-12-09 15:06:01 +000039from osm_ng_ro.vim_admin import LockRenew
sousaedu0fe84cb2022-01-17 13:48:22 +000040from osm_ro_plugin import sdnconn, vimconn
41from osm_ro_plugin.sdn_dummy import SdnDummyConnector
42from osm_ro_plugin.vim_dummy import VimDummyConnector
43import yaml
sousaedu80135b92021-02-17 15:05:18 +010044
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"]]
aticig2e38b942021-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"]
aticig2e38b942021-12-10 12:59:20 +0300136 # management network
sousaedu80135b92021-02-17 15:05:18 +0100137 elif task["find_params"].get("mgmt"):
aticig2e38b942021-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 ):
aticig2e38b942021-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 ):
aticig2e38b942021-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"):
aticig2e38b942021-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 )
aticig2e38b942021-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,
214 }
tierno1d213f42020-04-24 14:02:51 +0000215 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +0100216 "task={} {} new-net={} created={}".format(
217 task_id, ro_task["target_id"], vim_net_id, created
218 )
219 )
220
tierno1d213f42020-04-24 14:02:51 +0000221 return "BUILD", ro_vim_item_update
222 except (vimconn.VimConnException, NsWorkerException) as e:
sousaedu80135b92021-02-17 15:05:18 +0100223 self.logger.error(
224 "task={} vim={} new-net: {}".format(task_id, ro_task["target_id"], e)
225 )
226 ro_vim_item_update = {
227 "vim_status": "VIM_ERROR",
228 "created": created,
229 "vim_details": str(e),
230 }
231
tierno1d213f42020-04-24 14:02:51 +0000232 return "FAILED", ro_vim_item_update
233
tierno70eeb182020-10-19 16:38:00 +0000234 def refresh(self, ro_task):
tierno1d213f42020-04-24 14:02:51 +0000235 """Call VIM to get network status"""
236 ro_task_id = ro_task["_id"]
237 target_vim = self.my_vims[ro_task["target_id"]]
tierno1d213f42020-04-24 14:02:51 +0000238 vim_id = ro_task["vim_info"]["vim_id"]
239 net_to_refresh_list = [vim_id]
sousaedu80135b92021-02-17 15:05:18 +0100240
tierno1d213f42020-04-24 14:02:51 +0000241 try:
242 vim_dict = target_vim.refresh_nets_status(net_to_refresh_list)
243 vim_info = vim_dict[vim_id]
sousaedu80135b92021-02-17 15:05:18 +0100244
tierno1d213f42020-04-24 14:02:51 +0000245 if vim_info["status"] == "ACTIVE":
246 task_status = "DONE"
247 elif vim_info["status"] == "BUILD":
248 task_status = "BUILD"
249 else:
250 task_status = "FAILED"
251 except vimconn.VimConnException as e:
252 # Mark all tasks at VIM_ERROR status
sousaedu80135b92021-02-17 15:05:18 +0100253 self.logger.error(
254 "ro_task={} vim={} get-net={}: {}".format(
255 ro_task_id, ro_task["target_id"], vim_id, e
256 )
257 )
tierno1d213f42020-04-24 14:02:51 +0000258 vim_info = {"status": "VIM_ERROR", "error_msg": str(e)}
259 task_status = "FAILED"
260
261 ro_vim_item_update = {}
262 if ro_task["vim_info"]["vim_status"] != vim_info["status"]:
263 ro_vim_item_update["vim_status"] = vim_info["status"]
sousaedu80135b92021-02-17 15:05:18 +0100264
tierno1d213f42020-04-24 14:02:51 +0000265 if ro_task["vim_info"]["vim_name"] != vim_info.get("name"):
266 ro_vim_item_update["vim_name"] = vim_info.get("name")
sousaedu80135b92021-02-17 15:05:18 +0100267
tierno1d213f42020-04-24 14:02:51 +0000268 if vim_info["status"] in ("ERROR", "VIM_ERROR"):
tierno70eeb182020-10-19 16:38:00 +0000269 if ro_task["vim_info"]["vim_details"] != vim_info.get("error_msg"):
270 ro_vim_item_update["vim_details"] = vim_info.get("error_msg")
tierno1d213f42020-04-24 14:02:51 +0000271 elif vim_info["status"] == "DELETED":
272 ro_vim_item_update["vim_id"] = None
273 ro_vim_item_update["vim_details"] = "Deleted externally"
274 else:
275 if ro_task["vim_info"]["vim_details"] != vim_info["vim_info"]:
276 ro_vim_item_update["vim_details"] = vim_info["vim_info"]
sousaedu80135b92021-02-17 15:05:18 +0100277
tierno1d213f42020-04-24 14:02:51 +0000278 if ro_vim_item_update:
sousaedu80135b92021-02-17 15:05:18 +0100279 self.logger.debug(
280 "ro_task={} {} get-net={}: status={} {}".format(
281 ro_task_id,
282 ro_task["target_id"],
283 vim_id,
284 ro_vim_item_update.get("vim_status"),
285 ro_vim_item_update.get("vim_details")
286 if ro_vim_item_update.get("vim_status") != "ACTIVE"
287 else "",
288 )
289 )
290
tierno1d213f42020-04-24 14:02:51 +0000291 return task_status, ro_vim_item_update
292
tierno70eeb182020-10-19 16:38:00 +0000293 def delete(self, ro_task, task_index):
tierno1d213f42020-04-24 14:02:51 +0000294 task = ro_task["tasks"][task_index]
295 task_id = task["task_id"]
296 net_vim_id = ro_task["vim_info"]["vim_id"]
sousaedu80135b92021-02-17 15:05:18 +0100297 ro_vim_item_update_ok = {
298 "vim_status": "DELETED",
299 "created": False,
300 "vim_details": "DELETED",
301 "vim_id": None,
302 }
303
tierno1d213f42020-04-24 14:02:51 +0000304 try:
305 if net_vim_id or ro_task["vim_info"]["created_items"]:
306 target_vim = self.my_vims[ro_task["target_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100307 target_vim.delete_network(
308 net_vim_id, ro_task["vim_info"]["created_items"]
309 )
tierno1d213f42020-04-24 14:02:51 +0000310 except vimconn.VimConnNotFoundException:
311 ro_vim_item_update_ok["vim_details"] = "already deleted"
tierno1d213f42020-04-24 14:02:51 +0000312 except vimconn.VimConnException as e:
sousaedu80135b92021-02-17 15:05:18 +0100313 self.logger.error(
314 "ro_task={} vim={} del-net={}: {}".format(
315 ro_task["_id"], ro_task["target_id"], net_vim_id, e
316 )
317 )
318 ro_vim_item_update = {
319 "vim_status": "VIM_ERROR",
320 "vim_details": "Error while deleting: {}".format(e),
321 }
322
tierno1d213f42020-04-24 14:02:51 +0000323 return "FAILED", ro_vim_item_update
324
sousaedu80135b92021-02-17 15:05:18 +0100325 self.logger.debug(
326 "task={} {} del-net={} {}".format(
327 task_id,
328 ro_task["target_id"],
329 net_vim_id,
330 ro_vim_item_update_ok.get("vim_details", ""),
331 )
332 )
333
tierno1d213f42020-04-24 14:02:51 +0000334 return "DONE", ro_vim_item_update_ok
335
tierno70eeb182020-10-19 16:38:00 +0000336
337class VimInteractionVdu(VimInteractionBase):
sousaedu80135b92021-02-17 15:05:18 +0100338 max_retries_inject_ssh_key = 20 # 20 times
339 time_retries_inject_ssh_key = 30 # wevery 30 seconds
tierno70eeb182020-10-19 16:38:00 +0000340
341 def new(self, ro_task, task_index, task_depends):
tierno1d213f42020-04-24 14:02:51 +0000342 task = ro_task["tasks"][task_index]
343 task_id = task["task_id"]
344 created = False
345 created_items = {}
346 target_vim = self.my_vims[ro_task["target_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100347
tierno1d213f42020-04-24 14:02:51 +0000348 try:
349 created = True
350 params = task["params"]
351 params_copy = deepcopy(params)
352 net_list = params_copy["net_list"]
sousaedu80135b92021-02-17 15:05:18 +0100353
tierno1d213f42020-04-24 14:02:51 +0000354 for net in net_list:
sousaedu80135b92021-02-17 15:05:18 +0100355 # change task_id into network_id
356 if "net_id" in net and net["net_id"].startswith("TASK-"):
tierno1d213f42020-04-24 14:02:51 +0000357 network_id = task_depends[net["net_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100358
tierno1d213f42020-04-24 14:02:51 +0000359 if not network_id:
sousaedu80135b92021-02-17 15:05:18 +0100360 raise NsWorkerException(
361 "Cannot create VM because depends on a network not created or found "
362 "for {}".format(net["net_id"])
363 )
364
tierno1d213f42020-04-24 14:02:51 +0000365 net["net_id"] = network_id
sousaedu80135b92021-02-17 15:05:18 +0100366
tierno1d213f42020-04-24 14:02:51 +0000367 if params_copy["image_id"].startswith("TASK-"):
368 params_copy["image_id"] = task_depends[params_copy["image_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100369
tierno1d213f42020-04-24 14:02:51 +0000370 if params_copy["flavor_id"].startswith("TASK-"):
371 params_copy["flavor_id"] = task_depends[params_copy["flavor_id"]]
372
373 vim_vm_id, created_items = target_vim.new_vminstance(**params_copy)
374 interfaces = [iface["vim_id"] for iface in params_copy["net_list"]]
375
sousaedu80135b92021-02-17 15:05:18 +0100376 ro_vim_item_update = {
377 "vim_id": vim_vm_id,
378 "vim_status": "BUILD",
379 "created": created,
380 "created_items": created_items,
381 "vim_details": None,
382 "interfaces_vim_ids": interfaces,
383 "interfaces": [],
384 }
tierno1d213f42020-04-24 14:02:51 +0000385 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +0100386 "task={} {} new-vm={} created={}".format(
387 task_id, ro_task["target_id"], vim_vm_id, created
388 )
389 )
390
tierno1d213f42020-04-24 14:02:51 +0000391 return "BUILD", ro_vim_item_update
392 except (vimconn.VimConnException, NsWorkerException) as e:
sousaedu80135b92021-02-17 15:05:18 +0100393 self.logger.error(
394 "task={} {} new-vm: {}".format(task_id, ro_task["target_id"], e)
395 )
396 ro_vim_item_update = {
397 "vim_status": "VIM_ERROR",
398 "created": created,
399 "vim_details": str(e),
400 }
401
tierno1d213f42020-04-24 14:02:51 +0000402 return "FAILED", ro_vim_item_update
403
tierno70eeb182020-10-19 16:38:00 +0000404 def delete(self, ro_task, task_index):
tierno1d213f42020-04-24 14:02:51 +0000405 task = ro_task["tasks"][task_index]
406 task_id = task["task_id"]
407 vm_vim_id = ro_task["vim_info"]["vim_id"]
sousaedu80135b92021-02-17 15:05:18 +0100408 ro_vim_item_update_ok = {
409 "vim_status": "DELETED",
410 "created": False,
411 "vim_details": "DELETED",
412 "vim_id": None,
413 }
414
tierno1d213f42020-04-24 14:02:51 +0000415 try:
416 if vm_vim_id or ro_task["vim_info"]["created_items"]:
417 target_vim = self.my_vims[ro_task["target_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100418 target_vim.delete_vminstance(
419 vm_vim_id, ro_task["vim_info"]["created_items"]
420 )
tierno1d213f42020-04-24 14:02:51 +0000421 except vimconn.VimConnNotFoundException:
422 ro_vim_item_update_ok["vim_details"] = "already deleted"
tierno1d213f42020-04-24 14:02:51 +0000423 except vimconn.VimConnException as e:
sousaedu80135b92021-02-17 15:05:18 +0100424 self.logger.error(
425 "ro_task={} vim={} del-vm={}: {}".format(
426 ro_task["_id"], ro_task["target_id"], vm_vim_id, e
427 )
428 )
429 ro_vim_item_update = {
430 "vim_status": "VIM_ERROR",
431 "vim_details": "Error while deleting: {}".format(e),
432 }
433
tierno1d213f42020-04-24 14:02:51 +0000434 return "FAILED", ro_vim_item_update
435
sousaedu80135b92021-02-17 15:05:18 +0100436 self.logger.debug(
437 "task={} {} del-vm={} {}".format(
438 task_id,
439 ro_task["target_id"],
440 vm_vim_id,
441 ro_vim_item_update_ok.get("vim_details", ""),
442 )
443 )
444
tierno1d213f42020-04-24 14:02:51 +0000445 return "DONE", ro_vim_item_update_ok
446
tierno70eeb182020-10-19 16:38:00 +0000447 def refresh(self, ro_task):
tierno1d213f42020-04-24 14:02:51 +0000448 """Call VIM to get vm status"""
449 ro_task_id = ro_task["_id"]
450 target_vim = self.my_vims[ro_task["target_id"]]
tierno1d213f42020-04-24 14:02:51 +0000451 vim_id = ro_task["vim_info"]["vim_id"]
sousaedu80135b92021-02-17 15:05:18 +0100452
tierno1d213f42020-04-24 14:02:51 +0000453 if not vim_id:
454 return None, None
sousaedu80135b92021-02-17 15:05:18 +0100455
tierno1d213f42020-04-24 14:02:51 +0000456 vm_to_refresh_list = [vim_id]
457 try:
458 vim_dict = target_vim.refresh_vms_status(vm_to_refresh_list)
459 vim_info = vim_dict[vim_id]
sousaedu80135b92021-02-17 15:05:18 +0100460
tierno1d213f42020-04-24 14:02:51 +0000461 if vim_info["status"] == "ACTIVE":
462 task_status = "DONE"
463 elif vim_info["status"] == "BUILD":
464 task_status = "BUILD"
465 else:
466 task_status = "FAILED"
sousaedu80135b92021-02-17 15:05:18 +0100467
tierno70eeb182020-10-19 16:38:00 +0000468 # try to load and parse vim_information
469 try:
470 vim_info_info = yaml.safe_load(vim_info["vim_info"])
471 if vim_info_info.get("name"):
472 vim_info["name"] = vim_info_info["name"]
473 except Exception:
474 pass
tierno1d213f42020-04-24 14:02:51 +0000475 except vimconn.VimConnException as e:
476 # Mark all tasks at VIM_ERROR status
sousaedu80135b92021-02-17 15:05:18 +0100477 self.logger.error(
478 "ro_task={} vim={} get-vm={}: {}".format(
479 ro_task_id, ro_task["target_id"], vim_id, e
480 )
481 )
tierno1d213f42020-04-24 14:02:51 +0000482 vim_info = {"status": "VIM_ERROR", "error_msg": str(e)}
483 task_status = "FAILED"
484
485 ro_vim_item_update = {}
sousaedu80135b92021-02-17 15:05:18 +0100486
tierno70eeb182020-10-19 16:38:00 +0000487 # Interfaces cannot be present if e.g. VM is not present, that is status=DELETED
tierno1d213f42020-04-24 14:02:51 +0000488 vim_interfaces = []
tierno70eeb182020-10-19 16:38:00 +0000489 if vim_info.get("interfaces"):
490 for vim_iface_id in ro_task["vim_info"]["interfaces_vim_ids"]:
sousaedu80135b92021-02-17 15:05:18 +0100491 iface = next(
492 (
493 iface
494 for iface in vim_info["interfaces"]
495 if vim_iface_id == iface["vim_interface_id"]
496 ),
497 None,
498 )
tierno70eeb182020-10-19 16:38:00 +0000499 # if iface:
500 # iface.pop("vim_info", None)
501 vim_interfaces.append(iface)
tierno1d213f42020-04-24 14:02:51 +0000502
sousaedu80135b92021-02-17 15:05:18 +0100503 task_create = next(
504 t
505 for t in ro_task["tasks"]
506 if t and t["action"] == "CREATE" and t["status"] != "FINISHED"
507 )
tierno70eeb182020-10-19 16:38:00 +0000508 if vim_interfaces and task_create.get("mgmt_vnf_interface") is not None:
sousaedu80135b92021-02-17 15:05:18 +0100509 vim_interfaces[task_create["mgmt_vnf_interface"]][
510 "mgmt_vnf_interface"
511 ] = True
512
513 mgmt_vdu_iface = task_create.get(
514 "mgmt_vdu_interface", task_create.get("mgmt_vnf_interface", 0)
515 )
tierno70eeb182020-10-19 16:38:00 +0000516 if vim_interfaces:
517 vim_interfaces[mgmt_vdu_iface]["mgmt_vdu_interface"] = True
tierno1d213f42020-04-24 14:02:51 +0000518
519 if ro_task["vim_info"]["interfaces"] != vim_interfaces:
520 ro_vim_item_update["interfaces"] = vim_interfaces
sousaedu80135b92021-02-17 15:05:18 +0100521
tierno1d213f42020-04-24 14:02:51 +0000522 if ro_task["vim_info"]["vim_status"] != vim_info["status"]:
523 ro_vim_item_update["vim_status"] = vim_info["status"]
sousaedu80135b92021-02-17 15:05:18 +0100524
tierno1d213f42020-04-24 14:02:51 +0000525 if ro_task["vim_info"]["vim_name"] != vim_info.get("name"):
526 ro_vim_item_update["vim_name"] = vim_info.get("name")
sousaedu80135b92021-02-17 15:05:18 +0100527
tierno1d213f42020-04-24 14:02:51 +0000528 if vim_info["status"] in ("ERROR", "VIM_ERROR"):
tierno70eeb182020-10-19 16:38:00 +0000529 if ro_task["vim_info"]["vim_details"] != vim_info.get("error_msg"):
530 ro_vim_item_update["vim_details"] = vim_info.get("error_msg")
tierno1d213f42020-04-24 14:02:51 +0000531 elif vim_info["status"] == "DELETED":
532 ro_vim_item_update["vim_id"] = None
533 ro_vim_item_update["vim_details"] = "Deleted externally"
534 else:
535 if ro_task["vim_info"]["vim_details"] != vim_info["vim_info"]:
536 ro_vim_item_update["vim_details"] = vim_info["vim_info"]
sousaedu80135b92021-02-17 15:05:18 +0100537
tierno1d213f42020-04-24 14:02:51 +0000538 if ro_vim_item_update:
sousaedu80135b92021-02-17 15:05:18 +0100539 self.logger.debug(
540 "ro_task={} {} get-vm={}: status={} {}".format(
541 ro_task_id,
542 ro_task["target_id"],
543 vim_id,
544 ro_vim_item_update.get("vim_status"),
545 ro_vim_item_update.get("vim_details")
546 if ro_vim_item_update.get("vim_status") != "ACTIVE"
547 else "",
548 )
549 )
550
tierno1d213f42020-04-24 14:02:51 +0000551 return task_status, ro_vim_item_update
552
tierno70eeb182020-10-19 16:38:00 +0000553 def exec(self, ro_task, task_index, task_depends):
tierno1d213f42020-04-24 14:02:51 +0000554 task = ro_task["tasks"][task_index]
555 task_id = task["task_id"]
556 target_vim = self.my_vims[ro_task["target_id"]]
tierno70eeb182020-10-19 16:38:00 +0000557 db_task_update = {"retries": 0}
558 retries = task.get("retries", 0)
sousaedu80135b92021-02-17 15:05:18 +0100559
tierno1d213f42020-04-24 14:02:51 +0000560 try:
561 params = task["params"]
562 params_copy = deepcopy(params)
sousaedu80135b92021-02-17 15:05:18 +0100563 params_copy["ro_key"] = self.db.decrypt(
564 params_copy.pop("private_key"),
565 params_copy.pop("schema_version"),
566 params_copy.pop("salt"),
567 )
tierno70eeb182020-10-19 16:38:00 +0000568 params_copy["ip_addr"] = params_copy.pop("ip_address")
tierno1d213f42020-04-24 14:02:51 +0000569 target_vim.inject_user_key(**params_copy)
570 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +0100571 "task={} {} action-vm=inject_key".format(task_id, ro_task["target_id"])
572 )
573
574 return (
575 "DONE",
576 None,
577 db_task_update,
578 ) # params_copy["key"]
tierno1d213f42020-04-24 14:02:51 +0000579 except (vimconn.VimConnException, NsWorkerException) as e:
tierno70eeb182020-10-19 16:38:00 +0000580 retries += 1
sousaedu80135b92021-02-17 15:05:18 +0100581
tierno70eeb182020-10-19 16:38:00 +0000582 if retries < self.max_retries_inject_ssh_key:
sousaedu80135b92021-02-17 15:05:18 +0100583 return (
584 "BUILD",
585 None,
586 {
587 "retries": retries,
588 "next_retry": self.time_retries_inject_ssh_key,
589 },
590 )
591
592 self.logger.error(
593 "task={} {} inject-ssh-key: {}".format(task_id, ro_task["target_id"], e)
594 )
tierno1d213f42020-04-24 14:02:51 +0000595 ro_vim_item_update = {"vim_details": str(e)}
sousaedu80135b92021-02-17 15:05:18 +0100596
tierno70eeb182020-10-19 16:38:00 +0000597 return "FAILED", ro_vim_item_update, db_task_update
598
599
600class VimInteractionImage(VimInteractionBase):
tierno70eeb182020-10-19 16:38:00 +0000601 def new(self, ro_task, task_index, task_depends):
602 task = ro_task["tasks"][task_index]
603 task_id = task["task_id"]
604 created = False
605 created_items = {}
606 target_vim = self.my_vims[ro_task["target_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100607
tierno70eeb182020-10-19 16:38:00 +0000608 try:
609 # FIND
610 if task.get("find_params"):
611 vim_images = target_vim.get_image_list(**task["find_params"])
sousaedu80135b92021-02-17 15:05:18 +0100612
tierno70eeb182020-10-19 16:38:00 +0000613 if not vim_images:
sousaedu80135b92021-02-17 15:05:18 +0100614 raise NsWorkerExceptionNotFound(
615 "Image not found with this criteria: '{}'".format(
616 task["find_params"]
617 )
618 )
tierno70eeb182020-10-19 16:38:00 +0000619 elif len(vim_images) > 1:
620 raise NsWorkerException(
sousaeduee6a6202021-05-11 13:22:37 +0200621 "More than one image found with this criteria: '{}'".format(
sousaedu80135b92021-02-17 15:05:18 +0100622 task["find_params"]
623 )
624 )
tierno70eeb182020-10-19 16:38:00 +0000625 else:
626 vim_image_id = vim_images[0]["id"]
627
sousaedu80135b92021-02-17 15:05:18 +0100628 ro_vim_item_update = {
629 "vim_id": vim_image_id,
630 "vim_status": "DONE",
631 "created": created,
632 "created_items": created_items,
633 "vim_details": None,
634 }
tierno70eeb182020-10-19 16:38:00 +0000635 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +0100636 "task={} {} new-image={} created={}".format(
637 task_id, ro_task["target_id"], vim_image_id, created
638 )
639 )
640
tierno70eeb182020-10-19 16:38:00 +0000641 return "DONE", ro_vim_item_update
642 except (NsWorkerException, vimconn.VimConnException) as e:
sousaedu80135b92021-02-17 15:05:18 +0100643 self.logger.error(
644 "task={} {} new-image: {}".format(task_id, ro_task["target_id"], e)
645 )
646 ro_vim_item_update = {
647 "vim_status": "VIM_ERROR",
648 "created": created,
649 "vim_details": str(e),
650 }
651
tierno1d213f42020-04-24 14:02:51 +0000652 return "FAILED", ro_vim_item_update
653
tierno70eeb182020-10-19 16:38:00 +0000654
655class VimInteractionFlavor(VimInteractionBase):
tierno70eeb182020-10-19 16:38:00 +0000656 def delete(self, ro_task, task_index):
657 task = ro_task["tasks"][task_index]
658 task_id = task["task_id"]
659 flavor_vim_id = ro_task["vim_info"]["vim_id"]
sousaedu80135b92021-02-17 15:05:18 +0100660 ro_vim_item_update_ok = {
661 "vim_status": "DELETED",
662 "created": False,
663 "vim_details": "DELETED",
664 "vim_id": None,
665 }
666
tierno70eeb182020-10-19 16:38:00 +0000667 try:
668 if flavor_vim_id:
669 target_vim = self.my_vims[ro_task["target_id"]]
670 target_vim.delete_flavor(flavor_vim_id)
tierno70eeb182020-10-19 16:38:00 +0000671 except vimconn.VimConnNotFoundException:
672 ro_vim_item_update_ok["vim_details"] = "already deleted"
tierno70eeb182020-10-19 16:38:00 +0000673 except vimconn.VimConnException as e:
sousaedu80135b92021-02-17 15:05:18 +0100674 self.logger.error(
675 "ro_task={} vim={} del-flavor={}: {}".format(
676 ro_task["_id"], ro_task["target_id"], flavor_vim_id, e
677 )
678 )
679 ro_vim_item_update = {
680 "vim_status": "VIM_ERROR",
681 "vim_details": "Error while deleting: {}".format(e),
682 }
683
tierno70eeb182020-10-19 16:38:00 +0000684 return "FAILED", ro_vim_item_update
685
sousaedu80135b92021-02-17 15:05:18 +0100686 self.logger.debug(
687 "task={} {} del-flavor={} {}".format(
688 task_id,
689 ro_task["target_id"],
690 flavor_vim_id,
691 ro_vim_item_update_ok.get("vim_details", ""),
692 )
693 )
694
tierno70eeb182020-10-19 16:38:00 +0000695 return "DONE", ro_vim_item_update_ok
696
697 def new(self, ro_task, task_index, task_depends):
698 task = ro_task["tasks"][task_index]
699 task_id = task["task_id"]
700 created = False
701 created_items = {}
702 target_vim = self.my_vims[ro_task["target_id"]]
sousaedu80135b92021-02-17 15:05:18 +0100703
tierno70eeb182020-10-19 16:38:00 +0000704 try:
705 # FIND
706 vim_flavor_id = None
sousaedu80135b92021-02-17 15:05:18 +0100707
tierno70eeb182020-10-19 16:38:00 +0000708 if task.get("find_params"):
709 try:
710 flavor_data = task["find_params"]["flavor_data"]
711 vim_flavor_id = target_vim.get_flavor_id_from_data(flavor_data)
712 except vimconn.VimConnNotFoundException:
713 pass
714
715 if not vim_flavor_id and task.get("params"):
716 # CREATE
717 flavor_data = task["params"]["flavor_data"]
718 vim_flavor_id = target_vim.new_flavor(flavor_data)
719 created = True
720
sousaedu80135b92021-02-17 15:05:18 +0100721 ro_vim_item_update = {
722 "vim_id": vim_flavor_id,
723 "vim_status": "DONE",
724 "created": created,
725 "created_items": created_items,
726 "vim_details": None,
727 }
tierno70eeb182020-10-19 16:38:00 +0000728 self.logger.debug(
sousaedu80135b92021-02-17 15:05:18 +0100729 "task={} {} new-flavor={} created={}".format(
730 task_id, ro_task["target_id"], vim_flavor_id, created
731 )
732 )
733
tierno70eeb182020-10-19 16:38:00 +0000734 return "DONE", ro_vim_item_update
735 except (vimconn.VimConnException, NsWorkerException) as e:
sousaedu80135b92021-02-17 15:05:18 +0100736 self.logger.error(
737 "task={} vim={} new-flavor: {}".format(task_id, ro_task["target_id"], e)
738 )
739 ro_vim_item_update = {
740 "vim_status": "VIM_ERROR",
741 "created": created,
742 "vim_details": str(e),
743 }
744
tierno70eeb182020-10-19 16:38:00 +0000745 return "FAILED", ro_vim_item_update
746
747
748class VimInteractionSdnNet(VimInteractionBase):
tierno70eeb182020-10-19 16:38:00 +0000749 @staticmethod
750 def _match_pci(port_pci, mapping):
751 """
752 Check if port_pci matches with mapping
753 mapping can have brackets to indicate that several chars are accepted. e.g
754 pci '0000:af:10.1' matches with '0000:af:1[01].[1357]'
755 :param port_pci: text
756 :param mapping: text, can contain brackets to indicate several chars are available
757 :return: True if matches, False otherwise
758 """
759 if not port_pci or not mapping:
760 return False
761 if port_pci == mapping:
762 return True
763
764 mapping_index = 0
765 pci_index = 0
766 while True:
767 bracket_start = mapping.find("[", mapping_index)
sousaedu80135b92021-02-17 15:05:18 +0100768
tierno70eeb182020-10-19 16:38:00 +0000769 if bracket_start == -1:
770 break
sousaedu80135b92021-02-17 15:05:18 +0100771
tierno70eeb182020-10-19 16:38:00 +0000772 bracket_end = mapping.find("]", bracket_start)
773 if bracket_end == -1:
774 break
sousaedu80135b92021-02-17 15:05:18 +0100775
tierno70eeb182020-10-19 16:38:00 +0000776 length = bracket_start - mapping_index
sousaedu80135b92021-02-17 15:05:18 +0100777 if (
778 length
779 and port_pci[pci_index : pci_index + length]
780 != mapping[mapping_index:bracket_start]
781 ):
tierno70eeb182020-10-19 16:38:00 +0000782 return False
sousaedu80135b92021-02-17 15:05:18 +0100783
784 if (
785 port_pci[pci_index + length]
786 not in mapping[bracket_start + 1 : bracket_end]
787 ):
tierno70eeb182020-10-19 16:38:00 +0000788 return False
sousaedu80135b92021-02-17 15:05:18 +0100789
tierno70eeb182020-10-19 16:38:00 +0000790 pci_index += length + 1
791 mapping_index = bracket_end + 1
792
793 if port_pci[pci_index:] != mapping[mapping_index:]:
794 return False
sousaedu80135b92021-02-17 15:05:18 +0100795
tierno70eeb182020-10-19 16:38:00 +0000796 return True
797
798 def _get_interfaces(self, vlds_to_connect, vim_account_id):
799 """
800 :param vlds_to_connect: list with format vnfrs:<id>:vld.<vld_id> or nsrs:<id>:vld.<vld_id>
801 :param vim_account_id:
802 :return:
803 """
804 interfaces = []
sousaedu80135b92021-02-17 15:05:18 +0100805
tierno70eeb182020-10-19 16:38:00 +0000806 for vld in vlds_to_connect:
807 table, _, db_id = vld.partition(":")
808 db_id, _, vld = db_id.partition(":")
809 _, _, vld_id = vld.partition(".")
sousaedu80135b92021-02-17 15:05:18 +0100810
tierno70eeb182020-10-19 16:38:00 +0000811 if table == "vnfrs":
812 q_filter = {"vim-account-id": vim_account_id, "_id": db_id}
813 iface_key = "vnf-vld-id"
814 else: # table == "nsrs"
815 q_filter = {"vim-account-id": vim_account_id, "nsr-id-ref": db_id}
816 iface_key = "ns-vld-id"
sousaedu80135b92021-02-17 15:05:18 +0100817
tierno70eeb182020-10-19 16:38:00 +0000818 db_vnfrs = self.db.get_list("vnfrs", q_filter=q_filter)
sousaedu80135b92021-02-17 15:05:18 +0100819
tierno70eeb182020-10-19 16:38:00 +0000820 for db_vnfr in db_vnfrs:
821 for vdu_index, vdur in enumerate(db_vnfr.get("vdur", ())):
822 for iface_index, interface in enumerate(vdur["interfaces"]):
sousaedu80135b92021-02-17 15:05:18 +0100823 if interface.get(iface_key) == vld_id and interface.get(
824 "type"
825 ) in ("SR-IOV", "PCI-PASSTHROUGH"):
tierno70eeb182020-10-19 16:38:00 +0000826 # only SR-IOV o PT
827 interface_ = interface.copy()
sousaedu80135b92021-02-17 15:05:18 +0100828 interface_["id"] = "vnfrs:{}:vdu.{}.interfaces.{}".format(
829 db_vnfr["_id"], vdu_index, iface_index
830 )
831
tierno70eeb182020-10-19 16:38:00 +0000832 if vdur.get("status") == "ERROR":
833 interface_["status"] = "ERROR"
sousaedu80135b92021-02-17 15:05:18 +0100834
tierno70eeb182020-10-19 16:38:00 +0000835 interfaces.append(interface_)
sousaedu80135b92021-02-17 15:05:18 +0100836
tierno70eeb182020-10-19 16:38:00 +0000837 return interfaces
838
839 def refresh(self, ro_task):
840 # look for task create
sousaedu80135b92021-02-17 15:05:18 +0100841 task_create_index, _ = next(
842 i_t
843 for i_t in enumerate(ro_task["tasks"])
844 if i_t[1]
845 and i_t[1]["action"] == "CREATE"
846 and i_t[1]["status"] != "FINISHED"
847 )
tierno70eeb182020-10-19 16:38:00 +0000848
849 return self.new(ro_task, task_create_index, None)
850
851 def new(self, ro_task, task_index, task_depends):
852
853 task = ro_task["tasks"][task_index]
854 task_id = task["task_id"]
855 target_vim = self.my_vims[ro_task["target_id"]]
856
857 sdn_net_id = ro_task["vim_info"]["vim_id"]
858
859 created_items = ro_task["vim_info"].get("created_items")
860 connected_ports = ro_task["vim_info"].get("connected_ports", [])
861 new_connected_ports = []
862 last_update = ro_task["vim_info"].get("last_update", 0)
863 sdn_status = ro_task["vim_info"].get("vim_status", "BUILD") or "BUILD"
864 error_list = []
865 created = ro_task["vim_info"].get("created", False)
866
867 try:
tierno70eeb182020-10-19 16:38:00 +0000868 # CREATE
869 params = task["params"]
870 vlds_to_connect = params["vlds"]
871 associated_vim = params["target_vim"]
sousaedu80135b92021-02-17 15:05:18 +0100872 # external additional ports
873 additional_ports = params.get("sdn-ports") or ()
tierno70eeb182020-10-19 16:38:00 +0000874 _, _, vim_account_id = associated_vim.partition(":")
sousaedu80135b92021-02-17 15:05:18 +0100875
tierno70eeb182020-10-19 16:38:00 +0000876 if associated_vim:
877 # get associated VIM
878 if associated_vim not in self.db_vims:
sousaedu80135b92021-02-17 15:05:18 +0100879 self.db_vims[associated_vim] = self.db.get_one(
880 "vim_accounts", {"_id": vim_account_id}
881 )
882
tierno70eeb182020-10-19 16:38:00 +0000883 db_vim = self.db_vims[associated_vim]
884
885 # look for ports to connect
886 ports = self._get_interfaces(vlds_to_connect, vim_account_id)
887 # print(ports)
888
889 sdn_ports = []
890 pending_ports = error_ports = 0
891 vlan_used = None
892 sdn_need_update = False
sousaedu80135b92021-02-17 15:05:18 +0100893
tierno70eeb182020-10-19 16:38:00 +0000894 for port in ports:
895 vlan_used = port.get("vlan") or vlan_used
sousaedu80135b92021-02-17 15:05:18 +0100896
tierno70eeb182020-10-19 16:38:00 +0000897 # TODO. Do not connect if already done
898 if not port.get("compute_node") or not port.get("pci"):
899 if port.get("status") == "ERROR":
900 error_ports += 1
901 else:
902 pending_ports += 1
903 continue
sousaedu80135b92021-02-17 15:05:18 +0100904
tierno70eeb182020-10-19 16:38:00 +0000905 pmap = None
sousaedu80135b92021-02-17 15:05:18 +0100906 compute_node_mappings = next(
907 (
908 c
909 for c in db_vim["config"].get("sdn-port-mapping", ())
910 if c and c["compute_node"] == port["compute_node"]
911 ),
912 None,
913 )
914
tierno70eeb182020-10-19 16:38:00 +0000915 if compute_node_mappings:
916 # process port_mapping pci of type 0000:af:1[01].[1357]
sousaedu80135b92021-02-17 15:05:18 +0100917 pmap = next(
918 (
919 p
920 for p in compute_node_mappings["ports"]
921 if self._match_pci(port["pci"], p.get("pci"))
922 ),
923 None,
924 )
925
tierno70eeb182020-10-19 16:38:00 +0000926 if not pmap:
927 if not db_vim["config"].get("mapping_not_needed"):
sousaedu80135b92021-02-17 15:05:18 +0100928 error_list.append(
929 "Port mapping not found for compute_node={} pci={}".format(
930 port["compute_node"], port["pci"]
931 )
932 )
tierno70eeb182020-10-19 16:38:00 +0000933 continue
sousaedu80135b92021-02-17 15:05:18 +0100934
tierno70eeb182020-10-19 16:38:00 +0000935 pmap = {}
936
937 service_endpoint_id = "{}:{}".format(port["compute_node"], port["pci"])
938 new_port = {
sousaedu80135b92021-02-17 15:05:18 +0100939 "service_endpoint_id": pmap.get("service_endpoint_id")
940 or service_endpoint_id,
941 "service_endpoint_encapsulation_type": "dot1q"
942 if port["type"] == "SR-IOV"
943 else None,
tierno70eeb182020-10-19 16:38:00 +0000944 "service_endpoint_encapsulation_info": {
945 "vlan": port.get("vlan"),
lloretgalleg160fcad2021-02-19 10:57:50 +0000946 "mac": port.get("mac-address"),
sousaedu80135b92021-02-17 15:05:18 +0100947 "device_id": pmap.get("device_id") or port["compute_node"],
948 "device_interface_id": pmap.get("device_interface_id")
949 or port["pci"],
tierno70eeb182020-10-19 16:38:00 +0000950 "switch_dpid": pmap.get("switch_id") or pmap.get("switch_dpid"),
951 "switch_port": pmap.get("switch_port"),
952 "service_mapping_info": pmap.get("service_mapping_info"),
sousaedu80135b92021-02-17 15:05:18 +0100953 },
tierno70eeb182020-10-19 16:38:00 +0000954 }
955
956 # TODO
957 # if port["modified_at"] > last_update:
958 # sdn_need_update = True
959 new_connected_ports.append(port["id"]) # TODO
960 sdn_ports.append(new_port)
961
962 if error_ports:
sousaedu80135b92021-02-17 15:05:18 +0100963 error_list.append(
964 "{} interfaces have not been created as VDU is on ERROR status".format(
965 error_ports
966 )
967 )
tierno70eeb182020-10-19 16:38:00 +0000968
969 # connect external ports
970 for index, additional_port in enumerate(additional_ports):
sousaedu80135b92021-02-17 15:05:18 +0100971 additional_port_id = additional_port.get(
972 "service_endpoint_id"
973 ) or "external-{}".format(index)
974 sdn_ports.append(
975 {
976 "service_endpoint_id": additional_port_id,
977 "service_endpoint_encapsulation_type": additional_port.get(
978 "service_endpoint_encapsulation_type", "dot1q"
979 ),
980 "service_endpoint_encapsulation_info": {
981 "vlan": additional_port.get("vlan") or vlan_used,
982 "mac": additional_port.get("mac_address"),
983 "device_id": additional_port.get("device_id"),
984 "device_interface_id": additional_port.get(
985 "device_interface_id"
986 ),
987 "switch_dpid": additional_port.get("switch_dpid")
988 or additional_port.get("switch_id"),
989 "switch_port": additional_port.get("switch_port"),
990 "service_mapping_info": additional_port.get(
991 "service_mapping_info"
992 ),
993 },
994 }
995 )
tierno70eeb182020-10-19 16:38:00 +0000996 new_connected_ports.append(additional_port_id)
997 sdn_info = ""
sousaedu80135b92021-02-17 15:05:18 +0100998
tierno70eeb182020-10-19 16:38:00 +0000999 # if there are more ports to connect or they have been modified, call create/update
1000 if error_list:
1001 sdn_status = "ERROR"
1002 sdn_info = "; ".join(error_list)
1003 elif set(connected_ports) != set(new_connected_ports) or sdn_need_update:
1004 last_update = time.time()
sousaedu80135b92021-02-17 15:05:18 +01001005
tierno70eeb182020-10-19 16:38:00 +00001006 if not sdn_net_id:
1007 if len(sdn_ports) < 2:
1008 sdn_status = "ACTIVE"
sousaedu80135b92021-02-17 15:05:18 +01001009
tierno70eeb182020-10-19 16:38:00 +00001010 if not pending_ports:
sousaedu80135b92021-02-17 15:05:18 +01001011 self.logger.debug(
1012 "task={} {} new-sdn-net done, less than 2 ports".format(
1013 task_id, ro_task["target_id"]
1014 )
1015 )
tierno70eeb182020-10-19 16:38:00 +00001016 else:
1017 net_type = params.get("type") or "ELAN"
sousaedu80135b92021-02-17 15:05:18 +01001018 (
1019 sdn_net_id,
1020 created_items,
1021 ) = target_vim.create_connectivity_service(net_type, sdn_ports)
tierno70eeb182020-10-19 16:38:00 +00001022 created = True
sousaedu80135b92021-02-17 15:05:18 +01001023 self.logger.debug(
1024 "task={} {} new-sdn-net={} created={}".format(
1025 task_id, ro_task["target_id"], sdn_net_id, created
1026 )
1027 )
tierno70eeb182020-10-19 16:38:00 +00001028 else:
1029 created_items = target_vim.edit_connectivity_service(
sousaedu80135b92021-02-17 15:05:18 +01001030 sdn_net_id, conn_info=created_items, connection_points=sdn_ports
1031 )
tierno70eeb182020-10-19 16:38:00 +00001032 created = True
sousaedu80135b92021-02-17 15:05:18 +01001033 self.logger.debug(
1034 "task={} {} update-sdn-net={} created={}".format(
1035 task_id, ro_task["target_id"], sdn_net_id, created
1036 )
1037 )
1038
tierno70eeb182020-10-19 16:38:00 +00001039 connected_ports = new_connected_ports
1040 elif sdn_net_id:
sousaedu80135b92021-02-17 15:05:18 +01001041 wim_status_dict = target_vim.get_connectivity_service_status(
1042 sdn_net_id, conn_info=created_items
1043 )
tierno70eeb182020-10-19 16:38:00 +00001044 sdn_status = wim_status_dict["sdn_status"]
sousaedu80135b92021-02-17 15:05:18 +01001045
tierno70eeb182020-10-19 16:38:00 +00001046 if wim_status_dict.get("sdn_info"):
1047 sdn_info = str(wim_status_dict.get("sdn_info")) or ""
sousaedu80135b92021-02-17 15:05:18 +01001048
tierno70eeb182020-10-19 16:38:00 +00001049 if wim_status_dict.get("error_msg"):
1050 sdn_info = wim_status_dict.get("error_msg") or ""
1051
1052 if pending_ports:
1053 if sdn_status != "ERROR":
1054 sdn_info = "Waiting for getting interfaces location from VIM. Obtained '{}' of {}".format(
sousaedu80135b92021-02-17 15:05:18 +01001055 len(ports) - pending_ports, len(ports)
1056 )
1057
tierno70eeb182020-10-19 16:38:00 +00001058 if sdn_status == "ACTIVE":
1059 sdn_status = "BUILD"
1060
sousaedu80135b92021-02-17 15:05:18 +01001061 ro_vim_item_update = {
1062 "vim_id": sdn_net_id,
1063 "vim_status": sdn_status,
1064 "created": created,
1065 "created_items": created_items,
1066 "connected_ports": connected_ports,
1067 "vim_details": sdn_info,
1068 "last_update": last_update,
1069 }
1070
tierno70eeb182020-10-19 16:38:00 +00001071 return sdn_status, ro_vim_item_update
1072 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001073 self.logger.error(
1074 "task={} vim={} new-net: {}".format(task_id, ro_task["target_id"], e),
1075 exc_info=not isinstance(
1076 e, (sdnconn.SdnConnectorError, vimconn.VimConnException)
1077 ),
1078 )
1079 ro_vim_item_update = {
1080 "vim_status": "VIM_ERROR",
1081 "created": created,
1082 "vim_details": str(e),
1083 }
1084
tierno70eeb182020-10-19 16:38:00 +00001085 return "FAILED", ro_vim_item_update
1086
1087 def delete(self, ro_task, task_index):
1088 task = ro_task["tasks"][task_index]
1089 task_id = task["task_id"]
1090 sdn_vim_id = ro_task["vim_info"].get("vim_id")
sousaedu80135b92021-02-17 15:05:18 +01001091 ro_vim_item_update_ok = {
1092 "vim_status": "DELETED",
1093 "created": False,
1094 "vim_details": "DELETED",
1095 "vim_id": None,
1096 }
1097
tierno70eeb182020-10-19 16:38:00 +00001098 try:
1099 if sdn_vim_id:
1100 target_vim = self.my_vims[ro_task["target_id"]]
sousaedu80135b92021-02-17 15:05:18 +01001101 target_vim.delete_connectivity_service(
1102 sdn_vim_id, ro_task["vim_info"].get("created_items")
1103 )
tierno70eeb182020-10-19 16:38:00 +00001104
1105 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001106 if (
1107 isinstance(e, sdnconn.SdnConnectorError)
1108 and e.http_code == HTTPStatus.NOT_FOUND.value
1109 ):
tierno70eeb182020-10-19 16:38:00 +00001110 ro_vim_item_update_ok["vim_details"] = "already deleted"
1111 else:
sousaedu80135b92021-02-17 15:05:18 +01001112 self.logger.error(
1113 "ro_task={} vim={} del-sdn-net={}: {}".format(
1114 ro_task["_id"], ro_task["target_id"], sdn_vim_id, e
1115 ),
1116 exc_info=not isinstance(
1117 e, (sdnconn.SdnConnectorError, vimconn.VimConnException)
1118 ),
1119 )
1120 ro_vim_item_update = {
1121 "vim_status": "VIM_ERROR",
1122 "vim_details": "Error while deleting: {}".format(e),
1123 }
1124
tierno70eeb182020-10-19 16:38:00 +00001125 return "FAILED", ro_vim_item_update
1126
sousaedu80135b92021-02-17 15:05:18 +01001127 self.logger.debug(
1128 "task={} {} del-sdn-net={} {}".format(
1129 task_id,
1130 ro_task["target_id"],
1131 sdn_vim_id,
1132 ro_vim_item_update_ok.get("vim_details", ""),
1133 )
1134 )
1135
tierno70eeb182020-10-19 16:38:00 +00001136 return "DONE", ro_vim_item_update_ok
1137
1138
1139class NsWorker(threading.Thread):
1140 REFRESH_BUILD = 5 # 5 seconds
1141 REFRESH_ACTIVE = 60 # 1 minute
1142 REFRESH_ERROR = 600
1143 REFRESH_IMAGE = 3600 * 10
1144 REFRESH_DELETE = 3600 * 10
tiernof1b640f2020-12-09 15:06:01 +00001145 QUEUE_SIZE = 100
tierno70eeb182020-10-19 16:38:00 +00001146 terminate = False
tierno70eeb182020-10-19 16:38:00 +00001147
1148 def __init__(self, worker_index, config, plugins, db):
1149 """
1150
1151 :param worker_index: thread index
1152 :param config: general configuration of RO, among others the process_id with the docker id where it runs
1153 :param plugins: global shared dict with the loaded plugins
1154 :param db: database class instance to use
1155 """
1156 threading.Thread.__init__(self)
1157 self.config = config
1158 self.plugins = plugins
1159 self.plugin_name = "unknown"
sousaedu80135b92021-02-17 15:05:18 +01001160 self.logger = logging.getLogger("ro.worker{}".format(worker_index))
tierno70eeb182020-10-19 16:38:00 +00001161 self.worker_index = worker_index
1162 self.task_queue = queue.Queue(self.QUEUE_SIZE)
sousaedu80135b92021-02-17 15:05:18 +01001163 # targetvim: vimplugin class
1164 self.my_vims = {}
1165 # targetvim: vim information from database
1166 self.db_vims = {}
1167 # targetvim list
1168 self.vim_targets = []
tierno70eeb182020-10-19 16:38:00 +00001169 self.my_id = config["process_id"] + ":" + str(worker_index)
1170 self.db = db
1171 self.item2class = {
1172 "net": VimInteractionNet(self.db, self.my_vims, self.db_vims, self.logger),
1173 "vdu": VimInteractionVdu(self.db, self.my_vims, self.db_vims, self.logger),
sousaedu80135b92021-02-17 15:05:18 +01001174 "image": VimInteractionImage(
1175 self.db, self.my_vims, self.db_vims, self.logger
1176 ),
1177 "flavor": VimInteractionFlavor(
1178 self.db, self.my_vims, self.db_vims, self.logger
1179 ),
1180 "sdn_net": VimInteractionSdnNet(
1181 self.db, self.my_vims, self.db_vims, self.logger
1182 ),
tierno70eeb182020-10-19 16:38:00 +00001183 }
1184 self.time_last_task_processed = None
sousaedu80135b92021-02-17 15:05:18 +01001185 # lists of tasks to delete because nsrs or vnfrs has been deleted from db
1186 self.tasks_to_delete = []
1187 # it is idle when there are not vim_targets associated
1188 self.idle = True
tiernof1b640f2020-12-09 15:06:01 +00001189 self.task_locked_time = config["global"]["task_locked_time"]
tierno70eeb182020-10-19 16:38:00 +00001190
1191 def insert_task(self, task):
1192 try:
1193 self.task_queue.put(task, False)
1194 return None
1195 except queue.Full:
1196 raise NsWorkerException("timeout inserting a task")
1197
1198 def terminate(self):
1199 self.insert_task("exit")
1200
1201 def del_task(self, task):
1202 with self.task_lock:
1203 if task["status"] == "SCHEDULED":
1204 task["status"] = "SUPERSEDED"
1205 return True
1206 else: # task["status"] == "processing"
1207 self.task_lock.release()
1208 return False
1209
1210 def _process_vim_config(self, target_id, db_vim):
1211 """
1212 Process vim config, creating vim configuration files as ca_cert
1213 :param target_id: vim/sdn/wim + id
1214 :param db_vim: Vim dictionary obtained from database
1215 :return: None. Modifies vim. Creates a folder target_id:worker_index and several files
1216 """
1217 if not db_vim.get("config"):
1218 return
sousaedu80135b92021-02-17 15:05:18 +01001219
tierno70eeb182020-10-19 16:38:00 +00001220 file_name = ""
sousaedu80135b92021-02-17 15:05:18 +01001221
tierno70eeb182020-10-19 16:38:00 +00001222 try:
1223 if db_vim["config"].get("ca_cert_content"):
1224 file_name = "{}:{}".format(target_id, self.worker_index)
sousaedu80135b92021-02-17 15:05:18 +01001225
tierno70eeb182020-10-19 16:38:00 +00001226 try:
1227 mkdir(file_name)
1228 except FileExistsError:
1229 pass
sousaedu80135b92021-02-17 15:05:18 +01001230
tierno70eeb182020-10-19 16:38:00 +00001231 file_name = file_name + "/ca_cert"
sousaedu80135b92021-02-17 15:05:18 +01001232
tierno70eeb182020-10-19 16:38:00 +00001233 with open(file_name, "w") as f:
1234 f.write(db_vim["config"]["ca_cert_content"])
1235 del db_vim["config"]["ca_cert_content"]
1236 db_vim["config"]["ca_cert"] = file_name
1237 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001238 raise NsWorkerException(
1239 "Error writing to file '{}': {}".format(file_name, e)
1240 )
tierno70eeb182020-10-19 16:38:00 +00001241
1242 def _load_plugin(self, name, type="vim"):
1243 # type can be vim or sdn
1244 if "rovim_dummy" not in self.plugins:
1245 self.plugins["rovim_dummy"] = VimDummyConnector
sousaedu80135b92021-02-17 15:05:18 +01001246
tierno70eeb182020-10-19 16:38:00 +00001247 if "rosdn_dummy" not in self.plugins:
1248 self.plugins["rosdn_dummy"] = SdnDummyConnector
sousaedu80135b92021-02-17 15:05:18 +01001249
tierno70eeb182020-10-19 16:38:00 +00001250 if name in self.plugins:
1251 return self.plugins[name]
sousaedu80135b92021-02-17 15:05:18 +01001252
tierno70eeb182020-10-19 16:38:00 +00001253 try:
sousaedubecd0832021-04-08 00:16:18 +02001254 for ep in entry_points(group="osm_ro{}.plugins".format(type), name=name):
1255 self.plugins[name] = ep.load()
tierno70eeb182020-10-19 16:38:00 +00001256 except Exception as e:
1257 raise NsWorkerException("Cannot load plugin osm_{}: {}".format(name, e))
sousaedu80135b92021-02-17 15:05:18 +01001258
tierno70eeb182020-10-19 16:38:00 +00001259 if name and name not in self.plugins:
sousaedu80135b92021-02-17 15:05:18 +01001260 raise NsWorkerException(
1261 "Plugin 'osm_{n}' has not been installed".format(n=name)
1262 )
1263
tierno70eeb182020-10-19 16:38:00 +00001264 return self.plugins[name]
1265
1266 def _unload_vim(self, target_id):
1267 """
1268 Unload a vim_account. Removes it from self db_vims dictionary, my_vims dictionary and vim_targets list
1269 :param target_id: Contains type:_id; where type can be 'vim', ...
1270 :return: None.
1271 """
1272 try:
tierno70eeb182020-10-19 16:38:00 +00001273 self.db_vims.pop(target_id, None)
1274 self.my_vims.pop(target_id, None)
sousaedu80135b92021-02-17 15:05:18 +01001275
tierno86153522020-12-06 18:27:16 +00001276 if target_id in self.vim_targets:
1277 self.vim_targets.remove(target_id)
sousaedu80135b92021-02-17 15:05:18 +01001278
tierno86153522020-12-06 18:27:16 +00001279 self.logger.info("Unloaded {}".format(target_id))
tierno70eeb182020-10-19 16:38:00 +00001280 rmtree("{}:{}".format(target_id, self.worker_index))
1281 except FileNotFoundError:
1282 pass # this is raised by rmtree if folder does not exist
1283 except Exception as e:
1284 self.logger.error("Cannot unload {}: {}".format(target_id, e))
1285
1286 def _check_vim(self, target_id):
1287 """
1288 Load a VIM/SDN/WIM (if not loaded) and check connectivity, updating database with ENABLE or ERROR
1289 :param target_id: Contains type:_id; type can be 'vim', 'sdn' or 'wim'
1290 :return: None.
1291 """
1292 target, _, _id = target_id.partition(":")
1293 now = time.time()
1294 update_dict = {}
1295 unset_dict = {}
1296 op_text = ""
1297 step = ""
tierno86153522020-12-06 18:27:16 +00001298 loaded = target_id in self.vim_targets
sousaedu80135b92021-02-17 15:05:18 +01001299 target_database = (
1300 "vim_accounts"
1301 if target == "vim"
1302 else "wim_accounts"
1303 if target == "wim"
1304 else "sdns"
1305 )
1306
tierno70eeb182020-10-19 16:38:00 +00001307 try:
1308 step = "Getting {} from db".format(target_id)
1309 db_vim = self.db.get_one(target_database, {"_id": _id})
sousaedu80135b92021-02-17 15:05:18 +01001310
1311 for op_index, operation in enumerate(
1312 db_vim["_admin"].get("operations", ())
1313 ):
tierno70eeb182020-10-19 16:38:00 +00001314 if operation["operationState"] != "PROCESSING":
1315 continue
sousaedu80135b92021-02-17 15:05:18 +01001316
tierno70eeb182020-10-19 16:38:00 +00001317 locked_at = operation.get("locked_at")
sousaedu80135b92021-02-17 15:05:18 +01001318
tiernof1b640f2020-12-09 15:06:01 +00001319 if locked_at is not None and locked_at >= now - self.task_locked_time:
tierno70eeb182020-10-19 16:38:00 +00001320 # some other thread is doing this operation
1321 return
sousaedu80135b92021-02-17 15:05:18 +01001322
tierno70eeb182020-10-19 16:38:00 +00001323 # lock
1324 op_text = "_admin.operations.{}.".format(op_index)
sousaedu80135b92021-02-17 15:05:18 +01001325
1326 if not self.db.set_one(
1327 target_database,
1328 q_filter={
1329 "_id": _id,
1330 op_text + "operationState": "PROCESSING",
1331 op_text + "locked_at": locked_at,
1332 },
1333 update_dict={
1334 op_text + "locked_at": now,
1335 "admin.current_operation": op_index,
1336 },
1337 fail_on_empty=False,
1338 ):
tierno70eeb182020-10-19 16:38:00 +00001339 return
sousaedu80135b92021-02-17 15:05:18 +01001340
tierno70eeb182020-10-19 16:38:00 +00001341 unset_dict[op_text + "locked_at"] = None
1342 unset_dict["current_operation"] = None
1343 step = "Loading " + target_id
1344 error_text = self._load_vim(target_id)
sousaedu80135b92021-02-17 15:05:18 +01001345
tierno70eeb182020-10-19 16:38:00 +00001346 if not error_text:
1347 step = "Checking connectivity"
sousaedu80135b92021-02-17 15:05:18 +01001348
1349 if target == "vim":
tierno70eeb182020-10-19 16:38:00 +00001350 self.my_vims[target_id].check_vim_connectivity()
1351 else:
1352 self.my_vims[target_id].check_credentials()
sousaedu80135b92021-02-17 15:05:18 +01001353
tierno70eeb182020-10-19 16:38:00 +00001354 update_dict["_admin.operationalState"] = "ENABLED"
1355 update_dict["_admin.detailed-status"] = ""
1356 unset_dict[op_text + "detailed-status"] = None
1357 update_dict[op_text + "operationState"] = "COMPLETED"
sousaedu80135b92021-02-17 15:05:18 +01001358
tierno70eeb182020-10-19 16:38:00 +00001359 return
1360
1361 except Exception as e:
1362 error_text = "{}: {}".format(step, e)
1363 self.logger.error("{} for {}: {}".format(step, target_id, e))
1364
1365 finally:
1366 if update_dict or unset_dict:
1367 if error_text:
1368 update_dict[op_text + "operationState"] = "FAILED"
1369 update_dict[op_text + "detailed-status"] = error_text
1370 unset_dict.pop(op_text + "detailed-status", None)
1371 update_dict["_admin.operationalState"] = "ERROR"
1372 update_dict["_admin.detailed-status"] = error_text
sousaedu80135b92021-02-17 15:05:18 +01001373
tierno70eeb182020-10-19 16:38:00 +00001374 if op_text:
1375 update_dict[op_text + "statusEnteredTime"] = now
sousaedu80135b92021-02-17 15:05:18 +01001376
1377 self.db.set_one(
1378 target_database,
1379 q_filter={"_id": _id},
1380 update_dict=update_dict,
1381 unset=unset_dict,
1382 fail_on_empty=False,
1383 )
1384
tierno70eeb182020-10-19 16:38:00 +00001385 if not loaded:
1386 self._unload_vim(target_id)
1387
1388 def _reload_vim(self, target_id):
1389 if target_id in self.vim_targets:
1390 self._load_vim(target_id)
1391 else:
1392 # if the vim is not loaded, but database information of VIM is cached at self.db_vims,
1393 # just remove it to force load again next time it is needed
1394 self.db_vims.pop(target_id, None)
1395
1396 def _load_vim(self, target_id):
1397 """
1398 Load or reload a vim_account, sdn_controller or wim_account.
1399 Read content from database, load the plugin if not loaded.
1400 In case of error loading the plugin, it load a failing VIM_connector
1401 It fills self db_vims dictionary, my_vims dictionary and vim_targets list
1402 :param target_id: Contains type:_id; where type can be 'vim', ...
1403 :return: None if ok, descriptive text if error
1404 """
1405 target, _, _id = target_id.partition(":")
sousaedu80135b92021-02-17 15:05:18 +01001406 target_database = (
1407 "vim_accounts"
1408 if target == "vim"
1409 else "wim_accounts"
1410 if target == "wim"
1411 else "sdns"
1412 )
tierno70eeb182020-10-19 16:38:00 +00001413 plugin_name = ""
1414 vim = None
sousaedu80135b92021-02-17 15:05:18 +01001415
tierno70eeb182020-10-19 16:38:00 +00001416 try:
1417 step = "Getting {}={} from db".format(target, _id)
1418 # TODO process for wim, sdnc, ...
1419 vim = self.db.get_one(target_database, {"_id": _id})
1420
1421 # if deep_get(vim, "config", "sdn-controller"):
1422 # step = "Getting sdn-controller-id='{}' from db".format(vim["config"]["sdn-controller"])
1423 # db_sdn = self.db.get_one("sdns", {"_id": vim["config"]["sdn-controller"]})
1424
1425 step = "Decrypting password"
1426 schema_version = vim.get("schema_version")
sousaedu80135b92021-02-17 15:05:18 +01001427 self.db.encrypt_decrypt_fields(
1428 vim,
1429 "decrypt",
1430 fields=("password", "secret"),
1431 schema_version=schema_version,
1432 salt=_id,
1433 )
tierno70eeb182020-10-19 16:38:00 +00001434 self._process_vim_config(target_id, vim)
sousaedu80135b92021-02-17 15:05:18 +01001435
tierno70eeb182020-10-19 16:38:00 +00001436 if target == "vim":
1437 plugin_name = "rovim_" + vim["vim_type"]
1438 step = "Loading plugin '{}'".format(plugin_name)
1439 vim_module_conn = self._load_plugin(plugin_name)
1440 step = "Loading {}'".format(target_id)
1441 self.my_vims[target_id] = vim_module_conn(
sousaedu80135b92021-02-17 15:05:18 +01001442 uuid=vim["_id"],
1443 name=vim["name"],
1444 tenant_id=vim.get("vim_tenant_id"),
1445 tenant_name=vim.get("vim_tenant_name"),
1446 url=vim["vim_url"],
1447 url_admin=None,
1448 user=vim["vim_user"],
1449 passwd=vim["vim_password"],
1450 config=vim.get("config") or {},
1451 persistent_info={},
tierno70eeb182020-10-19 16:38:00 +00001452 )
1453 else: # sdn
1454 plugin_name = "rosdn_" + vim["type"]
1455 step = "Loading plugin '{}'".format(plugin_name)
1456 vim_module_conn = self._load_plugin(plugin_name, "sdn")
1457 step = "Loading {}'".format(target_id)
1458 wim = deepcopy(vim)
1459 wim_config = wim.pop("config", {}) or {}
1460 wim["uuid"] = wim["_id"]
1461 wim["wim_url"] = wim["url"]
sousaedu80135b92021-02-17 15:05:18 +01001462
tierno70eeb182020-10-19 16:38:00 +00001463 if wim.get("dpid"):
1464 wim_config["dpid"] = wim.pop("dpid")
sousaedu80135b92021-02-17 15:05:18 +01001465
tierno70eeb182020-10-19 16:38:00 +00001466 if wim.get("switch_id"):
1467 wim_config["switch_id"] = wim.pop("switch_id")
sousaedu80135b92021-02-17 15:05:18 +01001468
1469 # wim, wim_account, config
1470 self.my_vims[target_id] = vim_module_conn(wim, wim, wim_config)
tierno70eeb182020-10-19 16:38:00 +00001471 self.db_vims[target_id] = vim
1472 self.error_status = None
sousaedu80135b92021-02-17 15:05:18 +01001473
1474 self.logger.info(
1475 "Connector loaded for {}, plugin={}".format(target_id, plugin_name)
1476 )
tierno70eeb182020-10-19 16:38:00 +00001477 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001478 self.logger.error(
1479 "Cannot load {} plugin={}: {} {}".format(
1480 target_id, plugin_name, step, e
1481 )
1482 )
1483
tierno70eeb182020-10-19 16:38:00 +00001484 self.db_vims[target_id] = vim or {}
1485 self.db_vims[target_id] = FailingConnector(str(e))
1486 error_status = "{} Error: {}".format(step, e)
sousaedu80135b92021-02-17 15:05:18 +01001487
tierno70eeb182020-10-19 16:38:00 +00001488 return error_status
1489 finally:
1490 if target_id not in self.vim_targets:
1491 self.vim_targets.append(target_id)
1492
1493 def _get_db_task(self):
1494 """
1495 Read actions from database and reload them at memory. Fill self.refresh_list, pending_list, vim_actions
1496 :return: None
1497 """
1498 now = time.time()
sousaedu80135b92021-02-17 15:05:18 +01001499
tierno70eeb182020-10-19 16:38:00 +00001500 if not self.time_last_task_processed:
1501 self.time_last_task_processed = now
sousaedu80135b92021-02-17 15:05:18 +01001502
tierno70eeb182020-10-19 16:38:00 +00001503 try:
1504 while True:
1505 locked = self.db.set_one(
1506 "ro_tasks",
sousaedu80135b92021-02-17 15:05:18 +01001507 q_filter={
1508 "target_id": self.vim_targets,
1509 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
1510 "locked_at.lt": now - self.task_locked_time,
1511 "to_check_at.lt": self.time_last_task_processed,
1512 },
tierno70eeb182020-10-19 16:38:00 +00001513 update_dict={"locked_by": self.my_id, "locked_at": now},
sousaedu80135b92021-02-17 15:05:18 +01001514 fail_on_empty=False,
1515 )
1516
tierno70eeb182020-10-19 16:38:00 +00001517 if locked:
1518 # read and return
1519 ro_task = self.db.get_one(
1520 "ro_tasks",
sousaedu80135b92021-02-17 15:05:18 +01001521 q_filter={
1522 "target_id": self.vim_targets,
1523 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
1524 "locked_at": now,
1525 },
1526 )
tierno70eeb182020-10-19 16:38:00 +00001527 return ro_task
sousaedu80135b92021-02-17 15:05:18 +01001528
tierno70eeb182020-10-19 16:38:00 +00001529 if self.time_last_task_processed == now:
1530 self.time_last_task_processed = None
1531 return None
1532 else:
1533 self.time_last_task_processed = now
1534 # self.time_last_task_processed = min(self.time_last_task_processed + 1000, now)
1535
1536 except DbException as e:
1537 self.logger.error("Database exception at _get_db_task: {}".format(e))
1538 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001539 self.logger.critical(
1540 "Unexpected exception at _get_db_task: {}".format(e), exc_info=True
1541 )
1542
tierno70eeb182020-10-19 16:38:00 +00001543 return None
1544
1545 def _delete_task(self, ro_task, task_index, task_depends, db_update):
1546 """
1547 Determine if this task need to be done or superseded
1548 :return: None
1549 """
1550 my_task = ro_task["tasks"][task_index]
1551 task_id = my_task["task_id"]
sousaedu80135b92021-02-17 15:05:18 +01001552 needed_delete = ro_task["vim_info"]["created"] or ro_task["vim_info"].get(
1553 "created_items", False
1554 )
1555
tierno70eeb182020-10-19 16:38:00 +00001556 if my_task["status"] == "FAILED":
1557 return None, None # TODO need to be retry??
sousaedu80135b92021-02-17 15:05:18 +01001558
tierno70eeb182020-10-19 16:38:00 +00001559 try:
1560 for index, task in enumerate(ro_task["tasks"]):
1561 if index == task_index or not task:
1562 continue # own task
sousaedu80135b92021-02-17 15:05:18 +01001563
1564 if (
1565 my_task["target_record"] == task["target_record"]
1566 and task["action"] == "CREATE"
1567 ):
tierno70eeb182020-10-19 16:38:00 +00001568 # set to finished
sousaedu80135b92021-02-17 15:05:18 +01001569 db_update["tasks.{}.status".format(index)] = task[
1570 "status"
1571 ] = "FINISHED"
1572 elif task["action"] == "CREATE" and task["status"] not in (
1573 "FINISHED",
1574 "SUPERSEDED",
1575 ):
tierno70eeb182020-10-19 16:38:00 +00001576 needed_delete = False
sousaedu80135b92021-02-17 15:05:18 +01001577
tierno70eeb182020-10-19 16:38:00 +00001578 if needed_delete:
1579 return self.item2class[my_task["item"]].delete(ro_task, task_index)
1580 else:
1581 return "SUPERSEDED", None
1582 except Exception as e:
1583 if not isinstance(e, NsWorkerException):
sousaedu80135b92021-02-17 15:05:18 +01001584 self.logger.critical(
1585 "Unexpected exception at _delete_task task={}: {}".format(
1586 task_id, e
1587 ),
1588 exc_info=True,
1589 )
1590
tierno70eeb182020-10-19 16:38:00 +00001591 return "FAILED", {"vim_status": "VIM_ERROR", "vim_details": str(e)}
1592
1593 def _create_task(self, ro_task, task_index, task_depends, db_update):
1594 """
1595 Determine if this task need to create something at VIM
1596 :return: None
1597 """
1598 my_task = ro_task["tasks"][task_index]
1599 task_id = my_task["task_id"]
1600 task_status = None
sousaedu80135b92021-02-17 15:05:18 +01001601
tierno70eeb182020-10-19 16:38:00 +00001602 if my_task["status"] == "FAILED":
1603 return None, None # TODO need to be retry??
1604 elif my_task["status"] == "SCHEDULED":
1605 # check if already created by another task
1606 for index, task in enumerate(ro_task["tasks"]):
1607 if index == task_index or not task:
1608 continue # own task
sousaedu80135b92021-02-17 15:05:18 +01001609
1610 if task["action"] == "CREATE" and task["status"] not in (
1611 "SCHEDULED",
1612 "FINISHED",
1613 "SUPERSEDED",
1614 ):
tierno70eeb182020-10-19 16:38:00 +00001615 return task["status"], "COPY_VIM_INFO"
1616
1617 try:
1618 task_status, ro_vim_item_update = self.item2class[my_task["item"]].new(
sousaedu80135b92021-02-17 15:05:18 +01001619 ro_task, task_index, task_depends
1620 )
tierno70eeb182020-10-19 16:38:00 +00001621 # TODO update other CREATE tasks
1622 except Exception as e:
1623 if not isinstance(e, NsWorkerException):
sousaedu80135b92021-02-17 15:05:18 +01001624 self.logger.error(
1625 "Error executing task={}: {}".format(task_id, e), exc_info=True
1626 )
1627
tierno70eeb182020-10-19 16:38:00 +00001628 task_status = "FAILED"
1629 ro_vim_item_update = {"vim_status": "VIM_ERROR", "vim_details": str(e)}
1630 # TODO update ro_vim_item_update
sousaedu80135b92021-02-17 15:05:18 +01001631
tierno70eeb182020-10-19 16:38:00 +00001632 return task_status, ro_vim_item_update
1633 else:
1634 return None, None
1635
1636 def _get_dependency(self, task_id, ro_task=None, target_id=None):
1637 """
1638 Look for dependency task
1639 :param task_id: Can be one of
1640 1. target_vim+blank+task.target_record_id: "(vim|sdn|wim):<id> (vnfrs|nsrs):(vld|vdu|flavor|image).<id>"
1641 2. task.target_record_id: "(vnfrs|nsrs):(vld|vdu|flavor|image).<id>"
1642 3. task.task_id: "<action_id>:number"
1643 :param ro_task:
1644 :param target_id:
1645 :return: database ro_task plus index of task
1646 """
sousaedu80135b92021-02-17 15:05:18 +01001647 if (
1648 task_id.startswith("vim:")
1649 or task_id.startswith("sdn:")
1650 or task_id.startswith("wim:")
1651 ):
tierno70eeb182020-10-19 16:38:00 +00001652 target_id, _, task_id = task_id.partition(" ")
1653
1654 if task_id.startswith("nsrs:") or task_id.startswith("vnfrs:"):
1655 ro_task_dependency = self.db.get_one(
1656 "ro_tasks",
sousaedu80135b92021-02-17 15:05:18 +01001657 q_filter={"target_id": target_id, "tasks.target_record_id": task_id},
1658 fail_on_empty=False,
1659 )
1660
tierno70eeb182020-10-19 16:38:00 +00001661 if ro_task_dependency:
1662 for task_index, task in enumerate(ro_task_dependency["tasks"]):
1663 if task["target_record_id"] == task_id:
1664 return ro_task_dependency, task_index
1665
1666 else:
1667 if ro_task:
1668 for task_index, task in enumerate(ro_task["tasks"]):
1669 if task and task["task_id"] == task_id:
1670 return ro_task, task_index
sousaedu80135b92021-02-17 15:05:18 +01001671
tierno70eeb182020-10-19 16:38:00 +00001672 ro_task_dependency = self.db.get_one(
1673 "ro_tasks",
sousaedu80135b92021-02-17 15:05:18 +01001674 q_filter={
1675 "tasks.ANYINDEX.task_id": task_id,
1676 "tasks.ANYINDEX.target_record.ne": None,
1677 },
1678 fail_on_empty=False,
1679 )
1680
tierno70eeb182020-10-19 16:38:00 +00001681 if ro_task_dependency:
1682 for task_index, task in ro_task_dependency["tasks"]:
1683 if task["task_id"] == task_id:
1684 return ro_task_dependency, task_index
1685 raise NsWorkerException("Cannot get depending task {}".format(task_id))
1686
1687 def _process_pending_tasks(self, ro_task):
1688 ro_task_id = ro_task["_id"]
1689 now = time.time()
sousaedu80135b92021-02-17 15:05:18 +01001690 # one day
1691 next_check_at = now + (24 * 60 * 60)
tierno70eeb182020-10-19 16:38:00 +00001692 db_ro_task_update = {}
1693
1694 def _update_refresh(new_status):
1695 # compute next_refresh
1696 nonlocal task
1697 nonlocal next_check_at
1698 nonlocal db_ro_task_update
1699 nonlocal ro_task
1700
1701 next_refresh = time.time()
sousaedu80135b92021-02-17 15:05:18 +01001702
tierno70eeb182020-10-19 16:38:00 +00001703 if task["item"] in ("image", "flavor"):
1704 next_refresh += self.REFRESH_IMAGE
1705 elif new_status == "BUILD":
1706 next_refresh += self.REFRESH_BUILD
1707 elif new_status == "DONE":
1708 next_refresh += self.REFRESH_ACTIVE
1709 else:
1710 next_refresh += self.REFRESH_ERROR
sousaedu80135b92021-02-17 15:05:18 +01001711
tierno70eeb182020-10-19 16:38:00 +00001712 next_check_at = min(next_check_at, next_refresh)
1713 db_ro_task_update["vim_info.refresh_at"] = next_refresh
1714 ro_task["vim_info"]["refresh_at"] = next_refresh
1715
1716 try:
tiernof1b640f2020-12-09 15:06:01 +00001717 # 0: get task_status_create
1718 lock_object = None
tierno70eeb182020-10-19 16:38:00 +00001719 task_status_create = None
sousaedu80135b92021-02-17 15:05:18 +01001720 task_create = next(
1721 (
1722 t
1723 for t in ro_task["tasks"]
1724 if t
1725 and t["action"] == "CREATE"
1726 and t["status"] in ("BUILD", "DONE")
1727 ),
1728 None,
1729 )
1730
tierno70eeb182020-10-19 16:38:00 +00001731 if task_create:
1732 task_status_create = task_create["status"]
sousaedu80135b92021-02-17 15:05:18 +01001733
tiernof1b640f2020-12-09 15:06:01 +00001734 # 1: look for tasks in status SCHEDULED, or in status CREATE if action is DONE or BUILD
tierno70eeb182020-10-19 16:38:00 +00001735 for task_action in ("DELETE", "CREATE", "EXEC"):
1736 db_vim_update = None
1737 new_status = None
sousaedu80135b92021-02-17 15:05:18 +01001738
tierno70eeb182020-10-19 16:38:00 +00001739 for task_index, task in enumerate(ro_task["tasks"]):
1740 if not task:
1741 continue # task deleted
sousaedu80135b92021-02-17 15:05:18 +01001742
tierno55fa0bb2020-12-08 23:11:53 +00001743 task_depends = {}
tierno70eeb182020-10-19 16:38:00 +00001744 target_update = None
sousaedu80135b92021-02-17 15:05:18 +01001745
1746 if (
1747 (
1748 task_action in ("DELETE", "EXEC")
1749 and task["status"] not in ("SCHEDULED", "BUILD")
1750 )
1751 or task["action"] != task_action
1752 or (
1753 task_action == "CREATE"
1754 and task["status"] in ("FINISHED", "SUPERSEDED")
1755 )
1756 ):
tierno70eeb182020-10-19 16:38:00 +00001757 continue
sousaedu80135b92021-02-17 15:05:18 +01001758
tierno70eeb182020-10-19 16:38:00 +00001759 task_path = "tasks.{}.status".format(task_index)
1760 try:
1761 db_vim_info_update = None
sousaedu80135b92021-02-17 15:05:18 +01001762
tierno70eeb182020-10-19 16:38:00 +00001763 if task["status"] == "SCHEDULED":
tierno70eeb182020-10-19 16:38:00 +00001764 # check if tasks that this depends on have been completed
1765 dependency_not_completed = False
sousaedu80135b92021-02-17 15:05:18 +01001766
1767 for dependency_task_id in task.get("depends_on") or ():
1768 (
1769 dependency_ro_task,
1770 dependency_task_index,
1771 ) = self._get_dependency(
1772 dependency_task_id, target_id=ro_task["target_id"]
1773 )
1774 dependency_task = dependency_ro_task["tasks"][
1775 dependency_task_index
1776 ]
1777
tierno70eeb182020-10-19 16:38:00 +00001778 if dependency_task["status"] == "SCHEDULED":
1779 dependency_not_completed = True
sousaedu80135b92021-02-17 15:05:18 +01001780 next_check_at = min(
1781 next_check_at, dependency_ro_task["to_check_at"]
1782 )
lloretgalleg88486222021-02-19 12:06:52 +00001783 # must allow dependent task to be processed first
1784 # to do this set time after last_task_processed
1785 next_check_at = max(
1786 self.time_last_task_processed, next_check_at
1787 )
tierno70eeb182020-10-19 16:38:00 +00001788 break
1789 elif dependency_task["status"] == "FAILED":
1790 error_text = "Cannot {} {} because depends on failed {} {} id={}): {}".format(
sousaedu80135b92021-02-17 15:05:18 +01001791 task["action"],
1792 task["item"],
1793 dependency_task["action"],
1794 dependency_task["item"],
1795 dependency_task_id,
1796 dependency_ro_task["vim_info"].get(
1797 "vim_details"
1798 ),
1799 )
1800 self.logger.error(
1801 "task={} {}".format(task["task_id"], error_text)
1802 )
tierno70eeb182020-10-19 16:38:00 +00001803 raise NsWorkerException(error_text)
1804
sousaedu80135b92021-02-17 15:05:18 +01001805 task_depends[dependency_task_id] = dependency_ro_task[
1806 "vim_info"
1807 ]["vim_id"]
1808 task_depends[
1809 "TASK-{}".format(dependency_task_id)
1810 ] = dependency_ro_task["vim_info"]["vim_id"]
1811
tierno70eeb182020-10-19 16:38:00 +00001812 if dependency_not_completed:
1813 # TODO set at vim_info.vim_details that it is waiting
1814 continue
sousaedu80135b92021-02-17 15:05:18 +01001815
tiernof1b640f2020-12-09 15:06:01 +00001816 # before calling VIM-plugin as it can take more than task_locked_time, insert to LockRenew
1817 # the task of renew this locking. It will update database locket_at periodically
1818 if not lock_object:
sousaedu80135b92021-02-17 15:05:18 +01001819 lock_object = LockRenew.add_lock_object(
1820 "ro_tasks", ro_task, self
1821 )
1822
tierno70eeb182020-10-19 16:38:00 +00001823 if task["action"] == "DELETE":
sousaedu80135b92021-02-17 15:05:18 +01001824 (new_status, db_vim_info_update,) = self._delete_task(
1825 ro_task, task_index, task_depends, db_ro_task_update
1826 )
1827 new_status = (
1828 "FINISHED" if new_status == "DONE" else new_status
1829 )
tierno70eeb182020-10-19 16:38:00 +00001830 # ^with FINISHED instead of DONE it will not be refreshing
sousaedu80135b92021-02-17 15:05:18 +01001831
tierno70eeb182020-10-19 16:38:00 +00001832 if new_status in ("FINISHED", "SUPERSEDED"):
1833 target_update = "DELETE"
1834 elif task["action"] == "EXEC":
sousaedu80135b92021-02-17 15:05:18 +01001835 (
1836 new_status,
1837 db_vim_info_update,
1838 db_task_update,
1839 ) = self.item2class[task["item"]].exec(
1840 ro_task, task_index, task_depends
1841 )
1842 new_status = (
1843 "FINISHED" if new_status == "DONE" else new_status
1844 )
tierno70eeb182020-10-19 16:38:00 +00001845 # ^with FINISHED instead of DONE it will not be refreshing
sousaedu80135b92021-02-17 15:05:18 +01001846
tierno70eeb182020-10-19 16:38:00 +00001847 if db_task_update:
1848 # load into database the modified db_task_update "retries" and "next_retry"
1849 if db_task_update.get("retries"):
sousaedu80135b92021-02-17 15:05:18 +01001850 db_ro_task_update[
1851 "tasks.{}.retries".format(task_index)
1852 ] = db_task_update["retries"]
1853
1854 next_check_at = time.time() + db_task_update.get(
1855 "next_retry", 60
1856 )
tierno70eeb182020-10-19 16:38:00 +00001857 target_update = None
1858 elif task["action"] == "CREATE":
1859 if task["status"] == "SCHEDULED":
1860 if task_status_create:
1861 new_status = task_status_create
1862 target_update = "COPY_VIM_INFO"
1863 else:
sousaedu80135b92021-02-17 15:05:18 +01001864 new_status, db_vim_info_update = self.item2class[
1865 task["item"]
1866 ].new(ro_task, task_index, task_depends)
tierno70eeb182020-10-19 16:38:00 +00001867 # self._create_task(ro_task, task_index, task_depends, db_ro_task_update)
1868 _update_refresh(new_status)
1869 else:
sousaedu80135b92021-02-17 15:05:18 +01001870 if (
1871 ro_task["vim_info"]["refresh_at"]
1872 and now > ro_task["vim_info"]["refresh_at"]
1873 ):
1874 new_status, db_vim_info_update = self.item2class[
1875 task["item"]
1876 ].refresh(ro_task)
tierno70eeb182020-10-19 16:38:00 +00001877 _update_refresh(new_status)
sousaedu80135b92021-02-17 15:05:18 +01001878
tierno70eeb182020-10-19 16:38:00 +00001879 except Exception as e:
1880 new_status = "FAILED"
sousaedu80135b92021-02-17 15:05:18 +01001881 db_vim_info_update = {
1882 "vim_status": "VIM_ERROR",
1883 "vim_details": str(e),
1884 }
1885
1886 if not isinstance(
1887 e, (NsWorkerException, vimconn.VimConnException)
1888 ):
1889 self.logger.error(
1890 "Unexpected exception at _delete_task task={}: {}".format(
1891 task["task_id"], e
1892 ),
1893 exc_info=True,
1894 )
tierno70eeb182020-10-19 16:38:00 +00001895
1896 try:
1897 if db_vim_info_update:
1898 db_vim_update = db_vim_info_update.copy()
sousaedu80135b92021-02-17 15:05:18 +01001899 db_ro_task_update.update(
1900 {
1901 "vim_info." + k: v
1902 for k, v in db_vim_info_update.items()
1903 }
1904 )
tierno70eeb182020-10-19 16:38:00 +00001905 ro_task["vim_info"].update(db_vim_info_update)
1906
1907 if new_status:
1908 if task_action == "CREATE":
1909 task_status_create = new_status
1910 db_ro_task_update[task_path] = new_status
tierno70eeb182020-10-19 16:38:00 +00001911
sousaedu80135b92021-02-17 15:05:18 +01001912 if target_update or db_vim_update:
tierno70eeb182020-10-19 16:38:00 +00001913 if target_update == "DELETE":
1914 self._update_target(task, None)
1915 elif target_update == "COPY_VIM_INFO":
1916 self._update_target(task, ro_task["vim_info"])
1917 else:
1918 self._update_target(task, db_vim_update)
1919
1920 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001921 if (
1922 isinstance(e, DbException)
1923 and e.http_code == HTTPStatus.NOT_FOUND
1924 ):
tierno70eeb182020-10-19 16:38:00 +00001925 # if the vnfrs or nsrs has been removed from database, this task must be removed
sousaedu80135b92021-02-17 15:05:18 +01001926 self.logger.debug(
1927 "marking to delete task={}".format(task["task_id"])
1928 )
tierno70eeb182020-10-19 16:38:00 +00001929 self.tasks_to_delete.append(task)
1930 else:
sousaedu80135b92021-02-17 15:05:18 +01001931 self.logger.error(
1932 "Unexpected exception at _update_target task={}: {}".format(
1933 task["task_id"], e
1934 ),
1935 exc_info=True,
1936 )
tierno70eeb182020-10-19 16:38:00 +00001937
tiernof1b640f2020-12-09 15:06:01 +00001938 locked_at = ro_task["locked_at"]
sousaedu80135b92021-02-17 15:05:18 +01001939
tiernof1b640f2020-12-09 15:06:01 +00001940 if lock_object:
sousaedu80135b92021-02-17 15:05:18 +01001941 locked_at = [
1942 lock_object["locked_at"],
1943 lock_object["locked_at"] + self.task_locked_time,
1944 ]
tiernof1b640f2020-12-09 15:06:01 +00001945 # locked_at contains two times to avoid race condition. In case the lock has been renew, it will
1946 # contain exactly locked_at + self.task_locked_time
1947 LockRenew.remove_lock_object(lock_object)
sousaedu80135b92021-02-17 15:05:18 +01001948
1949 q_filter = {
1950 "_id": ro_task["_id"],
1951 "to_check_at": ro_task["to_check_at"],
1952 "locked_at": locked_at,
1953 }
tierno70eeb182020-10-19 16:38:00 +00001954 # modify own task. Try filtering by to_next_check. For race condition if to_check_at has been modified,
1955 # outside this task (by ro_nbi) do not update it
1956 db_ro_task_update["locked_by"] = None
1957 # locked_at converted to int only for debugging. When has not decimals it means it has been unlocked
tiernof1b640f2020-12-09 15:06:01 +00001958 db_ro_task_update["locked_at"] = int(now - self.task_locked_time)
1959 db_ro_task_update["modified_at"] = now
tierno70eeb182020-10-19 16:38:00 +00001960 db_ro_task_update["to_check_at"] = next_check_at
sousaedu80135b92021-02-17 15:05:18 +01001961
1962 if not self.db.set_one(
1963 "ro_tasks",
1964 update_dict=db_ro_task_update,
1965 q_filter=q_filter,
1966 fail_on_empty=False,
1967 ):
tierno70eeb182020-10-19 16:38:00 +00001968 del db_ro_task_update["to_check_at"]
1969 del q_filter["to_check_at"]
sousaedu80135b92021-02-17 15:05:18 +01001970 self.db.set_one(
1971 "ro_tasks",
1972 q_filter=q_filter,
1973 update_dict=db_ro_task_update,
1974 fail_on_empty=True,
1975 )
tierno70eeb182020-10-19 16:38:00 +00001976 except DbException as e:
sousaedu80135b92021-02-17 15:05:18 +01001977 self.logger.error(
1978 "ro_task={} Error updating database {}".format(ro_task_id, e)
1979 )
tierno70eeb182020-10-19 16:38:00 +00001980 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01001981 self.logger.error(
1982 "Error executing ro_task={}: {}".format(ro_task_id, e), exc_info=True
1983 )
tierno70eeb182020-10-19 16:38:00 +00001984
1985 def _update_target(self, task, ro_vim_item_update):
1986 table, _, temp = task["target_record"].partition(":")
1987 _id, _, path_vim_status = temp.partition(":")
sousaedu80135b92021-02-17 15:05:18 +01001988 path_item = path_vim_status[: path_vim_status.rfind(".")]
1989 path_item = path_item[: path_item.rfind(".")]
tierno70eeb182020-10-19 16:38:00 +00001990 # path_vim_status: dot separated list targeting vim information, e.g. "vdur.10.vim_info.vim:id"
1991 # path_item: dot separated list targeting record information, e.g. "vdur.10"
sousaedu80135b92021-02-17 15:05:18 +01001992
tierno70eeb182020-10-19 16:38:00 +00001993 if ro_vim_item_update:
sousaedu80135b92021-02-17 15:05:18 +01001994 update_dict = {
1995 path_vim_status + "." + k: v
1996 for k, v in ro_vim_item_update.items()
1997 if k
1998 in ("vim_id", "vim_details", "vim_name", "vim_status", "interfaces")
1999 }
2000
tierno70eeb182020-10-19 16:38:00 +00002001 if path_vim_status.startswith("vdur."):
2002 # for backward compatibility, add vdur.name apart from vdur.vim_name
2003 if ro_vim_item_update.get("vim_name"):
2004 update_dict[path_item + ".name"] = ro_vim_item_update["vim_name"]
sousaedu80135b92021-02-17 15:05:18 +01002005
tierno70eeb182020-10-19 16:38:00 +00002006 # for backward compatibility, add vdur.vim-id apart from vdur.vim_id
2007 if ro_vim_item_update.get("vim_id"):
2008 update_dict[path_item + ".vim-id"] = ro_vim_item_update["vim_id"]
sousaedu80135b92021-02-17 15:05:18 +01002009
tierno70eeb182020-10-19 16:38:00 +00002010 # update general status
2011 if ro_vim_item_update.get("vim_status"):
sousaedu80135b92021-02-17 15:05:18 +01002012 update_dict[path_item + ".status"] = ro_vim_item_update[
2013 "vim_status"
2014 ]
2015
tierno70eeb182020-10-19 16:38:00 +00002016 if ro_vim_item_update.get("interfaces"):
2017 path_interfaces = path_item + ".interfaces"
sousaedu80135b92021-02-17 15:05:18 +01002018
tierno70eeb182020-10-19 16:38:00 +00002019 for i, iface in enumerate(ro_vim_item_update.get("interfaces")):
2020 if iface:
sousaedu80135b92021-02-17 15:05:18 +01002021 update_dict.update(
2022 {
2023 path_interfaces + ".{}.".format(i) + k: v
2024 for k, v in iface.items()
2025 if k in ("vlan", "compute_node", "pci")
2026 }
2027 )
2028
tierno70eeb182020-10-19 16:38:00 +00002029 # put ip_address and mac_address with ip-address and mac-address
sousaedu80135b92021-02-17 15:05:18 +01002030 if iface.get("ip_address"):
2031 update_dict[
2032 path_interfaces + ".{}.".format(i) + "ip-address"
2033 ] = iface["ip_address"]
2034
2035 if iface.get("mac_address"):
2036 update_dict[
2037 path_interfaces + ".{}.".format(i) + "mac-address"
2038 ] = iface["mac_address"]
2039
tierno70eeb182020-10-19 16:38:00 +00002040 if iface.get("mgmt_vnf_interface") and iface.get("ip_address"):
sousaedu80135b92021-02-17 15:05:18 +01002041 update_dict["ip-address"] = iface.get("ip_address").split(
2042 ";"
2043 )[0]
2044
tierno70eeb182020-10-19 16:38:00 +00002045 if iface.get("mgmt_vdu_interface") and iface.get("ip_address"):
sousaedu80135b92021-02-17 15:05:18 +01002046 update_dict[path_item + ".ip-address"] = iface.get(
2047 "ip_address"
2048 ).split(";")[0]
tierno70eeb182020-10-19 16:38:00 +00002049
2050 self.db.set_one(table, q_filter={"_id": _id}, update_dict=update_dict)
2051 else:
2052 update_dict = {path_item + ".status": "DELETED"}
sousaedu80135b92021-02-17 15:05:18 +01002053 self.db.set_one(
2054 table,
2055 q_filter={"_id": _id},
2056 update_dict=update_dict,
2057 unset={path_vim_status: None},
2058 )
tierno70eeb182020-10-19 16:38:00 +00002059
2060 def _process_delete_db_tasks(self):
2061 """
2062 Delete task from database because vnfrs or nsrs or both have been deleted
2063 :return: None. Uses and modify self.tasks_to_delete
2064 """
2065 while self.tasks_to_delete:
2066 task = self.tasks_to_delete[0]
2067 vnfrs_deleted = None
2068 nsr_id = task["nsr_id"]
sousaedu80135b92021-02-17 15:05:18 +01002069
tierno70eeb182020-10-19 16:38:00 +00002070 if task["target_record"].startswith("vnfrs:"):
2071 # check if nsrs is present
2072 if self.db.get_one("nsrs", {"_id": nsr_id}, fail_on_empty=False):
2073 vnfrs_deleted = task["target_record"].split(":")[1]
sousaedu80135b92021-02-17 15:05:18 +01002074
tierno70eeb182020-10-19 16:38:00 +00002075 try:
2076 self.delete_db_tasks(self.db, nsr_id, vnfrs_deleted)
2077 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002078 self.logger.error(
2079 "Error deleting task={}: {}".format(task["task_id"], e)
2080 )
tierno70eeb182020-10-19 16:38:00 +00002081 self.tasks_to_delete.pop(0)
2082
2083 @staticmethod
2084 def delete_db_tasks(db, nsr_id, vnfrs_deleted):
2085 """
2086 Static method because it is called from osm_ng_ro.ns
2087 :param db: instance of database to use
2088 :param nsr_id: affected nsrs id
2089 :param vnfrs_deleted: only tasks with this vnfr id. If None, all affected by nsr_id
2090 :return: None, exception is fails
2091 """
2092 retries = 5
2093 for retry in range(retries):
2094 ro_tasks = db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2095 now = time.time()
2096 conflict = False
sousaedu80135b92021-02-17 15:05:18 +01002097
tierno70eeb182020-10-19 16:38:00 +00002098 for ro_task in ro_tasks:
2099 db_update = {}
2100 to_delete_ro_task = True
sousaedu80135b92021-02-17 15:05:18 +01002101
tierno70eeb182020-10-19 16:38:00 +00002102 for index, task in enumerate(ro_task["tasks"]):
2103 if not task:
2104 pass
sousaedu80135b92021-02-17 15:05:18 +01002105 elif (not vnfrs_deleted and task["nsr_id"] == nsr_id) or (
2106 vnfrs_deleted
2107 and task["target_record"].startswith("vnfrs:" + vnfrs_deleted)
2108 ):
tierno70eeb182020-10-19 16:38:00 +00002109 db_update["tasks.{}".format(index)] = None
2110 else:
sousaedu80135b92021-02-17 15:05:18 +01002111 # used by other nsr, ro_task cannot be deleted
2112 to_delete_ro_task = False
2113
tierno70eeb182020-10-19 16:38:00 +00002114 # delete or update if nobody has changed ro_task meanwhile. Used modified_at for known if changed
2115 if to_delete_ro_task:
sousaedu80135b92021-02-17 15:05:18 +01002116 if not db.del_one(
2117 "ro_tasks",
2118 q_filter={
2119 "_id": ro_task["_id"],
2120 "modified_at": ro_task["modified_at"],
2121 },
2122 fail_on_empty=False,
2123 ):
tierno70eeb182020-10-19 16:38:00 +00002124 conflict = True
2125 elif db_update:
2126 db_update["modified_at"] = now
sousaedu80135b92021-02-17 15:05:18 +01002127 if not db.set_one(
2128 "ro_tasks",
2129 q_filter={
2130 "_id": ro_task["_id"],
2131 "modified_at": ro_task["modified_at"],
2132 },
2133 update_dict=db_update,
2134 fail_on_empty=False,
2135 ):
tierno70eeb182020-10-19 16:38:00 +00002136 conflict = True
2137 if not conflict:
2138 return
2139 else:
2140 raise NsWorkerException("Exceeded {} retries".format(retries))
2141
tierno1d213f42020-04-24 14:02:51 +00002142 def run(self):
2143 # load database
tierno86153522020-12-06 18:27:16 +00002144 self.logger.info("Starting")
tierno1d213f42020-04-24 14:02:51 +00002145 while True:
tierno70eeb182020-10-19 16:38:00 +00002146 # step 1: get commands from queue
tierno1d213f42020-04-24 14:02:51 +00002147 try:
tierno86153522020-12-06 18:27:16 +00002148 if self.vim_targets:
2149 task = self.task_queue.get(block=False)
2150 else:
2151 if not self.idle:
2152 self.logger.debug("enters in idle state")
2153 self.idle = True
2154 task = self.task_queue.get(block=True)
2155 self.idle = False
2156
tierno1d213f42020-04-24 14:02:51 +00002157 if task[0] == "terminate":
2158 break
tierno70eeb182020-10-19 16:38:00 +00002159 elif task[0] == "load_vim":
tierno86153522020-12-06 18:27:16 +00002160 self.logger.info("order to load vim {}".format(task[1]))
tierno1d213f42020-04-24 14:02:51 +00002161 self._load_vim(task[1])
tierno70eeb182020-10-19 16:38:00 +00002162 elif task[0] == "unload_vim":
tierno86153522020-12-06 18:27:16 +00002163 self.logger.info("order to unload vim {}".format(task[1]))
tierno70eeb182020-10-19 16:38:00 +00002164 self._unload_vim(task[1])
2165 elif task[0] == "reload_vim":
2166 self._reload_vim(task[1])
2167 elif task[0] == "check_vim":
tierno86153522020-12-06 18:27:16 +00002168 self.logger.info("order to check vim {}".format(task[1]))
tierno70eeb182020-10-19 16:38:00 +00002169 self._check_vim(task[1])
tierno1d213f42020-04-24 14:02:51 +00002170 continue
tierno70eeb182020-10-19 16:38:00 +00002171 except Exception as e:
2172 if isinstance(e, queue.Empty):
2173 pass
2174 else:
sousaedu80135b92021-02-17 15:05:18 +01002175 self.logger.critical(
2176 "Error processing task: {}".format(e), exc_info=True
2177 )
tierno1d213f42020-04-24 14:02:51 +00002178
tierno70eeb182020-10-19 16:38:00 +00002179 # step 2: process pending_tasks, delete not needed tasks
tierno1d213f42020-04-24 14:02:51 +00002180 try:
tierno70eeb182020-10-19 16:38:00 +00002181 if self.tasks_to_delete:
2182 self._process_delete_db_tasks()
tierno1d213f42020-04-24 14:02:51 +00002183 busy = False
2184 ro_task = self._get_db_task()
2185 if ro_task:
tierno70eeb182020-10-19 16:38:00 +00002186 self._process_pending_tasks(ro_task)
tierno1d213f42020-04-24 14:02:51 +00002187 busy = True
2188 if not busy:
2189 time.sleep(5)
2190 except Exception as e:
sousaedu80135b92021-02-17 15:05:18 +01002191 self.logger.critical(
2192 "Unexpected exception at run: " + str(e), exc_info=True
2193 )
tierno1d213f42020-04-24 14:02:51 +00002194
tierno86153522020-12-06 18:27:16 +00002195 self.logger.info("Finishing")