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
, List
, Optional
, 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
,
120 "shared-volumes": Ns
._process
_shared
_volumes
_params
,
127 "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group",
128 "shared-volumes": "shared-volumes",
131 def init_db(self
, target_version
):
134 def start(self
, config
):
136 Connect to database, filesystem storage, and messaging
137 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
138 :param config: Configuration of db, storage, etc
142 self
.config
["process_id"] = get_process_id() # used for HA identity
143 self
.logger
= logging
.getLogger("ro.ns")
145 # check right version of common
146 if versiontuple(common_version
) < versiontuple(min_common_version
):
148 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
149 common_version
, min_common_version
155 if config
["database"]["driver"] == "mongo":
156 self
.db
= dbmongo
.DbMongo()
157 self
.db
.db_connect(config
["database"])
158 elif config
["database"]["driver"] == "memory":
159 self
.db
= dbmemory
.DbMemory()
160 self
.db
.db_connect(config
["database"])
163 "Invalid configuration param '{}' at '[database]':'driver'".format(
164 config
["database"]["driver"]
169 if config
["storage"]["driver"] == "local":
170 self
.fs
= fslocal
.FsLocal()
171 self
.fs
.fs_connect(config
["storage"])
172 elif config
["storage"]["driver"] == "mongo":
173 self
.fs
= fsmongo
.FsMongo()
174 self
.fs
.fs_connect(config
["storage"])
175 elif config
["storage"]["driver"] is None:
179 "Invalid configuration param '{}' at '[storage]':'driver'".format(
180 config
["storage"]["driver"]
185 if config
["message"]["driver"] == "local":
186 self
.msg
= msglocal
.MsgLocal()
187 self
.msg
.connect(config
["message"])
188 elif config
["message"]["driver"] == "kafka":
189 self
.msg
= msgkafka
.MsgKafka()
190 self
.msg
.connect(config
["message"])
193 "Invalid configuration param '{}' at '[message]':'driver'".format(
194 config
["message"]["driver"]
198 # TODO load workers to deal with exising database tasks
200 self
.write_lock
= Lock()
201 except (DbException
, FsException
, MsgException
) as e
:
202 raise NsException(str(e
), http_code
=e
.http_code
)
204 def get_assigned_vims(self
):
205 return list(self
.vims_assigned
.keys())
210 self
.db
.db_disconnect()
213 self
.fs
.fs_disconnect()
216 self
.msg
.disconnect()
218 self
.write_lock
= None
219 except (DbException
, FsException
, MsgException
) as e
:
220 raise NsException(str(e
), http_code
=e
.http_code
)
222 for worker
in self
.workers
:
223 worker
.insert_task(("terminate",))
225 def _create_worker(self
):
227 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
228 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
229 return the index of the assigned worker thread. Worker threads are storead at self.workers
231 # Look for a thread in idle status
235 for i
in range(len(self
.workers
))
236 if self
.workers
[i
] and self
.workers
[i
].idle
241 if worker_id
is not None:
242 # unset idle status to avoid race conditions
243 self
.workers
[worker_id
].idle
= False
245 worker_id
= len(self
.workers
)
247 if worker_id
< self
.config
["global"]["server.ns_threads"]:
248 # create a new worker
250 NsWorker(worker_id
, self
.config
, self
.plugins
, self
.db
)
252 self
.workers
[worker_id
].start()
254 # reached maximum number of threads, assign VIM to an existing one
255 worker_id
= self
.next_worker
256 self
.next_worker
= (self
.next_worker
+ 1) % self
.config
["global"][
262 def assign_vim(self
, target_id
):
263 with self
.write_lock
:
264 return self
._assign
_vim
(target_id
)
266 def _assign_vim(self
, target_id
):
267 if target_id
not in self
.vims_assigned
:
268 worker_id
= self
.vims_assigned
[target_id
] = self
._create
_worker
()
269 self
.workers
[worker_id
].insert_task(("load_vim", target_id
))
271 def reload_vim(self
, target_id
):
272 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
273 # this is because database VIM information is cached for threads working with SDN
274 with self
.write_lock
:
275 for worker
in self
.workers
:
276 if worker
and not worker
.idle
:
277 worker
.insert_task(("reload_vim", target_id
))
279 def unload_vim(self
, target_id
):
280 with self
.write_lock
:
281 return self
._unload
_vim
(target_id
)
283 def _unload_vim(self
, target_id
):
284 if target_id
in self
.vims_assigned
:
285 worker_id
= self
.vims_assigned
[target_id
]
286 self
.workers
[worker_id
].insert_task(("unload_vim", target_id
))
287 del self
.vims_assigned
[target_id
]
289 def check_vim(self
, target_id
):
290 with self
.write_lock
:
291 if target_id
in self
.vims_assigned
:
292 worker_id
= self
.vims_assigned
[target_id
]
294 worker_id
= self
._create
_worker
()
296 worker
= self
.workers
[worker_id
]
297 worker
.insert_task(("check_vim", target_id
))
299 def unload_unused_vims(self
):
300 with self
.write_lock
:
303 for target_id
in self
.vims_assigned
:
304 if not self
.db
.get_one(
307 "target_id": target_id
,
308 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
312 vims_to_unload
.append(target_id
)
314 for target_id
in vims_to_unload
:
315 self
._unload
_vim
(target_id
)
323 """This method reads cloud init from a file.
325 Note: Not used as cloud init content is provided in the http body.
328 db (Type[DbBase]): [description]
329 fs (Type[FsBase]): [description]
330 location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
333 NsException: [description]
334 NsException: [description]
339 vnfd_id
, _
, other
= location
.partition(":")
340 _type
, _
, name
= other
.partition(":")
341 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
344 base_folder
= vnfd
["_admin"]["storage"]
345 cloud_init_file
= "{}/{}/cloud_init/{}".format(
346 base_folder
["folder"], base_folder
["pkg-dir"], name
351 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
356 with fs
.file_open(cloud_init_file
, "r") as ci_file
:
357 cloud_init_content
= ci_file
.read()
359 cloud_init_content
= vnfd
["vdu"][int(name
)]["cloud-init"]
361 raise NsException("Mismatch descriptor for cloud init: {}".format(location
))
363 return cloud_init_content
367 cloud_init_content
: str,
368 params
: Dict
[str, Any
],
371 """Function that processes the cloud init to replace Jinja2 encoded parameters.
374 cloud_init_content (str): [description]
375 params (Dict[str, Any]): [description]
376 context (str): [description]
379 NsException: [description]
380 NsException: [description]
387 undefined
=StrictUndefined
,
388 autoescape
=select_autoescape(default_for_string
=True, default
=True),
390 template
= env
.from_string(cloud_init_content
)
392 return template
.render(params
or {})
393 except UndefinedError
as e
:
395 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
396 "inside the 'additionalParamsForVnf' block".format(e
, context
)
398 except (TemplateError
, TemplateNotFound
) as e
:
400 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
405 def _create_db_ro_nsrs(self
, nsr_id
, now
):
407 key
= rsa
.generate_private_key(
408 backend
=crypto_default_backend(), public_exponent
=65537, key_size
=2048
410 private_key
= key
.private_bytes(
411 crypto_serialization
.Encoding
.PEM
,
412 crypto_serialization
.PrivateFormat
.PKCS8
,
413 crypto_serialization
.NoEncryption(),
415 public_key
= key
.public_key().public_bytes(
416 crypto_serialization
.Encoding
.OpenSSH
,
417 crypto_serialization
.PublicFormat
.OpenSSH
,
419 private_key
= private_key
.decode("utf8")
420 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
421 i
= private_key
.find("\n")
422 private_key
= "-----BEGIN RSA PRIVATE KEY-----" + private_key
[i
:]
423 public_key
= public_key
.decode("utf8")
424 except Exception as e
:
425 raise NsException("Cannot create ssh-keys: {}".format(e
))
427 schema_version
= "1.1"
428 private_key_encrypted
= self
.db
.encrypt(
429 private_key
, schema_version
=schema_version
, salt
=nsr_id
436 "schema_version": schema_version
,
438 "public_key": public_key
,
439 "private_key": private_key_encrypted
,
442 self
.db
.create("ro_nsrs", db_content
)
448 deployment_info
: Dict
[str, Any
],
453 target_record_id
: str,
454 extra_dict
: Dict
[str, Any
] = None,
456 """Function to create task dict from deployment information.
459 deployment_info (Dict[str, Any]): [description]
460 target_id (str): [description]
461 item (str): [description]
462 action (str): [description]
463 target_record (str): [description]
464 target_record_id (str): [description]
465 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
468 Dict[str, Any]: [description]
471 "target_id": target_id
, # it will be removed before pushing at database
472 "action_id": deployment_info
.get("action_id"),
473 "nsr_id": deployment_info
.get("nsr_id"),
474 "task_id": f
"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
475 "status": "SCHEDULED",
478 "target_record": target_record
,
479 "target_record_id": target_record_id
,
483 task
.update(extra_dict
) # params, find_params, depends_on
485 deployment_info
["task_index"] = deployment_info
.get("task_index", 0) + 1
492 task
: Dict
[str, Any
],
494 """Function to create an RO task from task information.
497 target_id (str): [description]
498 task (Dict[str, Any]): [description]
501 Dict[str, Any]: [description]
505 _id
= task
.get("task_id")
510 "target_id": target_id
,
513 "created_items": None,
530 def _process_image_params(
531 target_image
: Dict
[str, Any
],
532 indata
: Dict
[str, Any
],
533 vim_info
: Dict
[str, Any
],
534 target_record_id
: str,
535 **kwargs
: Dict
[str, Any
],
537 """Function to process VDU image parameters.
540 target_image (Dict[str, Any]): [description]
541 indata (Dict[str, Any]): [description]
542 vim_info (Dict[str, Any]): [description]
543 target_record_id (str): [description]
546 Dict[str, Any]: [description]
550 if target_image
.get("image"):
551 find_params
["filter_dict"] = {"name": target_image
.get("image")}
553 if target_image
.get("vim_image_id"):
554 find_params
["filter_dict"] = {"id": target_image
.get("vim_image_id")}
556 if target_image
.get("image_checksum"):
557 find_params
["filter_dict"] = {
558 "checksum": target_image
.get("image_checksum")
561 return {"find_params": find_params
}
564 def _get_resource_allocation_params(
565 quota_descriptor
: Dict
[str, Any
],
567 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
571 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
574 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
578 if quota_descriptor
.get("limit"):
579 quota
["limit"] = int(quota_descriptor
["limit"])
581 if quota_descriptor
.get("reserve"):
582 quota
["reserve"] = int(quota_descriptor
["reserve"])
584 if quota_descriptor
.get("shares"):
585 quota
["shares"] = int(quota_descriptor
["shares"])
590 def _process_guest_epa_quota_params(
591 guest_epa_quota
: Dict
[str, Any
],
594 """Function to extract the guest epa quota parameters.
597 guest_epa_quota (Dict[str, Any]): [description]
598 epa_vcpu_set (bool): [description]
601 Dict[str, Any]: [description]
605 if guest_epa_quota
.get("cpu-quota") and not epa_vcpu_set
:
606 cpuquota
= Ns
._get
_resource
_allocation
_params
(
607 guest_epa_quota
.get("cpu-quota")
611 result
["cpu-quota"] = cpuquota
613 if guest_epa_quota
.get("mem-quota"):
614 vduquota
= Ns
._get
_resource
_allocation
_params
(
615 guest_epa_quota
.get("mem-quota")
619 result
["mem-quota"] = vduquota
621 if guest_epa_quota
.get("disk-io-quota"):
622 diskioquota
= Ns
._get
_resource
_allocation
_params
(
623 guest_epa_quota
.get("disk-io-quota")
627 result
["disk-io-quota"] = diskioquota
629 if guest_epa_quota
.get("vif-quota"):
630 vifquota
= Ns
._get
_resource
_allocation
_params
(
631 guest_epa_quota
.get("vif-quota")
635 result
["vif-quota"] = vifquota
640 def _process_guest_epa_numa_params(
641 guest_epa_quota
: Dict
[str, Any
],
642 ) -> Tuple
[Dict
[str, Any
], bool]:
646 guest_epa_quota (Dict[str, Any]): [description]
649 Tuple[Dict[str, Any], bool]: [description]
655 if guest_epa_quota
.get("numa-node-policy"):
656 numa_node_policy
= guest_epa_quota
.get("numa-node-policy")
658 if numa_node_policy
.get("node"):
659 for numa_node
in numa_node_policy
["node"]:
661 if numa_node
.get("id"):
662 numa
["id"] = int(numa_node
["id"])
664 if numa_node
.get("vcpu"):
665 for vcpu
in numa_node
.get("vcpu"):
666 vcpu_id
= int(vcpu
.get("id"))
667 vcpu_list
.append(vcpu_id
)
668 numa
["vcpu"] = vcpu_list
670 if numa_node
.get("num-cores"):
671 numa
["cores"] = numa_node
["num-cores"]
674 paired_threads
= numa_node
.get("paired-threads", {})
675 if paired_threads
.get("num-paired-threads"):
676 numa
["paired_threads"] = int(
677 numa_node
["paired-threads"]["num-paired-threads"]
681 if paired_threads
.get("paired-thread-ids"):
682 numa
["paired-threads-id"] = []
684 for pair
in paired_threads
["paired-thread-ids"]:
685 numa
["paired-threads-id"].append(
687 str(pair
["thread-a"]),
688 str(pair
["thread-b"]),
692 if numa_node
.get("num-threads"):
693 numa
["threads"] = int(numa_node
["num-threads"])
696 if numa_node
.get("memory-mb"):
697 numa
["memory"] = max(int(int(numa_node
["memory-mb"]) / 1024), 1)
699 numa_list
.append(numa
)
702 return numa_list
, epa_vcpu_set
705 def _process_guest_epa_cpu_pinning_params(
706 guest_epa_quota
: Dict
[str, Any
],
709 ) -> Tuple
[Dict
[str, Any
], bool]:
713 guest_epa_quota (Dict[str, Any]): [description]
714 vcpu_count (int): [description]
715 epa_vcpu_set (bool): [description]
718 Tuple[Dict[str, Any], bool]: [description]
721 local_epa_vcpu_set
= epa_vcpu_set
724 guest_epa_quota
.get("cpu-pinning-policy") == "DEDICATED"
727 # Pinning policy "REQUIRE" uses threads as host should support SMT architecture
728 # Pinning policy "ISOLATE" uses cores as host should not support SMT architecture
729 # Pinning policy "PREFER" uses threads in case host supports SMT architecture
732 if guest_epa_quota
.get("cpu-thread-pinning-policy") == "ISOLATE"
734 ] = max(vcpu_count
, 1)
735 local_epa_vcpu_set
= True
737 return numa
, local_epa_vcpu_set
740 def _process_epa_params(
741 target_flavor
: Dict
[str, Any
],
746 target_flavor (Dict[str, Any]): [description]
749 Dict[str, Any]: [description]
755 if target_flavor
.get("guest-epa"):
756 guest_epa
= target_flavor
["guest-epa"]
758 numa_list
, epa_vcpu_set
= Ns
._process
_guest
_epa
_numa
_params
(
759 guest_epa_quota
=guest_epa
762 if guest_epa
.get("mempage-size"):
763 extended
["mempage-size"] = guest_epa
.get("mempage-size")
765 if guest_epa
.get("cpu-pinning-policy"):
766 extended
["cpu-pinning-policy"] = guest_epa
.get("cpu-pinning-policy")
768 if guest_epa
.get("cpu-thread-pinning-policy"):
769 extended
["cpu-thread-pinning-policy"] = guest_epa
.get(
770 "cpu-thread-pinning-policy"
773 if guest_epa
.get("numa-node-policy"):
774 if guest_epa
.get("numa-node-policy").get("mem-policy"):
775 extended
["mem-policy"] = guest_epa
.get("numa-node-policy").get(
779 tmp_numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_cpu
_pinning
_params
(
780 guest_epa_quota
=guest_epa
,
781 vcpu_count
=int(target_flavor
.get("vcpu-count", 1)),
782 epa_vcpu_set
=epa_vcpu_set
,
784 for numa
in numa_list
:
785 numa
.update(tmp_numa
)
788 Ns
._process
_guest
_epa
_quota
_params
(
789 guest_epa_quota
=guest_epa
,
790 epa_vcpu_set
=epa_vcpu_set
,
795 extended
["numas"] = numa_list
800 def _process_flavor_params(
801 target_flavor
: Dict
[str, Any
],
802 indata
: Dict
[str, Any
],
803 vim_info
: Dict
[str, Any
],
804 target_record_id
: str,
805 **kwargs
: Dict
[str, Any
],
810 target_flavor (Dict[str, Any]): [description]
811 indata (Dict[str, Any]): [description]
812 vim_info (Dict[str, Any]): [description]
813 target_record_id (str): [description]
816 Dict[str, Any]: [description]
818 db
= kwargs
.get("db")
822 "disk": int(target_flavor
["storage-gb"]),
823 "ram": int(target_flavor
["memory-mb"]),
824 "vcpus": int(target_flavor
["vcpu-count"]),
827 for vnf
in indata
.get("vnf", []):
828 for vdur
in vnf
.get("vdur", []):
829 if vdur
.get("ns-flavor-id") == target_flavor
.get("id"):
832 if db
and isinstance(indata
.get("vnf"), list):
833 vnfd_id
= indata
.get("vnf")[0].get("vnfd-id")
834 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
835 # check if there is persistent root disk
836 for vdu
in vnfd
.get("vdu", ()):
837 if vdu
["name"] == target_vdur
.get("vdu-name"):
838 for vsd
in vnfd
.get("virtual-storage-desc", ()):
839 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
842 root_disk
.get("type-of-storage")
843 == "persistent-storage:persistent-storage"
845 flavor_data
["disk"] = 0
847 for storage
in target_vdur
.get("virtual-storages", []):
849 storage
.get("type-of-storage")
850 == "etsi-nfv-descriptors:ephemeral-storage"
852 flavor_data
["ephemeral"] = int(storage
.get("size-of-storage", 0))
853 elif storage
.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
854 flavor_data
["swap"] = int(storage
.get("size-of-storage", 0))
856 extended
= Ns
._process
_epa
_params
(target_flavor
)
858 flavor_data
["extended"] = extended
860 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
861 flavor_data_name
= flavor_data
.copy()
862 flavor_data_name
["name"] = target_flavor
["name"]
863 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
867 def _process_net_params(
868 target_vld
: Dict
[str, Any
],
869 indata
: Dict
[str, Any
],
870 vim_info
: Dict
[str, Any
],
871 target_record_id
: str,
872 **kwargs
: Dict
[str, Any
],
874 """Function to process network parameters.
877 target_vld (Dict[str, Any]): [description]
878 indata (Dict[str, Any]): [description]
879 vim_info (Dict[str, Any]): [description]
880 target_record_id (str): [description]
883 Dict[str, Any]: [description]
887 if vim_info
.get("sdn"):
888 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
889 # ns_preffix = "nsrs:{}".format(nsr_id)
890 # remove the ending ".sdn
891 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
892 extra_dict
["params"] = {
894 for k
in ("sdn-ports", "target_vim", "vlds", "type")
898 # TODO needed to add target_id in the dependency.
899 if vim_info
.get("target_vim"):
900 extra_dict
["depends_on"] = [
901 f
"{vim_info.get('target_vim')} {vld_target_record_id}"
906 if vim_info
.get("vim_network_name"):
907 extra_dict
["find_params"] = {
909 "name": vim_info
.get("vim_network_name"),
912 elif vim_info
.get("vim_network_id"):
913 extra_dict
["find_params"] = {
915 "id": vim_info
.get("vim_network_id"),
918 elif target_vld
.get("mgmt-network") and not vim_info
.get("provider_network"):
919 extra_dict
["find_params"] = {
921 "name": target_vld
["id"],
925 extra_dict
["params"] = {
927 f
"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
929 "ip_profile": vim_info
.get("ip_profile"),
930 "provider_network_profile": vim_info
.get("provider_network"),
933 if not target_vld
.get("underlay"):
934 extra_dict
["params"]["net_type"] = "bridge"
936 extra_dict
["params"]["net_type"] = (
937 "ptp" if target_vld
.get("type") == "ELINE" else "data"
943 def find_persistent_root_volumes(
946 vdu_instantiation_volumes_list
: list,
949 """Find the persistent root volumes and add them to the disk_list
950 by parsing the instantiation parameters.
953 vnfd (dict): VNF descriptor
954 target_vdu (dict): processed VDU
955 vdu_instantiation_volumes_list (list): instantiation parameters for the each VDU as a list
956 disk_list (list): to be filled up
959 persistent_root_disk (dict): Details of persistent root disk
962 persistent_root_disk
= {}
963 # There can be only one root disk, when we find it, it will return the result
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
:
979 vdu_volume
["vim-volume-id"]
980 and root_disk
["id"] == vdu_volume
["name"]
982 persistent_root_disk
[vsd
["id"]] = {
983 "vim_volume_id": vdu_volume
["vim-volume-id"],
984 "image_id": vdu
.get("sw-image-desc"),
987 disk_list
.append(persistent_root_disk
[vsd
["id"]])
989 return persistent_root_disk
992 if root_disk
.get("size-of-storage"):
993 persistent_root_disk
[vsd
["id"]] = {
994 "image_id": vdu
.get("sw-image-desc"),
995 "size": root_disk
.get("size-of-storage"),
996 "keep": Ns
.is_volume_keeping_required(root_disk
),
999 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1001 return persistent_root_disk
1004 def find_persistent_volumes(
1005 persistent_root_disk
: dict,
1007 vdu_instantiation_volumes_list
: list,
1010 """Find the ordinary persistent volumes and add them to the disk_list
1011 by parsing the instantiation parameters.
1014 persistent_root_disk: persistent root disk dictionary
1015 target_vdu: processed VDU
1016 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1017 disk_list: to be filled up
1020 # Find the ordinary volumes which are not added to the persistent_root_disk
1021 persistent_disk
= {}
1022 for disk
in target_vdu
.get("virtual-storages", {}):
1024 disk
.get("type-of-storage") == "persistent-storage:persistent-storage"
1025 and disk
["id"] not in persistent_root_disk
.keys()
1027 for vdu_volume
in vdu_instantiation_volumes_list
:
1028 if vdu_volume
["vim-volume-id"] and disk
["id"] == vdu_volume
["name"]:
1029 persistent_disk
[disk
["id"]] = {
1030 "vim_volume_id": vdu_volume
["vim-volume-id"],
1032 disk_list
.append(persistent_disk
[disk
["id"]])
1035 if disk
["id"] not in persistent_disk
.keys():
1036 persistent_disk
[disk
["id"]] = {
1037 "size": disk
.get("size-of-storage"),
1038 "keep": Ns
.is_volume_keeping_required(disk
),
1040 disk_list
.append(persistent_disk
[disk
["id"]])
1043 def is_volume_keeping_required(virtual_storage_desc
: Dict
[str, Any
]) -> bool:
1044 """Function to decide keeping persistent volume
1048 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1054 if not virtual_storage_desc
.get("vdu-storage-requirements"):
1056 for item
in virtual_storage_desc
.get("vdu-storage-requirements", {}):
1057 if item
.get("key") == "keep-volume" and item
.get("value").lower() == "true":
1062 def is_shared_volume(
1063 virtual_storage_desc
: Dict
[str, Any
], vnfd_id
: str
1065 """Function to decide if the volume type is multi attached or not .
1068 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1069 vnfd_id (str): vnfd id
1073 name (str) New name if it is a multiattach disk
1076 if vdu_storage_requirements
:= virtual_storage_desc
.get(
1077 "vdu-storage-requirements", {}
1079 for item
in vdu_storage_requirements
:
1081 item
.get("key") == "multiattach"
1082 and item
.get("value").lower() == "true"
1084 name
= f
"shared-{virtual_storage_desc['id']}-{vnfd_id}"
1086 return virtual_storage_desc
["id"], False
1089 def _sort_vdu_interfaces(target_vdu
: dict) -> None:
1090 """Sort the interfaces according to position number.
1093 target_vdu (dict): Details of VDU to be created
1096 # If the position info is provided for all the interfaces, it will be sorted
1097 # according to position number ascendingly.
1098 sorted_interfaces
= sorted(
1099 target_vdu
["interfaces"],
1100 key
=lambda x
: (x
.get("position") is None, x
.get("position")),
1102 target_vdu
["interfaces"] = sorted_interfaces
1105 def _partially_locate_vdu_interfaces(target_vdu
: dict) -> None:
1106 """Only place the interfaces which has specific position.
1109 target_vdu (dict): Details of VDU to be created
1112 # If the position info is provided for some interfaces but not all of them, the interfaces
1113 # which has specific position numbers will be placed and others' positions will not be taken care.
1115 i
.get("position") + 1
1116 for i
in target_vdu
["interfaces"]
1117 if i
.get("position") is not None
1119 n
= len(target_vdu
["interfaces"])
1120 sorted_interfaces
= [-1] * n
1124 if target_vdu
["interfaces"][k
].get("position") is not None:
1125 if any(i
.get("position") == 0 for i
in target_vdu
["interfaces"]):
1126 idx
= target_vdu
["interfaces"][k
]["position"] + 1
1128 idx
= target_vdu
["interfaces"][k
]["position"]
1129 sorted_interfaces
[idx
- 1] = target_vdu
["interfaces"][k
]
1133 if target_vdu
["interfaces"][m
].get("position") is None:
1134 idy
= sorted_interfaces
.index(-1)
1135 sorted_interfaces
[idy
] = target_vdu
["interfaces"][m
]
1138 target_vdu
["interfaces"] = sorted_interfaces
1141 def _prepare_vdu_cloud_init(
1142 target_vdu
: dict, vdu2cloud_init
: dict, db
: object, fs
: object
1144 """Fill cloud_config dict with cloud init details.
1147 target_vdu (dict): Details of VDU to be created
1148 vdu2cloud_init (dict): Cloud init dict
1149 db (object): DB object
1150 fs (object): FS object
1153 cloud_config (dict): Cloud config details of VDU
1159 if target_vdu
.get("cloud-init"):
1160 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1161 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1164 location
=target_vdu
["cloud-init"],
1167 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1168 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1169 cloud_init_content
=cloud_content_
,
1170 params
=target_vdu
.get("additionalParams"),
1171 context
=target_vdu
["cloud-init"],
1174 if target_vdu
.get("boot-data-drive"):
1175 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1180 def _check_vld_information_of_interfaces(
1181 interface
: dict, ns_preffix
: str, vnf_preffix
: str
1183 """Prepare the net_text by the virtual link information for vnf and ns level.
1185 interface (dict): Interface details
1186 ns_preffix (str): Prefix of NS
1187 vnf_preffix (str): Prefix of VNF
1190 net_text (str): information of net
1194 if interface
.get("ns-vld-id"):
1195 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
1196 elif interface
.get("vnf-vld-id"):
1197 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
1202 def _prepare_interface_port_security(interface
: dict) -> None:
1206 interface (dict): Interface details
1209 if "port-security-enabled" in interface
:
1210 interface
["port_security"] = interface
.pop("port-security-enabled")
1212 if "port-security-disable-strategy" in interface
:
1213 interface
["port_security_disable_strategy"] = interface
.pop(
1214 "port-security-disable-strategy"
1218 def _create_net_item_of_interface(interface
: dict, net_text
: str) -> dict:
1219 """Prepare net item including name, port security, floating ip etc.
1222 interface (dict): Interface details
1223 net_text (str): information of net
1226 net_item (dict): Dict including net details
1232 for x
, v
in interface
.items()
1238 "port_security_disable_strategy",
1242 net_item
["net_id"] = "TASK-" + net_text
1243 net_item
["type"] = "virtual"
1248 def _prepare_type_of_interface(
1249 interface
: dict, tasks_by_target_record_id
: dict, net_text
: str, net_item
: dict
1251 """Fill the net item type by interface type such as SR-IOV, OM-MGMT, bridge etc.
1254 interface (dict): Interface details
1255 tasks_by_target_record_id (dict): Task details
1256 net_text (str): information of net
1257 net_item (dict): Dict including net details
1260 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1261 # TODO floating_ip: True/False (or it can be None)
1263 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1264 # Mark the net create task as type data
1266 tasks_by_target_record_id
,
1272 tasks_by_target_record_id
[net_text
]["extra_dict"]["params"][
1276 net_item
["use"] = "data"
1277 net_item
["model"] = interface
["type"]
1278 net_item
["type"] = interface
["type"]
1281 interface
.get("type") == "OM-MGMT"
1282 or interface
.get("mgmt-interface")
1283 or interface
.get("mgmt-vnf")
1285 net_item
["use"] = "mgmt"
1288 # If interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1289 net_item
["use"] = "bridge"
1290 net_item
["model"] = interface
.get("type")
1293 def _prepare_vdu_interfaces(
1299 tasks_by_target_record_id
: dict,
1302 """Prepare the net_item and add net_list, add mgmt interface to extra_dict.
1305 target_vdu (dict): VDU to be created
1306 extra_dict (dict): Dictionary to be filled
1307 ns_preffix (str): NS prefix as string
1308 vnf_preffix (str): VNF prefix as string
1309 logger (object): Logger Object
1310 tasks_by_target_record_id (dict): Task details
1311 net_list (list): Net list of VDU
1313 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
1314 net_text
= Ns
._check
_vld
_information
_of
_interfaces
(
1315 interface
, ns_preffix
, vnf_preffix
1318 # Interface not connected to any vld
1320 "Interface {} from vdu {} not connected to any vld".format(
1321 iface_index
, target_vdu
["vdu-name"]
1326 extra_dict
["depends_on"].append(net_text
)
1328 Ns
._prepare
_interface
_port
_security
(interface
)
1330 net_item
= Ns
._create
_net
_item
_of
_interface
(interface
, net_text
)
1332 Ns
._prepare
_type
_of
_interface
(
1333 interface
, tasks_by_target_record_id
, net_text
, net_item
1336 if interface
.get("ip-address"):
1337 net_item
["ip_address"] = interface
["ip-address"]
1339 if interface
.get("mac-address"):
1340 net_item
["mac_address"] = interface
["mac-address"]
1342 net_list
.append(net_item
)
1344 if interface
.get("mgmt-vnf"):
1345 extra_dict
["mgmt_vnf_interface"] = iface_index
1346 elif interface
.get("mgmt-interface"):
1347 extra_dict
["mgmt_vdu_interface"] = iface_index
1350 def _prepare_vdu_ssh_keys(
1351 target_vdu
: dict, ro_nsr_public_key
: dict, cloud_config
: dict
1353 """Add ssh keys to cloud config.
1356 target_vdu (dict): Details of VDU to be created
1357 ro_nsr_public_key (dict): RO NSR public Key
1358 cloud_config (dict): Cloud config details
1363 if target_vdu
.get("ssh-keys"):
1364 ssh_keys
+= target_vdu
.get("ssh-keys")
1366 if target_vdu
.get("ssh-access-required"):
1367 ssh_keys
.append(ro_nsr_public_key
)
1370 cloud_config
["key-pairs"] = ssh_keys
1373 def _select_persistent_root_disk(vsd
: dict, vdu
: dict) -> dict:
1374 """Selects the persistent root disk if exists.
1376 vsd (dict): Virtual storage descriptors in VNFD
1377 vdu (dict): VNF descriptor
1380 root_disk (dict): Selected persistent root disk
1382 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
1386 ) == "persistent-storage:persistent-storage" and root_disk
.get(
1392 def _add_persistent_root_disk_to_disk_list(
1393 vnfd
: dict, target_vdu
: dict, persistent_root_disk
: dict, disk_list
: list
1395 """Find the persistent root disk and add to disk list.
1398 vnfd (dict): VNF descriptor
1399 target_vdu (dict): Details of VDU to be created
1400 persistent_root_disk (dict): Details of persistent root disk
1401 disk_list (list): Disks of VDU
1404 for vdu
in vnfd
.get("vdu", ()):
1405 if vdu
["name"] == target_vdu
["vdu-name"]:
1406 for vsd
in vnfd
.get("virtual-storage-desc", ()):
1407 root_disk
= Ns
._select
_persistent
_root
_disk
(vsd
, vdu
)
1411 persistent_root_disk
[vsd
["id"]] = {
1412 "image_id": vdu
.get("sw-image-desc"),
1413 "size": root_disk
["size-of-storage"],
1414 "keep": Ns
.is_volume_keeping_required(root_disk
),
1416 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1420 def _add_persistent_ordinary_disks_to_disk_list(
1422 persistent_root_disk
: dict,
1423 persistent_ordinary_disk
: dict,
1427 """Fill the disk list by adding persistent ordinary disks.
1430 target_vdu (dict): Details of VDU to be created
1431 persistent_root_disk (dict): Details of persistent root disk
1432 persistent_ordinary_disk (dict): Details of persistent ordinary disk
1433 disk_list (list): Disks of VDU
1436 if target_vdu
.get("virtual-storages"):
1437 for disk
in target_vdu
["virtual-storages"]:
1439 disk
.get("type-of-storage")
1440 == "persistent-storage:persistent-storage"
1441 and disk
["id"] not in persistent_root_disk
.keys()
1443 name
, multiattach
= Ns
.is_shared_volume(disk
, vnf_id
)
1444 persistent_ordinary_disk
[disk
["id"]] = {
1446 "size": disk
["size-of-storage"],
1447 "keep": Ns
.is_volume_keeping_required(disk
),
1448 "multiattach": multiattach
,
1450 disk_list
.append(persistent_ordinary_disk
[disk
["id"]])
1453 def _prepare_vdu_affinity_group_list(
1454 target_vdu
: dict, extra_dict
: dict, ns_preffix
: str
1455 ) -> List
[Dict
[str, any
]]:
1456 """Process affinity group details to prepare affinity group list.
1459 target_vdu (dict): Details of VDU to be created
1460 extra_dict (dict): Dictionary to be filled
1461 ns_preffix (str): Prefix as string
1465 affinity_group_list (list): Affinity group details
1468 affinity_group_list
= []
1470 if target_vdu
.get("affinity-or-anti-affinity-group-id"):
1471 for affinity_group_id
in target_vdu
["affinity-or-anti-affinity-group-id"]:
1473 affinity_group_text
= (
1474 ns_preffix
+ ":affinity-or-anti-affinity-group." + affinity_group_id
1477 if not isinstance(extra_dict
.get("depends_on"), list):
1478 raise NsException("Invalid extra_dict format.")
1480 extra_dict
["depends_on"].append(affinity_group_text
)
1481 affinity_group
["affinity_group_id"] = "TASK-" + affinity_group_text
1482 affinity_group_list
.append(affinity_group
)
1484 return affinity_group_list
1487 def _process_vdu_params(
1488 target_vdu
: Dict
[str, Any
],
1489 indata
: Dict
[str, Any
],
1490 vim_info
: Dict
[str, Any
],
1491 target_record_id
: str,
1492 **kwargs
: Dict
[str, Any
],
1493 ) -> Dict
[str, Any
]:
1494 """Function to process VDU parameters.
1497 target_vdu (Dict[str, Any]): [description]
1498 indata (Dict[str, Any]): [description]
1499 vim_info (Dict[str, Any]): [description]
1500 target_record_id (str): [description]
1503 Dict[str, Any]: [description]
1505 vnfr_id
= kwargs
.get("vnfr_id")
1506 nsr_id
= kwargs
.get("nsr_id")
1507 vnfr
= kwargs
.get("vnfr")
1508 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1509 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
1510 logger
= kwargs
.get("logger")
1511 db
= kwargs
.get("db")
1512 fs
= kwargs
.get("fs")
1513 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1515 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
1516 ns_preffix
= "nsrs:{}".format(nsr_id
)
1517 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
1518 extra_dict
= {"depends_on": [image_text
]}
1520 persistent_root_disk
= {}
1521 persistent_ordinary_disk
= {}
1522 vdu_instantiation_volumes_list
= []
1523 vdu_instantiation_flavor_id
= None
1525 vnfd_id
= vnfr
["vnfd-id"]
1526 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
1527 # If the position info is provided for all the interfaces, it will be sorted
1528 # according to position number ascendingly.
1530 True if i
.get("position") is not None else False
1531 for i
in target_vdu
["interfaces"]
1533 Ns
._sort
_vdu
_interfaces
(target_vdu
)
1535 # If the position info is provided for some interfaces but not all of them, the interfaces
1536 # which has specific position numbers will be placed and others' positions will not be taken care.
1538 Ns
._partially
_locate
_vdu
_interfaces
(target_vdu
)
1540 # If the position info is not provided for the interfaces, interfaces will be attached
1541 # according to the order in the VNFD.
1542 Ns
._prepare
_vdu
_interfaces
(
1548 tasks_by_target_record_id
,
1553 cloud_config
= Ns
._prepare
_vdu
_cloud
_init
(target_vdu
, vdu2cloud_init
, db
, fs
)
1555 # Prepare VDU ssh keys
1556 Ns
._prepare
_vdu
_ssh
_keys
(target_vdu
, ro_nsr_public_key
, cloud_config
)
1558 if target_vdu
.get("additionalParams"):
1559 vdu_instantiation_volumes_list
= (
1560 target_vdu
.get("additionalParams").get("OSM", {}).get("vdu_volumes")
1562 vdu_instantiation_flavor_id
= (
1563 target_vdu
.get("additionalParams").get("OSM", {}).get("vim_flavor_id")
1567 if vdu_instantiation_flavor_id
:
1568 flavor_id
= vdu_instantiation_flavor_id
1570 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
1571 flavor_id
= "TASK-" + flavor_text
1572 extra_dict
["depends_on"].append(flavor_text
)
1574 if vdu_instantiation_volumes_list
:
1575 # Find the root volumes and add to the disk_list
1576 persistent_root_disk
= Ns
.find_persistent_root_volumes(
1577 vnfd
, target_vdu
, vdu_instantiation_volumes_list
, disk_list
1580 # Find the ordinary volumes which are not added to the persistent_root_disk
1581 # and put them to the disk list
1582 Ns
.find_persistent_volumes(
1583 persistent_root_disk
,
1585 vdu_instantiation_volumes_list
,
1590 # Vdu_instantiation_volumes_list is empty
1591 # First get add the persistent root disks to disk_list
1592 Ns
._add
_persistent
_root
_disk
_to
_disk
_list
(
1593 vnfd
, target_vdu
, persistent_root_disk
, disk_list
1595 # Add the persistent non-root disks to disk_list
1596 Ns
._add
_persistent
_ordinary
_disks
_to
_disk
_list
(
1598 persistent_root_disk
,
1599 persistent_ordinary_disk
,
1604 affinity_group_list
= Ns
._prepare
_vdu
_affinity
_group
_list
(
1605 target_vdu
, extra_dict
, ns_preffix
1608 extra_dict
["params"] = {
1609 "name": "{}-{}-{}-{}".format(
1610 indata
["name"][:16],
1611 vnfr
["member-vnf-index-ref"][:16],
1612 target_vdu
["vdu-name"][:32],
1613 target_vdu
.get("count-index") or 0,
1615 "description": target_vdu
["vdu-name"],
1617 "image_id": "TASK-" + image_text
,
1618 "flavor_id": flavor_id
,
1619 "affinity_group_list": affinity_group_list
,
1620 "net_list": net_list
,
1621 "cloud_config": cloud_config
or None,
1622 "disk_list": disk_list
,
1623 "availability_zone_index": None, # TODO
1624 "availability_zone_list": None, # TODO
1629 def _process_shared_volumes_params(
1630 target_shared_volume
: Dict
[str, Any
],
1631 indata
: Dict
[str, Any
],
1632 vim_info
: Dict
[str, Any
],
1633 target_record_id
: str,
1634 **kwargs
: Dict
[str, Any
],
1635 ) -> Dict
[str, Any
]:
1637 shared_volume_data
= {
1638 "size": target_shared_volume
["size-of-storage"],
1639 "name": target_shared_volume
["id"],
1640 "type": target_shared_volume
["type-of-storage"],
1642 extra_dict
["params"] = shared_volume_data
1646 def _process_affinity_group_params(
1647 target_affinity_group
: Dict
[str, Any
],
1648 indata
: Dict
[str, Any
],
1649 vim_info
: Dict
[str, Any
],
1650 target_record_id
: str,
1651 **kwargs
: Dict
[str, Any
],
1652 ) -> Dict
[str, Any
]:
1653 """Get affinity or anti-affinity group parameters.
1656 target_affinity_group (Dict[str, Any]): [description]
1657 indata (Dict[str, Any]): [description]
1658 vim_info (Dict[str, Any]): [description]
1659 target_record_id (str): [description]
1662 Dict[str, Any]: [description]
1666 affinity_group_data
= {
1667 "name": target_affinity_group
["name"],
1668 "type": target_affinity_group
["type"],
1669 "scope": target_affinity_group
["scope"],
1672 if target_affinity_group
.get("vim-affinity-group-id"):
1673 affinity_group_data
["vim-affinity-group-id"] = target_affinity_group
[
1674 "vim-affinity-group-id"
1677 extra_dict
["params"] = {
1678 "affinity_group_data": affinity_group_data
,
1683 def _process_recreate_vdu_params(
1684 existing_vdu
: Dict
[str, Any
],
1685 db_nsr
: Dict
[str, Any
],
1686 vim_info
: Dict
[str, Any
],
1687 target_record_id
: str,
1689 **kwargs
: Dict
[str, Any
],
1690 ) -> Dict
[str, Any
]:
1691 """Function to process VDU parameters to recreate.
1694 existing_vdu (Dict[str, Any]): [description]
1695 db_nsr (Dict[str, Any]): [description]
1696 vim_info (Dict[str, Any]): [description]
1697 target_record_id (str): [description]
1698 target_id (str): [description]
1701 Dict[str, Any]: [description]
1703 vnfr
= kwargs
.get("vnfr")
1704 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1705 # logger = kwargs.get("logger")
1706 db
= kwargs
.get("db")
1707 fs
= kwargs
.get("fs")
1708 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1714 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
1716 if vim_details_text
:
1717 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
1719 for iface_index
, interface
in enumerate(existing_vdu
["interfaces"]):
1720 if "port-security-enabled" in interface
:
1721 interface
["port_security"] = interface
.pop("port-security-enabled")
1723 if "port-security-disable-strategy" in interface
:
1724 interface
["port_security_disable_strategy"] = interface
.pop(
1725 "port-security-disable-strategy"
1730 for x
, v
in interface
.items()
1736 "port_security_disable_strategy",
1740 existing_ifaces
= existing_vdu
["vim_info"][target_id
].get(
1741 "interfaces_backup", []
1746 for i
in existing_ifaces
1747 if i
["ip_address"] == interface
["ip-address"]
1752 net_item
["net_id"] = net_id
1753 net_item
["type"] = "virtual"
1755 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1756 # TODO floating_ip: True/False (or it can be None)
1757 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1758 net_item
["use"] = "data"
1759 net_item
["model"] = interface
["type"]
1760 net_item
["type"] = interface
["type"]
1762 interface
.get("type") == "OM-MGMT"
1763 or interface
.get("mgmt-interface")
1764 or interface
.get("mgmt-vnf")
1766 net_item
["use"] = "mgmt"
1768 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1769 net_item
["use"] = "bridge"
1770 net_item
["model"] = interface
.get("type")
1772 if interface
.get("ip-address"):
1773 net_item
["ip_address"] = interface
["ip-address"]
1775 if interface
.get("mac-address"):
1776 net_item
["mac_address"] = interface
["mac-address"]
1778 net_list
.append(net_item
)
1780 if interface
.get("mgmt-vnf"):
1781 extra_dict
["mgmt_vnf_interface"] = iface_index
1782 elif interface
.get("mgmt-interface"):
1783 extra_dict
["mgmt_vdu_interface"] = iface_index
1788 if existing_vdu
.get("cloud-init"):
1789 if existing_vdu
["cloud-init"] not in vdu2cloud_init
:
1790 vdu2cloud_init
[existing_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1793 location
=existing_vdu
["cloud-init"],
1796 cloud_content_
= vdu2cloud_init
[existing_vdu
["cloud-init"]]
1797 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1798 cloud_init_content
=cloud_content_
,
1799 params
=existing_vdu
.get("additionalParams"),
1800 context
=existing_vdu
["cloud-init"],
1803 if existing_vdu
.get("boot-data-drive"):
1804 cloud_config
["boot-data-drive"] = existing_vdu
.get("boot-data-drive")
1808 if existing_vdu
.get("ssh-keys"):
1809 ssh_keys
+= existing_vdu
.get("ssh-keys")
1811 if existing_vdu
.get("ssh-access-required"):
1812 ssh_keys
.append(ro_nsr_public_key
)
1815 cloud_config
["key-pairs"] = ssh_keys
1818 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
1819 disk_list
.append({"vim_id": vol_id
["id"]})
1821 affinity_group_list
= []
1823 if existing_vdu
.get("affinity-or-anti-affinity-group-id"):
1825 for affinity_group_id
in existing_vdu
["affinity-or-anti-affinity-group-id"]:
1826 for group
in db_nsr
.get("affinity-or-anti-affinity-group"):
1828 group
["id"] == affinity_group_id
1829 and group
["vim_info"][target_id
].get("vim_id", None) is not None
1831 affinity_group
["affinity_group_id"] = group
["vim_info"][
1833 ].get("vim_id", None)
1834 affinity_group_list
.append(affinity_group
)
1836 extra_dict
["params"] = {
1837 "name": "{}-{}-{}-{}".format(
1838 db_nsr
["name"][:16],
1839 vnfr
["member-vnf-index-ref"][:16],
1840 existing_vdu
["vdu-name"][:32],
1841 existing_vdu
.get("count-index") or 0,
1843 "description": existing_vdu
["vdu-name"],
1845 "image_id": vim_details
["image"]["id"],
1846 "flavor_id": vim_details
["flavor"]["id"],
1847 "affinity_group_list": affinity_group_list
,
1848 "net_list": net_list
,
1849 "cloud_config": cloud_config
or None,
1850 "disk_list": disk_list
,
1851 "availability_zone_index": None, # TODO
1852 "availability_zone_list": None, # TODO
1857 def calculate_diff_items(
1864 tasks_by_target_record_id
,
1871 """Function that returns the incremental changes (creation, deletion)
1872 related to a specific item `item` to be done. This function should be
1873 called for NS instantiation, NS termination, NS update to add a new VNF
1874 or a new VLD, remove a VNF or VLD, etc.
1875 Item can be `net`, `flavor`, `image` or `vdu`.
1876 It takes a list of target items from indata (which came from the REST API)
1877 and compares with the existing items from db_ro_nsr, identifying the
1878 incremental changes to be done. During the comparison, it calls the method
1879 `process_params` (which was passed as parameter, and is particular for each
1883 indata (Dict[str, Any]): deployment info
1884 db_nsr: NSR record from DB
1885 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1886 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1887 item (str): element to process (net, vdu...)
1888 tasks_by_target_record_id (Dict[str, Any]):
1889 [<target_record_id>, <task>]
1890 action_id (str): action id
1891 nsr_id (str): NSR id
1892 task_index (number): task index to add to task name
1893 vnfr_id (str): VNFR id
1894 vnfr (Dict[str, Any]): VNFR info
1897 List: list with the incremental changes (deletes, creates) for each item
1898 number: current task index
1906 process_params
= None
1907 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1908 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1909 # According to the type of item, the path, the target_list,
1910 # the existing_list and the method to process params are set
1911 db_path
= self
.db_path_map
[item
]
1912 process_params
= self
.process_params_function_map
[item
]
1913 if item
in ("net", "vdu"):
1914 # This case is specific for the NS VLD (not applied to VDU)
1916 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1917 target_list
= indata
.get("ns", []).get(db_path
, [])
1918 existing_list
= db_nsr
.get(db_path
, [])
1919 # This case is common for VNF VLDs and VNF VDUs
1921 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
1923 (vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
),
1926 target_list
= target_vnf
.get(db_path
, []) if target_vnf
else []
1927 existing_list
= vnfr
.get(db_path
, [])
1931 "affinity-or-anti-affinity-group",
1934 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1935 target_list
= indata
.get(item
, [])
1936 existing_list
= db_nsr
.get(item
, [])
1938 raise NsException("Item not supported: {}", item
)
1939 # ensure all the target_list elements has an "id". If not assign the index as id
1940 if target_list
is None:
1942 for target_index
, tl
in enumerate(target_list
):
1943 if tl
and not tl
.get("id"):
1944 tl
["id"] = str(target_index
)
1945 # step 1 items (networks,vdus,...) to be deleted/updated
1946 for item_index
, existing_item
in enumerate(existing_list
):
1948 (t
for t
in target_list
if t
["id"] == existing_item
["id"]),
1951 for target_vim
, existing_viminfo
in existing_item
.get(
1954 if existing_viminfo
is None:
1958 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
1960 target_viminfo
= None
1962 if target_viminfo
is None:
1964 self
._assign
_vim
(target_vim
)
1965 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
1968 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
1969 # item must be sdn-net instead of net if target_vim is a sdn
1971 target_record_id
+= ".sdn"
1974 "action_id": action_id
,
1976 "task_index": task_index
,
1981 "deployment_info": deployment_info
,
1982 "target_id": target_vim
,
1985 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1986 "target_record_id": target_record_id
,
1991 # step 2 items (networks,vdus,...) to be created
1992 for target_item
in target_list
:
1994 for item_index
, existing_item
in enumerate(existing_list
):
1995 if existing_item
["id"] == target_item
["id"]:
1999 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
2000 existing_list
.append(target_item
)
2001 existing_item
= None
2003 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
2004 existing_viminfo
= None
2007 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
2009 if existing_viminfo
is not None:
2012 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
2015 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
2016 # item must be sdn-net instead of net if target_vim is a sdn
2018 target_record_id
+= ".sdn"
2022 "ns.calculate_diff_items target_item={}".format(target_item
)
2024 if process_params
== Ns
._process
_flavor
_params
:
2031 "calculate_diff_items for flavor kwargs={}".format(kwargs
)
2034 if process_params
== Ns
._process
_vdu
_params
:
2035 self
.logger
.debug("calculate_diff_items self.fs={}".format(self
.fs
))
2041 "vdu2cloud_init": vdu2cloud_init
,
2042 "tasks_by_target_record_id": tasks_by_target_record_id
,
2043 "logger": self
.logger
,
2046 "ro_nsr_public_key": ro_nsr_public_key
,
2049 self
.logger
.debug("calculate_diff_items kwargs={}".format(kwargs
))
2050 extra_dict
= process_params(
2057 self
._assign
_vim
(target_vim
)
2060 "action_id": action_id
,
2062 "task_index": task_index
,
2066 "deployment_info": deployment_info
,
2067 "target_id": target_vim
,
2070 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
2071 "target_record_id": target_record_id
,
2072 "extra_dict": extra_dict
,
2073 "common_id": target_item
.get("common_id", None),
2075 diff_items
.append(new_item
)
2076 tasks_by_target_record_id
[target_record_id
] = new_item
2079 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
2081 return diff_items
, task_index
2083 def calculate_all_differences_to_deploy(
2093 tasks_by_target_record_id
,
2095 """This method calculates the ordered list of items (`changes_list`)
2096 to be created and deleted.
2099 indata (Dict[str, Any]): deployment info
2100 nsr_id (str): NSR id
2101 db_nsr: NSR record from DB
2102 db_vnfrs: VNFRS record from DB
2103 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2104 db_nsr_update (Dict[str, Any]): NSR info to update in DB
2105 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
2106 action_id (str): action id
2107 tasks_by_target_record_id (Dict[str, Any]):
2108 [<target_record_id>, <task>]
2111 List: ordered list of items to be created and deleted.
2115 # set list with diffs:
2118 # NS vld, image and flavor
2123 "affinity-or-anti-affinity-group",
2126 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
2127 diff_items
, task_index
= self
.calculate_diff_items(
2130 db_ro_nsr
=db_ro_nsr
,
2131 db_nsr_update
=db_nsr_update
,
2133 tasks_by_target_record_id
=tasks_by_target_record_id
,
2134 action_id
=action_id
,
2136 task_index
=task_index
,
2139 changes_list
+= diff_items
2142 for vnfr_id
, vnfr
in db_vnfrs
.items():
2143 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
2144 for item
in ["net", "vdu"]:
2145 self
.logger
.debug("process VNF={} {}".format(vnfr_id
, item
))
2146 diff_items
, task_index
= self
.calculate_diff_items(
2149 db_ro_nsr
=db_ro_nsr
,
2150 db_nsr_update
=db_vnfrs_update
[vnfr
["_id"]],
2152 tasks_by_target_record_id
=tasks_by_target_record_id
,
2153 action_id
=action_id
,
2155 task_index
=task_index
,
2159 changes_list
+= diff_items
2163 def define_all_tasks(
2167 tasks_by_target_record_id
,
2169 """Function to create all the task structures obtanied from
2170 the method calculate_all_differences_to_deploy
2173 changes_list (List): ordered list of items to be created or deleted
2174 db_new_tasks (List): tasks list to be created
2175 action_id (str): action id
2176 tasks_by_target_record_id (Dict[str, Any]):
2177 [<target_record_id>, <task>]
2181 for change
in changes_list
:
2182 task
= Ns
._create
_task
(
2183 deployment_info
=change
["deployment_info"],
2184 target_id
=change
["target_id"],
2185 item
=change
["item"],
2186 action
=change
["action"],
2187 target_record
=change
["target_record"],
2188 target_record_id
=change
["target_record_id"],
2189 extra_dict
=change
.get("extra_dict", None),
2192 self
.logger
.debug("ns.define_all_tasks task={}".format(task
))
2193 tasks_by_target_record_id
[change
["target_record_id"]] = task
2194 db_new_tasks
.append(task
)
2196 if change
.get("common_id"):
2197 task
["common_id"] = change
["common_id"]
2199 def upload_all_tasks(
2204 """Function to save all tasks in the common DB
2207 db_new_tasks (List): tasks list to be created
2208 now (time): current time
2212 nb_ro_tasks
= 0 # for logging
2214 for db_task
in db_new_tasks
:
2215 target_id
= db_task
.pop("target_id")
2216 common_id
= db_task
.get("common_id")
2218 # Do not chek tasks with vim_status DELETED
2219 # because in manual heealing there are two tasks for the same vdur:
2220 # one with vim_status deleted and the other one with the actual VM status.
2226 "target_id": target_id
,
2227 "tasks.common_id": common_id
,
2228 "vim_info.vim_status.ne": "DELETED",
2230 update_dict
={"to_check_at": now
, "modified_at": now
},
2231 push
={"tasks": db_task
},
2232 fail_on_empty
=False,
2236 if not self
.db
.set_one(
2239 "target_id": target_id
,
2240 "tasks.target_record": db_task
["target_record"],
2241 "vim_info.vim_status.ne": "DELETED",
2243 update_dict
={"to_check_at": now
, "modified_at": now
},
2244 push
={"tasks": db_task
},
2245 fail_on_empty
=False,
2248 self
.logger
.debug("Updating database, Creating ro_tasks")
2249 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2251 self
.db
.create("ro_tasks", db_ro_task
)
2254 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2255 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2259 def upload_recreate_tasks(
2264 """Function to save recreate tasks in the common DB
2267 db_new_tasks (List): tasks list to be created
2268 now (time): current time
2272 nb_ro_tasks
= 0 # for logging
2274 for db_task
in db_new_tasks
:
2275 target_id
= db_task
.pop("target_id")
2276 self
.logger
.debug("target_id={} db_task={}".format(target_id
, db_task
))
2278 action
= db_task
.get("action", None)
2281 self
.logger
.debug("Updating database, Creating ro_tasks")
2282 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2284 # If DELETE task: the associated created items should be removed
2285 # (except persistent volumes):
2286 if action
== "DELETE":
2287 db_ro_task
["vim_info"]["created"] = True
2288 db_ro_task
["vim_info"]["created_items"] = db_task
.get(
2291 db_ro_task
["vim_info"]["volumes_to_hold"] = db_task
.get(
2292 "volumes_to_hold", []
2294 db_ro_task
["vim_info"]["vim_id"] = db_task
.get("vim_id", None)
2297 self
.logger
.debug("upload_all_tasks db_ro_task={}".format(db_ro_task
))
2298 self
.db
.create("ro_tasks", db_ro_task
)
2301 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2302 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2306 def _prepare_created_items_for_healing(
2312 # Get created_items from ro_task
2313 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2314 for ro_task
in ro_tasks
:
2315 for task
in ro_task
["tasks"]:
2317 task
["target_record"] == target_record
2318 and task
["action"] == "CREATE"
2319 and ro_task
["vim_info"]["created_items"]
2321 created_items
= ro_task
["vim_info"]["created_items"]
2324 return created_items
2326 def _prepare_persistent_volumes_for_healing(
2331 # The associated volumes of the VM shouldn't be removed
2334 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
2335 if vim_details_text
:
2336 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
2338 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
2339 volumes_list
.append(vol_id
["id"])
2343 def prepare_changes_to_recreate(
2351 tasks_by_target_record_id
,
2353 """This method will obtain an ordered list of items (`changes_list`)
2354 to be created and deleted to meet the recreate request.
2358 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id
, indata
)
2362 # set list with diffs:
2364 db_path
= self
.db_path_map
["vdu"]
2365 target_list
= indata
.get("healVnfData", {})
2366 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
2367 ro_nsr_public_key
= db_ro_nsr
["public_key"]
2369 # Check each VNF of the target
2370 for target_vnf
in target_list
:
2371 # Find this VNF in the list from DB, raise exception if vnfInstanceId is not found
2372 vnfr_id
= target_vnf
["vnfInstanceId"]
2373 existing_vnf
= db_vnfrs
.get(vnfr_id
)
2374 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
2375 # vim_account_id = existing_vnf.get("vim-account-id", "")
2377 target_vdus
= target_vnf
.get("additionalParams", {}).get("vdu", [])
2378 # Check each VDU of this VNF
2380 # Create target_vdu_list from DB, if VDUs are not specified
2382 for existing_vdu
in existing_vnf
.get("vdur"):
2383 vdu_name
= existing_vdu
.get("vdu-name", None)
2384 vdu_index
= existing_vdu
.get("count-index", 0)
2385 vdu_to_be_healed
= {"vdu-id": vdu_name
, "count-index": vdu_index
}
2386 target_vdus
.append(vdu_to_be_healed
)
2387 for target_vdu
in target_vdus
:
2388 vdu_name
= target_vdu
.get("vdu-id", None)
2389 # For multi instance VDU count-index is mandatory
2390 # For single session VDU count-indes is 0
2391 count_index
= target_vdu
.get("count-index", 0)
2393 existing_instance
= None
2394 for instance
in existing_vnf
.get("vdur", None):
2396 instance
["vdu-name"] == vdu_name
2397 and instance
["count-index"] == count_index
2399 existing_instance
= instance
2404 target_record_id
= "{}.{}".format(db_record
, existing_instance
["id"])
2406 # The target VIM is the one already existing in DB to recreate
2407 for target_vim
, target_viminfo
in existing_instance
.get(
2410 # step 1 vdu to be deleted
2411 self
._assign
_vim
(target_vim
)
2413 "action_id": action_id
,
2415 "task_index": task_index
,
2418 target_record
= f
"{db_record}.{item_index}.vim_info.{target_vim}"
2419 created_items
= self
._prepare
_created
_items
_for
_healing
(
2420 nsr_id
, target_record
2423 volumes_to_hold
= self
._prepare
_persistent
_volumes
_for
_healing
(
2424 target_vim
, existing_instance
2427 # Specific extra params for recreate tasks:
2429 "created_items": created_items
,
2430 "vim_id": existing_instance
["vim-id"],
2431 "volumes_to_hold": volumes_to_hold
,
2434 changes_list
.append(
2436 "deployment_info": deployment_info
,
2437 "target_id": target_vim
,
2440 "target_record": target_record
,
2441 "target_record_id": target_record_id
,
2442 "extra_dict": extra_dict
,
2445 delete_task_id
= f
"{action_id}:{task_index}"
2448 # step 2 vdu to be created
2454 "vnfr": existing_vnf
,
2455 "vdu2cloud_init": vdu2cloud_init
,
2456 "tasks_by_target_record_id": tasks_by_target_record_id
,
2457 "logger": self
.logger
,
2460 "ro_nsr_public_key": ro_nsr_public_key
,
2464 extra_dict
= self
._process
_recreate
_vdu
_params
(
2473 # The CREATE task depens on the DELETE task
2474 extra_dict
["depends_on"] = [delete_task_id
]
2476 # Add volumes created from created_items if any
2477 # Ports should be deleted with delete task and automatically created with create task
2479 for k
, v
in created_items
.items():
2481 k_item
, _
, k_id
= k
.partition(":")
2482 if k_item
== "volume":
2484 except Exception as e
:
2486 "Error evaluating created item {}: {}".format(k
, e
)
2488 extra_dict
["previous_created_volumes"] = volumes
2491 "action_id": action_id
,
2493 "task_index": task_index
,
2495 self
._assign
_vim
(target_vim
)
2498 "deployment_info": deployment_info
,
2499 "target_id": target_vim
,
2502 "target_record": target_record
,
2503 "target_record_id": target_record_id
,
2504 "extra_dict": extra_dict
,
2506 changes_list
.append(new_item
)
2507 tasks_by_target_record_id
[target_record_id
] = new_item
2512 def recreate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2513 self
.logger
.debug("ns.recreate nsr_id={} indata={}".format(nsr_id
, indata
))
2514 # TODO: validate_input(indata, recreate_schema)
2515 action_id
= indata
.get("action_id", str(uuid4()))
2516 # get current deployment
2517 db_vnfrs
= {} # vnf's info indexed by _id
2519 logging_text
= "Recreate nsr_id={} action_id={} indata={}".format(
2520 nsr_id
, action_id
, indata
2522 self
.logger
.debug(logging_text
+ "Enter")
2525 step
= "Getting ns and vnfr record from db"
2526 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2528 tasks_by_target_record_id
= {}
2529 # read from db: vnf's of this ns
2530 step
= "Getting vnfrs from db"
2531 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2532 self
.logger
.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list
))
2534 if not db_vnfrs_list
:
2535 raise NsException("Cannot obtain associated VNF for ns")
2537 for vnfr
in db_vnfrs_list
:
2538 db_vnfrs
[vnfr
["_id"]] = vnfr
2541 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2542 self
.logger
.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr
))
2545 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2547 with self
.write_lock
:
2549 step
= "process NS elements"
2550 changes_list
= self
.prepare_changes_to_recreate(
2555 db_ro_nsr
=db_ro_nsr
,
2556 action_id
=action_id
,
2557 tasks_by_target_record_id
=tasks_by_target_record_id
,
2560 self
.define_all_tasks(
2561 changes_list
=changes_list
,
2562 db_new_tasks
=db_new_tasks
,
2563 tasks_by_target_record_id
=tasks_by_target_record_id
,
2566 # Delete all ro_tasks registered for the targets vdurs (target_record)
2567 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2568 # So remove all task related to target record.
2569 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2570 for change
in changes_list
:
2571 for ro_task
in ro_tasks
:
2572 for task
in ro_task
["tasks"]:
2573 if task
["target_record"] == change
["target_record"]:
2577 "_id": ro_task
["_id"],
2578 "modified_at": ro_task
["modified_at"],
2580 fail_on_empty
=False,
2583 step
= "Updating database, Appending tasks to ro_tasks"
2584 self
.upload_recreate_tasks(
2585 db_new_tasks
=db_new_tasks
,
2590 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2594 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2598 except Exception as e
:
2599 if isinstance(e
, (DbException
, NsException
)):
2601 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2604 e
= traceback_format_exc()
2605 self
.logger
.critical(
2606 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2610 raise NsException(e
)
2612 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2613 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
2614 validate_input(indata
, deploy_schema
)
2615 action_id
= indata
.get("action_id", str(uuid4()))
2617 # get current deployment
2618 db_nsr_update
= {} # update operation on nsrs
2619 db_vnfrs_update
= {}
2620 db_vnfrs
= {} # vnf's info indexed by _id
2622 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2623 self
.logger
.debug(logging_text
+ "Enter")
2626 step
= "Getting ns and vnfr record from db"
2627 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2628 self
.logger
.debug("ns.deploy: db_nsr={}".format(db_nsr
))
2630 tasks_by_target_record_id
= {}
2631 # read from db: vnf's of this ns
2632 step
= "Getting vnfrs from db"
2633 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2635 if not db_vnfrs_list
:
2636 raise NsException("Cannot obtain associated VNF for ns")
2638 for vnfr
in db_vnfrs_list
:
2639 db_vnfrs
[vnfr
["_id"]] = vnfr
2640 db_vnfrs_update
[vnfr
["_id"]] = {}
2641 self
.logger
.debug("ns.deploy db_vnfrs={}".format(db_vnfrs
))
2644 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2647 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2649 # check that action_id is not in the list of actions. Suffixed with :index
2650 if action_id
in db_ro_nsr
["actions"]:
2654 new_action_id
= "{}:{}".format(action_id
, index
)
2656 if new_action_id
not in db_ro_nsr
["actions"]:
2657 action_id
= new_action_id
2660 + "Changing action_id in use to {}".format(action_id
)
2666 def _process_action(indata
):
2667 nonlocal db_new_tasks
2674 if indata
["action"]["action"] == "inject_ssh_key":
2675 key
= indata
["action"].get("key")
2676 user
= indata
["action"].get("user")
2677 password
= indata
["action"].get("password")
2679 for vnf
in indata
.get("vnf", ()):
2680 if vnf
["_id"] not in db_vnfrs
:
2681 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
2683 db_vnfr
= db_vnfrs
[vnf
["_id"]]
2685 for target_vdu
in vnf
.get("vdur", ()):
2686 vdu_index
, vdur
= next(
2689 for i_v
in enumerate(db_vnfr
["vdur"])
2690 if i_v
[1]["id"] == target_vdu
["id"]
2697 "Invalid vdu vnf={}.{}".format(
2698 vnf
["_id"], target_vdu
["id"]
2702 target_vim
, vim_info
= next(
2703 k_v
for k_v
in vdur
["vim_info"].items()
2705 self
._assign
_vim
(target_vim
)
2706 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
2707 vnf
["_id"], vdu_index
2711 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
2714 "ip_address": vdur
.get("ip-address"),
2717 "password": password
,
2718 "private_key": db_ro_nsr
["private_key"],
2719 "salt": db_ro_nsr
["_id"],
2720 "schema_version": db_ro_nsr
["_admin"][
2727 "action_id": action_id
,
2729 "task_index": task_index
,
2732 task
= Ns
._create
_task
(
2733 deployment_info
=deployment_info
,
2734 target_id
=target_vim
,
2737 target_record
=target_record
,
2738 target_record_id
=None,
2739 extra_dict
=extra_dict
,
2742 task_index
= deployment_info
.get("task_index")
2744 db_new_tasks
.append(task
)
2746 with self
.write_lock
:
2747 if indata
.get("action"):
2748 _process_action(indata
)
2750 # compute network differences
2752 step
= "process NS elements"
2753 changes_list
= self
.calculate_all_differences_to_deploy(
2758 db_ro_nsr
=db_ro_nsr
,
2759 db_nsr_update
=db_nsr_update
,
2760 db_vnfrs_update
=db_vnfrs_update
,
2761 action_id
=action_id
,
2762 tasks_by_target_record_id
=tasks_by_target_record_id
,
2764 self
.define_all_tasks(
2765 changes_list
=changes_list
,
2766 db_new_tasks
=db_new_tasks
,
2767 tasks_by_target_record_id
=tasks_by_target_record_id
,
2770 step
= "Updating database, Appending tasks to ro_tasks"
2771 self
.upload_all_tasks(
2772 db_new_tasks
=db_new_tasks
,
2776 step
= "Updating database, nsrs"
2778 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
2780 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
2782 step
= "Updating database, vnfrs={}".format(vnfr_id
)
2783 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
2786 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2790 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2794 except Exception as e
:
2795 if isinstance(e
, (DbException
, NsException
)):
2797 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2800 e
= traceback_format_exc()
2801 self
.logger
.critical(
2802 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2806 raise NsException(e
)
2808 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2809 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
2810 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2812 with self
.write_lock
:
2814 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
2815 except NsWorkerException
as e
:
2816 raise NsException(e
)
2818 return None, None, True
2820 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2822 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2823 version
, nsr_id
, action_id
, indata
2829 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
2830 global_status
= "DONE"
2833 for ro_task
in ro_tasks
:
2834 for task
in ro_task
["tasks"]:
2835 if task
and task
["action_id"] == action_id
:
2836 task_list
.append(task
)
2839 if task
["status"] == "FAILED":
2840 global_status
= "FAILED"
2841 error_text
= "Error at {} {}: {}".format(
2842 task
["action"].lower(),
2844 ro_task
["vim_info"].get("vim_message") or "unknown",
2846 details
.append(error_text
)
2847 elif task
["status"] in ("SCHEDULED", "BUILD"):
2848 if global_status
!= "FAILED":
2849 global_status
= "BUILD"
2854 "status": global_status
,
2855 "details": ". ".join(details
)
2857 else "progress {}/{}".format(done
, total
),
2859 "action_id": action_id
,
2863 return return_data
, None, True
2865 def recreate_status(
2866 self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
2868 return self
.status(session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
)
2870 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2872 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2873 session
, indata
, version
, nsr_id
, action_id
2877 return None, None, True
2879 def rebuild_start_stop_task(
2890 self
._assign
_vim
(target_vim
)
2891 target_record
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_index
)
2892 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_id
)
2894 "action_id": action_id
,
2896 "task_index": task_index
,
2899 task
= Ns
._create
_task
(
2900 deployment_info
=deployment_info
,
2901 target_id
=target_vim
,
2904 target_record
=target_record
,
2905 target_record_id
=target_record_id
,
2906 extra_dict
=extra_dict
,
2910 def rebuild_start_stop(
2911 self
, session
, action_dict
, version
, nsr_id
, *args
, **kwargs
2916 action_id
= action_dict
.get("action_id", str(uuid4()))
2918 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2919 self
.logger
.debug(logging_text
+ "Enter")
2921 action
= list(action_dict
.keys())[0]
2922 task_dict
= action_dict
.get(action
)
2923 vim_vm_id
= action_dict
.get(action
).get("vim_vm_id")
2925 if action_dict
.get("stop"):
2929 step
= "lock the operation & do task creation"
2930 with self
.write_lock
:
2931 extra_dict
["params"] = {
2932 "vim_vm_id": vim_vm_id
,
2935 task
= self
.rebuild_start_stop_task(
2936 task_dict
["vdu_id"],
2937 task_dict
["vnf_id"],
2938 task_dict
["vdu_index"],
2942 task_dict
["target_vim"],
2945 db_new_tasks
.append(task
)
2946 step
= "upload Task to db"
2947 self
.upload_all_tasks(
2948 db_new_tasks
=db_new_tasks
,
2952 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2955 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2959 except Exception as e
:
2960 if isinstance(e
, (DbException
, NsException
)):
2962 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2965 e
= traceback_format_exc()
2966 self
.logger
.critical(
2967 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2970 raise NsException(e
)
2972 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2973 nsrs
= self
.db
.get_list("nsrs", {})
2977 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
2979 return return_data
, None, True
2981 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2982 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2985 for ro_task
in ro_tasks
:
2986 for task
in ro_task
["tasks"]:
2987 if task
["action_id"] not in return_data
:
2988 return_data
.append(task
["action_id"])
2990 return return_data
, None, True
2993 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
2995 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
2996 self
._assign
_vim
(target_vim
)
2997 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
2998 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
3000 "action_id": action_id
,
3002 "task_index": task_index
,
3005 task
= Ns
._create
_task
(
3006 deployment_info
=deployment_info
,
3007 target_id
=target_vim
,
3010 target_record
=target_record
,
3011 target_record_id
=target_record_id
,
3012 extra_dict
=extra_dict
,
3017 def migrate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3021 action_id
= indata
.get("action_id", str(uuid4()))
3023 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
3024 self
.logger
.debug(logging_text
+ "Enter")
3026 vnf_instance_id
= indata
["vnfInstanceId"]
3027 step
= "Getting vnfrs from db"
3028 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
3029 vdu
= indata
.get("vdu")
3030 migrateToHost
= indata
.get("migrateToHost")
3033 with self
.write_lock
:
3035 vdu_id
= indata
["vdu"]["vduId"]
3036 vdu_count_index
= indata
["vdu"].get("vduCountIndex", 0)
3037 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3039 vdu
["vdu-id-ref"] == vdu_id
3040 and vdu
["count-index"] == vdu_count_index
3042 extra_dict
["params"] = {
3043 "vim_vm_id": vdu
["vim-id"],
3044 "migrate_host": migrateToHost
,
3045 "vdu_vim_info": vdu
["vim_info"],
3047 step
= "Creating migration task for vdu:{}".format(vdu
)
3048 task
= self
.migrate_task(
3057 db_new_tasks
.append(task
)
3061 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3062 extra_dict
["params"] = {
3063 "vim_vm_id": vdu
["vim-id"],
3064 "migrate_host": migrateToHost
,
3065 "vdu_vim_info": vdu
["vim_info"],
3067 step
= "Creating migration task for vdu:{}".format(vdu
)
3068 task
= self
.migrate_task(
3077 db_new_tasks
.append(task
)
3080 self
.upload_all_tasks(
3081 db_new_tasks
=db_new_tasks
,
3086 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3089 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3093 except Exception as e
:
3094 if isinstance(e
, (DbException
, NsException
)):
3096 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3099 e
= traceback_format_exc()
3100 self
.logger
.critical(
3101 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3104 raise NsException(e
)
3106 def verticalscale_task(
3107 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
3109 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
3110 self
._assign
_vim
(target_vim
)
3111 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
3112 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
3114 "action_id": action_id
,
3116 "task_index": task_index
,
3119 task
= Ns
._create
_task
(
3120 deployment_info
=deployment_info
,
3121 target_id
=target_vim
,
3122 item
="verticalscale",
3124 target_record
=target_record
,
3125 target_record_id
=target_record_id
,
3126 extra_dict
=extra_dict
,
3130 def verticalscale(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3134 action_id
= indata
.get("action_id", str(uuid4()))
3136 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
3137 self
.logger
.debug(logging_text
+ "Enter")
3139 VnfFlavorData
= indata
.get("changeVnfFlavorData")
3140 vnf_instance_id
= VnfFlavorData
["vnfInstanceId"]
3141 step
= "Getting vnfrs from db"
3142 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
3143 vduid
= VnfFlavorData
["additionalParams"]["vduid"]
3144 vduCountIndex
= VnfFlavorData
["additionalParams"]["vduCountIndex"]
3145 virtualMemory
= VnfFlavorData
["additionalParams"]["virtualMemory"]
3146 numVirtualCpu
= VnfFlavorData
["additionalParams"]["numVirtualCpu"]
3147 sizeOfStorage
= VnfFlavorData
["additionalParams"]["sizeOfStorage"]
3149 "name": vduid
+ "-flv",
3150 "ram": virtualMemory
,
3151 "vcpus": numVirtualCpu
,
3152 "disk": sizeOfStorage
,
3155 step
= "Creating Tasks for vertical scaling"
3156 with self
.write_lock
:
3157 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3159 vdu
["vdu-id-ref"] == vduid
3160 and vdu
["count-index"] == vduCountIndex
3162 extra_dict
["params"] = {
3163 "vim_vm_id": vdu
["vim-id"],
3164 "flavor_dict": flavor_dict
,
3166 task
= self
.verticalscale_task(
3175 db_new_tasks
.append(task
)
3178 self
.upload_all_tasks(
3179 db_new_tasks
=db_new_tasks
,
3183 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3186 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3190 except Exception as e
:
3191 if isinstance(e
, (DbException
, NsException
)):
3193 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3196 e
= traceback_format_exc()
3197 self
.logger
.critical(
3198 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3201 raise NsException(e
)