1 # -*- coding: utf-8 -*-
4 # Copyright 2020 Telefonica Investigacion y Desarrollo, S.A.U.
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
10 # http://www.apache.org/licenses/LICENSE-2.0
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
21 This is thread that interacts with a VIM. It processes TASKs sequentially against a single VIM.
22 The tasks are stored at database in table ro_tasks
23 A single ro_task refers to a VIM element (flavor, image, network, ...).
24 A ro_task can contain several 'tasks', each one with a target, where to store the results
27 from copy
import deepcopy
28 from http
import HTTPStatus
32 from shutil
import rmtree
35 from unittest
.mock
import Mock
37 from importlib_metadata
import entry_points
38 from osm_common
.dbbase
import DbException
39 from osm_ng_ro
.vim_admin
import LockRenew
40 from osm_ro_plugin
import sdnconn
, vimconn
41 from osm_ro_plugin
.sdn_dummy
import SdnDummyConnector
42 from osm_ro_plugin
.vim_dummy
import VimDummyConnector
45 __author__
= "Alfonso Tierno"
46 __date__
= "$28-Sep-2017 12:07:15$"
49 def deep_get(target_dict
, *args
, **kwargs
):
51 Get a value from target_dict entering in the nested keys. If keys does not exist, it returns None
52 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
53 :param target_dict: dictionary to be read
54 :param args: list of keys to read from target_dict
55 :param kwargs: only can contain default=value to return if key is not present in the nested dictionary
56 :return: The wanted value if exist, None or default otherwise
59 if not isinstance(target_dict
, dict) or key
not in target_dict
:
60 return kwargs
.get("default")
61 target_dict
= target_dict
[key
]
65 class NsWorkerException(Exception):
69 class FailingConnector
:
70 def __init__(self
, error_msg
):
71 self
.error_msg
= error_msg
73 for method
in dir(vimconn
.VimConnector
):
76 self
, method
, Mock(side_effect
=vimconn
.VimConnException(error_msg
))
79 for method
in dir(sdnconn
.SdnConnectorBase
):
82 self
, method
, Mock(side_effect
=sdnconn
.SdnConnectorError(error_msg
))
86 class NsWorkerExceptionNotFound(NsWorkerException
):
90 class VimInteractionBase
:
91 """Base class to call VIM/SDN for creating, deleting and refresh networks, VMs, flavors, ...
92 It implements methods that does nothing and return ok"""
94 def __init__(self
, db
, my_vims
, db_vims
, logger
):
97 self
.my_vims
= my_vims
98 self
.db_vims
= db_vims
100 def new(self
, ro_task
, task_index
, task_depends
):
103 def refresh(self
, ro_task
):
104 """skip calling VIM to get image, flavor status. Assumes ok"""
105 if ro_task
["vim_info"]["vim_status"] == "VIM_ERROR":
110 def delete(self
, ro_task
, task_index
):
111 """skip calling VIM to delete image. Assumes ok"""
114 def exec(self
, ro_task
, task_index
, task_depends
):
115 return "DONE", None, None
118 class VimInteractionNet(VimInteractionBase
):
119 def new(self
, ro_task
, task_index
, task_depends
):
121 task
= ro_task
["tasks"][task_index
]
122 task_id
= task
["task_id"]
125 target_vim
= self
.my_vims
[ro_task
["target_id"]]
129 if task
.get("find_params"):
130 # if management, get configuration of VIM
131 if task
["find_params"].get("filter_dict"):
132 vim_filter
= task
["find_params"]["filter_dict"]
134 elif task
["find_params"].get("mgmt"):
136 self
.db_vims
[ro_task
["target_id"]],
138 "management_network_id",
141 "id": self
.db_vims
[ro_task
["target_id"]]["config"][
142 "management_network_id"
146 self
.db_vims
[ro_task
["target_id"]],
148 "management_network_name",
151 "name": self
.db_vims
[ro_task
["target_id"]]["config"][
152 "management_network_name"
156 vim_filter
= {"name": task
["find_params"]["name"]}
158 raise NsWorkerExceptionNotFound(
159 "Invalid find_params for new_net {}".format(task
["find_params"])
162 vim_nets
= target_vim
.get_network_list(vim_filter
)
163 if not vim_nets
and not task
.get("params"):
164 raise NsWorkerExceptionNotFound(
165 "Network not found with this criteria: '{}'".format(
166 task
.get("find_params")
169 elif len(vim_nets
) > 1:
170 raise NsWorkerException(
171 "More than one network found with this criteria: '{}'".format(
177 vim_net_id
= vim_nets
[0]["id"]
180 params
= task
["params"]
181 vim_net_id
, created_items
= target_vim
.new_network(**params
)
184 ro_vim_item_update
= {
185 "vim_id": vim_net_id
,
186 "vim_status": "BUILD",
188 "created_items": created_items
,
192 "task={} {} new-net={} created={}".format(
193 task_id
, ro_task
["target_id"], vim_net_id
, created
197 return "BUILD", ro_vim_item_update
198 except (vimconn
.VimConnException
, NsWorkerException
) as e
:
200 "task={} vim={} new-net: {}".format(task_id
, ro_task
["target_id"], e
)
202 ro_vim_item_update
= {
203 "vim_status": "VIM_ERROR",
205 "vim_details": str(e
),
208 return "FAILED", ro_vim_item_update
210 def refresh(self
, ro_task
):
211 """Call VIM to get network status"""
212 ro_task_id
= ro_task
["_id"]
213 target_vim
= self
.my_vims
[ro_task
["target_id"]]
214 vim_id
= ro_task
["vim_info"]["vim_id"]
215 net_to_refresh_list
= [vim_id
]
218 vim_dict
= target_vim
.refresh_nets_status(net_to_refresh_list
)
219 vim_info
= vim_dict
[vim_id
]
221 if vim_info
["status"] == "ACTIVE":
223 elif vim_info
["status"] == "BUILD":
224 task_status
= "BUILD"
226 task_status
= "FAILED"
227 except vimconn
.VimConnException
as e
:
228 # Mark all tasks at VIM_ERROR status
230 "ro_task={} vim={} get-net={}: {}".format(
231 ro_task_id
, ro_task
["target_id"], vim_id
, e
234 vim_info
= {"status": "VIM_ERROR", "error_msg": str(e
)}
235 task_status
= "FAILED"
237 ro_vim_item_update
= {}
238 if ro_task
["vim_info"]["vim_status"] != vim_info
["status"]:
239 ro_vim_item_update
["vim_status"] = vim_info
["status"]
241 if ro_task
["vim_info"]["vim_name"] != vim_info
.get("name"):
242 ro_vim_item_update
["vim_name"] = vim_info
.get("name")
244 if vim_info
["status"] in ("ERROR", "VIM_ERROR"):
245 if ro_task
["vim_info"]["vim_details"] != vim_info
.get("error_msg"):
246 ro_vim_item_update
["vim_details"] = vim_info
.get("error_msg")
247 elif vim_info
["status"] == "DELETED":
248 ro_vim_item_update
["vim_id"] = None
249 ro_vim_item_update
["vim_details"] = "Deleted externally"
251 if ro_task
["vim_info"]["vim_details"] != vim_info
["vim_info"]:
252 ro_vim_item_update
["vim_details"] = vim_info
["vim_info"]
254 if ro_vim_item_update
:
256 "ro_task={} {} get-net={}: status={} {}".format(
258 ro_task
["target_id"],
260 ro_vim_item_update
.get("vim_status"),
261 ro_vim_item_update
.get("vim_details")
262 if ro_vim_item_update
.get("vim_status") != "ACTIVE"
267 return task_status
, ro_vim_item_update
269 def delete(self
, ro_task
, task_index
):
270 task
= ro_task
["tasks"][task_index
]
271 task_id
= task
["task_id"]
272 net_vim_id
= ro_task
["vim_info"]["vim_id"]
273 ro_vim_item_update_ok
= {
274 "vim_status": "DELETED",
276 "vim_details": "DELETED",
281 if net_vim_id
or ro_task
["vim_info"]["created_items"]:
282 target_vim
= self
.my_vims
[ro_task
["target_id"]]
283 target_vim
.delete_network(
284 net_vim_id
, ro_task
["vim_info"]["created_items"]
286 except vimconn
.VimConnNotFoundException
:
287 ro_vim_item_update_ok
["vim_details"] = "already deleted"
288 except vimconn
.VimConnException
as e
:
290 "ro_task={} vim={} del-net={}: {}".format(
291 ro_task
["_id"], ro_task
["target_id"], net_vim_id
, e
294 ro_vim_item_update
= {
295 "vim_status": "VIM_ERROR",
296 "vim_details": "Error while deleting: {}".format(e
),
299 return "FAILED", ro_vim_item_update
302 "task={} {} del-net={} {}".format(
304 ro_task
["target_id"],
306 ro_vim_item_update_ok
.get("vim_details", ""),
310 return "DONE", ro_vim_item_update_ok
313 class VimInteractionVdu(VimInteractionBase
):
314 max_retries_inject_ssh_key
= 20 # 20 times
315 time_retries_inject_ssh_key
= 30 # wevery 30 seconds
317 def new(self
, ro_task
, task_index
, task_depends
):
318 task
= ro_task
["tasks"][task_index
]
319 task_id
= task
["task_id"]
322 target_vim
= self
.my_vims
[ro_task
["target_id"]]
326 params
= task
["params"]
327 params_copy
= deepcopy(params
)
328 net_list
= params_copy
["net_list"]
331 # change task_id into network_id
332 if "net_id" in net
and net
["net_id"].startswith("TASK-"):
333 network_id
= task_depends
[net
["net_id"]]
336 raise NsWorkerException(
337 "Cannot create VM because depends on a network not created or found "
338 "for {}".format(net
["net_id"])
341 net
["net_id"] = network_id
343 if params_copy
["image_id"].startswith("TASK-"):
344 params_copy
["image_id"] = task_depends
[params_copy
["image_id"]]
346 if params_copy
["flavor_id"].startswith("TASK-"):
347 params_copy
["flavor_id"] = task_depends
[params_copy
["flavor_id"]]
349 vim_vm_id
, created_items
= target_vim
.new_vminstance(**params_copy
)
350 interfaces
= [iface
["vim_id"] for iface
in params_copy
["net_list"]]
352 ro_vim_item_update
= {
354 "vim_status": "BUILD",
356 "created_items": created_items
,
358 "interfaces_vim_ids": interfaces
,
362 "task={} {} new-vm={} created={}".format(
363 task_id
, ro_task
["target_id"], vim_vm_id
, created
367 return "BUILD", ro_vim_item_update
368 except (vimconn
.VimConnException
, NsWorkerException
) as e
:
370 "task={} {} new-vm: {}".format(task_id
, ro_task
["target_id"], e
)
372 ro_vim_item_update
= {
373 "vim_status": "VIM_ERROR",
375 "vim_details": str(e
),
378 return "FAILED", ro_vim_item_update
380 def delete(self
, ro_task
, task_index
):
381 task
= ro_task
["tasks"][task_index
]
382 task_id
= task
["task_id"]
383 vm_vim_id
= ro_task
["vim_info"]["vim_id"]
384 ro_vim_item_update_ok
= {
385 "vim_status": "DELETED",
387 "vim_details": "DELETED",
392 if vm_vim_id
or ro_task
["vim_info"]["created_items"]:
393 target_vim
= self
.my_vims
[ro_task
["target_id"]]
394 target_vim
.delete_vminstance(
395 vm_vim_id
, ro_task
["vim_info"]["created_items"]
397 except vimconn
.VimConnNotFoundException
:
398 ro_vim_item_update_ok
["vim_details"] = "already deleted"
399 except vimconn
.VimConnException
as e
:
401 "ro_task={} vim={} del-vm={}: {}".format(
402 ro_task
["_id"], ro_task
["target_id"], vm_vim_id
, e
405 ro_vim_item_update
= {
406 "vim_status": "VIM_ERROR",
407 "vim_details": "Error while deleting: {}".format(e
),
410 return "FAILED", ro_vim_item_update
413 "task={} {} del-vm={} {}".format(
415 ro_task
["target_id"],
417 ro_vim_item_update_ok
.get("vim_details", ""),
421 return "DONE", ro_vim_item_update_ok
423 def refresh(self
, ro_task
):
424 """Call VIM to get vm status"""
425 ro_task_id
= ro_task
["_id"]
426 target_vim
= self
.my_vims
[ro_task
["target_id"]]
427 vim_id
= ro_task
["vim_info"]["vim_id"]
432 vm_to_refresh_list
= [vim_id
]
434 vim_dict
= target_vim
.refresh_vms_status(vm_to_refresh_list
)
435 vim_info
= vim_dict
[vim_id
]
437 if vim_info
["status"] == "ACTIVE":
439 elif vim_info
["status"] == "BUILD":
440 task_status
= "BUILD"
442 task_status
= "FAILED"
444 # try to load and parse vim_information
446 vim_info_info
= yaml
.safe_load(vim_info
["vim_info"])
447 if vim_info_info
.get("name"):
448 vim_info
["name"] = vim_info_info
["name"]
451 except vimconn
.VimConnException
as e
:
452 # Mark all tasks at VIM_ERROR status
454 "ro_task={} vim={} get-vm={}: {}".format(
455 ro_task_id
, ro_task
["target_id"], vim_id
, e
458 vim_info
= {"status": "VIM_ERROR", "error_msg": str(e
)}
459 task_status
= "FAILED"
461 ro_vim_item_update
= {}
463 # Interfaces cannot be present if e.g. VM is not present, that is status=DELETED
465 if vim_info
.get("interfaces"):
466 for vim_iface_id
in ro_task
["vim_info"]["interfaces_vim_ids"]:
470 for iface
in vim_info
["interfaces"]
471 if vim_iface_id
== iface
["vim_interface_id"]
476 # iface.pop("vim_info", None)
477 vim_interfaces
.append(iface
)
481 for t
in ro_task
["tasks"]
482 if t
and t
["action"] == "CREATE" and t
["status"] != "FINISHED"
484 if vim_interfaces
and task_create
.get("mgmt_vnf_interface") is not None:
485 vim_interfaces
[task_create
["mgmt_vnf_interface"]][
489 mgmt_vdu_iface
= task_create
.get(
490 "mgmt_vdu_interface", task_create
.get("mgmt_vnf_interface", 0)
493 vim_interfaces
[mgmt_vdu_iface
]["mgmt_vdu_interface"] = True
495 if ro_task
["vim_info"]["interfaces"] != vim_interfaces
:
496 ro_vim_item_update
["interfaces"] = vim_interfaces
498 if ro_task
["vim_info"]["vim_status"] != vim_info
["status"]:
499 ro_vim_item_update
["vim_status"] = vim_info
["status"]
501 if ro_task
["vim_info"]["vim_name"] != vim_info
.get("name"):
502 ro_vim_item_update
["vim_name"] = vim_info
.get("name")
504 if vim_info
["status"] in ("ERROR", "VIM_ERROR"):
505 if ro_task
["vim_info"]["vim_details"] != vim_info
.get("error_msg"):
506 ro_vim_item_update
["vim_details"] = vim_info
.get("error_msg")
507 elif vim_info
["status"] == "DELETED":
508 ro_vim_item_update
["vim_id"] = None
509 ro_vim_item_update
["vim_details"] = "Deleted externally"
511 if ro_task
["vim_info"]["vim_details"] != vim_info
["vim_info"]:
512 ro_vim_item_update
["vim_details"] = vim_info
["vim_info"]
514 if ro_vim_item_update
:
516 "ro_task={} {} get-vm={}: status={} {}".format(
518 ro_task
["target_id"],
520 ro_vim_item_update
.get("vim_status"),
521 ro_vim_item_update
.get("vim_details")
522 if ro_vim_item_update
.get("vim_status") != "ACTIVE"
527 return task_status
, ro_vim_item_update
529 def exec(self
, ro_task
, task_index
, task_depends
):
530 task
= ro_task
["tasks"][task_index
]
531 task_id
= task
["task_id"]
532 target_vim
= self
.my_vims
[ro_task
["target_id"]]
533 db_task_update
= {"retries": 0}
534 retries
= task
.get("retries", 0)
537 params
= task
["params"]
538 params_copy
= deepcopy(params
)
539 params_copy
["ro_key"] = self
.db
.decrypt(
540 params_copy
.pop("private_key"),
541 params_copy
.pop("schema_version"),
542 params_copy
.pop("salt"),
544 params_copy
["ip_addr"] = params_copy
.pop("ip_address")
545 target_vim
.inject_user_key(**params_copy
)
547 "task={} {} action-vm=inject_key".format(task_id
, ro_task
["target_id"])
554 ) # params_copy["key"]
555 except (vimconn
.VimConnException
, NsWorkerException
) as e
:
558 if retries
< self
.max_retries_inject_ssh_key
:
564 "next_retry": self
.time_retries_inject_ssh_key
,
569 "task={} {} inject-ssh-key: {}".format(task_id
, ro_task
["target_id"], e
)
571 ro_vim_item_update
= {"vim_details": str(e
)}
573 return "FAILED", ro_vim_item_update
, db_task_update
576 class VimInteractionImage(VimInteractionBase
):
577 def new(self
, ro_task
, task_index
, task_depends
):
578 task
= ro_task
["tasks"][task_index
]
579 task_id
= task
["task_id"]
582 target_vim
= self
.my_vims
[ro_task
["target_id"]]
586 if task
.get("find_params"):
587 vim_images
= target_vim
.get_image_list(**task
["find_params"])
590 raise NsWorkerExceptionNotFound(
591 "Image not found with this criteria: '{}'".format(
595 elif len(vim_images
) > 1:
596 raise NsWorkerException(
597 "More than one image found with this criteria: '{}'".format(
602 vim_image_id
= vim_images
[0]["id"]
604 ro_vim_item_update
= {
605 "vim_id": vim_image_id
,
606 "vim_status": "DONE",
608 "created_items": created_items
,
612 "task={} {} new-image={} created={}".format(
613 task_id
, ro_task
["target_id"], vim_image_id
, created
617 return "DONE", ro_vim_item_update
618 except (NsWorkerException
, vimconn
.VimConnException
) as e
:
620 "task={} {} new-image: {}".format(task_id
, ro_task
["target_id"], e
)
622 ro_vim_item_update
= {
623 "vim_status": "VIM_ERROR",
625 "vim_details": str(e
),
628 return "FAILED", ro_vim_item_update
631 class VimInteractionFlavor(VimInteractionBase
):
632 def delete(self
, ro_task
, task_index
):
633 task
= ro_task
["tasks"][task_index
]
634 task_id
= task
["task_id"]
635 flavor_vim_id
= ro_task
["vim_info"]["vim_id"]
636 ro_vim_item_update_ok
= {
637 "vim_status": "DELETED",
639 "vim_details": "DELETED",
645 target_vim
= self
.my_vims
[ro_task
["target_id"]]
646 target_vim
.delete_flavor(flavor_vim_id
)
647 except vimconn
.VimConnNotFoundException
:
648 ro_vim_item_update_ok
["vim_details"] = "already deleted"
649 except vimconn
.VimConnException
as e
:
651 "ro_task={} vim={} del-flavor={}: {}".format(
652 ro_task
["_id"], ro_task
["target_id"], flavor_vim_id
, e
655 ro_vim_item_update
= {
656 "vim_status": "VIM_ERROR",
657 "vim_details": "Error while deleting: {}".format(e
),
660 return "FAILED", ro_vim_item_update
663 "task={} {} del-flavor={} {}".format(
665 ro_task
["target_id"],
667 ro_vim_item_update_ok
.get("vim_details", ""),
671 return "DONE", ro_vim_item_update_ok
673 def new(self
, ro_task
, task_index
, task_depends
):
674 task
= ro_task
["tasks"][task_index
]
675 task_id
= task
["task_id"]
678 target_vim
= self
.my_vims
[ro_task
["target_id"]]
684 if task
.get("find_params"):
686 flavor_data
= task
["find_params"]["flavor_data"]
687 vim_flavor_id
= target_vim
.get_flavor_id_from_data(flavor_data
)
688 except vimconn
.VimConnNotFoundException
:
691 if not vim_flavor_id
and task
.get("params"):
693 flavor_data
= task
["params"]["flavor_data"]
694 vim_flavor_id
= target_vim
.new_flavor(flavor_data
)
697 ro_vim_item_update
= {
698 "vim_id": vim_flavor_id
,
699 "vim_status": "DONE",
701 "created_items": created_items
,
705 "task={} {} new-flavor={} created={}".format(
706 task_id
, ro_task
["target_id"], vim_flavor_id
, created
710 return "DONE", ro_vim_item_update
711 except (vimconn
.VimConnException
, NsWorkerException
) as e
:
713 "task={} vim={} new-flavor: {}".format(task_id
, ro_task
["target_id"], e
)
715 ro_vim_item_update
= {
716 "vim_status": "VIM_ERROR",
718 "vim_details": str(e
),
721 return "FAILED", ro_vim_item_update
724 class VimInteractionSdnNet(VimInteractionBase
):
726 def _match_pci(port_pci
, mapping
):
728 Check if port_pci matches with mapping
729 mapping can have brackets to indicate that several chars are accepted. e.g
730 pci '0000:af:10.1' matches with '0000:af:1[01].[1357]'
731 :param port_pci: text
732 :param mapping: text, can contain brackets to indicate several chars are available
733 :return: True if matches, False otherwise
735 if not port_pci
or not mapping
:
737 if port_pci
== mapping
:
743 bracket_start
= mapping
.find("[", mapping_index
)
745 if bracket_start
== -1:
748 bracket_end
= mapping
.find("]", bracket_start
)
749 if bracket_end
== -1:
752 length
= bracket_start
- mapping_index
755 and port_pci
[pci_index
: pci_index
+ length
]
756 != mapping
[mapping_index
:bracket_start
]
761 port_pci
[pci_index
+ length
]
762 not in mapping
[bracket_start
+ 1 : bracket_end
]
766 pci_index
+= length
+ 1
767 mapping_index
= bracket_end
+ 1
769 if port_pci
[pci_index
:] != mapping
[mapping_index
:]:
774 def _get_interfaces(self
, vlds_to_connect
, vim_account_id
):
776 :param vlds_to_connect: list with format vnfrs:<id>:vld.<vld_id> or nsrs:<id>:vld.<vld_id>
777 :param vim_account_id:
782 for vld
in vlds_to_connect
:
783 table
, _
, db_id
= vld
.partition(":")
784 db_id
, _
, vld
= db_id
.partition(":")
785 _
, _
, vld_id
= vld
.partition(".")
788 q_filter
= {"vim-account-id": vim_account_id
, "_id": db_id
}
789 iface_key
= "vnf-vld-id"
790 else: # table == "nsrs"
791 q_filter
= {"vim-account-id": vim_account_id
, "nsr-id-ref": db_id
}
792 iface_key
= "ns-vld-id"
794 db_vnfrs
= self
.db
.get_list("vnfrs", q_filter
=q_filter
)
796 for db_vnfr
in db_vnfrs
:
797 for vdu_index
, vdur
in enumerate(db_vnfr
.get("vdur", ())):
798 for iface_index
, interface
in enumerate(vdur
["interfaces"]):
799 if interface
.get(iface_key
) == vld_id
and interface
.get(
801 ) in ("SR-IOV", "PCI-PASSTHROUGH"):
803 interface_
= interface
.copy()
804 interface_
["id"] = "vnfrs:{}:vdu.{}.interfaces.{}".format(
805 db_vnfr
["_id"], vdu_index
, iface_index
808 if vdur
.get("status") == "ERROR":
809 interface_
["status"] = "ERROR"
811 interfaces
.append(interface_
)
815 def refresh(self
, ro_task
):
816 # look for task create
817 task_create_index
, _
= next(
819 for i_t
in enumerate(ro_task
["tasks"])
821 and i_t
[1]["action"] == "CREATE"
822 and i_t
[1]["status"] != "FINISHED"
825 return self
.new(ro_task
, task_create_index
, None)
827 def new(self
, ro_task
, task_index
, task_depends
):
829 task
= ro_task
["tasks"][task_index
]
830 task_id
= task
["task_id"]
831 target_vim
= self
.my_vims
[ro_task
["target_id"]]
833 sdn_net_id
= ro_task
["vim_info"]["vim_id"]
835 created_items
= ro_task
["vim_info"].get("created_items")
836 connected_ports
= ro_task
["vim_info"].get("connected_ports", [])
837 new_connected_ports
= []
838 last_update
= ro_task
["vim_info"].get("last_update", 0)
839 sdn_status
= ro_task
["vim_info"].get("vim_status", "BUILD") or "BUILD"
841 created
= ro_task
["vim_info"].get("created", False)
845 params
= task
["params"]
846 vlds_to_connect
= params
["vlds"]
847 associated_vim
= params
["target_vim"]
848 # external additional ports
849 additional_ports
= params
.get("sdn-ports") or ()
850 _
, _
, vim_account_id
= associated_vim
.partition(":")
854 if associated_vim
not in self
.db_vims
:
855 self
.db_vims
[associated_vim
] = self
.db
.get_one(
856 "vim_accounts", {"_id": vim_account_id
}
859 db_vim
= self
.db_vims
[associated_vim
]
861 # look for ports to connect
862 ports
= self
._get
_interfaces
(vlds_to_connect
, vim_account_id
)
866 pending_ports
= error_ports
= 0
868 sdn_need_update
= False
871 vlan_used
= port
.get("vlan") or vlan_used
873 # TODO. Do not connect if already done
874 if not port
.get("compute_node") or not port
.get("pci"):
875 if port
.get("status") == "ERROR":
882 compute_node_mappings
= next(
885 for c
in db_vim
["config"].get("sdn-port-mapping", ())
886 if c
and c
["compute_node"] == port
["compute_node"]
891 if compute_node_mappings
:
892 # process port_mapping pci of type 0000:af:1[01].[1357]
896 for p
in compute_node_mappings
["ports"]
897 if self
._match
_pci
(port
["pci"], p
.get("pci"))
903 if not db_vim
["config"].get("mapping_not_needed"):
905 "Port mapping not found for compute_node={} pci={}".format(
906 port
["compute_node"], port
["pci"]
913 service_endpoint_id
= "{}:{}".format(port
["compute_node"], port
["pci"])
915 "service_endpoint_id": pmap
.get("service_endpoint_id")
916 or service_endpoint_id
,
917 "service_endpoint_encapsulation_type": "dot1q"
918 if port
["type"] == "SR-IOV"
920 "service_endpoint_encapsulation_info": {
921 "vlan": port
.get("vlan"),
922 "mac": port
.get("mac-address"),
923 "device_id": pmap
.get("device_id") or port
["compute_node"],
924 "device_interface_id": pmap
.get("device_interface_id")
926 "switch_dpid": pmap
.get("switch_id") or pmap
.get("switch_dpid"),
927 "switch_port": pmap
.get("switch_port"),
928 "service_mapping_info": pmap
.get("service_mapping_info"),
933 # if port["modified_at"] > last_update:
934 # sdn_need_update = True
935 new_connected_ports
.append(port
["id"]) # TODO
936 sdn_ports
.append(new_port
)
940 "{} interfaces have not been created as VDU is on ERROR status".format(
945 # connect external ports
946 for index
, additional_port
in enumerate(additional_ports
):
947 additional_port_id
= additional_port
.get(
948 "service_endpoint_id"
949 ) or "external-{}".format(index
)
952 "service_endpoint_id": additional_port_id
,
953 "service_endpoint_encapsulation_type": additional_port
.get(
954 "service_endpoint_encapsulation_type", "dot1q"
956 "service_endpoint_encapsulation_info": {
957 "vlan": additional_port
.get("vlan") or vlan_used
,
958 "mac": additional_port
.get("mac_address"),
959 "device_id": additional_port
.get("device_id"),
960 "device_interface_id": additional_port
.get(
961 "device_interface_id"
963 "switch_dpid": additional_port
.get("switch_dpid")
964 or additional_port
.get("switch_id"),
965 "switch_port": additional_port
.get("switch_port"),
966 "service_mapping_info": additional_port
.get(
967 "service_mapping_info"
972 new_connected_ports
.append(additional_port_id
)
975 # if there are more ports to connect or they have been modified, call create/update
978 sdn_info
= "; ".join(error_list
)
979 elif set(connected_ports
) != set(new_connected_ports
) or sdn_need_update
:
980 last_update
= time
.time()
983 if len(sdn_ports
) < 2:
984 sdn_status
= "ACTIVE"
986 if not pending_ports
:
988 "task={} {} new-sdn-net done, less than 2 ports".format(
989 task_id
, ro_task
["target_id"]
993 net_type
= params
.get("type") or "ELAN"
997 ) = target_vim
.create_connectivity_service(net_type
, sdn_ports
)
1000 "task={} {} new-sdn-net={} created={}".format(
1001 task_id
, ro_task
["target_id"], sdn_net_id
, created
1005 created_items
= target_vim
.edit_connectivity_service(
1006 sdn_net_id
, conn_info
=created_items
, connection_points
=sdn_ports
1010 "task={} {} update-sdn-net={} created={}".format(
1011 task_id
, ro_task
["target_id"], sdn_net_id
, created
1015 connected_ports
= new_connected_ports
1017 wim_status_dict
= target_vim
.get_connectivity_service_status(
1018 sdn_net_id
, conn_info
=created_items
1020 sdn_status
= wim_status_dict
["sdn_status"]
1022 if wim_status_dict
.get("sdn_info"):
1023 sdn_info
= str(wim_status_dict
.get("sdn_info")) or ""
1025 if wim_status_dict
.get("error_msg"):
1026 sdn_info
= wim_status_dict
.get("error_msg") or ""
1029 if sdn_status
!= "ERROR":
1030 sdn_info
= "Waiting for getting interfaces location from VIM. Obtained '{}' of {}".format(
1031 len(ports
) - pending_ports
, len(ports
)
1034 if sdn_status
== "ACTIVE":
1035 sdn_status
= "BUILD"
1037 ro_vim_item_update
= {
1038 "vim_id": sdn_net_id
,
1039 "vim_status": sdn_status
,
1041 "created_items": created_items
,
1042 "connected_ports": connected_ports
,
1043 "vim_details": sdn_info
,
1044 "last_update": last_update
,
1047 return sdn_status
, ro_vim_item_update
1048 except Exception as e
:
1050 "task={} vim={} new-net: {}".format(task_id
, ro_task
["target_id"], e
),
1051 exc_info
=not isinstance(
1052 e
, (sdnconn
.SdnConnectorError
, vimconn
.VimConnException
)
1055 ro_vim_item_update
= {
1056 "vim_status": "VIM_ERROR",
1058 "vim_details": str(e
),
1061 return "FAILED", ro_vim_item_update
1063 def delete(self
, ro_task
, task_index
):
1064 task
= ro_task
["tasks"][task_index
]
1065 task_id
= task
["task_id"]
1066 sdn_vim_id
= ro_task
["vim_info"].get("vim_id")
1067 ro_vim_item_update_ok
= {
1068 "vim_status": "DELETED",
1070 "vim_details": "DELETED",
1076 target_vim
= self
.my_vims
[ro_task
["target_id"]]
1077 target_vim
.delete_connectivity_service(
1078 sdn_vim_id
, ro_task
["vim_info"].get("created_items")
1081 except Exception as e
:
1083 isinstance(e
, sdnconn
.SdnConnectorError
)
1084 and e
.http_code
== HTTPStatus
.NOT_FOUND
.value
1086 ro_vim_item_update_ok
["vim_details"] = "already deleted"
1089 "ro_task={} vim={} del-sdn-net={}: {}".format(
1090 ro_task
["_id"], ro_task
["target_id"], sdn_vim_id
, e
1092 exc_info
=not isinstance(
1093 e
, (sdnconn
.SdnConnectorError
, vimconn
.VimConnException
)
1096 ro_vim_item_update
= {
1097 "vim_status": "VIM_ERROR",
1098 "vim_details": "Error while deleting: {}".format(e
),
1101 return "FAILED", ro_vim_item_update
1104 "task={} {} del-sdn-net={} {}".format(
1106 ro_task
["target_id"],
1108 ro_vim_item_update_ok
.get("vim_details", ""),
1112 return "DONE", ro_vim_item_update_ok
1115 class NsWorker(threading
.Thread
):
1116 REFRESH_BUILD
= 5 # 5 seconds
1117 REFRESH_ACTIVE
= 60 # 1 minute
1119 REFRESH_IMAGE
= 3600 * 10
1120 REFRESH_DELETE
= 3600 * 10
1124 def __init__(self
, worker_index
, config
, plugins
, db
):
1127 :param worker_index: thread index
1128 :param config: general configuration of RO, among others the process_id with the docker id where it runs
1129 :param plugins: global shared dict with the loaded plugins
1130 :param db: database class instance to use
1132 threading
.Thread
.__init
__(self
)
1133 self
.config
= config
1134 self
.plugins
= plugins
1135 self
.plugin_name
= "unknown"
1136 self
.logger
= logging
.getLogger("ro.worker{}".format(worker_index
))
1137 self
.worker_index
= worker_index
1138 self
.task_queue
= queue
.Queue(self
.QUEUE_SIZE
)
1139 # targetvim: vimplugin class
1141 # targetvim: vim information from database
1144 self
.vim_targets
= []
1145 self
.my_id
= config
["process_id"] + ":" + str(worker_index
)
1148 "net": VimInteractionNet(self
.db
, self
.my_vims
, self
.db_vims
, self
.logger
),
1149 "vdu": VimInteractionVdu(self
.db
, self
.my_vims
, self
.db_vims
, self
.logger
),
1150 "image": VimInteractionImage(
1151 self
.db
, self
.my_vims
, self
.db_vims
, self
.logger
1153 "flavor": VimInteractionFlavor(
1154 self
.db
, self
.my_vims
, self
.db_vims
, self
.logger
1156 "sdn_net": VimInteractionSdnNet(
1157 self
.db
, self
.my_vims
, self
.db_vims
, self
.logger
1160 self
.time_last_task_processed
= None
1161 # lists of tasks to delete because nsrs or vnfrs has been deleted from db
1162 self
.tasks_to_delete
= []
1163 # it is idle when there are not vim_targets associated
1165 self
.task_locked_time
= config
["global"]["task_locked_time"]
1167 def insert_task(self
, task
):
1169 self
.task_queue
.put(task
, False)
1172 raise NsWorkerException("timeout inserting a task")
1174 def terminate(self
):
1175 self
.insert_task("exit")
1177 def del_task(self
, task
):
1178 with self
.task_lock
:
1179 if task
["status"] == "SCHEDULED":
1180 task
["status"] = "SUPERSEDED"
1182 else: # task["status"] == "processing"
1183 self
.task_lock
.release()
1186 def _process_vim_config(self
, target_id
, db_vim
):
1188 Process vim config, creating vim configuration files as ca_cert
1189 :param target_id: vim/sdn/wim + id
1190 :param db_vim: Vim dictionary obtained from database
1191 :return: None. Modifies vim. Creates a folder target_id:worker_index and several files
1193 if not db_vim
.get("config"):
1199 if db_vim
["config"].get("ca_cert_content"):
1200 file_name
= "{}:{}".format(target_id
, self
.worker_index
)
1204 except FileExistsError
:
1207 file_name
= file_name
+ "/ca_cert"
1209 with
open(file_name
, "w") as f
:
1210 f
.write(db_vim
["config"]["ca_cert_content"])
1211 del db_vim
["config"]["ca_cert_content"]
1212 db_vim
["config"]["ca_cert"] = file_name
1213 except Exception as e
:
1214 raise NsWorkerException(
1215 "Error writing to file '{}': {}".format(file_name
, e
)
1218 def _load_plugin(self
, name
, type="vim"):
1219 # type can be vim or sdn
1220 if "rovim_dummy" not in self
.plugins
:
1221 self
.plugins
["rovim_dummy"] = VimDummyConnector
1223 if "rosdn_dummy" not in self
.plugins
:
1224 self
.plugins
["rosdn_dummy"] = SdnDummyConnector
1226 if name
in self
.plugins
:
1227 return self
.plugins
[name
]
1230 for ep
in entry_points(group
="osm_ro{}.plugins".format(type), name
=name
):
1231 self
.plugins
[name
] = ep
.load()
1232 except Exception as e
:
1233 raise NsWorkerException("Cannot load plugin osm_{}: {}".format(name
, e
))
1235 if name
and name
not in self
.plugins
:
1236 raise NsWorkerException(
1237 "Plugin 'osm_{n}' has not been installed".format(n
=name
)
1240 return self
.plugins
[name
]
1242 def _unload_vim(self
, target_id
):
1244 Unload a vim_account. Removes it from self db_vims dictionary, my_vims dictionary and vim_targets list
1245 :param target_id: Contains type:_id; where type can be 'vim', ...
1249 self
.db_vims
.pop(target_id
, None)
1250 self
.my_vims
.pop(target_id
, None)
1252 if target_id
in self
.vim_targets
:
1253 self
.vim_targets
.remove(target_id
)
1255 self
.logger
.info("Unloaded {}".format(target_id
))
1256 rmtree("{}:{}".format(target_id
, self
.worker_index
))
1257 except FileNotFoundError
:
1258 pass # this is raised by rmtree if folder does not exist
1259 except Exception as e
:
1260 self
.logger
.error("Cannot unload {}: {}".format(target_id
, e
))
1262 def _check_vim(self
, target_id
):
1264 Load a VIM/SDN/WIM (if not loaded) and check connectivity, updating database with ENABLE or ERROR
1265 :param target_id: Contains type:_id; type can be 'vim', 'sdn' or 'wim'
1268 target
, _
, _id
= target_id
.partition(":")
1274 loaded
= target_id
in self
.vim_targets
1284 step
= "Getting {} from db".format(target_id
)
1285 db_vim
= self
.db
.get_one(target_database
, {"_id": _id
})
1287 for op_index
, operation
in enumerate(
1288 db_vim
["_admin"].get("operations", ())
1290 if operation
["operationState"] != "PROCESSING":
1293 locked_at
= operation
.get("locked_at")
1295 if locked_at
is not None and locked_at
>= now
- self
.task_locked_time
:
1296 # some other thread is doing this operation
1300 op_text
= "_admin.operations.{}.".format(op_index
)
1302 if not self
.db
.set_one(
1306 op_text
+ "operationState": "PROCESSING",
1307 op_text
+ "locked_at": locked_at
,
1310 op_text
+ "locked_at": now
,
1311 "admin.current_operation": op_index
,
1313 fail_on_empty
=False,
1317 unset_dict
[op_text
+ "locked_at"] = None
1318 unset_dict
["current_operation"] = None
1319 step
= "Loading " + target_id
1320 error_text
= self
._load
_vim
(target_id
)
1323 step
= "Checking connectivity"
1326 self
.my_vims
[target_id
].check_vim_connectivity()
1328 self
.my_vims
[target_id
].check_credentials()
1330 update_dict
["_admin.operationalState"] = "ENABLED"
1331 update_dict
["_admin.detailed-status"] = ""
1332 unset_dict
[op_text
+ "detailed-status"] = None
1333 update_dict
[op_text
+ "operationState"] = "COMPLETED"
1337 except Exception as e
:
1338 error_text
= "{}: {}".format(step
, e
)
1339 self
.logger
.error("{} for {}: {}".format(step
, target_id
, e
))
1342 if update_dict
or unset_dict
:
1344 update_dict
[op_text
+ "operationState"] = "FAILED"
1345 update_dict
[op_text
+ "detailed-status"] = error_text
1346 unset_dict
.pop(op_text
+ "detailed-status", None)
1347 update_dict
["_admin.operationalState"] = "ERROR"
1348 update_dict
["_admin.detailed-status"] = error_text
1351 update_dict
[op_text
+ "statusEnteredTime"] = now
1355 q_filter
={"_id": _id
},
1356 update_dict
=update_dict
,
1358 fail_on_empty
=False,
1362 self
._unload
_vim
(target_id
)
1364 def _reload_vim(self
, target_id
):
1365 if target_id
in self
.vim_targets
:
1366 self
._load
_vim
(target_id
)
1368 # if the vim is not loaded, but database information of VIM is cached at self.db_vims,
1369 # just remove it to force load again next time it is needed
1370 self
.db_vims
.pop(target_id
, None)
1372 def _load_vim(self
, target_id
):
1374 Load or reload a vim_account, sdn_controller or wim_account.
1375 Read content from database, load the plugin if not loaded.
1376 In case of error loading the plugin, it load a failing VIM_connector
1377 It fills self db_vims dictionary, my_vims dictionary and vim_targets list
1378 :param target_id: Contains type:_id; where type can be 'vim', ...
1379 :return: None if ok, descriptive text if error
1381 target
, _
, _id
= target_id
.partition(":")
1393 step
= "Getting {}={} from db".format(target
, _id
)
1394 # TODO process for wim, sdnc, ...
1395 vim
= self
.db
.get_one(target_database
, {"_id": _id
})
1397 # if deep_get(vim, "config", "sdn-controller"):
1398 # step = "Getting sdn-controller-id='{}' from db".format(vim["config"]["sdn-controller"])
1399 # db_sdn = self.db.get_one("sdns", {"_id": vim["config"]["sdn-controller"]})
1401 step
= "Decrypting password"
1402 schema_version
= vim
.get("schema_version")
1403 self
.db
.encrypt_decrypt_fields(
1406 fields
=("password", "secret"),
1407 schema_version
=schema_version
,
1410 self
._process
_vim
_config
(target_id
, vim
)
1413 plugin_name
= "rovim_" + vim
["vim_type"]
1414 step
= "Loading plugin '{}'".format(plugin_name
)
1415 vim_module_conn
= self
._load
_plugin
(plugin_name
)
1416 step
= "Loading {}'".format(target_id
)
1417 self
.my_vims
[target_id
] = vim_module_conn(
1420 tenant_id
=vim
.get("vim_tenant_id"),
1421 tenant_name
=vim
.get("vim_tenant_name"),
1424 user
=vim
["vim_user"],
1425 passwd
=vim
["vim_password"],
1426 config
=vim
.get("config") or {},
1430 plugin_name
= "rosdn_" + vim
["type"]
1431 step
= "Loading plugin '{}'".format(plugin_name
)
1432 vim_module_conn
= self
._load
_plugin
(plugin_name
, "sdn")
1433 step
= "Loading {}'".format(target_id
)
1435 wim_config
= wim
.pop("config", {}) or {}
1436 wim
["uuid"] = wim
["_id"]
1437 wim
["wim_url"] = wim
["url"]
1440 wim_config
["dpid"] = wim
.pop("dpid")
1442 if wim
.get("switch_id"):
1443 wim_config
["switch_id"] = wim
.pop("switch_id")
1445 # wim, wim_account, config
1446 self
.my_vims
[target_id
] = vim_module_conn(wim
, wim
, wim_config
)
1447 self
.db_vims
[target_id
] = vim
1448 self
.error_status
= None
1451 "Connector loaded for {}, plugin={}".format(target_id
, plugin_name
)
1453 except Exception as e
:
1455 "Cannot load {} plugin={}: {} {}".format(
1456 target_id
, plugin_name
, step
, e
1460 self
.db_vims
[target_id
] = vim
or {}
1461 self
.db_vims
[target_id
] = FailingConnector(str(e
))
1462 error_status
= "{} Error: {}".format(step
, e
)
1466 if target_id
not in self
.vim_targets
:
1467 self
.vim_targets
.append(target_id
)
1469 def _get_db_task(self
):
1471 Read actions from database and reload them at memory. Fill self.refresh_list, pending_list, vim_actions
1476 if not self
.time_last_task_processed
:
1477 self
.time_last_task_processed
= now
1481 locked
= self
.db
.set_one(
1484 "target_id": self
.vim_targets
,
1485 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
1486 "locked_at.lt": now
- self
.task_locked_time
,
1487 "to_check_at.lt": self
.time_last_task_processed
,
1489 update_dict
={"locked_by": self
.my_id
, "locked_at": now
},
1490 fail_on_empty
=False,
1495 ro_task
= self
.db
.get_one(
1498 "target_id": self
.vim_targets
,
1499 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
1505 if self
.time_last_task_processed
== now
:
1506 self
.time_last_task_processed
= None
1509 self
.time_last_task_processed
= now
1510 # self.time_last_task_processed = min(self.time_last_task_processed + 1000, now)
1512 except DbException
as e
:
1513 self
.logger
.error("Database exception at _get_db_task: {}".format(e
))
1514 except Exception as e
:
1515 self
.logger
.critical(
1516 "Unexpected exception at _get_db_task: {}".format(e
), exc_info
=True
1521 def _delete_task(self
, ro_task
, task_index
, task_depends
, db_update
):
1523 Determine if this task need to be done or superseded
1526 my_task
= ro_task
["tasks"][task_index
]
1527 task_id
= my_task
["task_id"]
1528 needed_delete
= ro_task
["vim_info"]["created"] or ro_task
["vim_info"].get(
1529 "created_items", False
1532 if my_task
["status"] == "FAILED":
1533 return None, None # TODO need to be retry??
1536 for index
, task
in enumerate(ro_task
["tasks"]):
1537 if index
== task_index
or not task
:
1541 my_task
["target_record"] == task
["target_record"]
1542 and task
["action"] == "CREATE"
1545 db_update
["tasks.{}.status".format(index
)] = task
[
1548 elif task
["action"] == "CREATE" and task
["status"] not in (
1552 needed_delete
= False
1555 return self
.item2class
[my_task
["item"]].delete(ro_task
, task_index
)
1557 return "SUPERSEDED", None
1558 except Exception as e
:
1559 if not isinstance(e
, NsWorkerException
):
1560 self
.logger
.critical(
1561 "Unexpected exception at _delete_task task={}: {}".format(
1567 return "FAILED", {"vim_status": "VIM_ERROR", "vim_details": str(e
)}
1569 def _create_task(self
, ro_task
, task_index
, task_depends
, db_update
):
1571 Determine if this task need to create something at VIM
1574 my_task
= ro_task
["tasks"][task_index
]
1575 task_id
= my_task
["task_id"]
1578 if my_task
["status"] == "FAILED":
1579 return None, None # TODO need to be retry??
1580 elif my_task
["status"] == "SCHEDULED":
1581 # check if already created by another task
1582 for index
, task
in enumerate(ro_task
["tasks"]):
1583 if index
== task_index
or not task
:
1586 if task
["action"] == "CREATE" and task
["status"] not in (
1591 return task
["status"], "COPY_VIM_INFO"
1594 task_status
, ro_vim_item_update
= self
.item2class
[my_task
["item"]].new(
1595 ro_task
, task_index
, task_depends
1597 # TODO update other CREATE tasks
1598 except Exception as e
:
1599 if not isinstance(e
, NsWorkerException
):
1601 "Error executing task={}: {}".format(task_id
, e
), exc_info
=True
1604 task_status
= "FAILED"
1605 ro_vim_item_update
= {"vim_status": "VIM_ERROR", "vim_details": str(e
)}
1606 # TODO update ro_vim_item_update
1608 return task_status
, ro_vim_item_update
1612 def _get_dependency(self
, task_id
, ro_task
=None, target_id
=None):
1614 Look for dependency task
1615 :param task_id: Can be one of
1616 1. target_vim+blank+task.target_record_id: "(vim|sdn|wim):<id> (vnfrs|nsrs):(vld|vdu|flavor|image).<id>"
1617 2. task.target_record_id: "(vnfrs|nsrs):(vld|vdu|flavor|image).<id>"
1618 3. task.task_id: "<action_id>:number"
1621 :return: database ro_task plus index of task
1624 task_id
.startswith("vim:")
1625 or task_id
.startswith("sdn:")
1626 or task_id
.startswith("wim:")
1628 target_id
, _
, task_id
= task_id
.partition(" ")
1630 if task_id
.startswith("nsrs:") or task_id
.startswith("vnfrs:"):
1631 ro_task_dependency
= self
.db
.get_one(
1633 q_filter
={"target_id": target_id
, "tasks.target_record_id": task_id
},
1634 fail_on_empty
=False,
1637 if ro_task_dependency
:
1638 for task_index
, task
in enumerate(ro_task_dependency
["tasks"]):
1639 if task
["target_record_id"] == task_id
:
1640 return ro_task_dependency
, task_index
1644 for task_index
, task
in enumerate(ro_task
["tasks"]):
1645 if task
and task
["task_id"] == task_id
:
1646 return ro_task
, task_index
1648 ro_task_dependency
= self
.db
.get_one(
1651 "tasks.ANYINDEX.task_id": task_id
,
1652 "tasks.ANYINDEX.target_record.ne": None,
1654 fail_on_empty
=False,
1657 if ro_task_dependency
:
1658 for task_index
, task
in ro_task_dependency
["tasks"]:
1659 if task
["task_id"] == task_id
:
1660 return ro_task_dependency
, task_index
1661 raise NsWorkerException("Cannot get depending task {}".format(task_id
))
1663 def _process_pending_tasks(self
, ro_task
):
1664 ro_task_id
= ro_task
["_id"]
1667 next_check_at
= now
+ (24 * 60 * 60)
1668 db_ro_task_update
= {}
1670 def _update_refresh(new_status
):
1671 # compute next_refresh
1673 nonlocal next_check_at
1674 nonlocal db_ro_task_update
1677 next_refresh
= time
.time()
1679 if task
["item"] in ("image", "flavor"):
1680 next_refresh
+= self
.REFRESH_IMAGE
1681 elif new_status
== "BUILD":
1682 next_refresh
+= self
.REFRESH_BUILD
1683 elif new_status
== "DONE":
1684 next_refresh
+= self
.REFRESH_ACTIVE
1686 next_refresh
+= self
.REFRESH_ERROR
1688 next_check_at
= min(next_check_at
, next_refresh
)
1689 db_ro_task_update
["vim_info.refresh_at"] = next_refresh
1690 ro_task
["vim_info"]["refresh_at"] = next_refresh
1693 # 0: get task_status_create
1695 task_status_create
= None
1699 for t
in ro_task
["tasks"]
1701 and t
["action"] == "CREATE"
1702 and t
["status"] in ("BUILD", "DONE")
1708 task_status_create
= task_create
["status"]
1710 # 1: look for tasks in status SCHEDULED, or in status CREATE if action is DONE or BUILD
1711 for task_action
in ("DELETE", "CREATE", "EXEC"):
1712 db_vim_update
= None
1715 for task_index
, task
in enumerate(ro_task
["tasks"]):
1717 continue # task deleted
1720 target_update
= None
1724 task_action
in ("DELETE", "EXEC")
1725 and task
["status"] not in ("SCHEDULED", "BUILD")
1727 or task
["action"] != task_action
1729 task_action
== "CREATE"
1730 and task
["status"] in ("FINISHED", "SUPERSEDED")
1735 task_path
= "tasks.{}.status".format(task_index
)
1737 db_vim_info_update
= None
1739 if task
["status"] == "SCHEDULED":
1740 # check if tasks that this depends on have been completed
1741 dependency_not_completed
= False
1743 for dependency_task_id
in task
.get("depends_on") or ():
1746 dependency_task_index
,
1747 ) = self
._get
_dependency
(
1748 dependency_task_id
, target_id
=ro_task
["target_id"]
1750 dependency_task
= dependency_ro_task
["tasks"][
1751 dependency_task_index
1754 if dependency_task
["status"] == "SCHEDULED":
1755 dependency_not_completed
= True
1756 next_check_at
= min(
1757 next_check_at
, dependency_ro_task
["to_check_at"]
1759 # must allow dependent task to be processed first
1760 # to do this set time after last_task_processed
1761 next_check_at
= max(
1762 self
.time_last_task_processed
, next_check_at
1765 elif dependency_task
["status"] == "FAILED":
1766 error_text
= "Cannot {} {} because depends on failed {} {} id={}): {}".format(
1769 dependency_task
["action"],
1770 dependency_task
["item"],
1772 dependency_ro_task
["vim_info"].get(
1777 "task={} {}".format(task
["task_id"], error_text
)
1779 raise NsWorkerException(error_text
)
1781 task_depends
[dependency_task_id
] = dependency_ro_task
[
1785 "TASK-{}".format(dependency_task_id
)
1786 ] = dependency_ro_task
["vim_info"]["vim_id"]
1788 if dependency_not_completed
:
1789 # TODO set at vim_info.vim_details that it is waiting
1792 # before calling VIM-plugin as it can take more than task_locked_time, insert to LockRenew
1793 # the task of renew this locking. It will update database locket_at periodically
1795 lock_object
= LockRenew
.add_lock_object(
1796 "ro_tasks", ro_task
, self
1799 if task
["action"] == "DELETE":
1800 (new_status
, db_vim_info_update
,) = self
._delete
_task
(
1801 ro_task
, task_index
, task_depends
, db_ro_task_update
1804 "FINISHED" if new_status
== "DONE" else new_status
1806 # ^with FINISHED instead of DONE it will not be refreshing
1808 if new_status
in ("FINISHED", "SUPERSEDED"):
1809 target_update
= "DELETE"
1810 elif task
["action"] == "EXEC":
1815 ) = self
.item2class
[task
["item"]].exec(
1816 ro_task
, task_index
, task_depends
1819 "FINISHED" if new_status
== "DONE" else new_status
1821 # ^with FINISHED instead of DONE it will not be refreshing
1824 # load into database the modified db_task_update "retries" and "next_retry"
1825 if db_task_update
.get("retries"):
1827 "tasks.{}.retries".format(task_index
)
1828 ] = db_task_update
["retries"]
1830 next_check_at
= time
.time() + db_task_update
.get(
1833 target_update
= None
1834 elif task
["action"] == "CREATE":
1835 if task
["status"] == "SCHEDULED":
1836 if task_status_create
:
1837 new_status
= task_status_create
1838 target_update
= "COPY_VIM_INFO"
1840 new_status
, db_vim_info_update
= self
.item2class
[
1842 ].new(ro_task
, task_index
, task_depends
)
1843 # self._create_task(ro_task, task_index, task_depends, db_ro_task_update)
1844 _update_refresh(new_status
)
1847 ro_task
["vim_info"]["refresh_at"]
1848 and now
> ro_task
["vim_info"]["refresh_at"]
1850 new_status
, db_vim_info_update
= self
.item2class
[
1853 _update_refresh(new_status
)
1855 except Exception as e
:
1856 new_status
= "FAILED"
1857 db_vim_info_update
= {
1858 "vim_status": "VIM_ERROR",
1859 "vim_details": str(e
),
1863 e
, (NsWorkerException
, vimconn
.VimConnException
)
1866 "Unexpected exception at _delete_task task={}: {}".format(
1873 if db_vim_info_update
:
1874 db_vim_update
= db_vim_info_update
.copy()
1875 db_ro_task_update
.update(
1878 for k
, v
in db_vim_info_update
.items()
1881 ro_task
["vim_info"].update(db_vim_info_update
)
1884 if task_action
== "CREATE":
1885 task_status_create
= new_status
1886 db_ro_task_update
[task_path
] = new_status
1888 if target_update
or db_vim_update
:
1889 if target_update
== "DELETE":
1890 self
._update
_target
(task
, None)
1891 elif target_update
== "COPY_VIM_INFO":
1892 self
._update
_target
(task
, ro_task
["vim_info"])
1894 self
._update
_target
(task
, db_vim_update
)
1896 except Exception as e
:
1898 isinstance(e
, DbException
)
1899 and e
.http_code
== HTTPStatus
.NOT_FOUND
1901 # if the vnfrs or nsrs has been removed from database, this task must be removed
1903 "marking to delete task={}".format(task
["task_id"])
1905 self
.tasks_to_delete
.append(task
)
1908 "Unexpected exception at _update_target task={}: {}".format(
1914 locked_at
= ro_task
["locked_at"]
1918 lock_object
["locked_at"],
1919 lock_object
["locked_at"] + self
.task_locked_time
,
1921 # locked_at contains two times to avoid race condition. In case the lock has been renew, it will
1922 # contain exactly locked_at + self.task_locked_time
1923 LockRenew
.remove_lock_object(lock_object
)
1926 "_id": ro_task
["_id"],
1927 "to_check_at": ro_task
["to_check_at"],
1928 "locked_at": locked_at
,
1930 # modify own task. Try filtering by to_next_check. For race condition if to_check_at has been modified,
1931 # outside this task (by ro_nbi) do not update it
1932 db_ro_task_update
["locked_by"] = None
1933 # locked_at converted to int only for debugging. When has not decimals it means it has been unlocked
1934 db_ro_task_update
["locked_at"] = int(now
- self
.task_locked_time
)
1935 db_ro_task_update
["modified_at"] = now
1936 db_ro_task_update
["to_check_at"] = next_check_at
1938 if not self
.db
.set_one(
1940 update_dict
=db_ro_task_update
,
1942 fail_on_empty
=False,
1944 del db_ro_task_update
["to_check_at"]
1945 del q_filter
["to_check_at"]
1949 update_dict
=db_ro_task_update
,
1952 except DbException
as e
:
1954 "ro_task={} Error updating database {}".format(ro_task_id
, e
)
1956 except Exception as e
:
1958 "Error executing ro_task={}: {}".format(ro_task_id
, e
), exc_info
=True
1961 def _update_target(self
, task
, ro_vim_item_update
):
1962 table
, _
, temp
= task
["target_record"].partition(":")
1963 _id
, _
, path_vim_status
= temp
.partition(":")
1964 path_item
= path_vim_status
[: path_vim_status
.rfind(".")]
1965 path_item
= path_item
[: path_item
.rfind(".")]
1966 # path_vim_status: dot separated list targeting vim information, e.g. "vdur.10.vim_info.vim:id"
1967 # path_item: dot separated list targeting record information, e.g. "vdur.10"
1969 if ro_vim_item_update
:
1971 path_vim_status
+ "." + k
: v
1972 for k
, v
in ro_vim_item_update
.items()
1974 in ("vim_id", "vim_details", "vim_name", "vim_status", "interfaces")
1977 if path_vim_status
.startswith("vdur."):
1978 # for backward compatibility, add vdur.name apart from vdur.vim_name
1979 if ro_vim_item_update
.get("vim_name"):
1980 update_dict
[path_item
+ ".name"] = ro_vim_item_update
["vim_name"]
1982 # for backward compatibility, add vdur.vim-id apart from vdur.vim_id
1983 if ro_vim_item_update
.get("vim_id"):
1984 update_dict
[path_item
+ ".vim-id"] = ro_vim_item_update
["vim_id"]
1986 # update general status
1987 if ro_vim_item_update
.get("vim_status"):
1988 update_dict
[path_item
+ ".status"] = ro_vim_item_update
[
1992 if ro_vim_item_update
.get("interfaces"):
1993 path_interfaces
= path_item
+ ".interfaces"
1995 for i
, iface
in enumerate(ro_vim_item_update
.get("interfaces")):
1999 path_interfaces
+ ".{}.".format(i
) + k
: v
2000 for k
, v
in iface
.items()
2001 if k
in ("vlan", "compute_node", "pci")
2005 # put ip_address and mac_address with ip-address and mac-address
2006 if iface
.get("ip_address"):
2008 path_interfaces
+ ".{}.".format(i
) + "ip-address"
2009 ] = iface
["ip_address"]
2011 if iface
.get("mac_address"):
2013 path_interfaces
+ ".{}.".format(i
) + "mac-address"
2014 ] = iface
["mac_address"]
2016 if iface
.get("mgmt_vnf_interface") and iface
.get("ip_address"):
2017 update_dict
["ip-address"] = iface
.get("ip_address").split(
2021 if iface
.get("mgmt_vdu_interface") and iface
.get("ip_address"):
2022 update_dict
[path_item
+ ".ip-address"] = iface
.get(
2026 self
.db
.set_one(table
, q_filter
={"_id": _id
}, update_dict
=update_dict
)
2028 update_dict
= {path_item
+ ".status": "DELETED"}
2031 q_filter
={"_id": _id
},
2032 update_dict
=update_dict
,
2033 unset
={path_vim_status
: None},
2036 def _process_delete_db_tasks(self
):
2038 Delete task from database because vnfrs or nsrs or both have been deleted
2039 :return: None. Uses and modify self.tasks_to_delete
2041 while self
.tasks_to_delete
:
2042 task
= self
.tasks_to_delete
[0]
2043 vnfrs_deleted
= None
2044 nsr_id
= task
["nsr_id"]
2046 if task
["target_record"].startswith("vnfrs:"):
2047 # check if nsrs is present
2048 if self
.db
.get_one("nsrs", {"_id": nsr_id
}, fail_on_empty
=False):
2049 vnfrs_deleted
= task
["target_record"].split(":")[1]
2052 self
.delete_db_tasks(self
.db
, nsr_id
, vnfrs_deleted
)
2053 except Exception as e
:
2055 "Error deleting task={}: {}".format(task
["task_id"], e
)
2057 self
.tasks_to_delete
.pop(0)
2060 def delete_db_tasks(db
, nsr_id
, vnfrs_deleted
):
2062 Static method because it is called from osm_ng_ro.ns
2063 :param db: instance of database to use
2064 :param nsr_id: affected nsrs id
2065 :param vnfrs_deleted: only tasks with this vnfr id. If None, all affected by nsr_id
2066 :return: None, exception is fails
2069 for retry
in range(retries
):
2070 ro_tasks
= db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2074 for ro_task
in ro_tasks
:
2076 to_delete_ro_task
= True
2078 for index
, task
in enumerate(ro_task
["tasks"]):
2081 elif (not vnfrs_deleted
and task
["nsr_id"] == nsr_id
) or (
2083 and task
["target_record"].startswith("vnfrs:" + vnfrs_deleted
)
2085 db_update
["tasks.{}".format(index
)] = None
2087 # used by other nsr, ro_task cannot be deleted
2088 to_delete_ro_task
= False
2090 # delete or update if nobody has changed ro_task meanwhile. Used modified_at for known if changed
2091 if to_delete_ro_task
:
2095 "_id": ro_task
["_id"],
2096 "modified_at": ro_task
["modified_at"],
2098 fail_on_empty
=False,
2102 db_update
["modified_at"] = now
2106 "_id": ro_task
["_id"],
2107 "modified_at": ro_task
["modified_at"],
2109 update_dict
=db_update
,
2110 fail_on_empty
=False,
2116 raise NsWorkerException("Exceeded {} retries".format(retries
))
2120 self
.logger
.info("Starting")
2122 # step 1: get commands from queue
2124 if self
.vim_targets
:
2125 task
= self
.task_queue
.get(block
=False)
2128 self
.logger
.debug("enters in idle state")
2130 task
= self
.task_queue
.get(block
=True)
2133 if task
[0] == "terminate":
2135 elif task
[0] == "load_vim":
2136 self
.logger
.info("order to load vim {}".format(task
[1]))
2137 self
._load
_vim
(task
[1])
2138 elif task
[0] == "unload_vim":
2139 self
.logger
.info("order to unload vim {}".format(task
[1]))
2140 self
._unload
_vim
(task
[1])
2141 elif task
[0] == "reload_vim":
2142 self
._reload
_vim
(task
[1])
2143 elif task
[0] == "check_vim":
2144 self
.logger
.info("order to check vim {}".format(task
[1]))
2145 self
._check
_vim
(task
[1])
2147 except Exception as e
:
2148 if isinstance(e
, queue
.Empty
):
2151 self
.logger
.critical(
2152 "Error processing task: {}".format(e
), exc_info
=True
2155 # step 2: process pending_tasks, delete not needed tasks
2157 if self
.tasks_to_delete
:
2158 self
._process
_delete
_db
_tasks
()
2160 ro_task
= self
._get
_db
_task
()
2162 self
._process
_pending
_tasks
(ro_task
)
2166 except Exception as e
:
2167 self
.logger
.critical(
2168 "Unexpected exception at run: " + str(e
), exc_info
=True
2171 self
.logger
.info("Finishing")