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
1010 def find_persistent_volumes(
1011 persistent_root_disk
: dict,
1013 vdu_instantiation_volumes_list
: list,
1016 """Find the ordinary persistent volumes and add them to the disk_list
1017 by parsing the instantiation parameters.
1020 persistent_root_disk: persistent root disk dictionary
1021 target_vdu: processed VDU
1022 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1023 disk_list: to be filled up
1026 # Find the ordinary volumes which are not added to the persistent_root_disk
1027 persistent_disk
= {}
1028 for disk
in target_vdu
.get("virtual-storages", {}):
1030 disk
.get("type-of-storage") == "persistent-storage:persistent-storage"
1031 and disk
["id"] not in persistent_root_disk
.keys()
1033 for vdu_volume
in vdu_instantiation_volumes_list
:
1034 if vdu_volume
["vim-volume-id"] and disk
["id"] == vdu_volume
["name"]:
1035 persistent_disk
[disk
["id"]] = {
1036 "vim_volume_id": vdu_volume
["vim-volume-id"],
1038 disk_list
.append(persistent_disk
[disk
["id"]])
1041 if disk
["id"] not in persistent_disk
.keys():
1042 persistent_disk
[disk
["id"]] = {
1043 "size": disk
.get("size-of-storage"),
1044 "keep": Ns
.is_volume_keeping_required(disk
),
1046 disk_list
.append(persistent_disk
[disk
["id"]])
1049 def is_volume_keeping_required(virtual_storage_desc
: Dict
[str, Any
]) -> bool:
1050 """Function to decide keeping persistent volume
1054 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1060 if not virtual_storage_desc
.get("vdu-storage-requirements"):
1062 for item
in virtual_storage_desc
.get("vdu-storage-requirements", {}):
1063 if item
.get("key") == "keep-volume" and item
.get("value").lower() == "true":
1068 def is_shared_volume(
1069 virtual_storage_desc
: Dict
[str, Any
], vnfd_id
: str
1071 """Function to decide if the volume type is multi attached or not .
1074 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1075 vnfd_id (str): vnfd id
1079 name (str) New name if it is a multiattach disk
1082 if vdu_storage_requirements
:= virtual_storage_desc
.get(
1083 "vdu-storage-requirements", {}
1085 for item
in vdu_storage_requirements
:
1087 item
.get("key") == "multiattach"
1088 and item
.get("value").lower() == "true"
1090 name
= f
"shared-{virtual_storage_desc['id']}-{vnfd_id}"
1092 return virtual_storage_desc
["id"], False
1095 def _sort_vdu_interfaces(target_vdu
: dict) -> None:
1096 """Sort the interfaces according to position number.
1099 target_vdu (dict): Details of VDU to be created
1102 # If the position info is provided for all the interfaces, it will be sorted
1103 # according to position number ascendingly.
1104 sorted_interfaces
= sorted(
1105 target_vdu
["interfaces"],
1106 key
=lambda x
: (x
.get("position") is None, x
.get("position")),
1108 target_vdu
["interfaces"] = sorted_interfaces
1111 def _partially_locate_vdu_interfaces(target_vdu
: dict) -> None:
1112 """Only place the interfaces which has specific position.
1115 target_vdu (dict): Details of VDU to be created
1118 # If the position info is provided for some interfaces but not all of them, the interfaces
1119 # which has specific position numbers will be placed and others' positions will not be taken care.
1121 i
.get("position") + 1
1122 for i
in target_vdu
["interfaces"]
1123 if i
.get("position") is not None
1125 n
= len(target_vdu
["interfaces"])
1126 sorted_interfaces
= [-1] * n
1130 if target_vdu
["interfaces"][k
].get("position") is not None:
1131 if any(i
.get("position") == 0 for i
in target_vdu
["interfaces"]):
1132 idx
= target_vdu
["interfaces"][k
]["position"] + 1
1134 idx
= target_vdu
["interfaces"][k
]["position"]
1135 sorted_interfaces
[idx
- 1] = target_vdu
["interfaces"][k
]
1139 if target_vdu
["interfaces"][m
].get("position") is None:
1140 idy
= sorted_interfaces
.index(-1)
1141 sorted_interfaces
[idy
] = target_vdu
["interfaces"][m
]
1144 target_vdu
["interfaces"] = sorted_interfaces
1147 def _prepare_vdu_cloud_init(
1148 target_vdu
: dict, vdu2cloud_init
: dict, db
: object, fs
: object
1150 """Fill cloud_config dict with cloud init details.
1153 target_vdu (dict): Details of VDU to be created
1154 vdu2cloud_init (dict): Cloud init dict
1155 db (object): DB object
1156 fs (object): FS object
1159 cloud_config (dict): Cloud config details of VDU
1165 if target_vdu
.get("cloud-init"):
1166 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1167 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1170 location
=target_vdu
["cloud-init"],
1173 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1174 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1175 cloud_init_content
=cloud_content_
,
1176 params
=target_vdu
.get("additionalParams"),
1177 context
=target_vdu
["cloud-init"],
1180 if target_vdu
.get("boot-data-drive"):
1181 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1186 def _check_vld_information_of_interfaces(
1187 interface
: dict, ns_preffix
: str, vnf_preffix
: str
1189 """Prepare the net_text by the virtual link information for vnf and ns level.
1191 interface (dict): Interface details
1192 ns_preffix (str): Prefix of NS
1193 vnf_preffix (str): Prefix of VNF
1196 net_text (str): information of net
1200 if interface
.get("ns-vld-id"):
1201 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
1202 elif interface
.get("vnf-vld-id"):
1203 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
1208 def _prepare_interface_port_security(interface
: dict) -> None:
1212 interface (dict): Interface details
1215 if "port-security-enabled" in interface
:
1216 interface
["port_security"] = interface
.pop("port-security-enabled")
1218 if "port-security-disable-strategy" in interface
:
1219 interface
["port_security_disable_strategy"] = interface
.pop(
1220 "port-security-disable-strategy"
1224 def _create_net_item_of_interface(interface
: dict, net_text
: str) -> dict:
1225 """Prepare net item including name, port security, floating ip etc.
1228 interface (dict): Interface details
1229 net_text (str): information of net
1232 net_item (dict): Dict including net details
1238 for x
, v
in interface
.items()
1244 "port_security_disable_strategy",
1248 net_item
["net_id"] = "TASK-" + net_text
1249 net_item
["type"] = "virtual"
1254 def _prepare_type_of_interface(
1255 interface
: dict, tasks_by_target_record_id
: dict, net_text
: str, net_item
: dict
1257 """Fill the net item type by interface type such as SR-IOV, OM-MGMT, bridge etc.
1260 interface (dict): Interface details
1261 tasks_by_target_record_id (dict): Task details
1262 net_text (str): information of net
1263 net_item (dict): Dict including net details
1266 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1267 # TODO floating_ip: True/False (or it can be None)
1269 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1270 # Mark the net create task as type data
1272 tasks_by_target_record_id
,
1278 tasks_by_target_record_id
[net_text
]["extra_dict"]["params"][
1282 net_item
["use"] = "data"
1283 net_item
["model"] = interface
["type"]
1284 net_item
["type"] = interface
["type"]
1287 interface
.get("type") == "OM-MGMT"
1288 or interface
.get("mgmt-interface")
1289 or interface
.get("mgmt-vnf")
1291 net_item
["use"] = "mgmt"
1294 # If interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1295 net_item
["use"] = "bridge"
1296 net_item
["model"] = interface
.get("type")
1299 def _prepare_vdu_interfaces(
1305 tasks_by_target_record_id
: dict,
1308 """Prepare the net_item and add net_list, add mgmt interface to extra_dict.
1311 target_vdu (dict): VDU to be created
1312 extra_dict (dict): Dictionary to be filled
1313 ns_preffix (str): NS prefix as string
1314 vnf_preffix (str): VNF prefix as string
1315 logger (object): Logger Object
1316 tasks_by_target_record_id (dict): Task details
1317 net_list (list): Net list of VDU
1319 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
1320 net_text
= Ns
._check
_vld
_information
_of
_interfaces
(
1321 interface
, ns_preffix
, vnf_preffix
1324 # Interface not connected to any vld
1326 "Interface {} from vdu {} not connected to any vld".format(
1327 iface_index
, target_vdu
["vdu-name"]
1332 extra_dict
["depends_on"].append(net_text
)
1334 Ns
._prepare
_interface
_port
_security
(interface
)
1336 net_item
= Ns
._create
_net
_item
_of
_interface
(interface
, net_text
)
1338 Ns
._prepare
_type
_of
_interface
(
1339 interface
, tasks_by_target_record_id
, net_text
, net_item
1342 if interface
.get("ip-address"):
1343 net_item
["ip_address"] = interface
["ip-address"]
1345 if interface
.get("mac-address"):
1346 net_item
["mac_address"] = interface
["mac-address"]
1348 net_list
.append(net_item
)
1350 if interface
.get("mgmt-vnf"):
1351 extra_dict
["mgmt_vnf_interface"] = iface_index
1352 elif interface
.get("mgmt-interface"):
1353 extra_dict
["mgmt_vdu_interface"] = iface_index
1356 def _prepare_vdu_ssh_keys(
1357 target_vdu
: dict, ro_nsr_public_key
: dict, cloud_config
: dict
1359 """Add ssh keys to cloud config.
1362 target_vdu (dict): Details of VDU to be created
1363 ro_nsr_public_key (dict): RO NSR public Key
1364 cloud_config (dict): Cloud config details
1369 if target_vdu
.get("ssh-keys"):
1370 ssh_keys
+= target_vdu
.get("ssh-keys")
1372 if target_vdu
.get("ssh-access-required"):
1373 ssh_keys
.append(ro_nsr_public_key
)
1376 cloud_config
["key-pairs"] = ssh_keys
1379 def _select_persistent_root_disk(vsd
: dict, vdu
: dict) -> dict:
1380 """Selects the persistent root disk if exists.
1382 vsd (dict): Virtual storage descriptors in VNFD
1383 vdu (dict): VNF descriptor
1386 root_disk (dict): Selected persistent root disk
1388 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
1392 ) == "persistent-storage:persistent-storage" and root_disk
.get(
1398 def _add_persistent_root_disk_to_disk_list(
1399 vnfd
: dict, target_vdu
: dict, persistent_root_disk
: dict, disk_list
: list
1401 """Find the persistent root disk and add to disk list.
1404 vnfd (dict): VNF descriptor
1405 target_vdu (dict): Details of VDU to be created
1406 persistent_root_disk (dict): Details of persistent root disk
1407 disk_list (list): Disks of VDU
1410 for vdu
in vnfd
.get("vdu", ()):
1411 if vdu
["name"] == target_vdu
["vdu-name"]:
1412 for vsd
in vnfd
.get("virtual-storage-desc", ()):
1413 root_disk
= Ns
._select
_persistent
_root
_disk
(vsd
, vdu
)
1417 persistent_root_disk
[vsd
["id"]] = {
1418 "image_id": vdu
.get("sw-image-desc"),
1419 "size": root_disk
["size-of-storage"],
1420 "keep": Ns
.is_volume_keeping_required(root_disk
),
1422 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1426 def _add_persistent_ordinary_disks_to_disk_list(
1428 persistent_root_disk
: dict,
1429 persistent_ordinary_disk
: dict,
1435 """Fill the disk list by adding persistent ordinary disks.
1438 target_vdu (dict): Details of VDU to be created
1439 persistent_root_disk (dict): Details of persistent root disk
1440 persistent_ordinary_disk (dict): Details of persistent ordinary disk
1441 disk_list (list): Disks of VDU
1444 if target_vdu
.get("virtual-storages"):
1445 for disk
in target_vdu
["virtual-storages"]:
1447 disk
.get("type-of-storage")
1448 == "persistent-storage:persistent-storage"
1449 and disk
["id"] not in persistent_root_disk
.keys()
1451 name
, multiattach
= Ns
.is_shared_volume(disk
, vnf_id
)
1452 persistent_ordinary_disk
[disk
["id"]] = {
1454 "size": disk
["size-of-storage"],
1455 "keep": Ns
.is_volume_keeping_required(disk
),
1456 "multiattach": multiattach
,
1458 disk_list
.append(persistent_ordinary_disk
[disk
["id"]])
1459 if multiattach
: # VDU creation has to wait for shared volumes
1460 extra_dict
["depends_on"].append(
1461 f
"nsrs:{nsr_id}:shared-volumes.{name}"
1465 def _prepare_vdu_affinity_group_list(
1466 target_vdu
: dict, extra_dict
: dict, ns_preffix
: str
1467 ) -> List
[Dict
[str, any
]]:
1468 """Process affinity group details to prepare affinity group list.
1471 target_vdu (dict): Details of VDU to be created
1472 extra_dict (dict): Dictionary to be filled
1473 ns_preffix (str): Prefix as string
1477 affinity_group_list (list): Affinity group details
1480 affinity_group_list
= []
1482 if target_vdu
.get("affinity-or-anti-affinity-group-id"):
1483 for affinity_group_id
in target_vdu
["affinity-or-anti-affinity-group-id"]:
1485 affinity_group_text
= (
1486 ns_preffix
+ ":affinity-or-anti-affinity-group." + affinity_group_id
1489 if not isinstance(extra_dict
.get("depends_on"), list):
1490 raise NsException("Invalid extra_dict format.")
1492 extra_dict
["depends_on"].append(affinity_group_text
)
1493 affinity_group
["affinity_group_id"] = "TASK-" + affinity_group_text
1494 affinity_group_list
.append(affinity_group
)
1496 return affinity_group_list
1499 def _process_vdu_params(
1500 target_vdu
: Dict
[str, Any
],
1501 indata
: Dict
[str, Any
],
1502 vim_info
: Dict
[str, Any
],
1503 target_record_id
: str,
1504 **kwargs
: Dict
[str, Any
],
1505 ) -> Dict
[str, Any
]:
1506 """Function to process VDU parameters.
1509 target_vdu (Dict[str, Any]): [description]
1510 indata (Dict[str, Any]): [description]
1511 vim_info (Dict[str, Any]): [description]
1512 target_record_id (str): [description]
1515 Dict[str, Any]: [description]
1517 vnfr_id
= kwargs
.get("vnfr_id")
1518 nsr_id
= kwargs
.get("nsr_id")
1519 vnfr
= kwargs
.get("vnfr")
1520 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1521 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
1522 logger
= kwargs
.get("logger")
1523 db
= kwargs
.get("db")
1524 fs
= kwargs
.get("fs")
1525 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1527 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
1528 ns_preffix
= "nsrs:{}".format(nsr_id
)
1529 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
1530 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
1531 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
1533 persistent_root_disk
= {}
1534 persistent_ordinary_disk
= {}
1535 vdu_instantiation_volumes_list
= []
1537 vnfd_id
= vnfr
["vnfd-id"]
1538 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
1539 # If the position info is provided for all the interfaces, it will be sorted
1540 # according to position number ascendingly.
1542 True if i
.get("position") is not None else False
1543 for i
in target_vdu
["interfaces"]
1545 Ns
._sort
_vdu
_interfaces
(target_vdu
)
1547 # If the position info is provided for some interfaces but not all of them, the interfaces
1548 # which has specific position numbers will be placed and others' positions will not be taken care.
1550 Ns
._partially
_locate
_vdu
_interfaces
(target_vdu
)
1552 # If the position info is not provided for the interfaces, interfaces will be attached
1553 # according to the order in the VNFD.
1554 Ns
._prepare
_vdu
_interfaces
(
1560 tasks_by_target_record_id
,
1565 cloud_config
= Ns
._prepare
_vdu
_cloud
_init
(target_vdu
, vdu2cloud_init
, db
, fs
)
1567 # Prepare VDU ssh keys
1568 Ns
._prepare
_vdu
_ssh
_keys
(target_vdu
, ro_nsr_public_key
, cloud_config
)
1570 if target_vdu
.get("additionalParams"):
1571 vdu_instantiation_volumes_list
= (
1572 target_vdu
.get("additionalParams").get("OSM", {}).get("vdu_volumes")
1575 if vdu_instantiation_volumes_list
:
1576 # Find the root volumes and add to the disk_list
1577 persistent_root_disk
= Ns
.find_persistent_root_volumes(
1578 vnfd
, target_vdu
, vdu_instantiation_volumes_list
, disk_list
1581 # Find the ordinary volumes which are not added to the persistent_root_disk
1582 # and put them to the disk list
1583 Ns
.find_persistent_volumes(
1584 persistent_root_disk
,
1586 vdu_instantiation_volumes_list
,
1591 # Vdu_instantiation_volumes_list is empty
1592 # First get add the persistent root disks to disk_list
1593 Ns
._add
_persistent
_root
_disk
_to
_disk
_list
(
1594 vnfd
, target_vdu
, persistent_root_disk
, disk_list
1596 # Add the persistent non-root disks to disk_list
1597 Ns
._add
_persistent
_ordinary
_disks
_to
_disk
_list
(
1599 persistent_root_disk
,
1600 persistent_ordinary_disk
,
1607 affinity_group_list
= Ns
._prepare
_vdu
_affinity
_group
_list
(
1608 target_vdu
, extra_dict
, ns_preffix
1611 extra_dict
["params"] = {
1612 "name": "{}-{}-{}-{}".format(
1613 indata
["name"][:16],
1614 vnfr
["member-vnf-index-ref"][:16],
1615 target_vdu
["vdu-name"][:32],
1616 target_vdu
.get("count-index") or 0,
1618 "description": target_vdu
["vdu-name"],
1620 "image_id": "TASK-" + image_text
,
1621 "flavor_id": "TASK-" + flavor_text
,
1622 "affinity_group_list": affinity_group_list
,
1623 "net_list": net_list
,
1624 "cloud_config": cloud_config
or None,
1625 "disk_list": disk_list
,
1626 "availability_zone_index": None, # TODO
1627 "availability_zone_list": None, # TODO
1632 def _process_shared_volumes_params(
1633 target_shared_volume
: Dict
[str, Any
],
1634 indata
: Dict
[str, Any
],
1635 vim_info
: Dict
[str, Any
],
1636 target_record_id
: str,
1637 **kwargs
: Dict
[str, Any
],
1638 ) -> Dict
[str, Any
]:
1640 shared_volume_data
= {
1641 "size": target_shared_volume
["size-of-storage"],
1642 "name": target_shared_volume
["id"],
1643 "type": target_shared_volume
["type-of-storage"],
1644 "keep": Ns
.is_volume_keeping_required(target_shared_volume
),
1646 extra_dict
["params"] = shared_volume_data
1650 def _process_affinity_group_params(
1651 target_affinity_group
: Dict
[str, Any
],
1652 indata
: Dict
[str, Any
],
1653 vim_info
: Dict
[str, Any
],
1654 target_record_id
: str,
1655 **kwargs
: Dict
[str, Any
],
1656 ) -> Dict
[str, Any
]:
1657 """Get affinity or anti-affinity group parameters.
1660 target_affinity_group (Dict[str, Any]): [description]
1661 indata (Dict[str, Any]): [description]
1662 vim_info (Dict[str, Any]): [description]
1663 target_record_id (str): [description]
1666 Dict[str, Any]: [description]
1670 affinity_group_data
= {
1671 "name": target_affinity_group
["name"],
1672 "type": target_affinity_group
["type"],
1673 "scope": target_affinity_group
["scope"],
1676 if target_affinity_group
.get("vim-affinity-group-id"):
1677 affinity_group_data
["vim-affinity-group-id"] = target_affinity_group
[
1678 "vim-affinity-group-id"
1681 extra_dict
["params"] = {
1682 "affinity_group_data": affinity_group_data
,
1687 def _process_recreate_vdu_params(
1688 existing_vdu
: Dict
[str, Any
],
1689 db_nsr
: Dict
[str, Any
],
1690 vim_info
: Dict
[str, Any
],
1691 target_record_id
: str,
1693 **kwargs
: Dict
[str, Any
],
1694 ) -> Dict
[str, Any
]:
1695 """Function to process VDU parameters to recreate.
1698 existing_vdu (Dict[str, Any]): [description]
1699 db_nsr (Dict[str, Any]): [description]
1700 vim_info (Dict[str, Any]): [description]
1701 target_record_id (str): [description]
1702 target_id (str): [description]
1705 Dict[str, Any]: [description]
1707 vnfr
= kwargs
.get("vnfr")
1708 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1709 # logger = kwargs.get("logger")
1710 db
= kwargs
.get("db")
1711 fs
= kwargs
.get("fs")
1712 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1718 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
1720 if vim_details_text
:
1721 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
1723 for iface_index
, interface
in enumerate(existing_vdu
["interfaces"]):
1724 if "port-security-enabled" in interface
:
1725 interface
["port_security"] = interface
.pop("port-security-enabled")
1727 if "port-security-disable-strategy" in interface
:
1728 interface
["port_security_disable_strategy"] = interface
.pop(
1729 "port-security-disable-strategy"
1734 for x
, v
in interface
.items()
1740 "port_security_disable_strategy",
1744 existing_ifaces
= existing_vdu
["vim_info"][target_id
].get(
1745 "interfaces_backup", []
1750 for i
in existing_ifaces
1751 if i
["ip_address"] == interface
["ip-address"]
1756 net_item
["net_id"] = net_id
1757 net_item
["type"] = "virtual"
1759 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1760 # TODO floating_ip: True/False (or it can be None)
1761 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1762 net_item
["use"] = "data"
1763 net_item
["model"] = interface
["type"]
1764 net_item
["type"] = interface
["type"]
1766 interface
.get("type") == "OM-MGMT"
1767 or interface
.get("mgmt-interface")
1768 or interface
.get("mgmt-vnf")
1770 net_item
["use"] = "mgmt"
1772 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1773 net_item
["use"] = "bridge"
1774 net_item
["model"] = interface
.get("type")
1776 if interface
.get("ip-address"):
1777 net_item
["ip_address"] = interface
["ip-address"]
1779 if interface
.get("mac-address"):
1780 net_item
["mac_address"] = interface
["mac-address"]
1782 net_list
.append(net_item
)
1784 if interface
.get("mgmt-vnf"):
1785 extra_dict
["mgmt_vnf_interface"] = iface_index
1786 elif interface
.get("mgmt-interface"):
1787 extra_dict
["mgmt_vdu_interface"] = iface_index
1792 if existing_vdu
.get("cloud-init"):
1793 if existing_vdu
["cloud-init"] not in vdu2cloud_init
:
1794 vdu2cloud_init
[existing_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1797 location
=existing_vdu
["cloud-init"],
1800 cloud_content_
= vdu2cloud_init
[existing_vdu
["cloud-init"]]
1801 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1802 cloud_init_content
=cloud_content_
,
1803 params
=existing_vdu
.get("additionalParams"),
1804 context
=existing_vdu
["cloud-init"],
1807 if existing_vdu
.get("boot-data-drive"):
1808 cloud_config
["boot-data-drive"] = existing_vdu
.get("boot-data-drive")
1812 if existing_vdu
.get("ssh-keys"):
1813 ssh_keys
+= existing_vdu
.get("ssh-keys")
1815 if existing_vdu
.get("ssh-access-required"):
1816 ssh_keys
.append(ro_nsr_public_key
)
1819 cloud_config
["key-pairs"] = ssh_keys
1822 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
1823 disk_list
.append({"vim_id": vol_id
["id"]})
1825 affinity_group_list
= []
1827 if existing_vdu
.get("affinity-or-anti-affinity-group-id"):
1829 for affinity_group_id
in existing_vdu
["affinity-or-anti-affinity-group-id"]:
1830 for group
in db_nsr
.get("affinity-or-anti-affinity-group"):
1832 group
["id"] == affinity_group_id
1833 and group
["vim_info"][target_id
].get("vim_id", None) is not None
1835 affinity_group
["affinity_group_id"] = group
["vim_info"][
1837 ].get("vim_id", None)
1838 affinity_group_list
.append(affinity_group
)
1840 extra_dict
["params"] = {
1841 "name": "{}-{}-{}-{}".format(
1842 db_nsr
["name"][:16],
1843 vnfr
["member-vnf-index-ref"][:16],
1844 existing_vdu
["vdu-name"][:32],
1845 existing_vdu
.get("count-index") or 0,
1847 "description": existing_vdu
["vdu-name"],
1849 "image_id": vim_details
["image"]["id"],
1850 "flavor_id": vim_details
["flavor"]["id"],
1851 "affinity_group_list": affinity_group_list
,
1852 "net_list": net_list
,
1853 "cloud_config": cloud_config
or None,
1854 "disk_list": disk_list
,
1855 "availability_zone_index": None, # TODO
1856 "availability_zone_list": None, # TODO
1861 def calculate_diff_items(
1868 tasks_by_target_record_id
,
1875 """Function that returns the incremental changes (creation, deletion)
1876 related to a specific item `item` to be done. This function should be
1877 called for NS instantiation, NS termination, NS update to add a new VNF
1878 or a new VLD, remove a VNF or VLD, etc.
1879 Item can be `net`, `flavor`, `image` or `vdu`.
1880 It takes a list of target items from indata (which came from the REST API)
1881 and compares with the existing items from db_ro_nsr, identifying the
1882 incremental changes to be done. During the comparison, it calls the method
1883 `process_params` (which was passed as parameter, and is particular for each
1887 indata (Dict[str, Any]): deployment info
1888 db_nsr: NSR record from DB
1889 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1890 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1891 item (str): element to process (net, vdu...)
1892 tasks_by_target_record_id (Dict[str, Any]):
1893 [<target_record_id>, <task>]
1894 action_id (str): action id
1895 nsr_id (str): NSR id
1896 task_index (number): task index to add to task name
1897 vnfr_id (str): VNFR id
1898 vnfr (Dict[str, Any]): VNFR info
1901 List: list with the incremental changes (deletes, creates) for each item
1902 number: current task index
1910 process_params
= None
1911 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1912 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1913 # According to the type of item, the path, the target_list,
1914 # the existing_list and the method to process params are set
1915 db_path
= self
.db_path_map
[item
]
1916 process_params
= self
.process_params_function_map
[item
]
1917 if item
in ("net", "vdu"):
1918 # This case is specific for the NS VLD (not applied to VDU)
1920 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1921 target_list
= indata
.get("ns", []).get(db_path
, [])
1922 existing_list
= db_nsr
.get(db_path
, [])
1923 # This case is common for VNF VLDs and VNF VDUs
1925 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
1927 (vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
),
1930 target_list
= target_vnf
.get(db_path
, []) if target_vnf
else []
1931 existing_list
= vnfr
.get(db_path
, [])
1935 "affinity-or-anti-affinity-group",
1938 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1939 target_list
= indata
.get(item
, [])
1940 existing_list
= db_nsr
.get(item
, [])
1942 raise NsException("Item not supported: {}", item
)
1943 # ensure all the target_list elements has an "id". If not assign the index as id
1944 if target_list
is None:
1946 for target_index
, tl
in enumerate(target_list
):
1947 if tl
and not tl
.get("id"):
1948 tl
["id"] = str(target_index
)
1949 # step 1 items (networks,vdus,...) to be deleted/updated
1950 for item_index
, existing_item
in enumerate(existing_list
):
1952 (t
for t
in target_list
if t
["id"] == existing_item
["id"]),
1955 for target_vim
, existing_viminfo
in existing_item
.get(
1958 if existing_viminfo
is None:
1962 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
1964 target_viminfo
= None
1966 if target_viminfo
is None:
1968 self
._assign
_vim
(target_vim
)
1969 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
1972 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
1973 # item must be sdn-net instead of net if target_vim is a sdn
1975 target_record_id
+= ".sdn"
1978 "action_id": action_id
,
1980 "task_index": task_index
,
1985 "deployment_info": deployment_info
,
1986 "target_id": target_vim
,
1989 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1990 "target_record_id": target_record_id
,
1995 # step 2 items (networks,vdus,...) to be created
1996 for target_item
in target_list
:
1998 for item_index
, existing_item
in enumerate(existing_list
):
1999 if existing_item
["id"] == target_item
["id"]:
2003 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
2004 existing_list
.append(target_item
)
2005 existing_item
= None
2007 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
2008 existing_viminfo
= None
2011 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
2013 if existing_viminfo
is not None:
2016 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
2019 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
2020 # item must be sdn-net instead of net if target_vim is a sdn
2022 target_record_id
+= ".sdn"
2026 "ns.calculate_diff_items target_item={}".format(target_item
)
2028 if process_params
== Ns
._process
_flavor
_params
:
2035 "calculate_diff_items for flavor kwargs={}".format(kwargs
)
2038 if process_params
== Ns
._process
_vdu
_params
:
2039 self
.logger
.debug("calculate_diff_items self.fs={}".format(self
.fs
))
2045 "vdu2cloud_init": vdu2cloud_init
,
2046 "tasks_by_target_record_id": tasks_by_target_record_id
,
2047 "logger": self
.logger
,
2050 "ro_nsr_public_key": ro_nsr_public_key
,
2053 self
.logger
.debug("calculate_diff_items kwargs={}".format(kwargs
))
2054 extra_dict
= process_params(
2061 self
._assign
_vim
(target_vim
)
2064 "action_id": action_id
,
2066 "task_index": task_index
,
2070 "deployment_info": deployment_info
,
2071 "target_id": target_vim
,
2074 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
2075 "target_record_id": target_record_id
,
2076 "extra_dict": extra_dict
,
2077 "common_id": target_item
.get("common_id", None),
2079 diff_items
.append(new_item
)
2080 tasks_by_target_record_id
[target_record_id
] = new_item
2083 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
2085 return diff_items
, task_index
2087 def calculate_all_differences_to_deploy(
2097 tasks_by_target_record_id
,
2099 """This method calculates the ordered list of items (`changes_list`)
2100 to be created and deleted.
2103 indata (Dict[str, Any]): deployment info
2104 nsr_id (str): NSR id
2105 db_nsr: NSR record from DB
2106 db_vnfrs: VNFRS record from DB
2107 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2108 db_nsr_update (Dict[str, Any]): NSR info to update in DB
2109 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
2110 action_id (str): action id
2111 tasks_by_target_record_id (Dict[str, Any]):
2112 [<target_record_id>, <task>]
2115 List: ordered list of items to be created and deleted.
2119 # set list with diffs:
2122 # NS vld, image and flavor
2127 "affinity-or-anti-affinity-group",
2129 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
2130 diff_items
, task_index
= self
.calculate_diff_items(
2133 db_ro_nsr
=db_ro_nsr
,
2134 db_nsr_update
=db_nsr_update
,
2136 tasks_by_target_record_id
=tasks_by_target_record_id
,
2137 action_id
=action_id
,
2139 task_index
=task_index
,
2142 changes_list
+= diff_items
2145 for vnfr_id
, vnfr
in db_vnfrs
.items():
2146 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
2147 for item
in ["net", "vdu", "shared-volumes"]:
2148 self
.logger
.debug("process VNF={} {}".format(vnfr_id
, item
))
2149 diff_items
, task_index
= self
.calculate_diff_items(
2152 db_ro_nsr
=db_ro_nsr
,
2153 db_nsr_update
=db_vnfrs_update
[vnfr
["_id"]],
2155 tasks_by_target_record_id
=tasks_by_target_record_id
,
2156 action_id
=action_id
,
2158 task_index
=task_index
,
2162 changes_list
+= diff_items
2166 def define_all_tasks(
2170 tasks_by_target_record_id
,
2172 """Function to create all the task structures obtanied from
2173 the method calculate_all_differences_to_deploy
2176 changes_list (List): ordered list of items to be created or deleted
2177 db_new_tasks (List): tasks list to be created
2178 action_id (str): action id
2179 tasks_by_target_record_id (Dict[str, Any]):
2180 [<target_record_id>, <task>]
2184 for change
in changes_list
:
2185 task
= Ns
._create
_task
(
2186 deployment_info
=change
["deployment_info"],
2187 target_id
=change
["target_id"],
2188 item
=change
["item"],
2189 action
=change
["action"],
2190 target_record
=change
["target_record"],
2191 target_record_id
=change
["target_record_id"],
2192 extra_dict
=change
.get("extra_dict", None),
2195 self
.logger
.debug("ns.define_all_tasks task={}".format(task
))
2196 tasks_by_target_record_id
[change
["target_record_id"]] = task
2197 db_new_tasks
.append(task
)
2199 if change
.get("common_id"):
2200 task
["common_id"] = change
["common_id"]
2202 def upload_all_tasks(
2207 """Function to save all tasks in the common DB
2210 db_new_tasks (List): tasks list to be created
2211 now (time): current time
2215 nb_ro_tasks
= 0 # for logging
2217 for db_task
in db_new_tasks
:
2218 target_id
= db_task
.pop("target_id")
2219 common_id
= db_task
.get("common_id")
2221 # Do not chek tasks with vim_status DELETED
2222 # because in manual heealing there are two tasks for the same vdur:
2223 # one with vim_status deleted and the other one with the actual VM status.
2229 "target_id": target_id
,
2230 "tasks.common_id": common_id
,
2231 "vim_info.vim_status.ne": "DELETED",
2233 update_dict
={"to_check_at": now
, "modified_at": now
},
2234 push
={"tasks": db_task
},
2235 fail_on_empty
=False,
2239 if not self
.db
.set_one(
2242 "target_id": target_id
,
2243 "tasks.target_record": db_task
["target_record"],
2244 "vim_info.vim_status.ne": "DELETED",
2246 update_dict
={"to_check_at": now
, "modified_at": now
},
2247 push
={"tasks": db_task
},
2248 fail_on_empty
=False,
2251 self
.logger
.debug("Updating database, Creating ro_tasks")
2252 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2254 self
.db
.create("ro_tasks", db_ro_task
)
2257 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2258 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2262 def upload_recreate_tasks(
2267 """Function to save recreate tasks in the common DB
2270 db_new_tasks (List): tasks list to be created
2271 now (time): current time
2275 nb_ro_tasks
= 0 # for logging
2277 for db_task
in db_new_tasks
:
2278 target_id
= db_task
.pop("target_id")
2279 self
.logger
.debug("target_id={} db_task={}".format(target_id
, db_task
))
2281 action
= db_task
.get("action", None)
2284 self
.logger
.debug("Updating database, Creating ro_tasks")
2285 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2287 # If DELETE task: the associated created items should be removed
2288 # (except persistent volumes):
2289 if action
== "DELETE":
2290 db_ro_task
["vim_info"]["created"] = True
2291 db_ro_task
["vim_info"]["created_items"] = db_task
.get(
2294 db_ro_task
["vim_info"]["volumes_to_hold"] = db_task
.get(
2295 "volumes_to_hold", []
2297 db_ro_task
["vim_info"]["vim_id"] = db_task
.get("vim_id", None)
2300 self
.logger
.debug("upload_all_tasks db_ro_task={}".format(db_ro_task
))
2301 self
.db
.create("ro_tasks", db_ro_task
)
2304 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2305 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2309 def _prepare_created_items_for_healing(
2315 # Get created_items from ro_task
2316 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2317 for ro_task
in ro_tasks
:
2318 for task
in ro_task
["tasks"]:
2320 task
["target_record"] == target_record
2321 and task
["action"] == "CREATE"
2322 and ro_task
["vim_info"]["created_items"]
2324 created_items
= ro_task
["vim_info"]["created_items"]
2327 return created_items
2329 def _prepare_persistent_volumes_for_healing(
2334 # The associated volumes of the VM shouldn't be removed
2337 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
2338 if vim_details_text
:
2339 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
2341 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
2342 volumes_list
.append(vol_id
["id"])
2346 def prepare_changes_to_recreate(
2354 tasks_by_target_record_id
,
2356 """This method will obtain an ordered list of items (`changes_list`)
2357 to be created and deleted to meet the recreate request.
2361 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id
, indata
)
2365 # set list with diffs:
2367 db_path
= self
.db_path_map
["vdu"]
2368 target_list
= indata
.get("healVnfData", {})
2369 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
2370 ro_nsr_public_key
= db_ro_nsr
["public_key"]
2372 # Check each VNF of the target
2373 for target_vnf
in target_list
:
2374 # Find this VNF in the list from DB, raise exception if vnfInstanceId is not found
2375 vnfr_id
= target_vnf
["vnfInstanceId"]
2376 existing_vnf
= db_vnfrs
.get(vnfr_id
, {})
2377 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
2378 # vim_account_id = existing_vnf.get("vim-account-id", "")
2380 target_vdus
= target_vnf
.get("additionalParams", {}).get("vdu", [])
2381 # Check each VDU of this VNF
2383 # Create target_vdu_list from DB, if VDUs are not specified
2385 for existing_vdu
in existing_vnf
.get("vdur"):
2386 vdu_name
= existing_vdu
.get("vdu-name", None)
2387 vdu_index
= existing_vdu
.get("count-index", 0)
2388 vdu_to_be_healed
= {"vdu-id": vdu_name
, "count-index": vdu_index
}
2389 target_vdus
.append(vdu_to_be_healed
)
2390 for target_vdu
in target_vdus
:
2391 vdu_name
= target_vdu
.get("vdu-id", None)
2392 # For multi instance VDU count-index is mandatory
2393 # For single session VDU count-indes is 0
2394 count_index
= target_vdu
.get("count-index", 0)
2396 existing_instance
= {}
2398 for instance
in existing_vnf
.get("vdur", {}):
2400 instance
["vdu-name"] == vdu_name
2401 and instance
["count-index"] == count_index
2403 existing_instance
= instance
2408 target_record_id
= "{}.{}".format(db_record
, existing_instance
["id"])
2410 # The target VIM is the one already existing in DB to recreate
2411 for target_vim
, target_viminfo
in existing_instance
.get(
2414 # step 1 vdu to be deleted
2415 self
._assign
_vim
(target_vim
)
2417 "action_id": action_id
,
2419 "task_index": task_index
,
2422 target_record
= f
"{db_record}.{item_index}.vim_info.{target_vim}"
2423 created_items
= self
._prepare
_created
_items
_for
_healing
(
2424 nsr_id
, target_record
2427 volumes_to_hold
= self
._prepare
_persistent
_volumes
_for
_healing
(
2428 target_vim
, existing_instance
2431 # Specific extra params for recreate tasks:
2433 "created_items": created_items
,
2434 "vim_id": existing_instance
["vim-id"],
2435 "volumes_to_hold": volumes_to_hold
,
2438 changes_list
.append(
2440 "deployment_info": deployment_info
,
2441 "target_id": target_vim
,
2444 "target_record": target_record
,
2445 "target_record_id": target_record_id
,
2446 "extra_dict": extra_dict
,
2449 delete_task_id
= f
"{action_id}:{task_index}"
2452 # step 2 vdu to be created
2458 "vnfr": existing_vnf
,
2459 "vdu2cloud_init": vdu2cloud_init
,
2460 "tasks_by_target_record_id": tasks_by_target_record_id
,
2461 "logger": self
.logger
,
2464 "ro_nsr_public_key": ro_nsr_public_key
,
2468 extra_dict
= self
._process
_recreate
_vdu
_params
(
2477 # The CREATE task depens on the DELETE task
2478 extra_dict
["depends_on"] = [delete_task_id
]
2480 # Add volumes created from created_items if any
2481 # Ports should be deleted with delete task and automatically created with create task
2483 for k
, v
in created_items
.items():
2485 k_item
, _
, k_id
= k
.partition(":")
2486 if k_item
== "volume":
2488 except Exception as e
:
2490 "Error evaluating created item {}: {}".format(k
, e
)
2492 extra_dict
["previous_created_volumes"] = volumes
2495 "action_id": action_id
,
2497 "task_index": task_index
,
2499 self
._assign
_vim
(target_vim
)
2502 "deployment_info": deployment_info
,
2503 "target_id": target_vim
,
2506 "target_record": target_record
,
2507 "target_record_id": target_record_id
,
2508 "extra_dict": extra_dict
,
2510 changes_list
.append(new_item
)
2511 tasks_by_target_record_id
[target_record_id
] = new_item
2516 def recreate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2517 self
.logger
.debug("ns.recreate nsr_id={} indata={}".format(nsr_id
, indata
))
2518 # TODO: validate_input(indata, recreate_schema)
2519 action_id
= indata
.get("action_id", str(uuid4()))
2520 # get current deployment
2521 db_vnfrs
= {} # vnf's info indexed by _id
2523 logging_text
= "Recreate nsr_id={} action_id={} indata={}".format(
2524 nsr_id
, action_id
, indata
2526 self
.logger
.debug(logging_text
+ "Enter")
2529 step
= "Getting ns and vnfr record from db"
2530 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2532 tasks_by_target_record_id
= {}
2533 # read from db: vnf's of this ns
2534 step
= "Getting vnfrs from db"
2535 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2536 self
.logger
.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list
))
2538 if not db_vnfrs_list
:
2539 raise NsException("Cannot obtain associated VNF for ns")
2541 for vnfr
in db_vnfrs_list
:
2542 db_vnfrs
[vnfr
["_id"]] = vnfr
2545 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2546 self
.logger
.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr
))
2549 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2551 with self
.write_lock
:
2553 step
= "process NS elements"
2554 changes_list
= self
.prepare_changes_to_recreate(
2559 db_ro_nsr
=db_ro_nsr
,
2560 action_id
=action_id
,
2561 tasks_by_target_record_id
=tasks_by_target_record_id
,
2564 self
.define_all_tasks(
2565 changes_list
=changes_list
,
2566 db_new_tasks
=db_new_tasks
,
2567 tasks_by_target_record_id
=tasks_by_target_record_id
,
2570 # Delete all ro_tasks registered for the targets vdurs (target_record)
2571 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2572 # So remove all task related to target record.
2573 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2574 for change
in changes_list
:
2575 for ro_task
in ro_tasks
:
2576 for task
in ro_task
["tasks"]:
2577 if task
["target_record"] == change
["target_record"]:
2581 "_id": ro_task
["_id"],
2582 "modified_at": ro_task
["modified_at"],
2584 fail_on_empty
=False,
2587 step
= "Updating database, Appending tasks to ro_tasks"
2588 self
.upload_recreate_tasks(
2589 db_new_tasks
=db_new_tasks
,
2594 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2598 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2602 except Exception as e
:
2603 if isinstance(e
, (DbException
, NsException
)):
2605 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2608 e
= traceback_format_exc()
2609 self
.logger
.critical(
2610 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2614 raise NsException(e
)
2616 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2617 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
2618 validate_input(indata
, deploy_schema
)
2619 action_id
= indata
.get("action_id", str(uuid4()))
2621 # get current deployment
2622 db_nsr_update
= {} # update operation on nsrs
2623 db_vnfrs_update
= {}
2624 db_vnfrs
= {} # vnf's info indexed by _id
2626 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2627 self
.logger
.debug(logging_text
+ "Enter")
2630 step
= "Getting ns and vnfr record from db"
2631 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2632 self
.logger
.debug("ns.deploy: db_nsr={}".format(db_nsr
))
2634 tasks_by_target_record_id
= {}
2635 # read from db: vnf's of this ns
2636 step
= "Getting vnfrs from db"
2637 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2639 if not db_vnfrs_list
:
2640 raise NsException("Cannot obtain associated VNF for ns")
2642 for vnfr
in db_vnfrs_list
:
2643 db_vnfrs
[vnfr
["_id"]] = vnfr
2644 db_vnfrs_update
[vnfr
["_id"]] = {}
2645 self
.logger
.debug("ns.deploy db_vnfrs={}".format(db_vnfrs
))
2648 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2651 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2653 # check that action_id is not in the list of actions. Suffixed with :index
2654 if action_id
in db_ro_nsr
["actions"]:
2658 new_action_id
= "{}:{}".format(action_id
, index
)
2660 if new_action_id
not in db_ro_nsr
["actions"]:
2661 action_id
= new_action_id
2664 + "Changing action_id in use to {}".format(action_id
)
2670 def _process_action(indata
):
2671 nonlocal db_new_tasks
2678 if indata
["action"]["action"] == "inject_ssh_key":
2679 key
= indata
["action"].get("key")
2680 user
= indata
["action"].get("user")
2681 password
= indata
["action"].get("password")
2683 for vnf
in indata
.get("vnf", ()):
2684 if vnf
["_id"] not in db_vnfrs
:
2685 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
2687 db_vnfr
= db_vnfrs
[vnf
["_id"]]
2689 for target_vdu
in vnf
.get("vdur", ()):
2690 vdu_index
, vdur
= next(
2693 for i_v
in enumerate(db_vnfr
["vdur"])
2694 if i_v
[1]["id"] == target_vdu
["id"]
2701 "Invalid vdu vnf={}.{}".format(
2702 vnf
["_id"], target_vdu
["id"]
2706 target_vim
, vim_info
= next(
2707 k_v
for k_v
in vdur
["vim_info"].items()
2709 self
._assign
_vim
(target_vim
)
2710 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
2711 vnf
["_id"], vdu_index
2715 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
2718 "ip_address": vdur
.get("ip-address"),
2721 "password": password
,
2722 "private_key": db_ro_nsr
["private_key"],
2723 "salt": db_ro_nsr
["_id"],
2724 "schema_version": db_ro_nsr
["_admin"][
2731 "action_id": action_id
,
2733 "task_index": task_index
,
2736 task
= Ns
._create
_task
(
2737 deployment_info
=deployment_info
,
2738 target_id
=target_vim
,
2741 target_record
=target_record
,
2742 target_record_id
=None,
2743 extra_dict
=extra_dict
,
2746 task_index
= deployment_info
.get("task_index")
2748 db_new_tasks
.append(task
)
2750 with self
.write_lock
:
2751 if indata
.get("action"):
2752 _process_action(indata
)
2754 # compute network differences
2756 step
= "process NS elements"
2757 changes_list
= self
.calculate_all_differences_to_deploy(
2762 db_ro_nsr
=db_ro_nsr
,
2763 db_nsr_update
=db_nsr_update
,
2764 db_vnfrs_update
=db_vnfrs_update
,
2765 action_id
=action_id
,
2766 tasks_by_target_record_id
=tasks_by_target_record_id
,
2768 self
.define_all_tasks(
2769 changes_list
=changes_list
,
2770 db_new_tasks
=db_new_tasks
,
2771 tasks_by_target_record_id
=tasks_by_target_record_id
,
2774 step
= "Updating database, Appending tasks to ro_tasks"
2775 self
.upload_all_tasks(
2776 db_new_tasks
=db_new_tasks
,
2780 step
= "Updating database, nsrs"
2782 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
2784 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
2786 step
= "Updating database, vnfrs={}".format(vnfr_id
)
2787 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
2790 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2794 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2798 except Exception as e
:
2799 if isinstance(e
, (DbException
, NsException
)):
2801 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2804 e
= traceback_format_exc()
2805 self
.logger
.critical(
2806 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2810 raise NsException(e
)
2812 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2813 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
2814 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2816 with self
.write_lock
:
2818 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
2819 except NsWorkerException
as e
:
2820 raise NsException(e
)
2822 return None, None, True
2824 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2826 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2827 version
, nsr_id
, action_id
, indata
2833 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
2834 global_status
= "DONE"
2837 for ro_task
in ro_tasks
:
2838 for task
in ro_task
["tasks"]:
2839 if task
and task
["action_id"] == action_id
:
2840 task_list
.append(task
)
2843 if task
["status"] == "FAILED":
2844 global_status
= "FAILED"
2845 error_text
= "Error at {} {}: {}".format(
2846 task
["action"].lower(),
2848 ro_task
["vim_info"].get("vim_message") or "unknown",
2850 details
.append(error_text
)
2851 elif task
["status"] in ("SCHEDULED", "BUILD"):
2852 if global_status
!= "FAILED":
2853 global_status
= "BUILD"
2858 "status": global_status
,
2859 "details": ". ".join(details
)
2861 else "progress {}/{}".format(done
, total
),
2863 "action_id": action_id
,
2867 return return_data
, None, True
2869 def recreate_status(
2870 self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
2872 return self
.status(session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
)
2874 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2876 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2877 session
, indata
, version
, nsr_id
, action_id
2881 return None, None, True
2883 def rebuild_start_stop_task(
2894 self
._assign
_vim
(target_vim
)
2895 target_record
= "vnfrs:{}:vdur.{}.vim_info.{}".format(
2896 vnf_id
, vdu_index
, target_vim
2898 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_id
)
2900 "action_id": action_id
,
2902 "task_index": task_index
,
2905 task
= Ns
._create
_task
(
2906 deployment_info
=deployment_info
,
2907 target_id
=target_vim
,
2910 target_record
=target_record
,
2911 target_record_id
=target_record_id
,
2912 extra_dict
=extra_dict
,
2916 def rebuild_start_stop(
2917 self
, session
, action_dict
, version
, nsr_id
, *args
, **kwargs
2922 action_id
= action_dict
.get("action_id", str(uuid4()))
2924 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2925 self
.logger
.debug(logging_text
+ "Enter")
2927 action
= list(action_dict
.keys())[0]
2928 task_dict
= action_dict
.get(action
)
2929 vim_vm_id
= action_dict
.get(action
).get("vim_vm_id")
2931 if action_dict
.get("stop"):
2935 step
= "lock the operation & do task creation"
2936 with self
.write_lock
:
2937 extra_dict
["params"] = {
2938 "vim_vm_id": vim_vm_id
,
2941 task
= self
.rebuild_start_stop_task(
2942 task_dict
["vdu_id"],
2943 task_dict
["vnf_id"],
2944 task_dict
["vdu_index"],
2948 task_dict
["target_vim"],
2951 db_new_tasks
.append(task
)
2952 step
= "upload Task to db"
2953 self
.upload_all_tasks(
2954 db_new_tasks
=db_new_tasks
,
2958 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2961 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2965 except Exception as e
:
2966 if isinstance(e
, (DbException
, NsException
)):
2968 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2971 e
= traceback_format_exc()
2972 self
.logger
.critical(
2973 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2976 raise NsException(e
)
2978 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2979 nsrs
= self
.db
.get_list("nsrs", {})
2983 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
2985 return return_data
, None, True
2987 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2988 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2991 for ro_task
in ro_tasks
:
2992 for task
in ro_task
["tasks"]:
2993 if task
["action_id"] not in return_data
:
2994 return_data
.append(task
["action_id"])
2996 return return_data
, None, True
2999 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
3001 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
3002 self
._assign
_vim
(target_vim
)
3003 target_record
= "vnfrs:{}:vdur.{}.vim_info.{}".format(
3004 vnf
["_id"], vdu_index
, target_vim
3006 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
3008 "action_id": action_id
,
3010 "task_index": task_index
,
3013 task
= Ns
._create
_task
(
3014 deployment_info
=deployment_info
,
3015 target_id
=target_vim
,
3018 target_record
=target_record
,
3019 target_record_id
=target_record_id
,
3020 extra_dict
=extra_dict
,
3025 def migrate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3029 action_id
= indata
.get("action_id", str(uuid4()))
3031 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
3032 self
.logger
.debug(logging_text
+ "Enter")
3034 vnf_instance_id
= indata
["vnfInstanceId"]
3035 step
= "Getting vnfrs from db"
3036 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
3037 vdu
= indata
.get("vdu")
3038 migrateToHost
= indata
.get("migrateToHost")
3041 with self
.write_lock
:
3043 vdu_id
= indata
["vdu"]["vduId"]
3044 vdu_count_index
= indata
["vdu"].get("vduCountIndex", 0)
3045 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3047 vdu
["vdu-id-ref"] == vdu_id
3048 and vdu
["count-index"] == vdu_count_index
3050 extra_dict
["params"] = {
3051 "vim_vm_id": vdu
["vim-id"],
3052 "migrate_host": migrateToHost
,
3053 "vdu_vim_info": vdu
["vim_info"],
3055 step
= "Creating migration task for vdu:{}".format(vdu
)
3056 task
= self
.migrate_task(
3065 db_new_tasks
.append(task
)
3069 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3070 extra_dict
["params"] = {
3071 "vim_vm_id": vdu
["vim-id"],
3072 "migrate_host": migrateToHost
,
3073 "vdu_vim_info": vdu
["vim_info"],
3075 step
= "Creating migration task for vdu:{}".format(vdu
)
3076 task
= self
.migrate_task(
3085 db_new_tasks
.append(task
)
3088 self
.upload_all_tasks(
3089 db_new_tasks
=db_new_tasks
,
3094 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3097 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3101 except Exception as e
:
3102 if isinstance(e
, (DbException
, NsException
)):
3104 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3107 e
= traceback_format_exc()
3108 self
.logger
.critical(
3109 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3112 raise NsException(e
)
3114 def verticalscale_task(
3115 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
3117 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
3118 self
._assign
_vim
(target_vim
)
3119 target_record
= "vnfrs:{}:vdur.{}.vim_info.{}".format(
3120 vnf
["_id"], vdu_index
, target_vim
3122 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
3124 "action_id": action_id
,
3126 "task_index": task_index
,
3129 task
= Ns
._create
_task
(
3130 deployment_info
=deployment_info
,
3131 target_id
=target_vim
,
3132 item
="verticalscale",
3134 target_record
=target_record
,
3135 target_record_id
=target_record_id
,
3136 extra_dict
=extra_dict
,
3140 def verticalscale(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3144 action_id
= indata
.get("action_id", str(uuid4()))
3146 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
3147 self
.logger
.debug(logging_text
+ "Enter")
3149 VnfFlavorData
= indata
.get("changeVnfFlavorData")
3150 vnf_instance_id
= VnfFlavorData
["vnfInstanceId"]
3151 step
= "Getting vnfrs from db"
3152 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
3153 vduid
= VnfFlavorData
["additionalParams"]["vduid"]
3154 vduCountIndex
= VnfFlavorData
["additionalParams"]["vduCountIndex"]
3155 virtualMemory
= VnfFlavorData
["additionalParams"]["virtualMemory"]
3156 numVirtualCpu
= VnfFlavorData
["additionalParams"]["numVirtualCpu"]
3157 sizeOfStorage
= VnfFlavorData
["additionalParams"]["sizeOfStorage"]
3159 "name": vduid
+ "-flv",
3160 "ram": virtualMemory
,
3161 "vcpus": numVirtualCpu
,
3162 "disk": sizeOfStorage
,
3165 step
= "Creating Tasks for vertical scaling"
3166 with self
.write_lock
:
3167 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3169 vdu
["vdu-id-ref"] == vduid
3170 and vdu
["count-index"] == vduCountIndex
3172 extra_dict
["params"] = {
3173 "vim_vm_id": vdu
["vim-id"],
3174 "flavor_dict": flavor_dict
,
3176 task
= self
.verticalscale_task(
3185 db_new_tasks
.append(task
)
3188 self
.upload_all_tasks(
3189 db_new_tasks
=db_new_tasks
,
3193 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3196 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3200 except Exception as e
:
3201 if isinstance(e
, (DbException
, NsException
)):
3203 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3206 e
= traceback_format_exc()
3207 self
.logger
.critical(
3208 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3211 raise NsException(e
)