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
,
126 "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group",
129 def init_db(self
, target_version
):
132 def start(self
, config
):
134 Connect to database, filesystem storage, and messaging
135 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
136 :param config: Configuration of db, storage, etc
140 self
.config
["process_id"] = get_process_id() # used for HA identity
141 self
.logger
= logging
.getLogger("ro.ns")
143 # check right version of common
144 if versiontuple(common_version
) < versiontuple(min_common_version
):
146 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
147 common_version
, min_common_version
153 if config
["database"]["driver"] == "mongo":
154 self
.db
= dbmongo
.DbMongo()
155 self
.db
.db_connect(config
["database"])
156 elif config
["database"]["driver"] == "memory":
157 self
.db
= dbmemory
.DbMemory()
158 self
.db
.db_connect(config
["database"])
161 "Invalid configuration param '{}' at '[database]':'driver'".format(
162 config
["database"]["driver"]
167 if config
["storage"]["driver"] == "local":
168 self
.fs
= fslocal
.FsLocal()
169 self
.fs
.fs_connect(config
["storage"])
170 elif config
["storage"]["driver"] == "mongo":
171 self
.fs
= fsmongo
.FsMongo()
172 self
.fs
.fs_connect(config
["storage"])
173 elif config
["storage"]["driver"] is None:
177 "Invalid configuration param '{}' at '[storage]':'driver'".format(
178 config
["storage"]["driver"]
183 if config
["message"]["driver"] == "local":
184 self
.msg
= msglocal
.MsgLocal()
185 self
.msg
.connect(config
["message"])
186 elif config
["message"]["driver"] == "kafka":
187 self
.msg
= msgkafka
.MsgKafka()
188 self
.msg
.connect(config
["message"])
191 "Invalid configuration param '{}' at '[message]':'driver'".format(
192 config
["message"]["driver"]
196 # TODO load workers to deal with exising database tasks
198 self
.write_lock
= Lock()
199 except (DbException
, FsException
, MsgException
) as e
:
200 raise NsException(str(e
), http_code
=e
.http_code
)
202 def get_assigned_vims(self
):
203 return list(self
.vims_assigned
.keys())
208 self
.db
.db_disconnect()
211 self
.fs
.fs_disconnect()
214 self
.msg
.disconnect()
216 self
.write_lock
= None
217 except (DbException
, FsException
, MsgException
) as e
:
218 raise NsException(str(e
), http_code
=e
.http_code
)
220 for worker
in self
.workers
:
221 worker
.insert_task(("terminate",))
223 def _create_worker(self
):
225 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
226 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
227 return the index of the assigned worker thread. Worker threads are storead at self.workers
229 # Look for a thread in idle status
233 for i
in range(len(self
.workers
))
234 if self
.workers
[i
] and self
.workers
[i
].idle
239 if worker_id
is not None:
240 # unset idle status to avoid race conditions
241 self
.workers
[worker_id
].idle
= False
243 worker_id
= len(self
.workers
)
245 if worker_id
< self
.config
["global"]["server.ns_threads"]:
246 # create a new worker
248 NsWorker(worker_id
, self
.config
, self
.plugins
, self
.db
)
250 self
.workers
[worker_id
].start()
252 # reached maximum number of threads, assign VIM to an existing one
253 worker_id
= self
.next_worker
254 self
.next_worker
= (self
.next_worker
+ 1) % self
.config
["global"][
260 def assign_vim(self
, target_id
):
261 with self
.write_lock
:
262 return self
._assign
_vim
(target_id
)
264 def _assign_vim(self
, target_id
):
265 if target_id
not in self
.vims_assigned
:
266 worker_id
= self
.vims_assigned
[target_id
] = self
._create
_worker
()
267 self
.workers
[worker_id
].insert_task(("load_vim", target_id
))
269 def reload_vim(self
, target_id
):
270 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
271 # this is because database VIM information is cached for threads working with SDN
272 with self
.write_lock
:
273 for worker
in self
.workers
:
274 if worker
and not worker
.idle
:
275 worker
.insert_task(("reload_vim", target_id
))
277 def unload_vim(self
, target_id
):
278 with self
.write_lock
:
279 return self
._unload
_vim
(target_id
)
281 def _unload_vim(self
, target_id
):
282 if target_id
in self
.vims_assigned
:
283 worker_id
= self
.vims_assigned
[target_id
]
284 self
.workers
[worker_id
].insert_task(("unload_vim", target_id
))
285 del self
.vims_assigned
[target_id
]
287 def check_vim(self
, target_id
):
288 with self
.write_lock
:
289 if target_id
in self
.vims_assigned
:
290 worker_id
= self
.vims_assigned
[target_id
]
292 worker_id
= self
._create
_worker
()
294 worker
= self
.workers
[worker_id
]
295 worker
.insert_task(("check_vim", target_id
))
297 def unload_unused_vims(self
):
298 with self
.write_lock
:
301 for target_id
in self
.vims_assigned
:
302 if not self
.db
.get_one(
305 "target_id": target_id
,
306 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
310 vims_to_unload
.append(target_id
)
312 for target_id
in vims_to_unload
:
313 self
._unload
_vim
(target_id
)
321 """This method reads cloud init from a file.
323 Note: Not used as cloud init content is provided in the http body.
326 db (Type[DbBase]): [description]
327 fs (Type[FsBase]): [description]
328 location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
331 NsException: [description]
332 NsException: [description]
337 vnfd_id
, _
, other
= location
.partition(":")
338 _type
, _
, name
= other
.partition(":")
339 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
342 base_folder
= vnfd
["_admin"]["storage"]
343 cloud_init_file
= "{}/{}/cloud_init/{}".format(
344 base_folder
["folder"], base_folder
["pkg-dir"], name
349 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
354 with fs
.file_open(cloud_init_file
, "r") as ci_file
:
355 cloud_init_content
= ci_file
.read()
357 cloud_init_content
= vnfd
["vdu"][int(name
)]["cloud-init"]
359 raise NsException("Mismatch descriptor for cloud init: {}".format(location
))
361 return cloud_init_content
365 cloud_init_content
: str,
366 params
: Dict
[str, Any
],
369 """Function that processes the cloud init to replace Jinja2 encoded parameters.
372 cloud_init_content (str): [description]
373 params (Dict[str, Any]): [description]
374 context (str): [description]
377 NsException: [description]
378 NsException: [description]
385 undefined
=StrictUndefined
,
386 autoescape
=select_autoescape(default_for_string
=True, default
=True),
388 template
= env
.from_string(cloud_init_content
)
390 return template
.render(params
or {})
391 except UndefinedError
as e
:
393 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
394 "inside the 'additionalParamsForVnf' block".format(e
, context
)
396 except (TemplateError
, TemplateNotFound
) as e
:
398 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
403 def _create_db_ro_nsrs(self
, nsr_id
, now
):
405 key
= rsa
.generate_private_key(
406 backend
=crypto_default_backend(), public_exponent
=65537, key_size
=2048
408 private_key
= key
.private_bytes(
409 crypto_serialization
.Encoding
.PEM
,
410 crypto_serialization
.PrivateFormat
.PKCS8
,
411 crypto_serialization
.NoEncryption(),
413 public_key
= key
.public_key().public_bytes(
414 crypto_serialization
.Encoding
.OpenSSH
,
415 crypto_serialization
.PublicFormat
.OpenSSH
,
417 private_key
= private_key
.decode("utf8")
418 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
419 i
= private_key
.find("\n")
420 private_key
= "-----BEGIN RSA PRIVATE KEY-----" + private_key
[i
:]
421 public_key
= public_key
.decode("utf8")
422 except Exception as e
:
423 raise NsException("Cannot create ssh-keys: {}".format(e
))
425 schema_version
= "1.1"
426 private_key_encrypted
= self
.db
.encrypt(
427 private_key
, schema_version
=schema_version
, salt
=nsr_id
434 "schema_version": schema_version
,
436 "public_key": public_key
,
437 "private_key": private_key_encrypted
,
440 self
.db
.create("ro_nsrs", db_content
)
446 deployment_info
: Dict
[str, Any
],
451 target_record_id
: str,
452 extra_dict
: Dict
[str, Any
] = None,
454 """Function to create task dict from deployment information.
457 deployment_info (Dict[str, Any]): [description]
458 target_id (str): [description]
459 item (str): [description]
460 action (str): [description]
461 target_record (str): [description]
462 target_record_id (str): [description]
463 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
466 Dict[str, Any]: [description]
469 "target_id": target_id
, # it will be removed before pushing at database
470 "action_id": deployment_info
.get("action_id"),
471 "nsr_id": deployment_info
.get("nsr_id"),
472 "task_id": f
"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
473 "status": "SCHEDULED",
476 "target_record": target_record
,
477 "target_record_id": target_record_id
,
481 task
.update(extra_dict
) # params, find_params, depends_on
483 deployment_info
["task_index"] = deployment_info
.get("task_index", 0) + 1
490 task
: Dict
[str, Any
],
492 """Function to create an RO task from task information.
495 target_id (str): [description]
496 task (Dict[str, Any]): [description]
499 Dict[str, Any]: [description]
503 _id
= task
.get("task_id")
508 "target_id": target_id
,
511 "created_items": None,
528 def _process_image_params(
529 target_image
: Dict
[str, Any
],
530 indata
: Dict
[str, Any
],
531 vim_info
: Dict
[str, Any
],
532 target_record_id
: str,
533 **kwargs
: Dict
[str, Any
],
535 """Function to process VDU image parameters.
538 target_image (Dict[str, Any]): [description]
539 indata (Dict[str, Any]): [description]
540 vim_info (Dict[str, Any]): [description]
541 target_record_id (str): [description]
544 Dict[str, Any]: [description]
548 if target_image
.get("image"):
549 find_params
["filter_dict"] = {"name": target_image
.get("image")}
551 if target_image
.get("vim_image_id"):
552 find_params
["filter_dict"] = {"id": target_image
.get("vim_image_id")}
554 if target_image
.get("image_checksum"):
555 find_params
["filter_dict"] = {
556 "checksum": target_image
.get("image_checksum")
559 return {"find_params": find_params
}
562 def _get_resource_allocation_params(
563 quota_descriptor
: Dict
[str, Any
],
565 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
569 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
572 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
576 if quota_descriptor
.get("limit"):
577 quota
["limit"] = int(quota_descriptor
["limit"])
579 if quota_descriptor
.get("reserve"):
580 quota
["reserve"] = int(quota_descriptor
["reserve"])
582 if quota_descriptor
.get("shares"):
583 quota
["shares"] = int(quota_descriptor
["shares"])
588 def _process_guest_epa_quota_params(
589 guest_epa_quota
: Dict
[str, Any
],
592 """Function to extract the guest epa quota parameters.
595 guest_epa_quota (Dict[str, Any]): [description]
596 epa_vcpu_set (bool): [description]
599 Dict[str, Any]: [description]
603 if guest_epa_quota
.get("cpu-quota") and not epa_vcpu_set
:
604 cpuquota
= Ns
._get
_resource
_allocation
_params
(
605 guest_epa_quota
.get("cpu-quota")
609 result
["cpu-quota"] = cpuquota
611 if guest_epa_quota
.get("mem-quota"):
612 vduquota
= Ns
._get
_resource
_allocation
_params
(
613 guest_epa_quota
.get("mem-quota")
617 result
["mem-quota"] = vduquota
619 if guest_epa_quota
.get("disk-io-quota"):
620 diskioquota
= Ns
._get
_resource
_allocation
_params
(
621 guest_epa_quota
.get("disk-io-quota")
625 result
["disk-io-quota"] = diskioquota
627 if guest_epa_quota
.get("vif-quota"):
628 vifquota
= Ns
._get
_resource
_allocation
_params
(
629 guest_epa_quota
.get("vif-quota")
633 result
["vif-quota"] = vifquota
638 def _process_guest_epa_numa_params(
639 guest_epa_quota
: Dict
[str, Any
],
640 ) -> Tuple
[Dict
[str, Any
], bool]:
644 guest_epa_quota (Dict[str, Any]): [description]
647 Tuple[Dict[str, Any], bool]: [description]
653 if guest_epa_quota
.get("numa-node-policy"):
654 numa_node_policy
= guest_epa_quota
.get("numa-node-policy")
656 if numa_node_policy
.get("node"):
657 for numa_node
in numa_node_policy
["node"]:
659 if numa_node
.get("id"):
660 numa
["id"] = int(numa_node
["id"])
662 if numa_node
.get("vcpu"):
663 for vcpu
in numa_node
.get("vcpu"):
664 vcpu_id
= int(vcpu
.get("id"))
665 vcpu_list
.append(vcpu_id
)
666 numa
["vcpu"] = vcpu_list
668 if numa_node
.get("num-cores"):
669 numa
["cores"] = numa_node
["num-cores"]
672 paired_threads
= numa_node
.get("paired-threads", {})
673 if paired_threads
.get("num-paired-threads"):
674 numa
["paired_threads"] = int(
675 numa_node
["paired-threads"]["num-paired-threads"]
679 if paired_threads
.get("paired-thread-ids"):
680 numa
["paired-threads-id"] = []
682 for pair
in paired_threads
["paired-thread-ids"]:
683 numa
["paired-threads-id"].append(
685 str(pair
["thread-a"]),
686 str(pair
["thread-b"]),
690 if numa_node
.get("num-threads"):
691 numa
["threads"] = int(numa_node
["num-threads"])
694 if numa_node
.get("memory-mb"):
695 numa
["memory"] = max(int(int(numa_node
["memory-mb"]) / 1024), 1)
697 numa_list
.append(numa
)
700 return numa_list
, epa_vcpu_set
703 def _process_guest_epa_cpu_pinning_params(
704 guest_epa_quota
: Dict
[str, Any
],
707 ) -> Tuple
[Dict
[str, Any
], bool]:
711 guest_epa_quota (Dict[str, Any]): [description]
712 vcpu_count (int): [description]
713 epa_vcpu_set (bool): [description]
716 Tuple[Dict[str, Any], bool]: [description]
719 local_epa_vcpu_set
= epa_vcpu_set
722 guest_epa_quota
.get("cpu-pinning-policy") == "DEDICATED"
725 # Pinning policy "REQUIRE" uses threads as host should support SMT architecture
726 # Pinning policy "ISOLATE" uses cores as host should not support SMT architecture
727 # Pinning policy "PREFER" uses threads in case host supports SMT architecture
730 if guest_epa_quota
.get("cpu-thread-pinning-policy") == "ISOLATE"
732 ] = max(vcpu_count
, 1)
733 local_epa_vcpu_set
= True
735 return numa
, local_epa_vcpu_set
738 def _process_epa_params(
739 target_flavor
: Dict
[str, Any
],
744 target_flavor (Dict[str, Any]): [description]
747 Dict[str, Any]: [description]
753 if target_flavor
.get("guest-epa"):
754 guest_epa
= target_flavor
["guest-epa"]
756 numa_list
, epa_vcpu_set
= Ns
._process
_guest
_epa
_numa
_params
(
757 guest_epa_quota
=guest_epa
760 if guest_epa
.get("mempage-size"):
761 extended
["mempage-size"] = guest_epa
.get("mempage-size")
763 if guest_epa
.get("cpu-pinning-policy"):
764 extended
["cpu-pinning-policy"] = guest_epa
.get("cpu-pinning-policy")
766 if guest_epa
.get("cpu-thread-pinning-policy"):
767 extended
["cpu-thread-pinning-policy"] = guest_epa
.get(
768 "cpu-thread-pinning-policy"
771 if guest_epa
.get("numa-node-policy"):
772 if guest_epa
.get("numa-node-policy").get("mem-policy"):
773 extended
["mem-policy"] = guest_epa
.get("numa-node-policy").get(
777 tmp_numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_cpu
_pinning
_params
(
778 guest_epa_quota
=guest_epa
,
779 vcpu_count
=int(target_flavor
.get("vcpu-count", 1)),
780 epa_vcpu_set
=epa_vcpu_set
,
782 for numa
in numa_list
:
783 numa
.update(tmp_numa
)
786 Ns
._process
_guest
_epa
_quota
_params
(
787 guest_epa_quota
=guest_epa
,
788 epa_vcpu_set
=epa_vcpu_set
,
793 extended
["numas"] = numa_list
798 def _process_flavor_params(
799 target_flavor
: Dict
[str, Any
],
800 indata
: Dict
[str, Any
],
801 vim_info
: Dict
[str, Any
],
802 target_record_id
: str,
803 **kwargs
: Dict
[str, Any
],
808 target_flavor (Dict[str, Any]): [description]
809 indata (Dict[str, Any]): [description]
810 vim_info (Dict[str, Any]): [description]
811 target_record_id (str): [description]
814 Dict[str, Any]: [description]
816 db
= kwargs
.get("db")
820 "disk": int(target_flavor
["storage-gb"]),
821 "ram": int(target_flavor
["memory-mb"]),
822 "vcpus": int(target_flavor
["vcpu-count"]),
825 for vnf
in indata
.get("vnf", []):
826 for vdur
in vnf
.get("vdur", []):
827 if vdur
.get("ns-flavor-id") == target_flavor
.get("id"):
830 if db
and isinstance(indata
.get("vnf"), list):
831 vnfd_id
= indata
.get("vnf")[0].get("vnfd-id")
832 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
833 # check if there is persistent root disk
834 for vdu
in vnfd
.get("vdu", ()):
835 if vdu
["name"] == target_vdur
.get("vdu-name"):
836 for vsd
in vnfd
.get("virtual-storage-desc", ()):
837 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
840 root_disk
.get("type-of-storage")
841 == "persistent-storage:persistent-storage"
843 flavor_data
["disk"] = 0
845 for storage
in target_vdur
.get("virtual-storages", []):
847 storage
.get("type-of-storage")
848 == "etsi-nfv-descriptors:ephemeral-storage"
850 flavor_data
["ephemeral"] = int(storage
.get("size-of-storage", 0))
851 elif storage
.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
852 flavor_data
["swap"] = int(storage
.get("size-of-storage", 0))
854 extended
= Ns
._process
_epa
_params
(target_flavor
)
856 flavor_data
["extended"] = extended
858 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
859 flavor_data_name
= flavor_data
.copy()
860 flavor_data_name
["name"] = target_flavor
["name"]
861 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
866 def _process_net_params(
867 target_vld
: Dict
[str, Any
],
868 indata
: Dict
[str, Any
],
869 vim_info
: Dict
[str, Any
],
870 target_record_id
: str,
871 **kwargs
: Dict
[str, Any
],
873 """Function to process network parameters.
876 target_vld (Dict[str, Any]): [description]
877 indata (Dict[str, Any]): [description]
878 vim_info (Dict[str, Any]): [description]
879 target_record_id (str): [description]
882 Dict[str, Any]: [description]
886 if vim_info
.get("sdn"):
887 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
888 # ns_preffix = "nsrs:{}".format(nsr_id)
889 # remove the ending ".sdn
890 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
891 extra_dict
["params"] = {
893 for k
in ("sdn-ports", "target_vim", "vlds", "type")
897 # TODO needed to add target_id in the dependency.
898 if vim_info
.get("target_vim"):
899 extra_dict
["depends_on"] = [
900 f
"{vim_info.get('target_vim')} {vld_target_record_id}"
905 if vim_info
.get("vim_network_name"):
906 extra_dict
["find_params"] = {
908 "name": vim_info
.get("vim_network_name"),
911 elif vim_info
.get("vim_network_id"):
912 extra_dict
["find_params"] = {
914 "id": vim_info
.get("vim_network_id"),
917 elif target_vld
.get("mgmt-network") and not vim_info
.get("provider_network"):
918 extra_dict
["find_params"] = {
920 "name": target_vld
["id"],
924 extra_dict
["params"] = {
926 f
"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
928 "ip_profile": vim_info
.get("ip_profile"),
929 "provider_network_profile": vim_info
.get("provider_network"),
932 if not target_vld
.get("underlay"):
933 extra_dict
["params"]["net_type"] = "bridge"
935 extra_dict
["params"]["net_type"] = (
936 "ptp" if target_vld
.get("type") == "ELINE" else "data"
942 def find_persistent_root_volumes(
945 vdu_instantiation_volumes_list
: list,
948 """Find the persistent root volumes and add them to the disk_list
949 by parsing the instantiation parameters.
952 vnfd (dict): VNF descriptor
953 target_vdu (dict): processed VDU
954 vdu_instantiation_volumes_list (list): instantiation parameters for the each VDU as a list
955 disk_list (list): to be filled up
958 persistent_root_disk (dict): Details of persistent root disk
961 persistent_root_disk
= {}
962 # There can be only one root disk, when we find it, it will return the result
964 for vdu
, vsd
in product(
965 vnfd
.get("vdu", ()), vnfd
.get("virtual-storage-desc", ())
968 vdu
["name"] == target_vdu
["vdu-name"]
969 and vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]
973 root_disk
.get("type-of-storage")
974 == "persistent-storage:persistent-storage"
976 for vdu_volume
in vdu_instantiation_volumes_list
:
978 vdu_volume
["vim-volume-id"]
979 and root_disk
["id"] == vdu_volume
["name"]
981 persistent_root_disk
[vsd
["id"]] = {
982 "vim_volume_id": vdu_volume
["vim-volume-id"],
983 "image_id": vdu
.get("sw-image-desc"),
986 disk_list
.append(persistent_root_disk
[vsd
["id"]])
988 return persistent_root_disk
991 if root_disk
.get("size-of-storage"):
992 persistent_root_disk
[vsd
["id"]] = {
993 "image_id": vdu
.get("sw-image-desc"),
994 "size": root_disk
.get("size-of-storage"),
995 "keep": Ns
.is_volume_keeping_required(root_disk
),
998 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1000 return persistent_root_disk
1003 def find_persistent_volumes(
1004 persistent_root_disk
: dict,
1006 vdu_instantiation_volumes_list
: list,
1009 """Find the ordinary persistent volumes and add them to the disk_list
1010 by parsing the instantiation parameters.
1013 persistent_root_disk: persistent root disk dictionary
1014 target_vdu: processed VDU
1015 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1016 disk_list: to be filled up
1019 # Find the ordinary volumes which are not added to the persistent_root_disk
1020 persistent_disk
= {}
1021 for disk
in target_vdu
.get("virtual-storages", {}):
1023 disk
.get("type-of-storage") == "persistent-storage:persistent-storage"
1024 and disk
["id"] not in persistent_root_disk
.keys()
1026 for vdu_volume
in vdu_instantiation_volumes_list
:
1027 if vdu_volume
["vim-volume-id"] and disk
["id"] == vdu_volume
["name"]:
1028 persistent_disk
[disk
["id"]] = {
1029 "vim_volume_id": vdu_volume
["vim-volume-id"],
1031 disk_list
.append(persistent_disk
[disk
["id"]])
1034 if disk
["id"] not in persistent_disk
.keys():
1035 persistent_disk
[disk
["id"]] = {
1036 "size": disk
.get("size-of-storage"),
1037 "keep": Ns
.is_volume_keeping_required(disk
),
1039 disk_list
.append(persistent_disk
[disk
["id"]])
1042 def is_volume_keeping_required(virtual_storage_desc
: Dict
[str, Any
]) -> bool:
1043 """Function to decide keeping persistent volume
1047 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1053 if not virtual_storage_desc
.get("vdu-storage-requirements"):
1055 for item
in virtual_storage_desc
.get("vdu-storage-requirements", {}):
1056 if item
.get("key") == "keep-volume" and item
.get("value") == "true":
1061 def _sort_vdu_interfaces(target_vdu
: dict) -> None:
1062 """Sort the interfaces according to position number.
1065 target_vdu (dict): Details of VDU to be created
1068 # If the position info is provided for all the interfaces, it will be sorted
1069 # according to position number ascendingly.
1070 sorted_interfaces
= sorted(
1071 target_vdu
["interfaces"],
1072 key
=lambda x
: (x
.get("position") is None, x
.get("position")),
1074 target_vdu
["interfaces"] = sorted_interfaces
1077 def _partially_locate_vdu_interfaces(target_vdu
: dict) -> None:
1078 """Only place the interfaces which has specific position.
1081 target_vdu (dict): Details of VDU to be created
1084 # If the position info is provided for some interfaces but not all of them, the interfaces
1085 # which has specific position numbers will be placed and others' positions will not be taken care.
1087 i
.get("position") + 1
1088 for i
in target_vdu
["interfaces"]
1089 if i
.get("position") is not None
1091 n
= len(target_vdu
["interfaces"])
1092 sorted_interfaces
= [-1] * n
1096 if target_vdu
["interfaces"][k
].get("position") is not None:
1097 if any(i
.get("position") == 0 for i
in target_vdu
["interfaces"]):
1098 idx
= target_vdu
["interfaces"][k
]["position"] + 1
1100 idx
= target_vdu
["interfaces"][k
]["position"]
1101 sorted_interfaces
[idx
- 1] = target_vdu
["interfaces"][k
]
1105 if target_vdu
["interfaces"][m
].get("position") is None:
1106 idy
= sorted_interfaces
.index(-1)
1107 sorted_interfaces
[idy
] = target_vdu
["interfaces"][m
]
1110 target_vdu
["interfaces"] = sorted_interfaces
1113 def _prepare_vdu_cloud_init(
1114 target_vdu
: dict, vdu2cloud_init
: dict, db
: object, fs
: object
1116 """Fill cloud_config dict with cloud init details.
1119 target_vdu (dict): Details of VDU to be created
1120 vdu2cloud_init (dict): Cloud init dict
1121 db (object): DB object
1122 fs (object): FS object
1125 cloud_config (dict): Cloud config details of VDU
1131 if target_vdu
.get("cloud-init"):
1132 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1133 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1136 location
=target_vdu
["cloud-init"],
1139 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1140 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1141 cloud_init_content
=cloud_content_
,
1142 params
=target_vdu
.get("additionalParams"),
1143 context
=target_vdu
["cloud-init"],
1146 if target_vdu
.get("boot-data-drive"):
1147 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1152 def _check_vld_information_of_interfaces(
1153 interface
: dict, ns_preffix
: str, vnf_preffix
: str
1155 """Prepare the net_text by the virtual link information for vnf and ns level.
1157 interface (dict): Interface details
1158 ns_preffix (str): Prefix of NS
1159 vnf_preffix (str): Prefix of VNF
1162 net_text (str): information of net
1166 if interface
.get("ns-vld-id"):
1167 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
1168 elif interface
.get("vnf-vld-id"):
1169 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
1174 def _prepare_interface_port_security(interface
: dict) -> None:
1178 interface (dict): Interface details
1181 if "port-security-enabled" in interface
:
1182 interface
["port_security"] = interface
.pop("port-security-enabled")
1184 if "port-security-disable-strategy" in interface
:
1185 interface
["port_security_disable_strategy"] = interface
.pop(
1186 "port-security-disable-strategy"
1190 def _create_net_item_of_interface(interface
: dict, net_text
: str) -> dict:
1191 """Prepare net item including name, port security, floating ip etc.
1194 interface (dict): Interface details
1195 net_text (str): information of net
1198 net_item (dict): Dict including net details
1204 for x
, v
in interface
.items()
1210 "port_security_disable_strategy",
1214 net_item
["net_id"] = "TASK-" + net_text
1215 net_item
["type"] = "virtual"
1220 def _prepare_type_of_interface(
1221 interface
: dict, tasks_by_target_record_id
: dict, net_text
: str, net_item
: dict
1223 """Fill the net item type by interface type such as SR-IOV, OM-MGMT, bridge etc.
1226 interface (dict): Interface details
1227 tasks_by_target_record_id (dict): Task details
1228 net_text (str): information of net
1229 net_item (dict): Dict including net details
1232 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1233 # TODO floating_ip: True/False (or it can be None)
1235 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1236 # Mark the net create task as type data
1238 tasks_by_target_record_id
,
1244 tasks_by_target_record_id
[net_text
]["extra_dict"]["params"][
1248 net_item
["use"] = "data"
1249 net_item
["model"] = interface
["type"]
1250 net_item
["type"] = interface
["type"]
1253 interface
.get("type") == "OM-MGMT"
1254 or interface
.get("mgmt-interface")
1255 or interface
.get("mgmt-vnf")
1257 net_item
["use"] = "mgmt"
1260 # If interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1261 net_item
["use"] = "bridge"
1262 net_item
["model"] = interface
.get("type")
1265 def _prepare_vdu_interfaces(
1271 tasks_by_target_record_id
: dict,
1274 """Prepare the net_item and add net_list, add mgmt interface to extra_dict.
1277 target_vdu (dict): VDU to be created
1278 extra_dict (dict): Dictionary to be filled
1279 ns_preffix (str): NS prefix as string
1280 vnf_preffix (str): VNF prefix as string
1281 logger (object): Logger Object
1282 tasks_by_target_record_id (dict): Task details
1283 net_list (list): Net list of VDU
1285 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
1286 net_text
= Ns
._check
_vld
_information
_of
_interfaces
(
1287 interface
, ns_preffix
, vnf_preffix
1290 # Interface not connected to any vld
1292 "Interface {} from vdu {} not connected to any vld".format(
1293 iface_index
, target_vdu
["vdu-name"]
1298 extra_dict
["depends_on"].append(net_text
)
1300 Ns
._prepare
_interface
_port
_security
(interface
)
1302 net_item
= Ns
._create
_net
_item
_of
_interface
(interface
, net_text
)
1304 Ns
._prepare
_type
_of
_interface
(
1305 interface
, tasks_by_target_record_id
, net_text
, net_item
1308 if interface
.get("ip-address"):
1309 net_item
["ip_address"] = interface
["ip-address"]
1311 if interface
.get("mac-address"):
1312 net_item
["mac_address"] = interface
["mac-address"]
1314 net_list
.append(net_item
)
1316 if interface
.get("mgmt-vnf"):
1317 extra_dict
["mgmt_vnf_interface"] = iface_index
1318 elif interface
.get("mgmt-interface"):
1319 extra_dict
["mgmt_vdu_interface"] = iface_index
1322 def _prepare_vdu_ssh_keys(
1323 target_vdu
: dict, ro_nsr_public_key
: dict, cloud_config
: dict
1325 """Add ssh keys to cloud config.
1328 target_vdu (dict): Details of VDU to be created
1329 ro_nsr_public_key (dict): RO NSR public Key
1330 cloud_config (dict): Cloud config details
1335 if target_vdu
.get("ssh-keys"):
1336 ssh_keys
+= target_vdu
.get("ssh-keys")
1338 if target_vdu
.get("ssh-access-required"):
1339 ssh_keys
.append(ro_nsr_public_key
)
1342 cloud_config
["key-pairs"] = ssh_keys
1345 def _select_persistent_root_disk(vsd
: dict, vdu
: dict) -> dict:
1346 """Selects the persistent root disk if exists.
1348 vsd (dict): Virtual storage descriptors in VNFD
1349 vdu (dict): VNF descriptor
1352 root_disk (dict): Selected persistent root disk
1354 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
1358 ) == "persistent-storage:persistent-storage" and root_disk
.get(
1364 def _add_persistent_root_disk_to_disk_list(
1365 vnfd
: dict, target_vdu
: dict, persistent_root_disk
: dict, disk_list
: list
1367 """Find the persistent root disk and add to disk list.
1370 vnfd (dict): VNF descriptor
1371 target_vdu (dict): Details of VDU to be created
1372 persistent_root_disk (dict): Details of persistent root disk
1373 disk_list (list): Disks of VDU
1376 for vdu
in vnfd
.get("vdu", ()):
1377 if vdu
["name"] == target_vdu
["vdu-name"]:
1378 for vsd
in vnfd
.get("virtual-storage-desc", ()):
1379 root_disk
= Ns
._select
_persistent
_root
_disk
(vsd
, vdu
)
1383 persistent_root_disk
[vsd
["id"]] = {
1384 "image_id": vdu
.get("sw-image-desc"),
1385 "size": root_disk
["size-of-storage"],
1386 "keep": Ns
.is_volume_keeping_required(root_disk
),
1389 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1393 def _add_persistent_ordinary_disks_to_disk_list(
1395 persistent_root_disk
: dict,
1396 persistent_ordinary_disk
: dict,
1399 """Fill the disk list by adding persistent ordinary disks.
1402 target_vdu (dict): Details of VDU to be created
1403 persistent_root_disk (dict): Details of persistent root disk
1404 persistent_ordinary_disk (dict): Details of persistent ordinary disk
1405 disk_list (list): Disks of VDU
1408 if target_vdu
.get("virtual-storages"):
1409 for disk
in target_vdu
["virtual-storages"]:
1411 disk
.get("type-of-storage")
1412 == "persistent-storage:persistent-storage"
1413 and disk
["id"] not in persistent_root_disk
.keys()
1415 persistent_ordinary_disk
[disk
["id"]] = {
1416 "size": disk
["size-of-storage"],
1417 "keep": Ns
.is_volume_keeping_required(disk
),
1419 disk_list
.append(persistent_ordinary_disk
[disk
["id"]])
1422 def _prepare_vdu_affinity_group_list(
1423 target_vdu
: dict, extra_dict
: dict, ns_preffix
: str
1424 ) -> List
[Dict
[str, any
]]:
1425 """Process affinity group details to prepare affinity group list.
1428 target_vdu (dict): Details of VDU to be created
1429 extra_dict (dict): Dictionary to be filled
1430 ns_preffix (str): Prefix as string
1434 affinity_group_list (list): Affinity group details
1437 affinity_group_list
= []
1439 if target_vdu
.get("affinity-or-anti-affinity-group-id"):
1440 for affinity_group_id
in target_vdu
["affinity-or-anti-affinity-group-id"]:
1442 affinity_group_text
= (
1443 ns_preffix
+ ":affinity-or-anti-affinity-group." + affinity_group_id
1446 if not isinstance(extra_dict
.get("depends_on"), list):
1447 raise NsException("Invalid extra_dict format.")
1449 extra_dict
["depends_on"].append(affinity_group_text
)
1450 affinity_group
["affinity_group_id"] = "TASK-" + affinity_group_text
1451 affinity_group_list
.append(affinity_group
)
1453 return affinity_group_list
1456 def _process_vdu_params(
1457 target_vdu
: Dict
[str, Any
],
1458 indata
: Dict
[str, Any
],
1459 vim_info
: Dict
[str, Any
],
1460 target_record_id
: str,
1461 **kwargs
: Dict
[str, Any
],
1462 ) -> Dict
[str, Any
]:
1463 """Function to process VDU parameters.
1466 target_vdu (Dict[str, Any]): [description]
1467 indata (Dict[str, Any]): [description]
1468 vim_info (Dict[str, Any]): [description]
1469 target_record_id (str): [description]
1472 Dict[str, Any]: [description]
1474 vnfr_id
= kwargs
.get("vnfr_id")
1475 nsr_id
= kwargs
.get("nsr_id")
1476 vnfr
= kwargs
.get("vnfr")
1477 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1478 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
1479 logger
= kwargs
.get("logger")
1480 db
= kwargs
.get("db")
1481 fs
= kwargs
.get("fs")
1482 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1484 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
1485 ns_preffix
= "nsrs:{}".format(nsr_id
)
1486 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
1487 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
1488 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
1491 persistent_root_disk
= {}
1492 persistent_ordinary_disk
= {}
1493 vdu_instantiation_volumes_list
= []
1495 vnfd_id
= vnfr
["vnfd-id"]
1496 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
1498 # If the position info is provided for all the interfaces, it will be sorted
1499 # according to position number ascendingly.
1501 True if i
.get("position") is not None else False
1502 for i
in target_vdu
["interfaces"]
1504 Ns
._sort
_vdu
_interfaces
(target_vdu
)
1506 # If the position info is provided for some interfaces but not all of them, the interfaces
1507 # which has specific position numbers will be placed and others' positions will not be taken care.
1509 Ns
._partially
_locate
_vdu
_interfaces
(target_vdu
)
1511 # If the position info is not provided for the interfaces, interfaces will be attached
1512 # according to the order in the VNFD.
1513 Ns
._prepare
_vdu
_interfaces
(
1519 tasks_by_target_record_id
,
1524 cloud_config
= Ns
._prepare
_vdu
_cloud
_init
(target_vdu
, vdu2cloud_init
, db
, fs
)
1526 # Prepare VDU ssh keys
1527 Ns
._prepare
_vdu
_ssh
_keys
(target_vdu
, ro_nsr_public_key
, cloud_config
)
1529 if target_vdu
.get("additionalParams"):
1530 vdu_instantiation_volumes_list
= (
1531 target_vdu
.get("additionalParams").get("OSM").get("vdu_volumes")
1534 if vdu_instantiation_volumes_list
:
1535 # Find the root volumes and add to the disk_list
1536 persistent_root_disk
= Ns
.find_persistent_root_volumes(
1537 vnfd
, target_vdu
, vdu_instantiation_volumes_list
, disk_list
1540 # Find the ordinary volumes which are not added to the persistent_root_disk
1541 # and put them to the disk list
1542 Ns
.find_persistent_volumes(
1543 persistent_root_disk
,
1545 vdu_instantiation_volumes_list
,
1550 # Vdu_instantiation_volumes_list is empty
1551 # First get add the persistent root disks to disk_list
1552 Ns
._add
_persistent
_root
_disk
_to
_disk
_list
(
1553 vnfd
, target_vdu
, persistent_root_disk
, disk_list
1555 # Add the persistent non-root disks to disk_list
1556 Ns
._add
_persistent
_ordinary
_disks
_to
_disk
_list
(
1557 target_vdu
, persistent_root_disk
, persistent_ordinary_disk
, disk_list
1560 affinity_group_list
= Ns
._prepare
_vdu
_affinity
_group
_list
(
1561 target_vdu
, extra_dict
, ns_preffix
1564 extra_dict
["params"] = {
1565 "name": "{}-{}-{}-{}".format(
1566 indata
["name"][:16],
1567 vnfr
["member-vnf-index-ref"][:16],
1568 target_vdu
["vdu-name"][:32],
1569 target_vdu
.get("count-index") or 0,
1571 "description": target_vdu
["vdu-name"],
1573 "image_id": "TASK-" + image_text
,
1574 "flavor_id": "TASK-" + flavor_text
,
1575 "affinity_group_list": affinity_group_list
,
1576 "net_list": net_list
,
1577 "cloud_config": cloud_config
or None,
1578 "disk_list": disk_list
,
1579 "availability_zone_index": None, # TODO
1580 "availability_zone_list": None, # TODO
1586 def _process_affinity_group_params(
1587 target_affinity_group
: Dict
[str, Any
],
1588 indata
: Dict
[str, Any
],
1589 vim_info
: Dict
[str, Any
],
1590 target_record_id
: str,
1591 **kwargs
: Dict
[str, Any
],
1592 ) -> Dict
[str, Any
]:
1593 """Get affinity or anti-affinity group parameters.
1596 target_affinity_group (Dict[str, Any]): [description]
1597 indata (Dict[str, Any]): [description]
1598 vim_info (Dict[str, Any]): [description]
1599 target_record_id (str): [description]
1602 Dict[str, Any]: [description]
1606 affinity_group_data
= {
1607 "name": target_affinity_group
["name"],
1608 "type": target_affinity_group
["type"],
1609 "scope": target_affinity_group
["scope"],
1612 if target_affinity_group
.get("vim-affinity-group-id"):
1613 affinity_group_data
["vim-affinity-group-id"] = target_affinity_group
[
1614 "vim-affinity-group-id"
1617 extra_dict
["params"] = {
1618 "affinity_group_data": affinity_group_data
,
1624 def _process_recreate_vdu_params(
1625 existing_vdu
: Dict
[str, Any
],
1626 db_nsr
: Dict
[str, Any
],
1627 vim_info
: Dict
[str, Any
],
1628 target_record_id
: str,
1630 **kwargs
: Dict
[str, Any
],
1631 ) -> Dict
[str, Any
]:
1632 """Function to process VDU parameters to recreate.
1635 existing_vdu (Dict[str, Any]): [description]
1636 db_nsr (Dict[str, Any]): [description]
1637 vim_info (Dict[str, Any]): [description]
1638 target_record_id (str): [description]
1639 target_id (str): [description]
1642 Dict[str, Any]: [description]
1644 vnfr
= kwargs
.get("vnfr")
1645 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1646 # logger = kwargs.get("logger")
1647 db
= kwargs
.get("db")
1648 fs
= kwargs
.get("fs")
1649 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1655 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
1656 if vim_details_text
:
1657 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
1659 for iface_index
, interface
in enumerate(existing_vdu
["interfaces"]):
1660 if "port-security-enabled" in interface
:
1661 interface
["port_security"] = interface
.pop("port-security-enabled")
1663 if "port-security-disable-strategy" in interface
:
1664 interface
["port_security_disable_strategy"] = interface
.pop(
1665 "port-security-disable-strategy"
1670 for x
, v
in interface
.items()
1676 "port_security_disable_strategy",
1680 existing_ifaces
= existing_vdu
["vim_info"][target_id
].get(
1681 "interfaces_backup", []
1686 for i
in existing_ifaces
1687 if i
["ip_address"] == interface
["ip-address"]
1692 net_item
["net_id"] = net_id
1693 net_item
["type"] = "virtual"
1695 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1696 # TODO floating_ip: True/False (or it can be None)
1697 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1698 net_item
["use"] = "data"
1699 net_item
["model"] = interface
["type"]
1700 net_item
["type"] = interface
["type"]
1702 interface
.get("type") == "OM-MGMT"
1703 or interface
.get("mgmt-interface")
1704 or interface
.get("mgmt-vnf")
1706 net_item
["use"] = "mgmt"
1708 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1709 net_item
["use"] = "bridge"
1710 net_item
["model"] = interface
.get("type")
1712 if interface
.get("ip-address"):
1713 net_item
["ip_address"] = interface
["ip-address"]
1715 if interface
.get("mac-address"):
1716 net_item
["mac_address"] = interface
["mac-address"]
1718 net_list
.append(net_item
)
1720 if interface
.get("mgmt-vnf"):
1721 extra_dict
["mgmt_vnf_interface"] = iface_index
1722 elif interface
.get("mgmt-interface"):
1723 extra_dict
["mgmt_vdu_interface"] = iface_index
1728 if existing_vdu
.get("cloud-init"):
1729 if existing_vdu
["cloud-init"] not in vdu2cloud_init
:
1730 vdu2cloud_init
[existing_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1733 location
=existing_vdu
["cloud-init"],
1736 cloud_content_
= vdu2cloud_init
[existing_vdu
["cloud-init"]]
1737 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1738 cloud_init_content
=cloud_content_
,
1739 params
=existing_vdu
.get("additionalParams"),
1740 context
=existing_vdu
["cloud-init"],
1743 if existing_vdu
.get("boot-data-drive"):
1744 cloud_config
["boot-data-drive"] = existing_vdu
.get("boot-data-drive")
1748 if existing_vdu
.get("ssh-keys"):
1749 ssh_keys
+= existing_vdu
.get("ssh-keys")
1751 if existing_vdu
.get("ssh-access-required"):
1752 ssh_keys
.append(ro_nsr_public_key
)
1755 cloud_config
["key-pairs"] = ssh_keys
1758 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
1759 disk_list
.append({"vim_id": vol_id
["id"]})
1761 affinity_group_list
= []
1763 if existing_vdu
.get("affinity-or-anti-affinity-group-id"):
1765 for affinity_group_id
in existing_vdu
["affinity-or-anti-affinity-group-id"]:
1766 for group
in db_nsr
.get("affinity-or-anti-affinity-group"):
1768 group
["id"] == affinity_group_id
1769 and group
["vim_info"][target_id
].get("vim_id", None) is not None
1771 affinity_group
["affinity_group_id"] = group
["vim_info"][
1773 ].get("vim_id", None)
1774 affinity_group_list
.append(affinity_group
)
1776 extra_dict
["params"] = {
1777 "name": "{}-{}-{}-{}".format(
1778 db_nsr
["name"][:16],
1779 vnfr
["member-vnf-index-ref"][:16],
1780 existing_vdu
["vdu-name"][:32],
1781 existing_vdu
.get("count-index") or 0,
1783 "description": existing_vdu
["vdu-name"],
1785 "image_id": vim_details
["image"]["id"],
1786 "flavor_id": vim_details
["flavor"]["id"],
1787 "affinity_group_list": affinity_group_list
,
1788 "net_list": net_list
,
1789 "cloud_config": cloud_config
or None,
1790 "disk_list": disk_list
,
1791 "availability_zone_index": None, # TODO
1792 "availability_zone_list": None, # TODO
1797 def calculate_diff_items(
1804 tasks_by_target_record_id
,
1811 """Function that returns the incremental changes (creation, deletion)
1812 related to a specific item `item` to be done. This function should be
1813 called for NS instantiation, NS termination, NS update to add a new VNF
1814 or a new VLD, remove a VNF or VLD, etc.
1815 Item can be `net`, `flavor`, `image` or `vdu`.
1816 It takes a list of target items from indata (which came from the REST API)
1817 and compares with the existing items from db_ro_nsr, identifying the
1818 incremental changes to be done. During the comparison, it calls the method
1819 `process_params` (which was passed as parameter, and is particular for each
1823 indata (Dict[str, Any]): deployment info
1824 db_nsr: NSR record from DB
1825 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1826 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1827 item (str): element to process (net, vdu...)
1828 tasks_by_target_record_id (Dict[str, Any]):
1829 [<target_record_id>, <task>]
1830 action_id (str): action id
1831 nsr_id (str): NSR id
1832 task_index (number): task index to add to task name
1833 vnfr_id (str): VNFR id
1834 vnfr (Dict[str, Any]): VNFR info
1837 List: list with the incremental changes (deletes, creates) for each item
1838 number: current task index
1846 process_params
= None
1847 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1848 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1850 # According to the type of item, the path, the target_list,
1851 # the existing_list and the method to process params are set
1852 db_path
= self
.db_path_map
[item
]
1853 process_params
= self
.process_params_function_map
[item
]
1854 if item
in ("net", "vdu"):
1855 # This case is specific for the NS VLD (not applied to VDU)
1857 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1858 target_list
= indata
.get("ns", []).get(db_path
, [])
1859 existing_list
= db_nsr
.get(db_path
, [])
1860 # This case is common for VNF VLDs and VNF VDUs
1862 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
1864 (vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
),
1867 target_list
= target_vnf
.get(db_path
, []) if target_vnf
else []
1868 existing_list
= vnfr
.get(db_path
, [])
1869 elif item
in ("image", "flavor", "affinity-or-anti-affinity-group"):
1870 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1871 target_list
= indata
.get(item
, [])
1872 existing_list
= db_nsr
.get(item
, [])
1874 raise NsException("Item not supported: {}", item
)
1876 # ensure all the target_list elements has an "id". If not assign the index as id
1877 if target_list
is None:
1879 for target_index
, tl
in enumerate(target_list
):
1880 if tl
and not tl
.get("id"):
1881 tl
["id"] = str(target_index
)
1883 # step 1 items (networks,vdus,...) to be deleted/updated
1884 for item_index
, existing_item
in enumerate(existing_list
):
1886 (t
for t
in target_list
if t
["id"] == existing_item
["id"]),
1890 for target_vim
, existing_viminfo
in existing_item
.get(
1893 if existing_viminfo
is None:
1897 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
1899 target_viminfo
= None
1901 if target_viminfo
is None:
1903 self
._assign
_vim
(target_vim
)
1904 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
1907 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
1908 # item must be sdn-net instead of net if target_vim is a sdn
1910 target_record_id
+= ".sdn"
1913 "action_id": action_id
,
1915 "task_index": task_index
,
1920 "deployment_info": deployment_info
,
1921 "target_id": target_vim
,
1924 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1925 "target_record_id": target_record_id
,
1930 # step 2 items (networks,vdus,...) to be created
1931 for target_item
in target_list
:
1934 for item_index
, existing_item
in enumerate(existing_list
):
1935 if existing_item
["id"] == target_item
["id"]:
1939 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1940 existing_list
.append(target_item
)
1941 existing_item
= None
1943 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
1944 existing_viminfo
= None
1947 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
1949 if existing_viminfo
is not None:
1952 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
1955 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
1956 # item must be sdn-net instead of net if target_vim is a sdn
1958 target_record_id
+= ".sdn"
1962 "ns.calculate_diff_items target_item={}".format(target_item
)
1964 if process_params
== Ns
._process
_flavor
_params
:
1971 "calculate_diff_items for flavor kwargs={}".format(kwargs
)
1974 if process_params
== Ns
._process
_vdu
_params
:
1975 self
.logger
.debug("calculate_diff_items self.fs={}".format(self
.fs
))
1981 "vdu2cloud_init": vdu2cloud_init
,
1982 "tasks_by_target_record_id": tasks_by_target_record_id
,
1983 "logger": self
.logger
,
1986 "ro_nsr_public_key": ro_nsr_public_key
,
1989 self
.logger
.debug("calculate_diff_items kwargs={}".format(kwargs
))
1991 extra_dict
= process_params(
1998 self
._assign
_vim
(target_vim
)
2001 "action_id": action_id
,
2003 "task_index": task_index
,
2007 "deployment_info": deployment_info
,
2008 "target_id": target_vim
,
2011 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
2012 "target_record_id": target_record_id
,
2013 "extra_dict": extra_dict
,
2014 "common_id": target_item
.get("common_id", None),
2016 diff_items
.append(new_item
)
2017 tasks_by_target_record_id
[target_record_id
] = new_item
2020 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
2022 return diff_items
, task_index
2024 def calculate_all_differences_to_deploy(
2034 tasks_by_target_record_id
,
2036 """This method calculates the ordered list of items (`changes_list`)
2037 to be created and deleted.
2040 indata (Dict[str, Any]): deployment info
2041 nsr_id (str): NSR id
2042 db_nsr: NSR record from DB
2043 db_vnfrs: VNFRS record from DB
2044 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2045 db_nsr_update (Dict[str, Any]): NSR info to update in DB
2046 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
2047 action_id (str): action id
2048 tasks_by_target_record_id (Dict[str, Any]):
2049 [<target_record_id>, <task>]
2052 List: ordered list of items to be created and deleted.
2056 # set list with diffs:
2059 # NS vld, image and flavor
2060 for item
in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
2061 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
2062 diff_items
, task_index
= self
.calculate_diff_items(
2065 db_ro_nsr
=db_ro_nsr
,
2066 db_nsr_update
=db_nsr_update
,
2068 tasks_by_target_record_id
=tasks_by_target_record_id
,
2069 action_id
=action_id
,
2071 task_index
=task_index
,
2074 changes_list
+= diff_items
2077 for vnfr_id
, vnfr
in db_vnfrs
.items():
2078 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
2079 for item
in ["net", "vdu"]:
2080 self
.logger
.debug("process VNF={} {}".format(vnfr_id
, item
))
2081 diff_items
, task_index
= self
.calculate_diff_items(
2084 db_ro_nsr
=db_ro_nsr
,
2085 db_nsr_update
=db_vnfrs_update
[vnfr
["_id"]],
2087 tasks_by_target_record_id
=tasks_by_target_record_id
,
2088 action_id
=action_id
,
2090 task_index
=task_index
,
2094 changes_list
+= diff_items
2098 def define_all_tasks(
2102 tasks_by_target_record_id
,
2104 """Function to create all the task structures obtanied from
2105 the method calculate_all_differences_to_deploy
2108 changes_list (List): ordered list of items to be created or deleted
2109 db_new_tasks (List): tasks list to be created
2110 action_id (str): action id
2111 tasks_by_target_record_id (Dict[str, Any]):
2112 [<target_record_id>, <task>]
2116 for change
in changes_list
:
2117 task
= Ns
._create
_task
(
2118 deployment_info
=change
["deployment_info"],
2119 target_id
=change
["target_id"],
2120 item
=change
["item"],
2121 action
=change
["action"],
2122 target_record
=change
["target_record"],
2123 target_record_id
=change
["target_record_id"],
2124 extra_dict
=change
.get("extra_dict", None),
2127 self
.logger
.debug("ns.define_all_tasks task={}".format(task
))
2128 tasks_by_target_record_id
[change
["target_record_id"]] = task
2129 db_new_tasks
.append(task
)
2131 if change
.get("common_id"):
2132 task
["common_id"] = change
["common_id"]
2134 def upload_all_tasks(
2139 """Function to save all tasks in the common DB
2142 db_new_tasks (List): tasks list to be created
2143 now (time): current time
2147 nb_ro_tasks
= 0 # for logging
2149 for db_task
in db_new_tasks
:
2150 target_id
= db_task
.pop("target_id")
2151 common_id
= db_task
.get("common_id")
2153 # Do not chek tasks with vim_status DELETED
2154 # because in manual heealing there are two tasks for the same vdur:
2155 # one with vim_status deleted and the other one with the actual VM status.
2161 "target_id": target_id
,
2162 "tasks.common_id": common_id
,
2163 "vim_info.vim_status.ne": "DELETED",
2165 update_dict
={"to_check_at": now
, "modified_at": now
},
2166 push
={"tasks": db_task
},
2167 fail_on_empty
=False,
2171 if not self
.db
.set_one(
2174 "target_id": target_id
,
2175 "tasks.target_record": db_task
["target_record"],
2176 "vim_info.vim_status.ne": "DELETED",
2178 update_dict
={"to_check_at": now
, "modified_at": now
},
2179 push
={"tasks": db_task
},
2180 fail_on_empty
=False,
2183 self
.logger
.debug("Updating database, Creating ro_tasks")
2184 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2186 self
.db
.create("ro_tasks", db_ro_task
)
2189 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2190 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2194 def upload_recreate_tasks(
2199 """Function to save recreate tasks in the common DB
2202 db_new_tasks (List): tasks list to be created
2203 now (time): current time
2207 nb_ro_tasks
= 0 # for logging
2209 for db_task
in db_new_tasks
:
2210 target_id
= db_task
.pop("target_id")
2211 self
.logger
.debug("target_id={} db_task={}".format(target_id
, db_task
))
2213 action
= db_task
.get("action", None)
2216 self
.logger
.debug("Updating database, Creating ro_tasks")
2217 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2219 # If DELETE task: the associated created items should be removed
2220 # (except persistent volumes):
2221 if action
== "DELETE":
2222 db_ro_task
["vim_info"]["created"] = True
2223 db_ro_task
["vim_info"]["created_items"] = db_task
.get(
2226 db_ro_task
["vim_info"]["volumes_to_hold"] = db_task
.get(
2227 "volumes_to_hold", []
2229 db_ro_task
["vim_info"]["vim_id"] = db_task
.get("vim_id", None)
2232 self
.logger
.debug("upload_all_tasks db_ro_task={}".format(db_ro_task
))
2233 self
.db
.create("ro_tasks", db_ro_task
)
2236 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2237 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2241 def _prepare_created_items_for_healing(
2247 # Get created_items from ro_task
2248 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2249 for ro_task
in ro_tasks
:
2250 for task
in ro_task
["tasks"]:
2252 task
["target_record"] == target_record
2253 and task
["action"] == "CREATE"
2254 and ro_task
["vim_info"]["created_items"]
2256 created_items
= ro_task
["vim_info"]["created_items"]
2259 return created_items
2261 def _prepare_persistent_volumes_for_healing(
2266 # The associated volumes of the VM shouldn't be removed
2269 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
2270 if vim_details_text
:
2271 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
2273 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
2274 volumes_list
.append(vol_id
["id"])
2278 def prepare_changes_to_recreate(
2286 tasks_by_target_record_id
,
2288 """This method will obtain an ordered list of items (`changes_list`)
2289 to be created and deleted to meet the recreate request.
2293 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id
, indata
)
2297 # set list with diffs:
2299 db_path
= self
.db_path_map
["vdu"]
2300 target_list
= indata
.get("healVnfData", {})
2301 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
2302 ro_nsr_public_key
= db_ro_nsr
["public_key"]
2304 # Check each VNF of the target
2305 for target_vnf
in target_list
:
2306 # Find this VNF in the list from DB
2307 vnfr_id
= target_vnf
.get("vnfInstanceId", None)
2309 existing_vnf
= db_vnfrs
.get(vnfr_id
)
2310 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
2311 # vim_account_id = existing_vnf.get("vim-account-id", "")
2313 # Check each VDU of this VNF
2314 for target_vdu
in target_vnf
["additionalParams"].get("vdu", None):
2315 vdu_name
= target_vdu
.get("vdu-id", None)
2316 # For multi instance VDU count-index is mandatory
2317 # For single session VDU count-indes is 0
2318 count_index
= target_vdu
.get("count-index", 0)
2320 existing_instance
= None
2321 for instance
in existing_vnf
.get("vdur", None):
2323 instance
["vdu-name"] == vdu_name
2324 and instance
["count-index"] == count_index
2326 existing_instance
= instance
2331 target_record_id
= "{}.{}".format(db_record
, existing_instance
["id"])
2333 # The target VIM is the one already existing in DB to recreate
2334 for target_vim
, target_viminfo
in existing_instance
.get(
2337 # step 1 vdu to be deleted
2338 self
._assign
_vim
(target_vim
)
2340 "action_id": action_id
,
2342 "task_index": task_index
,
2345 target_record
= f
"{db_record}.{item_index}.vim_info.{target_vim}"
2346 created_items
= self
._prepare
_created
_items
_for
_healing
(
2347 nsr_id
, target_record
2350 volumes_to_hold
= self
._prepare
_persistent
_volumes
_for
_healing
(
2351 target_vim
, existing_instance
2354 # Specific extra params for recreate tasks:
2356 "created_items": created_items
,
2357 "vim_id": existing_instance
["vim-id"],
2358 "volumes_to_hold": volumes_to_hold
,
2361 changes_list
.append(
2363 "deployment_info": deployment_info
,
2364 "target_id": target_vim
,
2367 "target_record": target_record
,
2368 "target_record_id": target_record_id
,
2369 "extra_dict": extra_dict
,
2372 delete_task_id
= f
"{action_id}:{task_index}"
2375 # step 2 vdu to be created
2381 "vnfr": existing_vnf
,
2382 "vdu2cloud_init": vdu2cloud_init
,
2383 "tasks_by_target_record_id": tasks_by_target_record_id
,
2384 "logger": self
.logger
,
2387 "ro_nsr_public_key": ro_nsr_public_key
,
2391 extra_dict
= self
._process
_recreate
_vdu
_params
(
2400 # The CREATE task depens on the DELETE task
2401 extra_dict
["depends_on"] = [delete_task_id
]
2403 # Add volumes created from created_items if any
2404 # Ports should be deleted with delete task and automatically created with create task
2406 for k
, v
in created_items
.items():
2408 k_item
, _
, k_id
= k
.partition(":")
2409 if k_item
== "volume":
2411 except Exception as e
:
2413 "Error evaluating created item {}: {}".format(k
, e
)
2415 extra_dict
["previous_created_volumes"] = volumes
2418 "action_id": action_id
,
2420 "task_index": task_index
,
2422 self
._assign
_vim
(target_vim
)
2425 "deployment_info": deployment_info
,
2426 "target_id": target_vim
,
2429 "target_record": target_record
,
2430 "target_record_id": target_record_id
,
2431 "extra_dict": extra_dict
,
2433 changes_list
.append(new_item
)
2434 tasks_by_target_record_id
[target_record_id
] = new_item
2439 def recreate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2440 self
.logger
.debug("ns.recreate nsr_id={} indata={}".format(nsr_id
, indata
))
2441 # TODO: validate_input(indata, recreate_schema)
2442 action_id
= indata
.get("action_id", str(uuid4()))
2443 # get current deployment
2444 db_vnfrs
= {} # vnf's info indexed by _id
2446 logging_text
= "Recreate nsr_id={} action_id={} indata={}".format(
2447 nsr_id
, action_id
, indata
2449 self
.logger
.debug(logging_text
+ "Enter")
2452 step
= "Getting ns and vnfr record from db"
2453 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2455 tasks_by_target_record_id
= {}
2456 # read from db: vnf's of this ns
2457 step
= "Getting vnfrs from db"
2458 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2459 self
.logger
.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list
))
2461 if not db_vnfrs_list
:
2462 raise NsException("Cannot obtain associated VNF for ns")
2464 for vnfr
in db_vnfrs_list
:
2465 db_vnfrs
[vnfr
["_id"]] = vnfr
2468 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2469 self
.logger
.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr
))
2472 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2474 with self
.write_lock
:
2476 step
= "process NS elements"
2477 changes_list
= self
.prepare_changes_to_recreate(
2482 db_ro_nsr
=db_ro_nsr
,
2483 action_id
=action_id
,
2484 tasks_by_target_record_id
=tasks_by_target_record_id
,
2487 self
.define_all_tasks(
2488 changes_list
=changes_list
,
2489 db_new_tasks
=db_new_tasks
,
2490 tasks_by_target_record_id
=tasks_by_target_record_id
,
2493 # Delete all ro_tasks registered for the targets vdurs (target_record)
2494 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2495 # So remove all task related to target record.
2496 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2497 for change
in changes_list
:
2498 for ro_task
in ro_tasks
:
2499 for task
in ro_task
["tasks"]:
2500 if task
["target_record"] == change
["target_record"]:
2504 "_id": ro_task
["_id"],
2505 "modified_at": ro_task
["modified_at"],
2507 fail_on_empty
=False,
2510 step
= "Updating database, Appending tasks to ro_tasks"
2511 self
.upload_recreate_tasks(
2512 db_new_tasks
=db_new_tasks
,
2517 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2521 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2525 except Exception as e
:
2526 if isinstance(e
, (DbException
, NsException
)):
2528 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2531 e
= traceback_format_exc()
2532 self
.logger
.critical(
2533 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2537 raise NsException(e
)
2539 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2540 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
2541 validate_input(indata
, deploy_schema
)
2542 action_id
= indata
.get("action_id", str(uuid4()))
2544 # get current deployment
2545 db_nsr_update
= {} # update operation on nsrs
2546 db_vnfrs_update
= {}
2547 db_vnfrs
= {} # vnf's info indexed by _id
2549 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2550 self
.logger
.debug(logging_text
+ "Enter")
2553 step
= "Getting ns and vnfr record from db"
2554 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2555 self
.logger
.debug("ns.deploy: db_nsr={}".format(db_nsr
))
2557 tasks_by_target_record_id
= {}
2558 # read from db: vnf's of this ns
2559 step
= "Getting vnfrs from db"
2560 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2562 if not db_vnfrs_list
:
2563 raise NsException("Cannot obtain associated VNF for ns")
2565 for vnfr
in db_vnfrs_list
:
2566 db_vnfrs
[vnfr
["_id"]] = vnfr
2567 db_vnfrs_update
[vnfr
["_id"]] = {}
2568 self
.logger
.debug("ns.deploy db_vnfrs={}".format(db_vnfrs
))
2571 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2574 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2576 # check that action_id is not in the list of actions. Suffixed with :index
2577 if action_id
in db_ro_nsr
["actions"]:
2581 new_action_id
= "{}:{}".format(action_id
, index
)
2583 if new_action_id
not in db_ro_nsr
["actions"]:
2584 action_id
= new_action_id
2587 + "Changing action_id in use to {}".format(action_id
)
2593 def _process_action(indata
):
2594 nonlocal db_new_tasks
2601 if indata
["action"]["action"] == "inject_ssh_key":
2602 key
= indata
["action"].get("key")
2603 user
= indata
["action"].get("user")
2604 password
= indata
["action"].get("password")
2606 for vnf
in indata
.get("vnf", ()):
2607 if vnf
["_id"] not in db_vnfrs
:
2608 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
2610 db_vnfr
= db_vnfrs
[vnf
["_id"]]
2612 for target_vdu
in vnf
.get("vdur", ()):
2613 vdu_index
, vdur
= next(
2616 for i_v
in enumerate(db_vnfr
["vdur"])
2617 if i_v
[1]["id"] == target_vdu
["id"]
2624 "Invalid vdu vnf={}.{}".format(
2625 vnf
["_id"], target_vdu
["id"]
2629 target_vim
, vim_info
= next(
2630 k_v
for k_v
in vdur
["vim_info"].items()
2632 self
._assign
_vim
(target_vim
)
2633 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
2634 vnf
["_id"], vdu_index
2638 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
2641 "ip_address": vdur
.get("ip-address"),
2644 "password": password
,
2645 "private_key": db_ro_nsr
["private_key"],
2646 "salt": db_ro_nsr
["_id"],
2647 "schema_version": db_ro_nsr
["_admin"][
2654 "action_id": action_id
,
2656 "task_index": task_index
,
2659 task
= Ns
._create
_task
(
2660 deployment_info
=deployment_info
,
2661 target_id
=target_vim
,
2664 target_record
=target_record
,
2665 target_record_id
=None,
2666 extra_dict
=extra_dict
,
2669 task_index
= deployment_info
.get("task_index")
2671 db_new_tasks
.append(task
)
2673 with self
.write_lock
:
2674 if indata
.get("action"):
2675 _process_action(indata
)
2677 # compute network differences
2679 step
= "process NS elements"
2680 changes_list
= self
.calculate_all_differences_to_deploy(
2685 db_ro_nsr
=db_ro_nsr
,
2686 db_nsr_update
=db_nsr_update
,
2687 db_vnfrs_update
=db_vnfrs_update
,
2688 action_id
=action_id
,
2689 tasks_by_target_record_id
=tasks_by_target_record_id
,
2691 self
.define_all_tasks(
2692 changes_list
=changes_list
,
2693 db_new_tasks
=db_new_tasks
,
2694 tasks_by_target_record_id
=tasks_by_target_record_id
,
2697 step
= "Updating database, Appending tasks to ro_tasks"
2698 self
.upload_all_tasks(
2699 db_new_tasks
=db_new_tasks
,
2703 step
= "Updating database, nsrs"
2705 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
2707 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
2709 step
= "Updating database, vnfrs={}".format(vnfr_id
)
2710 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
2713 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2717 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2721 except Exception as e
:
2722 if isinstance(e
, (DbException
, NsException
)):
2724 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2727 e
= traceback_format_exc()
2728 self
.logger
.critical(
2729 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2733 raise NsException(e
)
2735 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2736 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
2737 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2739 with self
.write_lock
:
2741 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
2742 except NsWorkerException
as e
:
2743 raise NsException(e
)
2745 return None, None, True
2747 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2749 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2750 version
, nsr_id
, action_id
, indata
2756 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
2757 global_status
= "DONE"
2760 for ro_task
in ro_tasks
:
2761 for task
in ro_task
["tasks"]:
2762 if task
and task
["action_id"] == action_id
:
2763 task_list
.append(task
)
2766 if task
["status"] == "FAILED":
2767 global_status
= "FAILED"
2768 error_text
= "Error at {} {}: {}".format(
2769 task
["action"].lower(),
2771 ro_task
["vim_info"].get("vim_message") or "unknown",
2773 details
.append(error_text
)
2774 elif task
["status"] in ("SCHEDULED", "BUILD"):
2775 if global_status
!= "FAILED":
2776 global_status
= "BUILD"
2781 "status": global_status
,
2782 "details": ". ".join(details
)
2784 else "progress {}/{}".format(done
, total
),
2786 "action_id": action_id
,
2790 return return_data
, None, True
2792 def recreate_status(
2793 self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
2795 return self
.status(session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
)
2797 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2799 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2800 session
, indata
, version
, nsr_id
, action_id
2804 return None, None, True
2806 def rebuild_start_stop_task(
2817 self
._assign
_vim
(target_vim
)
2818 target_record
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_index
)
2819 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_id
)
2821 "action_id": action_id
,
2823 "task_index": task_index
,
2826 task
= Ns
._create
_task
(
2827 deployment_info
=deployment_info
,
2828 target_id
=target_vim
,
2831 target_record
=target_record
,
2832 target_record_id
=target_record_id
,
2833 extra_dict
=extra_dict
,
2837 def rebuild_start_stop(
2838 self
, session
, action_dict
, version
, nsr_id
, *args
, **kwargs
2843 action_id
= action_dict
.get("action_id", str(uuid4()))
2845 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2846 self
.logger
.debug(logging_text
+ "Enter")
2848 action
= list(action_dict
.keys())[0]
2849 task_dict
= action_dict
.get(action
)
2850 vim_vm_id
= action_dict
.get(action
).get("vim_vm_id")
2852 if action_dict
.get("stop"):
2856 step
= "lock the operation & do task creation"
2857 with self
.write_lock
:
2858 extra_dict
["params"] = {
2859 "vim_vm_id": vim_vm_id
,
2862 task
= self
.rebuild_start_stop_task(
2863 task_dict
["vdu_id"],
2864 task_dict
["vnf_id"],
2865 task_dict
["vdu_index"],
2869 task_dict
["target_vim"],
2872 db_new_tasks
.append(task
)
2873 step
= "upload Task to db"
2874 self
.upload_all_tasks(
2875 db_new_tasks
=db_new_tasks
,
2879 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2882 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2886 except Exception as e
:
2887 if isinstance(e
, (DbException
, NsException
)):
2889 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2892 e
= traceback_format_exc()
2893 self
.logger
.critical(
2894 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2897 raise NsException(e
)
2899 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2900 nsrs
= self
.db
.get_list("nsrs", {})
2904 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
2906 return return_data
, None, True
2908 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2909 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2912 for ro_task
in ro_tasks
:
2913 for task
in ro_task
["tasks"]:
2914 if task
["action_id"] not in return_data
:
2915 return_data
.append(task
["action_id"])
2917 return return_data
, None, True
2920 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
2922 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
2923 self
._assign
_vim
(target_vim
)
2924 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
2925 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
2927 "action_id": action_id
,
2929 "task_index": task_index
,
2932 task
= Ns
._create
_task
(
2933 deployment_info
=deployment_info
,
2934 target_id
=target_vim
,
2937 target_record
=target_record
,
2938 target_record_id
=target_record_id
,
2939 extra_dict
=extra_dict
,
2944 def migrate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2948 action_id
= indata
.get("action_id", str(uuid4()))
2950 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2951 self
.logger
.debug(logging_text
+ "Enter")
2953 vnf_instance_id
= indata
["vnfInstanceId"]
2954 step
= "Getting vnfrs from db"
2955 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
2956 vdu
= indata
.get("vdu")
2957 migrateToHost
= indata
.get("migrateToHost")
2960 with self
.write_lock
:
2962 vdu_id
= indata
["vdu"]["vduId"]
2963 vdu_count_index
= indata
["vdu"].get("vduCountIndex", 0)
2964 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2966 vdu
["vdu-id-ref"] == vdu_id
2967 and vdu
["count-index"] == vdu_count_index
2969 extra_dict
["params"] = {
2970 "vim_vm_id": vdu
["vim-id"],
2971 "migrate_host": migrateToHost
,
2972 "vdu_vim_info": vdu
["vim_info"],
2974 step
= "Creating migration task for vdu:{}".format(vdu
)
2975 task
= self
.migrate_task(
2984 db_new_tasks
.append(task
)
2988 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2989 extra_dict
["params"] = {
2990 "vim_vm_id": vdu
["vim-id"],
2991 "migrate_host": migrateToHost
,
2992 "vdu_vim_info": vdu
["vim_info"],
2994 step
= "Creating migration task for vdu:{}".format(vdu
)
2995 task
= self
.migrate_task(
3004 db_new_tasks
.append(task
)
3007 self
.upload_all_tasks(
3008 db_new_tasks
=db_new_tasks
,
3013 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3016 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3020 except Exception as e
:
3021 if isinstance(e
, (DbException
, NsException
)):
3023 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3026 e
= traceback_format_exc()
3027 self
.logger
.critical(
3028 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3031 raise NsException(e
)
3033 def verticalscale_task(
3034 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
3036 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
3037 self
._assign
_vim
(target_vim
)
3038 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
3039 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
3041 "action_id": action_id
,
3043 "task_index": task_index
,
3046 task
= Ns
._create
_task
(
3047 deployment_info
=deployment_info
,
3048 target_id
=target_vim
,
3049 item
="verticalscale",
3051 target_record
=target_record
,
3052 target_record_id
=target_record_id
,
3053 extra_dict
=extra_dict
,
3057 def verticalscale(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3061 action_id
= indata
.get("action_id", str(uuid4()))
3063 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
3064 self
.logger
.debug(logging_text
+ "Enter")
3066 VnfFlavorData
= indata
.get("changeVnfFlavorData")
3067 vnf_instance_id
= VnfFlavorData
["vnfInstanceId"]
3068 step
= "Getting vnfrs from db"
3069 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
3070 vduid
= VnfFlavorData
["additionalParams"]["vduid"]
3071 vduCountIndex
= VnfFlavorData
["additionalParams"]["vduCountIndex"]
3072 virtualMemory
= VnfFlavorData
["additionalParams"]["virtualMemory"]
3073 numVirtualCpu
= VnfFlavorData
["additionalParams"]["numVirtualCpu"]
3074 sizeOfStorage
= VnfFlavorData
["additionalParams"]["sizeOfStorage"]
3076 "name": vduid
+ "-flv",
3077 "ram": virtualMemory
,
3078 "vcpus": numVirtualCpu
,
3079 "disk": sizeOfStorage
,
3082 step
= "Creating Tasks for vertical scaling"
3083 with self
.write_lock
:
3084 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3086 vdu
["vdu-id-ref"] == vduid
3087 and vdu
["count-index"] == vduCountIndex
3089 extra_dict
["params"] = {
3090 "vim_vm_id": vdu
["vim-id"],
3091 "flavor_dict": flavor_dict
,
3093 task
= self
.verticalscale_task(
3102 db_new_tasks
.append(task
)
3105 self
.upload_all_tasks(
3106 db_new_tasks
=db_new_tasks
,
3110 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3113 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3117 except Exception as e
:
3118 if isinstance(e
, (DbException
, NsException
)):
3120 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3123 e
= traceback_format_exc()
3124 self
.logger
.critical(
3125 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3128 raise NsException(e
)