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
40 from osm_common
import (
47 version
as common_version
,
49 from osm_common
.dbbase
import DbBase
, DbException
50 from osm_common
.fsbase
import FsBase
, FsException
51 from osm_common
.msgbase
import MsgException
52 from osm_ng_ro
.ns_thread
import deep_get
, NsWorker
, NsWorkerException
53 from osm_ng_ro
.validation
import deploy_schema
, validate_input
56 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
57 min_common_version
= "0.1.16"
60 class NsException(Exception):
61 def __init__(self
, message
, http_code
=HTTPStatus
.BAD_REQUEST
):
62 self
.http_code
= http_code
63 super(Exception, self
).__init
__(message
)
68 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
69 will provide a random one
72 # Try getting docker id. If fails, get pid
74 with
open("/proc/self/cgroup", "r") as f
:
75 text_id_
= f
.readline()
76 _
, _
, text_id
= text_id_
.rpartition("/")
77 text_id
= text_id
.replace("\n", "")[:12]
81 except Exception as error
:
82 logging
.exception(f
"{error} occured while getting process id")
85 return "".join(random_choice("0123456789abcdef") for _
in range(12))
89 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
92 for point
in v
.split("."):
93 filled
.append(point
.zfill(8))
104 # self.operations = None
106 # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
107 # If done now it will not be linked to parent not getting its handler and level
109 self
.write_lock
= None
110 self
.vims_assigned
= {}
114 self
.process_params_function_map
= {
115 "net": Ns
._process
_net
_params
,
116 "image": Ns
._process
_image
_params
,
117 "flavor": Ns
._process
_flavor
_params
,
118 "vdu": Ns
._process
_vdu
_params
,
119 "affinity-or-anti-affinity-group": Ns
._process
_affinity
_group
_params
,
126 "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group",
129 def init_db(self
, target_version
):
132 def start(self
, config
):
134 Connect to database, filesystem storage, and messaging
135 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
136 :param config: Configuration of db, storage, etc
140 self
.config
["process_id"] = get_process_id() # used for HA identity
141 self
.logger
= logging
.getLogger("ro.ns")
143 # check right version of common
144 if versiontuple(common_version
) < versiontuple(min_common_version
):
146 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
147 common_version
, min_common_version
153 if config
["database"]["driver"] == "mongo":
154 self
.db
= dbmongo
.DbMongo()
155 self
.db
.db_connect(config
["database"])
156 elif config
["database"]["driver"] == "memory":
157 self
.db
= dbmemory
.DbMemory()
158 self
.db
.db_connect(config
["database"])
161 "Invalid configuration param '{}' at '[database]':'driver'".format(
162 config
["database"]["driver"]
167 if config
["storage"]["driver"] == "local":
168 self
.fs
= fslocal
.FsLocal()
169 self
.fs
.fs_connect(config
["storage"])
170 elif config
["storage"]["driver"] == "mongo":
171 self
.fs
= fsmongo
.FsMongo()
172 self
.fs
.fs_connect(config
["storage"])
173 elif config
["storage"]["driver"] is None:
177 "Invalid configuration param '{}' at '[storage]':'driver'".format(
178 config
["storage"]["driver"]
183 if config
["message"]["driver"] == "local":
184 self
.msg
= msglocal
.MsgLocal()
185 self
.msg
.connect(config
["message"])
186 elif config
["message"]["driver"] == "kafka":
187 self
.msg
= msgkafka
.MsgKafka()
188 self
.msg
.connect(config
["message"])
191 "Invalid configuration param '{}' at '[message]':'driver'".format(
192 config
["message"]["driver"]
196 # TODO load workers to deal with exising database tasks
198 self
.write_lock
= Lock()
199 except (DbException
, FsException
, MsgException
) as e
:
200 raise NsException(str(e
), http_code
=e
.http_code
)
202 def get_assigned_vims(self
):
203 return list(self
.vims_assigned
.keys())
208 self
.db
.db_disconnect()
211 self
.fs
.fs_disconnect()
214 self
.msg
.disconnect()
216 self
.write_lock
= None
217 except (DbException
, FsException
, MsgException
) as e
:
218 raise NsException(str(e
), http_code
=e
.http_code
)
220 for worker
in self
.workers
:
221 worker
.insert_task(("terminate",))
223 def _create_worker(self
):
225 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
226 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
227 return the index of the assigned worker thread. Worker threads are storead at self.workers
229 # Look for a thread in idle status
233 for i
in range(len(self
.workers
))
234 if self
.workers
[i
] and self
.workers
[i
].idle
239 if worker_id
is not None:
240 # unset idle status to avoid race conditions
241 self
.workers
[worker_id
].idle
= False
243 worker_id
= len(self
.workers
)
245 if worker_id
< self
.config
["global"]["server.ns_threads"]:
246 # create a new worker
248 NsWorker(worker_id
, self
.config
, self
.plugins
, self
.db
)
250 self
.workers
[worker_id
].start()
252 # reached maximum number of threads, assign VIM to an existing one
253 worker_id
= self
.next_worker
254 self
.next_worker
= (self
.next_worker
+ 1) % self
.config
["global"][
260 def assign_vim(self
, target_id
):
261 with self
.write_lock
:
262 return self
._assign
_vim
(target_id
)
264 def _assign_vim(self
, target_id
):
265 if target_id
not in self
.vims_assigned
:
266 worker_id
= self
.vims_assigned
[target_id
] = self
._create
_worker
()
267 self
.workers
[worker_id
].insert_task(("load_vim", target_id
))
269 def reload_vim(self
, target_id
):
270 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
271 # this is because database VIM information is cached for threads working with SDN
272 with self
.write_lock
:
273 for worker
in self
.workers
:
274 if worker
and not worker
.idle
:
275 worker
.insert_task(("reload_vim", target_id
))
277 def unload_vim(self
, target_id
):
278 with self
.write_lock
:
279 return self
._unload
_vim
(target_id
)
281 def _unload_vim(self
, target_id
):
282 if target_id
in self
.vims_assigned
:
283 worker_id
= self
.vims_assigned
[target_id
]
284 self
.workers
[worker_id
].insert_task(("unload_vim", target_id
))
285 del self
.vims_assigned
[target_id
]
287 def check_vim(self
, target_id
):
288 with self
.write_lock
:
289 if target_id
in self
.vims_assigned
:
290 worker_id
= self
.vims_assigned
[target_id
]
292 worker_id
= self
._create
_worker
()
294 worker
= self
.workers
[worker_id
]
295 worker
.insert_task(("check_vim", target_id
))
297 def unload_unused_vims(self
):
298 with self
.write_lock
:
301 for target_id
in self
.vims_assigned
:
302 if not self
.db
.get_one(
305 "target_id": target_id
,
306 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
310 vims_to_unload
.append(target_id
)
312 for target_id
in vims_to_unload
:
313 self
._unload
_vim
(target_id
)
321 """This method reads cloud init from a file.
323 Note: Not used as cloud init content is provided in the http body.
326 db (Type[DbBase]): [description]
327 fs (Type[FsBase]): [description]
328 location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
331 NsException: [description]
332 NsException: [description]
337 vnfd_id
, _
, other
= location
.partition(":")
338 _type
, _
, name
= other
.partition(":")
339 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
342 base_folder
= vnfd
["_admin"]["storage"]
343 cloud_init_file
= "{}/{}/cloud_init/{}".format(
344 base_folder
["folder"], base_folder
["pkg-dir"], name
349 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
354 with fs
.file_open(cloud_init_file
, "r") as ci_file
:
355 cloud_init_content
= ci_file
.read()
357 cloud_init_content
= vnfd
["vdu"][int(name
)]["cloud-init"]
359 raise NsException("Mismatch descriptor for cloud init: {}".format(location
))
361 return cloud_init_content
365 cloud_init_content
: str,
366 params
: Dict
[str, Any
],
369 """Function that processes the cloud init to replace Jinja2 encoded parameters.
372 cloud_init_content (str): [description]
373 params (Dict[str, Any]): [description]
374 context (str): [description]
377 NsException: [description]
378 NsException: [description]
385 undefined
=StrictUndefined
,
386 autoescape
=select_autoescape(default_for_string
=True, default
=True),
388 template
= env
.from_string(cloud_init_content
)
390 return template
.render(params
or {})
391 except UndefinedError
as e
:
393 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
394 "inside the 'additionalParamsForVnf' block".format(e
, context
)
396 except (TemplateError
, TemplateNotFound
) as e
:
398 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
403 def _create_db_ro_nsrs(self
, nsr_id
, now
):
405 key
= rsa
.generate_private_key(
406 backend
=crypto_default_backend(), public_exponent
=65537, key_size
=2048
408 private_key
= key
.private_bytes(
409 crypto_serialization
.Encoding
.PEM
,
410 crypto_serialization
.PrivateFormat
.PKCS8
,
411 crypto_serialization
.NoEncryption(),
413 public_key
= key
.public_key().public_bytes(
414 crypto_serialization
.Encoding
.OpenSSH
,
415 crypto_serialization
.PublicFormat
.OpenSSH
,
417 private_key
= private_key
.decode("utf8")
418 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
419 i
= private_key
.find("\n")
420 private_key
= "-----BEGIN RSA PRIVATE KEY-----" + private_key
[i
:]
421 public_key
= public_key
.decode("utf8")
422 except Exception as e
:
423 raise NsException("Cannot create ssh-keys: {}".format(e
))
425 schema_version
= "1.1"
426 private_key_encrypted
= self
.db
.encrypt(
427 private_key
, schema_version
=schema_version
, salt
=nsr_id
434 "schema_version": schema_version
,
436 "public_key": public_key
,
437 "private_key": private_key_encrypted
,
440 self
.db
.create("ro_nsrs", db_content
)
446 deployment_info
: Dict
[str, Any
],
451 target_record_id
: str,
452 extra_dict
: Dict
[str, Any
] = None,
454 """Function to create task dict from deployment information.
457 deployment_info (Dict[str, Any]): [description]
458 target_id (str): [description]
459 item (str): [description]
460 action (str): [description]
461 target_record (str): [description]
462 target_record_id (str): [description]
463 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
466 Dict[str, Any]: [description]
469 "target_id": target_id
, # it will be removed before pushing at database
470 "action_id": deployment_info
.get("action_id"),
471 "nsr_id": deployment_info
.get("nsr_id"),
472 "task_id": f
"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
473 "status": "SCHEDULED",
476 "target_record": target_record
,
477 "target_record_id": target_record_id
,
481 task
.update(extra_dict
) # params, find_params, depends_on
483 deployment_info
["task_index"] = deployment_info
.get("task_index", 0) + 1
490 task
: Dict
[str, Any
],
492 """Function to create an RO task from task information.
495 target_id (str): [description]
496 task (Dict[str, Any]): [description]
499 Dict[str, Any]: [description]
503 _id
= task
.get("task_id")
508 "target_id": target_id
,
511 "created_items": None,
528 def _process_image_params(
529 target_image
: Dict
[str, Any
],
530 indata
: Dict
[str, Any
],
531 vim_info
: Dict
[str, Any
],
532 target_record_id
: str,
533 **kwargs
: Dict
[str, Any
],
535 """Function to process VDU image parameters.
538 target_image (Dict[str, Any]): [description]
539 indata (Dict[str, Any]): [description]
540 vim_info (Dict[str, Any]): [description]
541 target_record_id (str): [description]
544 Dict[str, Any]: [description]
548 if target_image
.get("image"):
549 find_params
["filter_dict"] = {"name": target_image
.get("image")}
551 if target_image
.get("vim_image_id"):
552 find_params
["filter_dict"] = {"id": target_image
.get("vim_image_id")}
554 if target_image
.get("image_checksum"):
555 find_params
["filter_dict"] = {
556 "checksum": target_image
.get("image_checksum")
559 return {"find_params": find_params
}
562 def _get_resource_allocation_params(
563 quota_descriptor
: Dict
[str, Any
],
565 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
569 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
572 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
576 if quota_descriptor
.get("limit"):
577 quota
["limit"] = int(quota_descriptor
["limit"])
579 if quota_descriptor
.get("reserve"):
580 quota
["reserve"] = int(quota_descriptor
["reserve"])
582 if quota_descriptor
.get("shares"):
583 quota
["shares"] = int(quota_descriptor
["shares"])
588 def _process_guest_epa_quota_params(
589 guest_epa_quota
: Dict
[str, Any
],
592 """Function to extract the guest epa quota parameters.
595 guest_epa_quota (Dict[str, Any]): [description]
596 epa_vcpu_set (bool): [description]
599 Dict[str, Any]: [description]
603 if guest_epa_quota
.get("cpu-quota") and not epa_vcpu_set
:
604 cpuquota
= Ns
._get
_resource
_allocation
_params
(
605 guest_epa_quota
.get("cpu-quota")
609 result
["cpu-quota"] = cpuquota
611 if guest_epa_quota
.get("mem-quota"):
612 vduquota
= Ns
._get
_resource
_allocation
_params
(
613 guest_epa_quota
.get("mem-quota")
617 result
["mem-quota"] = vduquota
619 if guest_epa_quota
.get("disk-io-quota"):
620 diskioquota
= Ns
._get
_resource
_allocation
_params
(
621 guest_epa_quota
.get("disk-io-quota")
625 result
["disk-io-quota"] = diskioquota
627 if guest_epa_quota
.get("vif-quota"):
628 vifquota
= Ns
._get
_resource
_allocation
_params
(
629 guest_epa_quota
.get("vif-quota")
633 result
["vif-quota"] = vifquota
638 def _process_guest_epa_numa_params(
639 guest_epa_quota
: Dict
[str, Any
],
640 ) -> Tuple
[Dict
[str, Any
], bool]:
644 guest_epa_quota (Dict[str, Any]): [description]
647 Tuple[Dict[str, Any], bool]: [description]
652 if guest_epa_quota
.get("numa-node-policy"):
653 numa_node_policy
= guest_epa_quota
.get("numa-node-policy")
655 if numa_node_policy
.get("node"):
656 numa_node
= numa_node_policy
["node"][0]
658 if numa_node
.get("num-cores"):
659 numa
["cores"] = numa_node
["num-cores"]
662 paired_threads
= numa_node
.get("paired-threads", {})
663 if paired_threads
.get("num-paired-threads"):
664 numa
["paired-threads"] = int(
665 numa_node
["paired-threads"]["num-paired-threads"]
669 if paired_threads
.get("paired-thread-ids"):
670 numa
["paired-threads-id"] = []
672 for pair
in paired_threads
["paired-thread-ids"]:
673 numa
["paired-threads-id"].append(
675 str(pair
["thread-a"]),
676 str(pair
["thread-b"]),
680 if numa_node
.get("num-threads"):
681 numa
["threads"] = int(numa_node
["num-threads"])
684 if numa_node
.get("memory-mb"):
685 numa
["memory"] = max(int(int(numa_node
["memory-mb"]) / 1024), 1)
687 return numa
, epa_vcpu_set
690 def _process_guest_epa_cpu_pinning_params(
691 guest_epa_quota
: Dict
[str, Any
],
694 ) -> Tuple
[Dict
[str, Any
], bool]:
698 guest_epa_quota (Dict[str, Any]): [description]
699 vcpu_count (int): [description]
700 epa_vcpu_set (bool): [description]
703 Tuple[Dict[str, Any], bool]: [description]
706 local_epa_vcpu_set
= epa_vcpu_set
709 guest_epa_quota
.get("cpu-pinning-policy") == "DEDICATED"
714 if guest_epa_quota
.get("cpu-thread-pinning-policy") != "PREFER"
716 ] = max(vcpu_count
, 1)
717 local_epa_vcpu_set
= True
719 return numa
, local_epa_vcpu_set
722 def _process_epa_params(
723 target_flavor
: Dict
[str, Any
],
728 target_flavor (Dict[str, Any]): [description]
731 Dict[str, Any]: [description]
736 if target_flavor
.get("guest-epa"):
737 guest_epa
= target_flavor
["guest-epa"]
739 numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_numa
_params
(
740 guest_epa_quota
=guest_epa
743 if guest_epa
.get("mempage-size"):
744 extended
["mempage-size"] = guest_epa
.get("mempage-size")
746 tmp_numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_cpu
_pinning
_params
(
747 guest_epa_quota
=guest_epa
,
748 vcpu_count
=int(target_flavor
.get("vcpu-count", 1)),
749 epa_vcpu_set
=epa_vcpu_set
,
751 numa
.update(tmp_numa
)
754 Ns
._process
_guest
_epa
_quota
_params
(
755 guest_epa_quota
=guest_epa
,
756 epa_vcpu_set
=epa_vcpu_set
,
761 extended
["numas"] = [numa
]
766 def _process_flavor_params(
767 target_flavor
: Dict
[str, Any
],
768 indata
: Dict
[str, Any
],
769 vim_info
: Dict
[str, Any
],
770 target_record_id
: str,
771 **kwargs
: Dict
[str, Any
],
776 target_flavor (Dict[str, Any]): [description]
777 indata (Dict[str, Any]): [description]
778 vim_info (Dict[str, Any]): [description]
779 target_record_id (str): [description]
782 Dict[str, Any]: [description]
784 db
= kwargs
.get("db")
788 "disk": int(target_flavor
["storage-gb"]),
789 "ram": int(target_flavor
["memory-mb"]),
790 "vcpus": int(target_flavor
["vcpu-count"]),
793 for vnf
in indata
.get("vnf", []):
794 for vdur
in vnf
.get("vdur", []):
795 if vdur
.get("ns-flavor-id") == target_flavor
.get("id"):
798 if db
and isinstance(indata
.get("vnf"), list):
799 vnfd_id
= indata
.get("vnf")[0].get("vnfd-id")
800 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
801 # check if there is persistent root disk
802 for vdu
in vnfd
.get("vdu", ()):
803 if vdu
["name"] == target_vdur
.get("vdu-name"):
804 for vsd
in vnfd
.get("virtual-storage-desc", ()):
805 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
808 root_disk
.get("type-of-storage")
809 == "persistent-storage:persistent-storage"
811 flavor_data
["disk"] = 0
813 for storage
in target_vdur
.get("virtual-storages", []):
815 storage
.get("type-of-storage")
816 == "etsi-nfv-descriptors:ephemeral-storage"
818 flavor_data
["ephemeral"] = int(storage
.get("size-of-storage", 0))
819 elif storage
.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
820 flavor_data
["swap"] = int(storage
.get("size-of-storage", 0))
822 extended
= Ns
._process
_epa
_params
(target_flavor
)
824 flavor_data
["extended"] = extended
826 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
827 flavor_data_name
= flavor_data
.copy()
828 flavor_data_name
["name"] = target_flavor
["name"]
829 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
834 def _ip_profile_to_ro(
835 ip_profile
: Dict
[str, Any
],
840 ip_profile (Dict[str, Any]): [description]
843 Dict[str, Any]: [description]
850 if "v4" in ip_profile
.get("ip-version", "ipv4")
852 "subnet_address": ip_profile
.get("subnet-address"),
853 "gateway_address": ip_profile
.get("gateway-address"),
854 "dhcp_enabled": ip_profile
.get("dhcp-params", {}).get("enabled", False),
855 "dhcp_start_address": ip_profile
.get("dhcp-params", {}).get(
856 "start-address", None
858 "dhcp_count": ip_profile
.get("dhcp-params", {}).get("count", None),
861 if ip_profile
.get("dns-server"):
862 ro_ip_profile
["dns_address"] = ";".join(
863 [v
["address"] for v
in ip_profile
["dns-server"] if v
.get("address")]
866 if ip_profile
.get("security-group"):
867 ro_ip_profile
["security_group"] = ip_profile
["security-group"]
872 def _process_net_params(
873 target_vld
: Dict
[str, Any
],
874 indata
: Dict
[str, Any
],
875 vim_info
: Dict
[str, Any
],
876 target_record_id
: str,
877 **kwargs
: Dict
[str, Any
],
879 """Function to process network parameters.
882 target_vld (Dict[str, Any]): [description]
883 indata (Dict[str, Any]): [description]
884 vim_info (Dict[str, Any]): [description]
885 target_record_id (str): [description]
888 Dict[str, Any]: [description]
892 if vim_info
.get("sdn"):
893 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
894 # ns_preffix = "nsrs:{}".format(nsr_id)
895 # remove the ending ".sdn
896 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
897 extra_dict
["params"] = {
899 for k
in ("sdn-ports", "target_vim", "vlds", "type")
903 # TODO needed to add target_id in the dependency.
904 if vim_info
.get("target_vim"):
905 extra_dict
["depends_on"] = [
906 f
"{vim_info.get('target_vim')} {vld_target_record_id}"
911 if vim_info
.get("vim_network_name"):
912 extra_dict
["find_params"] = {
914 "name": vim_info
.get("vim_network_name"),
917 elif vim_info
.get("vim_network_id"):
918 extra_dict
["find_params"] = {
920 "id": vim_info
.get("vim_network_id"),
923 elif target_vld
.get("mgmt-network") and not vim_info
.get("provider_network"):
924 extra_dict
["find_params"] = {
926 "name": target_vld
["id"],
930 extra_dict
["params"] = {
932 f
"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
934 "ip_profile": Ns
._ip
_profile
_to
_ro
(vim_info
.get("ip_profile")),
935 "provider_network_profile": vim_info
.get("provider_network"),
938 if not target_vld
.get("underlay"):
939 extra_dict
["params"]["net_type"] = "bridge"
941 extra_dict
["params"]["net_type"] = (
942 "ptp" if target_vld
.get("type") == "ELINE" else "data"
948 def find_persistent_root_volumes(
951 vdu_instantiation_volumes_list
: list,
954 """Find the persistent root volumes and add them to the disk_list
955 by parsing the instantiation parameters
959 target_vdu: processed VDU
960 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
961 disk_list: to be filled up
964 disk_list: filled VDU list which is used for VDU creation
967 persistent_root_disk
= {}
969 for vdu
, vsd
in product(
970 vnfd
.get("vdu", ()), vnfd
.get("virtual-storage-desc", ())
973 vdu
["name"] == target_vdu
["vdu-name"]
974 and vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]
978 root_disk
.get("type-of-storage")
979 == "persistent-storage:persistent-storage"
981 for vdu_volume
in vdu_instantiation_volumes_list
:
984 vdu_volume
["vim-volume-id"]
985 and root_disk
["id"] == vdu_volume
["name"]
988 persistent_root_disk
[vsd
["id"]] = {
989 "vim_volume_id": vdu_volume
["vim-volume-id"],
990 "image_id": vdu
.get("sw-image-desc"),
993 disk_list
.append(persistent_root_disk
[vsd
["id"]])
995 # There can be only one root disk, when we find it, it will return the result
996 return disk_list
, persistent_root_disk
1000 if root_disk
.get("size-of-storage"):
1001 persistent_root_disk
[vsd
["id"]] = {
1002 "image_id": vdu
.get("sw-image-desc"),
1003 "size": root_disk
.get("size-of-storage"),
1006 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1007 return disk_list
, persistent_root_disk
1009 return disk_list
, persistent_root_disk
1012 def find_persistent_volumes(
1013 persistent_root_disk
: dict,
1015 vdu_instantiation_volumes_list
: list,
1018 """Find the ordinary persistent volumes and add them to the disk_list
1019 by parsing the instantiation parameters
1022 persistent_root_disk: persistent root disk dictionary
1023 target_vdu: processed VDU
1024 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1025 disk_list: to be filled up
1028 disk_list: filled VDU list which is used for VDU creation
1031 # Find the ordinary volumes which are not added to the persistent_root_disk
1032 persistent_disk
= {}
1033 for disk
in target_vdu
.get("virtual-storages", {}):
1035 disk
.get("type-of-storage") == "persistent-storage:persistent-storage"
1036 and disk
["id"] not in persistent_root_disk
.keys()
1038 for vdu_volume
in vdu_instantiation_volumes_list
:
1040 if vdu_volume
["vim-volume-id"] and disk
["id"] == vdu_volume
["name"]:
1042 persistent_disk
[disk
["id"]] = {
1043 "vim_volume_id": vdu_volume
["vim-volume-id"],
1045 disk_list
.append(persistent_disk
[disk
["id"]])
1048 if disk
["id"] not in persistent_disk
.keys():
1049 persistent_disk
[disk
["id"]] = {
1050 "size": disk
.get("size-of-storage"),
1052 disk_list
.append(persistent_disk
[disk
["id"]])
1057 def _process_vdu_params(
1058 target_vdu
: Dict
[str, Any
],
1059 indata
: Dict
[str, Any
],
1060 vim_info
: Dict
[str, Any
],
1061 target_record_id
: str,
1062 **kwargs
: Dict
[str, Any
],
1063 ) -> Dict
[str, Any
]:
1064 """Function to process VDU parameters.
1067 target_vdu (Dict[str, Any]): [description]
1068 indata (Dict[str, Any]): [description]
1069 vim_info (Dict[str, Any]): [description]
1070 target_record_id (str): [description]
1073 Dict[str, Any]: [description]
1075 vnfr_id
= kwargs
.get("vnfr_id")
1076 nsr_id
= kwargs
.get("nsr_id")
1077 vnfr
= kwargs
.get("vnfr")
1078 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1079 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
1080 logger
= kwargs
.get("logger")
1081 db
= kwargs
.get("db")
1082 fs
= kwargs
.get("fs")
1083 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1085 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
1086 ns_preffix
= "nsrs:{}".format(nsr_id
)
1087 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
1088 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
1089 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
1092 # If the position info is provided for all the interfaces, it will be sorted
1093 # according to position number ascendingly.
1095 i
.get("position") + 1
1096 for i
in target_vdu
["interfaces"]
1097 if i
.get("position") is not None
1099 sorted_interfaces
= sorted(
1100 target_vdu
["interfaces"],
1101 key
=lambda x
: (x
.get("position") is None, x
.get("position")),
1103 target_vdu
["interfaces"] = sorted_interfaces
1105 # If the position info is provided for some interfaces but not all of them, the interfaces
1106 # which has specific position numbers will be placed and others' positions will not be taken care.
1109 i
.get("position") + 1
1110 for i
in target_vdu
["interfaces"]
1111 if i
.get("position") is not None
1113 n
= len(target_vdu
["interfaces"])
1114 sorted_interfaces
= [-1] * n
1117 if target_vdu
["interfaces"][k
].get("position"):
1118 idx
= target_vdu
["interfaces"][k
]["position"]
1119 sorted_interfaces
[idx
- 1] = target_vdu
["interfaces"][k
]
1122 if not target_vdu
["interfaces"][m
].get("position"):
1123 idy
= sorted_interfaces
.index(-1)
1124 sorted_interfaces
[idy
] = target_vdu
["interfaces"][m
]
1127 target_vdu
["interfaces"] = sorted_interfaces
1129 # If the position info is not provided for the interfaces, interfaces will be attached
1130 # according to the order in the VNFD.
1131 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
1132 if interface
.get("ns-vld-id"):
1133 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
1134 elif interface
.get("vnf-vld-id"):
1135 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
1138 "Interface {} from vdu {} not connected to any vld".format(
1139 iface_index
, target_vdu
["vdu-name"]
1143 continue # interface not connected to any vld
1145 extra_dict
["depends_on"].append(net_text
)
1147 if "port-security-enabled" in interface
:
1148 interface
["port_security"] = interface
.pop("port-security-enabled")
1150 if "port-security-disable-strategy" in interface
:
1151 interface
["port_security_disable_strategy"] = interface
.pop(
1152 "port-security-disable-strategy"
1157 for x
, v
in interface
.items()
1163 "port_security_disable_strategy",
1167 net_item
["net_id"] = "TASK-" + net_text
1168 net_item
["type"] = "virtual"
1170 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1171 # TODO floating_ip: True/False (or it can be None)
1172 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1173 # mark the net create task as type data
1175 tasks_by_target_record_id
,
1181 tasks_by_target_record_id
[net_text
]["extra_dict"]["params"][
1185 net_item
["use"] = "data"
1186 net_item
["model"] = interface
["type"]
1187 net_item
["type"] = interface
["type"]
1189 interface
.get("type") == "OM-MGMT"
1190 or interface
.get("mgmt-interface")
1191 or interface
.get("mgmt-vnf")
1193 net_item
["use"] = "mgmt"
1195 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1196 net_item
["use"] = "bridge"
1197 net_item
["model"] = interface
.get("type")
1199 if interface
.get("ip-address"):
1200 net_item
["ip_address"] = interface
["ip-address"]
1202 if interface
.get("mac-address"):
1203 net_item
["mac_address"] = interface
["mac-address"]
1205 net_list
.append(net_item
)
1207 if interface
.get("mgmt-vnf"):
1208 extra_dict
["mgmt_vnf_interface"] = iface_index
1209 elif interface
.get("mgmt-interface"):
1210 extra_dict
["mgmt_vdu_interface"] = iface_index
1215 if target_vdu
.get("cloud-init"):
1216 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1217 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1220 location
=target_vdu
["cloud-init"],
1223 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1224 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1225 cloud_init_content
=cloud_content_
,
1226 params
=target_vdu
.get("additionalParams"),
1227 context
=target_vdu
["cloud-init"],
1230 if target_vdu
.get("boot-data-drive"):
1231 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1235 if target_vdu
.get("ssh-keys"):
1236 ssh_keys
+= target_vdu
.get("ssh-keys")
1238 if target_vdu
.get("ssh-access-required"):
1239 ssh_keys
.append(ro_nsr_public_key
)
1242 cloud_config
["key-pairs"] = ssh_keys
1244 persistent_root_disk
= {}
1245 vdu_instantiation_volumes_list
= []
1247 vnfd_id
= vnfr
["vnfd-id"]
1248 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
1250 if target_vdu
.get("additionalParams"):
1251 vdu_instantiation_volumes_list
= (
1252 target_vdu
.get("additionalParams").get("OSM").get("vdu_volumes")
1255 if vdu_instantiation_volumes_list
:
1257 # Find the root volumes and add to the disk_list
1258 (disk_list
, persistent_root_disk
,) = Ns
.find_persistent_root_volumes(
1259 vnfd
, target_vdu
, vdu_instantiation_volumes_list
, disk_list
1262 # Find the ordinary volumes which are not added to the persistent_root_disk
1263 # and put them to the disk list
1264 disk_list
= Ns
.find_persistent_volumes(
1265 persistent_root_disk
,
1267 vdu_instantiation_volumes_list
,
1273 # vdu_instantiation_volumes_list is empty
1274 for vdu
in vnfd
.get("vdu", ()):
1275 if vdu
["name"] == target_vdu
["vdu-name"]:
1276 for vsd
in vnfd
.get("virtual-storage-desc", ()):
1277 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
1281 ) == "persistent-storage:persistent-storage" and root_disk
.get(
1284 persistent_root_disk
[vsd
["id"]] = {
1285 "image_id": vdu
.get("sw-image-desc"),
1286 "size": root_disk
["size-of-storage"],
1288 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1290 if target_vdu
.get("virtual-storages"):
1291 for disk
in target_vdu
["virtual-storages"]:
1293 disk
.get("type-of-storage")
1294 == "persistent-storage:persistent-storage"
1295 and disk
["id"] not in persistent_root_disk
.keys()
1297 disk_list
.append({"size": disk
["size-of-storage"]})
1299 affinity_group_list
= []
1301 if target_vdu
.get("affinity-or-anti-affinity-group-id"):
1303 for affinity_group_id
in target_vdu
["affinity-or-anti-affinity-group-id"]:
1304 affinity_group_text
= (
1305 ns_preffix
+ ":affinity-or-anti-affinity-group." + affinity_group_id
1308 extra_dict
["depends_on"].append(affinity_group_text
)
1309 affinity_group
["affinity_group_id"] = "TASK-" + affinity_group_text
1310 affinity_group_list
.append(affinity_group
)
1312 extra_dict
["params"] = {
1313 "name": "{}-{}-{}-{}".format(
1314 indata
["name"][:16],
1315 vnfr
["member-vnf-index-ref"][:16],
1316 target_vdu
["vdu-name"][:32],
1317 target_vdu
.get("count-index") or 0,
1319 "description": target_vdu
["vdu-name"],
1321 "image_id": "TASK-" + image_text
,
1322 "flavor_id": "TASK-" + flavor_text
,
1323 "affinity_group_list": affinity_group_list
,
1324 "net_list": net_list
,
1325 "cloud_config": cloud_config
or None,
1326 "disk_list": disk_list
,
1327 "availability_zone_index": None, # TODO
1328 "availability_zone_list": None, # TODO
1334 def _process_affinity_group_params(
1335 target_affinity_group
: Dict
[str, Any
],
1336 indata
: Dict
[str, Any
],
1337 vim_info
: Dict
[str, Any
],
1338 target_record_id
: str,
1339 **kwargs
: Dict
[str, Any
],
1340 ) -> Dict
[str, Any
]:
1341 """Get affinity or anti-affinity group parameters.
1344 target_affinity_group (Dict[str, Any]): [description]
1345 indata (Dict[str, Any]): [description]
1346 vim_info (Dict[str, Any]): [description]
1347 target_record_id (str): [description]
1350 Dict[str, Any]: [description]
1354 affinity_group_data
= {
1355 "name": target_affinity_group
["name"],
1356 "type": target_affinity_group
["type"],
1357 "scope": target_affinity_group
["scope"],
1360 if target_affinity_group
.get("vim-affinity-group-id"):
1361 affinity_group_data
["vim-affinity-group-id"] = target_affinity_group
[
1362 "vim-affinity-group-id"
1365 extra_dict
["params"] = {
1366 "affinity_group_data": affinity_group_data
,
1372 def _process_recreate_vdu_params(
1373 existing_vdu
: Dict
[str, Any
],
1374 db_nsr
: Dict
[str, Any
],
1375 vim_info
: Dict
[str, Any
],
1376 target_record_id
: str,
1378 **kwargs
: Dict
[str, Any
],
1379 ) -> Dict
[str, Any
]:
1380 """Function to process VDU parameters to recreate.
1383 existing_vdu (Dict[str, Any]): [description]
1384 db_nsr (Dict[str, Any]): [description]
1385 vim_info (Dict[str, Any]): [description]
1386 target_record_id (str): [description]
1387 target_id (str): [description]
1390 Dict[str, Any]: [description]
1392 vnfr
= kwargs
.get("vnfr")
1393 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1394 # logger = kwargs.get("logger")
1395 db
= kwargs
.get("db")
1396 fs
= kwargs
.get("fs")
1397 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1403 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
1404 if vim_details_text
:
1405 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
1407 for iface_index
, interface
in enumerate(existing_vdu
["interfaces"]):
1409 if "port-security-enabled" in interface
:
1410 interface
["port_security"] = interface
.pop("port-security-enabled")
1412 if "port-security-disable-strategy" in interface
:
1413 interface
["port_security_disable_strategy"] = interface
.pop(
1414 "port-security-disable-strategy"
1419 for x
, v
in interface
.items()
1425 "port_security_disable_strategy",
1429 existing_ifaces
= existing_vdu
["vim_info"][target_id
].get(
1430 "interfaces_backup", []
1435 for i
in existing_ifaces
1436 if i
["ip_address"] == interface
["ip-address"]
1441 net_item
["net_id"] = net_id
1442 net_item
["type"] = "virtual"
1444 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1445 # TODO floating_ip: True/False (or it can be None)
1446 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1447 net_item
["use"] = "data"
1448 net_item
["model"] = interface
["type"]
1449 net_item
["type"] = interface
["type"]
1451 interface
.get("type") == "OM-MGMT"
1452 or interface
.get("mgmt-interface")
1453 or interface
.get("mgmt-vnf")
1455 net_item
["use"] = "mgmt"
1457 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1458 net_item
["use"] = "bridge"
1459 net_item
["model"] = interface
.get("type")
1461 if interface
.get("ip-address"):
1462 net_item
["ip_address"] = interface
["ip-address"]
1464 if interface
.get("mac-address"):
1465 net_item
["mac_address"] = interface
["mac-address"]
1467 net_list
.append(net_item
)
1469 if interface
.get("mgmt-vnf"):
1470 extra_dict
["mgmt_vnf_interface"] = iface_index
1471 elif interface
.get("mgmt-interface"):
1472 extra_dict
["mgmt_vdu_interface"] = iface_index
1477 if existing_vdu
.get("cloud-init"):
1478 if existing_vdu
["cloud-init"] not in vdu2cloud_init
:
1479 vdu2cloud_init
[existing_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1482 location
=existing_vdu
["cloud-init"],
1485 cloud_content_
= vdu2cloud_init
[existing_vdu
["cloud-init"]]
1486 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1487 cloud_init_content
=cloud_content_
,
1488 params
=existing_vdu
.get("additionalParams"),
1489 context
=existing_vdu
["cloud-init"],
1492 if existing_vdu
.get("boot-data-drive"):
1493 cloud_config
["boot-data-drive"] = existing_vdu
.get("boot-data-drive")
1497 if existing_vdu
.get("ssh-keys"):
1498 ssh_keys
+= existing_vdu
.get("ssh-keys")
1500 if existing_vdu
.get("ssh-access-required"):
1501 ssh_keys
.append(ro_nsr_public_key
)
1504 cloud_config
["key-pairs"] = ssh_keys
1507 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
1508 disk_list
.append({"vim_id": vol_id
["id"]})
1510 affinity_group_list
= []
1512 if existing_vdu
.get("affinity-or-anti-affinity-group-id"):
1514 for affinity_group_id
in existing_vdu
["affinity-or-anti-affinity-group-id"]:
1515 for group
in db_nsr
.get("affinity-or-anti-affinity-group"):
1517 group
["id"] == affinity_group_id
1518 and group
["vim_info"][target_id
].get("vim_id", None) is not None
1520 affinity_group
["affinity_group_id"] = group
["vim_info"][
1522 ].get("vim_id", None)
1523 affinity_group_list
.append(affinity_group
)
1525 extra_dict
["params"] = {
1526 "name": "{}-{}-{}-{}".format(
1527 db_nsr
["name"][:16],
1528 vnfr
["member-vnf-index-ref"][:16],
1529 existing_vdu
["vdu-name"][:32],
1530 existing_vdu
.get("count-index") or 0,
1532 "description": existing_vdu
["vdu-name"],
1534 "image_id": vim_details
["image"]["id"],
1535 "flavor_id": vim_details
["flavor"]["id"],
1536 "affinity_group_list": affinity_group_list
,
1537 "net_list": net_list
,
1538 "cloud_config": cloud_config
or None,
1539 "disk_list": disk_list
,
1540 "availability_zone_index": None, # TODO
1541 "availability_zone_list": None, # TODO
1546 def calculate_diff_items(
1553 tasks_by_target_record_id
,
1560 """Function that returns the incremental changes (creation, deletion)
1561 related to a specific item `item` to be done. This function should be
1562 called for NS instantiation, NS termination, NS update to add a new VNF
1563 or a new VLD, remove a VNF or VLD, etc.
1564 Item can be `net`, `flavor`, `image` or `vdu`.
1565 It takes a list of target items from indata (which came from the REST API)
1566 and compares with the existing items from db_ro_nsr, identifying the
1567 incremental changes to be done. During the comparison, it calls the method
1568 `process_params` (which was passed as parameter, and is particular for each
1572 indata (Dict[str, Any]): deployment info
1573 db_nsr: NSR record from DB
1574 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1575 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1576 item (str): element to process (net, vdu...)
1577 tasks_by_target_record_id (Dict[str, Any]):
1578 [<target_record_id>, <task>]
1579 action_id (str): action id
1580 nsr_id (str): NSR id
1581 task_index (number): task index to add to task name
1582 vnfr_id (str): VNFR id
1583 vnfr (Dict[str, Any]): VNFR info
1586 List: list with the incremental changes (deletes, creates) for each item
1587 number: current task index
1595 process_params
= None
1596 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1597 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1599 # According to the type of item, the path, the target_list,
1600 # the existing_list and the method to process params are set
1601 db_path
= self
.db_path_map
[item
]
1602 process_params
= self
.process_params_function_map
[item
]
1603 if item
in ("net", "vdu"):
1604 # This case is specific for the NS VLD (not applied to VDU)
1606 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1607 target_list
= indata
.get("ns", []).get(db_path
, [])
1608 existing_list
= db_nsr
.get(db_path
, [])
1609 # This case is common for VNF VLDs and VNF VDUs
1611 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
1613 (vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
),
1616 target_list
= target_vnf
.get(db_path
, []) if target_vnf
else []
1617 existing_list
= vnfr
.get(db_path
, [])
1618 elif item
in ("image", "flavor", "affinity-or-anti-affinity-group"):
1619 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1620 target_list
= indata
.get(item
, [])
1621 existing_list
= db_nsr
.get(item
, [])
1623 raise NsException("Item not supported: {}", item
)
1625 # ensure all the target_list elements has an "id". If not assign the index as id
1626 if target_list
is None:
1628 for target_index
, tl
in enumerate(target_list
):
1629 if tl
and not tl
.get("id"):
1630 tl
["id"] = str(target_index
)
1632 # step 1 items (networks,vdus,...) to be deleted/updated
1633 for item_index
, existing_item
in enumerate(existing_list
):
1635 (t
for t
in target_list
if t
["id"] == existing_item
["id"]),
1639 for target_vim
, existing_viminfo
in existing_item
.get(
1642 if existing_viminfo
is None:
1646 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
1648 target_viminfo
= None
1650 if target_viminfo
is None:
1652 self
._assign
_vim
(target_vim
)
1653 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
1656 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
1657 # item must be sdn-net instead of net if target_vim is a sdn
1659 target_record_id
+= ".sdn"
1662 "action_id": action_id
,
1664 "task_index": task_index
,
1669 "deployment_info": deployment_info
,
1670 "target_id": target_vim
,
1673 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1674 "target_record_id": target_record_id
,
1679 # step 2 items (networks,vdus,...) to be created
1680 for target_item
in target_list
:
1683 for item_index
, existing_item
in enumerate(existing_list
):
1684 if existing_item
["id"] == target_item
["id"]:
1688 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1689 existing_list
.append(target_item
)
1690 existing_item
= None
1692 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
1693 existing_viminfo
= None
1696 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
1698 if existing_viminfo
is not None:
1701 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
1704 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
1705 # item must be sdn-net instead of net if target_vim is a sdn
1707 target_record_id
+= ".sdn"
1710 self
.logger
.warning(
1711 "ns.calculate_diff_items target_item={}".format(target_item
)
1713 if process_params
== Ns
._process
_flavor
_params
:
1719 self
.logger
.warning(
1720 "calculate_diff_items for flavor kwargs={}".format(kwargs
)
1723 if process_params
== Ns
._process
_vdu
_params
:
1724 self
.logger
.warning(
1725 "calculate_diff_items self.fs={}".format(self
.fs
)
1732 "vdu2cloud_init": vdu2cloud_init
,
1733 "tasks_by_target_record_id": tasks_by_target_record_id
,
1734 "logger": self
.logger
,
1737 "ro_nsr_public_key": ro_nsr_public_key
,
1740 self
.logger
.warning("calculate_diff_items kwargs={}".format(kwargs
))
1742 extra_dict
= process_params(
1749 self
._assign
_vim
(target_vim
)
1752 "action_id": action_id
,
1754 "task_index": task_index
,
1758 "deployment_info": deployment_info
,
1759 "target_id": target_vim
,
1762 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1763 "target_record_id": target_record_id
,
1764 "extra_dict": extra_dict
,
1765 "common_id": target_item
.get("common_id", None),
1767 diff_items
.append(new_item
)
1768 tasks_by_target_record_id
[target_record_id
] = new_item
1771 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1773 return diff_items
, task_index
1775 def calculate_all_differences_to_deploy(
1785 tasks_by_target_record_id
,
1787 """This method calculates the ordered list of items (`changes_list`)
1788 to be created and deleted.
1791 indata (Dict[str, Any]): deployment info
1792 nsr_id (str): NSR id
1793 db_nsr: NSR record from DB
1794 db_vnfrs: VNFRS record from DB
1795 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1796 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1797 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
1798 action_id (str): action id
1799 tasks_by_target_record_id (Dict[str, Any]):
1800 [<target_record_id>, <task>]
1803 List: ordered list of items to be created and deleted.
1807 # set list with diffs:
1810 # NS vld, image and flavor
1811 for item
in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
1812 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
1813 diff_items
, task_index
= self
.calculate_diff_items(
1816 db_ro_nsr
=db_ro_nsr
,
1817 db_nsr_update
=db_nsr_update
,
1819 tasks_by_target_record_id
=tasks_by_target_record_id
,
1820 action_id
=action_id
,
1822 task_index
=task_index
,
1825 changes_list
+= diff_items
1828 for vnfr_id
, vnfr
in db_vnfrs
.items():
1829 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1830 for item
in ["net", "vdu"]:
1831 self
.logger
.debug("process VNF={} {}".format(vnfr_id
, item
))
1832 diff_items
, task_index
= self
.calculate_diff_items(
1835 db_ro_nsr
=db_ro_nsr
,
1836 db_nsr_update
=db_vnfrs_update
[vnfr
["_id"]],
1838 tasks_by_target_record_id
=tasks_by_target_record_id
,
1839 action_id
=action_id
,
1841 task_index
=task_index
,
1845 changes_list
+= diff_items
1849 def define_all_tasks(
1853 tasks_by_target_record_id
,
1855 """Function to create all the task structures obtanied from
1856 the method calculate_all_differences_to_deploy
1859 changes_list (List): ordered list of items to be created or deleted
1860 db_new_tasks (List): tasks list to be created
1861 action_id (str): action id
1862 tasks_by_target_record_id (Dict[str, Any]):
1863 [<target_record_id>, <task>]
1867 for change
in changes_list
:
1868 task
= Ns
._create
_task
(
1869 deployment_info
=change
["deployment_info"],
1870 target_id
=change
["target_id"],
1871 item
=change
["item"],
1872 action
=change
["action"],
1873 target_record
=change
["target_record"],
1874 target_record_id
=change
["target_record_id"],
1875 extra_dict
=change
.get("extra_dict", None),
1878 self
.logger
.warning("ns.define_all_tasks task={}".format(task
))
1879 tasks_by_target_record_id
[change
["target_record_id"]] = task
1880 db_new_tasks
.append(task
)
1882 if change
.get("common_id"):
1883 task
["common_id"] = change
["common_id"]
1885 def upload_all_tasks(
1890 """Function to save all tasks in the common DB
1893 db_new_tasks (List): tasks list to be created
1894 now (time): current time
1898 nb_ro_tasks
= 0 # for logging
1900 for db_task
in db_new_tasks
:
1901 target_id
= db_task
.pop("target_id")
1902 common_id
= db_task
.get("common_id")
1904 # Do not chek tasks with vim_status DELETED
1905 # because in manual heealing there are two tasks for the same vdur:
1906 # one with vim_status deleted and the other one with the actual VM status.
1912 "target_id": target_id
,
1913 "tasks.common_id": common_id
,
1914 "vim_info.vim_status.ne": "DELETED",
1916 update_dict
={"to_check_at": now
, "modified_at": now
},
1917 push
={"tasks": db_task
},
1918 fail_on_empty
=False,
1922 if not self
.db
.set_one(
1925 "target_id": target_id
,
1926 "tasks.target_record": db_task
["target_record"],
1927 "vim_info.vim_status.ne": "DELETED",
1929 update_dict
={"to_check_at": now
, "modified_at": now
},
1930 push
={"tasks": db_task
},
1931 fail_on_empty
=False,
1934 self
.logger
.debug("Updating database, Creating ro_tasks")
1935 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
1937 self
.db
.create("ro_tasks", db_ro_task
)
1940 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1941 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
1945 def upload_recreate_tasks(
1950 """Function to save recreate tasks in the common DB
1953 db_new_tasks (List): tasks list to be created
1954 now (time): current time
1958 nb_ro_tasks
= 0 # for logging
1960 for db_task
in db_new_tasks
:
1961 target_id
= db_task
.pop("target_id")
1962 self
.logger
.warning("target_id={} db_task={}".format(target_id
, db_task
))
1964 action
= db_task
.get("action", None)
1967 self
.logger
.debug("Updating database, Creating ro_tasks")
1968 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
1970 # If DELETE task: the associated created items should be removed
1971 # (except persistent volumes):
1972 if action
== "DELETE":
1973 db_ro_task
["vim_info"]["created"] = True
1974 db_ro_task
["vim_info"]["created_items"] = db_task
.get(
1977 db_ro_task
["vim_info"]["volumes_to_hold"] = db_task
.get(
1978 "volumes_to_hold", []
1980 db_ro_task
["vim_info"]["vim_id"] = db_task
.get("vim_id", None)
1983 self
.logger
.warning("upload_all_tasks db_ro_task={}".format(db_ro_task
))
1984 self
.db
.create("ro_tasks", db_ro_task
)
1987 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1988 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
1992 def _prepare_created_items_for_healing(
1998 # Get created_items from ro_task
1999 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2000 for ro_task
in ro_tasks
:
2001 for task
in ro_task
["tasks"]:
2003 task
["target_record"] == target_record
2004 and task
["action"] == "CREATE"
2005 and ro_task
["vim_info"]["created_items"]
2007 created_items
= ro_task
["vim_info"]["created_items"]
2010 return created_items
2012 def _prepare_persistent_volumes_for_healing(
2017 # The associated volumes of the VM shouldn't be removed
2020 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
2021 if vim_details_text
:
2022 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
2024 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
2025 volumes_list
.append(vol_id
["id"])
2029 def prepare_changes_to_recreate(
2037 tasks_by_target_record_id
,
2039 """This method will obtain an ordered list of items (`changes_list`)
2040 to be created and deleted to meet the recreate request.
2044 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id
, indata
)
2048 # set list with diffs:
2050 db_path
= self
.db_path_map
["vdu"]
2051 target_list
= indata
.get("healVnfData", {})
2052 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
2053 ro_nsr_public_key
= db_ro_nsr
["public_key"]
2055 # Check each VNF of the target
2056 for target_vnf
in target_list
:
2057 # Find this VNF in the list from DB, raise exception if vnfInstanceId is not found
2058 vnfr_id
= target_vnf
["vnfInstanceId"]
2059 existing_vnf
= db_vnfrs
.get(vnfr_id
)
2060 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
2061 # vim_account_id = existing_vnf.get("vim-account-id", "")
2063 target_vdus
= target_vnf
.get("additionalParams", {}).get("vdu", [])
2064 # Check each VDU of this VNF
2066 # Create target_vdu_list from DB, if VDUs are not specified
2068 for existing_vdu
in existing_vnf
.get("vdur"):
2069 vdu_name
= existing_vdu
.get("vdu-name", None)
2070 vdu_index
= existing_vdu
.get("count-index", 0)
2071 vdu_to_be_healed
= {"vdu-id": vdu_name
, "count-index": vdu_index
}
2072 target_vdus
.append(vdu_to_be_healed
)
2073 for target_vdu
in target_vdus
:
2074 vdu_name
= target_vdu
.get("vdu-id", None)
2075 # For multi instance VDU count-index is mandatory
2076 # For single session VDU count-indes is 0
2077 count_index
= target_vdu
.get("count-index", 0)
2079 existing_instance
= None
2080 for instance
in existing_vnf
.get("vdur", None):
2082 instance
["vdu-name"] == vdu_name
2083 and instance
["count-index"] == count_index
2085 existing_instance
= instance
2090 target_record_id
= "{}.{}".format(db_record
, existing_instance
["id"])
2092 # The target VIM is the one already existing in DB to recreate
2093 for target_vim
, target_viminfo
in existing_instance
.get(
2096 # step 1 vdu to be deleted
2097 self
._assign
_vim
(target_vim
)
2099 "action_id": action_id
,
2101 "task_index": task_index
,
2104 target_record
= f
"{db_record}.{item_index}.vim_info.{target_vim}"
2105 created_items
= self
._prepare
_created
_items
_for
_healing
(
2106 nsr_id
, target_record
2109 volumes_to_hold
= self
._prepare
_persistent
_volumes
_for
_healing
(
2110 target_vim
, existing_instance
2113 # Specific extra params for recreate tasks:
2115 "created_items": created_items
,
2116 "vim_id": existing_instance
["vim-id"],
2117 "volumes_to_hold": volumes_to_hold
,
2120 changes_list
.append(
2122 "deployment_info": deployment_info
,
2123 "target_id": target_vim
,
2126 "target_record": target_record
,
2127 "target_record_id": target_record_id
,
2128 "extra_dict": extra_dict
,
2131 delete_task_id
= f
"{action_id}:{task_index}"
2134 # step 2 vdu to be created
2140 "vnfr": existing_vnf
,
2141 "vdu2cloud_init": vdu2cloud_init
,
2142 "tasks_by_target_record_id": tasks_by_target_record_id
,
2143 "logger": self
.logger
,
2146 "ro_nsr_public_key": ro_nsr_public_key
,
2150 extra_dict
= self
._process
_recreate
_vdu
_params
(
2159 # The CREATE task depens on the DELETE task
2160 extra_dict
["depends_on"] = [delete_task_id
]
2162 # Add volumes created from created_items if any
2163 # Ports should be deleted with delete task and automatically created with create task
2165 for k
, v
in created_items
.items():
2167 k_item
, _
, k_id
= k
.partition(":")
2168 if k_item
== "volume":
2170 except Exception as e
:
2172 "Error evaluating created item {}: {}".format(k
, e
)
2174 extra_dict
["previous_created_volumes"] = volumes
2177 "action_id": action_id
,
2179 "task_index": task_index
,
2181 self
._assign
_vim
(target_vim
)
2184 "deployment_info": deployment_info
,
2185 "target_id": target_vim
,
2188 "target_record": target_record
,
2189 "target_record_id": target_record_id
,
2190 "extra_dict": extra_dict
,
2192 changes_list
.append(new_item
)
2193 tasks_by_target_record_id
[target_record_id
] = new_item
2198 def recreate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2199 self
.logger
.debug("ns.recreate nsr_id={} indata={}".format(nsr_id
, indata
))
2200 # TODO: validate_input(indata, recreate_schema)
2201 action_id
= indata
.get("action_id", str(uuid4()))
2202 # get current deployment
2203 db_vnfrs
= {} # vnf's info indexed by _id
2205 logging_text
= "Recreate nsr_id={} action_id={} indata={}".format(
2206 nsr_id
, action_id
, indata
2208 self
.logger
.debug(logging_text
+ "Enter")
2211 step
= "Getting ns and vnfr record from db"
2212 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2214 tasks_by_target_record_id
= {}
2215 # read from db: vnf's of this ns
2216 step
= "Getting vnfrs from db"
2217 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2218 self
.logger
.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list
))
2220 if not db_vnfrs_list
:
2221 raise NsException("Cannot obtain associated VNF for ns")
2223 for vnfr
in db_vnfrs_list
:
2224 db_vnfrs
[vnfr
["_id"]] = vnfr
2227 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2228 self
.logger
.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr
))
2231 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2233 with self
.write_lock
:
2235 step
= "process NS elements"
2236 changes_list
= self
.prepare_changes_to_recreate(
2241 db_ro_nsr
=db_ro_nsr
,
2242 action_id
=action_id
,
2243 tasks_by_target_record_id
=tasks_by_target_record_id
,
2246 self
.define_all_tasks(
2247 changes_list
=changes_list
,
2248 db_new_tasks
=db_new_tasks
,
2249 tasks_by_target_record_id
=tasks_by_target_record_id
,
2252 # Delete all ro_tasks registered for the targets vdurs (target_record)
2253 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2254 # So remove all task related to target record.
2255 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2256 for change
in changes_list
:
2257 for ro_task
in ro_tasks
:
2258 for task
in ro_task
["tasks"]:
2259 if task
["target_record"] == change
["target_record"]:
2263 "_id": ro_task
["_id"],
2264 "modified_at": ro_task
["modified_at"],
2266 fail_on_empty
=False,
2269 step
= "Updating database, Appending tasks to ro_tasks"
2270 self
.upload_recreate_tasks(
2271 db_new_tasks
=db_new_tasks
,
2276 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2280 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2284 except Exception as e
:
2285 if isinstance(e
, (DbException
, NsException
)):
2287 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2290 e
= traceback_format_exc()
2291 self
.logger
.critical(
2292 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2296 raise NsException(e
)
2298 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2299 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
2300 validate_input(indata
, deploy_schema
)
2301 action_id
= indata
.get("action_id", str(uuid4()))
2303 # get current deployment
2304 db_nsr_update
= {} # update operation on nsrs
2305 db_vnfrs_update
= {}
2306 db_vnfrs
= {} # vnf's info indexed by _id
2308 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2309 self
.logger
.debug(logging_text
+ "Enter")
2312 step
= "Getting ns and vnfr record from db"
2313 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2314 self
.logger
.debug("ns.deploy: db_nsr={}".format(db_nsr
))
2316 tasks_by_target_record_id
= {}
2317 # read from db: vnf's of this ns
2318 step
= "Getting vnfrs from db"
2319 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2321 if not db_vnfrs_list
:
2322 raise NsException("Cannot obtain associated VNF for ns")
2324 for vnfr
in db_vnfrs_list
:
2325 db_vnfrs
[vnfr
["_id"]] = vnfr
2326 db_vnfrs_update
[vnfr
["_id"]] = {}
2327 self
.logger
.debug("ns.deploy db_vnfrs={}".format(db_vnfrs
))
2330 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2333 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2335 # check that action_id is not in the list of actions. Suffixed with :index
2336 if action_id
in db_ro_nsr
["actions"]:
2340 new_action_id
= "{}:{}".format(action_id
, index
)
2342 if new_action_id
not in db_ro_nsr
["actions"]:
2343 action_id
= new_action_id
2346 + "Changing action_id in use to {}".format(action_id
)
2352 def _process_action(indata
):
2353 nonlocal db_new_tasks
2360 if indata
["action"]["action"] == "inject_ssh_key":
2361 key
= indata
["action"].get("key")
2362 user
= indata
["action"].get("user")
2363 password
= indata
["action"].get("password")
2365 for vnf
in indata
.get("vnf", ()):
2366 if vnf
["_id"] not in db_vnfrs
:
2367 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
2369 db_vnfr
= db_vnfrs
[vnf
["_id"]]
2371 for target_vdu
in vnf
.get("vdur", ()):
2372 vdu_index
, vdur
= next(
2375 for i_v
in enumerate(db_vnfr
["vdur"])
2376 if i_v
[1]["id"] == target_vdu
["id"]
2383 "Invalid vdu vnf={}.{}".format(
2384 vnf
["_id"], target_vdu
["id"]
2388 target_vim
, vim_info
= next(
2389 k_v
for k_v
in vdur
["vim_info"].items()
2391 self
._assign
_vim
(target_vim
)
2392 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
2393 vnf
["_id"], vdu_index
2397 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
2400 "ip_address": vdur
.get("ip-address"),
2403 "password": password
,
2404 "private_key": db_ro_nsr
["private_key"],
2405 "salt": db_ro_nsr
["_id"],
2406 "schema_version": db_ro_nsr
["_admin"][
2413 "action_id": action_id
,
2415 "task_index": task_index
,
2418 task
= Ns
._create
_task
(
2419 deployment_info
=deployment_info
,
2420 target_id
=target_vim
,
2423 target_record
=target_record
,
2424 target_record_id
=None,
2425 extra_dict
=extra_dict
,
2428 task_index
= deployment_info
.get("task_index")
2430 db_new_tasks
.append(task
)
2432 with self
.write_lock
:
2433 if indata
.get("action"):
2434 _process_action(indata
)
2436 # compute network differences
2438 step
= "process NS elements"
2439 changes_list
= self
.calculate_all_differences_to_deploy(
2444 db_ro_nsr
=db_ro_nsr
,
2445 db_nsr_update
=db_nsr_update
,
2446 db_vnfrs_update
=db_vnfrs_update
,
2447 action_id
=action_id
,
2448 tasks_by_target_record_id
=tasks_by_target_record_id
,
2450 self
.define_all_tasks(
2451 changes_list
=changes_list
,
2452 db_new_tasks
=db_new_tasks
,
2453 tasks_by_target_record_id
=tasks_by_target_record_id
,
2456 step
= "Updating database, Appending tasks to ro_tasks"
2457 self
.upload_all_tasks(
2458 db_new_tasks
=db_new_tasks
,
2462 step
= "Updating database, nsrs"
2464 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
2466 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
2468 step
= "Updating database, vnfrs={}".format(vnfr_id
)
2469 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
2472 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2476 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2480 except Exception as e
:
2481 if isinstance(e
, (DbException
, NsException
)):
2483 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2486 e
= traceback_format_exc()
2487 self
.logger
.critical(
2488 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2492 raise NsException(e
)
2494 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2495 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
2496 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2498 with self
.write_lock
:
2500 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
2501 except NsWorkerException
as e
:
2502 raise NsException(e
)
2504 return None, None, True
2506 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2508 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2509 version
, nsr_id
, action_id
, indata
2515 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
2516 global_status
= "DONE"
2519 for ro_task
in ro_tasks
:
2520 for task
in ro_task
["tasks"]:
2521 if task
and task
["action_id"] == action_id
:
2522 task_list
.append(task
)
2525 if task
["status"] == "FAILED":
2526 global_status
= "FAILED"
2527 error_text
= "Error at {} {}: {}".format(
2528 task
["action"].lower(),
2530 ro_task
["vim_info"].get("vim_message") or "unknown",
2532 details
.append(error_text
)
2533 elif task
["status"] in ("SCHEDULED", "BUILD"):
2534 if global_status
!= "FAILED":
2535 global_status
= "BUILD"
2540 "status": global_status
,
2541 "details": ". ".join(details
)
2543 else "progress {}/{}".format(done
, total
),
2545 "action_id": action_id
,
2549 return return_data
, None, True
2551 def recreate_status(
2552 self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
2554 return self
.status(session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
)
2556 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2558 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2559 session
, indata
, version
, nsr_id
, action_id
2563 return None, None, True
2565 def rebuild_start_stop_task(
2576 self
._assign
_vim
(target_vim
)
2577 target_record
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_index
)
2578 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_id
)
2580 "action_id": action_id
,
2582 "task_index": task_index
,
2585 task
= Ns
._create
_task
(
2586 deployment_info
=deployment_info
,
2587 target_id
=target_vim
,
2590 target_record
=target_record
,
2591 target_record_id
=target_record_id
,
2592 extra_dict
=extra_dict
,
2596 def rebuild_start_stop(
2597 self
, session
, action_dict
, version
, nsr_id
, *args
, **kwargs
2602 action_id
= action_dict
.get("action_id", str(uuid4()))
2604 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2605 self
.logger
.debug(logging_text
+ "Enter")
2607 action
= list(action_dict
.keys())[0]
2608 task_dict
= action_dict
.get(action
)
2609 vim_vm_id
= action_dict
.get(action
).get("vim_vm_id")
2611 if action_dict
.get("stop"):
2615 step
= "lock the operation & do task creation"
2616 with self
.write_lock
:
2617 extra_dict
["params"] = {
2618 "vim_vm_id": vim_vm_id
,
2621 task
= self
.rebuild_start_stop_task(
2622 task_dict
["vdu_id"],
2623 task_dict
["vnf_id"],
2624 task_dict
["vdu_index"],
2628 task_dict
["target_vim"],
2631 db_new_tasks
.append(task
)
2632 step
= "upload Task to db"
2633 self
.upload_all_tasks(
2634 db_new_tasks
=db_new_tasks
,
2638 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2641 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2645 except Exception as e
:
2646 if isinstance(e
, (DbException
, NsException
)):
2648 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2651 e
= traceback_format_exc()
2652 self
.logger
.critical(
2653 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2656 raise NsException(e
)
2658 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2659 nsrs
= self
.db
.get_list("nsrs", {})
2663 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
2665 return return_data
, None, True
2667 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2668 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2671 for ro_task
in ro_tasks
:
2672 for task
in ro_task
["tasks"]:
2673 if task
["action_id"] not in return_data
:
2674 return_data
.append(task
["action_id"])
2676 return return_data
, None, True
2679 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
2681 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
2682 self
._assign
_vim
(target_vim
)
2683 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
2684 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
2686 "action_id": action_id
,
2688 "task_index": task_index
,
2691 task
= Ns
._create
_task
(
2692 deployment_info
=deployment_info
,
2693 target_id
=target_vim
,
2696 target_record
=target_record
,
2697 target_record_id
=target_record_id
,
2698 extra_dict
=extra_dict
,
2703 def migrate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2707 action_id
= indata
.get("action_id", str(uuid4()))
2709 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2710 self
.logger
.debug(logging_text
+ "Enter")
2712 vnf_instance_id
= indata
["vnfInstanceId"]
2713 step
= "Getting vnfrs from db"
2714 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
2715 vdu
= indata
.get("vdu")
2716 migrateToHost
= indata
.get("migrateToHost")
2719 with self
.write_lock
:
2721 vdu_id
= indata
["vdu"]["vduId"]
2722 vdu_count_index
= indata
["vdu"].get("vduCountIndex", 0)
2723 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2725 vdu
["vdu-id-ref"] == vdu_id
2726 and vdu
["count-index"] == vdu_count_index
2728 extra_dict
["params"] = {
2729 "vim_vm_id": vdu
["vim-id"],
2730 "migrate_host": migrateToHost
,
2731 "vdu_vim_info": vdu
["vim_info"],
2733 step
= "Creating migration task for vdu:{}".format(vdu
)
2734 task
= self
.migrate_task(
2743 db_new_tasks
.append(task
)
2748 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2749 extra_dict
["params"] = {
2750 "vim_vm_id": vdu
["vim-id"],
2751 "migrate_host": migrateToHost
,
2752 "vdu_vim_info": vdu
["vim_info"],
2754 step
= "Creating migration task for vdu:{}".format(vdu
)
2755 task
= self
.migrate_task(
2764 db_new_tasks
.append(task
)
2767 self
.upload_all_tasks(
2768 db_new_tasks
=db_new_tasks
,
2773 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2776 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2780 except Exception as e
:
2781 if isinstance(e
, (DbException
, NsException
)):
2783 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2786 e
= traceback_format_exc()
2787 self
.logger
.critical(
2788 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2791 raise NsException(e
)
2793 def verticalscale_task(
2794 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
2796 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
2797 self
._assign
_vim
(target_vim
)
2798 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
2799 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
2801 "action_id": action_id
,
2803 "task_index": task_index
,
2806 task
= Ns
._create
_task
(
2807 deployment_info
=deployment_info
,
2808 target_id
=target_vim
,
2809 item
="verticalscale",
2811 target_record
=target_record
,
2812 target_record_id
=target_record_id
,
2813 extra_dict
=extra_dict
,
2817 def verticalscale(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2821 action_id
= indata
.get("action_id", str(uuid4()))
2823 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2824 self
.logger
.debug(logging_text
+ "Enter")
2826 VnfFlavorData
= indata
.get("changeVnfFlavorData")
2827 vnf_instance_id
= VnfFlavorData
["vnfInstanceId"]
2828 step
= "Getting vnfrs from db"
2829 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
2830 vduid
= VnfFlavorData
["additionalParams"]["vduid"]
2831 vduCountIndex
= VnfFlavorData
["additionalParams"]["vduCountIndex"]
2832 virtualMemory
= VnfFlavorData
["additionalParams"]["virtualMemory"]
2833 numVirtualCpu
= VnfFlavorData
["additionalParams"]["numVirtualCpu"]
2834 sizeOfStorage
= VnfFlavorData
["additionalParams"]["sizeOfStorage"]
2836 "name": vduid
+ "-flv",
2837 "ram": virtualMemory
,
2838 "vcpus": numVirtualCpu
,
2839 "disk": sizeOfStorage
,
2842 step
= "Creating Tasks for vertical scaling"
2843 with self
.write_lock
:
2844 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2846 vdu
["vdu-id-ref"] == vduid
2847 and vdu
["count-index"] == vduCountIndex
2849 extra_dict
["params"] = {
2850 "vim_vm_id": vdu
["vim-id"],
2851 "flavor_dict": flavor_dict
,
2853 task
= self
.verticalscale_task(
2862 db_new_tasks
.append(task
)
2865 self
.upload_all_tasks(
2866 db_new_tasks
=db_new_tasks
,
2870 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2873 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2877 except Exception as e
:
2878 if isinstance(e
, (DbException
, NsException
)):
2880 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2883 e
= traceback_format_exc()
2884 self
.logger
.critical(
2885 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2888 raise NsException(e
)