1 # -*- coding: utf-8 -*-
4 # Copyright 2020 Telefonica Investigacion y Desarrollo, S.A.U.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
19 from http
import HTTPStatus
21 from random
import choice
as random_choice
22 from threading
import Lock
24 from traceback
import format_exc
as traceback_format_exc
25 from typing
import Any
, Dict
, Tuple
, Type
26 from uuid
import uuid4
28 from cryptography
.hazmat
.backends
import default_backend
as crypto_default_backend
29 from cryptography
.hazmat
.primitives
import serialization
as crypto_serialization
30 from cryptography
.hazmat
.primitives
.asymmetric
import rsa
38 from osm_common
import (
45 version
as common_version
,
47 from osm_common
.dbbase
import DbBase
, DbException
48 from osm_common
.fsbase
import FsBase
, FsException
49 from osm_common
.msgbase
import MsgException
50 from osm_ng_ro
.ns_thread
import deep_get
, NsWorker
, NsWorkerException
51 from osm_ng_ro
.validation
import deploy_schema
, validate_input
54 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
55 min_common_version
= "0.1.16"
58 class NsException(Exception):
59 def __init__(self
, message
, http_code
=HTTPStatus
.BAD_REQUEST
):
60 self
.http_code
= http_code
61 super(Exception, self
).__init
__(message
)
66 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
67 will provide a random one
70 # Try getting docker id. If fails, get pid
72 with
open("/proc/self/cgroup", "r") as f
:
73 text_id_
= f
.readline()
74 _
, _
, text_id
= text_id_
.rpartition("/")
75 text_id
= text_id
.replace("\n", "")[:12]
83 return "".join(random_choice("0123456789abcdef") for _
in range(12))
87 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
90 for point
in v
.split("."):
91 filled
.append(point
.zfill(8))
102 # self.operations = None
104 # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
105 # If done now it will not be linked to parent not getting its handler and level
107 self
.write_lock
= None
108 self
.vims_assigned
= {}
112 self
.process_params_function_map
= {
113 "net": Ns
._process
_net
_params
,
114 "image": Ns
._process
_image
_params
,
115 "flavor": Ns
._process
_flavor
_params
,
116 "vdu": Ns
._process
_vdu
_params
,
117 "affinity-or-anti-affinity-group": Ns
._process
_affinity
_group
_params
,
124 "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group",
127 def init_db(self
, target_version
):
130 def start(self
, config
):
132 Connect to database, filesystem storage, and messaging
133 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
134 :param config: Configuration of db, storage, etc
138 self
.config
["process_id"] = get_process_id() # used for HA identity
139 self
.logger
= logging
.getLogger("ro.ns")
141 # check right version of common
142 if versiontuple(common_version
) < versiontuple(min_common_version
):
144 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
145 common_version
, min_common_version
151 if config
["database"]["driver"] == "mongo":
152 self
.db
= dbmongo
.DbMongo()
153 self
.db
.db_connect(config
["database"])
154 elif config
["database"]["driver"] == "memory":
155 self
.db
= dbmemory
.DbMemory()
156 self
.db
.db_connect(config
["database"])
159 "Invalid configuration param '{}' at '[database]':'driver'".format(
160 config
["database"]["driver"]
165 if config
["storage"]["driver"] == "local":
166 self
.fs
= fslocal
.FsLocal()
167 self
.fs
.fs_connect(config
["storage"])
168 elif config
["storage"]["driver"] == "mongo":
169 self
.fs
= fsmongo
.FsMongo()
170 self
.fs
.fs_connect(config
["storage"])
171 elif config
["storage"]["driver"] is None:
175 "Invalid configuration param '{}' at '[storage]':'driver'".format(
176 config
["storage"]["driver"]
181 if config
["message"]["driver"] == "local":
182 self
.msg
= msglocal
.MsgLocal()
183 self
.msg
.connect(config
["message"])
184 elif config
["message"]["driver"] == "kafka":
185 self
.msg
= msgkafka
.MsgKafka()
186 self
.msg
.connect(config
["message"])
189 "Invalid configuration param '{}' at '[message]':'driver'".format(
190 config
["message"]["driver"]
194 # TODO load workers to deal with exising database tasks
196 self
.write_lock
= Lock()
197 except (DbException
, FsException
, MsgException
) as e
:
198 raise NsException(str(e
), http_code
=e
.http_code
)
200 def get_assigned_vims(self
):
201 return list(self
.vims_assigned
.keys())
206 self
.db
.db_disconnect()
209 self
.fs
.fs_disconnect()
212 self
.msg
.disconnect()
214 self
.write_lock
= None
215 except (DbException
, FsException
, MsgException
) as e
:
216 raise NsException(str(e
), http_code
=e
.http_code
)
218 for worker
in self
.workers
:
219 worker
.insert_task(("terminate",))
221 def _create_worker(self
):
223 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
224 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
225 return the index of the assigned worker thread. Worker threads are storead at self.workers
227 # Look for a thread in idle status
231 for i
in range(len(self
.workers
))
232 if self
.workers
[i
] and self
.workers
[i
].idle
237 if worker_id
is not None:
238 # unset idle status to avoid race conditions
239 self
.workers
[worker_id
].idle
= False
241 worker_id
= len(self
.workers
)
243 if worker_id
< self
.config
["global"]["server.ns_threads"]:
244 # create a new worker
246 NsWorker(worker_id
, self
.config
, self
.plugins
, self
.db
)
248 self
.workers
[worker_id
].start()
250 # reached maximum number of threads, assign VIM to an existing one
251 worker_id
= self
.next_worker
252 self
.next_worker
= (self
.next_worker
+ 1) % self
.config
["global"][
258 def assign_vim(self
, target_id
):
259 with self
.write_lock
:
260 return self
._assign
_vim
(target_id
)
262 def _assign_vim(self
, target_id
):
263 if target_id
not in self
.vims_assigned
:
264 worker_id
= self
.vims_assigned
[target_id
] = self
._create
_worker
()
265 self
.workers
[worker_id
].insert_task(("load_vim", target_id
))
267 def reload_vim(self
, target_id
):
268 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
269 # this is because database VIM information is cached for threads working with SDN
270 with self
.write_lock
:
271 for worker
in self
.workers
:
272 if worker
and not worker
.idle
:
273 worker
.insert_task(("reload_vim", target_id
))
275 def unload_vim(self
, target_id
):
276 with self
.write_lock
:
277 return self
._unload
_vim
(target_id
)
279 def _unload_vim(self
, target_id
):
280 if target_id
in self
.vims_assigned
:
281 worker_id
= self
.vims_assigned
[target_id
]
282 self
.workers
[worker_id
].insert_task(("unload_vim", target_id
))
283 del self
.vims_assigned
[target_id
]
285 def check_vim(self
, target_id
):
286 with self
.write_lock
:
287 if target_id
in self
.vims_assigned
:
288 worker_id
= self
.vims_assigned
[target_id
]
290 worker_id
= self
._create
_worker
()
292 worker
= self
.workers
[worker_id
]
293 worker
.insert_task(("check_vim", target_id
))
295 def unload_unused_vims(self
):
296 with self
.write_lock
:
299 for target_id
in self
.vims_assigned
:
300 if not self
.db
.get_one(
303 "target_id": target_id
,
304 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
308 vims_to_unload
.append(target_id
)
310 for target_id
in vims_to_unload
:
311 self
._unload
_vim
(target_id
)
319 """This method reads cloud init from a file.
321 Note: Not used as cloud init content is provided in the http body.
324 db (Type[DbBase]): [description]
325 fs (Type[FsBase]): [description]
326 location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
329 NsException: [description]
330 NsException: [description]
335 vnfd_id
, _
, other
= location
.partition(":")
336 _type
, _
, name
= other
.partition(":")
337 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
340 base_folder
= vnfd
["_admin"]["storage"]
341 cloud_init_file
= "{}/{}/cloud_init/{}".format(
342 base_folder
["folder"], base_folder
["pkg-dir"], name
347 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
352 with fs
.file_open(cloud_init_file
, "r") as ci_file
:
353 cloud_init_content
= ci_file
.read()
355 cloud_init_content
= vnfd
["vdu"][int(name
)]["cloud-init"]
357 raise NsException("Mismatch descriptor for cloud init: {}".format(location
))
359 return cloud_init_content
363 cloud_init_content
: str,
364 params
: Dict
[str, Any
],
367 """Function that processes the cloud init to replace Jinja2 encoded parameters.
370 cloud_init_content (str): [description]
371 params (Dict[str, Any]): [description]
372 context (str): [description]
375 NsException: [description]
376 NsException: [description]
382 env
= Environment(undefined
=StrictUndefined
)
383 template
= env
.from_string(cloud_init_content
)
385 return template
.render(params
or {})
386 except UndefinedError
as e
:
388 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
389 "inside the 'additionalParamsForVnf' block".format(e
, context
)
391 except (TemplateError
, TemplateNotFound
) as e
:
393 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
398 def _create_db_ro_nsrs(self
, nsr_id
, now
):
400 key
= rsa
.generate_private_key(
401 backend
=crypto_default_backend(), public_exponent
=65537, key_size
=2048
403 private_key
= key
.private_bytes(
404 crypto_serialization
.Encoding
.PEM
,
405 crypto_serialization
.PrivateFormat
.PKCS8
,
406 crypto_serialization
.NoEncryption(),
408 public_key
= key
.public_key().public_bytes(
409 crypto_serialization
.Encoding
.OpenSSH
,
410 crypto_serialization
.PublicFormat
.OpenSSH
,
412 private_key
= private_key
.decode("utf8")
413 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
414 i
= private_key
.find("\n")
415 private_key
= "-----BEGIN RSA PRIVATE KEY-----" + private_key
[i
:]
416 public_key
= public_key
.decode("utf8")
417 except Exception as e
:
418 raise NsException("Cannot create ssh-keys: {}".format(e
))
420 schema_version
= "1.1"
421 private_key_encrypted
= self
.db
.encrypt(
422 private_key
, schema_version
=schema_version
, salt
=nsr_id
429 "schema_version": schema_version
,
431 "public_key": public_key
,
432 "private_key": private_key_encrypted
,
435 self
.db
.create("ro_nsrs", db_content
)
441 deployment_info
: Dict
[str, Any
],
446 target_record_id
: str,
447 extra_dict
: Dict
[str, Any
] = None,
449 """Function to create task dict from deployment information.
452 deployment_info (Dict[str, Any]): [description]
453 target_id (str): [description]
454 item (str): [description]
455 action (str): [description]
456 target_record (str): [description]
457 target_record_id (str): [description]
458 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
461 Dict[str, Any]: [description]
464 "target_id": target_id
, # it will be removed before pushing at database
465 "action_id": deployment_info
.get("action_id"),
466 "nsr_id": deployment_info
.get("nsr_id"),
467 "task_id": f
"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
468 "status": "SCHEDULED",
471 "target_record": target_record
,
472 "target_record_id": target_record_id
,
476 task
.update(extra_dict
) # params, find_params, depends_on
478 deployment_info
["task_index"] = deployment_info
.get("task_index", 0) + 1
485 task
: Dict
[str, Any
],
487 """Function to create an RO task from task information.
490 target_id (str): [description]
491 task (Dict[str, Any]): [description]
494 Dict[str, Any]: [description]
498 _id
= task
.get("task_id")
503 "target_id": target_id
,
506 "created_items": None,
523 def _process_image_params(
524 target_image
: Dict
[str, Any
],
525 indata
: Dict
[str, Any
],
526 vim_info
: Dict
[str, Any
],
527 target_record_id
: str,
528 **kwargs
: Dict
[str, Any
],
530 """Function to process VDU image parameters.
533 target_image (Dict[str, Any]): [description]
534 indata (Dict[str, Any]): [description]
535 vim_info (Dict[str, Any]): [description]
536 target_record_id (str): [description]
539 Dict[str, Any]: [description]
543 if target_image
.get("image"):
544 find_params
["filter_dict"] = {"name": target_image
.get("image")}
546 if target_image
.get("vim_image_id"):
547 find_params
["filter_dict"] = {"id": target_image
.get("vim_image_id")}
549 if target_image
.get("image_checksum"):
550 find_params
["filter_dict"] = {
551 "checksum": target_image
.get("image_checksum")
554 return {"find_params": find_params
}
557 def _get_resource_allocation_params(
558 quota_descriptor
: Dict
[str, Any
],
560 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
564 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
567 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
571 if quota_descriptor
.get("limit"):
572 quota
["limit"] = int(quota_descriptor
["limit"])
574 if quota_descriptor
.get("reserve"):
575 quota
["reserve"] = int(quota_descriptor
["reserve"])
577 if quota_descriptor
.get("shares"):
578 quota
["shares"] = int(quota_descriptor
["shares"])
583 def _process_guest_epa_quota_params(
584 guest_epa_quota
: Dict
[str, Any
],
587 """Function to extract the guest epa quota parameters.
590 guest_epa_quota (Dict[str, Any]): [description]
591 epa_vcpu_set (bool): [description]
594 Dict[str, Any]: [description]
598 if guest_epa_quota
.get("cpu-quota") and not epa_vcpu_set
:
599 cpuquota
= Ns
._get
_resource
_allocation
_params
(
600 guest_epa_quota
.get("cpu-quota")
604 result
["cpu-quota"] = cpuquota
606 if guest_epa_quota
.get("mem-quota"):
607 vduquota
= Ns
._get
_resource
_allocation
_params
(
608 guest_epa_quota
.get("mem-quota")
612 result
["mem-quota"] = vduquota
614 if guest_epa_quota
.get("disk-io-quota"):
615 diskioquota
= Ns
._get
_resource
_allocation
_params
(
616 guest_epa_quota
.get("disk-io-quota")
620 result
["disk-io-quota"] = diskioquota
622 if guest_epa_quota
.get("vif-quota"):
623 vifquota
= Ns
._get
_resource
_allocation
_params
(
624 guest_epa_quota
.get("vif-quota")
628 result
["vif-quota"] = vifquota
633 def _process_guest_epa_numa_params(
634 guest_epa_quota
: Dict
[str, Any
],
635 ) -> Tuple
[Dict
[str, Any
], bool]:
639 guest_epa_quota (Dict[str, Any]): [description]
642 Tuple[Dict[str, Any], bool]: [description]
647 if guest_epa_quota
.get("numa-node-policy"):
648 numa_node_policy
= guest_epa_quota
.get("numa-node-policy")
650 if numa_node_policy
.get("node"):
651 numa_node
= numa_node_policy
["node"][0]
653 if numa_node
.get("num-cores"):
654 numa
["cores"] = numa_node
["num-cores"]
657 paired_threads
= numa_node
.get("paired-threads", {})
658 if paired_threads
.get("num-paired-threads"):
659 numa
["paired-threads"] = int(
660 numa_node
["paired-threads"]["num-paired-threads"]
664 if paired_threads
.get("paired-thread-ids"):
665 numa
["paired-threads-id"] = []
667 for pair
in paired_threads
["paired-thread-ids"]:
668 numa
["paired-threads-id"].append(
670 str(pair
["thread-a"]),
671 str(pair
["thread-b"]),
675 if numa_node
.get("num-threads"):
676 numa
["threads"] = int(numa_node
["num-threads"])
679 if numa_node
.get("memory-mb"):
680 numa
["memory"] = max(int(int(numa_node
["memory-mb"]) / 1024), 1)
682 return numa
, epa_vcpu_set
685 def _process_guest_epa_cpu_pinning_params(
686 guest_epa_quota
: Dict
[str, Any
],
689 ) -> Tuple
[Dict
[str, Any
], bool]:
693 guest_epa_quota (Dict[str, Any]): [description]
694 vcpu_count (int): [description]
695 epa_vcpu_set (bool): [description]
698 Tuple[Dict[str, Any], bool]: [description]
701 local_epa_vcpu_set
= epa_vcpu_set
704 guest_epa_quota
.get("cpu-pinning-policy") == "DEDICATED"
709 if guest_epa_quota
.get("cpu-thread-pinning-policy") != "PREFER"
711 ] = max(vcpu_count
, 1)
712 local_epa_vcpu_set
= True
714 return numa
, local_epa_vcpu_set
717 def _process_epa_params(
718 target_flavor
: Dict
[str, Any
],
723 target_flavor (Dict[str, Any]): [description]
726 Dict[str, Any]: [description]
731 if target_flavor
.get("guest-epa"):
732 guest_epa
= target_flavor
["guest-epa"]
734 numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_numa
_params
(
735 guest_epa_quota
=guest_epa
738 if guest_epa
.get("mempage-size"):
739 extended
["mempage-size"] = guest_epa
.get("mempage-size")
741 tmp_numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_cpu
_pinning
_params
(
742 guest_epa_quota
=guest_epa
,
743 vcpu_count
=int(target_flavor
.get("vcpu-count", 1)),
744 epa_vcpu_set
=epa_vcpu_set
,
746 numa
.update(tmp_numa
)
749 Ns
._process
_guest
_epa
_quota
_params
(
750 guest_epa_quota
=guest_epa
,
751 epa_vcpu_set
=epa_vcpu_set
,
756 extended
["numas"] = [numa
]
761 def _process_flavor_params(
762 target_flavor
: Dict
[str, Any
],
763 indata
: Dict
[str, Any
],
764 vim_info
: Dict
[str, Any
],
765 target_record_id
: str,
766 **kwargs
: Dict
[str, Any
],
771 target_flavor (Dict[str, Any]): [description]
772 indata (Dict[str, Any]): [description]
773 vim_info (Dict[str, Any]): [description]
774 target_record_id (str): [description]
777 Dict[str, Any]: [description]
780 "disk": int(target_flavor
["storage-gb"]),
781 "ram": int(target_flavor
["memory-mb"]),
782 "vcpus": int(target_flavor
["vcpu-count"]),
786 for vnf
in indata
.get("vnf", []):
787 for vdur
in vnf
.get("vdur", []):
788 if vdur
.get("ns-flavor-id") == target_flavor
["id"]:
791 for storage
in target_vdur
.get("virtual-storages", []):
793 storage
.get("type-of-storage")
794 == "etsi-nfv-descriptors:ephemeral-storage"
796 flavor_data
["ephemeral"] = int(storage
.get("size-of-storage", 0))
797 elif storage
.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
798 flavor_data
["swap"] = int(storage
.get("size-of-storage", 0))
800 extended
= Ns
._process
_epa
_params
(target_flavor
)
802 flavor_data
["extended"] = extended
804 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
805 flavor_data_name
= flavor_data
.copy()
806 flavor_data_name
["name"] = target_flavor
["name"]
807 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
812 def _ip_profile_to_ro(
813 ip_profile
: Dict
[str, Any
],
818 ip_profile (Dict[str, Any]): [description]
821 Dict[str, Any]: [description]
828 if "v4" in ip_profile
.get("ip-version", "ipv4")
830 "subnet_address": ip_profile
.get("subnet-address"),
831 "gateway_address": ip_profile
.get("gateway-address"),
832 "dhcp_enabled": ip_profile
.get("dhcp-params", {}).get("enabled", False),
833 "dhcp_start_address": ip_profile
.get("dhcp-params", {}).get(
834 "start-address", None
836 "dhcp_count": ip_profile
.get("dhcp-params", {}).get("count", None),
839 if ip_profile
.get("dns-server"):
840 ro_ip_profile
["dns_address"] = ";".join(
841 [v
["address"] for v
in ip_profile
["dns-server"] if v
.get("address")]
844 if ip_profile
.get("security-group"):
845 ro_ip_profile
["security_group"] = ip_profile
["security-group"]
850 def _process_net_params(
851 target_vld
: Dict
[str, Any
],
852 indata
: Dict
[str, Any
],
853 vim_info
: Dict
[str, Any
],
854 target_record_id
: str,
855 **kwargs
: Dict
[str, Any
],
857 """Function to process network parameters.
860 target_vld (Dict[str, Any]): [description]
861 indata (Dict[str, Any]): [description]
862 vim_info (Dict[str, Any]): [description]
863 target_record_id (str): [description]
866 Dict[str, Any]: [description]
870 if vim_info
.get("sdn"):
871 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
872 # ns_preffix = "nsrs:{}".format(nsr_id)
873 # remove the ending ".sdn
874 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
875 extra_dict
["params"] = {
877 for k
in ("sdn-ports", "target_vim", "vlds", "type")
881 # TODO needed to add target_id in the dependency.
882 if vim_info
.get("target_vim"):
883 extra_dict
["depends_on"] = [
884 f
"{vim_info.get('target_vim')} {vld_target_record_id}"
889 if vim_info
.get("vim_network_name"):
890 extra_dict
["find_params"] = {
892 "name": vim_info
.get("vim_network_name"),
895 elif vim_info
.get("vim_network_id"):
896 extra_dict
["find_params"] = {
898 "id": vim_info
.get("vim_network_id"),
901 elif target_vld
.get("mgmt-network"):
902 extra_dict
["find_params"] = {
904 "name": target_vld
["id"],
908 extra_dict
["params"] = {
910 f
"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
912 "ip_profile": Ns
._ip
_profile
_to
_ro
(vim_info
.get("ip_profile")),
913 "provider_network_profile": vim_info
.get("provider_network"),
916 if not target_vld
.get("underlay"):
917 extra_dict
["params"]["net_type"] = "bridge"
919 extra_dict
["params"]["net_type"] = (
920 "ptp" if target_vld
.get("type") == "ELINE" else "data"
926 def _process_vdu_params(
927 target_vdu
: Dict
[str, Any
],
928 indata
: Dict
[str, Any
],
929 vim_info
: Dict
[str, Any
],
930 target_record_id
: str,
931 **kwargs
: Dict
[str, Any
],
933 """Function to process VDU parameters.
936 target_vdu (Dict[str, Any]): [description]
937 indata (Dict[str, Any]): [description]
938 vim_info (Dict[str, Any]): [description]
939 target_record_id (str): [description]
942 Dict[str, Any]: [description]
944 vnfr_id
= kwargs
.get("vnfr_id")
945 nsr_id
= kwargs
.get("nsr_id")
946 vnfr
= kwargs
.get("vnfr")
947 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
948 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
949 logger
= kwargs
.get("logger")
950 db
= kwargs
.get("db")
951 fs
= kwargs
.get("fs")
952 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
954 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
955 ns_preffix
= "nsrs:{}".format(nsr_id
)
956 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
957 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
958 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
961 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
962 if interface
.get("ns-vld-id"):
963 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
964 elif interface
.get("vnf-vld-id"):
965 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
968 "Interface {} from vdu {} not connected to any vld".format(
969 iface_index
, target_vdu
["vdu-name"]
973 continue # interface not connected to any vld
975 extra_dict
["depends_on"].append(net_text
)
977 if "port-security-enabled" in interface
:
978 interface
["port_security"] = interface
.pop("port-security-enabled")
980 if "port-security-disable-strategy" in interface
:
981 interface
["port_security_disable_strategy"] = interface
.pop(
982 "port-security-disable-strategy"
987 for x
, v
in interface
.items()
993 "port_security_disable_strategy",
997 net_item
["net_id"] = "TASK-" + net_text
998 net_item
["type"] = "virtual"
1000 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1001 # TODO floating_ip: True/False (or it can be None)
1002 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1003 # mark the net create task as type data
1005 tasks_by_target_record_id
,
1011 tasks_by_target_record_id
[net_text
]["extra_dict"]["params"][
1015 net_item
["use"] = "data"
1016 net_item
["model"] = interface
["type"]
1017 net_item
["type"] = interface
["type"]
1019 interface
.get("type") == "OM-MGMT"
1020 or interface
.get("mgmt-interface")
1021 or interface
.get("mgmt-vnf")
1023 net_item
["use"] = "mgmt"
1025 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1026 net_item
["use"] = "bridge"
1027 net_item
["model"] = interface
.get("type")
1029 if interface
.get("ip-address"):
1030 net_item
["ip_address"] = interface
["ip-address"]
1032 if interface
.get("mac-address"):
1033 net_item
["mac_address"] = interface
["mac-address"]
1035 net_list
.append(net_item
)
1037 if interface
.get("mgmt-vnf"):
1038 extra_dict
["mgmt_vnf_interface"] = iface_index
1039 elif interface
.get("mgmt-interface"):
1040 extra_dict
["mgmt_vdu_interface"] = iface_index
1045 if target_vdu
.get("cloud-init"):
1046 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1047 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1050 location
=target_vdu
["cloud-init"],
1053 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1054 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1055 cloud_init_content
=cloud_content_
,
1056 params
=target_vdu
.get("additionalParams"),
1057 context
=target_vdu
["cloud-init"],
1060 if target_vdu
.get("boot-data-drive"):
1061 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1065 if target_vdu
.get("ssh-keys"):
1066 ssh_keys
+= target_vdu
.get("ssh-keys")
1068 if target_vdu
.get("ssh-access-required"):
1069 ssh_keys
.append(ro_nsr_public_key
)
1072 cloud_config
["key-pairs"] = ssh_keys
1074 persistent_root_disk
= {}
1076 vnfd_id
= vnfr
["vnfd-id"]
1077 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
1078 for vdu
in vnfd
.get("vdu", ()):
1079 if vdu
["name"] == target_vdu
["vdu-name"]:
1080 for vsd
in vnfd
.get("virtual-storage-desc", ()):
1081 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
1085 ) == "persistent-storage:persistent-storage" and root_disk
.get(
1088 persistent_root_disk
[vsd
["id"]] = {
1089 "image_id": vdu
.get("sw-image-desc"),
1090 "size": root_disk
["size-of-storage"],
1092 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1094 if target_vdu
.get("virtual-storages"):
1095 for disk
in target_vdu
["virtual-storages"]:
1097 disk
.get("type-of-storage")
1098 == "persistent-storage:persistent-storage"
1099 and disk
["id"] not in persistent_root_disk
.keys()
1101 disk_list
.append({"size": disk
["size-of-storage"]})
1103 affinity_group_list
= []
1105 if target_vdu
.get("affinity-or-anti-affinity-group-id"):
1107 for affinity_group_id
in target_vdu
["affinity-or-anti-affinity-group-id"]:
1108 affinity_group_text
= (
1109 ns_preffix
+ ":affinity-or-anti-affinity-group." + affinity_group_id
1112 extra_dict
["depends_on"].append(affinity_group_text
)
1113 affinity_group
["affinity_group_id"] = "TASK-" + affinity_group_text
1114 affinity_group_list
.append(affinity_group
)
1116 extra_dict
["params"] = {
1117 "name": "{}-{}-{}-{}".format(
1118 indata
["name"][:16],
1119 vnfr
["member-vnf-index-ref"][:16],
1120 target_vdu
["vdu-name"][:32],
1121 target_vdu
.get("count-index") or 0,
1123 "description": target_vdu
["vdu-name"],
1125 "image_id": "TASK-" + image_text
,
1126 "flavor_id": "TASK-" + flavor_text
,
1127 "affinity_group_list": affinity_group_list
,
1128 "net_list": net_list
,
1129 "cloud_config": cloud_config
or None,
1130 "disk_list": disk_list
,
1131 "availability_zone_index": None, # TODO
1132 "availability_zone_list": None, # TODO
1138 def _process_affinity_group_params(
1139 target_affinity_group
: Dict
[str, Any
],
1140 indata
: Dict
[str, Any
],
1141 vim_info
: Dict
[str, Any
],
1142 target_record_id
: str,
1143 **kwargs
: Dict
[str, Any
],
1144 ) -> Dict
[str, Any
]:
1145 """Get affinity or anti-affinity group parameters.
1148 target_affinity_group (Dict[str, Any]): [description]
1149 indata (Dict[str, Any]): [description]
1150 vim_info (Dict[str, Any]): [description]
1151 target_record_id (str): [description]
1154 Dict[str, Any]: [description]
1158 affinity_group_data
= {
1159 "name": target_affinity_group
["name"],
1160 "type": target_affinity_group
["type"],
1161 "scope": target_affinity_group
["scope"],
1164 if target_affinity_group
.get("vim-affinity-group-id"):
1165 affinity_group_data
["vim-affinity-group-id"] = target_affinity_group
[
1166 "vim-affinity-group-id"
1169 extra_dict
["params"] = {
1170 "affinity_group_data": affinity_group_data
,
1176 def _process_recreate_vdu_params(
1177 existing_vdu
: Dict
[str, Any
],
1178 db_nsr
: Dict
[str, Any
],
1179 vim_info
: Dict
[str, Any
],
1180 target_record_id
: str,
1182 **kwargs
: Dict
[str, Any
],
1183 ) -> Dict
[str, Any
]:
1184 """Function to process VDU parameters to recreate.
1187 existing_vdu (Dict[str, Any]): [description]
1188 db_nsr (Dict[str, Any]): [description]
1189 vim_info (Dict[str, Any]): [description]
1190 target_record_id (str): [description]
1191 target_id (str): [description]
1194 Dict[str, Any]: [description]
1196 vnfr
= kwargs
.get("vnfr")
1197 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1198 # logger = kwargs.get("logger")
1199 db
= kwargs
.get("db")
1200 fs
= kwargs
.get("fs")
1201 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1207 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
1208 if vim_details_text
:
1209 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
1211 for iface_index
, interface
in enumerate(existing_vdu
["interfaces"]):
1213 if "port-security-enabled" in interface
:
1214 interface
["port_security"] = interface
.pop("port-security-enabled")
1216 if "port-security-disable-strategy" in interface
:
1217 interface
["port_security_disable_strategy"] = interface
.pop(
1218 "port-security-disable-strategy"
1223 for x
, v
in interface
.items()
1229 "port_security_disable_strategy",
1233 existing_ifaces
= existing_vdu
["vim_info"][target_id
].get(
1234 "interfaces_backup", []
1239 for i
in existing_ifaces
1240 if i
["ip_address"] == interface
["ip-address"]
1245 net_item
["net_id"] = net_id
1246 net_item
["type"] = "virtual"
1248 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1249 # TODO floating_ip: True/False (or it can be None)
1250 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1251 net_item
["use"] = "data"
1252 net_item
["model"] = interface
["type"]
1253 net_item
["type"] = interface
["type"]
1255 interface
.get("type") == "OM-MGMT"
1256 or interface
.get("mgmt-interface")
1257 or interface
.get("mgmt-vnf")
1259 net_item
["use"] = "mgmt"
1261 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1262 net_item
["use"] = "bridge"
1263 net_item
["model"] = interface
.get("type")
1265 if interface
.get("ip-address"):
1266 net_item
["ip_address"] = interface
["ip-address"]
1268 if interface
.get("mac-address"):
1269 net_item
["mac_address"] = interface
["mac-address"]
1271 net_list
.append(net_item
)
1273 if interface
.get("mgmt-vnf"):
1274 extra_dict
["mgmt_vnf_interface"] = iface_index
1275 elif interface
.get("mgmt-interface"):
1276 extra_dict
["mgmt_vdu_interface"] = iface_index
1281 if existing_vdu
.get("cloud-init"):
1282 if existing_vdu
["cloud-init"] not in vdu2cloud_init
:
1283 vdu2cloud_init
[existing_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1286 location
=existing_vdu
["cloud-init"],
1289 cloud_content_
= vdu2cloud_init
[existing_vdu
["cloud-init"]]
1290 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1291 cloud_init_content
=cloud_content_
,
1292 params
=existing_vdu
.get("additionalParams"),
1293 context
=existing_vdu
["cloud-init"],
1296 if existing_vdu
.get("boot-data-drive"):
1297 cloud_config
["boot-data-drive"] = existing_vdu
.get("boot-data-drive")
1301 if existing_vdu
.get("ssh-keys"):
1302 ssh_keys
+= existing_vdu
.get("ssh-keys")
1304 if existing_vdu
.get("ssh-access-required"):
1305 ssh_keys
.append(ro_nsr_public_key
)
1308 cloud_config
["key-pairs"] = ssh_keys
1311 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
1312 disk_list
.append({"vim_id": vol_id
["id"]})
1314 affinity_group_list
= []
1316 if existing_vdu
.get("affinity-or-anti-affinity-group-id"):
1318 for affinity_group_id
in existing_vdu
["affinity-or-anti-affinity-group-id"]:
1319 for group
in db_nsr
.get("affinity-or-anti-affinity-group"):
1321 group
["id"] == affinity_group_id
1322 and group
["vim_info"][target_id
].get("vim_id", None) is not None
1324 affinity_group
["affinity_group_id"] = group
["vim_info"][
1326 ].get("vim_id", None)
1327 affinity_group_list
.append(affinity_group
)
1329 extra_dict
["params"] = {
1330 "name": "{}-{}-{}-{}".format(
1331 db_nsr
["name"][:16],
1332 vnfr
["member-vnf-index-ref"][:16],
1333 existing_vdu
["vdu-name"][:32],
1334 existing_vdu
.get("count-index") or 0,
1336 "description": existing_vdu
["vdu-name"],
1338 "image_id": vim_details
["image"]["id"],
1339 "flavor_id": vim_details
["flavor"]["id"],
1340 "affinity_group_list": affinity_group_list
,
1341 "net_list": net_list
,
1342 "cloud_config": cloud_config
or None,
1343 "disk_list": disk_list
,
1344 "availability_zone_index": None, # TODO
1345 "availability_zone_list": None, # TODO
1350 def calculate_diff_items(
1357 tasks_by_target_record_id
,
1364 """Function that returns the incremental changes (creation, deletion)
1365 related to a specific item `item` to be done. This function should be
1366 called for NS instantiation, NS termination, NS update to add a new VNF
1367 or a new VLD, remove a VNF or VLD, etc.
1368 Item can be `net`, `flavor`, `image` or `vdu`.
1369 It takes a list of target items from indata (which came from the REST API)
1370 and compares with the existing items from db_ro_nsr, identifying the
1371 incremental changes to be done. During the comparison, it calls the method
1372 `process_params` (which was passed as parameter, and is particular for each
1376 indata (Dict[str, Any]): deployment info
1377 db_nsr: NSR record from DB
1378 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1379 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1380 item (str): element to process (net, vdu...)
1381 tasks_by_target_record_id (Dict[str, Any]):
1382 [<target_record_id>, <task>]
1383 action_id (str): action id
1384 nsr_id (str): NSR id
1385 task_index (number): task index to add to task name
1386 vnfr_id (str): VNFR id
1387 vnfr (Dict[str, Any]): VNFR info
1390 List: list with the incremental changes (deletes, creates) for each item
1391 number: current task index
1399 process_params
= None
1400 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1401 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1403 # According to the type of item, the path, the target_list,
1404 # the existing_list and the method to process params are set
1405 db_path
= self
.db_path_map
[item
]
1406 process_params
= self
.process_params_function_map
[item
]
1407 if item
in ("net", "vdu"):
1408 # This case is specific for the NS VLD (not applied to VDU)
1410 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1411 target_list
= indata
.get("ns", []).get(db_path
, [])
1412 existing_list
= db_nsr
.get(db_path
, [])
1413 # This case is common for VNF VLDs and VNF VDUs
1415 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
1417 (vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
),
1420 target_list
= target_vnf
.get(db_path
, []) if target_vnf
else []
1421 existing_list
= vnfr
.get(db_path
, [])
1422 elif item
in ("image", "flavor", "affinity-or-anti-affinity-group"):
1423 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1424 target_list
= indata
.get(item
, [])
1425 existing_list
= db_nsr
.get(item
, [])
1427 raise NsException("Item not supported: {}", item
)
1429 # ensure all the target_list elements has an "id". If not assign the index as id
1430 if target_list
is None:
1432 for target_index
, tl
in enumerate(target_list
):
1433 if tl
and not tl
.get("id"):
1434 tl
["id"] = str(target_index
)
1436 # step 1 items (networks,vdus,...) to be deleted/updated
1437 for item_index
, existing_item
in enumerate(existing_list
):
1439 (t
for t
in target_list
if t
["id"] == existing_item
["id"]),
1443 for target_vim
, existing_viminfo
in existing_item
.get(
1446 if existing_viminfo
is None:
1450 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
1452 target_viminfo
= None
1454 if target_viminfo
is None:
1456 self
._assign
_vim
(target_vim
)
1457 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
1460 if target_vim
.startswith("sdn"):
1461 # item must be sdn-net instead of net if target_vim is a sdn
1463 target_record_id
+= ".sdn"
1466 "action_id": action_id
,
1468 "task_index": task_index
,
1473 "deployment_info": deployment_info
,
1474 "target_id": target_vim
,
1477 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1478 "target_record_id": target_record_id
,
1483 # step 2 items (networks,vdus,...) to be created
1484 for target_item
in target_list
:
1487 for item_index
, existing_item
in enumerate(existing_list
):
1488 if existing_item
["id"] == target_item
["id"]:
1492 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1493 existing_list
.append(target_item
)
1494 existing_item
= None
1496 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
1497 existing_viminfo
= None
1500 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
1502 if existing_viminfo
is not None:
1505 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
1508 if target_vim
.startswith("sdn"):
1509 # item must be sdn-net instead of net if target_vim is a sdn
1511 target_record_id
+= ".sdn"
1514 self
.logger
.warning(
1515 "ns.calculate_diff_items target_item={}".format(target_item
)
1517 if process_params
== Ns
._process
_vdu
_params
:
1518 self
.logger
.warning(
1519 "calculate_diff_items self.fs={}".format(self
.fs
)
1526 "vdu2cloud_init": vdu2cloud_init
,
1527 "tasks_by_target_record_id": tasks_by_target_record_id
,
1528 "logger": self
.logger
,
1531 "ro_nsr_public_key": ro_nsr_public_key
,
1534 self
.logger
.warning("calculate_diff_items kwargs={}".format(kwargs
))
1536 extra_dict
= process_params(
1543 self
._assign
_vim
(target_vim
)
1546 "action_id": action_id
,
1548 "task_index": task_index
,
1552 "deployment_info": deployment_info
,
1553 "target_id": target_vim
,
1556 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1557 "target_record_id": target_record_id
,
1558 "extra_dict": extra_dict
,
1559 "common_id": target_item
.get("common_id", None),
1561 diff_items
.append(new_item
)
1562 tasks_by_target_record_id
[target_record_id
] = new_item
1565 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1567 return diff_items
, task_index
1569 def calculate_all_differences_to_deploy(
1579 tasks_by_target_record_id
,
1581 """This method calculates the ordered list of items (`changes_list`)
1582 to be created and deleted.
1585 indata (Dict[str, Any]): deployment info
1586 nsr_id (str): NSR id
1587 db_nsr: NSR record from DB
1588 db_vnfrs: VNFRS record from DB
1589 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1590 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1591 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
1592 action_id (str): action id
1593 tasks_by_target_record_id (Dict[str, Any]):
1594 [<target_record_id>, <task>]
1597 List: ordered list of items to be created and deleted.
1601 # set list with diffs:
1604 # NS vld, image and flavor
1605 for item
in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
1606 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
1607 diff_items
, task_index
= self
.calculate_diff_items(
1610 db_ro_nsr
=db_ro_nsr
,
1611 db_nsr_update
=db_nsr_update
,
1613 tasks_by_target_record_id
=tasks_by_target_record_id
,
1614 action_id
=action_id
,
1616 task_index
=task_index
,
1619 changes_list
+= diff_items
1622 for vnfr_id
, vnfr
in db_vnfrs
.items():
1623 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1624 for item
in ["net", "vdu"]:
1625 self
.logger
.debug("process VNF={} {}".format(vnfr_id
, item
))
1626 diff_items
, task_index
= self
.calculate_diff_items(
1629 db_ro_nsr
=db_ro_nsr
,
1630 db_nsr_update
=db_vnfrs_update
[vnfr
["_id"]],
1632 tasks_by_target_record_id
=tasks_by_target_record_id
,
1633 action_id
=action_id
,
1635 task_index
=task_index
,
1639 changes_list
+= diff_items
1643 def define_all_tasks(
1647 tasks_by_target_record_id
,
1649 """Function to create all the task structures obtanied from
1650 the method calculate_all_differences_to_deploy
1653 changes_list (List): ordered list of items to be created or deleted
1654 db_new_tasks (List): tasks list to be created
1655 action_id (str): action id
1656 tasks_by_target_record_id (Dict[str, Any]):
1657 [<target_record_id>, <task>]
1661 for change
in changes_list
:
1662 task
= Ns
._create
_task
(
1663 deployment_info
=change
["deployment_info"],
1664 target_id
=change
["target_id"],
1665 item
=change
["item"],
1666 action
=change
["action"],
1667 target_record
=change
["target_record"],
1668 target_record_id
=change
["target_record_id"],
1669 extra_dict
=change
.get("extra_dict", None),
1672 self
.logger
.warning("ns.define_all_tasks task={}".format(task
))
1673 tasks_by_target_record_id
[change
["target_record_id"]] = task
1674 db_new_tasks
.append(task
)
1676 if change
.get("common_id"):
1677 task
["common_id"] = change
["common_id"]
1679 def upload_all_tasks(
1684 """Function to save all tasks in the common DB
1687 db_new_tasks (List): tasks list to be created
1688 now (time): current time
1692 nb_ro_tasks
= 0 # for logging
1694 for db_task
in db_new_tasks
:
1695 target_id
= db_task
.pop("target_id")
1696 common_id
= db_task
.get("common_id")
1698 # Do not chek tasks with vim_status DELETED
1699 # because in manual heealing there are two tasks for the same vdur:
1700 # one with vim_status deleted and the other one with the actual VM status.
1706 "target_id": target_id
,
1707 "tasks.common_id": common_id
,
1708 "vim_info.vim_status.ne": "DELETED",
1710 update_dict
={"to_check_at": now
, "modified_at": now
},
1711 push
={"tasks": db_task
},
1712 fail_on_empty
=False,
1716 if not self
.db
.set_one(
1719 "target_id": target_id
,
1720 "tasks.target_record": db_task
["target_record"],
1721 "vim_info.vim_status.ne": "DELETED",
1723 update_dict
={"to_check_at": now
, "modified_at": now
},
1724 push
={"tasks": db_task
},
1725 fail_on_empty
=False,
1728 self
.logger
.debug("Updating database, Creating ro_tasks")
1729 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
1731 self
.db
.create("ro_tasks", db_ro_task
)
1734 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1735 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
1739 def upload_recreate_tasks(
1744 """Function to save recreate tasks in the common DB
1747 db_new_tasks (List): tasks list to be created
1748 now (time): current time
1752 nb_ro_tasks
= 0 # for logging
1754 for db_task
in db_new_tasks
:
1755 target_id
= db_task
.pop("target_id")
1756 self
.logger
.warning("target_id={} db_task={}".format(target_id
, db_task
))
1758 action
= db_task
.get("action", None)
1761 self
.logger
.debug("Updating database, Creating ro_tasks")
1762 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
1764 # If DELETE task: the associated created items should be removed
1765 # (except persistent volumes):
1766 if action
== "DELETE":
1767 db_ro_task
["vim_info"]["created"] = True
1768 db_ro_task
["vim_info"]["created_items"] = db_task
.get(
1771 db_ro_task
["vim_info"]["volumes_to_hold"] = db_task
.get(
1772 "volumes_to_hold", []
1774 db_ro_task
["vim_info"]["vim_id"] = db_task
.get("vim_id", None)
1777 self
.logger
.warning("upload_all_tasks db_ro_task={}".format(db_ro_task
))
1778 self
.db
.create("ro_tasks", db_ro_task
)
1781 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1782 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
1786 def _prepare_created_items_for_healing(
1792 # Get created_items from ro_task
1793 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
1794 for ro_task
in ro_tasks
:
1795 for task
in ro_task
["tasks"]:
1797 task
["target_record"] == target_record
1798 and task
["action"] == "CREATE"
1799 and ro_task
["vim_info"]["created_items"]
1801 created_items
= ro_task
["vim_info"]["created_items"]
1804 return created_items
1806 def _prepare_persistent_volumes_for_healing(
1811 # The associated volumes of the VM shouldn't be removed
1814 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
1815 if vim_details_text
:
1816 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
1818 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
1819 volumes_list
.append(vol_id
["id"])
1823 def prepare_changes_to_recreate(
1831 tasks_by_target_record_id
,
1833 """This method will obtain an ordered list of items (`changes_list`)
1834 to be created and deleted to meet the recreate request.
1838 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id
, indata
)
1842 # set list with diffs:
1844 db_path
= self
.db_path_map
["vdu"]
1845 target_list
= indata
.get("healVnfData", {})
1846 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1847 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1849 # Check each VNF of the target
1850 for target_vnf
in target_list
:
1851 # Find this VNF in the list from DB
1852 vnfr_id
= target_vnf
.get("vnfInstanceId", None)
1854 existing_vnf
= db_vnfrs
.get(vnfr_id
)
1855 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
1856 # vim_account_id = existing_vnf.get("vim-account-id", "")
1858 # Check each VDU of this VNF
1859 for target_vdu
in target_vnf
["additionalParams"].get("vdu", None):
1860 vdu_name
= target_vdu
.get("vdu-id", None)
1861 # For multi instance VDU count-index is mandatory
1862 # For single session VDU count-indes is 0
1863 count_index
= target_vdu
.get("count-index", 0)
1865 existing_instance
= None
1866 for instance
in existing_vnf
.get("vdur", None):
1868 instance
["vdu-name"] == vdu_name
1869 and instance
["count-index"] == count_index
1871 existing_instance
= instance
1876 target_record_id
= "{}.{}".format(db_record
, existing_instance
["id"])
1878 # The target VIM is the one already existing in DB to recreate
1879 for target_vim
, target_viminfo
in existing_instance
.get(
1882 # step 1 vdu to be deleted
1883 self
._assign
_vim
(target_vim
)
1885 "action_id": action_id
,
1887 "task_index": task_index
,
1890 target_record
= f
"{db_record}.{item_index}.vim_info.{target_vim}"
1891 created_items
= self
._prepare
_created
_items
_for
_healing
(
1892 nsr_id
, target_record
1895 volumes_to_hold
= self
._prepare
_persistent
_volumes
_for
_healing
(
1896 target_vim
, existing_instance
1899 # Specific extra params for recreate tasks:
1901 "created_items": created_items
,
1902 "vim_id": existing_instance
["vim-id"],
1903 "volumes_to_hold": volumes_to_hold
,
1906 changes_list
.append(
1908 "deployment_info": deployment_info
,
1909 "target_id": target_vim
,
1912 "target_record": target_record
,
1913 "target_record_id": target_record_id
,
1914 "extra_dict": extra_dict
,
1917 delete_task_id
= f
"{action_id}:{task_index}"
1920 # step 2 vdu to be created
1926 "vnfr": existing_vnf
,
1927 "vdu2cloud_init": vdu2cloud_init
,
1928 "tasks_by_target_record_id": tasks_by_target_record_id
,
1929 "logger": self
.logger
,
1932 "ro_nsr_public_key": ro_nsr_public_key
,
1936 extra_dict
= self
._process
_recreate
_vdu
_params
(
1945 # The CREATE task depens on the DELETE task
1946 extra_dict
["depends_on"] = [delete_task_id
]
1948 # Add volumes created from created_items if any
1949 # Ports should be deleted with delete task and automatically created with create task
1951 for k
, v
in created_items
.items():
1953 k_item
, _
, k_id
= k
.partition(":")
1954 if k_item
== "volume":
1956 except Exception as e
:
1958 "Error evaluating created item {}: {}".format(k
, e
)
1960 extra_dict
["previous_created_volumes"] = volumes
1963 "action_id": action_id
,
1965 "task_index": task_index
,
1967 self
._assign
_vim
(target_vim
)
1970 "deployment_info": deployment_info
,
1971 "target_id": target_vim
,
1974 "target_record": target_record
,
1975 "target_record_id": target_record_id
,
1976 "extra_dict": extra_dict
,
1978 changes_list
.append(new_item
)
1979 tasks_by_target_record_id
[target_record_id
] = new_item
1984 def recreate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
1985 self
.logger
.debug("ns.recreate nsr_id={} indata={}".format(nsr_id
, indata
))
1986 # TODO: validate_input(indata, recreate_schema)
1987 action_id
= indata
.get("action_id", str(uuid4()))
1988 # get current deployment
1989 db_vnfrs
= {} # vnf's info indexed by _id
1991 logging_text
= "Recreate nsr_id={} action_id={} indata={}".format(
1992 nsr_id
, action_id
, indata
1994 self
.logger
.debug(logging_text
+ "Enter")
1997 step
= "Getting ns and vnfr record from db"
1998 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2000 tasks_by_target_record_id
= {}
2001 # read from db: vnf's of this ns
2002 step
= "Getting vnfrs from db"
2003 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2004 self
.logger
.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list
))
2006 if not db_vnfrs_list
:
2007 raise NsException("Cannot obtain associated VNF for ns")
2009 for vnfr
in db_vnfrs_list
:
2010 db_vnfrs
[vnfr
["_id"]] = vnfr
2013 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2014 self
.logger
.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr
))
2017 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2019 with self
.write_lock
:
2021 step
= "process NS elements"
2022 changes_list
= self
.prepare_changes_to_recreate(
2027 db_ro_nsr
=db_ro_nsr
,
2028 action_id
=action_id
,
2029 tasks_by_target_record_id
=tasks_by_target_record_id
,
2032 self
.define_all_tasks(
2033 changes_list
=changes_list
,
2034 db_new_tasks
=db_new_tasks
,
2035 tasks_by_target_record_id
=tasks_by_target_record_id
,
2038 # Delete all ro_tasks registered for the targets vdurs (target_record)
2039 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2040 # So remove all task related to target record.
2041 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2042 for change
in changes_list
:
2043 for ro_task
in ro_tasks
:
2044 for task
in ro_task
["tasks"]:
2045 if task
["target_record"] == change
["target_record"]:
2049 "_id": ro_task
["_id"],
2050 "modified_at": ro_task
["modified_at"],
2052 fail_on_empty
=False,
2055 step
= "Updating database, Appending tasks to ro_tasks"
2056 self
.upload_recreate_tasks(
2057 db_new_tasks
=db_new_tasks
,
2062 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2066 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2070 except Exception as e
:
2071 if isinstance(e
, (DbException
, NsException
)):
2073 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2076 e
= traceback_format_exc()
2077 self
.logger
.critical(
2078 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2082 raise NsException(e
)
2084 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2085 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
2086 validate_input(indata
, deploy_schema
)
2087 action_id
= indata
.get("action_id", str(uuid4()))
2089 # get current deployment
2090 db_nsr_update
= {} # update operation on nsrs
2091 db_vnfrs_update
= {}
2092 db_vnfrs
= {} # vnf's info indexed by _id
2094 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2095 self
.logger
.debug(logging_text
+ "Enter")
2098 step
= "Getting ns and vnfr record from db"
2099 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2100 self
.logger
.debug("ns.deploy: db_nsr={}".format(db_nsr
))
2102 tasks_by_target_record_id
= {}
2103 # read from db: vnf's of this ns
2104 step
= "Getting vnfrs from db"
2105 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2107 if not db_vnfrs_list
:
2108 raise NsException("Cannot obtain associated VNF for ns")
2110 for vnfr
in db_vnfrs_list
:
2111 db_vnfrs
[vnfr
["_id"]] = vnfr
2112 db_vnfrs_update
[vnfr
["_id"]] = {}
2113 self
.logger
.debug("ns.deploy db_vnfrs={}".format(db_vnfrs
))
2116 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2119 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2121 # check that action_id is not in the list of actions. Suffixed with :index
2122 if action_id
in db_ro_nsr
["actions"]:
2126 new_action_id
= "{}:{}".format(action_id
, index
)
2128 if new_action_id
not in db_ro_nsr
["actions"]:
2129 action_id
= new_action_id
2132 + "Changing action_id in use to {}".format(action_id
)
2138 def _process_action(indata
):
2139 nonlocal db_new_tasks
2146 if indata
["action"]["action"] == "inject_ssh_key":
2147 key
= indata
["action"].get("key")
2148 user
= indata
["action"].get("user")
2149 password
= indata
["action"].get("password")
2151 for vnf
in indata
.get("vnf", ()):
2152 if vnf
["_id"] not in db_vnfrs
:
2153 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
2155 db_vnfr
= db_vnfrs
[vnf
["_id"]]
2157 for target_vdu
in vnf
.get("vdur", ()):
2158 vdu_index
, vdur
= next(
2161 for i_v
in enumerate(db_vnfr
["vdur"])
2162 if i_v
[1]["id"] == target_vdu
["id"]
2169 "Invalid vdu vnf={}.{}".format(
2170 vnf
["_id"], target_vdu
["id"]
2174 target_vim
, vim_info
= next(
2175 k_v
for k_v
in vdur
["vim_info"].items()
2177 self
._assign
_vim
(target_vim
)
2178 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
2179 vnf
["_id"], vdu_index
2183 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
2186 "ip_address": vdur
.get("ip-address"),
2189 "password": password
,
2190 "private_key": db_ro_nsr
["private_key"],
2191 "salt": db_ro_nsr
["_id"],
2192 "schema_version": db_ro_nsr
["_admin"][
2199 "action_id": action_id
,
2201 "task_index": task_index
,
2204 task
= Ns
._create
_task
(
2205 deployment_info
=deployment_info
,
2206 target_id
=target_vim
,
2209 target_record
=target_record
,
2210 target_record_id
=None,
2211 extra_dict
=extra_dict
,
2214 task_index
= deployment_info
.get("task_index")
2216 db_new_tasks
.append(task
)
2218 with self
.write_lock
:
2219 if indata
.get("action"):
2220 _process_action(indata
)
2222 # compute network differences
2224 step
= "process NS elements"
2225 changes_list
= self
.calculate_all_differences_to_deploy(
2230 db_ro_nsr
=db_ro_nsr
,
2231 db_nsr_update
=db_nsr_update
,
2232 db_vnfrs_update
=db_vnfrs_update
,
2233 action_id
=action_id
,
2234 tasks_by_target_record_id
=tasks_by_target_record_id
,
2236 self
.define_all_tasks(
2237 changes_list
=changes_list
,
2238 db_new_tasks
=db_new_tasks
,
2239 tasks_by_target_record_id
=tasks_by_target_record_id
,
2242 step
= "Updating database, Appending tasks to ro_tasks"
2243 self
.upload_all_tasks(
2244 db_new_tasks
=db_new_tasks
,
2248 step
= "Updating database, nsrs"
2250 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
2252 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
2254 step
= "Updating database, vnfrs={}".format(vnfr_id
)
2255 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
2258 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2262 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2266 except Exception as e
:
2267 if isinstance(e
, (DbException
, NsException
)):
2269 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2272 e
= traceback_format_exc()
2273 self
.logger
.critical(
2274 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2278 raise NsException(e
)
2280 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2281 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
2282 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2284 with self
.write_lock
:
2286 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
2287 except NsWorkerException
as e
:
2288 raise NsException(e
)
2290 return None, None, True
2292 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2294 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2295 version
, nsr_id
, action_id
, indata
2301 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
2302 global_status
= "DONE"
2305 for ro_task
in ro_tasks
:
2306 for task
in ro_task
["tasks"]:
2307 if task
and task
["action_id"] == action_id
:
2308 task_list
.append(task
)
2311 if task
["status"] == "FAILED":
2312 global_status
= "FAILED"
2313 error_text
= "Error at {} {}: {}".format(
2314 task
["action"].lower(),
2316 ro_task
["vim_info"].get("vim_message") or "unknown",
2318 details
.append(error_text
)
2319 elif task
["status"] in ("SCHEDULED", "BUILD"):
2320 if global_status
!= "FAILED":
2321 global_status
= "BUILD"
2326 "status": global_status
,
2327 "details": ". ".join(details
)
2329 else "progress {}/{}".format(done
, total
),
2331 "action_id": action_id
,
2335 return return_data
, None, True
2337 def recreate_status(
2338 self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
2340 return self
.status(session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
)
2342 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2344 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2345 session
, indata
, version
, nsr_id
, action_id
2349 return None, None, True
2351 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2352 nsrs
= self
.db
.get_list("nsrs", {})
2356 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
2358 return return_data
, None, True
2360 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2361 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2364 for ro_task
in ro_tasks
:
2365 for task
in ro_task
["tasks"]:
2366 if task
["action_id"] not in return_data
:
2367 return_data
.append(task
["action_id"])
2369 return return_data
, None, True
2372 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
2374 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
2375 self
._assign
_vim
(target_vim
)
2376 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
2377 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
2379 "action_id": action_id
,
2381 "task_index": task_index
,
2384 task
= Ns
._create
_task
(
2385 deployment_info
=deployment_info
,
2386 target_id
=target_vim
,
2389 target_record
=target_record
,
2390 target_record_id
=target_record_id
,
2391 extra_dict
=extra_dict
,
2396 def migrate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2400 action_id
= indata
.get("action_id", str(uuid4()))
2402 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2403 self
.logger
.debug(logging_text
+ "Enter")
2405 vnf_instance_id
= indata
["vnfInstanceId"]
2406 step
= "Getting vnfrs from db"
2407 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
2408 vdu
= indata
.get("vdu")
2409 migrateToHost
= indata
.get("migrateToHost")
2412 with self
.write_lock
:
2414 vdu_id
= indata
["vdu"]["vduId"]
2415 vdu_count_index
= indata
["vdu"].get("vduCountIndex", 0)
2416 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2418 vdu
["vdu-id-ref"] == vdu_id
2419 and vdu
["count-index"] == vdu_count_index
2421 extra_dict
["params"] = {
2422 "vim_vm_id": vdu
["vim-id"],
2423 "migrate_host": migrateToHost
,
2424 "vdu_vim_info": vdu
["vim_info"],
2426 step
= "Creating migration task for vdu:{}".format(vdu
)
2427 task
= self
.migrate_task(
2436 db_new_tasks
.append(task
)
2441 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2442 extra_dict
["params"] = {
2443 "vim_vm_id": vdu
["vim-id"],
2444 "migrate_host": migrateToHost
,
2445 "vdu_vim_info": vdu
["vim_info"],
2447 step
= "Creating migration task for vdu:{}".format(vdu
)
2448 task
= self
.migrate_task(
2457 db_new_tasks
.append(task
)
2460 self
.upload_all_tasks(
2461 db_new_tasks
=db_new_tasks
,
2466 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2469 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2473 except Exception as e
:
2474 if isinstance(e
, (DbException
, NsException
)):
2476 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2479 e
= traceback_format_exc()
2480 self
.logger
.critical(
2481 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2484 raise NsException(e
)