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")
821 for vnf
in indata
.get("vnf", []):
822 for vdur
in vnf
.get("vdur", []):
823 if vdur
.get("ns-flavor-id") == target_flavor
.get("id"):
827 target_vdur
.get("additionalParams", {}).get("OSM", {}).get("vim_flavor_id")
829 if vim_flavor_id
: # vim-flavor-id was passed so flavor won't be created
830 return {"find_params": {"vim_flavor_id": vim_flavor_id
}}
833 "disk": int(target_flavor
["storage-gb"]),
834 "ram": int(target_flavor
["memory-mb"]),
835 "vcpus": int(target_flavor
["vcpu-count"]),
838 if db
and isinstance(indata
.get("vnf"), list):
839 vnfd_id
= indata
.get("vnf")[0].get("vnfd-id")
840 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
841 # check if there is persistent root disk
842 for vdu
in vnfd
.get("vdu", ()):
843 if vdu
["name"] == target_vdur
.get("vdu-name"):
844 for vsd
in vnfd
.get("virtual-storage-desc", ()):
845 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
848 root_disk
.get("type-of-storage")
849 == "persistent-storage:persistent-storage"
851 flavor_data
["disk"] = 0
853 for storage
in target_vdur
.get("virtual-storages", []):
855 storage
.get("type-of-storage")
856 == "etsi-nfv-descriptors:ephemeral-storage"
858 flavor_data
["ephemeral"] = int(storage
.get("size-of-storage", 0))
859 elif storage
.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
860 flavor_data
["swap"] = int(storage
.get("size-of-storage", 0))
862 extended
= Ns
._process
_epa
_params
(target_flavor
)
864 flavor_data
["extended"] = extended
866 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
867 flavor_data_name
= flavor_data
.copy()
868 flavor_data_name
["name"] = target_flavor
["name"]
869 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
873 def _process_net_params(
874 target_vld
: Dict
[str, Any
],
875 indata
: Dict
[str, Any
],
876 vim_info
: Dict
[str, Any
],
877 target_record_id
: str,
878 **kwargs
: Dict
[str, Any
],
880 """Function to process network parameters.
883 target_vld (Dict[str, Any]): [description]
884 indata (Dict[str, Any]): [description]
885 vim_info (Dict[str, Any]): [description]
886 target_record_id (str): [description]
889 Dict[str, Any]: [description]
893 if vim_info
.get("sdn"):
894 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
895 # ns_preffix = "nsrs:{}".format(nsr_id)
896 # remove the ending ".sdn
897 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
898 extra_dict
["params"] = {
900 for k
in ("sdn-ports", "target_vim", "vlds", "type")
904 # TODO needed to add target_id in the dependency.
905 if vim_info
.get("target_vim"):
906 extra_dict
["depends_on"] = [
907 f
"{vim_info.get('target_vim')} {vld_target_record_id}"
912 if vim_info
.get("vim_network_name"):
913 extra_dict
["find_params"] = {
915 "name": vim_info
.get("vim_network_name"),
918 elif vim_info
.get("vim_network_id"):
919 extra_dict
["find_params"] = {
921 "id": vim_info
.get("vim_network_id"),
924 elif target_vld
.get("mgmt-network") and not vim_info
.get("provider_network"):
925 extra_dict
["find_params"] = {
927 "name": target_vld
["id"],
931 extra_dict
["params"] = {
933 f
"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
935 "ip_profile": vim_info
.get("ip_profile"),
936 "provider_network_profile": vim_info
.get("provider_network"),
939 if not target_vld
.get("underlay"):
940 extra_dict
["params"]["net_type"] = "bridge"
942 extra_dict
["params"]["net_type"] = (
943 "ptp" if target_vld
.get("type") == "ELINE" else "data"
949 def find_persistent_root_volumes(
952 vdu_instantiation_volumes_list
: list,
955 """Find the persistent root volumes and add them to the disk_list
956 by parsing the instantiation parameters.
959 vnfd (dict): VNF descriptor
960 target_vdu (dict): processed VDU
961 vdu_instantiation_volumes_list (list): instantiation parameters for the each VDU as a list
962 disk_list (list): to be filled up
965 persistent_root_disk (dict): Details of persistent root disk
968 persistent_root_disk
= {}
969 # There can be only one root disk, when we find it, it will return the result
971 for vdu
, vsd
in product(
972 vnfd
.get("vdu", ()), vnfd
.get("virtual-storage-desc", ())
975 vdu
["name"] == target_vdu
["vdu-name"]
976 and vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]
980 root_disk
.get("type-of-storage")
981 == "persistent-storage:persistent-storage"
983 for vdu_volume
in vdu_instantiation_volumes_list
:
985 vdu_volume
["vim-volume-id"]
986 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 return persistent_root_disk
998 if root_disk
.get("size-of-storage"):
999 persistent_root_disk
[vsd
["id"]] = {
1000 "image_id": vdu
.get("sw-image-desc"),
1001 "size": root_disk
.get("size-of-storage"),
1002 "keep": Ns
.is_volume_keeping_required(root_disk
),
1005 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1007 return persistent_root_disk
1008 return persistent_root_disk
1011 def find_persistent_volumes(
1012 persistent_root_disk
: dict,
1014 vdu_instantiation_volumes_list
: list,
1017 """Find the ordinary persistent volumes and add them to the disk_list
1018 by parsing the instantiation parameters.
1021 persistent_root_disk: persistent root disk dictionary
1022 target_vdu: processed VDU
1023 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1024 disk_list: to be filled up
1027 # Find the ordinary volumes which are not added to the persistent_root_disk
1028 persistent_disk
= {}
1029 for disk
in target_vdu
.get("virtual-storages", {}):
1031 disk
.get("type-of-storage") == "persistent-storage:persistent-storage"
1032 and disk
["id"] not in persistent_root_disk
.keys()
1034 for vdu_volume
in vdu_instantiation_volumes_list
:
1035 if vdu_volume
["vim-volume-id"] and disk
["id"] == vdu_volume
["name"]:
1036 persistent_disk
[disk
["id"]] = {
1037 "vim_volume_id": vdu_volume
["vim-volume-id"],
1039 disk_list
.append(persistent_disk
[disk
["id"]])
1042 if disk
["id"] not in persistent_disk
.keys():
1043 persistent_disk
[disk
["id"]] = {
1044 "size": disk
.get("size-of-storage"),
1045 "keep": Ns
.is_volume_keeping_required(disk
),
1047 disk_list
.append(persistent_disk
[disk
["id"]])
1050 def is_volume_keeping_required(virtual_storage_desc
: Dict
[str, Any
]) -> bool:
1051 """Function to decide keeping persistent volume
1055 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1061 if not virtual_storage_desc
.get("vdu-storage-requirements"):
1063 for item
in virtual_storage_desc
.get("vdu-storage-requirements", {}):
1064 if item
.get("key") == "keep-volume" and item
.get("value").lower() == "true":
1069 def is_shared_volume(
1070 virtual_storage_desc
: Dict
[str, Any
], vnfd_id
: str
1072 """Function to decide if the volume type is multi attached or not .
1075 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1076 vnfd_id (str): vnfd id
1080 name (str) New name if it is a multiattach disk
1083 if vdu_storage_requirements
:= virtual_storage_desc
.get(
1084 "vdu-storage-requirements", {}
1086 for item
in vdu_storage_requirements
:
1088 item
.get("key") == "multiattach"
1089 and item
.get("value").lower() == "true"
1091 name
= f
"shared-{virtual_storage_desc['id']}-{vnfd_id}"
1093 return virtual_storage_desc
["id"], False
1096 def _sort_vdu_interfaces(target_vdu
: dict) -> None:
1097 """Sort the interfaces according to position number.
1100 target_vdu (dict): Details of VDU to be created
1103 # If the position info is provided for all the interfaces, it will be sorted
1104 # according to position number ascendingly.
1105 sorted_interfaces
= sorted(
1106 target_vdu
["interfaces"],
1107 key
=lambda x
: (x
.get("position") is None, x
.get("position")),
1109 target_vdu
["interfaces"] = sorted_interfaces
1112 def _partially_locate_vdu_interfaces(target_vdu
: dict) -> None:
1113 """Only place the interfaces which has specific position.
1116 target_vdu (dict): Details of VDU to be created
1119 # If the position info is provided for some interfaces but not all of them, the interfaces
1120 # which has specific position numbers will be placed and others' positions will not be taken care.
1122 i
.get("position") + 1
1123 for i
in target_vdu
["interfaces"]
1124 if i
.get("position") is not None
1126 n
= len(target_vdu
["interfaces"])
1127 sorted_interfaces
= [-1] * n
1131 if target_vdu
["interfaces"][k
].get("position") is not None:
1132 if any(i
.get("position") == 0 for i
in target_vdu
["interfaces"]):
1133 idx
= target_vdu
["interfaces"][k
]["position"] + 1
1135 idx
= target_vdu
["interfaces"][k
]["position"]
1136 sorted_interfaces
[idx
- 1] = target_vdu
["interfaces"][k
]
1140 if target_vdu
["interfaces"][m
].get("position") is None:
1141 idy
= sorted_interfaces
.index(-1)
1142 sorted_interfaces
[idy
] = target_vdu
["interfaces"][m
]
1145 target_vdu
["interfaces"] = sorted_interfaces
1148 def _prepare_vdu_cloud_init(
1149 target_vdu
: dict, vdu2cloud_init
: dict, db
: object, fs
: object
1151 """Fill cloud_config dict with cloud init details.
1154 target_vdu (dict): Details of VDU to be created
1155 vdu2cloud_init (dict): Cloud init dict
1156 db (object): DB object
1157 fs (object): FS object
1160 cloud_config (dict): Cloud config details of VDU
1166 if target_vdu
.get("cloud-init"):
1167 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1168 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1171 location
=target_vdu
["cloud-init"],
1174 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1175 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1176 cloud_init_content
=cloud_content_
,
1177 params
=target_vdu
.get("additionalParams"),
1178 context
=target_vdu
["cloud-init"],
1181 if target_vdu
.get("boot-data-drive"):
1182 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1187 def _check_vld_information_of_interfaces(
1188 interface
: dict, ns_preffix
: str, vnf_preffix
: str
1190 """Prepare the net_text by the virtual link information for vnf and ns level.
1192 interface (dict): Interface details
1193 ns_preffix (str): Prefix of NS
1194 vnf_preffix (str): Prefix of VNF
1197 net_text (str): information of net
1201 if interface
.get("ns-vld-id"):
1202 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
1203 elif interface
.get("vnf-vld-id"):
1204 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
1209 def _prepare_interface_port_security(interface
: dict) -> None:
1213 interface (dict): Interface details
1216 if "port-security-enabled" in interface
:
1217 interface
["port_security"] = interface
.pop("port-security-enabled")
1219 if "port-security-disable-strategy" in interface
:
1220 interface
["port_security_disable_strategy"] = interface
.pop(
1221 "port-security-disable-strategy"
1225 def _create_net_item_of_interface(interface
: dict, net_text
: str) -> dict:
1226 """Prepare net item including name, port security, floating ip etc.
1229 interface (dict): Interface details
1230 net_text (str): information of net
1233 net_item (dict): Dict including net details
1239 for x
, v
in interface
.items()
1245 "port_security_disable_strategy",
1249 net_item
["net_id"] = "TASK-" + net_text
1250 net_item
["type"] = "virtual"
1255 def _prepare_type_of_interface(
1256 interface
: dict, tasks_by_target_record_id
: dict, net_text
: str, net_item
: dict
1258 """Fill the net item type by interface type such as SR-IOV, OM-MGMT, bridge etc.
1261 interface (dict): Interface details
1262 tasks_by_target_record_id (dict): Task details
1263 net_text (str): information of net
1264 net_item (dict): Dict including net details
1267 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1268 # TODO floating_ip: True/False (or it can be None)
1270 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1271 # Mark the net create task as type data
1273 tasks_by_target_record_id
,
1279 tasks_by_target_record_id
[net_text
]["extra_dict"]["params"][
1283 net_item
["use"] = "data"
1284 net_item
["model"] = interface
["type"]
1285 net_item
["type"] = interface
["type"]
1288 interface
.get("type") == "OM-MGMT"
1289 or interface
.get("mgmt-interface")
1290 or interface
.get("mgmt-vnf")
1292 net_item
["use"] = "mgmt"
1295 # If interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1296 net_item
["use"] = "bridge"
1297 net_item
["model"] = interface
.get("type")
1300 def _prepare_vdu_interfaces(
1306 tasks_by_target_record_id
: dict,
1309 """Prepare the net_item and add net_list, add mgmt interface to extra_dict.
1312 target_vdu (dict): VDU to be created
1313 extra_dict (dict): Dictionary to be filled
1314 ns_preffix (str): NS prefix as string
1315 vnf_preffix (str): VNF prefix as string
1316 logger (object): Logger Object
1317 tasks_by_target_record_id (dict): Task details
1318 net_list (list): Net list of VDU
1320 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
1321 net_text
= Ns
._check
_vld
_information
_of
_interfaces
(
1322 interface
, ns_preffix
, vnf_preffix
1325 # Interface not connected to any vld
1327 "Interface {} from vdu {} not connected to any vld".format(
1328 iface_index
, target_vdu
["vdu-name"]
1333 extra_dict
["depends_on"].append(net_text
)
1335 Ns
._prepare
_interface
_port
_security
(interface
)
1337 net_item
= Ns
._create
_net
_item
_of
_interface
(interface
, net_text
)
1339 Ns
._prepare
_type
_of
_interface
(
1340 interface
, tasks_by_target_record_id
, net_text
, net_item
1343 if interface
.get("ip-address"):
1344 net_item
["ip_address"] = interface
["ip-address"]
1346 if interface
.get("mac-address"):
1347 net_item
["mac_address"] = interface
["mac-address"]
1349 net_list
.append(net_item
)
1351 if interface
.get("mgmt-vnf"):
1352 extra_dict
["mgmt_vnf_interface"] = iface_index
1353 elif interface
.get("mgmt-interface"):
1354 extra_dict
["mgmt_vdu_interface"] = iface_index
1357 def _prepare_vdu_ssh_keys(
1358 target_vdu
: dict, ro_nsr_public_key
: dict, cloud_config
: dict
1360 """Add ssh keys to cloud config.
1363 target_vdu (dict): Details of VDU to be created
1364 ro_nsr_public_key (dict): RO NSR public Key
1365 cloud_config (dict): Cloud config details
1370 if target_vdu
.get("ssh-keys"):
1371 ssh_keys
+= target_vdu
.get("ssh-keys")
1373 if target_vdu
.get("ssh-access-required"):
1374 ssh_keys
.append(ro_nsr_public_key
)
1377 cloud_config
["key-pairs"] = ssh_keys
1380 def _select_persistent_root_disk(vsd
: dict, vdu
: dict) -> dict:
1381 """Selects the persistent root disk if exists.
1383 vsd (dict): Virtual storage descriptors in VNFD
1384 vdu (dict): VNF descriptor
1387 root_disk (dict): Selected persistent root disk
1389 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
1393 ) == "persistent-storage:persistent-storage" and root_disk
.get(
1399 def _add_persistent_root_disk_to_disk_list(
1400 vnfd
: dict, target_vdu
: dict, persistent_root_disk
: dict, disk_list
: list
1402 """Find the persistent root disk and add to disk list.
1405 vnfd (dict): VNF descriptor
1406 target_vdu (dict): Details of VDU to be created
1407 persistent_root_disk (dict): Details of persistent root disk
1408 disk_list (list): Disks of VDU
1411 for vdu
in vnfd
.get("vdu", ()):
1412 if vdu
["name"] == target_vdu
["vdu-name"]:
1413 for vsd
in vnfd
.get("virtual-storage-desc", ()):
1414 root_disk
= Ns
._select
_persistent
_root
_disk
(vsd
, vdu
)
1418 persistent_root_disk
[vsd
["id"]] = {
1419 "image_id": vdu
.get("sw-image-desc"),
1420 "size": root_disk
["size-of-storage"],
1421 "keep": Ns
.is_volume_keeping_required(root_disk
),
1423 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1427 def _add_persistent_ordinary_disks_to_disk_list(
1429 persistent_root_disk
: dict,
1430 persistent_ordinary_disk
: dict,
1436 """Fill the disk list by adding persistent ordinary disks.
1439 target_vdu (dict): Details of VDU to be created
1440 persistent_root_disk (dict): Details of persistent root disk
1441 persistent_ordinary_disk (dict): Details of persistent ordinary disk
1442 disk_list (list): Disks of VDU
1445 if target_vdu
.get("virtual-storages"):
1446 for disk
in target_vdu
["virtual-storages"]:
1448 disk
.get("type-of-storage")
1449 == "persistent-storage:persistent-storage"
1450 and disk
["id"] not in persistent_root_disk
.keys()
1452 name
, multiattach
= Ns
.is_shared_volume(disk
, vnf_id
)
1453 persistent_ordinary_disk
[disk
["id"]] = {
1455 "size": disk
["size-of-storage"],
1456 "keep": Ns
.is_volume_keeping_required(disk
),
1457 "multiattach": multiattach
,
1459 disk_list
.append(persistent_ordinary_disk
[disk
["id"]])
1460 if multiattach
: # VDU creation has to wait for shared volumes
1461 extra_dict
["depends_on"].append(
1462 f
"nsrs:{nsr_id}:shared-volumes.{name}"
1466 def _prepare_vdu_affinity_group_list(
1467 target_vdu
: dict, extra_dict
: dict, ns_preffix
: str
1468 ) -> List
[Dict
[str, any
]]:
1469 """Process affinity group details to prepare affinity group list.
1472 target_vdu (dict): Details of VDU to be created
1473 extra_dict (dict): Dictionary to be filled
1474 ns_preffix (str): Prefix as string
1478 affinity_group_list (list): Affinity group details
1481 affinity_group_list
= []
1483 if target_vdu
.get("affinity-or-anti-affinity-group-id"):
1484 for affinity_group_id
in target_vdu
["affinity-or-anti-affinity-group-id"]:
1486 affinity_group_text
= (
1487 ns_preffix
+ ":affinity-or-anti-affinity-group." + affinity_group_id
1490 if not isinstance(extra_dict
.get("depends_on"), list):
1491 raise NsException("Invalid extra_dict format.")
1493 extra_dict
["depends_on"].append(affinity_group_text
)
1494 affinity_group
["affinity_group_id"] = "TASK-" + affinity_group_text
1495 affinity_group_list
.append(affinity_group
)
1497 return affinity_group_list
1500 def _process_vdu_params(
1501 target_vdu
: Dict
[str, Any
],
1502 indata
: Dict
[str, Any
],
1503 vim_info
: Dict
[str, Any
],
1504 target_record_id
: str,
1505 **kwargs
: Dict
[str, Any
],
1506 ) -> Dict
[str, Any
]:
1507 """Function to process VDU parameters.
1510 target_vdu (Dict[str, Any]): [description]
1511 indata (Dict[str, Any]): [description]
1512 vim_info (Dict[str, Any]): [description]
1513 target_record_id (str): [description]
1516 Dict[str, Any]: [description]
1518 vnfr_id
= kwargs
.get("vnfr_id")
1519 nsr_id
= kwargs
.get("nsr_id")
1520 vnfr
= kwargs
.get("vnfr")
1521 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1522 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
1523 logger
= kwargs
.get("logger")
1524 db
= kwargs
.get("db")
1525 fs
= kwargs
.get("fs")
1526 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1528 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
1529 ns_preffix
= "nsrs:{}".format(nsr_id
)
1530 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
1531 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
1532 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
1534 persistent_root_disk
= {}
1535 persistent_ordinary_disk
= {}
1536 vdu_instantiation_volumes_list
= []
1538 vnfd_id
= vnfr
["vnfd-id"]
1539 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
1540 # If the position info is provided for all the interfaces, it will be sorted
1541 # according to position number ascendingly.
1543 True if i
.get("position") is not None else False
1544 for i
in target_vdu
["interfaces"]
1546 Ns
._sort
_vdu
_interfaces
(target_vdu
)
1548 # If the position info is provided for some interfaces but not all of them, the interfaces
1549 # which has specific position numbers will be placed and others' positions will not be taken care.
1551 Ns
._partially
_locate
_vdu
_interfaces
(target_vdu
)
1553 # If the position info is not provided for the interfaces, interfaces will be attached
1554 # according to the order in the VNFD.
1555 Ns
._prepare
_vdu
_interfaces
(
1561 tasks_by_target_record_id
,
1566 cloud_config
= Ns
._prepare
_vdu
_cloud
_init
(target_vdu
, vdu2cloud_init
, db
, fs
)
1568 # Prepare VDU ssh keys
1569 Ns
._prepare
_vdu
_ssh
_keys
(target_vdu
, ro_nsr_public_key
, cloud_config
)
1571 if target_vdu
.get("additionalParams"):
1572 vdu_instantiation_volumes_list
= (
1573 target_vdu
.get("additionalParams").get("OSM", {}).get("vdu_volumes")
1576 if vdu_instantiation_volumes_list
:
1577 # Find the root volumes and add to the disk_list
1578 persistent_root_disk
= Ns
.find_persistent_root_volumes(
1579 vnfd
, target_vdu
, vdu_instantiation_volumes_list
, disk_list
1582 # Find the ordinary volumes which are not added to the persistent_root_disk
1583 # and put them to the disk list
1584 Ns
.find_persistent_volumes(
1585 persistent_root_disk
,
1587 vdu_instantiation_volumes_list
,
1592 # Vdu_instantiation_volumes_list is empty
1593 # First get add the persistent root disks to disk_list
1594 Ns
._add
_persistent
_root
_disk
_to
_disk
_list
(
1595 vnfd
, target_vdu
, persistent_root_disk
, disk_list
1597 # Add the persistent non-root disks to disk_list
1598 Ns
._add
_persistent
_ordinary
_disks
_to
_disk
_list
(
1600 persistent_root_disk
,
1601 persistent_ordinary_disk
,
1608 affinity_group_list
= Ns
._prepare
_vdu
_affinity
_group
_list
(
1609 target_vdu
, extra_dict
, ns_preffix
1612 extra_dict
["params"] = {
1613 "name": "{}-{}-{}-{}".format(
1615 vnfr
["member-vnf-index-ref"],
1616 target_vdu
["vdu-name"],
1617 target_vdu
.get("count-index") or 0,
1619 "description": target_vdu
["vdu-name"],
1621 "image_id": "TASK-" + image_text
,
1622 "flavor_id": "TASK-" + flavor_text
,
1623 "affinity_group_list": affinity_group_list
,
1624 "net_list": net_list
,
1625 "cloud_config": cloud_config
or None,
1626 "disk_list": disk_list
,
1627 "availability_zone_index": None, # TODO
1628 "availability_zone_list": None, # TODO
1633 def _process_shared_volumes_params(
1634 target_shared_volume
: Dict
[str, Any
],
1635 indata
: Dict
[str, Any
],
1636 vim_info
: Dict
[str, Any
],
1637 target_record_id
: str,
1638 **kwargs
: Dict
[str, Any
],
1639 ) -> Dict
[str, Any
]:
1641 shared_volume_data
= {
1642 "size": target_shared_volume
["size-of-storage"],
1643 "name": target_shared_volume
["id"],
1644 "type": target_shared_volume
["type-of-storage"],
1645 "keep": Ns
.is_volume_keeping_required(target_shared_volume
),
1647 extra_dict
["params"] = shared_volume_data
1651 def _process_affinity_group_params(
1652 target_affinity_group
: Dict
[str, Any
],
1653 indata
: Dict
[str, Any
],
1654 vim_info
: Dict
[str, Any
],
1655 target_record_id
: str,
1656 **kwargs
: Dict
[str, Any
],
1657 ) -> Dict
[str, Any
]:
1658 """Get affinity or anti-affinity group parameters.
1661 target_affinity_group (Dict[str, Any]): [description]
1662 indata (Dict[str, Any]): [description]
1663 vim_info (Dict[str, Any]): [description]
1664 target_record_id (str): [description]
1667 Dict[str, Any]: [description]
1671 affinity_group_data
= {
1672 "name": target_affinity_group
["name"],
1673 "type": target_affinity_group
["type"],
1674 "scope": target_affinity_group
["scope"],
1677 if target_affinity_group
.get("vim-affinity-group-id"):
1678 affinity_group_data
["vim-affinity-group-id"] = target_affinity_group
[
1679 "vim-affinity-group-id"
1682 extra_dict
["params"] = {
1683 "affinity_group_data": affinity_group_data
,
1688 def _process_recreate_vdu_params(
1689 existing_vdu
: Dict
[str, Any
],
1690 db_nsr
: Dict
[str, Any
],
1691 vim_info
: Dict
[str, Any
],
1692 target_record_id
: str,
1694 **kwargs
: Dict
[str, Any
],
1695 ) -> Dict
[str, Any
]:
1696 """Function to process VDU parameters to recreate.
1699 existing_vdu (Dict[str, Any]): [description]
1700 db_nsr (Dict[str, Any]): [description]
1701 vim_info (Dict[str, Any]): [description]
1702 target_record_id (str): [description]
1703 target_id (str): [description]
1706 Dict[str, Any]: [description]
1708 vnfr
= kwargs
.get("vnfr")
1709 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1710 # logger = kwargs.get("logger")
1711 db
= kwargs
.get("db")
1712 fs
= kwargs
.get("fs")
1713 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1719 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
1721 if vim_details_text
:
1722 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
1724 for iface_index
, interface
in enumerate(existing_vdu
["interfaces"]):
1725 if "port-security-enabled" in interface
:
1726 interface
["port_security"] = interface
.pop("port-security-enabled")
1728 if "port-security-disable-strategy" in interface
:
1729 interface
["port_security_disable_strategy"] = interface
.pop(
1730 "port-security-disable-strategy"
1735 for x
, v
in interface
.items()
1741 "port_security_disable_strategy",
1745 existing_ifaces
= existing_vdu
["vim_info"][target_id
].get(
1746 "interfaces_backup", []
1751 for i
in existing_ifaces
1752 if i
["ip_address"] == interface
["ip-address"]
1757 net_item
["net_id"] = net_id
1758 net_item
["type"] = "virtual"
1760 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1761 # TODO floating_ip: True/False (or it can be None)
1762 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1763 net_item
["use"] = "data"
1764 net_item
["model"] = interface
["type"]
1765 net_item
["type"] = interface
["type"]
1767 interface
.get("type") == "OM-MGMT"
1768 or interface
.get("mgmt-interface")
1769 or interface
.get("mgmt-vnf")
1771 net_item
["use"] = "mgmt"
1773 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1774 net_item
["use"] = "bridge"
1775 net_item
["model"] = interface
.get("type")
1777 if interface
.get("ip-address"):
1778 dual_ip
= interface
.get("ip-address").split(";")
1779 if len(dual_ip
) == 2:
1780 net_item
["ip_address"] = dual_ip
1782 net_item
["ip_address"] = interface
["ip-address"]
1784 if interface
.get("mac-address"):
1785 net_item
["mac_address"] = interface
["mac-address"]
1787 net_list
.append(net_item
)
1789 if interface
.get("mgmt-vnf"):
1790 extra_dict
["mgmt_vnf_interface"] = iface_index
1791 elif interface
.get("mgmt-interface"):
1792 extra_dict
["mgmt_vdu_interface"] = iface_index
1797 if existing_vdu
.get("cloud-init"):
1798 if existing_vdu
["cloud-init"] not in vdu2cloud_init
:
1799 vdu2cloud_init
[existing_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1802 location
=existing_vdu
["cloud-init"],
1805 cloud_content_
= vdu2cloud_init
[existing_vdu
["cloud-init"]]
1806 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1807 cloud_init_content
=cloud_content_
,
1808 params
=existing_vdu
.get("additionalParams"),
1809 context
=existing_vdu
["cloud-init"],
1812 if existing_vdu
.get("boot-data-drive"):
1813 cloud_config
["boot-data-drive"] = existing_vdu
.get("boot-data-drive")
1817 if existing_vdu
.get("ssh-keys"):
1818 ssh_keys
+= existing_vdu
.get("ssh-keys")
1820 if existing_vdu
.get("ssh-access-required"):
1821 ssh_keys
.append(ro_nsr_public_key
)
1824 cloud_config
["key-pairs"] = ssh_keys
1827 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
1828 disk_list
.append({"vim_id": vol_id
["id"]})
1830 affinity_group_list
= []
1832 if existing_vdu
.get("affinity-or-anti-affinity-group-id"):
1834 for affinity_group_id
in existing_vdu
["affinity-or-anti-affinity-group-id"]:
1835 for group
in db_nsr
.get("affinity-or-anti-affinity-group"):
1837 group
["id"] == affinity_group_id
1838 and group
["vim_info"][target_id
].get("vim_id", None) is not None
1840 affinity_group
["affinity_group_id"] = group
["vim_info"][
1842 ].get("vim_id", None)
1843 affinity_group_list
.append(affinity_group
)
1845 extra_dict
["params"] = {
1846 "name": "{}-{}-{}-{}".format(
1848 vnfr
["member-vnf-index-ref"],
1849 existing_vdu
["vdu-name"],
1850 existing_vdu
.get("count-index") or 0,
1852 "description": existing_vdu
["vdu-name"],
1854 "image_id": vim_details
["image"]["id"],
1855 "flavor_id": vim_details
["flavor"]["id"],
1856 "affinity_group_list": affinity_group_list
,
1857 "net_list": net_list
,
1858 "cloud_config": cloud_config
or None,
1859 "disk_list": disk_list
,
1860 "availability_zone_index": None, # TODO
1861 "availability_zone_list": None, # TODO
1866 def calculate_diff_items(
1873 tasks_by_target_record_id
,
1880 """Function that returns the incremental changes (creation, deletion)
1881 related to a specific item `item` to be done. This function should be
1882 called for NS instantiation, NS termination, NS update to add a new VNF
1883 or a new VLD, remove a VNF or VLD, etc.
1884 Item can be `net`, `flavor`, `image` or `vdu`.
1885 It takes a list of target items from indata (which came from the REST API)
1886 and compares with the existing items from db_ro_nsr, identifying the
1887 incremental changes to be done. During the comparison, it calls the method
1888 `process_params` (which was passed as parameter, and is particular for each
1892 indata (Dict[str, Any]): deployment info
1893 db_nsr: NSR record from DB
1894 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1895 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1896 item (str): element to process (net, vdu...)
1897 tasks_by_target_record_id (Dict[str, Any]):
1898 [<target_record_id>, <task>]
1899 action_id (str): action id
1900 nsr_id (str): NSR id
1901 task_index (number): task index to add to task name
1902 vnfr_id (str): VNFR id
1903 vnfr (Dict[str, Any]): VNFR info
1906 List: list with the incremental changes (deletes, creates) for each item
1907 number: current task index
1915 process_params
= None
1916 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1917 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1918 # According to the type of item, the path, the target_list,
1919 # the existing_list and the method to process params are set
1920 db_path
= self
.db_path_map
[item
]
1921 process_params
= self
.process_params_function_map
[item
]
1922 if item
in ("net", "vdu"):
1923 # This case is specific for the NS VLD (not applied to VDU)
1925 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1926 target_list
= indata
.get("ns", []).get(db_path
, [])
1927 existing_list
= db_nsr
.get(db_path
, [])
1928 # This case is common for VNF VLDs and VNF VDUs
1930 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
1932 (vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
),
1935 target_list
= target_vnf
.get(db_path
, []) if target_vnf
else []
1936 existing_list
= vnfr
.get(db_path
, [])
1940 "affinity-or-anti-affinity-group",
1943 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1944 target_list
= indata
.get(item
, [])
1945 existing_list
= db_nsr
.get(item
, [])
1947 raise NsException("Item not supported: {}", item
)
1948 # ensure all the target_list elements has an "id". If not assign the index as id
1949 if target_list
is None:
1951 for target_index
, tl
in enumerate(target_list
):
1952 if tl
and not tl
.get("id"):
1953 tl
["id"] = str(target_index
)
1954 # step 1 items (networks,vdus,...) to be deleted/updated
1955 for item_index
, existing_item
in enumerate(existing_list
):
1957 (t
for t
in target_list
if t
["id"] == existing_item
["id"]),
1960 for target_vim
, existing_viminfo
in existing_item
.get(
1963 if existing_viminfo
is None:
1967 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
1969 target_viminfo
= None
1971 if target_viminfo
is None:
1973 self
._assign
_vim
(target_vim
)
1974 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
1977 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
1978 # item must be sdn-net instead of net if target_vim is a sdn
1980 target_record_id
+= ".sdn"
1983 "action_id": action_id
,
1985 "task_index": task_index
,
1990 "deployment_info": deployment_info
,
1991 "target_id": target_vim
,
1994 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1995 "target_record_id": target_record_id
,
2000 # step 2 items (networks,vdus,...) to be created
2001 for target_item
in target_list
:
2003 for item_index
, existing_item
in enumerate(existing_list
):
2004 if existing_item
["id"] == target_item
["id"]:
2008 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
2009 existing_list
.append(target_item
)
2010 existing_item
= None
2012 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
2013 existing_viminfo
= None
2016 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
2018 if existing_viminfo
is not None:
2021 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
2024 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
2025 # item must be sdn-net instead of net if target_vim is a sdn
2027 target_record_id
+= ".sdn"
2031 "ns.calculate_diff_items target_item={}".format(target_item
)
2033 if process_params
== Ns
._process
_flavor
_params
:
2040 "calculate_diff_items for flavor kwargs={}".format(kwargs
)
2043 if process_params
== Ns
._process
_vdu
_params
:
2044 self
.logger
.debug("calculate_diff_items self.fs={}".format(self
.fs
))
2050 "vdu2cloud_init": vdu2cloud_init
,
2051 "tasks_by_target_record_id": tasks_by_target_record_id
,
2052 "logger": self
.logger
,
2055 "ro_nsr_public_key": ro_nsr_public_key
,
2058 self
.logger
.debug("calculate_diff_items kwargs={}".format(kwargs
))
2059 extra_dict
= process_params(
2066 self
._assign
_vim
(target_vim
)
2069 "action_id": action_id
,
2071 "task_index": task_index
,
2075 "deployment_info": deployment_info
,
2076 "target_id": target_vim
,
2079 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
2080 "target_record_id": target_record_id
,
2081 "extra_dict": extra_dict
,
2082 "common_id": target_item
.get("common_id", None),
2084 diff_items
.append(new_item
)
2085 tasks_by_target_record_id
[target_record_id
] = new_item
2088 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
2090 return diff_items
, task_index
2092 def calculate_all_differences_to_deploy(
2102 tasks_by_target_record_id
,
2104 """This method calculates the ordered list of items (`changes_list`)
2105 to be created and deleted.
2108 indata (Dict[str, Any]): deployment info
2109 nsr_id (str): NSR id
2110 db_nsr: NSR record from DB
2111 db_vnfrs: VNFRS record from DB
2112 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2113 db_nsr_update (Dict[str, Any]): NSR info to update in DB
2114 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
2115 action_id (str): action id
2116 tasks_by_target_record_id (Dict[str, Any]):
2117 [<target_record_id>, <task>]
2120 List: ordered list of items to be created and deleted.
2124 # set list with diffs:
2127 # NS vld, image and flavor
2132 "affinity-or-anti-affinity-group",
2134 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
2135 diff_items
, task_index
= self
.calculate_diff_items(
2138 db_ro_nsr
=db_ro_nsr
,
2139 db_nsr_update
=db_nsr_update
,
2141 tasks_by_target_record_id
=tasks_by_target_record_id
,
2142 action_id
=action_id
,
2144 task_index
=task_index
,
2147 changes_list
+= diff_items
2150 for vnfr_id
, vnfr
in db_vnfrs
.items():
2151 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
2152 for item
in ["net", "vdu", "shared-volumes"]:
2153 self
.logger
.debug("process VNF={} {}".format(vnfr_id
, item
))
2154 diff_items
, task_index
= self
.calculate_diff_items(
2157 db_ro_nsr
=db_ro_nsr
,
2158 db_nsr_update
=db_vnfrs_update
[vnfr
["_id"]],
2160 tasks_by_target_record_id
=tasks_by_target_record_id
,
2161 action_id
=action_id
,
2163 task_index
=task_index
,
2167 changes_list
+= diff_items
2171 def define_all_tasks(
2175 tasks_by_target_record_id
,
2177 """Function to create all the task structures obtanied from
2178 the method calculate_all_differences_to_deploy
2181 changes_list (List): ordered list of items to be created or deleted
2182 db_new_tasks (List): tasks list to be created
2183 action_id (str): action id
2184 tasks_by_target_record_id (Dict[str, Any]):
2185 [<target_record_id>, <task>]
2189 for change
in changes_list
:
2190 task
= Ns
._create
_task
(
2191 deployment_info
=change
["deployment_info"],
2192 target_id
=change
["target_id"],
2193 item
=change
["item"],
2194 action
=change
["action"],
2195 target_record
=change
["target_record"],
2196 target_record_id
=change
["target_record_id"],
2197 extra_dict
=change
.get("extra_dict", None),
2200 self
.logger
.debug("ns.define_all_tasks task={}".format(task
))
2201 tasks_by_target_record_id
[change
["target_record_id"]] = task
2202 db_new_tasks
.append(task
)
2204 if change
.get("common_id"):
2205 task
["common_id"] = change
["common_id"]
2207 def upload_all_tasks(
2212 """Function to save all tasks in the common DB
2215 db_new_tasks (List): tasks list to be created
2216 now (time): current time
2220 nb_ro_tasks
= 0 # for logging
2222 for db_task
in db_new_tasks
:
2223 target_id
= db_task
.pop("target_id")
2224 common_id
= db_task
.get("common_id")
2226 # Do not chek tasks with vim_status DELETED
2227 # because in manual heealing there are two tasks for the same vdur:
2228 # one with vim_status deleted and the other one with the actual VM status.
2234 "target_id": target_id
,
2235 "tasks.common_id": common_id
,
2236 "vim_info.vim_status.ne": "DELETED",
2238 update_dict
={"to_check_at": now
, "modified_at": now
},
2239 push
={"tasks": db_task
},
2240 fail_on_empty
=False,
2244 if not self
.db
.set_one(
2247 "target_id": target_id
,
2248 "tasks.target_record": db_task
["target_record"],
2249 "vim_info.vim_status.ne": "DELETED",
2251 update_dict
={"to_check_at": now
, "modified_at": now
},
2252 push
={"tasks": db_task
},
2253 fail_on_empty
=False,
2256 self
.logger
.debug("Updating database, Creating ro_tasks")
2257 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2259 self
.db
.create("ro_tasks", db_ro_task
)
2262 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2263 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2267 def upload_recreate_tasks(
2272 """Function to save recreate tasks in the common DB
2275 db_new_tasks (List): tasks list to be created
2276 now (time): current time
2280 nb_ro_tasks
= 0 # for logging
2282 for db_task
in db_new_tasks
:
2283 target_id
= db_task
.pop("target_id")
2284 self
.logger
.debug("target_id={} db_task={}".format(target_id
, db_task
))
2286 action
= db_task
.get("action", None)
2289 self
.logger
.debug("Updating database, Creating ro_tasks")
2290 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2292 # If DELETE task: the associated created items should be removed
2293 # (except persistent volumes):
2294 if action
== "DELETE":
2295 db_ro_task
["vim_info"]["created"] = True
2296 db_ro_task
["vim_info"]["created_items"] = db_task
.get(
2299 db_ro_task
["vim_info"]["volumes_to_hold"] = db_task
.get(
2300 "volumes_to_hold", []
2302 db_ro_task
["vim_info"]["vim_id"] = db_task
.get("vim_id", None)
2305 self
.logger
.debug("upload_all_tasks db_ro_task={}".format(db_ro_task
))
2306 self
.db
.create("ro_tasks", db_ro_task
)
2309 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2310 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2314 def _prepare_created_items_for_healing(
2320 # Get created_items from ro_task
2321 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2322 for ro_task
in ro_tasks
:
2323 for task
in ro_task
["tasks"]:
2325 task
["target_record"] == target_record
2326 and task
["action"] == "CREATE"
2327 and ro_task
["vim_info"]["created_items"]
2329 created_items
= ro_task
["vim_info"]["created_items"]
2332 return created_items
2334 def _prepare_persistent_volumes_for_healing(
2339 # The associated volumes of the VM shouldn't be removed
2342 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
2343 if vim_details_text
:
2344 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
2346 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
2347 volumes_list
.append(vol_id
["id"])
2351 def prepare_changes_to_recreate(
2359 tasks_by_target_record_id
,
2361 """This method will obtain an ordered list of items (`changes_list`)
2362 to be created and deleted to meet the recreate request.
2366 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id
, indata
)
2370 # set list with diffs:
2372 db_path
= self
.db_path_map
["vdu"]
2373 target_list
= indata
.get("healVnfData", {})
2374 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
2375 ro_nsr_public_key
= db_ro_nsr
["public_key"]
2377 # Check each VNF of the target
2378 for target_vnf
in target_list
:
2379 # Find this VNF in the list from DB, raise exception if vnfInstanceId is not found
2380 vnfr_id
= target_vnf
["vnfInstanceId"]
2381 existing_vnf
= db_vnfrs
.get(vnfr_id
, {})
2382 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
2383 # vim_account_id = existing_vnf.get("vim-account-id", "")
2385 target_vdus
= target_vnf
.get("additionalParams", {}).get("vdu", [])
2386 # Check each VDU of this VNF
2388 # Create target_vdu_list from DB, if VDUs are not specified
2390 for existing_vdu
in existing_vnf
.get("vdur"):
2391 vdu_name
= existing_vdu
.get("vdu-name", None)
2392 vdu_index
= existing_vdu
.get("count-index", 0)
2393 vdu_to_be_healed
= {"vdu-id": vdu_name
, "count-index": vdu_index
}
2394 target_vdus
.append(vdu_to_be_healed
)
2395 for target_vdu
in target_vdus
:
2396 vdu_name
= target_vdu
.get("vdu-id", None)
2397 # For multi instance VDU count-index is mandatory
2398 # For single session VDU count-indes is 0
2399 count_index
= target_vdu
.get("count-index", 0)
2401 existing_instance
= {}
2403 for instance
in existing_vnf
.get("vdur", {}):
2405 instance
["vdu-name"] == vdu_name
2406 and instance
["count-index"] == count_index
2408 existing_instance
= instance
2413 target_record_id
= "{}.{}".format(db_record
, existing_instance
["id"])
2415 # The target VIM is the one already existing in DB to recreate
2416 for target_vim
, target_viminfo
in existing_instance
.get(
2419 # step 1 vdu to be deleted
2420 self
._assign
_vim
(target_vim
)
2422 "action_id": action_id
,
2424 "task_index": task_index
,
2427 target_record
= f
"{db_record}.{item_index}.vim_info.{target_vim}"
2428 created_items
= self
._prepare
_created
_items
_for
_healing
(
2429 nsr_id
, target_record
2432 volumes_to_hold
= self
._prepare
_persistent
_volumes
_for
_healing
(
2433 target_vim
, existing_instance
2436 # Specific extra params for recreate tasks:
2438 "created_items": created_items
,
2439 "vim_id": existing_instance
["vim-id"],
2440 "volumes_to_hold": volumes_to_hold
,
2443 changes_list
.append(
2445 "deployment_info": deployment_info
,
2446 "target_id": target_vim
,
2449 "target_record": target_record
,
2450 "target_record_id": target_record_id
,
2451 "extra_dict": extra_dict
,
2454 delete_task_id
= f
"{action_id}:{task_index}"
2457 # step 2 vdu to be created
2463 "vnfr": existing_vnf
,
2464 "vdu2cloud_init": vdu2cloud_init
,
2465 "tasks_by_target_record_id": tasks_by_target_record_id
,
2466 "logger": self
.logger
,
2469 "ro_nsr_public_key": ro_nsr_public_key
,
2473 extra_dict
= self
._process
_recreate
_vdu
_params
(
2482 # The CREATE task depens on the DELETE task
2483 extra_dict
["depends_on"] = [delete_task_id
]
2485 # Add volumes created from created_items if any
2486 # Ports should be deleted with delete task and automatically created with create task
2488 for k
, v
in created_items
.items():
2490 k_item
, _
, k_id
= k
.partition(":")
2491 if k_item
== "volume":
2493 except Exception as e
:
2495 "Error evaluating created item {}: {}".format(k
, e
)
2497 extra_dict
["previous_created_volumes"] = volumes
2500 "action_id": action_id
,
2502 "task_index": task_index
,
2504 self
._assign
_vim
(target_vim
)
2507 "deployment_info": deployment_info
,
2508 "target_id": target_vim
,
2511 "target_record": target_record
,
2512 "target_record_id": target_record_id
,
2513 "extra_dict": extra_dict
,
2515 changes_list
.append(new_item
)
2516 tasks_by_target_record_id
[target_record_id
] = new_item
2521 def recreate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2522 self
.logger
.debug("ns.recreate nsr_id={} indata={}".format(nsr_id
, indata
))
2523 # TODO: validate_input(indata, recreate_schema)
2524 action_id
= indata
.get("action_id", str(uuid4()))
2525 # get current deployment
2526 db_vnfrs
= {} # vnf's info indexed by _id
2528 logging_text
= "Recreate nsr_id={} action_id={} indata={}".format(
2529 nsr_id
, action_id
, indata
2531 self
.logger
.debug(logging_text
+ "Enter")
2534 step
= "Getting ns and vnfr record from db"
2535 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2537 tasks_by_target_record_id
= {}
2538 # read from db: vnf's of this ns
2539 step
= "Getting vnfrs from db"
2540 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2541 self
.logger
.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list
))
2543 if not db_vnfrs_list
:
2544 raise NsException("Cannot obtain associated VNF for ns")
2546 for vnfr
in db_vnfrs_list
:
2547 db_vnfrs
[vnfr
["_id"]] = vnfr
2550 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2551 self
.logger
.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr
))
2554 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2556 with self
.write_lock
:
2558 step
= "process NS elements"
2559 changes_list
= self
.prepare_changes_to_recreate(
2564 db_ro_nsr
=db_ro_nsr
,
2565 action_id
=action_id
,
2566 tasks_by_target_record_id
=tasks_by_target_record_id
,
2569 self
.define_all_tasks(
2570 changes_list
=changes_list
,
2571 db_new_tasks
=db_new_tasks
,
2572 tasks_by_target_record_id
=tasks_by_target_record_id
,
2575 # Delete all ro_tasks registered for the targets vdurs (target_record)
2576 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2577 # So remove all task related to target record.
2578 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2579 for change
in changes_list
:
2580 for ro_task
in ro_tasks
:
2581 for task
in ro_task
["tasks"]:
2582 if task
["target_record"] == change
["target_record"]:
2586 "_id": ro_task
["_id"],
2587 "modified_at": ro_task
["modified_at"],
2589 fail_on_empty
=False,
2592 step
= "Updating database, Appending tasks to ro_tasks"
2593 self
.upload_recreate_tasks(
2594 db_new_tasks
=db_new_tasks
,
2599 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2603 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2607 except Exception as e
:
2608 if isinstance(e
, (DbException
, NsException
)):
2610 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2613 e
= traceback_format_exc()
2614 self
.logger
.critical(
2615 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2619 raise NsException(e
)
2621 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2622 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
2623 validate_input(indata
, deploy_schema
)
2624 action_id
= indata
.get("action_id", str(uuid4()))
2626 # get current deployment
2627 db_nsr_update
= {} # update operation on nsrs
2628 db_vnfrs_update
= {}
2629 db_vnfrs
= {} # vnf's info indexed by _id
2631 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2632 self
.logger
.debug(logging_text
+ "Enter")
2635 step
= "Getting ns and vnfr record from db"
2636 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2637 self
.logger
.debug("ns.deploy: db_nsr={}".format(db_nsr
))
2639 tasks_by_target_record_id
= {}
2640 # read from db: vnf's of this ns
2641 step
= "Getting vnfrs from db"
2642 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2644 if not db_vnfrs_list
:
2645 raise NsException("Cannot obtain associated VNF for ns")
2647 for vnfr
in db_vnfrs_list
:
2648 db_vnfrs
[vnfr
["_id"]] = vnfr
2649 db_vnfrs_update
[vnfr
["_id"]] = {}
2650 self
.logger
.debug("ns.deploy db_vnfrs={}".format(db_vnfrs
))
2653 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2656 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2658 # check that action_id is not in the list of actions. Suffixed with :index
2659 if action_id
in db_ro_nsr
["actions"]:
2663 new_action_id
= "{}:{}".format(action_id
, index
)
2665 if new_action_id
not in db_ro_nsr
["actions"]:
2666 action_id
= new_action_id
2669 + "Changing action_id in use to {}".format(action_id
)
2675 def _process_action(indata
):
2676 nonlocal db_new_tasks
2683 if indata
["action"]["action"] == "inject_ssh_key":
2684 key
= indata
["action"].get("key")
2685 user
= indata
["action"].get("user")
2686 password
= indata
["action"].get("password")
2688 for vnf
in indata
.get("vnf", ()):
2689 if vnf
["_id"] not in db_vnfrs
:
2690 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
2692 db_vnfr
= db_vnfrs
[vnf
["_id"]]
2694 for target_vdu
in vnf
.get("vdur", ()):
2695 vdu_index
, vdur
= next(
2698 for i_v
in enumerate(db_vnfr
["vdur"])
2699 if i_v
[1]["id"] == target_vdu
["id"]
2706 "Invalid vdu vnf={}.{}".format(
2707 vnf
["_id"], target_vdu
["id"]
2711 target_vim
, vim_info
= next(
2712 k_v
for k_v
in vdur
["vim_info"].items()
2714 self
._assign
_vim
(target_vim
)
2715 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
2716 vnf
["_id"], vdu_index
2720 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
2723 "ip_address": vdur
.get("ip-address"),
2726 "password": password
,
2727 "private_key": db_ro_nsr
["private_key"],
2728 "salt": db_ro_nsr
["_id"],
2729 "schema_version": db_ro_nsr
["_admin"][
2736 "action_id": action_id
,
2738 "task_index": task_index
,
2741 task
= Ns
._create
_task
(
2742 deployment_info
=deployment_info
,
2743 target_id
=target_vim
,
2746 target_record
=target_record
,
2747 target_record_id
=None,
2748 extra_dict
=extra_dict
,
2751 task_index
= deployment_info
.get("task_index")
2753 db_new_tasks
.append(task
)
2755 with self
.write_lock
:
2756 if indata
.get("action"):
2757 _process_action(indata
)
2759 # compute network differences
2761 step
= "process NS elements"
2762 changes_list
= self
.calculate_all_differences_to_deploy(
2767 db_ro_nsr
=db_ro_nsr
,
2768 db_nsr_update
=db_nsr_update
,
2769 db_vnfrs_update
=db_vnfrs_update
,
2770 action_id
=action_id
,
2771 tasks_by_target_record_id
=tasks_by_target_record_id
,
2773 self
.define_all_tasks(
2774 changes_list
=changes_list
,
2775 db_new_tasks
=db_new_tasks
,
2776 tasks_by_target_record_id
=tasks_by_target_record_id
,
2779 step
= "Updating database, Appending tasks to ro_tasks"
2780 self
.upload_all_tasks(
2781 db_new_tasks
=db_new_tasks
,
2785 step
= "Updating database, nsrs"
2787 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
2789 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
2791 step
= "Updating database, vnfrs={}".format(vnfr_id
)
2792 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
2795 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2799 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2803 except Exception as e
:
2804 if isinstance(e
, (DbException
, NsException
)):
2806 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2809 e
= traceback_format_exc()
2810 self
.logger
.critical(
2811 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2815 raise NsException(e
)
2817 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2818 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
2819 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2821 with self
.write_lock
:
2823 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
2824 except NsWorkerException
as e
:
2825 raise NsException(e
)
2827 return None, None, True
2829 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2831 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2832 version
, nsr_id
, action_id
, indata
2838 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
2839 global_status
= "DONE"
2842 for ro_task
in ro_tasks
:
2843 for task
in ro_task
["tasks"]:
2844 if task
and task
["action_id"] == action_id
:
2845 task_list
.append(task
)
2848 if task
["status"] == "FAILED":
2849 global_status
= "FAILED"
2850 error_text
= "Error at {} {}: {}".format(
2851 task
["action"].lower(),
2853 ro_task
["vim_info"].get("vim_message") or "unknown",
2855 details
.append(error_text
)
2856 elif task
["status"] in ("SCHEDULED", "BUILD"):
2857 if global_status
!= "FAILED":
2858 global_status
= "BUILD"
2863 "status": global_status
,
2864 "details": ". ".join(details
)
2866 else "progress {}/{}".format(done
, total
),
2868 "action_id": action_id
,
2872 return return_data
, None, True
2874 def recreate_status(
2875 self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
2877 return self
.status(session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
)
2879 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2881 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2882 session
, indata
, version
, nsr_id
, action_id
2886 return None, None, True
2888 def rebuild_start_stop_task(
2899 self
._assign
_vim
(target_vim
)
2900 target_record
= "vnfrs:{}:vdur.{}.vim_info.{}".format(
2901 vnf_id
, vdu_index
, target_vim
2903 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_id
)
2905 "action_id": action_id
,
2907 "task_index": task_index
,
2910 task
= Ns
._create
_task
(
2911 deployment_info
=deployment_info
,
2912 target_id
=target_vim
,
2915 target_record
=target_record
,
2916 target_record_id
=target_record_id
,
2917 extra_dict
=extra_dict
,
2921 def rebuild_start_stop(
2922 self
, session
, action_dict
, version
, nsr_id
, *args
, **kwargs
2927 action_id
= action_dict
.get("action_id", str(uuid4()))
2929 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2930 self
.logger
.debug(logging_text
+ "Enter")
2932 action
= list(action_dict
.keys())[0]
2933 task_dict
= action_dict
.get(action
)
2934 vim_vm_id
= action_dict
.get(action
).get("vim_vm_id")
2936 if action_dict
.get("stop"):
2940 step
= "lock the operation & do task creation"
2941 with self
.write_lock
:
2942 extra_dict
["params"] = {
2943 "vim_vm_id": vim_vm_id
,
2946 task
= self
.rebuild_start_stop_task(
2947 task_dict
["vdu_id"],
2948 task_dict
["vnf_id"],
2949 task_dict
["vdu_index"],
2953 task_dict
["target_vim"],
2956 db_new_tasks
.append(task
)
2957 step
= "upload Task to db"
2958 self
.upload_all_tasks(
2959 db_new_tasks
=db_new_tasks
,
2963 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2966 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2970 except Exception as e
:
2971 if isinstance(e
, (DbException
, NsException
)):
2973 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2976 e
= traceback_format_exc()
2977 self
.logger
.critical(
2978 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2981 raise NsException(e
)
2983 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2984 nsrs
= self
.db
.get_list("nsrs", {})
2988 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
2990 return return_data
, None, True
2992 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2993 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2996 for ro_task
in ro_tasks
:
2997 for task
in ro_task
["tasks"]:
2998 if task
["action_id"] not in return_data
:
2999 return_data
.append(task
["action_id"])
3001 return return_data
, None, True
3004 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
3006 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
3007 self
._assign
_vim
(target_vim
)
3008 target_record
= "vnfrs:{}:vdur.{}.vim_info.{}".format(
3009 vnf
["_id"], vdu_index
, target_vim
3011 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
3013 "action_id": action_id
,
3015 "task_index": task_index
,
3018 task
= Ns
._create
_task
(
3019 deployment_info
=deployment_info
,
3020 target_id
=target_vim
,
3023 target_record
=target_record
,
3024 target_record_id
=target_record_id
,
3025 extra_dict
=extra_dict
,
3030 def migrate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3034 action_id
= indata
.get("action_id", str(uuid4()))
3036 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
3037 self
.logger
.debug(logging_text
+ "Enter")
3039 vnf_instance_id
= indata
["vnfInstanceId"]
3040 step
= "Getting vnfrs from db"
3041 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
3042 vdu
= indata
.get("vdu")
3043 migrateToHost
= indata
.get("migrateToHost")
3046 with self
.write_lock
:
3048 vdu_id
= indata
["vdu"]["vduId"]
3049 vdu_count_index
= indata
["vdu"].get("vduCountIndex", 0)
3050 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3052 vdu
["vdu-id-ref"] == vdu_id
3053 and vdu
["count-index"] == vdu_count_index
3055 extra_dict
["params"] = {
3056 "vim_vm_id": vdu
["vim-id"],
3057 "migrate_host": migrateToHost
,
3058 "vdu_vim_info": vdu
["vim_info"],
3060 step
= "Creating migration task for vdu:{}".format(vdu
)
3061 task
= self
.migrate_task(
3070 db_new_tasks
.append(task
)
3074 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3075 extra_dict
["params"] = {
3076 "vim_vm_id": vdu
["vim-id"],
3077 "migrate_host": migrateToHost
,
3078 "vdu_vim_info": vdu
["vim_info"],
3080 step
= "Creating migration task for vdu:{}".format(vdu
)
3081 task
= self
.migrate_task(
3090 db_new_tasks
.append(task
)
3093 self
.upload_all_tasks(
3094 db_new_tasks
=db_new_tasks
,
3099 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3102 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3106 except Exception as e
:
3107 if isinstance(e
, (DbException
, NsException
)):
3109 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3112 e
= traceback_format_exc()
3113 self
.logger
.critical(
3114 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3117 raise NsException(e
)
3119 def verticalscale_task(
3120 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
3122 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
3123 self
._assign
_vim
(target_vim
)
3124 target_record
= "vnfrs:{}:vdur.{}.vim_info.{}".format(
3125 vnf
["_id"], vdu_index
, target_vim
3127 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
3129 "action_id": action_id
,
3131 "task_index": task_index
,
3134 task
= Ns
._create
_task
(
3135 deployment_info
=deployment_info
,
3136 target_id
=target_vim
,
3137 item
="verticalscale",
3139 target_record
=target_record
,
3140 target_record_id
=target_record_id
,
3141 extra_dict
=extra_dict
,
3145 def verticalscale(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3149 action_id
= indata
.get("action_id", str(uuid4()))
3151 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
3152 self
.logger
.debug(logging_text
+ "Enter")
3154 VnfFlavorData
= indata
.get("changeVnfFlavorData")
3155 vnf_instance_id
= VnfFlavorData
["vnfInstanceId"]
3156 step
= "Getting vnfrs from db"
3157 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
3158 vduid
= VnfFlavorData
["additionalParams"]["vduid"]
3159 vduCountIndex
= VnfFlavorData
["additionalParams"]["vduCountIndex"]
3160 virtualMemory
= VnfFlavorData
["additionalParams"]["virtualMemory"]
3161 numVirtualCpu
= VnfFlavorData
["additionalParams"]["numVirtualCpu"]
3162 sizeOfStorage
= VnfFlavorData
["additionalParams"]["sizeOfStorage"]
3164 "name": vduid
+ "-flv",
3165 "ram": virtualMemory
,
3166 "vcpus": numVirtualCpu
,
3167 "disk": sizeOfStorage
,
3170 step
= "Creating Tasks for vertical scaling"
3171 with self
.write_lock
:
3172 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3174 vdu
["vdu-id-ref"] == vduid
3175 and vdu
["count-index"] == vduCountIndex
3177 extra_dict
["params"] = {
3178 "vim_vm_id": vdu
["vim-id"],
3179 "flavor_dict": flavor_dict
,
3181 task
= self
.verticalscale_task(
3190 db_new_tasks
.append(task
)
3193 self
.upload_all_tasks(
3194 db_new_tasks
=db_new_tasks
,
3198 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3201 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3205 except Exception as e
:
3206 if isinstance(e
, (DbException
, NsException
)):
3208 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3211 e
= traceback_format_exc()
3212 self
.logger
.critical(
3213 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3216 raise NsException(e
)