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 _ip_profile_to_ro(
867 ip_profile
: Dict
[str, Any
],
872 ip_profile (Dict[str, Any]): [description]
875 Dict[str, Any]: [description]
882 if "v4" in ip_profile
.get("ip-version", "ipv4")
884 "subnet_address": ip_profile
.get("subnet-address"),
885 "gateway_address": ip_profile
.get("gateway-address"),
886 "dhcp_enabled": ip_profile
.get("dhcp-params", {}).get("enabled", False),
887 "dhcp_start_address": ip_profile
.get("dhcp-params", {}).get(
888 "start-address", None
890 "dhcp_count": ip_profile
.get("dhcp-params", {}).get("count", None),
893 if ip_profile
.get("dns-server"):
894 ro_ip_profile
["dns_address"] = ";".join(
895 [v
["address"] for v
in ip_profile
["dns-server"] if v
.get("address")]
898 if ip_profile
.get("security-group"):
899 ro_ip_profile
["security_group"] = ip_profile
["security-group"]
904 def _process_net_params(
905 target_vld
: Dict
[str, Any
],
906 indata
: Dict
[str, Any
],
907 vim_info
: Dict
[str, Any
],
908 target_record_id
: str,
909 **kwargs
: Dict
[str, Any
],
911 """Function to process network parameters.
914 target_vld (Dict[str, Any]): [description]
915 indata (Dict[str, Any]): [description]
916 vim_info (Dict[str, Any]): [description]
917 target_record_id (str): [description]
920 Dict[str, Any]: [description]
924 if vim_info
.get("sdn"):
925 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
926 # ns_preffix = "nsrs:{}".format(nsr_id)
927 # remove the ending ".sdn
928 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
929 extra_dict
["params"] = {
931 for k
in ("sdn-ports", "target_vim", "vlds", "type")
935 # TODO needed to add target_id in the dependency.
936 if vim_info
.get("target_vim"):
937 extra_dict
["depends_on"] = [
938 f
"{vim_info.get('target_vim')} {vld_target_record_id}"
943 if vim_info
.get("vim_network_name"):
944 extra_dict
["find_params"] = {
946 "name": vim_info
.get("vim_network_name"),
949 elif vim_info
.get("vim_network_id"):
950 extra_dict
["find_params"] = {
952 "id": vim_info
.get("vim_network_id"),
955 elif target_vld
.get("mgmt-network") and not vim_info
.get("provider_network"):
956 extra_dict
["find_params"] = {
958 "name": target_vld
["id"],
962 extra_dict
["params"] = {
964 f
"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
966 "ip_profile": Ns
._ip
_profile
_to
_ro
(vim_info
.get("ip_profile")),
967 "provider_network_profile": vim_info
.get("provider_network"),
970 if not target_vld
.get("underlay"):
971 extra_dict
["params"]["net_type"] = "bridge"
973 extra_dict
["params"]["net_type"] = (
974 "ptp" if target_vld
.get("type") == "ELINE" else "data"
980 def find_persistent_root_volumes(
983 vdu_instantiation_volumes_list
: list,
986 """Find the persistent root volumes and add them to the disk_list
987 by parsing the instantiation parameters.
990 vnfd (dict): VNF descriptor
991 target_vdu (dict): processed VDU
992 vdu_instantiation_volumes_list (list): instantiation parameters for the each VDU as a list
993 disk_list (list): to be filled up
996 persistent_root_disk (dict): Details of persistent root disk
999 persistent_root_disk
= {}
1000 # There can be only one root disk, when we find it, it will return the result
1002 for vdu
, vsd
in product(
1003 vnfd
.get("vdu", ()), vnfd
.get("virtual-storage-desc", ())
1006 vdu
["name"] == target_vdu
["vdu-name"]
1007 and vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]
1011 root_disk
.get("type-of-storage")
1012 == "persistent-storage:persistent-storage"
1014 for vdu_volume
in vdu_instantiation_volumes_list
:
1017 vdu_volume
["vim-volume-id"]
1018 and root_disk
["id"] == vdu_volume
["name"]
1021 persistent_root_disk
[vsd
["id"]] = {
1022 "vim_volume_id": vdu_volume
["vim-volume-id"],
1023 "image_id": vdu
.get("sw-image-desc"),
1026 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1028 return persistent_root_disk
1032 if root_disk
.get("size-of-storage"):
1033 persistent_root_disk
[vsd
["id"]] = {
1034 "image_id": vdu
.get("sw-image-desc"),
1035 "size": root_disk
.get("size-of-storage"),
1036 "keep": Ns
.is_volume_keeping_required(root_disk
),
1039 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1041 return persistent_root_disk
1044 def find_persistent_volumes(
1045 persistent_root_disk
: dict,
1047 vdu_instantiation_volumes_list
: list,
1050 """Find the ordinary persistent volumes and add them to the disk_list
1051 by parsing the instantiation parameters.
1054 persistent_root_disk: persistent root disk dictionary
1055 target_vdu: processed VDU
1056 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1057 disk_list: to be filled up
1060 # Find the ordinary volumes which are not added to the persistent_root_disk
1061 persistent_disk
= {}
1062 for disk
in target_vdu
.get("virtual-storages", {}):
1064 disk
.get("type-of-storage") == "persistent-storage:persistent-storage"
1065 and disk
["id"] not in persistent_root_disk
.keys()
1067 for vdu_volume
in vdu_instantiation_volumes_list
:
1069 if vdu_volume
["vim-volume-id"] and disk
["id"] == vdu_volume
["name"]:
1071 persistent_disk
[disk
["id"]] = {
1072 "vim_volume_id": vdu_volume
["vim-volume-id"],
1074 disk_list
.append(persistent_disk
[disk
["id"]])
1077 if disk
["id"] not in persistent_disk
.keys():
1078 persistent_disk
[disk
["id"]] = {
1079 "size": disk
.get("size-of-storage"),
1080 "keep": Ns
.is_volume_keeping_required(disk
),
1082 disk_list
.append(persistent_disk
[disk
["id"]])
1085 def is_volume_keeping_required(virtual_storage_desc
: Dict
[str, Any
]) -> bool:
1086 """Function to decide keeping persistent volume
1090 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1096 if not virtual_storage_desc
.get("vdu-storage-requirements"):
1098 for item
in virtual_storage_desc
.get("vdu-storage-requirements", {}):
1099 if item
.get("key") == "keep-volume" and item
.get("value") == "true":
1104 def _sort_vdu_interfaces(target_vdu
: dict) -> None:
1105 """Sort the interfaces according to position number.
1108 target_vdu (dict): Details of VDU to be created
1111 # If the position info is provided for all the interfaces, it will be sorted
1112 # according to position number ascendingly.
1113 sorted_interfaces
= sorted(
1114 target_vdu
["interfaces"],
1115 key
=lambda x
: (x
.get("position") is None, x
.get("position")),
1117 target_vdu
["interfaces"] = sorted_interfaces
1120 def _partially_locate_vdu_interfaces(target_vdu
: dict) -> None:
1121 """Only place the interfaces which has specific position.
1124 target_vdu (dict): Details of VDU to be created
1127 # If the position info is provided for some interfaces but not all of them, the interfaces
1128 # which has specific position numbers will be placed and others' positions will not be taken care.
1130 i
.get("position") + 1
1131 for i
in target_vdu
["interfaces"]
1132 if i
.get("position") is not None
1134 n
= len(target_vdu
["interfaces"])
1135 sorted_interfaces
= [-1] * n
1139 if target_vdu
["interfaces"][k
].get("position") is not None:
1140 if any(i
.get("position") == 0 for i
in target_vdu
["interfaces"]):
1141 idx
= target_vdu
["interfaces"][k
]["position"] + 1
1143 idx
= target_vdu
["interfaces"][k
]["position"]
1144 sorted_interfaces
[idx
- 1] = target_vdu
["interfaces"][k
]
1148 if target_vdu
["interfaces"][m
].get("position") is None:
1149 idy
= sorted_interfaces
.index(-1)
1150 sorted_interfaces
[idy
] = target_vdu
["interfaces"][m
]
1153 target_vdu
["interfaces"] = sorted_interfaces
1156 def _prepare_vdu_cloud_init(
1157 target_vdu
: dict, vdu2cloud_init
: dict, db
: object, fs
: object
1159 """Fill cloud_config dict with cloud init details.
1162 target_vdu (dict): Details of VDU to be created
1163 vdu2cloud_init (dict): Cloud init dict
1164 db (object): DB object
1165 fs (object): FS object
1168 cloud_config (dict): Cloud config details of VDU
1174 if target_vdu
.get("cloud-init"):
1175 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1176 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1179 location
=target_vdu
["cloud-init"],
1182 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1183 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1184 cloud_init_content
=cloud_content_
,
1185 params
=target_vdu
.get("additionalParams"),
1186 context
=target_vdu
["cloud-init"],
1189 if target_vdu
.get("boot-data-drive"):
1190 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1195 def _check_vld_information_of_interfaces(
1196 interface
: dict, ns_preffix
: str, vnf_preffix
: str
1198 """Prepare the net_text by the virtual link information for vnf and ns level.
1200 interface (dict): Interface details
1201 ns_preffix (str): Prefix of NS
1202 vnf_preffix (str): Prefix of VNF
1205 net_text (str): information of net
1209 if interface
.get("ns-vld-id"):
1210 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
1211 elif interface
.get("vnf-vld-id"):
1212 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
1217 def _prepare_interface_port_security(interface
: dict) -> None:
1221 interface (dict): Interface details
1224 if "port-security-enabled" in interface
:
1225 interface
["port_security"] = interface
.pop("port-security-enabled")
1227 if "port-security-disable-strategy" in interface
:
1228 interface
["port_security_disable_strategy"] = interface
.pop(
1229 "port-security-disable-strategy"
1233 def _create_net_item_of_interface(interface
: dict, net_text
: str) -> dict:
1234 """Prepare net item including name, port security, floating ip etc.
1237 interface (dict): Interface details
1238 net_text (str): information of net
1241 net_item (dict): Dict including net details
1247 for x
, v
in interface
.items()
1253 "port_security_disable_strategy",
1257 net_item
["net_id"] = "TASK-" + net_text
1258 net_item
["type"] = "virtual"
1263 def _prepare_type_of_interface(
1264 interface
: dict, tasks_by_target_record_id
: dict, net_text
: str, net_item
: dict
1266 """Fill the net item type by interface type such as SR-IOV, OM-MGMT, bridge etc.
1269 interface (dict): Interface details
1270 tasks_by_target_record_id (dict): Task details
1271 net_text (str): information of net
1272 net_item (dict): Dict including net details
1275 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1276 # TODO floating_ip: True/False (or it can be None)
1278 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1279 # Mark the net create task as type data
1281 tasks_by_target_record_id
,
1287 tasks_by_target_record_id
[net_text
]["extra_dict"]["params"][
1291 net_item
["use"] = "data"
1292 net_item
["model"] = interface
["type"]
1293 net_item
["type"] = interface
["type"]
1296 interface
.get("type") == "OM-MGMT"
1297 or interface
.get("mgmt-interface")
1298 or interface
.get("mgmt-vnf")
1300 net_item
["use"] = "mgmt"
1303 # If interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1304 net_item
["use"] = "bridge"
1305 net_item
["model"] = interface
.get("type")
1308 def _prepare_vdu_interfaces(
1314 tasks_by_target_record_id
: dict,
1317 """Prepare the net_item and add net_list, add mgmt interface to extra_dict.
1320 target_vdu (dict): VDU to be created
1321 extra_dict (dict): Dictionary to be filled
1322 ns_preffix (str): NS prefix as string
1323 vnf_preffix (str): VNF prefix as string
1324 logger (object): Logger Object
1325 tasks_by_target_record_id (dict): Task details
1326 net_list (list): Net list of VDU
1328 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
1330 net_text
= Ns
._check
_vld
_information
_of
_interfaces
(
1331 interface
, ns_preffix
, vnf_preffix
1334 # Interface not connected to any vld
1336 "Interface {} from vdu {} not connected to any vld".format(
1337 iface_index
, target_vdu
["vdu-name"]
1342 extra_dict
["depends_on"].append(net_text
)
1344 Ns
._prepare
_interface
_port
_security
(interface
)
1346 net_item
= Ns
._create
_net
_item
_of
_interface
(interface
, net_text
)
1348 Ns
._prepare
_type
_of
_interface
(
1349 interface
, tasks_by_target_record_id
, net_text
, net_item
1352 if interface
.get("ip-address"):
1353 net_item
["ip_address"] = interface
["ip-address"]
1355 if interface
.get("mac-address"):
1356 net_item
["mac_address"] = interface
["mac-address"]
1358 net_list
.append(net_item
)
1360 if interface
.get("mgmt-vnf"):
1361 extra_dict
["mgmt_vnf_interface"] = iface_index
1362 elif interface
.get("mgmt-interface"):
1363 extra_dict
["mgmt_vdu_interface"] = iface_index
1366 def _prepare_vdu_ssh_keys(
1367 target_vdu
: dict, ro_nsr_public_key
: dict, cloud_config
: dict
1369 """Add ssh keys to cloud config.
1372 target_vdu (dict): Details of VDU to be created
1373 ro_nsr_public_key (dict): RO NSR public Key
1374 cloud_config (dict): Cloud config details
1379 if target_vdu
.get("ssh-keys"):
1380 ssh_keys
+= target_vdu
.get("ssh-keys")
1382 if target_vdu
.get("ssh-access-required"):
1383 ssh_keys
.append(ro_nsr_public_key
)
1386 cloud_config
["key-pairs"] = ssh_keys
1389 def _select_persistent_root_disk(vsd
: dict, vdu
: dict) -> dict:
1390 """Selects the persistent root disk if exists.
1392 vsd (dict): Virtual storage descriptors in VNFD
1393 vdu (dict): VNF descriptor
1396 root_disk (dict): Selected persistent root disk
1398 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
1402 ) == "persistent-storage:persistent-storage" and root_disk
.get(
1408 def _add_persistent_root_disk_to_disk_list(
1409 vnfd
: dict, target_vdu
: dict, persistent_root_disk
: dict, disk_list
: list
1411 """Find the persistent root disk and add to disk list.
1414 vnfd (dict): VNF descriptor
1415 target_vdu (dict): Details of VDU to be created
1416 persistent_root_disk (dict): Details of persistent root disk
1417 disk_list (list): Disks of VDU
1420 for vdu
in vnfd
.get("vdu", ()):
1421 if vdu
["name"] == target_vdu
["vdu-name"]:
1422 for vsd
in vnfd
.get("virtual-storage-desc", ()):
1423 root_disk
= Ns
._select
_persistent
_root
_disk
(vsd
, vdu
)
1427 persistent_root_disk
[vsd
["id"]] = {
1428 "image_id": vdu
.get("sw-image-desc"),
1429 "size": root_disk
["size-of-storage"],
1430 "keep": Ns
.is_volume_keeping_required(root_disk
),
1433 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1437 def _add_persistent_ordinary_disks_to_disk_list(
1439 persistent_root_disk
: dict,
1440 persistent_ordinary_disk
: dict,
1443 """Fill the disk list by adding persistent ordinary disks.
1446 target_vdu (dict): Details of VDU to be created
1447 persistent_root_disk (dict): Details of persistent root disk
1448 persistent_ordinary_disk (dict): Details of persistent ordinary disk
1449 disk_list (list): Disks of VDU
1452 if target_vdu
.get("virtual-storages"):
1453 for disk
in target_vdu
["virtual-storages"]:
1455 disk
.get("type-of-storage")
1456 == "persistent-storage:persistent-storage"
1457 and disk
["id"] not in persistent_root_disk
.keys()
1459 persistent_ordinary_disk
[disk
["id"]] = {
1460 "size": disk
["size-of-storage"],
1461 "keep": Ns
.is_volume_keeping_required(disk
),
1463 disk_list
.append(persistent_ordinary_disk
[disk
["id"]])
1466 def _prepare_vdu_affinity_group_list(
1467 target_vdu
: dict, extra_dict
: dict, ns_preffix
: str
1468 ) -> List
[Dict
[str, any
]]:
1469 """Process affinity group details to prepare affinity group list.
1472 target_vdu (dict): Details of VDU to be created
1473 extra_dict (dict): Dictionary to be filled
1474 ns_preffix (str): Prefix as string
1478 affinity_group_list (list): Affinity group details
1481 affinity_group_list
= []
1483 if target_vdu
.get("affinity-or-anti-affinity-group-id"):
1484 for affinity_group_id
in target_vdu
["affinity-or-anti-affinity-group-id"]:
1486 affinity_group_text
= (
1487 ns_preffix
+ ":affinity-or-anti-affinity-group." + affinity_group_id
1490 if not isinstance(extra_dict
.get("depends_on"), list):
1491 raise NsException("Invalid extra_dict format.")
1493 extra_dict
["depends_on"].append(affinity_group_text
)
1494 affinity_group
["affinity_group_id"] = "TASK-" + affinity_group_text
1495 affinity_group_list
.append(affinity_group
)
1497 return affinity_group_list
1500 def _process_vdu_params(
1501 target_vdu
: Dict
[str, Any
],
1502 indata
: Dict
[str, Any
],
1503 vim_info
: Dict
[str, Any
],
1504 target_record_id
: str,
1505 **kwargs
: Dict
[str, Any
],
1506 ) -> Dict
[str, Any
]:
1507 """Function to process VDU parameters.
1510 target_vdu (Dict[str, Any]): [description]
1511 indata (Dict[str, Any]): [description]
1512 vim_info (Dict[str, Any]): [description]
1513 target_record_id (str): [description]
1516 Dict[str, Any]: [description]
1518 vnfr_id
= kwargs
.get("vnfr_id")
1519 nsr_id
= kwargs
.get("nsr_id")
1520 vnfr
= kwargs
.get("vnfr")
1521 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1522 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
1523 logger
= kwargs
.get("logger")
1524 db
= kwargs
.get("db")
1525 fs
= kwargs
.get("fs")
1526 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1528 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
1529 ns_preffix
= "nsrs:{}".format(nsr_id
)
1530 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
1531 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
1532 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
1535 persistent_root_disk
= {}
1536 persistent_ordinary_disk
= {}
1537 vdu_instantiation_volumes_list
= []
1539 vnfd_id
= vnfr
["vnfd-id"]
1540 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
1542 # If the position info is provided for all the interfaces, it will be sorted
1543 # according to position number ascendingly.
1545 True if i
.get("position") is not None else False
1546 for i
in target_vdu
["interfaces"]
1549 Ns
._sort
_vdu
_interfaces
(target_vdu
)
1551 # If the position info is provided for some interfaces but not all of them, the interfaces
1552 # which has specific position numbers will be placed and others' positions will not be taken care.
1555 Ns
._partially
_locate
_vdu
_interfaces
(target_vdu
)
1557 # If the position info is not provided for the interfaces, interfaces will be attached
1558 # according to the order in the VNFD.
1559 Ns
._prepare
_vdu
_interfaces
(
1565 tasks_by_target_record_id
,
1570 cloud_config
= Ns
._prepare
_vdu
_cloud
_init
(target_vdu
, vdu2cloud_init
, db
, fs
)
1572 # Prepare VDU ssh keys
1573 Ns
._prepare
_vdu
_ssh
_keys
(target_vdu
, ro_nsr_public_key
, cloud_config
)
1575 if target_vdu
.get("additionalParams"):
1576 vdu_instantiation_volumes_list
= (
1577 target_vdu
.get("additionalParams").get("OSM").get("vdu_volumes")
1580 if vdu_instantiation_volumes_list
:
1582 # Find the root volumes and add to the disk_list
1583 persistent_root_disk
= Ns
.find_persistent_root_volumes(
1584 vnfd
, target_vdu
, vdu_instantiation_volumes_list
, disk_list
1587 # Find the ordinary volumes which are not added to the persistent_root_disk
1588 # and put them to the disk list
1589 Ns
.find_persistent_volumes(
1590 persistent_root_disk
,
1592 vdu_instantiation_volumes_list
,
1597 # Vdu_instantiation_volumes_list is empty
1598 # First get add the persistent root disks to disk_list
1599 Ns
._add
_persistent
_root
_disk
_to
_disk
_list
(
1600 vnfd
, target_vdu
, persistent_root_disk
, disk_list
1602 # Add the persistent non-root disks to disk_list
1603 Ns
._add
_persistent
_ordinary
_disks
_to
_disk
_list
(
1604 target_vdu
, persistent_root_disk
, persistent_ordinary_disk
, disk_list
1607 affinity_group_list
= Ns
._prepare
_vdu
_affinity
_group
_list
(
1608 target_vdu
, extra_dict
, ns_preffix
1611 extra_dict
["params"] = {
1612 "name": "{}-{}-{}-{}".format(
1613 indata
["name"][:16],
1614 vnfr
["member-vnf-index-ref"][:16],
1615 target_vdu
["vdu-name"][:32],
1616 target_vdu
.get("count-index") or 0,
1618 "description": target_vdu
["vdu-name"],
1620 "image_id": "TASK-" + image_text
,
1621 "flavor_id": "TASK-" + flavor_text
,
1622 "affinity_group_list": affinity_group_list
,
1623 "net_list": net_list
,
1624 "cloud_config": cloud_config
or None,
1625 "disk_list": disk_list
,
1626 "availability_zone_index": None, # TODO
1627 "availability_zone_list": None, # TODO
1633 def _process_affinity_group_params(
1634 target_affinity_group
: Dict
[str, Any
],
1635 indata
: Dict
[str, Any
],
1636 vim_info
: Dict
[str, Any
],
1637 target_record_id
: str,
1638 **kwargs
: Dict
[str, Any
],
1639 ) -> Dict
[str, Any
]:
1640 """Get affinity or anti-affinity group parameters.
1643 target_affinity_group (Dict[str, Any]): [description]
1644 indata (Dict[str, Any]): [description]
1645 vim_info (Dict[str, Any]): [description]
1646 target_record_id (str): [description]
1649 Dict[str, Any]: [description]
1653 affinity_group_data
= {
1654 "name": target_affinity_group
["name"],
1655 "type": target_affinity_group
["type"],
1656 "scope": target_affinity_group
["scope"],
1659 if target_affinity_group
.get("vim-affinity-group-id"):
1660 affinity_group_data
["vim-affinity-group-id"] = target_affinity_group
[
1661 "vim-affinity-group-id"
1664 extra_dict
["params"] = {
1665 "affinity_group_data": affinity_group_data
,
1671 def _process_recreate_vdu_params(
1672 existing_vdu
: Dict
[str, Any
],
1673 db_nsr
: Dict
[str, Any
],
1674 vim_info
: Dict
[str, Any
],
1675 target_record_id
: str,
1677 **kwargs
: Dict
[str, Any
],
1678 ) -> Dict
[str, Any
]:
1679 """Function to process VDU parameters to recreate.
1682 existing_vdu (Dict[str, Any]): [description]
1683 db_nsr (Dict[str, Any]): [description]
1684 vim_info (Dict[str, Any]): [description]
1685 target_record_id (str): [description]
1686 target_id (str): [description]
1689 Dict[str, Any]: [description]
1691 vnfr
= kwargs
.get("vnfr")
1692 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1693 # logger = kwargs.get("logger")
1694 db
= kwargs
.get("db")
1695 fs
= kwargs
.get("fs")
1696 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1702 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
1703 if vim_details_text
:
1704 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
1706 for iface_index
, interface
in enumerate(existing_vdu
["interfaces"]):
1708 if "port-security-enabled" in interface
:
1709 interface
["port_security"] = interface
.pop("port-security-enabled")
1711 if "port-security-disable-strategy" in interface
:
1712 interface
["port_security_disable_strategy"] = interface
.pop(
1713 "port-security-disable-strategy"
1718 for x
, v
in interface
.items()
1724 "port_security_disable_strategy",
1728 existing_ifaces
= existing_vdu
["vim_info"][target_id
].get(
1729 "interfaces_backup", []
1734 for i
in existing_ifaces
1735 if i
["ip_address"] == interface
["ip-address"]
1740 net_item
["net_id"] = net_id
1741 net_item
["type"] = "virtual"
1743 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1744 # TODO floating_ip: True/False (or it can be None)
1745 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1746 net_item
["use"] = "data"
1747 net_item
["model"] = interface
["type"]
1748 net_item
["type"] = interface
["type"]
1750 interface
.get("type") == "OM-MGMT"
1751 or interface
.get("mgmt-interface")
1752 or interface
.get("mgmt-vnf")
1754 net_item
["use"] = "mgmt"
1756 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1757 net_item
["use"] = "bridge"
1758 net_item
["model"] = interface
.get("type")
1760 if interface
.get("ip-address"):
1761 net_item
["ip_address"] = interface
["ip-address"]
1763 if interface
.get("mac-address"):
1764 net_item
["mac_address"] = interface
["mac-address"]
1766 net_list
.append(net_item
)
1768 if interface
.get("mgmt-vnf"):
1769 extra_dict
["mgmt_vnf_interface"] = iface_index
1770 elif interface
.get("mgmt-interface"):
1771 extra_dict
["mgmt_vdu_interface"] = iface_index
1776 if existing_vdu
.get("cloud-init"):
1777 if existing_vdu
["cloud-init"] not in vdu2cloud_init
:
1778 vdu2cloud_init
[existing_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1781 location
=existing_vdu
["cloud-init"],
1784 cloud_content_
= vdu2cloud_init
[existing_vdu
["cloud-init"]]
1785 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1786 cloud_init_content
=cloud_content_
,
1787 params
=existing_vdu
.get("additionalParams"),
1788 context
=existing_vdu
["cloud-init"],
1791 if existing_vdu
.get("boot-data-drive"):
1792 cloud_config
["boot-data-drive"] = existing_vdu
.get("boot-data-drive")
1796 if existing_vdu
.get("ssh-keys"):
1797 ssh_keys
+= existing_vdu
.get("ssh-keys")
1799 if existing_vdu
.get("ssh-access-required"):
1800 ssh_keys
.append(ro_nsr_public_key
)
1803 cloud_config
["key-pairs"] = ssh_keys
1806 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
1807 disk_list
.append({"vim_id": vol_id
["id"]})
1809 affinity_group_list
= []
1811 if existing_vdu
.get("affinity-or-anti-affinity-group-id"):
1813 for affinity_group_id
in existing_vdu
["affinity-or-anti-affinity-group-id"]:
1814 for group
in db_nsr
.get("affinity-or-anti-affinity-group"):
1816 group
["id"] == affinity_group_id
1817 and group
["vim_info"][target_id
].get("vim_id", None) is not None
1819 affinity_group
["affinity_group_id"] = group
["vim_info"][
1821 ].get("vim_id", None)
1822 affinity_group_list
.append(affinity_group
)
1824 extra_dict
["params"] = {
1825 "name": "{}-{}-{}-{}".format(
1826 db_nsr
["name"][:16],
1827 vnfr
["member-vnf-index-ref"][:16],
1828 existing_vdu
["vdu-name"][:32],
1829 existing_vdu
.get("count-index") or 0,
1831 "description": existing_vdu
["vdu-name"],
1833 "image_id": vim_details
["image"]["id"],
1834 "flavor_id": vim_details
["flavor"]["id"],
1835 "affinity_group_list": affinity_group_list
,
1836 "net_list": net_list
,
1837 "cloud_config": cloud_config
or None,
1838 "disk_list": disk_list
,
1839 "availability_zone_index": None, # TODO
1840 "availability_zone_list": None, # TODO
1845 def calculate_diff_items(
1852 tasks_by_target_record_id
,
1859 """Function that returns the incremental changes (creation, deletion)
1860 related to a specific item `item` to be done. This function should be
1861 called for NS instantiation, NS termination, NS update to add a new VNF
1862 or a new VLD, remove a VNF or VLD, etc.
1863 Item can be `net`, `flavor`, `image` or `vdu`.
1864 It takes a list of target items from indata (which came from the REST API)
1865 and compares with the existing items from db_ro_nsr, identifying the
1866 incremental changes to be done. During the comparison, it calls the method
1867 `process_params` (which was passed as parameter, and is particular for each
1871 indata (Dict[str, Any]): deployment info
1872 db_nsr: NSR record from DB
1873 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1874 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1875 item (str): element to process (net, vdu...)
1876 tasks_by_target_record_id (Dict[str, Any]):
1877 [<target_record_id>, <task>]
1878 action_id (str): action id
1879 nsr_id (str): NSR id
1880 task_index (number): task index to add to task name
1881 vnfr_id (str): VNFR id
1882 vnfr (Dict[str, Any]): VNFR info
1885 List: list with the incremental changes (deletes, creates) for each item
1886 number: current task index
1894 process_params
= None
1895 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1896 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1898 # According to the type of item, the path, the target_list,
1899 # the existing_list and the method to process params are set
1900 db_path
= self
.db_path_map
[item
]
1901 process_params
= self
.process_params_function_map
[item
]
1902 if item
in ("net", "vdu"):
1903 # This case is specific for the NS VLD (not applied to VDU)
1905 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1906 target_list
= indata
.get("ns", []).get(db_path
, [])
1907 existing_list
= db_nsr
.get(db_path
, [])
1908 # This case is common for VNF VLDs and VNF VDUs
1910 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
1912 (vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
),
1915 target_list
= target_vnf
.get(db_path
, []) if target_vnf
else []
1916 existing_list
= vnfr
.get(db_path
, [])
1917 elif item
in ("image", "flavor", "affinity-or-anti-affinity-group"):
1918 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1919 target_list
= indata
.get(item
, [])
1920 existing_list
= db_nsr
.get(item
, [])
1922 raise NsException("Item not supported: {}", item
)
1924 # ensure all the target_list elements has an "id". If not assign the index as id
1925 if target_list
is None:
1927 for target_index
, tl
in enumerate(target_list
):
1928 if tl
and not tl
.get("id"):
1929 tl
["id"] = str(target_index
)
1931 # step 1 items (networks,vdus,...) to be deleted/updated
1932 for item_index
, existing_item
in enumerate(existing_list
):
1934 (t
for t
in target_list
if t
["id"] == existing_item
["id"]),
1938 for target_vim
, existing_viminfo
in existing_item
.get(
1941 if existing_viminfo
is None:
1945 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
1947 target_viminfo
= None
1949 if target_viminfo
is None:
1951 self
._assign
_vim
(target_vim
)
1952 target_record_id
= "{}.{}".format(db_record
, existing_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"
1961 "action_id": action_id
,
1963 "task_index": task_index
,
1968 "deployment_info": deployment_info
,
1969 "target_id": target_vim
,
1972 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1973 "target_record_id": target_record_id
,
1978 # step 2 items (networks,vdus,...) to be created
1979 for target_item
in target_list
:
1982 for item_index
, existing_item
in enumerate(existing_list
):
1983 if existing_item
["id"] == target_item
["id"]:
1987 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1988 existing_list
.append(target_item
)
1989 existing_item
= None
1991 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
1992 existing_viminfo
= None
1995 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
1997 if existing_viminfo
is not None:
2000 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
2003 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
2004 # item must be sdn-net instead of net if target_vim is a sdn
2006 target_record_id
+= ".sdn"
2010 "ns.calculate_diff_items target_item={}".format(target_item
)
2012 if process_params
== Ns
._process
_flavor
_params
:
2019 "calculate_diff_items for flavor kwargs={}".format(kwargs
)
2022 if process_params
== Ns
._process
_vdu
_params
:
2023 self
.logger
.debug("calculate_diff_items self.fs={}".format(self
.fs
))
2029 "vdu2cloud_init": vdu2cloud_init
,
2030 "tasks_by_target_record_id": tasks_by_target_record_id
,
2031 "logger": self
.logger
,
2034 "ro_nsr_public_key": ro_nsr_public_key
,
2037 self
.logger
.debug("calculate_diff_items kwargs={}".format(kwargs
))
2039 extra_dict
= process_params(
2046 self
._assign
_vim
(target_vim
)
2049 "action_id": action_id
,
2051 "task_index": task_index
,
2055 "deployment_info": deployment_info
,
2056 "target_id": target_vim
,
2059 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
2060 "target_record_id": target_record_id
,
2061 "extra_dict": extra_dict
,
2062 "common_id": target_item
.get("common_id", None),
2064 diff_items
.append(new_item
)
2065 tasks_by_target_record_id
[target_record_id
] = new_item
2068 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
2070 return diff_items
, task_index
2072 def calculate_all_differences_to_deploy(
2082 tasks_by_target_record_id
,
2084 """This method calculates the ordered list of items (`changes_list`)
2085 to be created and deleted.
2088 indata (Dict[str, Any]): deployment info
2089 nsr_id (str): NSR id
2090 db_nsr: NSR record from DB
2091 db_vnfrs: VNFRS record from DB
2092 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2093 db_nsr_update (Dict[str, Any]): NSR info to update in DB
2094 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
2095 action_id (str): action id
2096 tasks_by_target_record_id (Dict[str, Any]):
2097 [<target_record_id>, <task>]
2100 List: ordered list of items to be created and deleted.
2104 # set list with diffs:
2107 # NS vld, image and flavor
2108 for item
in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
2109 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
2110 diff_items
, task_index
= self
.calculate_diff_items(
2113 db_ro_nsr
=db_ro_nsr
,
2114 db_nsr_update
=db_nsr_update
,
2116 tasks_by_target_record_id
=tasks_by_target_record_id
,
2117 action_id
=action_id
,
2119 task_index
=task_index
,
2122 changes_list
+= diff_items
2125 for vnfr_id
, vnfr
in db_vnfrs
.items():
2126 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
2127 for item
in ["net", "vdu"]:
2128 self
.logger
.debug("process VNF={} {}".format(vnfr_id
, item
))
2129 diff_items
, task_index
= self
.calculate_diff_items(
2132 db_ro_nsr
=db_ro_nsr
,
2133 db_nsr_update
=db_vnfrs_update
[vnfr
["_id"]],
2135 tasks_by_target_record_id
=tasks_by_target_record_id
,
2136 action_id
=action_id
,
2138 task_index
=task_index
,
2142 changes_list
+= diff_items
2146 def define_all_tasks(
2150 tasks_by_target_record_id
,
2152 """Function to create all the task structures obtanied from
2153 the method calculate_all_differences_to_deploy
2156 changes_list (List): ordered list of items to be created or deleted
2157 db_new_tasks (List): tasks list to be created
2158 action_id (str): action id
2159 tasks_by_target_record_id (Dict[str, Any]):
2160 [<target_record_id>, <task>]
2164 for change
in changes_list
:
2165 task
= Ns
._create
_task
(
2166 deployment_info
=change
["deployment_info"],
2167 target_id
=change
["target_id"],
2168 item
=change
["item"],
2169 action
=change
["action"],
2170 target_record
=change
["target_record"],
2171 target_record_id
=change
["target_record_id"],
2172 extra_dict
=change
.get("extra_dict", None),
2175 self
.logger
.debug("ns.define_all_tasks task={}".format(task
))
2176 tasks_by_target_record_id
[change
["target_record_id"]] = task
2177 db_new_tasks
.append(task
)
2179 if change
.get("common_id"):
2180 task
["common_id"] = change
["common_id"]
2182 def upload_all_tasks(
2187 """Function to save all tasks in the common DB
2190 db_new_tasks (List): tasks list to be created
2191 now (time): current time
2195 nb_ro_tasks
= 0 # for logging
2197 for db_task
in db_new_tasks
:
2198 target_id
= db_task
.pop("target_id")
2199 common_id
= db_task
.get("common_id")
2201 # Do not chek tasks with vim_status DELETED
2202 # because in manual heealing there are two tasks for the same vdur:
2203 # one with vim_status deleted and the other one with the actual VM status.
2209 "target_id": target_id
,
2210 "tasks.common_id": common_id
,
2211 "vim_info.vim_status.ne": "DELETED",
2213 update_dict
={"to_check_at": now
, "modified_at": now
},
2214 push
={"tasks": db_task
},
2215 fail_on_empty
=False,
2219 if not self
.db
.set_one(
2222 "target_id": target_id
,
2223 "tasks.target_record": db_task
["target_record"],
2224 "vim_info.vim_status.ne": "DELETED",
2226 update_dict
={"to_check_at": now
, "modified_at": now
},
2227 push
={"tasks": db_task
},
2228 fail_on_empty
=False,
2231 self
.logger
.debug("Updating database, Creating ro_tasks")
2232 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2234 self
.db
.create("ro_tasks", db_ro_task
)
2237 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2238 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2242 def upload_recreate_tasks(
2247 """Function to save recreate tasks in the common DB
2250 db_new_tasks (List): tasks list to be created
2251 now (time): current time
2255 nb_ro_tasks
= 0 # for logging
2257 for db_task
in db_new_tasks
:
2258 target_id
= db_task
.pop("target_id")
2259 self
.logger
.debug("target_id={} db_task={}".format(target_id
, db_task
))
2261 action
= db_task
.get("action", None)
2264 self
.logger
.debug("Updating database, Creating ro_tasks")
2265 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2267 # If DELETE task: the associated created items should be removed
2268 # (except persistent volumes):
2269 if action
== "DELETE":
2270 db_ro_task
["vim_info"]["created"] = True
2271 db_ro_task
["vim_info"]["created_items"] = db_task
.get(
2274 db_ro_task
["vim_info"]["volumes_to_hold"] = db_task
.get(
2275 "volumes_to_hold", []
2277 db_ro_task
["vim_info"]["vim_id"] = db_task
.get("vim_id", None)
2280 self
.logger
.debug("upload_all_tasks db_ro_task={}".format(db_ro_task
))
2281 self
.db
.create("ro_tasks", db_ro_task
)
2284 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2285 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2289 def _prepare_created_items_for_healing(
2295 # Get created_items from ro_task
2296 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2297 for ro_task
in ro_tasks
:
2298 for task
in ro_task
["tasks"]:
2300 task
["target_record"] == target_record
2301 and task
["action"] == "CREATE"
2302 and ro_task
["vim_info"]["created_items"]
2304 created_items
= ro_task
["vim_info"]["created_items"]
2307 return created_items
2309 def _prepare_persistent_volumes_for_healing(
2314 # The associated volumes of the VM shouldn't be removed
2317 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
2318 if vim_details_text
:
2319 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
2321 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
2322 volumes_list
.append(vol_id
["id"])
2326 def prepare_changes_to_recreate(
2334 tasks_by_target_record_id
,
2336 """This method will obtain an ordered list of items (`changes_list`)
2337 to be created and deleted to meet the recreate request.
2341 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id
, indata
)
2345 # set list with diffs:
2347 db_path
= self
.db_path_map
["vdu"]
2348 target_list
= indata
.get("healVnfData", {})
2349 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
2350 ro_nsr_public_key
= db_ro_nsr
["public_key"]
2352 # Check each VNF of the target
2353 for target_vnf
in target_list
:
2354 # Find this VNF in the list from DB
2355 vnfr_id
= target_vnf
.get("vnfInstanceId", None)
2357 existing_vnf
= db_vnfrs
.get(vnfr_id
)
2358 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
2359 # vim_account_id = existing_vnf.get("vim-account-id", "")
2361 # Check each VDU of this VNF
2362 for target_vdu
in target_vnf
["additionalParams"].get("vdu", None):
2363 vdu_name
= target_vdu
.get("vdu-id", None)
2364 # For multi instance VDU count-index is mandatory
2365 # For single session VDU count-indes is 0
2366 count_index
= target_vdu
.get("count-index", 0)
2368 existing_instance
= None
2369 for instance
in existing_vnf
.get("vdur", None):
2371 instance
["vdu-name"] == vdu_name
2372 and instance
["count-index"] == count_index
2374 existing_instance
= instance
2379 target_record_id
= "{}.{}".format(db_record
, existing_instance
["id"])
2381 # The target VIM is the one already existing in DB to recreate
2382 for target_vim
, target_viminfo
in existing_instance
.get(
2385 # step 1 vdu to be deleted
2386 self
._assign
_vim
(target_vim
)
2388 "action_id": action_id
,
2390 "task_index": task_index
,
2393 target_record
= f
"{db_record}.{item_index}.vim_info.{target_vim}"
2394 created_items
= self
._prepare
_created
_items
_for
_healing
(
2395 nsr_id
, target_record
2398 volumes_to_hold
= self
._prepare
_persistent
_volumes
_for
_healing
(
2399 target_vim
, existing_instance
2402 # Specific extra params for recreate tasks:
2404 "created_items": created_items
,
2405 "vim_id": existing_instance
["vim-id"],
2406 "volumes_to_hold": volumes_to_hold
,
2409 changes_list
.append(
2411 "deployment_info": deployment_info
,
2412 "target_id": target_vim
,
2415 "target_record": target_record
,
2416 "target_record_id": target_record_id
,
2417 "extra_dict": extra_dict
,
2420 delete_task_id
= f
"{action_id}:{task_index}"
2423 # step 2 vdu to be created
2429 "vnfr": existing_vnf
,
2430 "vdu2cloud_init": vdu2cloud_init
,
2431 "tasks_by_target_record_id": tasks_by_target_record_id
,
2432 "logger": self
.logger
,
2435 "ro_nsr_public_key": ro_nsr_public_key
,
2439 extra_dict
= self
._process
_recreate
_vdu
_params
(
2448 # The CREATE task depens on the DELETE task
2449 extra_dict
["depends_on"] = [delete_task_id
]
2451 # Add volumes created from created_items if any
2452 # Ports should be deleted with delete task and automatically created with create task
2454 for k
, v
in created_items
.items():
2456 k_item
, _
, k_id
= k
.partition(":")
2457 if k_item
== "volume":
2459 except Exception as e
:
2461 "Error evaluating created item {}: {}".format(k
, e
)
2463 extra_dict
["previous_created_volumes"] = volumes
2466 "action_id": action_id
,
2468 "task_index": task_index
,
2470 self
._assign
_vim
(target_vim
)
2473 "deployment_info": deployment_info
,
2474 "target_id": target_vim
,
2477 "target_record": target_record
,
2478 "target_record_id": target_record_id
,
2479 "extra_dict": extra_dict
,
2481 changes_list
.append(new_item
)
2482 tasks_by_target_record_id
[target_record_id
] = new_item
2487 def recreate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2488 self
.logger
.debug("ns.recreate nsr_id={} indata={}".format(nsr_id
, indata
))
2489 # TODO: validate_input(indata, recreate_schema)
2490 action_id
= indata
.get("action_id", str(uuid4()))
2491 # get current deployment
2492 db_vnfrs
= {} # vnf's info indexed by _id
2494 logging_text
= "Recreate nsr_id={} action_id={} indata={}".format(
2495 nsr_id
, action_id
, indata
2497 self
.logger
.debug(logging_text
+ "Enter")
2500 step
= "Getting ns and vnfr record from db"
2501 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2503 tasks_by_target_record_id
= {}
2504 # read from db: vnf's of this ns
2505 step
= "Getting vnfrs from db"
2506 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2507 self
.logger
.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list
))
2509 if not db_vnfrs_list
:
2510 raise NsException("Cannot obtain associated VNF for ns")
2512 for vnfr
in db_vnfrs_list
:
2513 db_vnfrs
[vnfr
["_id"]] = vnfr
2516 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2517 self
.logger
.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr
))
2520 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2522 with self
.write_lock
:
2524 step
= "process NS elements"
2525 changes_list
= self
.prepare_changes_to_recreate(
2530 db_ro_nsr
=db_ro_nsr
,
2531 action_id
=action_id
,
2532 tasks_by_target_record_id
=tasks_by_target_record_id
,
2535 self
.define_all_tasks(
2536 changes_list
=changes_list
,
2537 db_new_tasks
=db_new_tasks
,
2538 tasks_by_target_record_id
=tasks_by_target_record_id
,
2541 # Delete all ro_tasks registered for the targets vdurs (target_record)
2542 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2543 # So remove all task related to target record.
2544 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2545 for change
in changes_list
:
2546 for ro_task
in ro_tasks
:
2547 for task
in ro_task
["tasks"]:
2548 if task
["target_record"] == change
["target_record"]:
2552 "_id": ro_task
["_id"],
2553 "modified_at": ro_task
["modified_at"],
2555 fail_on_empty
=False,
2558 step
= "Updating database, Appending tasks to ro_tasks"
2559 self
.upload_recreate_tasks(
2560 db_new_tasks
=db_new_tasks
,
2565 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2569 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2573 except Exception as e
:
2574 if isinstance(e
, (DbException
, NsException
)):
2576 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2579 e
= traceback_format_exc()
2580 self
.logger
.critical(
2581 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2585 raise NsException(e
)
2587 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2588 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
2589 validate_input(indata
, deploy_schema
)
2590 action_id
= indata
.get("action_id", str(uuid4()))
2592 # get current deployment
2593 db_nsr_update
= {} # update operation on nsrs
2594 db_vnfrs_update
= {}
2595 db_vnfrs
= {} # vnf's info indexed by _id
2597 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2598 self
.logger
.debug(logging_text
+ "Enter")
2601 step
= "Getting ns and vnfr record from db"
2602 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2603 self
.logger
.debug("ns.deploy: db_nsr={}".format(db_nsr
))
2605 tasks_by_target_record_id
= {}
2606 # read from db: vnf's of this ns
2607 step
= "Getting vnfrs from db"
2608 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2610 if not db_vnfrs_list
:
2611 raise NsException("Cannot obtain associated VNF for ns")
2613 for vnfr
in db_vnfrs_list
:
2614 db_vnfrs
[vnfr
["_id"]] = vnfr
2615 db_vnfrs_update
[vnfr
["_id"]] = {}
2616 self
.logger
.debug("ns.deploy db_vnfrs={}".format(db_vnfrs
))
2619 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2622 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2624 # check that action_id is not in the list of actions. Suffixed with :index
2625 if action_id
in db_ro_nsr
["actions"]:
2629 new_action_id
= "{}:{}".format(action_id
, index
)
2631 if new_action_id
not in db_ro_nsr
["actions"]:
2632 action_id
= new_action_id
2635 + "Changing action_id in use to {}".format(action_id
)
2641 def _process_action(indata
):
2642 nonlocal db_new_tasks
2649 if indata
["action"]["action"] == "inject_ssh_key":
2650 key
= indata
["action"].get("key")
2651 user
= indata
["action"].get("user")
2652 password
= indata
["action"].get("password")
2654 for vnf
in indata
.get("vnf", ()):
2655 if vnf
["_id"] not in db_vnfrs
:
2656 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
2658 db_vnfr
= db_vnfrs
[vnf
["_id"]]
2660 for target_vdu
in vnf
.get("vdur", ()):
2661 vdu_index
, vdur
= next(
2664 for i_v
in enumerate(db_vnfr
["vdur"])
2665 if i_v
[1]["id"] == target_vdu
["id"]
2672 "Invalid vdu vnf={}.{}".format(
2673 vnf
["_id"], target_vdu
["id"]
2677 target_vim
, vim_info
= next(
2678 k_v
for k_v
in vdur
["vim_info"].items()
2680 self
._assign
_vim
(target_vim
)
2681 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
2682 vnf
["_id"], vdu_index
2686 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
2689 "ip_address": vdur
.get("ip-address"),
2692 "password": password
,
2693 "private_key": db_ro_nsr
["private_key"],
2694 "salt": db_ro_nsr
["_id"],
2695 "schema_version": db_ro_nsr
["_admin"][
2702 "action_id": action_id
,
2704 "task_index": task_index
,
2707 task
= Ns
._create
_task
(
2708 deployment_info
=deployment_info
,
2709 target_id
=target_vim
,
2712 target_record
=target_record
,
2713 target_record_id
=None,
2714 extra_dict
=extra_dict
,
2717 task_index
= deployment_info
.get("task_index")
2719 db_new_tasks
.append(task
)
2721 with self
.write_lock
:
2722 if indata
.get("action"):
2723 _process_action(indata
)
2725 # compute network differences
2727 step
= "process NS elements"
2728 changes_list
= self
.calculate_all_differences_to_deploy(
2733 db_ro_nsr
=db_ro_nsr
,
2734 db_nsr_update
=db_nsr_update
,
2735 db_vnfrs_update
=db_vnfrs_update
,
2736 action_id
=action_id
,
2737 tasks_by_target_record_id
=tasks_by_target_record_id
,
2739 self
.define_all_tasks(
2740 changes_list
=changes_list
,
2741 db_new_tasks
=db_new_tasks
,
2742 tasks_by_target_record_id
=tasks_by_target_record_id
,
2745 step
= "Updating database, Appending tasks to ro_tasks"
2746 self
.upload_all_tasks(
2747 db_new_tasks
=db_new_tasks
,
2751 step
= "Updating database, nsrs"
2753 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
2755 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
2757 step
= "Updating database, vnfrs={}".format(vnfr_id
)
2758 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
2761 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2765 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2769 except Exception as e
:
2770 if isinstance(e
, (DbException
, NsException
)):
2772 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2775 e
= traceback_format_exc()
2776 self
.logger
.critical(
2777 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2781 raise NsException(e
)
2783 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2784 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
2785 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2787 with self
.write_lock
:
2789 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
2790 except NsWorkerException
as e
:
2791 raise NsException(e
)
2793 return None, None, True
2795 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2797 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2798 version
, nsr_id
, action_id
, indata
2804 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
2805 global_status
= "DONE"
2808 for ro_task
in ro_tasks
:
2809 for task
in ro_task
["tasks"]:
2810 if task
and task
["action_id"] == action_id
:
2811 task_list
.append(task
)
2814 if task
["status"] == "FAILED":
2815 global_status
= "FAILED"
2816 error_text
= "Error at {} {}: {}".format(
2817 task
["action"].lower(),
2819 ro_task
["vim_info"].get("vim_message") or "unknown",
2821 details
.append(error_text
)
2822 elif task
["status"] in ("SCHEDULED", "BUILD"):
2823 if global_status
!= "FAILED":
2824 global_status
= "BUILD"
2829 "status": global_status
,
2830 "details": ". ".join(details
)
2832 else "progress {}/{}".format(done
, total
),
2834 "action_id": action_id
,
2838 return return_data
, None, True
2840 def recreate_status(
2841 self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
2843 return self
.status(session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
)
2845 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2847 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2848 session
, indata
, version
, nsr_id
, action_id
2852 return None, None, True
2854 def rebuild_start_stop_task(
2865 self
._assign
_vim
(target_vim
)
2866 target_record
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_index
)
2867 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_id
)
2869 "action_id": action_id
,
2871 "task_index": task_index
,
2874 task
= Ns
._create
_task
(
2875 deployment_info
=deployment_info
,
2876 target_id
=target_vim
,
2879 target_record
=target_record
,
2880 target_record_id
=target_record_id
,
2881 extra_dict
=extra_dict
,
2885 def rebuild_start_stop(
2886 self
, session
, action_dict
, version
, nsr_id
, *args
, **kwargs
2891 action_id
= action_dict
.get("action_id", str(uuid4()))
2893 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2894 self
.logger
.debug(logging_text
+ "Enter")
2896 action
= list(action_dict
.keys())[0]
2897 task_dict
= action_dict
.get(action
)
2898 vim_vm_id
= action_dict
.get(action
).get("vim_vm_id")
2900 if action_dict
.get("stop"):
2904 step
= "lock the operation & do task creation"
2905 with self
.write_lock
:
2906 extra_dict
["params"] = {
2907 "vim_vm_id": vim_vm_id
,
2910 task
= self
.rebuild_start_stop_task(
2911 task_dict
["vdu_id"],
2912 task_dict
["vnf_id"],
2913 task_dict
["vdu_index"],
2917 task_dict
["target_vim"],
2920 db_new_tasks
.append(task
)
2921 step
= "upload Task to db"
2922 self
.upload_all_tasks(
2923 db_new_tasks
=db_new_tasks
,
2927 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2930 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2934 except Exception as e
:
2935 if isinstance(e
, (DbException
, NsException
)):
2937 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2940 e
= traceback_format_exc()
2941 self
.logger
.critical(
2942 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2945 raise NsException(e
)
2947 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2948 nsrs
= self
.db
.get_list("nsrs", {})
2952 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
2954 return return_data
, None, True
2956 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2957 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2960 for ro_task
in ro_tasks
:
2961 for task
in ro_task
["tasks"]:
2962 if task
["action_id"] not in return_data
:
2963 return_data
.append(task
["action_id"])
2965 return return_data
, None, True
2968 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
2970 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
2971 self
._assign
_vim
(target_vim
)
2972 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
2973 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
2975 "action_id": action_id
,
2977 "task_index": task_index
,
2980 task
= Ns
._create
_task
(
2981 deployment_info
=deployment_info
,
2982 target_id
=target_vim
,
2985 target_record
=target_record
,
2986 target_record_id
=target_record_id
,
2987 extra_dict
=extra_dict
,
2992 def migrate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2996 action_id
= indata
.get("action_id", str(uuid4()))
2998 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2999 self
.logger
.debug(logging_text
+ "Enter")
3001 vnf_instance_id
= indata
["vnfInstanceId"]
3002 step
= "Getting vnfrs from db"
3003 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
3004 vdu
= indata
.get("vdu")
3005 migrateToHost
= indata
.get("migrateToHost")
3008 with self
.write_lock
:
3010 vdu_id
= indata
["vdu"]["vduId"]
3011 vdu_count_index
= indata
["vdu"].get("vduCountIndex", 0)
3012 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3014 vdu
["vdu-id-ref"] == vdu_id
3015 and vdu
["count-index"] == vdu_count_index
3017 extra_dict
["params"] = {
3018 "vim_vm_id": vdu
["vim-id"],
3019 "migrate_host": migrateToHost
,
3020 "vdu_vim_info": vdu
["vim_info"],
3022 step
= "Creating migration task for vdu:{}".format(vdu
)
3023 task
= self
.migrate_task(
3032 db_new_tasks
.append(task
)
3037 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3038 extra_dict
["params"] = {
3039 "vim_vm_id": vdu
["vim-id"],
3040 "migrate_host": migrateToHost
,
3041 "vdu_vim_info": vdu
["vim_info"],
3043 step
= "Creating migration task for vdu:{}".format(vdu
)
3044 task
= self
.migrate_task(
3053 db_new_tasks
.append(task
)
3056 self
.upload_all_tasks(
3057 db_new_tasks
=db_new_tasks
,
3062 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3065 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3069 except Exception as e
:
3070 if isinstance(e
, (DbException
, NsException
)):
3072 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3075 e
= traceback_format_exc()
3076 self
.logger
.critical(
3077 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3080 raise NsException(e
)
3082 def verticalscale_task(
3083 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
3085 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
3086 self
._assign
_vim
(target_vim
)
3087 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
3088 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
3090 "action_id": action_id
,
3092 "task_index": task_index
,
3095 task
= Ns
._create
_task
(
3096 deployment_info
=deployment_info
,
3097 target_id
=target_vim
,
3098 item
="verticalscale",
3100 target_record
=target_record
,
3101 target_record_id
=target_record_id
,
3102 extra_dict
=extra_dict
,
3106 def verticalscale(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3110 action_id
= indata
.get("action_id", str(uuid4()))
3112 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
3113 self
.logger
.debug(logging_text
+ "Enter")
3115 VnfFlavorData
= indata
.get("changeVnfFlavorData")
3116 vnf_instance_id
= VnfFlavorData
["vnfInstanceId"]
3117 step
= "Getting vnfrs from db"
3118 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
3119 vduid
= VnfFlavorData
["additionalParams"]["vduid"]
3120 vduCountIndex
= VnfFlavorData
["additionalParams"]["vduCountIndex"]
3121 virtualMemory
= VnfFlavorData
["additionalParams"]["virtualMemory"]
3122 numVirtualCpu
= VnfFlavorData
["additionalParams"]["numVirtualCpu"]
3123 sizeOfStorage
= VnfFlavorData
["additionalParams"]["sizeOfStorage"]
3125 "name": vduid
+ "-flv",
3126 "ram": virtualMemory
,
3127 "vcpus": numVirtualCpu
,
3128 "disk": sizeOfStorage
,
3131 step
= "Creating Tasks for vertical scaling"
3132 with self
.write_lock
:
3133 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3135 vdu
["vdu-id-ref"] == vduid
3136 and vdu
["count-index"] == vduCountIndex
3138 extra_dict
["params"] = {
3139 "vim_vm_id": vdu
["vim-id"],
3140 "flavor_dict": flavor_dict
,
3142 task
= self
.verticalscale_task(
3151 db_new_tasks
.append(task
)
3154 self
.upload_all_tasks(
3155 db_new_tasks
=db_new_tasks
,
3159 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3162 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3166 except Exception as e
:
3167 if isinstance(e
, (DbException
, NsException
)):
3169 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3172 e
= traceback_format_exc()
3173 self
.logger
.critical(
3174 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3177 raise NsException(e
)