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"
727 if guest_epa_quota
.get("cpu-thread-pinning-policy") != "PREFER"
729 ] = max(vcpu_count
, 1)
730 local_epa_vcpu_set
= True
732 return numa
, local_epa_vcpu_set
735 def _process_epa_params(
736 target_flavor
: Dict
[str, Any
],
741 target_flavor (Dict[str, Any]): [description]
744 Dict[str, Any]: [description]
750 if target_flavor
.get("guest-epa"):
751 guest_epa
= target_flavor
["guest-epa"]
753 numa_list
, epa_vcpu_set
= Ns
._process
_guest
_epa
_numa
_params
(
754 guest_epa_quota
=guest_epa
757 if guest_epa
.get("mempage-size"):
758 extended
["mempage-size"] = guest_epa
.get("mempage-size")
760 if guest_epa
.get("cpu-pinning-policy"):
761 extended
["cpu-pinning-policy"] = guest_epa
.get("cpu-pinning-policy")
763 if guest_epa
.get("cpu-thread-pinning-policy"):
764 extended
["cpu-thread-pinning-policy"] = guest_epa
.get(
765 "cpu-thread-pinning-policy"
768 if guest_epa
.get("numa-node-policy"):
769 if guest_epa
.get("numa-node-policy").get("mem-policy"):
770 extended
["mem-policy"] = guest_epa
.get("numa-node-policy").get(
774 tmp_numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_cpu
_pinning
_params
(
775 guest_epa_quota
=guest_epa
,
776 vcpu_count
=int(target_flavor
.get("vcpu-count", 1)),
777 epa_vcpu_set
=epa_vcpu_set
,
779 for numa
in numa_list
:
780 numa
.update(tmp_numa
)
783 Ns
._process
_guest
_epa
_quota
_params
(
784 guest_epa_quota
=guest_epa
,
785 epa_vcpu_set
=epa_vcpu_set
,
790 extended
["numas"] = numa_list
795 def _process_flavor_params(
796 target_flavor
: Dict
[str, Any
],
797 indata
: Dict
[str, Any
],
798 vim_info
: Dict
[str, Any
],
799 target_record_id
: str,
800 **kwargs
: Dict
[str, Any
],
805 target_flavor (Dict[str, Any]): [description]
806 indata (Dict[str, Any]): [description]
807 vim_info (Dict[str, Any]): [description]
808 target_record_id (str): [description]
811 Dict[str, Any]: [description]
813 db
= kwargs
.get("db")
817 "disk": int(target_flavor
["storage-gb"]),
818 "ram": int(target_flavor
["memory-mb"]),
819 "vcpus": int(target_flavor
["vcpu-count"]),
822 for vnf
in indata
.get("vnf", []):
823 for vdur
in vnf
.get("vdur", []):
824 if vdur
.get("ns-flavor-id") == target_flavor
.get("id"):
827 if db
and isinstance(indata
.get("vnf"), list):
828 vnfd_id
= indata
.get("vnf")[0].get("vnfd-id")
829 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
830 # check if there is persistent root disk
831 for vdu
in vnfd
.get("vdu", ()):
832 if vdu
["name"] == target_vdur
.get("vdu-name"):
833 for vsd
in vnfd
.get("virtual-storage-desc", ()):
834 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
837 root_disk
.get("type-of-storage")
838 == "persistent-storage:persistent-storage"
840 flavor_data
["disk"] = 0
842 for storage
in target_vdur
.get("virtual-storages", []):
844 storage
.get("type-of-storage")
845 == "etsi-nfv-descriptors:ephemeral-storage"
847 flavor_data
["ephemeral"] = int(storage
.get("size-of-storage", 0))
848 elif storage
.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
849 flavor_data
["swap"] = int(storage
.get("size-of-storage", 0))
851 extended
= Ns
._process
_epa
_params
(target_flavor
)
853 flavor_data
["extended"] = extended
855 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
856 flavor_data_name
= flavor_data
.copy()
857 flavor_data_name
["name"] = target_flavor
["name"]
858 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
863 def _ip_profile_to_ro(
864 ip_profile
: Dict
[str, Any
],
869 ip_profile (Dict[str, Any]): [description]
872 Dict[str, Any]: [description]
879 if "v4" in ip_profile
.get("ip-version", "ipv4")
881 "subnet_address": ip_profile
.get("subnet-address"),
882 "gateway_address": ip_profile
.get("gateway-address"),
883 "dhcp_enabled": ip_profile
.get("dhcp-params", {}).get("enabled", False),
884 "dhcp_start_address": ip_profile
.get("dhcp-params", {}).get(
885 "start-address", None
887 "dhcp_count": ip_profile
.get("dhcp-params", {}).get("count", None),
890 if ip_profile
.get("dns-server"):
891 ro_ip_profile
["dns_address"] = ";".join(
892 [v
["address"] for v
in ip_profile
["dns-server"] if v
.get("address")]
895 if ip_profile
.get("security-group"):
896 ro_ip_profile
["security_group"] = ip_profile
["security-group"]
901 def _process_net_params(
902 target_vld
: Dict
[str, Any
],
903 indata
: Dict
[str, Any
],
904 vim_info
: Dict
[str, Any
],
905 target_record_id
: str,
906 **kwargs
: Dict
[str, Any
],
908 """Function to process network parameters.
911 target_vld (Dict[str, Any]): [description]
912 indata (Dict[str, Any]): [description]
913 vim_info (Dict[str, Any]): [description]
914 target_record_id (str): [description]
917 Dict[str, Any]: [description]
921 if vim_info
.get("sdn"):
922 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
923 # ns_preffix = "nsrs:{}".format(nsr_id)
924 # remove the ending ".sdn
925 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
926 extra_dict
["params"] = {
928 for k
in ("sdn-ports", "target_vim", "vlds", "type")
932 # TODO needed to add target_id in the dependency.
933 if vim_info
.get("target_vim"):
934 extra_dict
["depends_on"] = [
935 f
"{vim_info.get('target_vim')} {vld_target_record_id}"
940 if vim_info
.get("vim_network_name"):
941 extra_dict
["find_params"] = {
943 "name": vim_info
.get("vim_network_name"),
946 elif vim_info
.get("vim_network_id"):
947 extra_dict
["find_params"] = {
949 "id": vim_info
.get("vim_network_id"),
952 elif target_vld
.get("mgmt-network") and not vim_info
.get("provider_network"):
953 extra_dict
["find_params"] = {
955 "name": target_vld
["id"],
959 extra_dict
["params"] = {
961 f
"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
963 "ip_profile": Ns
._ip
_profile
_to
_ro
(vim_info
.get("ip_profile")),
964 "provider_network_profile": vim_info
.get("provider_network"),
967 if not target_vld
.get("underlay"):
968 extra_dict
["params"]["net_type"] = "bridge"
970 extra_dict
["params"]["net_type"] = (
971 "ptp" if target_vld
.get("type") == "ELINE" else "data"
977 def find_persistent_root_volumes(
980 vdu_instantiation_volumes_list
: list,
983 """Find the persistent root volumes and add them to the disk_list
984 by parsing the instantiation parameters.
987 vnfd (dict): VNF descriptor
988 target_vdu (dict): processed VDU
989 vdu_instantiation_volumes_list (list): instantiation parameters for the each VDU as a list
990 disk_list (list): to be filled up
993 persistent_root_disk (dict): Details of persistent root disk
996 persistent_root_disk
= {}
997 # There can be only one root disk, when we find it, it will return the result
999 for vdu
, vsd
in product(
1000 vnfd
.get("vdu", ()), vnfd
.get("virtual-storage-desc", ())
1003 vdu
["name"] == target_vdu
["vdu-name"]
1004 and vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]
1008 root_disk
.get("type-of-storage")
1009 == "persistent-storage:persistent-storage"
1011 for vdu_volume
in vdu_instantiation_volumes_list
:
1013 vdu_volume
["vim-volume-id"]
1014 and root_disk
["id"] == vdu_volume
["name"]
1016 persistent_root_disk
[vsd
["id"]] = {
1017 "vim_volume_id": vdu_volume
["vim-volume-id"],
1018 "image_id": vdu
.get("sw-image-desc"),
1021 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1023 return persistent_root_disk
1026 if root_disk
.get("size-of-storage"):
1027 persistent_root_disk
[vsd
["id"]] = {
1028 "image_id": vdu
.get("sw-image-desc"),
1029 "size": root_disk
.get("size-of-storage"),
1032 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1034 return persistent_root_disk
1037 def find_persistent_volumes(
1038 persistent_root_disk
: dict,
1040 vdu_instantiation_volumes_list
: list,
1043 """Find the ordinary persistent volumes and add them to the disk_list
1044 by parsing the instantiation parameters.
1047 persistent_root_disk: persistent root disk dictionary
1048 target_vdu: processed VDU
1049 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1050 disk_list: to be filled up
1053 # Find the ordinary volumes which are not added to the persistent_root_disk
1054 persistent_disk
= {}
1055 for disk
in target_vdu
.get("virtual-storages", {}):
1057 disk
.get("type-of-storage") == "persistent-storage:persistent-storage"
1058 and disk
["id"] not in persistent_root_disk
.keys()
1060 for vdu_volume
in vdu_instantiation_volumes_list
:
1061 if vdu_volume
["vim-volume-id"] and disk
["id"] == vdu_volume
["name"]:
1062 persistent_disk
[disk
["id"]] = {
1063 "vim_volume_id": vdu_volume
["vim-volume-id"],
1065 disk_list
.append(persistent_disk
[disk
["id"]])
1068 if disk
["id"] not in persistent_disk
.keys():
1069 persistent_disk
[disk
["id"]] = {
1070 "size": disk
.get("size-of-storage"),
1072 disk_list
.append(persistent_disk
[disk
["id"]])
1075 def _sort_vdu_interfaces(target_vdu
: dict) -> None:
1076 """Sort the interfaces according to position number.
1079 target_vdu (dict): Details of VDU to be created
1082 # If the position info is provided for all the interfaces, it will be sorted
1083 # according to position number ascendingly.
1084 sorted_interfaces
= sorted(
1085 target_vdu
["interfaces"],
1086 key
=lambda x
: (x
.get("position") is None, x
.get("position")),
1088 target_vdu
["interfaces"] = sorted_interfaces
1091 def _partially_locate_vdu_interfaces(target_vdu
: dict) -> None:
1092 """Only place the interfaces which has specific position.
1095 target_vdu (dict): Details of VDU to be created
1098 # If the position info is provided for some interfaces but not all of them, the interfaces
1099 # which has specific position numbers will be placed and others' positions will not be taken care.
1101 i
.get("position") + 1
1102 for i
in target_vdu
["interfaces"]
1103 if i
.get("position") is not None
1105 n
= len(target_vdu
["interfaces"])
1106 sorted_interfaces
= [-1] * n
1110 if target_vdu
["interfaces"][k
].get("position") is not None:
1111 if any(i
.get("position") == 0 for i
in target_vdu
["interfaces"]):
1112 idx
= target_vdu
["interfaces"][k
]["position"] + 1
1114 idx
= target_vdu
["interfaces"][k
]["position"]
1115 sorted_interfaces
[idx
- 1] = target_vdu
["interfaces"][k
]
1119 if target_vdu
["interfaces"][m
].get("position") is None:
1120 idy
= sorted_interfaces
.index(-1)
1121 sorted_interfaces
[idy
] = target_vdu
["interfaces"][m
]
1124 target_vdu
["interfaces"] = sorted_interfaces
1127 def _prepare_vdu_cloud_init(
1128 target_vdu
: dict, vdu2cloud_init
: dict, db
: object, fs
: object
1130 """Fill cloud_config dict with cloud init details.
1133 target_vdu (dict): Details of VDU to be created
1134 vdu2cloud_init (dict): Cloud init dict
1135 db (object): DB object
1136 fs (object): FS object
1139 cloud_config (dict): Cloud config details of VDU
1145 if target_vdu
.get("cloud-init"):
1146 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1147 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1150 location
=target_vdu
["cloud-init"],
1153 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1154 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1155 cloud_init_content
=cloud_content_
,
1156 params
=target_vdu
.get("additionalParams"),
1157 context
=target_vdu
["cloud-init"],
1160 if target_vdu
.get("boot-data-drive"):
1161 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1166 def _check_vld_information_of_interfaces(
1167 interface
: dict, ns_preffix
: str, vnf_preffix
: str
1169 """Prepare the net_text by the virtual link information for vnf and ns level.
1171 interface (dict): Interface details
1172 ns_preffix (str): Prefix of NS
1173 vnf_preffix (str): Prefix of VNF
1176 net_text (str): information of net
1180 if interface
.get("ns-vld-id"):
1181 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
1182 elif interface
.get("vnf-vld-id"):
1183 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
1188 def _prepare_interface_port_security(interface
: dict) -> None:
1192 interface (dict): Interface details
1195 if "port-security-enabled" in interface
:
1196 interface
["port_security"] = interface
.pop("port-security-enabled")
1198 if "port-security-disable-strategy" in interface
:
1199 interface
["port_security_disable_strategy"] = interface
.pop(
1200 "port-security-disable-strategy"
1204 def _create_net_item_of_interface(interface
: dict, net_text
: str) -> dict:
1205 """Prepare net item including name, port security, floating ip etc.
1208 interface (dict): Interface details
1209 net_text (str): information of net
1212 net_item (dict): Dict including net details
1218 for x
, v
in interface
.items()
1224 "port_security_disable_strategy",
1228 net_item
["net_id"] = "TASK-" + net_text
1229 net_item
["type"] = "virtual"
1234 def _prepare_type_of_interface(
1235 interface
: dict, tasks_by_target_record_id
: dict, net_text
: str, net_item
: dict
1237 """Fill the net item type by interface type such as SR-IOV, OM-MGMT, bridge etc.
1240 interface (dict): Interface details
1241 tasks_by_target_record_id (dict): Task details
1242 net_text (str): information of net
1243 net_item (dict): Dict including net details
1246 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1247 # TODO floating_ip: True/False (or it can be None)
1249 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1250 # Mark the net create task as type data
1252 tasks_by_target_record_id
,
1258 tasks_by_target_record_id
[net_text
]["extra_dict"]["params"][
1262 net_item
["use"] = "data"
1263 net_item
["model"] = interface
["type"]
1264 net_item
["type"] = interface
["type"]
1267 interface
.get("type") == "OM-MGMT"
1268 or interface
.get("mgmt-interface")
1269 or interface
.get("mgmt-vnf")
1271 net_item
["use"] = "mgmt"
1274 # If interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1275 net_item
["use"] = "bridge"
1276 net_item
["model"] = interface
.get("type")
1279 def _prepare_vdu_interfaces(
1285 tasks_by_target_record_id
: dict,
1288 """Prepare the net_item and add net_list, add mgmt interface to extra_dict.
1291 target_vdu (dict): VDU to be created
1292 extra_dict (dict): Dictionary to be filled
1293 ns_preffix (str): NS prefix as string
1294 vnf_preffix (str): VNF prefix as string
1295 logger (object): Logger Object
1296 tasks_by_target_record_id (dict): Task details
1297 net_list (list): Net list of VDU
1299 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
1300 net_text
= Ns
._check
_vld
_information
_of
_interfaces
(
1301 interface
, ns_preffix
, vnf_preffix
1304 # Interface not connected to any vld
1306 "Interface {} from vdu {} not connected to any vld".format(
1307 iface_index
, target_vdu
["vdu-name"]
1312 extra_dict
["depends_on"].append(net_text
)
1314 Ns
._prepare
_interface
_port
_security
(interface
)
1316 net_item
= Ns
._create
_net
_item
_of
_interface
(interface
, net_text
)
1318 Ns
._prepare
_type
_of
_interface
(
1319 interface
, tasks_by_target_record_id
, net_text
, net_item
1322 if interface
.get("ip-address"):
1323 net_item
["ip_address"] = interface
["ip-address"]
1325 if interface
.get("mac-address"):
1326 net_item
["mac_address"] = interface
["mac-address"]
1328 net_list
.append(net_item
)
1330 if interface
.get("mgmt-vnf"):
1331 extra_dict
["mgmt_vnf_interface"] = iface_index
1332 elif interface
.get("mgmt-interface"):
1333 extra_dict
["mgmt_vdu_interface"] = iface_index
1336 def _prepare_vdu_ssh_keys(
1337 target_vdu
: dict, ro_nsr_public_key
: dict, cloud_config
: dict
1339 """Add ssh keys to cloud config.
1342 target_vdu (dict): Details of VDU to be created
1343 ro_nsr_public_key (dict): RO NSR public Key
1344 cloud_config (dict): Cloud config details
1349 if target_vdu
.get("ssh-keys"):
1350 ssh_keys
+= target_vdu
.get("ssh-keys")
1352 if target_vdu
.get("ssh-access-required"):
1353 ssh_keys
.append(ro_nsr_public_key
)
1356 cloud_config
["key-pairs"] = ssh_keys
1359 def _select_persistent_root_disk(vsd
: dict, vdu
: dict) -> dict:
1360 """Selects the persistent root disk if exists.
1362 vsd (dict): Virtual storage descriptors in VNFD
1363 vdu (dict): VNF descriptor
1366 root_disk (dict): Selected persistent root disk
1368 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
1372 ) == "persistent-storage:persistent-storage" and root_disk
.get(
1378 def _add_persistent_root_disk_to_disk_list(
1379 vnfd
: dict, target_vdu
: dict, persistent_root_disk
: dict, disk_list
: list
1381 """Find the persistent root disk and add to disk list.
1384 vnfd (dict): VNF descriptor
1385 target_vdu (dict): Details of VDU to be created
1386 persistent_root_disk (dict): Details of persistent root disk
1387 disk_list (list): Disks of VDU
1390 for vdu
in vnfd
.get("vdu", ()):
1391 if vdu
["name"] == target_vdu
["vdu-name"]:
1392 for vsd
in vnfd
.get("virtual-storage-desc", ()):
1393 root_disk
= Ns
._select
_persistent
_root
_disk
(vsd
, vdu
)
1398 persistent_root_disk
[vsd
["id"]] = {
1399 "image_id": vdu
.get("sw-image-desc"),
1400 "size": root_disk
["size-of-storage"],
1403 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1407 def _add_persistent_ordinary_disks_to_disk_list(
1409 persistent_root_disk
: dict,
1410 persistent_ordinary_disk
: dict,
1413 """Fill the disk list by adding persistent ordinary disks.
1416 target_vdu (dict): Details of VDU to be created
1417 persistent_root_disk (dict): Details of persistent root disk
1418 persistent_ordinary_disk (dict): Details of persistent ordinary disk
1419 disk_list (list): Disks of VDU
1422 if target_vdu
.get("virtual-storages"):
1423 for disk
in target_vdu
["virtual-storages"]:
1425 disk
.get("type-of-storage")
1426 == "persistent-storage:persistent-storage"
1427 and disk
["id"] not in persistent_root_disk
.keys()
1429 persistent_ordinary_disk
[disk
["id"]] = {
1430 "size": disk
["size-of-storage"],
1432 disk_list
.append(persistent_ordinary_disk
[disk
["id"]])
1435 def _prepare_vdu_affinity_group_list(
1436 target_vdu
: dict, extra_dict
: dict, ns_preffix
: str
1437 ) -> List
[Dict
[str, any
]]:
1438 """Process affinity group details to prepare affinity group list.
1441 target_vdu (dict): Details of VDU to be created
1442 extra_dict (dict): Dictionary to be filled
1443 ns_preffix (str): Prefix as string
1447 affinity_group_list (list): Affinity group details
1450 affinity_group_list
= []
1452 if target_vdu
.get("affinity-or-anti-affinity-group-id"):
1453 for affinity_group_id
in target_vdu
["affinity-or-anti-affinity-group-id"]:
1455 affinity_group_text
= (
1456 ns_preffix
+ ":affinity-or-anti-affinity-group." + affinity_group_id
1459 if not isinstance(extra_dict
.get("depends_on"), list):
1460 raise NsException("Invalid extra_dict format.")
1462 extra_dict
["depends_on"].append(affinity_group_text
)
1463 affinity_group
["affinity_group_id"] = "TASK-" + affinity_group_text
1464 affinity_group_list
.append(affinity_group
)
1466 return affinity_group_list
1469 def _process_vdu_params(
1470 target_vdu
: Dict
[str, Any
],
1471 indata
: Dict
[str, Any
],
1472 vim_info
: Dict
[str, Any
],
1473 target_record_id
: str,
1474 **kwargs
: Dict
[str, Any
],
1475 ) -> Dict
[str, Any
]:
1476 """Function to process VDU parameters.
1479 target_vdu (Dict[str, Any]): [description]
1480 indata (Dict[str, Any]): [description]
1481 vim_info (Dict[str, Any]): [description]
1482 target_record_id (str): [description]
1485 Dict[str, Any]: [description]
1487 vnfr_id
= kwargs
.get("vnfr_id")
1488 nsr_id
= kwargs
.get("nsr_id")
1489 vnfr
= kwargs
.get("vnfr")
1490 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1491 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
1492 logger
= kwargs
.get("logger")
1493 db
= kwargs
.get("db")
1494 fs
= kwargs
.get("fs")
1495 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1497 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
1498 ns_preffix
= "nsrs:{}".format(nsr_id
)
1499 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
1500 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
1501 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
1504 persistent_root_disk
= {}
1505 persistent_ordinary_disk
= {}
1506 vdu_instantiation_volumes_list
= []
1508 vnfd_id
= vnfr
["vnfd-id"]
1509 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
1511 # If the position info is provided for all the interfaces, it will be sorted
1512 # according to position number ascendingly.
1514 True if i
.get("position") is not None else False
1515 for i
in target_vdu
["interfaces"]
1517 Ns
._sort
_vdu
_interfaces
(target_vdu
)
1519 # If the position info is provided for some interfaces but not all of them, the interfaces
1520 # which has specific position numbers will be placed and others' positions will not be taken care.
1522 Ns
._partially
_locate
_vdu
_interfaces
(target_vdu
)
1524 # If the position info is not provided for the interfaces, interfaces will be attached
1525 # according to the order in the VNFD.
1526 Ns
._prepare
_vdu
_interfaces
(
1532 tasks_by_target_record_id
,
1537 cloud_config
= Ns
._prepare
_vdu
_cloud
_init
(target_vdu
, vdu2cloud_init
, db
, fs
)
1539 # Prepare VDU ssh keys
1540 Ns
._prepare
_vdu
_ssh
_keys
(target_vdu
, ro_nsr_public_key
, cloud_config
)
1542 if target_vdu
.get("additionalParams"):
1543 vdu_instantiation_volumes_list
= (
1544 target_vdu
.get("additionalParams").get("OSM").get("vdu_volumes")
1547 if vdu_instantiation_volumes_list
:
1548 # Find the root volumes and add to the disk_list
1549 persistent_root_disk
= Ns
.find_persistent_root_volumes(
1550 vnfd
, target_vdu
, vdu_instantiation_volumes_list
, disk_list
1553 # Find the ordinary volumes which are not added to the persistent_root_disk
1554 # and put them to the disk list
1555 Ns
.find_persistent_volumes(
1556 persistent_root_disk
,
1558 vdu_instantiation_volumes_list
,
1563 # Vdu_instantiation_volumes_list is empty
1564 # First get add the persistent root disks to disk_list
1565 Ns
._add
_persistent
_root
_disk
_to
_disk
_list
(
1566 vnfd
, target_vdu
, persistent_root_disk
, disk_list
1568 # Add the persistent non-root disks to disk_list
1569 Ns
._add
_persistent
_ordinary
_disks
_to
_disk
_list
(
1570 target_vdu
, persistent_root_disk
, persistent_ordinary_disk
, disk_list
1573 affinity_group_list
= Ns
._prepare
_vdu
_affinity
_group
_list
(
1574 target_vdu
, extra_dict
, ns_preffix
1577 extra_dict
["params"] = {
1578 "name": "{}-{}-{}-{}".format(
1579 indata
["name"][:16],
1580 vnfr
["member-vnf-index-ref"][:16],
1581 target_vdu
["vdu-name"][:32],
1582 target_vdu
.get("count-index") or 0,
1584 "description": target_vdu
["vdu-name"],
1586 "image_id": "TASK-" + image_text
,
1587 "flavor_id": "TASK-" + flavor_text
,
1588 "affinity_group_list": affinity_group_list
,
1589 "net_list": net_list
,
1590 "cloud_config": cloud_config
or None,
1591 "disk_list": disk_list
,
1592 "availability_zone_index": None, # TODO
1593 "availability_zone_list": None, # TODO
1599 def _process_affinity_group_params(
1600 target_affinity_group
: Dict
[str, Any
],
1601 indata
: Dict
[str, Any
],
1602 vim_info
: Dict
[str, Any
],
1603 target_record_id
: str,
1604 **kwargs
: Dict
[str, Any
],
1605 ) -> Dict
[str, Any
]:
1606 """Get affinity or anti-affinity group parameters.
1609 target_affinity_group (Dict[str, Any]): [description]
1610 indata (Dict[str, Any]): [description]
1611 vim_info (Dict[str, Any]): [description]
1612 target_record_id (str): [description]
1615 Dict[str, Any]: [description]
1619 affinity_group_data
= {
1620 "name": target_affinity_group
["name"],
1621 "type": target_affinity_group
["type"],
1622 "scope": target_affinity_group
["scope"],
1625 if target_affinity_group
.get("vim-affinity-group-id"):
1626 affinity_group_data
["vim-affinity-group-id"] = target_affinity_group
[
1627 "vim-affinity-group-id"
1630 extra_dict
["params"] = {
1631 "affinity_group_data": affinity_group_data
,
1637 def _process_recreate_vdu_params(
1638 existing_vdu
: Dict
[str, Any
],
1639 db_nsr
: Dict
[str, Any
],
1640 vim_info
: Dict
[str, Any
],
1641 target_record_id
: str,
1643 **kwargs
: Dict
[str, Any
],
1644 ) -> Dict
[str, Any
]:
1645 """Function to process VDU parameters to recreate.
1648 existing_vdu (Dict[str, Any]): [description]
1649 db_nsr (Dict[str, Any]): [description]
1650 vim_info (Dict[str, Any]): [description]
1651 target_record_id (str): [description]
1652 target_id (str): [description]
1655 Dict[str, Any]: [description]
1657 vnfr
= kwargs
.get("vnfr")
1658 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1659 # logger = kwargs.get("logger")
1660 db
= kwargs
.get("db")
1661 fs
= kwargs
.get("fs")
1662 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1668 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
1669 if vim_details_text
:
1670 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
1672 for iface_index
, interface
in enumerate(existing_vdu
["interfaces"]):
1673 if "port-security-enabled" in interface
:
1674 interface
["port_security"] = interface
.pop("port-security-enabled")
1676 if "port-security-disable-strategy" in interface
:
1677 interface
["port_security_disable_strategy"] = interface
.pop(
1678 "port-security-disable-strategy"
1683 for x
, v
in interface
.items()
1689 "port_security_disable_strategy",
1693 existing_ifaces
= existing_vdu
["vim_info"][target_id
].get(
1694 "interfaces_backup", []
1699 for i
in existing_ifaces
1700 if i
["ip_address"] == interface
["ip-address"]
1705 net_item
["net_id"] = net_id
1706 net_item
["type"] = "virtual"
1708 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1709 # TODO floating_ip: True/False (or it can be None)
1710 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1711 net_item
["use"] = "data"
1712 net_item
["model"] = interface
["type"]
1713 net_item
["type"] = interface
["type"]
1715 interface
.get("type") == "OM-MGMT"
1716 or interface
.get("mgmt-interface")
1717 or interface
.get("mgmt-vnf")
1719 net_item
["use"] = "mgmt"
1721 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1722 net_item
["use"] = "bridge"
1723 net_item
["model"] = interface
.get("type")
1725 if interface
.get("ip-address"):
1726 net_item
["ip_address"] = interface
["ip-address"]
1728 if interface
.get("mac-address"):
1729 net_item
["mac_address"] = interface
["mac-address"]
1731 net_list
.append(net_item
)
1733 if interface
.get("mgmt-vnf"):
1734 extra_dict
["mgmt_vnf_interface"] = iface_index
1735 elif interface
.get("mgmt-interface"):
1736 extra_dict
["mgmt_vdu_interface"] = iface_index
1741 if existing_vdu
.get("cloud-init"):
1742 if existing_vdu
["cloud-init"] not in vdu2cloud_init
:
1743 vdu2cloud_init
[existing_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1746 location
=existing_vdu
["cloud-init"],
1749 cloud_content_
= vdu2cloud_init
[existing_vdu
["cloud-init"]]
1750 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1751 cloud_init_content
=cloud_content_
,
1752 params
=existing_vdu
.get("additionalParams"),
1753 context
=existing_vdu
["cloud-init"],
1756 if existing_vdu
.get("boot-data-drive"):
1757 cloud_config
["boot-data-drive"] = existing_vdu
.get("boot-data-drive")
1761 if existing_vdu
.get("ssh-keys"):
1762 ssh_keys
+= existing_vdu
.get("ssh-keys")
1764 if existing_vdu
.get("ssh-access-required"):
1765 ssh_keys
.append(ro_nsr_public_key
)
1768 cloud_config
["key-pairs"] = ssh_keys
1771 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
1772 disk_list
.append({"vim_id": vol_id
["id"]})
1774 affinity_group_list
= []
1776 if existing_vdu
.get("affinity-or-anti-affinity-group-id"):
1778 for affinity_group_id
in existing_vdu
["affinity-or-anti-affinity-group-id"]:
1779 for group
in db_nsr
.get("affinity-or-anti-affinity-group"):
1781 group
["id"] == affinity_group_id
1782 and group
["vim_info"][target_id
].get("vim_id", None) is not None
1784 affinity_group
["affinity_group_id"] = group
["vim_info"][
1786 ].get("vim_id", None)
1787 affinity_group_list
.append(affinity_group
)
1789 extra_dict
["params"] = {
1790 "name": "{}-{}-{}-{}".format(
1791 db_nsr
["name"][:16],
1792 vnfr
["member-vnf-index-ref"][:16],
1793 existing_vdu
["vdu-name"][:32],
1794 existing_vdu
.get("count-index") or 0,
1796 "description": existing_vdu
["vdu-name"],
1798 "image_id": vim_details
["image"]["id"],
1799 "flavor_id": vim_details
["flavor"]["id"],
1800 "affinity_group_list": affinity_group_list
,
1801 "net_list": net_list
,
1802 "cloud_config": cloud_config
or None,
1803 "disk_list": disk_list
,
1804 "availability_zone_index": None, # TODO
1805 "availability_zone_list": None, # TODO
1810 def calculate_diff_items(
1817 tasks_by_target_record_id
,
1824 """Function that returns the incremental changes (creation, deletion)
1825 related to a specific item `item` to be done. This function should be
1826 called for NS instantiation, NS termination, NS update to add a new VNF
1827 or a new VLD, remove a VNF or VLD, etc.
1828 Item can be `net`, `flavor`, `image` or `vdu`.
1829 It takes a list of target items from indata (which came from the REST API)
1830 and compares with the existing items from db_ro_nsr, identifying the
1831 incremental changes to be done. During the comparison, it calls the method
1832 `process_params` (which was passed as parameter, and is particular for each
1836 indata (Dict[str, Any]): deployment info
1837 db_nsr: NSR record from DB
1838 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1839 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1840 item (str): element to process (net, vdu...)
1841 tasks_by_target_record_id (Dict[str, Any]):
1842 [<target_record_id>, <task>]
1843 action_id (str): action id
1844 nsr_id (str): NSR id
1845 task_index (number): task index to add to task name
1846 vnfr_id (str): VNFR id
1847 vnfr (Dict[str, Any]): VNFR info
1850 List: list with the incremental changes (deletes, creates) for each item
1851 number: current task index
1859 process_params
= None
1860 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1861 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1863 # According to the type of item, the path, the target_list,
1864 # the existing_list and the method to process params are set
1865 db_path
= self
.db_path_map
[item
]
1866 process_params
= self
.process_params_function_map
[item
]
1867 if item
in ("net", "vdu"):
1868 # This case is specific for the NS VLD (not applied to VDU)
1870 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1871 target_list
= indata
.get("ns", []).get(db_path
, [])
1872 existing_list
= db_nsr
.get(db_path
, [])
1873 # This case is common for VNF VLDs and VNF VDUs
1875 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
1877 (vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
),
1880 target_list
= target_vnf
.get(db_path
, []) if target_vnf
else []
1881 existing_list
= vnfr
.get(db_path
, [])
1882 elif item
in ("image", "flavor", "affinity-or-anti-affinity-group"):
1883 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1884 target_list
= indata
.get(item
, [])
1885 existing_list
= db_nsr
.get(item
, [])
1887 raise NsException("Item not supported: {}", item
)
1889 # ensure all the target_list elements has an "id". If not assign the index as id
1890 if target_list
is None:
1892 for target_index
, tl
in enumerate(target_list
):
1893 if tl
and not tl
.get("id"):
1894 tl
["id"] = str(target_index
)
1896 # step 1 items (networks,vdus,...) to be deleted/updated
1897 for item_index
, existing_item
in enumerate(existing_list
):
1899 (t
for t
in target_list
if t
["id"] == existing_item
["id"]),
1903 for target_vim
, existing_viminfo
in existing_item
.get(
1906 if existing_viminfo
is None:
1910 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
1912 target_viminfo
= None
1914 if target_viminfo
is None:
1916 self
._assign
_vim
(target_vim
)
1917 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
1920 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
1921 # item must be sdn-net instead of net if target_vim is a sdn
1923 target_record_id
+= ".sdn"
1926 "action_id": action_id
,
1928 "task_index": task_index
,
1933 "deployment_info": deployment_info
,
1934 "target_id": target_vim
,
1937 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1938 "target_record_id": target_record_id
,
1943 # step 2 items (networks,vdus,...) to be created
1944 for target_item
in target_list
:
1947 for item_index
, existing_item
in enumerate(existing_list
):
1948 if existing_item
["id"] == target_item
["id"]:
1952 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1953 existing_list
.append(target_item
)
1954 existing_item
= None
1956 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
1957 existing_viminfo
= None
1960 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
1962 if existing_viminfo
is not None:
1965 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
1968 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
1969 # item must be sdn-net instead of net if target_vim is a sdn
1971 target_record_id
+= ".sdn"
1974 self
.logger
.warning(
1975 "ns.calculate_diff_items target_item={}".format(target_item
)
1977 if process_params
== Ns
._process
_flavor
_params
:
1983 self
.logger
.warning(
1984 "calculate_diff_items for flavor kwargs={}".format(kwargs
)
1987 if process_params
== Ns
._process
_vdu
_params
:
1988 self
.logger
.warning(
1989 "calculate_diff_items self.fs={}".format(self
.fs
)
1996 "vdu2cloud_init": vdu2cloud_init
,
1997 "tasks_by_target_record_id": tasks_by_target_record_id
,
1998 "logger": self
.logger
,
2001 "ro_nsr_public_key": ro_nsr_public_key
,
2004 self
.logger
.warning("calculate_diff_items kwargs={}".format(kwargs
))
2006 extra_dict
= process_params(
2013 self
._assign
_vim
(target_vim
)
2016 "action_id": action_id
,
2018 "task_index": task_index
,
2022 "deployment_info": deployment_info
,
2023 "target_id": target_vim
,
2026 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
2027 "target_record_id": target_record_id
,
2028 "extra_dict": extra_dict
,
2029 "common_id": target_item
.get("common_id", None),
2031 diff_items
.append(new_item
)
2032 tasks_by_target_record_id
[target_record_id
] = new_item
2035 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
2037 return diff_items
, task_index
2039 def calculate_all_differences_to_deploy(
2049 tasks_by_target_record_id
,
2051 """This method calculates the ordered list of items (`changes_list`)
2052 to be created and deleted.
2055 indata (Dict[str, Any]): deployment info
2056 nsr_id (str): NSR id
2057 db_nsr: NSR record from DB
2058 db_vnfrs: VNFRS record from DB
2059 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2060 db_nsr_update (Dict[str, Any]): NSR info to update in DB
2061 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
2062 action_id (str): action id
2063 tasks_by_target_record_id (Dict[str, Any]):
2064 [<target_record_id>, <task>]
2067 List: ordered list of items to be created and deleted.
2071 # set list with diffs:
2074 # NS vld, image and flavor
2075 for item
in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
2076 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
2077 diff_items
, task_index
= self
.calculate_diff_items(
2080 db_ro_nsr
=db_ro_nsr
,
2081 db_nsr_update
=db_nsr_update
,
2083 tasks_by_target_record_id
=tasks_by_target_record_id
,
2084 action_id
=action_id
,
2086 task_index
=task_index
,
2089 changes_list
+= diff_items
2092 for vnfr_id
, vnfr
in db_vnfrs
.items():
2093 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
2094 for item
in ["net", "vdu"]:
2095 self
.logger
.debug("process VNF={} {}".format(vnfr_id
, item
))
2096 diff_items
, task_index
= self
.calculate_diff_items(
2099 db_ro_nsr
=db_ro_nsr
,
2100 db_nsr_update
=db_vnfrs_update
[vnfr
["_id"]],
2102 tasks_by_target_record_id
=tasks_by_target_record_id
,
2103 action_id
=action_id
,
2105 task_index
=task_index
,
2109 changes_list
+= diff_items
2113 def define_all_tasks(
2117 tasks_by_target_record_id
,
2119 """Function to create all the task structures obtanied from
2120 the method calculate_all_differences_to_deploy
2123 changes_list (List): ordered list of items to be created or deleted
2124 db_new_tasks (List): tasks list to be created
2125 action_id (str): action id
2126 tasks_by_target_record_id (Dict[str, Any]):
2127 [<target_record_id>, <task>]
2131 for change
in changes_list
:
2132 task
= Ns
._create
_task
(
2133 deployment_info
=change
["deployment_info"],
2134 target_id
=change
["target_id"],
2135 item
=change
["item"],
2136 action
=change
["action"],
2137 target_record
=change
["target_record"],
2138 target_record_id
=change
["target_record_id"],
2139 extra_dict
=change
.get("extra_dict", None),
2142 self
.logger
.warning("ns.define_all_tasks task={}".format(task
))
2143 tasks_by_target_record_id
[change
["target_record_id"]] = task
2144 db_new_tasks
.append(task
)
2146 if change
.get("common_id"):
2147 task
["common_id"] = change
["common_id"]
2149 def upload_all_tasks(
2154 """Function to save all tasks in the common DB
2157 db_new_tasks (List): tasks list to be created
2158 now (time): current time
2162 nb_ro_tasks
= 0 # for logging
2164 for db_task
in db_new_tasks
:
2165 target_id
= db_task
.pop("target_id")
2166 common_id
= db_task
.get("common_id")
2168 # Do not chek tasks with vim_status DELETED
2169 # because in manual heealing there are two tasks for the same vdur:
2170 # one with vim_status deleted and the other one with the actual VM status.
2176 "target_id": target_id
,
2177 "tasks.common_id": common_id
,
2178 "vim_info.vim_status.ne": "DELETED",
2180 update_dict
={"to_check_at": now
, "modified_at": now
},
2181 push
={"tasks": db_task
},
2182 fail_on_empty
=False,
2186 if not self
.db
.set_one(
2189 "target_id": target_id
,
2190 "tasks.target_record": db_task
["target_record"],
2191 "vim_info.vim_status.ne": "DELETED",
2193 update_dict
={"to_check_at": now
, "modified_at": now
},
2194 push
={"tasks": db_task
},
2195 fail_on_empty
=False,
2198 self
.logger
.debug("Updating database, Creating ro_tasks")
2199 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2201 self
.db
.create("ro_tasks", db_ro_task
)
2204 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2205 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2209 def upload_recreate_tasks(
2214 """Function to save recreate tasks in the common DB
2217 db_new_tasks (List): tasks list to be created
2218 now (time): current time
2222 nb_ro_tasks
= 0 # for logging
2224 for db_task
in db_new_tasks
:
2225 target_id
= db_task
.pop("target_id")
2226 self
.logger
.warning("target_id={} db_task={}".format(target_id
, db_task
))
2228 action
= db_task
.get("action", None)
2231 self
.logger
.debug("Updating database, Creating ro_tasks")
2232 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2234 # If DELETE task: the associated created items should be removed
2235 # (except persistent volumes):
2236 if action
== "DELETE":
2237 db_ro_task
["vim_info"]["created"] = True
2238 db_ro_task
["vim_info"]["created_items"] = db_task
.get(
2241 db_ro_task
["vim_info"]["volumes_to_hold"] = db_task
.get(
2242 "volumes_to_hold", []
2244 db_ro_task
["vim_info"]["vim_id"] = db_task
.get("vim_id", None)
2247 self
.logger
.warning("upload_all_tasks db_ro_task={}".format(db_ro_task
))
2248 self
.db
.create("ro_tasks", db_ro_task
)
2251 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2252 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2256 def _prepare_created_items_for_healing(
2262 # Get created_items from ro_task
2263 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2264 for ro_task
in ro_tasks
:
2265 for task
in ro_task
["tasks"]:
2267 task
["target_record"] == target_record
2268 and task
["action"] == "CREATE"
2269 and ro_task
["vim_info"]["created_items"]
2271 created_items
= ro_task
["vim_info"]["created_items"]
2274 return created_items
2276 def _prepare_persistent_volumes_for_healing(
2281 # The associated volumes of the VM shouldn't be removed
2284 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
2285 if vim_details_text
:
2286 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
2288 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
2289 volumes_list
.append(vol_id
["id"])
2293 def prepare_changes_to_recreate(
2301 tasks_by_target_record_id
,
2303 """This method will obtain an ordered list of items (`changes_list`)
2304 to be created and deleted to meet the recreate request.
2308 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id
, indata
)
2312 # set list with diffs:
2314 db_path
= self
.db_path_map
["vdu"]
2315 target_list
= indata
.get("healVnfData", {})
2316 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
2317 ro_nsr_public_key
= db_ro_nsr
["public_key"]
2319 # Check each VNF of the target
2320 for target_vnf
in target_list
:
2321 # Find this VNF in the list from DB, raise exception if vnfInstanceId is not found
2322 vnfr_id
= target_vnf
["vnfInstanceId"]
2323 existing_vnf
= db_vnfrs
.get(vnfr_id
)
2324 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
2325 # vim_account_id = existing_vnf.get("vim-account-id", "")
2327 target_vdus
= target_vnf
.get("additionalParams", {}).get("vdu", [])
2328 # Check each VDU of this VNF
2330 # Create target_vdu_list from DB, if VDUs are not specified
2332 for existing_vdu
in existing_vnf
.get("vdur"):
2333 vdu_name
= existing_vdu
.get("vdu-name", None)
2334 vdu_index
= existing_vdu
.get("count-index", 0)
2335 vdu_to_be_healed
= {"vdu-id": vdu_name
, "count-index": vdu_index
}
2336 target_vdus
.append(vdu_to_be_healed
)
2337 for target_vdu
in target_vdus
:
2338 vdu_name
= target_vdu
.get("vdu-id", None)
2339 # For multi instance VDU count-index is mandatory
2340 # For single session VDU count-indes is 0
2341 count_index
= target_vdu
.get("count-index", 0)
2343 existing_instance
= None
2344 for instance
in existing_vnf
.get("vdur", None):
2346 instance
["vdu-name"] == vdu_name
2347 and instance
["count-index"] == count_index
2349 existing_instance
= instance
2354 target_record_id
= "{}.{}".format(db_record
, existing_instance
["id"])
2356 # The target VIM is the one already existing in DB to recreate
2357 for target_vim
, target_viminfo
in existing_instance
.get(
2360 # step 1 vdu to be deleted
2361 self
._assign
_vim
(target_vim
)
2363 "action_id": action_id
,
2365 "task_index": task_index
,
2368 target_record
= f
"{db_record}.{item_index}.vim_info.{target_vim}"
2369 created_items
= self
._prepare
_created
_items
_for
_healing
(
2370 nsr_id
, target_record
2373 volumes_to_hold
= self
._prepare
_persistent
_volumes
_for
_healing
(
2374 target_vim
, existing_instance
2377 # Specific extra params for recreate tasks:
2379 "created_items": created_items
,
2380 "vim_id": existing_instance
["vim-id"],
2381 "volumes_to_hold": volumes_to_hold
,
2384 changes_list
.append(
2386 "deployment_info": deployment_info
,
2387 "target_id": target_vim
,
2390 "target_record": target_record
,
2391 "target_record_id": target_record_id
,
2392 "extra_dict": extra_dict
,
2395 delete_task_id
= f
"{action_id}:{task_index}"
2398 # step 2 vdu to be created
2404 "vnfr": existing_vnf
,
2405 "vdu2cloud_init": vdu2cloud_init
,
2406 "tasks_by_target_record_id": tasks_by_target_record_id
,
2407 "logger": self
.logger
,
2410 "ro_nsr_public_key": ro_nsr_public_key
,
2414 extra_dict
= self
._process
_recreate
_vdu
_params
(
2423 # The CREATE task depens on the DELETE task
2424 extra_dict
["depends_on"] = [delete_task_id
]
2426 # Add volumes created from created_items if any
2427 # Ports should be deleted with delete task and automatically created with create task
2429 for k
, v
in created_items
.items():
2431 k_item
, _
, k_id
= k
.partition(":")
2432 if k_item
== "volume":
2434 except Exception as e
:
2436 "Error evaluating created item {}: {}".format(k
, e
)
2438 extra_dict
["previous_created_volumes"] = volumes
2441 "action_id": action_id
,
2443 "task_index": task_index
,
2445 self
._assign
_vim
(target_vim
)
2448 "deployment_info": deployment_info
,
2449 "target_id": target_vim
,
2452 "target_record": target_record
,
2453 "target_record_id": target_record_id
,
2454 "extra_dict": extra_dict
,
2456 changes_list
.append(new_item
)
2457 tasks_by_target_record_id
[target_record_id
] = new_item
2462 def recreate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2463 self
.logger
.debug("ns.recreate nsr_id={} indata={}".format(nsr_id
, indata
))
2464 # TODO: validate_input(indata, recreate_schema)
2465 action_id
= indata
.get("action_id", str(uuid4()))
2466 # get current deployment
2467 db_vnfrs
= {} # vnf's info indexed by _id
2469 logging_text
= "Recreate nsr_id={} action_id={} indata={}".format(
2470 nsr_id
, action_id
, indata
2472 self
.logger
.debug(logging_text
+ "Enter")
2475 step
= "Getting ns and vnfr record from db"
2476 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2478 tasks_by_target_record_id
= {}
2479 # read from db: vnf's of this ns
2480 step
= "Getting vnfrs from db"
2481 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2482 self
.logger
.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list
))
2484 if not db_vnfrs_list
:
2485 raise NsException("Cannot obtain associated VNF for ns")
2487 for vnfr
in db_vnfrs_list
:
2488 db_vnfrs
[vnfr
["_id"]] = vnfr
2491 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2492 self
.logger
.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr
))
2495 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2497 with self
.write_lock
:
2499 step
= "process NS elements"
2500 changes_list
= self
.prepare_changes_to_recreate(
2505 db_ro_nsr
=db_ro_nsr
,
2506 action_id
=action_id
,
2507 tasks_by_target_record_id
=tasks_by_target_record_id
,
2510 self
.define_all_tasks(
2511 changes_list
=changes_list
,
2512 db_new_tasks
=db_new_tasks
,
2513 tasks_by_target_record_id
=tasks_by_target_record_id
,
2516 # Delete all ro_tasks registered for the targets vdurs (target_record)
2517 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2518 # So remove all task related to target record.
2519 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2520 for change
in changes_list
:
2521 for ro_task
in ro_tasks
:
2522 for task
in ro_task
["tasks"]:
2523 if task
["target_record"] == change
["target_record"]:
2527 "_id": ro_task
["_id"],
2528 "modified_at": ro_task
["modified_at"],
2530 fail_on_empty
=False,
2533 step
= "Updating database, Appending tasks to ro_tasks"
2534 self
.upload_recreate_tasks(
2535 db_new_tasks
=db_new_tasks
,
2540 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2544 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2548 except Exception as e
:
2549 if isinstance(e
, (DbException
, NsException
)):
2551 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2554 e
= traceback_format_exc()
2555 self
.logger
.critical(
2556 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2560 raise NsException(e
)
2562 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2563 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
2564 validate_input(indata
, deploy_schema
)
2565 action_id
= indata
.get("action_id", str(uuid4()))
2567 # get current deployment
2568 db_nsr_update
= {} # update operation on nsrs
2569 db_vnfrs_update
= {}
2570 db_vnfrs
= {} # vnf's info indexed by _id
2572 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2573 self
.logger
.debug(logging_text
+ "Enter")
2576 step
= "Getting ns and vnfr record from db"
2577 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2578 self
.logger
.debug("ns.deploy: db_nsr={}".format(db_nsr
))
2580 tasks_by_target_record_id
= {}
2581 # read from db: vnf's of this ns
2582 step
= "Getting vnfrs from db"
2583 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2585 if not db_vnfrs_list
:
2586 raise NsException("Cannot obtain associated VNF for ns")
2588 for vnfr
in db_vnfrs_list
:
2589 db_vnfrs
[vnfr
["_id"]] = vnfr
2590 db_vnfrs_update
[vnfr
["_id"]] = {}
2591 self
.logger
.debug("ns.deploy db_vnfrs={}".format(db_vnfrs
))
2594 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2597 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2599 # check that action_id is not in the list of actions. Suffixed with :index
2600 if action_id
in db_ro_nsr
["actions"]:
2604 new_action_id
= "{}:{}".format(action_id
, index
)
2606 if new_action_id
not in db_ro_nsr
["actions"]:
2607 action_id
= new_action_id
2610 + "Changing action_id in use to {}".format(action_id
)
2616 def _process_action(indata
):
2617 nonlocal db_new_tasks
2624 if indata
["action"]["action"] == "inject_ssh_key":
2625 key
= indata
["action"].get("key")
2626 user
= indata
["action"].get("user")
2627 password
= indata
["action"].get("password")
2629 for vnf
in indata
.get("vnf", ()):
2630 if vnf
["_id"] not in db_vnfrs
:
2631 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
2633 db_vnfr
= db_vnfrs
[vnf
["_id"]]
2635 for target_vdu
in vnf
.get("vdur", ()):
2636 vdu_index
, vdur
= next(
2639 for i_v
in enumerate(db_vnfr
["vdur"])
2640 if i_v
[1]["id"] == target_vdu
["id"]
2647 "Invalid vdu vnf={}.{}".format(
2648 vnf
["_id"], target_vdu
["id"]
2652 target_vim
, vim_info
= next(
2653 k_v
for k_v
in vdur
["vim_info"].items()
2655 self
._assign
_vim
(target_vim
)
2656 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
2657 vnf
["_id"], vdu_index
2661 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
2664 "ip_address": vdur
.get("ip-address"),
2667 "password": password
,
2668 "private_key": db_ro_nsr
["private_key"],
2669 "salt": db_ro_nsr
["_id"],
2670 "schema_version": db_ro_nsr
["_admin"][
2677 "action_id": action_id
,
2679 "task_index": task_index
,
2682 task
= Ns
._create
_task
(
2683 deployment_info
=deployment_info
,
2684 target_id
=target_vim
,
2687 target_record
=target_record
,
2688 target_record_id
=None,
2689 extra_dict
=extra_dict
,
2692 task_index
= deployment_info
.get("task_index")
2694 db_new_tasks
.append(task
)
2696 with self
.write_lock
:
2697 if indata
.get("action"):
2698 _process_action(indata
)
2700 # compute network differences
2702 step
= "process NS elements"
2703 changes_list
= self
.calculate_all_differences_to_deploy(
2708 db_ro_nsr
=db_ro_nsr
,
2709 db_nsr_update
=db_nsr_update
,
2710 db_vnfrs_update
=db_vnfrs_update
,
2711 action_id
=action_id
,
2712 tasks_by_target_record_id
=tasks_by_target_record_id
,
2714 self
.define_all_tasks(
2715 changes_list
=changes_list
,
2716 db_new_tasks
=db_new_tasks
,
2717 tasks_by_target_record_id
=tasks_by_target_record_id
,
2720 step
= "Updating database, Appending tasks to ro_tasks"
2721 self
.upload_all_tasks(
2722 db_new_tasks
=db_new_tasks
,
2726 step
= "Updating database, nsrs"
2728 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
2730 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
2732 step
= "Updating database, vnfrs={}".format(vnfr_id
)
2733 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
2736 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2740 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2744 except Exception as e
:
2745 if isinstance(e
, (DbException
, NsException
)):
2747 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2750 e
= traceback_format_exc()
2751 self
.logger
.critical(
2752 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2756 raise NsException(e
)
2758 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2759 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
2760 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2762 with self
.write_lock
:
2764 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
2765 except NsWorkerException
as e
:
2766 raise NsException(e
)
2768 return None, None, True
2770 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2772 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2773 version
, nsr_id
, action_id
, indata
2779 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
2780 global_status
= "DONE"
2783 for ro_task
in ro_tasks
:
2784 for task
in ro_task
["tasks"]:
2785 if task
and task
["action_id"] == action_id
:
2786 task_list
.append(task
)
2789 if task
["status"] == "FAILED":
2790 global_status
= "FAILED"
2791 error_text
= "Error at {} {}: {}".format(
2792 task
["action"].lower(),
2794 ro_task
["vim_info"].get("vim_message") or "unknown",
2796 details
.append(error_text
)
2797 elif task
["status"] in ("SCHEDULED", "BUILD"):
2798 if global_status
!= "FAILED":
2799 global_status
= "BUILD"
2804 "status": global_status
,
2805 "details": ". ".join(details
)
2807 else "progress {}/{}".format(done
, total
),
2809 "action_id": action_id
,
2813 return return_data
, None, True
2815 def recreate_status(
2816 self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
2818 return self
.status(session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
)
2820 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2822 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2823 session
, indata
, version
, nsr_id
, action_id
2827 return None, None, True
2829 def rebuild_start_stop_task(
2840 self
._assign
_vim
(target_vim
)
2841 target_record
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_index
)
2842 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_id
)
2844 "action_id": action_id
,
2846 "task_index": task_index
,
2849 task
= Ns
._create
_task
(
2850 deployment_info
=deployment_info
,
2851 target_id
=target_vim
,
2854 target_record
=target_record
,
2855 target_record_id
=target_record_id
,
2856 extra_dict
=extra_dict
,
2860 def rebuild_start_stop(
2861 self
, session
, action_dict
, version
, nsr_id
, *args
, **kwargs
2866 action_id
= action_dict
.get("action_id", str(uuid4()))
2868 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2869 self
.logger
.debug(logging_text
+ "Enter")
2871 action
= list(action_dict
.keys())[0]
2872 task_dict
= action_dict
.get(action
)
2873 vim_vm_id
= action_dict
.get(action
).get("vim_vm_id")
2875 if action_dict
.get("stop"):
2879 step
= "lock the operation & do task creation"
2880 with self
.write_lock
:
2881 extra_dict
["params"] = {
2882 "vim_vm_id": vim_vm_id
,
2885 task
= self
.rebuild_start_stop_task(
2886 task_dict
["vdu_id"],
2887 task_dict
["vnf_id"],
2888 task_dict
["vdu_index"],
2892 task_dict
["target_vim"],
2895 db_new_tasks
.append(task
)
2896 step
= "upload Task to db"
2897 self
.upload_all_tasks(
2898 db_new_tasks
=db_new_tasks
,
2902 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2905 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2909 except Exception as e
:
2910 if isinstance(e
, (DbException
, NsException
)):
2912 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2915 e
= traceback_format_exc()
2916 self
.logger
.critical(
2917 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2920 raise NsException(e
)
2922 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2923 nsrs
= self
.db
.get_list("nsrs", {})
2927 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
2929 return return_data
, None, True
2931 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2932 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2935 for ro_task
in ro_tasks
:
2936 for task
in ro_task
["tasks"]:
2937 if task
["action_id"] not in return_data
:
2938 return_data
.append(task
["action_id"])
2940 return return_data
, None, True
2943 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
2945 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
2946 self
._assign
_vim
(target_vim
)
2947 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
2948 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
2950 "action_id": action_id
,
2952 "task_index": task_index
,
2955 task
= Ns
._create
_task
(
2956 deployment_info
=deployment_info
,
2957 target_id
=target_vim
,
2960 target_record
=target_record
,
2961 target_record_id
=target_record_id
,
2962 extra_dict
=extra_dict
,
2967 def migrate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2971 action_id
= indata
.get("action_id", str(uuid4()))
2973 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2974 self
.logger
.debug(logging_text
+ "Enter")
2976 vnf_instance_id
= indata
["vnfInstanceId"]
2977 step
= "Getting vnfrs from db"
2978 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
2979 vdu
= indata
.get("vdu")
2980 migrateToHost
= indata
.get("migrateToHost")
2983 with self
.write_lock
:
2985 vdu_id
= indata
["vdu"]["vduId"]
2986 vdu_count_index
= indata
["vdu"].get("vduCountIndex", 0)
2987 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2989 vdu
["vdu-id-ref"] == vdu_id
2990 and vdu
["count-index"] == vdu_count_index
2992 extra_dict
["params"] = {
2993 "vim_vm_id": vdu
["vim-id"],
2994 "migrate_host": migrateToHost
,
2995 "vdu_vim_info": vdu
["vim_info"],
2997 step
= "Creating migration task for vdu:{}".format(vdu
)
2998 task
= self
.migrate_task(
3007 db_new_tasks
.append(task
)
3011 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3012 extra_dict
["params"] = {
3013 "vim_vm_id": vdu
["vim-id"],
3014 "migrate_host": migrateToHost
,
3015 "vdu_vim_info": vdu
["vim_info"],
3017 step
= "Creating migration task for vdu:{}".format(vdu
)
3018 task
= self
.migrate_task(
3027 db_new_tasks
.append(task
)
3030 self
.upload_all_tasks(
3031 db_new_tasks
=db_new_tasks
,
3036 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3039 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3043 except Exception as e
:
3044 if isinstance(e
, (DbException
, NsException
)):
3046 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3049 e
= traceback_format_exc()
3050 self
.logger
.critical(
3051 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3054 raise NsException(e
)
3056 def verticalscale_task(
3057 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
3059 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
3060 self
._assign
_vim
(target_vim
)
3061 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
3062 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
3064 "action_id": action_id
,
3066 "task_index": task_index
,
3069 task
= Ns
._create
_task
(
3070 deployment_info
=deployment_info
,
3071 target_id
=target_vim
,
3072 item
="verticalscale",
3074 target_record
=target_record
,
3075 target_record_id
=target_record_id
,
3076 extra_dict
=extra_dict
,
3080 def verticalscale(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3084 action_id
= indata
.get("action_id", str(uuid4()))
3086 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
3087 self
.logger
.debug(logging_text
+ "Enter")
3089 VnfFlavorData
= indata
.get("changeVnfFlavorData")
3090 vnf_instance_id
= VnfFlavorData
["vnfInstanceId"]
3091 step
= "Getting vnfrs from db"
3092 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
3093 vduid
= VnfFlavorData
["additionalParams"]["vduid"]
3094 vduCountIndex
= VnfFlavorData
["additionalParams"]["vduCountIndex"]
3095 virtualMemory
= VnfFlavorData
["additionalParams"]["virtualMemory"]
3096 numVirtualCpu
= VnfFlavorData
["additionalParams"]["numVirtualCpu"]
3097 sizeOfStorage
= VnfFlavorData
["additionalParams"]["sizeOfStorage"]
3099 "name": vduid
+ "-flv",
3100 "ram": virtualMemory
,
3101 "vcpus": numVirtualCpu
,
3102 "disk": sizeOfStorage
,
3105 step
= "Creating Tasks for vertical scaling"
3106 with self
.write_lock
:
3107 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3109 vdu
["vdu-id-ref"] == vduid
3110 and vdu
["count-index"] == vduCountIndex
3112 extra_dict
["params"] = {
3113 "vim_vm_id": vdu
["vim-id"],
3114 "flavor_dict": flavor_dict
,
3116 task
= self
.verticalscale_task(
3125 db_new_tasks
.append(task
)
3128 self
.upload_all_tasks(
3129 db_new_tasks
=db_new_tasks
,
3133 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3136 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3140 except Exception as e
:
3141 if isinstance(e
, (DbException
, NsException
)):
3143 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3146 e
= traceback_format_exc()
3147 self
.logger
.critical(
3148 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3151 raise NsException(e
)