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
20 from itertools
import product
22 from random
import choice
as random_choice
23 from threading
import Lock
25 from traceback
import format_exc
as traceback_format_exc
26 from typing
import Any
, Dict
, Tuple
, Type
27 from uuid
import uuid4
29 from cryptography
.hazmat
.backends
import default_backend
as crypto_default_backend
30 from cryptography
.hazmat
.primitives
import serialization
as crypto_serialization
31 from cryptography
.hazmat
.primitives
.asymmetric
import rsa
39 from osm_common
import (
46 version
as common_version
,
48 from osm_common
.dbbase
import DbBase
, DbException
49 from osm_common
.fsbase
import FsBase
, FsException
50 from osm_common
.msgbase
import MsgException
51 from osm_ng_ro
.ns_thread
import deep_get
, NsWorker
, NsWorkerException
52 from osm_ng_ro
.validation
import deploy_schema
, validate_input
55 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
56 min_common_version
= "0.1.16"
59 class NsException(Exception):
60 def __init__(self
, message
, http_code
=HTTPStatus
.BAD_REQUEST
):
61 self
.http_code
= http_code
62 super(Exception, self
).__init
__(message
)
67 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
68 will provide a random one
71 # Try getting docker id. If fails, get pid
73 with
open("/proc/self/cgroup", "r") as f
:
74 text_id_
= f
.readline()
75 _
, _
, text_id
= text_id_
.rpartition("/")
76 text_id
= text_id
.replace("\n", "")[:12]
84 return "".join(random_choice("0123456789abcdef") for _
in range(12))
88 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
91 for point
in v
.split("."):
92 filled
.append(point
.zfill(8))
103 # self.operations = None
105 # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
106 # If done now it will not be linked to parent not getting its handler and level
108 self
.write_lock
= None
109 self
.vims_assigned
= {}
113 self
.process_params_function_map
= {
114 "net": Ns
._process
_net
_params
,
115 "image": Ns
._process
_image
_params
,
116 "flavor": Ns
._process
_flavor
_params
,
117 "vdu": Ns
._process
_vdu
_params
,
118 "affinity-or-anti-affinity-group": Ns
._process
_affinity
_group
_params
,
125 "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group",
128 def init_db(self
, target_version
):
131 def start(self
, config
):
133 Connect to database, filesystem storage, and messaging
134 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
135 :param config: Configuration of db, storage, etc
139 self
.config
["process_id"] = get_process_id() # used for HA identity
140 self
.logger
= logging
.getLogger("ro.ns")
142 # check right version of common
143 if versiontuple(common_version
) < versiontuple(min_common_version
):
145 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
146 common_version
, min_common_version
152 if config
["database"]["driver"] == "mongo":
153 self
.db
= dbmongo
.DbMongo()
154 self
.db
.db_connect(config
["database"])
155 elif config
["database"]["driver"] == "memory":
156 self
.db
= dbmemory
.DbMemory()
157 self
.db
.db_connect(config
["database"])
160 "Invalid configuration param '{}' at '[database]':'driver'".format(
161 config
["database"]["driver"]
166 if config
["storage"]["driver"] == "local":
167 self
.fs
= fslocal
.FsLocal()
168 self
.fs
.fs_connect(config
["storage"])
169 elif config
["storage"]["driver"] == "mongo":
170 self
.fs
= fsmongo
.FsMongo()
171 self
.fs
.fs_connect(config
["storage"])
172 elif config
["storage"]["driver"] is None:
176 "Invalid configuration param '{}' at '[storage]':'driver'".format(
177 config
["storage"]["driver"]
182 if config
["message"]["driver"] == "local":
183 self
.msg
= msglocal
.MsgLocal()
184 self
.msg
.connect(config
["message"])
185 elif config
["message"]["driver"] == "kafka":
186 self
.msg
= msgkafka
.MsgKafka()
187 self
.msg
.connect(config
["message"])
190 "Invalid configuration param '{}' at '[message]':'driver'".format(
191 config
["message"]["driver"]
195 # TODO load workers to deal with exising database tasks
197 self
.write_lock
= Lock()
198 except (DbException
, FsException
, MsgException
) as e
:
199 raise NsException(str(e
), http_code
=e
.http_code
)
201 def get_assigned_vims(self
):
202 return list(self
.vims_assigned
.keys())
207 self
.db
.db_disconnect()
210 self
.fs
.fs_disconnect()
213 self
.msg
.disconnect()
215 self
.write_lock
= None
216 except (DbException
, FsException
, MsgException
) as e
:
217 raise NsException(str(e
), http_code
=e
.http_code
)
219 for worker
in self
.workers
:
220 worker
.insert_task(("terminate",))
222 def _create_worker(self
):
224 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
225 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
226 return the index of the assigned worker thread. Worker threads are storead at self.workers
228 # Look for a thread in idle status
232 for i
in range(len(self
.workers
))
233 if self
.workers
[i
] and self
.workers
[i
].idle
238 if worker_id
is not None:
239 # unset idle status to avoid race conditions
240 self
.workers
[worker_id
].idle
= False
242 worker_id
= len(self
.workers
)
244 if worker_id
< self
.config
["global"]["server.ns_threads"]:
245 # create a new worker
247 NsWorker(worker_id
, self
.config
, self
.plugins
, self
.db
)
249 self
.workers
[worker_id
].start()
251 # reached maximum number of threads, assign VIM to an existing one
252 worker_id
= self
.next_worker
253 self
.next_worker
= (self
.next_worker
+ 1) % self
.config
["global"][
259 def assign_vim(self
, target_id
):
260 with self
.write_lock
:
261 return self
._assign
_vim
(target_id
)
263 def _assign_vim(self
, target_id
):
264 if target_id
not in self
.vims_assigned
:
265 worker_id
= self
.vims_assigned
[target_id
] = self
._create
_worker
()
266 self
.workers
[worker_id
].insert_task(("load_vim", target_id
))
268 def reload_vim(self
, target_id
):
269 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
270 # this is because database VIM information is cached for threads working with SDN
271 with self
.write_lock
:
272 for worker
in self
.workers
:
273 if worker
and not worker
.idle
:
274 worker
.insert_task(("reload_vim", target_id
))
276 def unload_vim(self
, target_id
):
277 with self
.write_lock
:
278 return self
._unload
_vim
(target_id
)
280 def _unload_vim(self
, target_id
):
281 if target_id
in self
.vims_assigned
:
282 worker_id
= self
.vims_assigned
[target_id
]
283 self
.workers
[worker_id
].insert_task(("unload_vim", target_id
))
284 del self
.vims_assigned
[target_id
]
286 def check_vim(self
, target_id
):
287 with self
.write_lock
:
288 if target_id
in self
.vims_assigned
:
289 worker_id
= self
.vims_assigned
[target_id
]
291 worker_id
= self
._create
_worker
()
293 worker
= self
.workers
[worker_id
]
294 worker
.insert_task(("check_vim", target_id
))
296 def unload_unused_vims(self
):
297 with self
.write_lock
:
300 for target_id
in self
.vims_assigned
:
301 if not self
.db
.get_one(
304 "target_id": target_id
,
305 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
309 vims_to_unload
.append(target_id
)
311 for target_id
in vims_to_unload
:
312 self
._unload
_vim
(target_id
)
320 """This method reads cloud init from a file.
322 Note: Not used as cloud init content is provided in the http body.
325 db (Type[DbBase]): [description]
326 fs (Type[FsBase]): [description]
327 location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
330 NsException: [description]
331 NsException: [description]
336 vnfd_id
, _
, other
= location
.partition(":")
337 _type
, _
, name
= other
.partition(":")
338 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
341 base_folder
= vnfd
["_admin"]["storage"]
342 cloud_init_file
= "{}/{}/cloud_init/{}".format(
343 base_folder
["folder"], base_folder
["pkg-dir"], name
348 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
353 with fs
.file_open(cloud_init_file
, "r") as ci_file
:
354 cloud_init_content
= ci_file
.read()
356 cloud_init_content
= vnfd
["vdu"][int(name
)]["cloud-init"]
358 raise NsException("Mismatch descriptor for cloud init: {}".format(location
))
360 return cloud_init_content
364 cloud_init_content
: str,
365 params
: Dict
[str, Any
],
368 """Function that processes the cloud init to replace Jinja2 encoded parameters.
371 cloud_init_content (str): [description]
372 params (Dict[str, Any]): [description]
373 context (str): [description]
376 NsException: [description]
377 NsException: [description]
383 env
= Environment(undefined
=StrictUndefined
)
384 template
= env
.from_string(cloud_init_content
)
386 return template
.render(params
or {})
387 except UndefinedError
as e
:
389 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
390 "inside the 'additionalParamsForVnf' block".format(e
, context
)
392 except (TemplateError
, TemplateNotFound
) as e
:
394 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
399 def _create_db_ro_nsrs(self
, nsr_id
, now
):
401 key
= rsa
.generate_private_key(
402 backend
=crypto_default_backend(), public_exponent
=65537, key_size
=2048
404 private_key
= key
.private_bytes(
405 crypto_serialization
.Encoding
.PEM
,
406 crypto_serialization
.PrivateFormat
.PKCS8
,
407 crypto_serialization
.NoEncryption(),
409 public_key
= key
.public_key().public_bytes(
410 crypto_serialization
.Encoding
.OpenSSH
,
411 crypto_serialization
.PublicFormat
.OpenSSH
,
413 private_key
= private_key
.decode("utf8")
414 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
415 i
= private_key
.find("\n")
416 private_key
= "-----BEGIN RSA PRIVATE KEY-----" + private_key
[i
:]
417 public_key
= public_key
.decode("utf8")
418 except Exception as e
:
419 raise NsException("Cannot create ssh-keys: {}".format(e
))
421 schema_version
= "1.1"
422 private_key_encrypted
= self
.db
.encrypt(
423 private_key
, schema_version
=schema_version
, salt
=nsr_id
430 "schema_version": schema_version
,
432 "public_key": public_key
,
433 "private_key": private_key_encrypted
,
436 self
.db
.create("ro_nsrs", db_content
)
442 deployment_info
: Dict
[str, Any
],
447 target_record_id
: str,
448 extra_dict
: Dict
[str, Any
] = None,
450 """Function to create task dict from deployment information.
453 deployment_info (Dict[str, Any]): [description]
454 target_id (str): [description]
455 item (str): [description]
456 action (str): [description]
457 target_record (str): [description]
458 target_record_id (str): [description]
459 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
462 Dict[str, Any]: [description]
465 "target_id": target_id
, # it will be removed before pushing at database
466 "action_id": deployment_info
.get("action_id"),
467 "nsr_id": deployment_info
.get("nsr_id"),
468 "task_id": f
"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
469 "status": "SCHEDULED",
472 "target_record": target_record
,
473 "target_record_id": target_record_id
,
477 task
.update(extra_dict
) # params, find_params, depends_on
479 deployment_info
["task_index"] = deployment_info
.get("task_index", 0) + 1
486 task
: Dict
[str, Any
],
488 """Function to create an RO task from task information.
491 target_id (str): [description]
492 task (Dict[str, Any]): [description]
495 Dict[str, Any]: [description]
499 _id
= task
.get("task_id")
504 "target_id": target_id
,
507 "created_items": None,
524 def _process_image_params(
525 target_image
: Dict
[str, Any
],
526 indata
: Dict
[str, Any
],
527 vim_info
: Dict
[str, Any
],
528 target_record_id
: str,
529 **kwargs
: Dict
[str, Any
],
531 """Function to process VDU image parameters.
534 target_image (Dict[str, Any]): [description]
535 indata (Dict[str, Any]): [description]
536 vim_info (Dict[str, Any]): [description]
537 target_record_id (str): [description]
540 Dict[str, Any]: [description]
544 if target_image
.get("image"):
545 find_params
["filter_dict"] = {"name": target_image
.get("image")}
547 if target_image
.get("vim_image_id"):
548 find_params
["filter_dict"] = {"id": target_image
.get("vim_image_id")}
550 if target_image
.get("image_checksum"):
551 find_params
["filter_dict"] = {
552 "checksum": target_image
.get("image_checksum")
555 return {"find_params": find_params
}
558 def _get_resource_allocation_params(
559 quota_descriptor
: Dict
[str, Any
],
561 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
565 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
568 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
572 if quota_descriptor
.get("limit"):
573 quota
["limit"] = int(quota_descriptor
["limit"])
575 if quota_descriptor
.get("reserve"):
576 quota
["reserve"] = int(quota_descriptor
["reserve"])
578 if quota_descriptor
.get("shares"):
579 quota
["shares"] = int(quota_descriptor
["shares"])
584 def _process_guest_epa_quota_params(
585 guest_epa_quota
: Dict
[str, Any
],
588 """Function to extract the guest epa quota parameters.
591 guest_epa_quota (Dict[str, Any]): [description]
592 epa_vcpu_set (bool): [description]
595 Dict[str, Any]: [description]
599 if guest_epa_quota
.get("cpu-quota") and not epa_vcpu_set
:
600 cpuquota
= Ns
._get
_resource
_allocation
_params
(
601 guest_epa_quota
.get("cpu-quota")
605 result
["cpu-quota"] = cpuquota
607 if guest_epa_quota
.get("mem-quota"):
608 vduquota
= Ns
._get
_resource
_allocation
_params
(
609 guest_epa_quota
.get("mem-quota")
613 result
["mem-quota"] = vduquota
615 if guest_epa_quota
.get("disk-io-quota"):
616 diskioquota
= Ns
._get
_resource
_allocation
_params
(
617 guest_epa_quota
.get("disk-io-quota")
621 result
["disk-io-quota"] = diskioquota
623 if guest_epa_quota
.get("vif-quota"):
624 vifquota
= Ns
._get
_resource
_allocation
_params
(
625 guest_epa_quota
.get("vif-quota")
629 result
["vif-quota"] = vifquota
634 def _process_guest_epa_numa_params(
635 guest_epa_quota
: Dict
[str, Any
],
636 ) -> Tuple
[Dict
[str, Any
], bool]:
640 guest_epa_quota (Dict[str, Any]): [description]
643 Tuple[Dict[str, Any], bool]: [description]
648 if guest_epa_quota
.get("numa-node-policy"):
649 numa_node_policy
= guest_epa_quota
.get("numa-node-policy")
651 if numa_node_policy
.get("node"):
652 numa_node
= numa_node_policy
["node"][0]
654 if numa_node
.get("num-cores"):
655 numa
["cores"] = numa_node
["num-cores"]
658 paired_threads
= numa_node
.get("paired-threads", {})
659 if paired_threads
.get("num-paired-threads"):
660 numa
["paired-threads"] = int(
661 numa_node
["paired-threads"]["num-paired-threads"]
665 if paired_threads
.get("paired-thread-ids"):
666 numa
["paired-threads-id"] = []
668 for pair
in paired_threads
["paired-thread-ids"]:
669 numa
["paired-threads-id"].append(
671 str(pair
["thread-a"]),
672 str(pair
["thread-b"]),
676 if numa_node
.get("num-threads"):
677 numa
["threads"] = int(numa_node
["num-threads"])
680 if numa_node
.get("memory-mb"):
681 numa
["memory"] = max(int(int(numa_node
["memory-mb"]) / 1024), 1)
683 return numa
, epa_vcpu_set
686 def _process_guest_epa_cpu_pinning_params(
687 guest_epa_quota
: Dict
[str, Any
],
690 ) -> Tuple
[Dict
[str, Any
], bool]:
694 guest_epa_quota (Dict[str, Any]): [description]
695 vcpu_count (int): [description]
696 epa_vcpu_set (bool): [description]
699 Tuple[Dict[str, Any], bool]: [description]
702 local_epa_vcpu_set
= epa_vcpu_set
705 guest_epa_quota
.get("cpu-pinning-policy") == "DEDICATED"
710 if guest_epa_quota
.get("cpu-thread-pinning-policy") != "PREFER"
712 ] = max(vcpu_count
, 1)
713 local_epa_vcpu_set
= True
715 return numa
, local_epa_vcpu_set
718 def _process_epa_params(
719 target_flavor
: Dict
[str, Any
],
724 target_flavor (Dict[str, Any]): [description]
727 Dict[str, Any]: [description]
732 if target_flavor
.get("guest-epa"):
733 guest_epa
= target_flavor
["guest-epa"]
735 numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_numa
_params
(
736 guest_epa_quota
=guest_epa
739 if guest_epa
.get("mempage-size"):
740 extended
["mempage-size"] = guest_epa
.get("mempage-size")
742 tmp_numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_cpu
_pinning
_params
(
743 guest_epa_quota
=guest_epa
,
744 vcpu_count
=int(target_flavor
.get("vcpu-count", 1)),
745 epa_vcpu_set
=epa_vcpu_set
,
747 numa
.update(tmp_numa
)
750 Ns
._process
_guest
_epa
_quota
_params
(
751 guest_epa_quota
=guest_epa
,
752 epa_vcpu_set
=epa_vcpu_set
,
757 extended
["numas"] = [numa
]
762 def _process_flavor_params(
763 target_flavor
: Dict
[str, Any
],
764 indata
: Dict
[str, Any
],
765 vim_info
: Dict
[str, Any
],
766 target_record_id
: str,
767 **kwargs
: Dict
[str, Any
],
772 target_flavor (Dict[str, Any]): [description]
773 indata (Dict[str, Any]): [description]
774 vim_info (Dict[str, Any]): [description]
775 target_record_id (str): [description]
778 Dict[str, Any]: [description]
780 db
= kwargs
.get("db")
784 "disk": int(target_flavor
["storage-gb"]),
785 "ram": int(target_flavor
["memory-mb"]),
786 "vcpus": int(target_flavor
["vcpu-count"]),
789 for vnf
in indata
.get("vnf", []):
790 for vdur
in vnf
.get("vdur", []):
791 if vdur
.get("ns-flavor-id") == target_flavor
.get("id"):
794 if db
and isinstance(indata
.get("vnf"), list):
795 vnfd_id
= indata
.get("vnf")[0].get("vnfd-id")
796 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
797 # check if there is persistent root disk
798 for vdu
in vnfd
.get("vdu", ()):
799 if vdu
["name"] == target_vdur
.get("vdu-name"):
800 for vsd
in vnfd
.get("virtual-storage-desc", ()):
801 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
804 root_disk
.get("type-of-storage")
805 == "persistent-storage:persistent-storage"
807 flavor_data
["disk"] = 0
809 for storage
in target_vdur
.get("virtual-storages", []):
811 storage
.get("type-of-storage")
812 == "etsi-nfv-descriptors:ephemeral-storage"
814 flavor_data
["ephemeral"] = int(storage
.get("size-of-storage", 0))
815 elif storage
.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
816 flavor_data
["swap"] = int(storage
.get("size-of-storage", 0))
818 extended
= Ns
._process
_epa
_params
(target_flavor
)
820 flavor_data
["extended"] = extended
822 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
823 flavor_data_name
= flavor_data
.copy()
824 flavor_data_name
["name"] = target_flavor
["name"]
825 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
830 def _ip_profile_to_ro(
831 ip_profile
: Dict
[str, Any
],
836 ip_profile (Dict[str, Any]): [description]
839 Dict[str, Any]: [description]
846 if "v4" in ip_profile
.get("ip-version", "ipv4")
848 "subnet_address": ip_profile
.get("subnet-address"),
849 "gateway_address": ip_profile
.get("gateway-address"),
850 "dhcp_enabled": ip_profile
.get("dhcp-params", {}).get("enabled", False),
851 "dhcp_start_address": ip_profile
.get("dhcp-params", {}).get(
852 "start-address", None
854 "dhcp_count": ip_profile
.get("dhcp-params", {}).get("count", None),
857 if ip_profile
.get("dns-server"):
858 ro_ip_profile
["dns_address"] = ";".join(
859 [v
["address"] for v
in ip_profile
["dns-server"] if v
.get("address")]
862 if ip_profile
.get("security-group"):
863 ro_ip_profile
["security_group"] = ip_profile
["security-group"]
868 def _process_net_params(
869 target_vld
: Dict
[str, Any
],
870 indata
: Dict
[str, Any
],
871 vim_info
: Dict
[str, Any
],
872 target_record_id
: str,
873 **kwargs
: Dict
[str, Any
],
875 """Function to process network parameters.
878 target_vld (Dict[str, Any]): [description]
879 indata (Dict[str, Any]): [description]
880 vim_info (Dict[str, Any]): [description]
881 target_record_id (str): [description]
884 Dict[str, Any]: [description]
888 if vim_info
.get("sdn"):
889 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
890 # ns_preffix = "nsrs:{}".format(nsr_id)
891 # remove the ending ".sdn
892 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
893 extra_dict
["params"] = {
895 for k
in ("sdn-ports", "target_vim", "vlds", "type")
899 # TODO needed to add target_id in the dependency.
900 if vim_info
.get("target_vim"):
901 extra_dict
["depends_on"] = [
902 f
"{vim_info.get('target_vim')} {vld_target_record_id}"
907 if vim_info
.get("vim_network_name"):
908 extra_dict
["find_params"] = {
910 "name": vim_info
.get("vim_network_name"),
913 elif vim_info
.get("vim_network_id"):
914 extra_dict
["find_params"] = {
916 "id": vim_info
.get("vim_network_id"),
919 elif target_vld
.get("mgmt-network"):
920 extra_dict
["find_params"] = {
922 "name": target_vld
["id"],
926 extra_dict
["params"] = {
928 f
"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
930 "ip_profile": Ns
._ip
_profile
_to
_ro
(vim_info
.get("ip_profile")),
931 "provider_network_profile": vim_info
.get("provider_network"),
934 if not target_vld
.get("underlay"):
935 extra_dict
["params"]["net_type"] = "bridge"
937 extra_dict
["params"]["net_type"] = (
938 "ptp" if target_vld
.get("type") == "ELINE" else "data"
944 def find_persistent_root_volumes(
947 vdu_instantiation_volumes_list
: list,
950 """Find the persistent root volumes and add them to the disk_list
951 by parsing the instantiation parameters
955 target_vdu: processed VDU
956 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
957 disk_list: to be filled up
960 disk_list: filled VDU list which is used for VDU creation
963 persistent_root_disk
= {}
965 for vdu
, vsd
in product(
966 vnfd
.get("vdu", ()), vnfd
.get("virtual-storage-desc", ())
969 vdu
["name"] == target_vdu
["vdu-name"]
970 and vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]
974 root_disk
.get("type-of-storage")
975 == "persistent-storage:persistent-storage"
977 for vdu_volume
in vdu_instantiation_volumes_list
:
980 vdu_volume
["vim-volume-id"]
981 and root_disk
["id"] == vdu_volume
["name"]
984 persistent_root_disk
[vsd
["id"]] = {
985 "vim_volume_id": vdu_volume
["vim-volume-id"],
986 "image_id": vdu
.get("sw-image-desc"),
989 disk_list
.append(persistent_root_disk
[vsd
["id"]])
991 # There can be only one root disk, when we find it, it will return the result
992 return disk_list
, persistent_root_disk
996 if root_disk
.get("size-of-storage"):
997 persistent_root_disk
[vsd
["id"]] = {
998 "image_id": vdu
.get("sw-image-desc"),
999 "size": root_disk
.get("size-of-storage"),
1002 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1003 return disk_list
, persistent_root_disk
1005 return disk_list
, persistent_root_disk
1008 def find_persistent_volumes(
1009 persistent_root_disk
: dict,
1011 vdu_instantiation_volumes_list
: list,
1014 """Find the ordinary persistent volumes and add them to the disk_list
1015 by parsing the instantiation parameters
1018 persistent_root_disk: persistent root disk dictionary
1019 target_vdu: processed VDU
1020 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1021 disk_list: to be filled up
1024 disk_list: filled VDU list which is used for VDU creation
1027 # Find the ordinary volumes which are not added to the persistent_root_disk
1028 persistent_disk
= {}
1029 for disk
in target_vdu
.get("virtual-storages", {}):
1031 disk
.get("type-of-storage") == "persistent-storage:persistent-storage"
1032 and disk
["id"] not in persistent_root_disk
.keys()
1034 for vdu_volume
in vdu_instantiation_volumes_list
:
1036 if vdu_volume
["vim-volume-id"] and disk
["id"] == vdu_volume
["name"]:
1038 persistent_disk
[disk
["id"]] = {
1039 "vim_volume_id": vdu_volume
["vim-volume-id"],
1041 disk_list
.append(persistent_disk
[disk
["id"]])
1044 if disk
["id"] not in persistent_disk
.keys():
1045 persistent_disk
[disk
["id"]] = {
1046 "size": disk
.get("size-of-storage"),
1048 disk_list
.append(persistent_disk
[disk
["id"]])
1053 def _process_vdu_params(
1054 target_vdu
: Dict
[str, Any
],
1055 indata
: Dict
[str, Any
],
1056 vim_info
: Dict
[str, Any
],
1057 target_record_id
: str,
1058 **kwargs
: Dict
[str, Any
],
1059 ) -> Dict
[str, Any
]:
1060 """Function to process VDU parameters.
1063 target_vdu (Dict[str, Any]): [description]
1064 indata (Dict[str, Any]): [description]
1065 vim_info (Dict[str, Any]): [description]
1066 target_record_id (str): [description]
1069 Dict[str, Any]: [description]
1071 vnfr_id
= kwargs
.get("vnfr_id")
1072 nsr_id
= kwargs
.get("nsr_id")
1073 vnfr
= kwargs
.get("vnfr")
1074 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1075 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
1076 logger
= kwargs
.get("logger")
1077 db
= kwargs
.get("db")
1078 fs
= kwargs
.get("fs")
1079 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1081 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
1082 ns_preffix
= "nsrs:{}".format(nsr_id
)
1083 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
1084 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
1085 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
1088 # If the position info is provided for all the interfaces, it will be sorted
1089 # according to position number ascendingly.
1091 i
.get("position") + 1
1092 for i
in target_vdu
["interfaces"]
1093 if i
.get("position") is not None
1095 sorted_interfaces
= sorted(
1096 target_vdu
["interfaces"],
1097 key
=lambda x
: (x
.get("position") is None, x
.get("position")),
1099 target_vdu
["interfaces"] = sorted_interfaces
1101 # If the position info is provided for some interfaces but not all of them, the interfaces
1102 # which has specific position numbers will be placed and others' positions will not be taken care.
1105 i
.get("position") + 1
1106 for i
in target_vdu
["interfaces"]
1107 if i
.get("position") is not None
1109 n
= len(target_vdu
["interfaces"])
1110 sorted_interfaces
= [-1] * n
1113 if target_vdu
["interfaces"][k
].get("position"):
1114 idx
= target_vdu
["interfaces"][k
]["position"]
1115 sorted_interfaces
[idx
- 1] = target_vdu
["interfaces"][k
]
1118 if not target_vdu
["interfaces"][m
].get("position"):
1119 idy
= sorted_interfaces
.index(-1)
1120 sorted_interfaces
[idy
] = target_vdu
["interfaces"][m
]
1123 target_vdu
["interfaces"] = sorted_interfaces
1125 # If the position info is not provided for the interfaces, interfaces will be attached
1126 # according to the order in the VNFD.
1127 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
1128 if interface
.get("ns-vld-id"):
1129 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
1130 elif interface
.get("vnf-vld-id"):
1131 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
1134 "Interface {} from vdu {} not connected to any vld".format(
1135 iface_index
, target_vdu
["vdu-name"]
1139 continue # interface not connected to any vld
1141 extra_dict
["depends_on"].append(net_text
)
1143 if "port-security-enabled" in interface
:
1144 interface
["port_security"] = interface
.pop("port-security-enabled")
1146 if "port-security-disable-strategy" in interface
:
1147 interface
["port_security_disable_strategy"] = interface
.pop(
1148 "port-security-disable-strategy"
1153 for x
, v
in interface
.items()
1159 "port_security_disable_strategy",
1163 net_item
["net_id"] = "TASK-" + net_text
1164 net_item
["type"] = "virtual"
1166 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1167 # TODO floating_ip: True/False (or it can be None)
1168 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1169 # mark the net create task as type data
1171 tasks_by_target_record_id
,
1177 tasks_by_target_record_id
[net_text
]["extra_dict"]["params"][
1181 net_item
["use"] = "data"
1182 net_item
["model"] = interface
["type"]
1183 net_item
["type"] = interface
["type"]
1185 interface
.get("type") == "OM-MGMT"
1186 or interface
.get("mgmt-interface")
1187 or interface
.get("mgmt-vnf")
1189 net_item
["use"] = "mgmt"
1191 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1192 net_item
["use"] = "bridge"
1193 net_item
["model"] = interface
.get("type")
1195 if interface
.get("ip-address"):
1196 net_item
["ip_address"] = interface
["ip-address"]
1198 if interface
.get("mac-address"):
1199 net_item
["mac_address"] = interface
["mac-address"]
1201 net_list
.append(net_item
)
1203 if interface
.get("mgmt-vnf"):
1204 extra_dict
["mgmt_vnf_interface"] = iface_index
1205 elif interface
.get("mgmt-interface"):
1206 extra_dict
["mgmt_vdu_interface"] = iface_index
1211 if target_vdu
.get("cloud-init"):
1212 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1213 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1216 location
=target_vdu
["cloud-init"],
1219 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1220 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1221 cloud_init_content
=cloud_content_
,
1222 params
=target_vdu
.get("additionalParams"),
1223 context
=target_vdu
["cloud-init"],
1226 if target_vdu
.get("boot-data-drive"):
1227 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1231 if target_vdu
.get("ssh-keys"):
1232 ssh_keys
+= target_vdu
.get("ssh-keys")
1234 if target_vdu
.get("ssh-access-required"):
1235 ssh_keys
.append(ro_nsr_public_key
)
1238 cloud_config
["key-pairs"] = ssh_keys
1240 persistent_root_disk
= {}
1241 vdu_instantiation_volumes_list
= []
1243 vnfd_id
= vnfr
["vnfd-id"]
1244 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
1246 if target_vdu
.get("additionalParams"):
1247 vdu_instantiation_volumes_list
= (
1248 target_vdu
.get("additionalParams").get("OSM").get("vdu_volumes")
1251 if vdu_instantiation_volumes_list
:
1253 # Find the root volumes and add to the disk_list
1254 (disk_list
, persistent_root_disk
,) = Ns
.find_persistent_root_volumes(
1255 vnfd
, target_vdu
, vdu_instantiation_volumes_list
, disk_list
1258 # Find the ordinary volumes which are not added to the persistent_root_disk
1259 # and put them to the disk list
1260 disk_list
= Ns
.find_persistent_volumes(
1261 persistent_root_disk
,
1263 vdu_instantiation_volumes_list
,
1269 # vdu_instantiation_volumes_list is empty
1270 for vdu
in vnfd
.get("vdu", ()):
1271 if vdu
["name"] == target_vdu
["vdu-name"]:
1272 for vsd
in vnfd
.get("virtual-storage-desc", ()):
1273 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
1277 ) == "persistent-storage:persistent-storage" and root_disk
.get(
1280 persistent_root_disk
[vsd
["id"]] = {
1281 "image_id": vdu
.get("sw-image-desc"),
1282 "size": root_disk
["size-of-storage"],
1284 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1286 if target_vdu
.get("virtual-storages"):
1287 for disk
in target_vdu
["virtual-storages"]:
1289 disk
.get("type-of-storage")
1290 == "persistent-storage:persistent-storage"
1291 and disk
["id"] not in persistent_root_disk
.keys()
1293 disk_list
.append({"size": disk
["size-of-storage"]})
1295 affinity_group_list
= []
1297 if target_vdu
.get("affinity-or-anti-affinity-group-id"):
1299 for affinity_group_id
in target_vdu
["affinity-or-anti-affinity-group-id"]:
1300 affinity_group_text
= (
1301 ns_preffix
+ ":affinity-or-anti-affinity-group." + affinity_group_id
1304 extra_dict
["depends_on"].append(affinity_group_text
)
1305 affinity_group
["affinity_group_id"] = "TASK-" + affinity_group_text
1306 affinity_group_list
.append(affinity_group
)
1308 extra_dict
["params"] = {
1309 "name": "{}-{}-{}-{}".format(
1310 indata
["name"][:16],
1311 vnfr
["member-vnf-index-ref"][:16],
1312 target_vdu
["vdu-name"][:32],
1313 target_vdu
.get("count-index") or 0,
1315 "description": target_vdu
["vdu-name"],
1317 "image_id": "TASK-" + image_text
,
1318 "flavor_id": "TASK-" + flavor_text
,
1319 "affinity_group_list": affinity_group_list
,
1320 "net_list": net_list
,
1321 "cloud_config": cloud_config
or None,
1322 "disk_list": disk_list
,
1323 "availability_zone_index": None, # TODO
1324 "availability_zone_list": None, # TODO
1330 def _process_affinity_group_params(
1331 target_affinity_group
: Dict
[str, Any
],
1332 indata
: Dict
[str, Any
],
1333 vim_info
: Dict
[str, Any
],
1334 target_record_id
: str,
1335 **kwargs
: Dict
[str, Any
],
1336 ) -> Dict
[str, Any
]:
1337 """Get affinity or anti-affinity group parameters.
1340 target_affinity_group (Dict[str, Any]): [description]
1341 indata (Dict[str, Any]): [description]
1342 vim_info (Dict[str, Any]): [description]
1343 target_record_id (str): [description]
1346 Dict[str, Any]: [description]
1350 affinity_group_data
= {
1351 "name": target_affinity_group
["name"],
1352 "type": target_affinity_group
["type"],
1353 "scope": target_affinity_group
["scope"],
1356 if target_affinity_group
.get("vim-affinity-group-id"):
1357 affinity_group_data
["vim-affinity-group-id"] = target_affinity_group
[
1358 "vim-affinity-group-id"
1361 extra_dict
["params"] = {
1362 "affinity_group_data": affinity_group_data
,
1368 def _process_recreate_vdu_params(
1369 existing_vdu
: Dict
[str, Any
],
1370 db_nsr
: Dict
[str, Any
],
1371 vim_info
: Dict
[str, Any
],
1372 target_record_id
: str,
1374 **kwargs
: Dict
[str, Any
],
1375 ) -> Dict
[str, Any
]:
1376 """Function to process VDU parameters to recreate.
1379 existing_vdu (Dict[str, Any]): [description]
1380 db_nsr (Dict[str, Any]): [description]
1381 vim_info (Dict[str, Any]): [description]
1382 target_record_id (str): [description]
1383 target_id (str): [description]
1386 Dict[str, Any]: [description]
1388 vnfr
= kwargs
.get("vnfr")
1389 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1390 # logger = kwargs.get("logger")
1391 db
= kwargs
.get("db")
1392 fs
= kwargs
.get("fs")
1393 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1399 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
1400 if vim_details_text
:
1401 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
1403 for iface_index
, interface
in enumerate(existing_vdu
["interfaces"]):
1405 if "port-security-enabled" in interface
:
1406 interface
["port_security"] = interface
.pop("port-security-enabled")
1408 if "port-security-disable-strategy" in interface
:
1409 interface
["port_security_disable_strategy"] = interface
.pop(
1410 "port-security-disable-strategy"
1415 for x
, v
in interface
.items()
1421 "port_security_disable_strategy",
1425 existing_ifaces
= existing_vdu
["vim_info"][target_id
].get(
1426 "interfaces_backup", []
1431 for i
in existing_ifaces
1432 if i
["ip_address"] == interface
["ip-address"]
1437 net_item
["net_id"] = net_id
1438 net_item
["type"] = "virtual"
1440 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1441 # TODO floating_ip: True/False (or it can be None)
1442 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1443 net_item
["use"] = "data"
1444 net_item
["model"] = interface
["type"]
1445 net_item
["type"] = interface
["type"]
1447 interface
.get("type") == "OM-MGMT"
1448 or interface
.get("mgmt-interface")
1449 or interface
.get("mgmt-vnf")
1451 net_item
["use"] = "mgmt"
1453 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1454 net_item
["use"] = "bridge"
1455 net_item
["model"] = interface
.get("type")
1457 if interface
.get("ip-address"):
1458 net_item
["ip_address"] = interface
["ip-address"]
1460 if interface
.get("mac-address"):
1461 net_item
["mac_address"] = interface
["mac-address"]
1463 net_list
.append(net_item
)
1465 if interface
.get("mgmt-vnf"):
1466 extra_dict
["mgmt_vnf_interface"] = iface_index
1467 elif interface
.get("mgmt-interface"):
1468 extra_dict
["mgmt_vdu_interface"] = iface_index
1473 if existing_vdu
.get("cloud-init"):
1474 if existing_vdu
["cloud-init"] not in vdu2cloud_init
:
1475 vdu2cloud_init
[existing_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1478 location
=existing_vdu
["cloud-init"],
1481 cloud_content_
= vdu2cloud_init
[existing_vdu
["cloud-init"]]
1482 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1483 cloud_init_content
=cloud_content_
,
1484 params
=existing_vdu
.get("additionalParams"),
1485 context
=existing_vdu
["cloud-init"],
1488 if existing_vdu
.get("boot-data-drive"):
1489 cloud_config
["boot-data-drive"] = existing_vdu
.get("boot-data-drive")
1493 if existing_vdu
.get("ssh-keys"):
1494 ssh_keys
+= existing_vdu
.get("ssh-keys")
1496 if existing_vdu
.get("ssh-access-required"):
1497 ssh_keys
.append(ro_nsr_public_key
)
1500 cloud_config
["key-pairs"] = ssh_keys
1503 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
1504 disk_list
.append({"vim_id": vol_id
["id"]})
1506 affinity_group_list
= []
1508 if existing_vdu
.get("affinity-or-anti-affinity-group-id"):
1510 for affinity_group_id
in existing_vdu
["affinity-or-anti-affinity-group-id"]:
1511 for group
in db_nsr
.get("affinity-or-anti-affinity-group"):
1513 group
["id"] == affinity_group_id
1514 and group
["vim_info"][target_id
].get("vim_id", None) is not None
1516 affinity_group
["affinity_group_id"] = group
["vim_info"][
1518 ].get("vim_id", None)
1519 affinity_group_list
.append(affinity_group
)
1521 extra_dict
["params"] = {
1522 "name": "{}-{}-{}-{}".format(
1523 db_nsr
["name"][:16],
1524 vnfr
["member-vnf-index-ref"][:16],
1525 existing_vdu
["vdu-name"][:32],
1526 existing_vdu
.get("count-index") or 0,
1528 "description": existing_vdu
["vdu-name"],
1530 "image_id": vim_details
["image"]["id"],
1531 "flavor_id": vim_details
["flavor"]["id"],
1532 "affinity_group_list": affinity_group_list
,
1533 "net_list": net_list
,
1534 "cloud_config": cloud_config
or None,
1535 "disk_list": disk_list
,
1536 "availability_zone_index": None, # TODO
1537 "availability_zone_list": None, # TODO
1542 def calculate_diff_items(
1549 tasks_by_target_record_id
,
1556 """Function that returns the incremental changes (creation, deletion)
1557 related to a specific item `item` to be done. This function should be
1558 called for NS instantiation, NS termination, NS update to add a new VNF
1559 or a new VLD, remove a VNF or VLD, etc.
1560 Item can be `net`, `flavor`, `image` or `vdu`.
1561 It takes a list of target items from indata (which came from the REST API)
1562 and compares with the existing items from db_ro_nsr, identifying the
1563 incremental changes to be done. During the comparison, it calls the method
1564 `process_params` (which was passed as parameter, and is particular for each
1568 indata (Dict[str, Any]): deployment info
1569 db_nsr: NSR record from DB
1570 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1571 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1572 item (str): element to process (net, vdu...)
1573 tasks_by_target_record_id (Dict[str, Any]):
1574 [<target_record_id>, <task>]
1575 action_id (str): action id
1576 nsr_id (str): NSR id
1577 task_index (number): task index to add to task name
1578 vnfr_id (str): VNFR id
1579 vnfr (Dict[str, Any]): VNFR info
1582 List: list with the incremental changes (deletes, creates) for each item
1583 number: current task index
1591 process_params
= None
1592 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1593 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1595 # According to the type of item, the path, the target_list,
1596 # the existing_list and the method to process params are set
1597 db_path
= self
.db_path_map
[item
]
1598 process_params
= self
.process_params_function_map
[item
]
1599 if item
in ("net", "vdu"):
1600 # This case is specific for the NS VLD (not applied to VDU)
1602 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1603 target_list
= indata
.get("ns", []).get(db_path
, [])
1604 existing_list
= db_nsr
.get(db_path
, [])
1605 # This case is common for VNF VLDs and VNF VDUs
1607 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
1609 (vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
),
1612 target_list
= target_vnf
.get(db_path
, []) if target_vnf
else []
1613 existing_list
= vnfr
.get(db_path
, [])
1614 elif item
in ("image", "flavor", "affinity-or-anti-affinity-group"):
1615 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1616 target_list
= indata
.get(item
, [])
1617 existing_list
= db_nsr
.get(item
, [])
1619 raise NsException("Item not supported: {}", item
)
1621 # ensure all the target_list elements has an "id". If not assign the index as id
1622 if target_list
is None:
1624 for target_index
, tl
in enumerate(target_list
):
1625 if tl
and not tl
.get("id"):
1626 tl
["id"] = str(target_index
)
1628 # step 1 items (networks,vdus,...) to be deleted/updated
1629 for item_index
, existing_item
in enumerate(existing_list
):
1631 (t
for t
in target_list
if t
["id"] == existing_item
["id"]),
1635 for target_vim
, existing_viminfo
in existing_item
.get(
1638 if existing_viminfo
is None:
1642 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
1644 target_viminfo
= None
1646 if target_viminfo
is None:
1648 self
._assign
_vim
(target_vim
)
1649 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
1652 if target_vim
.startswith("sdn"):
1653 # item must be sdn-net instead of net if target_vim is a sdn
1655 target_record_id
+= ".sdn"
1658 "action_id": action_id
,
1660 "task_index": task_index
,
1665 "deployment_info": deployment_info
,
1666 "target_id": target_vim
,
1669 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1670 "target_record_id": target_record_id
,
1675 # step 2 items (networks,vdus,...) to be created
1676 for target_item
in target_list
:
1679 for item_index
, existing_item
in enumerate(existing_list
):
1680 if existing_item
["id"] == target_item
["id"]:
1684 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1685 existing_list
.append(target_item
)
1686 existing_item
= None
1688 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
1689 existing_viminfo
= None
1692 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
1694 if existing_viminfo
is not None:
1697 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
1700 if target_vim
.startswith("sdn"):
1701 # item must be sdn-net instead of net if target_vim is a sdn
1703 target_record_id
+= ".sdn"
1706 self
.logger
.warning(
1707 "ns.calculate_diff_items target_item={}".format(target_item
)
1709 if process_params
== Ns
._process
_flavor
_params
:
1715 self
.logger
.warning(
1716 "calculate_diff_items for flavor kwargs={}".format(kwargs
)
1719 if process_params
== Ns
._process
_vdu
_params
:
1720 self
.logger
.warning(
1721 "calculate_diff_items self.fs={}".format(self
.fs
)
1728 "vdu2cloud_init": vdu2cloud_init
,
1729 "tasks_by_target_record_id": tasks_by_target_record_id
,
1730 "logger": self
.logger
,
1733 "ro_nsr_public_key": ro_nsr_public_key
,
1736 self
.logger
.warning("calculate_diff_items kwargs={}".format(kwargs
))
1738 extra_dict
= process_params(
1745 self
._assign
_vim
(target_vim
)
1748 "action_id": action_id
,
1750 "task_index": task_index
,
1754 "deployment_info": deployment_info
,
1755 "target_id": target_vim
,
1758 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1759 "target_record_id": target_record_id
,
1760 "extra_dict": extra_dict
,
1761 "common_id": target_item
.get("common_id", None),
1763 diff_items
.append(new_item
)
1764 tasks_by_target_record_id
[target_record_id
] = new_item
1767 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1769 return diff_items
, task_index
1771 def calculate_all_differences_to_deploy(
1781 tasks_by_target_record_id
,
1783 """This method calculates the ordered list of items (`changes_list`)
1784 to be created and deleted.
1787 indata (Dict[str, Any]): deployment info
1788 nsr_id (str): NSR id
1789 db_nsr: NSR record from DB
1790 db_vnfrs: VNFRS record from DB
1791 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1792 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1793 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
1794 action_id (str): action id
1795 tasks_by_target_record_id (Dict[str, Any]):
1796 [<target_record_id>, <task>]
1799 List: ordered list of items to be created and deleted.
1803 # set list with diffs:
1806 # NS vld, image and flavor
1807 for item
in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
1808 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
1809 diff_items
, task_index
= self
.calculate_diff_items(
1812 db_ro_nsr
=db_ro_nsr
,
1813 db_nsr_update
=db_nsr_update
,
1815 tasks_by_target_record_id
=tasks_by_target_record_id
,
1816 action_id
=action_id
,
1818 task_index
=task_index
,
1821 changes_list
+= diff_items
1824 for vnfr_id
, vnfr
in db_vnfrs
.items():
1825 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1826 for item
in ["net", "vdu"]:
1827 self
.logger
.debug("process VNF={} {}".format(vnfr_id
, item
))
1828 diff_items
, task_index
= self
.calculate_diff_items(
1831 db_ro_nsr
=db_ro_nsr
,
1832 db_nsr_update
=db_vnfrs_update
[vnfr
["_id"]],
1834 tasks_by_target_record_id
=tasks_by_target_record_id
,
1835 action_id
=action_id
,
1837 task_index
=task_index
,
1841 changes_list
+= diff_items
1845 def define_all_tasks(
1849 tasks_by_target_record_id
,
1851 """Function to create all the task structures obtanied from
1852 the method calculate_all_differences_to_deploy
1855 changes_list (List): ordered list of items to be created or deleted
1856 db_new_tasks (List): tasks list to be created
1857 action_id (str): action id
1858 tasks_by_target_record_id (Dict[str, Any]):
1859 [<target_record_id>, <task>]
1863 for change
in changes_list
:
1864 task
= Ns
._create
_task
(
1865 deployment_info
=change
["deployment_info"],
1866 target_id
=change
["target_id"],
1867 item
=change
["item"],
1868 action
=change
["action"],
1869 target_record
=change
["target_record"],
1870 target_record_id
=change
["target_record_id"],
1871 extra_dict
=change
.get("extra_dict", None),
1874 self
.logger
.warning("ns.define_all_tasks task={}".format(task
))
1875 tasks_by_target_record_id
[change
["target_record_id"]] = task
1876 db_new_tasks
.append(task
)
1878 if change
.get("common_id"):
1879 task
["common_id"] = change
["common_id"]
1881 def upload_all_tasks(
1886 """Function to save all tasks in the common DB
1889 db_new_tasks (List): tasks list to be created
1890 now (time): current time
1894 nb_ro_tasks
= 0 # for logging
1896 for db_task
in db_new_tasks
:
1897 target_id
= db_task
.pop("target_id")
1898 common_id
= db_task
.get("common_id")
1900 # Do not chek tasks with vim_status DELETED
1901 # because in manual heealing there are two tasks for the same vdur:
1902 # one with vim_status deleted and the other one with the actual VM status.
1908 "target_id": target_id
,
1909 "tasks.common_id": common_id
,
1910 "vim_info.vim_status.ne": "DELETED",
1912 update_dict
={"to_check_at": now
, "modified_at": now
},
1913 push
={"tasks": db_task
},
1914 fail_on_empty
=False,
1918 if not self
.db
.set_one(
1921 "target_id": target_id
,
1922 "tasks.target_record": db_task
["target_record"],
1923 "vim_info.vim_status.ne": "DELETED",
1925 update_dict
={"to_check_at": now
, "modified_at": now
},
1926 push
={"tasks": db_task
},
1927 fail_on_empty
=False,
1930 self
.logger
.debug("Updating database, Creating ro_tasks")
1931 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
1933 self
.db
.create("ro_tasks", db_ro_task
)
1936 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1937 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
1941 def upload_recreate_tasks(
1946 """Function to save recreate tasks in the common DB
1949 db_new_tasks (List): tasks list to be created
1950 now (time): current time
1954 nb_ro_tasks
= 0 # for logging
1956 for db_task
in db_new_tasks
:
1957 target_id
= db_task
.pop("target_id")
1958 self
.logger
.warning("target_id={} db_task={}".format(target_id
, db_task
))
1960 action
= db_task
.get("action", None)
1963 self
.logger
.debug("Updating database, Creating ro_tasks")
1964 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
1966 # If DELETE task: the associated created items should be removed
1967 # (except persistent volumes):
1968 if action
== "DELETE":
1969 db_ro_task
["vim_info"]["created"] = True
1970 db_ro_task
["vim_info"]["created_items"] = db_task
.get(
1973 db_ro_task
["vim_info"]["volumes_to_hold"] = db_task
.get(
1974 "volumes_to_hold", []
1976 db_ro_task
["vim_info"]["vim_id"] = db_task
.get("vim_id", None)
1979 self
.logger
.warning("upload_all_tasks db_ro_task={}".format(db_ro_task
))
1980 self
.db
.create("ro_tasks", db_ro_task
)
1983 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1984 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
1988 def _prepare_created_items_for_healing(
1994 # Get created_items from ro_task
1995 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
1996 for ro_task
in ro_tasks
:
1997 for task
in ro_task
["tasks"]:
1999 task
["target_record"] == target_record
2000 and task
["action"] == "CREATE"
2001 and ro_task
["vim_info"]["created_items"]
2003 created_items
= ro_task
["vim_info"]["created_items"]
2006 return created_items
2008 def _prepare_persistent_volumes_for_healing(
2013 # The associated volumes of the VM shouldn't be removed
2016 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
2017 if vim_details_text
:
2018 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
2020 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
2021 volumes_list
.append(vol_id
["id"])
2025 def prepare_changes_to_recreate(
2033 tasks_by_target_record_id
,
2035 """This method will obtain an ordered list of items (`changes_list`)
2036 to be created and deleted to meet the recreate request.
2040 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id
, indata
)
2044 # set list with diffs:
2046 db_path
= self
.db_path_map
["vdu"]
2047 target_list
= indata
.get("healVnfData", {})
2048 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
2049 ro_nsr_public_key
= db_ro_nsr
["public_key"]
2051 # Check each VNF of the target
2052 for target_vnf
in target_list
:
2053 # Find this VNF in the list from DB
2054 vnfr_id
= target_vnf
.get("vnfInstanceId", None)
2056 existing_vnf
= db_vnfrs
.get(vnfr_id
)
2057 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
2058 # vim_account_id = existing_vnf.get("vim-account-id", "")
2060 # Check each VDU of this VNF
2061 for target_vdu
in target_vnf
["additionalParams"].get("vdu", None):
2062 vdu_name
= target_vdu
.get("vdu-id", None)
2063 # For multi instance VDU count-index is mandatory
2064 # For single session VDU count-indes is 0
2065 count_index
= target_vdu
.get("count-index", 0)
2067 existing_instance
= None
2068 for instance
in existing_vnf
.get("vdur", None):
2070 instance
["vdu-name"] == vdu_name
2071 and instance
["count-index"] == count_index
2073 existing_instance
= instance
2078 target_record_id
= "{}.{}".format(db_record
, existing_instance
["id"])
2080 # The target VIM is the one already existing in DB to recreate
2081 for target_vim
, target_viminfo
in existing_instance
.get(
2084 # step 1 vdu to be deleted
2085 self
._assign
_vim
(target_vim
)
2087 "action_id": action_id
,
2089 "task_index": task_index
,
2092 target_record
= f
"{db_record}.{item_index}.vim_info.{target_vim}"
2093 created_items
= self
._prepare
_created
_items
_for
_healing
(
2094 nsr_id
, target_record
2097 volumes_to_hold
= self
._prepare
_persistent
_volumes
_for
_healing
(
2098 target_vim
, existing_instance
2101 # Specific extra params for recreate tasks:
2103 "created_items": created_items
,
2104 "vim_id": existing_instance
["vim-id"],
2105 "volumes_to_hold": volumes_to_hold
,
2108 changes_list
.append(
2110 "deployment_info": deployment_info
,
2111 "target_id": target_vim
,
2114 "target_record": target_record
,
2115 "target_record_id": target_record_id
,
2116 "extra_dict": extra_dict
,
2119 delete_task_id
= f
"{action_id}:{task_index}"
2122 # step 2 vdu to be created
2128 "vnfr": existing_vnf
,
2129 "vdu2cloud_init": vdu2cloud_init
,
2130 "tasks_by_target_record_id": tasks_by_target_record_id
,
2131 "logger": self
.logger
,
2134 "ro_nsr_public_key": ro_nsr_public_key
,
2138 extra_dict
= self
._process
_recreate
_vdu
_params
(
2147 # The CREATE task depens on the DELETE task
2148 extra_dict
["depends_on"] = [delete_task_id
]
2150 # Add volumes created from created_items if any
2151 # Ports should be deleted with delete task and automatically created with create task
2153 for k
, v
in created_items
.items():
2155 k_item
, _
, k_id
= k
.partition(":")
2156 if k_item
== "volume":
2158 except Exception as e
:
2160 "Error evaluating created item {}: {}".format(k
, e
)
2162 extra_dict
["previous_created_volumes"] = volumes
2165 "action_id": action_id
,
2167 "task_index": task_index
,
2169 self
._assign
_vim
(target_vim
)
2172 "deployment_info": deployment_info
,
2173 "target_id": target_vim
,
2176 "target_record": target_record
,
2177 "target_record_id": target_record_id
,
2178 "extra_dict": extra_dict
,
2180 changes_list
.append(new_item
)
2181 tasks_by_target_record_id
[target_record_id
] = new_item
2186 def recreate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2187 self
.logger
.debug("ns.recreate nsr_id={} indata={}".format(nsr_id
, indata
))
2188 # TODO: validate_input(indata, recreate_schema)
2189 action_id
= indata
.get("action_id", str(uuid4()))
2190 # get current deployment
2191 db_vnfrs
= {} # vnf's info indexed by _id
2193 logging_text
= "Recreate nsr_id={} action_id={} indata={}".format(
2194 nsr_id
, action_id
, indata
2196 self
.logger
.debug(logging_text
+ "Enter")
2199 step
= "Getting ns and vnfr record from db"
2200 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2202 tasks_by_target_record_id
= {}
2203 # read from db: vnf's of this ns
2204 step
= "Getting vnfrs from db"
2205 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2206 self
.logger
.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list
))
2208 if not db_vnfrs_list
:
2209 raise NsException("Cannot obtain associated VNF for ns")
2211 for vnfr
in db_vnfrs_list
:
2212 db_vnfrs
[vnfr
["_id"]] = vnfr
2215 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2216 self
.logger
.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr
))
2219 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2221 with self
.write_lock
:
2223 step
= "process NS elements"
2224 changes_list
= self
.prepare_changes_to_recreate(
2229 db_ro_nsr
=db_ro_nsr
,
2230 action_id
=action_id
,
2231 tasks_by_target_record_id
=tasks_by_target_record_id
,
2234 self
.define_all_tasks(
2235 changes_list
=changes_list
,
2236 db_new_tasks
=db_new_tasks
,
2237 tasks_by_target_record_id
=tasks_by_target_record_id
,
2240 # Delete all ro_tasks registered for the targets vdurs (target_record)
2241 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2242 # So remove all task related to target record.
2243 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2244 for change
in changes_list
:
2245 for ro_task
in ro_tasks
:
2246 for task
in ro_task
["tasks"]:
2247 if task
["target_record"] == change
["target_record"]:
2251 "_id": ro_task
["_id"],
2252 "modified_at": ro_task
["modified_at"],
2254 fail_on_empty
=False,
2257 step
= "Updating database, Appending tasks to ro_tasks"
2258 self
.upload_recreate_tasks(
2259 db_new_tasks
=db_new_tasks
,
2264 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2268 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2272 except Exception as e
:
2273 if isinstance(e
, (DbException
, NsException
)):
2275 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2278 e
= traceback_format_exc()
2279 self
.logger
.critical(
2280 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2284 raise NsException(e
)
2286 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2287 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
2288 validate_input(indata
, deploy_schema
)
2289 action_id
= indata
.get("action_id", str(uuid4()))
2291 # get current deployment
2292 db_nsr_update
= {} # update operation on nsrs
2293 db_vnfrs_update
= {}
2294 db_vnfrs
= {} # vnf's info indexed by _id
2296 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2297 self
.logger
.debug(logging_text
+ "Enter")
2300 step
= "Getting ns and vnfr record from db"
2301 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2302 self
.logger
.debug("ns.deploy: db_nsr={}".format(db_nsr
))
2304 tasks_by_target_record_id
= {}
2305 # read from db: vnf's of this ns
2306 step
= "Getting vnfrs from db"
2307 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2309 if not db_vnfrs_list
:
2310 raise NsException("Cannot obtain associated VNF for ns")
2312 for vnfr
in db_vnfrs_list
:
2313 db_vnfrs
[vnfr
["_id"]] = vnfr
2314 db_vnfrs_update
[vnfr
["_id"]] = {}
2315 self
.logger
.debug("ns.deploy db_vnfrs={}".format(db_vnfrs
))
2318 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2321 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2323 # check that action_id is not in the list of actions. Suffixed with :index
2324 if action_id
in db_ro_nsr
["actions"]:
2328 new_action_id
= "{}:{}".format(action_id
, index
)
2330 if new_action_id
not in db_ro_nsr
["actions"]:
2331 action_id
= new_action_id
2334 + "Changing action_id in use to {}".format(action_id
)
2340 def _process_action(indata
):
2341 nonlocal db_new_tasks
2348 if indata
["action"]["action"] == "inject_ssh_key":
2349 key
= indata
["action"].get("key")
2350 user
= indata
["action"].get("user")
2351 password
= indata
["action"].get("password")
2353 for vnf
in indata
.get("vnf", ()):
2354 if vnf
["_id"] not in db_vnfrs
:
2355 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
2357 db_vnfr
= db_vnfrs
[vnf
["_id"]]
2359 for target_vdu
in vnf
.get("vdur", ()):
2360 vdu_index
, vdur
= next(
2363 for i_v
in enumerate(db_vnfr
["vdur"])
2364 if i_v
[1]["id"] == target_vdu
["id"]
2371 "Invalid vdu vnf={}.{}".format(
2372 vnf
["_id"], target_vdu
["id"]
2376 target_vim
, vim_info
= next(
2377 k_v
for k_v
in vdur
["vim_info"].items()
2379 self
._assign
_vim
(target_vim
)
2380 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
2381 vnf
["_id"], vdu_index
2385 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
2388 "ip_address": vdur
.get("ip-address"),
2391 "password": password
,
2392 "private_key": db_ro_nsr
["private_key"],
2393 "salt": db_ro_nsr
["_id"],
2394 "schema_version": db_ro_nsr
["_admin"][
2401 "action_id": action_id
,
2403 "task_index": task_index
,
2406 task
= Ns
._create
_task
(
2407 deployment_info
=deployment_info
,
2408 target_id
=target_vim
,
2411 target_record
=target_record
,
2412 target_record_id
=None,
2413 extra_dict
=extra_dict
,
2416 task_index
= deployment_info
.get("task_index")
2418 db_new_tasks
.append(task
)
2420 with self
.write_lock
:
2421 if indata
.get("action"):
2422 _process_action(indata
)
2424 # compute network differences
2426 step
= "process NS elements"
2427 changes_list
= self
.calculate_all_differences_to_deploy(
2432 db_ro_nsr
=db_ro_nsr
,
2433 db_nsr_update
=db_nsr_update
,
2434 db_vnfrs_update
=db_vnfrs_update
,
2435 action_id
=action_id
,
2436 tasks_by_target_record_id
=tasks_by_target_record_id
,
2438 self
.define_all_tasks(
2439 changes_list
=changes_list
,
2440 db_new_tasks
=db_new_tasks
,
2441 tasks_by_target_record_id
=tasks_by_target_record_id
,
2444 step
= "Updating database, Appending tasks to ro_tasks"
2445 self
.upload_all_tasks(
2446 db_new_tasks
=db_new_tasks
,
2450 step
= "Updating database, nsrs"
2452 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
2454 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
2456 step
= "Updating database, vnfrs={}".format(vnfr_id
)
2457 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
2460 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2464 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2468 except Exception as e
:
2469 if isinstance(e
, (DbException
, NsException
)):
2471 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2474 e
= traceback_format_exc()
2475 self
.logger
.critical(
2476 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2480 raise NsException(e
)
2482 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2483 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
2484 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2486 with self
.write_lock
:
2488 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
2489 except NsWorkerException
as e
:
2490 raise NsException(e
)
2492 return None, None, True
2494 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2496 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2497 version
, nsr_id
, action_id
, indata
2503 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
2504 global_status
= "DONE"
2507 for ro_task
in ro_tasks
:
2508 for task
in ro_task
["tasks"]:
2509 if task
and task
["action_id"] == action_id
:
2510 task_list
.append(task
)
2513 if task
["status"] == "FAILED":
2514 global_status
= "FAILED"
2515 error_text
= "Error at {} {}: {}".format(
2516 task
["action"].lower(),
2518 ro_task
["vim_info"].get("vim_message") or "unknown",
2520 details
.append(error_text
)
2521 elif task
["status"] in ("SCHEDULED", "BUILD"):
2522 if global_status
!= "FAILED":
2523 global_status
= "BUILD"
2528 "status": global_status
,
2529 "details": ". ".join(details
)
2531 else "progress {}/{}".format(done
, total
),
2533 "action_id": action_id
,
2537 return return_data
, None, True
2539 def recreate_status(
2540 self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
2542 return self
.status(session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
)
2544 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2546 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2547 session
, indata
, version
, nsr_id
, action_id
2551 return None, None, True
2553 def rebuild_start_stop_task(
2564 self
._assign
_vim
(target_vim
)
2565 target_record
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_index
)
2566 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_id
)
2568 "action_id": action_id
,
2570 "task_index": task_index
,
2573 task
= Ns
._create
_task
(
2574 deployment_info
=deployment_info
,
2575 target_id
=target_vim
,
2578 target_record
=target_record
,
2579 target_record_id
=target_record_id
,
2580 extra_dict
=extra_dict
,
2584 def rebuild_start_stop(
2585 self
, session
, action_dict
, version
, nsr_id
, *args
, **kwargs
2590 action_id
= action_dict
.get("action_id", str(uuid4()))
2592 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2593 self
.logger
.debug(logging_text
+ "Enter")
2595 action
= list(action_dict
.keys())[0]
2596 task_dict
= action_dict
.get(action
)
2597 vim_vm_id
= action_dict
.get(action
).get("vim_vm_id")
2599 if action_dict
.get("stop"):
2603 step
= "lock the operation & do task creation"
2604 with self
.write_lock
:
2605 extra_dict
["params"] = {
2606 "vim_vm_id": vim_vm_id
,
2609 task
= self
.rebuild_start_stop_task(
2610 task_dict
["vdu_id"],
2611 task_dict
["vnf_id"],
2612 task_dict
["vdu_index"],
2616 task_dict
["target_vim"],
2619 db_new_tasks
.append(task
)
2620 step
= "upload Task to db"
2621 self
.upload_all_tasks(
2622 db_new_tasks
=db_new_tasks
,
2626 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2629 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2633 except Exception as e
:
2634 if isinstance(e
, (DbException
, NsException
)):
2636 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2639 e
= traceback_format_exc()
2640 self
.logger
.critical(
2641 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2644 raise NsException(e
)
2646 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2647 nsrs
= self
.db
.get_list("nsrs", {})
2651 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
2653 return return_data
, None, True
2655 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2656 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2659 for ro_task
in ro_tasks
:
2660 for task
in ro_task
["tasks"]:
2661 if task
["action_id"] not in return_data
:
2662 return_data
.append(task
["action_id"])
2664 return return_data
, None, True
2667 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
2669 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
2670 self
._assign
_vim
(target_vim
)
2671 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
2672 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
2674 "action_id": action_id
,
2676 "task_index": task_index
,
2679 task
= Ns
._create
_task
(
2680 deployment_info
=deployment_info
,
2681 target_id
=target_vim
,
2684 target_record
=target_record
,
2685 target_record_id
=target_record_id
,
2686 extra_dict
=extra_dict
,
2691 def migrate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2695 action_id
= indata
.get("action_id", str(uuid4()))
2697 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2698 self
.logger
.debug(logging_text
+ "Enter")
2700 vnf_instance_id
= indata
["vnfInstanceId"]
2701 step
= "Getting vnfrs from db"
2702 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
2703 vdu
= indata
.get("vdu")
2704 migrateToHost
= indata
.get("migrateToHost")
2707 with self
.write_lock
:
2709 vdu_id
= indata
["vdu"]["vduId"]
2710 vdu_count_index
= indata
["vdu"].get("vduCountIndex", 0)
2711 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2713 vdu
["vdu-id-ref"] == vdu_id
2714 and vdu
["count-index"] == vdu_count_index
2716 extra_dict
["params"] = {
2717 "vim_vm_id": vdu
["vim-id"],
2718 "migrate_host": migrateToHost
,
2719 "vdu_vim_info": vdu
["vim_info"],
2721 step
= "Creating migration task for vdu:{}".format(vdu
)
2722 task
= self
.migrate_task(
2731 db_new_tasks
.append(task
)
2736 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2737 extra_dict
["params"] = {
2738 "vim_vm_id": vdu
["vim-id"],
2739 "migrate_host": migrateToHost
,
2740 "vdu_vim_info": vdu
["vim_info"],
2742 step
= "Creating migration task for vdu:{}".format(vdu
)
2743 task
= self
.migrate_task(
2752 db_new_tasks
.append(task
)
2755 self
.upload_all_tasks(
2756 db_new_tasks
=db_new_tasks
,
2761 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2764 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2768 except Exception as e
:
2769 if isinstance(e
, (DbException
, NsException
)):
2771 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2774 e
= traceback_format_exc()
2775 self
.logger
.critical(
2776 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2779 raise NsException(e
)
2781 def verticalscale_task(
2782 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
2784 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
2785 self
._assign
_vim
(target_vim
)
2786 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
2787 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
2789 "action_id": action_id
,
2791 "task_index": task_index
,
2794 task
= Ns
._create
_task
(
2795 deployment_info
=deployment_info
,
2796 target_id
=target_vim
,
2797 item
="verticalscale",
2799 target_record
=target_record
,
2800 target_record_id
=target_record_id
,
2801 extra_dict
=extra_dict
,
2805 def verticalscale(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2809 action_id
= indata
.get("action_id", str(uuid4()))
2811 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2812 self
.logger
.debug(logging_text
+ "Enter")
2814 VnfFlavorData
= indata
.get("changeVnfFlavorData")
2815 vnf_instance_id
= VnfFlavorData
["vnfInstanceId"]
2816 step
= "Getting vnfrs from db"
2817 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
2818 vduid
= VnfFlavorData
["additionalParams"]["vduid"]
2819 vduCountIndex
= VnfFlavorData
["additionalParams"]["vduCountIndex"]
2820 virtualMemory
= VnfFlavorData
["additionalParams"]["virtualMemory"]
2821 numVirtualCpu
= VnfFlavorData
["additionalParams"]["numVirtualCpu"]
2822 sizeOfStorage
= VnfFlavorData
["additionalParams"]["sizeOfStorage"]
2824 "name": vduid
+ "-flv",
2825 "ram": virtualMemory
,
2826 "vcpus": numVirtualCpu
,
2827 "disk": sizeOfStorage
,
2830 step
= "Creating Tasks for vertical scaling"
2831 with self
.write_lock
:
2832 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2834 vdu
["vdu-id-ref"] == vduid
2835 and vdu
["count-index"] == vduCountIndex
2837 extra_dict
["params"] = {
2838 "vim_vm_id": vdu
["vim-id"],
2839 "flavor_dict": flavor_dict
,
2841 task
= self
.verticalscale_task(
2850 db_new_tasks
.append(task
)
2853 self
.upload_all_tasks(
2854 db_new_tasks
=db_new_tasks
,
2858 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2861 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2865 except Exception as e
:
2866 if isinstance(e
, (DbException
, NsException
)):
2868 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2871 e
= traceback_format_exc()
2872 self
.logger
.critical(
2873 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2876 raise NsException(e
)