+ params_copy["ro_key"] = self.db.decrypt(
+ params_copy.pop("private_key"),
+ params_copy.pop("schema_version"),
+ params_copy.pop("salt"),
+ )
+ params_copy["ip_addr"] = params_copy.pop("ip_address")
+ target_vim.inject_user_key(**params_copy)
+ self.logger.debug(
+ "task={} {} action-vm=inject_key".format(task_id, ro_task["target_id"])
+ )
+
+ return (
+ "DONE",
+ None,
+ db_task_update,
+ ) # params_copy["key"]
+ except (vimconn.VimConnException, NsWorkerException) as e:
+ retries += 1
+
+ if retries < self.max_retries_inject_ssh_key:
+ return (
+ "BUILD",
+ None,
+ {
+ "retries": retries,
+ "next_retry": self.time_retries_inject_ssh_key,
+ },
+ )
+
+ self.logger.error(
+ "task={} {} inject-ssh-key: {}".format(task_id, ro_task["target_id"], e)
+ )
+ ro_vim_item_update = {"vim_details": str(e)}
+
+ return "FAILED", ro_vim_item_update, db_task_update
+
+
+class VimInteractionImage(VimInteractionBase):
+ def new(self, ro_task, task_index, task_depends):
+ task = ro_task["tasks"][task_index]
+ task_id = task["task_id"]
+ created = False
+ created_items = {}
+ target_vim = self.my_vims[ro_task["target_id"]]
+
+ try:
+ # FIND
+ if task.get("find_params"):
+ vim_images = target_vim.get_image_list(**task["find_params"])
+
+ if not vim_images:
+ raise NsWorkerExceptionNotFound(
+ "Image not found with this criteria: '{}'".format(
+ task["find_params"]
+ )
+ )
+ elif len(vim_images) > 1:
+ raise NsWorkerException(
+ "More than one image found with this criteria: '{}'".format(
+ task["find_params"]
+ )
+ )
+ else:
+ vim_image_id = vim_images[0]["id"]
+
+ ro_vim_item_update = {
+ "vim_id": vim_image_id,
+ "vim_status": "DONE",
+ "created": created,
+ "created_items": created_items,
+ "vim_details": None,
+ }
+ self.logger.debug(
+ "task={} {} new-image={} created={}".format(
+ task_id, ro_task["target_id"], vim_image_id, created
+ )
+ )
+
+ return "DONE", ro_vim_item_update
+ except (NsWorkerException, vimconn.VimConnException) as e:
+ self.logger.error(
+ "task={} {} new-image: {}".format(task_id, ro_task["target_id"], e)
+ )
+ ro_vim_item_update = {
+ "vim_status": "VIM_ERROR",
+ "created": created,
+ "vim_details": str(e),
+ }
+
+ return "FAILED", ro_vim_item_update
+
+
+class VimInteractionFlavor(VimInteractionBase):
+ def delete(self, ro_task, task_index):
+ task = ro_task["tasks"][task_index]
+ task_id = task["task_id"]
+ flavor_vim_id = ro_task["vim_info"]["vim_id"]
+ ro_vim_item_update_ok = {
+ "vim_status": "DELETED",
+ "created": False,
+ "vim_details": "DELETED",
+ "vim_id": None,
+ }
+
+ try:
+ if flavor_vim_id:
+ target_vim = self.my_vims[ro_task["target_id"]]
+ target_vim.delete_flavor(flavor_vim_id)
+ except vimconn.VimConnNotFoundException:
+ ro_vim_item_update_ok["vim_details"] = "already deleted"
+ except vimconn.VimConnException as e:
+ self.logger.error(
+ "ro_task={} vim={} del-flavor={}: {}".format(
+ ro_task["_id"], ro_task["target_id"], flavor_vim_id, e
+ )
+ )
+ ro_vim_item_update = {
+ "vim_status": "VIM_ERROR",
+ "vim_details": "Error while deleting: {}".format(e),
+ }
+
+ return "FAILED", ro_vim_item_update
+
+ self.logger.debug(
+ "task={} {} del-flavor={} {}".format(
+ task_id,
+ ro_task["target_id"],
+ flavor_vim_id,
+ ro_vim_item_update_ok.get("vim_details", ""),
+ )
+ )
+
+ return "DONE", ro_vim_item_update_ok
+
+ def new(self, ro_task, task_index, task_depends):
+ task = ro_task["tasks"][task_index]
+ task_id = task["task_id"]
+ created = False
+ created_items = {}
+ target_vim = self.my_vims[ro_task["target_id"]]
+
+ try:
+ # FIND
+ vim_flavor_id = None
+
+ if task.get("find_params"):
+ try:
+ flavor_data = task["find_params"]["flavor_data"]
+ vim_flavor_id = target_vim.get_flavor_id_from_data(flavor_data)
+ except vimconn.VimConnNotFoundException:
+ pass
+
+ if not vim_flavor_id and task.get("params"):
+ # CREATE
+ flavor_data = task["params"]["flavor_data"]
+ vim_flavor_id = target_vim.new_flavor(flavor_data)
+ created = True
+
+ ro_vim_item_update = {
+ "vim_id": vim_flavor_id,
+ "vim_status": "DONE",
+ "created": created,
+ "created_items": created_items,
+ "vim_details": None,
+ }
+ self.logger.debug(
+ "task={} {} new-flavor={} created={}".format(
+ task_id, ro_task["target_id"], vim_flavor_id, created
+ )
+ )
+
+ return "DONE", ro_vim_item_update
+ except (vimconn.VimConnException, NsWorkerException) as e:
+ self.logger.error(
+ "task={} vim={} new-flavor: {}".format(task_id, ro_task["target_id"], e)
+ )
+ ro_vim_item_update = {
+ "vim_status": "VIM_ERROR",
+ "created": created,
+ "vim_details": str(e),
+ }
+
+ return "FAILED", ro_vim_item_update
+
+
+class VimInteractionSdnNet(VimInteractionBase):
+ @staticmethod
+ def _match_pci(port_pci, mapping):
+ """
+ Check if port_pci matches with mapping
+ mapping can have brackets to indicate that several chars are accepted. e.g
+ pci '0000:af:10.1' matches with '0000:af:1[01].[1357]'
+ :param port_pci: text
+ :param mapping: text, can contain brackets to indicate several chars are available
+ :return: True if matches, False otherwise
+ """
+ if not port_pci or not mapping:
+ return False
+ if port_pci == mapping:
+ return True
+
+ mapping_index = 0
+ pci_index = 0
+ while True:
+ bracket_start = mapping.find("[", mapping_index)
+
+ if bracket_start == -1:
+ break
+
+ bracket_end = mapping.find("]", bracket_start)
+ if bracket_end == -1:
+ break
+
+ length = bracket_start - mapping_index
+ if (
+ length
+ and port_pci[pci_index : pci_index + length]
+ != mapping[mapping_index:bracket_start]
+ ):
+ return False
+
+ if (
+ port_pci[pci_index + length]
+ not in mapping[bracket_start + 1 : bracket_end]
+ ):
+ return False
+
+ pci_index += length + 1
+ mapping_index = bracket_end + 1
+
+ if port_pci[pci_index:] != mapping[mapping_index:]:
+ return False
+
+ return True
+
+ def _get_interfaces(self, vlds_to_connect, vim_account_id):
+ """
+ :param vlds_to_connect: list with format vnfrs:<id>:vld.<vld_id> or nsrs:<id>:vld.<vld_id>
+ :param vim_account_id:
+ :return:
+ """
+ interfaces = []
+
+ for vld in vlds_to_connect:
+ table, _, db_id = vld.partition(":")
+ db_id, _, vld = db_id.partition(":")
+ _, _, vld_id = vld.partition(".")
+
+ if table == "vnfrs":
+ q_filter = {"vim-account-id": vim_account_id, "_id": db_id}
+ iface_key = "vnf-vld-id"
+ else: # table == "nsrs"
+ q_filter = {"vim-account-id": vim_account_id, "nsr-id-ref": db_id}
+ iface_key = "ns-vld-id"
+
+ db_vnfrs = self.db.get_list("vnfrs", q_filter=q_filter)
+
+ for db_vnfr in db_vnfrs:
+ for vdu_index, vdur in enumerate(db_vnfr.get("vdur", ())):
+ for iface_index, interface in enumerate(vdur["interfaces"]):
+ if interface.get(iface_key) == vld_id and interface.get(
+ "type"
+ ) in ("SR-IOV", "PCI-PASSTHROUGH"):
+ # only SR-IOV o PT
+ interface_ = interface.copy()
+ interface_["id"] = "vnfrs:{}:vdu.{}.interfaces.{}".format(
+ db_vnfr["_id"], vdu_index, iface_index
+ )
+
+ if vdur.get("status") == "ERROR":
+ interface_["status"] = "ERROR"
+
+ interfaces.append(interface_)
+
+ return interfaces
+
+ def refresh(self, ro_task):
+ # look for task create
+ task_create_index, _ = next(
+ i_t
+ for i_t in enumerate(ro_task["tasks"])
+ if i_t[1]
+ and i_t[1]["action"] == "CREATE"
+ and i_t[1]["status"] != "FINISHED"
+ )
+
+ return self.new(ro_task, task_create_index, None)
+
+ def new(self, ro_task, task_index, task_depends):
+
+ task = ro_task["tasks"][task_index]
+ task_id = task["task_id"]
+ target_vim = self.my_vims[ro_task["target_id"]]
+
+ sdn_net_id = ro_task["vim_info"]["vim_id"]
+
+ created_items = ro_task["vim_info"].get("created_items")
+ connected_ports = ro_task["vim_info"].get("connected_ports", [])
+ new_connected_ports = []
+ last_update = ro_task["vim_info"].get("last_update", 0)
+ sdn_status = ro_task["vim_info"].get("vim_status", "BUILD") or "BUILD"
+ error_list = []
+ created = ro_task["vim_info"].get("created", False)
+
+ try:
+ # CREATE
+ params = task["params"]
+ vlds_to_connect = params["vlds"]
+ associated_vim = params["target_vim"]
+ # external additional ports
+ additional_ports = params.get("sdn-ports") or ()
+ _, _, vim_account_id = associated_vim.partition(":")
+
+ if associated_vim:
+ # get associated VIM
+ if associated_vim not in self.db_vims:
+ self.db_vims[associated_vim] = self.db.get_one(
+ "vim_accounts", {"_id": vim_account_id}
+ )
+
+ db_vim = self.db_vims[associated_vim]
+
+ # look for ports to connect
+ ports = self._get_interfaces(vlds_to_connect, vim_account_id)
+ # print(ports)
+
+ sdn_ports = []
+ pending_ports = error_ports = 0
+ vlan_used = None
+ sdn_need_update = False
+
+ for port in ports:
+ vlan_used = port.get("vlan") or vlan_used
+
+ # TODO. Do not connect if already done
+ if not port.get("compute_node") or not port.get("pci"):
+ if port.get("status") == "ERROR":
+ error_ports += 1
+ else:
+ pending_ports += 1
+ continue
+
+ pmap = None
+ compute_node_mappings = next(
+ (
+ c
+ for c in db_vim["config"].get("sdn-port-mapping", ())
+ if c and c["compute_node"] == port["compute_node"]
+ ),
+ None,
+ )
+
+ if compute_node_mappings:
+ # process port_mapping pci of type 0000:af:1[01].[1357]
+ pmap = next(
+ (
+ p
+ for p in compute_node_mappings["ports"]
+ if self._match_pci(port["pci"], p.get("pci"))
+ ),
+ None,
+ )
+
+ if not pmap:
+ if not db_vim["config"].get("mapping_not_needed"):
+ error_list.append(
+ "Port mapping not found for compute_node={} pci={}".format(
+ port["compute_node"], port["pci"]
+ )
+ )
+ continue
+
+ pmap = {}
+
+ service_endpoint_id = "{}:{}".format(port["compute_node"], port["pci"])
+ new_port = {
+ "service_endpoint_id": pmap.get("service_endpoint_id")
+ or service_endpoint_id,
+ "service_endpoint_encapsulation_type": "dot1q"
+ if port["type"] == "SR-IOV"
+ else None,
+ "service_endpoint_encapsulation_info": {
+ "vlan": port.get("vlan"),
+ "mac": port.get("mac-address"),
+ "device_id": pmap.get("device_id") or port["compute_node"],
+ "device_interface_id": pmap.get("device_interface_id")
+ or port["pci"],
+ "switch_dpid": pmap.get("switch_id") or pmap.get("switch_dpid"),
+ "switch_port": pmap.get("switch_port"),
+ "service_mapping_info": pmap.get("service_mapping_info"),
+ },
+ }
+
+ # TODO
+ # if port["modified_at"] > last_update:
+ # sdn_need_update = True
+ new_connected_ports.append(port["id"]) # TODO
+ sdn_ports.append(new_port)
+
+ if error_ports:
+ error_list.append(
+ "{} interfaces have not been created as VDU is on ERROR status".format(
+ error_ports
+ )
+ )
+
+ # connect external ports
+ for index, additional_port in enumerate(additional_ports):
+ additional_port_id = additional_port.get(
+ "service_endpoint_id"
+ ) or "external-{}".format(index)
+ sdn_ports.append(
+ {
+ "service_endpoint_id": additional_port_id,
+ "service_endpoint_encapsulation_type": additional_port.get(
+ "service_endpoint_encapsulation_type", "dot1q"
+ ),
+ "service_endpoint_encapsulation_info": {
+ "vlan": additional_port.get("vlan") or vlan_used,
+ "mac": additional_port.get("mac_address"),
+ "device_id": additional_port.get("device_id"),
+ "device_interface_id": additional_port.get(
+ "device_interface_id"
+ ),
+ "switch_dpid": additional_port.get("switch_dpid")
+ or additional_port.get("switch_id"),
+ "switch_port": additional_port.get("switch_port"),
+ "service_mapping_info": additional_port.get(
+ "service_mapping_info"
+ ),
+ },
+ }
+ )
+ new_connected_ports.append(additional_port_id)
+ sdn_info = ""
+
+ # if there are more ports to connect or they have been modified, call create/update
+ if error_list:
+ sdn_status = "ERROR"
+ sdn_info = "; ".join(error_list)
+ elif set(connected_ports) != set(new_connected_ports) or sdn_need_update:
+ last_update = time.time()
+
+ if not sdn_net_id:
+ if len(sdn_ports) < 2:
+ sdn_status = "ACTIVE"
+
+ if not pending_ports:
+ self.logger.debug(
+ "task={} {} new-sdn-net done, less than 2 ports".format(
+ task_id, ro_task["target_id"]
+ )
+ )
+ else:
+ net_type = params.get("type") or "ELAN"
+ (
+ sdn_net_id,
+ created_items,
+ ) = target_vim.create_connectivity_service(net_type, sdn_ports)
+ created = True
+ self.logger.debug(
+ "task={} {} new-sdn-net={} created={}".format(
+ task_id, ro_task["target_id"], sdn_net_id, created
+ )
+ )
+ else:
+ created_items = target_vim.edit_connectivity_service(
+ sdn_net_id, conn_info=created_items, connection_points=sdn_ports
+ )
+ created = True
+ self.logger.debug(
+ "task={} {} update-sdn-net={} created={}".format(
+ task_id, ro_task["target_id"], sdn_net_id, created
+ )
+ )
+
+ connected_ports = new_connected_ports
+ elif sdn_net_id:
+ wim_status_dict = target_vim.get_connectivity_service_status(
+ sdn_net_id, conn_info=created_items
+ )
+ sdn_status = wim_status_dict["sdn_status"]
+
+ if wim_status_dict.get("sdn_info"):
+ sdn_info = str(wim_status_dict.get("sdn_info")) or ""
+
+ if wim_status_dict.get("error_msg"):
+ sdn_info = wim_status_dict.get("error_msg") or ""
+
+ if pending_ports:
+ if sdn_status != "ERROR":
+ sdn_info = "Waiting for getting interfaces location from VIM. Obtained '{}' of {}".format(
+ len(ports) - pending_ports, len(ports)
+ )
+
+ if sdn_status == "ACTIVE":
+ sdn_status = "BUILD"
+
+ ro_vim_item_update = {
+ "vim_id": sdn_net_id,
+ "vim_status": sdn_status,
+ "created": created,
+ "created_items": created_items,
+ "connected_ports": connected_ports,
+ "vim_details": sdn_info,
+ "last_update": last_update,
+ }
+
+ return sdn_status, ro_vim_item_update
+ except Exception as e:
+ self.logger.error(
+ "task={} vim={} new-net: {}".format(task_id, ro_task["target_id"], e),
+ exc_info=not isinstance(
+ e, (sdnconn.SdnConnectorError, vimconn.VimConnException)
+ ),
+ )
+ ro_vim_item_update = {
+ "vim_status": "VIM_ERROR",
+ "created": created,
+ "vim_details": str(e),
+ }
+
+ return "FAILED", ro_vim_item_update
+
+ def delete(self, ro_task, task_index):
+ task = ro_task["tasks"][task_index]
+ task_id = task["task_id"]
+ sdn_vim_id = ro_task["vim_info"].get("vim_id")
+ ro_vim_item_update_ok = {
+ "vim_status": "DELETED",
+ "created": False,
+ "vim_details": "DELETED",
+ "vim_id": None,
+ }
+
+ try:
+ if sdn_vim_id:
+ target_vim = self.my_vims[ro_task["target_id"]]
+ target_vim.delete_connectivity_service(
+ sdn_vim_id, ro_task["vim_info"].get("created_items")
+ )
+
+ except Exception as e:
+ if (
+ isinstance(e, sdnconn.SdnConnectorError)
+ and e.http_code == HTTPStatus.NOT_FOUND.value
+ ):
+ ro_vim_item_update_ok["vim_details"] = "already deleted"
+ else:
+ self.logger.error(
+ "ro_task={} vim={} del-sdn-net={}: {}".format(
+ ro_task["_id"], ro_task["target_id"], sdn_vim_id, e
+ ),
+ exc_info=not isinstance(
+ e, (sdnconn.SdnConnectorError, vimconn.VimConnException)
+ ),
+ )
+ ro_vim_item_update = {
+ "vim_status": "VIM_ERROR",
+ "vim_details": "Error while deleting: {}".format(e),
+ }
+
+ return "FAILED", ro_vim_item_update
+
+ self.logger.debug(
+ "task={} {} del-sdn-net={} {}".format(
+ task_id,
+ ro_task["target_id"],
+ sdn_vim_id,
+ ro_vim_item_update_ok.get("vim_details", ""),
+ )
+ )
+
+ return "DONE", ro_vim_item_update_ok
+
+
+class NsWorker(threading.Thread):
+ REFRESH_BUILD = 5 # 5 seconds
+ REFRESH_ACTIVE = 60 # 1 minute
+ REFRESH_ERROR = 600
+ REFRESH_IMAGE = 3600 * 10
+ REFRESH_DELETE = 3600 * 10
+ QUEUE_SIZE = 100
+ terminate = False
+
+ def __init__(self, worker_index, config, plugins, db):
+ """
+
+ :param worker_index: thread index
+ :param config: general configuration of RO, among others the process_id with the docker id where it runs
+ :param plugins: global shared dict with the loaded plugins
+ :param db: database class instance to use
+ """
+ threading.Thread.__init__(self)
+ self.config = config
+ self.plugins = plugins
+ self.plugin_name = "unknown"
+ self.logger = logging.getLogger("ro.worker{}".format(worker_index))
+ self.worker_index = worker_index
+ self.task_queue = queue.Queue(self.QUEUE_SIZE)
+ # targetvim: vimplugin class
+ self.my_vims = {}
+ # targetvim: vim information from database
+ self.db_vims = {}
+ # targetvim list
+ self.vim_targets = []
+ self.my_id = config["process_id"] + ":" + str(worker_index)
+ self.db = db
+ self.item2class = {
+ "net": VimInteractionNet(self.db, self.my_vims, self.db_vims, self.logger),
+ "vdu": VimInteractionVdu(self.db, self.my_vims, self.db_vims, self.logger),
+ "image": VimInteractionImage(
+ self.db, self.my_vims, self.db_vims, self.logger
+ ),
+ "flavor": VimInteractionFlavor(
+ self.db, self.my_vims, self.db_vims, self.logger
+ ),
+ "sdn_net": VimInteractionSdnNet(
+ self.db, self.my_vims, self.db_vims, self.logger
+ ),
+ }
+ self.time_last_task_processed = None
+ # lists of tasks to delete because nsrs or vnfrs has been deleted from db
+ self.tasks_to_delete = []
+ # it is idle when there are not vim_targets associated
+ self.idle = True
+ self.task_locked_time = config["global"]["task_locked_time"]
+
+ def insert_task(self, task):
+ try:
+ self.task_queue.put(task, False)
+ return None
+ except queue.Full:
+ raise NsWorkerException("timeout inserting a task")
+
+ def terminate(self):
+ self.insert_task("exit")
+
+ def del_task(self, task):
+ with self.task_lock:
+ if task["status"] == "SCHEDULED":
+ task["status"] = "SUPERSEDED"
+ return True
+ else: # task["status"] == "processing"
+ self.task_lock.release()
+ return False
+
+ def _process_vim_config(self, target_id, db_vim):
+ """
+ Process vim config, creating vim configuration files as ca_cert
+ :param target_id: vim/sdn/wim + id
+ :param db_vim: Vim dictionary obtained from database
+ :return: None. Modifies vim. Creates a folder target_id:worker_index and several files
+ """
+ if not db_vim.get("config"):
+ return
+
+ file_name = ""
+
+ try:
+ if db_vim["config"].get("ca_cert_content"):
+ file_name = "{}:{}".format(target_id, self.worker_index)
+
+ try:
+ mkdir(file_name)
+ except FileExistsError:
+ pass
+
+ file_name = file_name + "/ca_cert"
+
+ with open(file_name, "w") as f:
+ f.write(db_vim["config"]["ca_cert_content"])
+ del db_vim["config"]["ca_cert_content"]
+ db_vim["config"]["ca_cert"] = file_name
+ except Exception as e:
+ raise NsWorkerException(
+ "Error writing to file '{}': {}".format(file_name, e)
+ )
+
+ def _load_plugin(self, name, type="vim"):
+ # type can be vim or sdn
+ if "rovim_dummy" not in self.plugins:
+ self.plugins["rovim_dummy"] = VimDummyConnector
+
+ if "rosdn_dummy" not in self.plugins:
+ self.plugins["rosdn_dummy"] = SdnDummyConnector
+
+ if name in self.plugins:
+ return self.plugins[name]
+
+ try:
+ for ep in entry_points(group="osm_ro{}.plugins".format(type), name=name):
+ self.plugins[name] = ep.load()
+ except Exception as e:
+ raise NsWorkerException("Cannot load plugin osm_{}: {}".format(name, e))
+
+ if name and name not in self.plugins:
+ raise NsWorkerException(
+ "Plugin 'osm_{n}' has not been installed".format(n=name)
+ )
+
+ return self.plugins[name]
+
+ def _unload_vim(self, target_id):
+ """
+ Unload a vim_account. Removes it from self db_vims dictionary, my_vims dictionary and vim_targets list
+ :param target_id: Contains type:_id; where type can be 'vim', ...
+ :return: None.
+ """
+ try:
+ self.db_vims.pop(target_id, None)
+ self.my_vims.pop(target_id, None)
+
+ if target_id in self.vim_targets:
+ self.vim_targets.remove(target_id)
+
+ self.logger.info("Unloaded {}".format(target_id))
+ rmtree("{}:{}".format(target_id, self.worker_index))
+ except FileNotFoundError:
+ pass # this is raised by rmtree if folder does not exist
+ except Exception as e:
+ self.logger.error("Cannot unload {}: {}".format(target_id, e))
+
+ def _check_vim(self, target_id):
+ """
+ Load a VIM/SDN/WIM (if not loaded) and check connectivity, updating database with ENABLE or ERROR
+ :param target_id: Contains type:_id; type can be 'vim', 'sdn' or 'wim'
+ :return: None.
+ """
+ target, _, _id = target_id.partition(":")
+ now = time.time()
+ update_dict = {}
+ unset_dict = {}
+ op_text = ""
+ step = ""
+ loaded = target_id in self.vim_targets
+ target_database = (
+ "vim_accounts"
+ if target == "vim"
+ else "wim_accounts"
+ if target == "wim"
+ else "sdns"
+ )
+
+ try:
+ step = "Getting {} from db".format(target_id)
+ db_vim = self.db.get_one(target_database, {"_id": _id})
+
+ for op_index, operation in enumerate(
+ db_vim["_admin"].get("operations", ())
+ ):
+ if operation["operationState"] != "PROCESSING":
+ continue
+
+ locked_at = operation.get("locked_at")
+
+ if locked_at is not None and locked_at >= now - self.task_locked_time:
+ # some other thread is doing this operation
+ return
+
+ # lock
+ op_text = "_admin.operations.{}.".format(op_index)
+
+ if not self.db.set_one(
+ target_database,
+ q_filter={
+ "_id": _id,
+ op_text + "operationState": "PROCESSING",
+ op_text + "locked_at": locked_at,
+ },
+ update_dict={
+ op_text + "locked_at": now,
+ "admin.current_operation": op_index,
+ },
+ fail_on_empty=False,
+ ):
+ return
+
+ unset_dict[op_text + "locked_at"] = None
+ unset_dict["current_operation"] = None
+ step = "Loading " + target_id
+ error_text = self._load_vim(target_id)
+
+ if not error_text:
+ step = "Checking connectivity"
+
+ if target == "vim":
+ self.my_vims[target_id].check_vim_connectivity()
+ else:
+ self.my_vims[target_id].check_credentials()
+
+ update_dict["_admin.operationalState"] = "ENABLED"
+ update_dict["_admin.detailed-status"] = ""
+ unset_dict[op_text + "detailed-status"] = None
+ update_dict[op_text + "operationState"] = "COMPLETED"
+
+ return
+
+ except Exception as e:
+ error_text = "{}: {}".format(step, e)
+ self.logger.error("{} for {}: {}".format(step, target_id, e))
+
+ finally:
+ if update_dict or unset_dict:
+ if error_text:
+ update_dict[op_text + "operationState"] = "FAILED"
+ update_dict[op_text + "detailed-status"] = error_text
+ unset_dict.pop(op_text + "detailed-status", None)
+ update_dict["_admin.operationalState"] = "ERROR"
+ update_dict["_admin.detailed-status"] = error_text
+
+ if op_text:
+ update_dict[op_text + "statusEnteredTime"] = now
+
+ self.db.set_one(
+ target_database,
+ q_filter={"_id": _id},
+ update_dict=update_dict,
+ unset=unset_dict,
+ fail_on_empty=False,
+ )
+
+ if not loaded:
+ self._unload_vim(target_id)
+
+ def _reload_vim(self, target_id):
+ if target_id in self.vim_targets:
+ self._load_vim(target_id)
+ else:
+ # if the vim is not loaded, but database information of VIM is cached at self.db_vims,
+ # just remove it to force load again next time it is needed
+ self.db_vims.pop(target_id, None)
+
+ def _load_vim(self, target_id):
+ """
+ Load or reload a vim_account, sdn_controller or wim_account.
+ Read content from database, load the plugin if not loaded.
+ In case of error loading the plugin, it load a failing VIM_connector
+ It fills self db_vims dictionary, my_vims dictionary and vim_targets list
+ :param target_id: Contains type:_id; where type can be 'vim', ...
+ :return: None if ok, descriptive text if error
+ """
+ target, _, _id = target_id.partition(":")
+ target_database = (
+ "vim_accounts"
+ if target == "vim"
+ else "wim_accounts"
+ if target == "wim"
+ else "sdns"
+ )
+ plugin_name = ""
+ vim = None
+
+ try:
+ step = "Getting {}={} from db".format(target, _id)
+ # TODO process for wim, sdnc, ...
+ vim = self.db.get_one(target_database, {"_id": _id})
+
+ # if deep_get(vim, "config", "sdn-controller"):
+ # step = "Getting sdn-controller-id='{}' from db".format(vim["config"]["sdn-controller"])
+ # db_sdn = self.db.get_one("sdns", {"_id": vim["config"]["sdn-controller"]})
+
+ step = "Decrypting password"
+ schema_version = vim.get("schema_version")
+ self.db.encrypt_decrypt_fields(
+ vim,
+ "decrypt",
+ fields=("password", "secret"),
+ schema_version=schema_version,
+ salt=_id,
+ )
+ self._process_vim_config(target_id, vim)
+
+ if target == "vim":
+ plugin_name = "rovim_" + vim["vim_type"]
+ step = "Loading plugin '{}'".format(plugin_name)
+ vim_module_conn = self._load_plugin(plugin_name)
+ step = "Loading {}'".format(target_id)
+ self.my_vims[target_id] = vim_module_conn(
+ uuid=vim["_id"],
+ name=vim["name"],
+ tenant_id=vim.get("vim_tenant_id"),
+ tenant_name=vim.get("vim_tenant_name"),
+ url=vim["vim_url"],
+ url_admin=None,
+ user=vim["vim_user"],
+ passwd=vim["vim_password"],
+ config=vim.get("config") or {},
+ persistent_info={},
+ )
+ else: # sdn
+ plugin_name = "rosdn_" + vim["type"]
+ step = "Loading plugin '{}'".format(plugin_name)
+ vim_module_conn = self._load_plugin(plugin_name, "sdn")
+ step = "Loading {}'".format(target_id)
+ wim = deepcopy(vim)
+ wim_config = wim.pop("config", {}) or {}
+ wim["uuid"] = wim["_id"]
+ wim["wim_url"] = wim["url"]
+
+ if wim.get("dpid"):
+ wim_config["dpid"] = wim.pop("dpid")
+
+ if wim.get("switch_id"):
+ wim_config["switch_id"] = wim.pop("switch_id")
+
+ # wim, wim_account, config
+ self.my_vims[target_id] = vim_module_conn(wim, wim, wim_config)
+ self.db_vims[target_id] = vim
+ self.error_status = None
+
+ self.logger.info(
+ "Connector loaded for {}, plugin={}".format(target_id, plugin_name)
+ )
+ except Exception as e:
+ self.logger.error(
+ "Cannot load {} plugin={}: {} {}".format(
+ target_id, plugin_name, step, e
+ )
+ )
+
+ self.db_vims[target_id] = vim or {}
+ self.db_vims[target_id] = FailingConnector(str(e))
+ error_status = "{} Error: {}".format(step, e)
+
+ return error_status
+ finally:
+ if target_id not in self.vim_targets:
+ self.vim_targets.append(target_id)
+
+ def _get_db_task(self):
+ """
+ Read actions from database and reload them at memory. Fill self.refresh_list, pending_list, vim_actions
+ :return: None
+ """
+ now = time.time()
+
+ if not self.time_last_task_processed:
+ self.time_last_task_processed = now
+
+ try:
+ while True:
+ """
+ # Log RO tasks only when loglevel is DEBUG
+ if self.logger.getEffectiveLevel() == logging.DEBUG:
+ self._log_ro_task(
+ None,
+ None,
+ None,
+ "TASK_WF",
+ "task_locked_time="
+ + str(self.task_locked_time)
+ + " "
+ + "time_last_task_processed="
+ + str(self.time_last_task_processed)
+ + " "
+ + "now="
+ + str(now),
+ )
+ """
+ locked = self.db.set_one(
+ "ro_tasks",
+ q_filter={
+ "target_id": self.vim_targets,
+ "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
+ "locked_at.lt": now - self.task_locked_time,
+ "to_check_at.lt": self.time_last_task_processed,
+ },
+ update_dict={"locked_by": self.my_id, "locked_at": now},
+ fail_on_empty=False,
+ )
+
+ if locked:
+ # read and return
+ ro_task = self.db.get_one(
+ "ro_tasks",
+ q_filter={
+ "target_id": self.vim_targets,
+ "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
+ "locked_at": now,
+ },
+ )
+ return ro_task
+
+ if self.time_last_task_processed == now:
+ self.time_last_task_processed = None
+ return None
+ else:
+ self.time_last_task_processed = now
+ # self.time_last_task_processed = min(self.time_last_task_processed + 1000, now)
+
+ except DbException as e:
+ self.logger.error("Database exception at _get_db_task: {}".format(e))
+ except Exception as e:
+ self.logger.critical(
+ "Unexpected exception at _get_db_task: {}".format(e), exc_info=True
+ )
+
+ return None
+
+ def _get_db_all_tasks(self):
+ """
+ Read all content of table ro_tasks to log it
+ :return: None
+ """
+ try:
+ # Checking the content of the BD: