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
, 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
988 target_vdu: processed VDU
989 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
990 disk_list: to be filled up
993 disk_list: filled VDU list which is used for VDU creation
996 persistent_root_disk
= {}
998 for vdu
, vsd
in product(
999 vnfd
.get("vdu", ()), vnfd
.get("virtual-storage-desc", ())
1002 vdu
["name"] == target_vdu
["vdu-name"]
1003 and vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]
1007 root_disk
.get("type-of-storage")
1008 == "persistent-storage:persistent-storage"
1010 for vdu_volume
in vdu_instantiation_volumes_list
:
1012 vdu_volume
["vim-volume-id"]
1013 and root_disk
["id"] == vdu_volume
["name"]
1015 persistent_root_disk
[vsd
["id"]] = {
1016 "vim_volume_id": vdu_volume
["vim-volume-id"],
1017 "image_id": vdu
.get("sw-image-desc"),
1020 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1022 # There can be only one root disk, when we find it, it will return the result
1023 return disk_list
, 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"]])
1033 return disk_list
, persistent_root_disk
1035 return disk_list
, persistent_root_disk
1038 def find_persistent_volumes(
1039 persistent_root_disk
: dict,
1041 vdu_instantiation_volumes_list
: list,
1044 """Find the ordinary persistent volumes and add them to the disk_list
1045 by parsing the instantiation parameters
1048 persistent_root_disk: persistent root disk dictionary
1049 target_vdu: processed VDU
1050 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1051 disk_list: to be filled up
1054 disk_list: filled VDU list which is used for VDU creation
1057 # Find the ordinary volumes which are not added to the persistent_root_disk
1058 persistent_disk
= {}
1059 for disk
in target_vdu
.get("virtual-storages", {}):
1061 disk
.get("type-of-storage") == "persistent-storage:persistent-storage"
1062 and disk
["id"] not in persistent_root_disk
.keys()
1064 for vdu_volume
in vdu_instantiation_volumes_list
:
1065 if vdu_volume
["vim-volume-id"] and disk
["id"] == vdu_volume
["name"]:
1066 persistent_disk
[disk
["id"]] = {
1067 "vim_volume_id": vdu_volume
["vim-volume-id"],
1069 disk_list
.append(persistent_disk
[disk
["id"]])
1072 if disk
["id"] not in persistent_disk
.keys():
1073 persistent_disk
[disk
["id"]] = {
1074 "size": disk
.get("size-of-storage"),
1076 disk_list
.append(persistent_disk
[disk
["id"]])
1081 def _process_vdu_params(
1082 target_vdu
: Dict
[str, Any
],
1083 indata
: Dict
[str, Any
],
1084 vim_info
: Dict
[str, Any
],
1085 target_record_id
: str,
1086 **kwargs
: Dict
[str, Any
],
1087 ) -> Dict
[str, Any
]:
1088 """Function to process VDU parameters.
1091 target_vdu (Dict[str, Any]): [description]
1092 indata (Dict[str, Any]): [description]
1093 vim_info (Dict[str, Any]): [description]
1094 target_record_id (str): [description]
1097 Dict[str, Any]: [description]
1099 vnfr_id
= kwargs
.get("vnfr_id")
1100 nsr_id
= kwargs
.get("nsr_id")
1101 vnfr
= kwargs
.get("vnfr")
1102 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1103 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
1104 logger
= kwargs
.get("logger")
1105 db
= kwargs
.get("db")
1106 fs
= kwargs
.get("fs")
1107 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1109 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
1110 ns_preffix
= "nsrs:{}".format(nsr_id
)
1111 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
1112 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
1113 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
1116 # If the position info is provided for all the interfaces, it will be sorted
1117 # according to position number ascendingly.
1119 i
.get("position") + 1
1120 for i
in target_vdu
["interfaces"]
1121 if i
.get("position") is not None
1123 sorted_interfaces
= sorted(
1124 target_vdu
["interfaces"],
1125 key
=lambda x
: (x
.get("position") is None, x
.get("position")),
1127 target_vdu
["interfaces"] = sorted_interfaces
1129 # If the position info is provided for some interfaces but not all of them, the interfaces
1130 # which has specific position numbers will be placed and others' positions will not be taken care.
1133 i
.get("position") + 1
1134 for i
in target_vdu
["interfaces"]
1135 if i
.get("position") is not None
1137 n
= len(target_vdu
["interfaces"])
1138 sorted_interfaces
= [-1] * n
1141 if target_vdu
["interfaces"][k
].get("position"):
1142 idx
= target_vdu
["interfaces"][k
]["position"]
1143 sorted_interfaces
[idx
- 1] = target_vdu
["interfaces"][k
]
1146 if not target_vdu
["interfaces"][m
].get("position"):
1147 idy
= sorted_interfaces
.index(-1)
1148 sorted_interfaces
[idy
] = target_vdu
["interfaces"][m
]
1151 target_vdu
["interfaces"] = sorted_interfaces
1153 # If the position info is not provided for the interfaces, interfaces will be attached
1154 # according to the order in the VNFD.
1155 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
1156 if interface
.get("ns-vld-id"):
1157 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
1158 elif interface
.get("vnf-vld-id"):
1159 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
1162 "Interface {} from vdu {} not connected to any vld".format(
1163 iface_index
, target_vdu
["vdu-name"]
1167 continue # interface not connected to any vld
1169 extra_dict
["depends_on"].append(net_text
)
1171 if "port-security-enabled" in interface
:
1172 interface
["port_security"] = interface
.pop("port-security-enabled")
1174 if "port-security-disable-strategy" in interface
:
1175 interface
["port_security_disable_strategy"] = interface
.pop(
1176 "port-security-disable-strategy"
1181 for x
, v
in interface
.items()
1187 "port_security_disable_strategy",
1191 net_item
["net_id"] = "TASK-" + net_text
1192 net_item
["type"] = "virtual"
1194 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1195 # TODO floating_ip: True/False (or it can be None)
1196 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1197 # mark the net create task as type data
1199 tasks_by_target_record_id
,
1205 tasks_by_target_record_id
[net_text
]["extra_dict"]["params"][
1209 net_item
["use"] = "data"
1210 net_item
["model"] = interface
["type"]
1211 net_item
["type"] = interface
["type"]
1213 interface
.get("type") == "OM-MGMT"
1214 or interface
.get("mgmt-interface")
1215 or interface
.get("mgmt-vnf")
1217 net_item
["use"] = "mgmt"
1219 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1220 net_item
["use"] = "bridge"
1221 net_item
["model"] = interface
.get("type")
1223 if interface
.get("ip-address"):
1224 net_item
["ip_address"] = interface
["ip-address"]
1226 if interface
.get("mac-address"):
1227 net_item
["mac_address"] = interface
["mac-address"]
1229 net_list
.append(net_item
)
1231 if interface
.get("mgmt-vnf"):
1232 extra_dict
["mgmt_vnf_interface"] = iface_index
1233 elif interface
.get("mgmt-interface"):
1234 extra_dict
["mgmt_vdu_interface"] = iface_index
1239 if target_vdu
.get("cloud-init"):
1240 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1241 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1244 location
=target_vdu
["cloud-init"],
1247 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1248 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1249 cloud_init_content
=cloud_content_
,
1250 params
=target_vdu
.get("additionalParams"),
1251 context
=target_vdu
["cloud-init"],
1254 if target_vdu
.get("boot-data-drive"):
1255 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1259 if target_vdu
.get("ssh-keys"):
1260 ssh_keys
+= target_vdu
.get("ssh-keys")
1262 if target_vdu
.get("ssh-access-required"):
1263 ssh_keys
.append(ro_nsr_public_key
)
1266 cloud_config
["key-pairs"] = ssh_keys
1268 persistent_root_disk
= {}
1269 vdu_instantiation_volumes_list
= []
1271 vnfd_id
= vnfr
["vnfd-id"]
1272 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
1274 if target_vdu
.get("additionalParams"):
1275 vdu_instantiation_volumes_list
= (
1276 target_vdu
.get("additionalParams").get("OSM").get("vdu_volumes")
1279 if vdu_instantiation_volumes_list
:
1280 # Find the root volumes and add to the disk_list
1283 persistent_root_disk
,
1284 ) = Ns
.find_persistent_root_volumes(
1285 vnfd
, target_vdu
, vdu_instantiation_volumes_list
, disk_list
1288 # Find the ordinary volumes which are not added to the persistent_root_disk
1289 # and put them to the disk list
1290 disk_list
= Ns
.find_persistent_volumes(
1291 persistent_root_disk
,
1293 vdu_instantiation_volumes_list
,
1298 # vdu_instantiation_volumes_list is empty
1299 for vdu
in vnfd
.get("vdu", ()):
1300 if vdu
["name"] == target_vdu
["vdu-name"]:
1301 for vsd
in vnfd
.get("virtual-storage-desc", ()):
1302 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
1306 ) == "persistent-storage:persistent-storage" and root_disk
.get(
1309 persistent_root_disk
[vsd
["id"]] = {
1310 "image_id": vdu
.get("sw-image-desc"),
1311 "size": root_disk
["size-of-storage"],
1313 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1315 if target_vdu
.get("virtual-storages"):
1316 for disk
in target_vdu
["virtual-storages"]:
1318 disk
.get("type-of-storage")
1319 == "persistent-storage:persistent-storage"
1320 and disk
["id"] not in persistent_root_disk
.keys()
1322 disk_list
.append({"size": disk
["size-of-storage"]})
1324 affinity_group_list
= []
1326 if target_vdu
.get("affinity-or-anti-affinity-group-id"):
1328 for affinity_group_id
in target_vdu
["affinity-or-anti-affinity-group-id"]:
1329 affinity_group_text
= (
1330 ns_preffix
+ ":affinity-or-anti-affinity-group." + affinity_group_id
1333 extra_dict
["depends_on"].append(affinity_group_text
)
1334 affinity_group
["affinity_group_id"] = "TASK-" + affinity_group_text
1335 affinity_group_list
.append(affinity_group
)
1337 extra_dict
["params"] = {
1338 "name": "{}-{}-{}-{}".format(
1339 indata
["name"][:16],
1340 vnfr
["member-vnf-index-ref"][:16],
1341 target_vdu
["vdu-name"][:32],
1342 target_vdu
.get("count-index") or 0,
1344 "description": target_vdu
["vdu-name"],
1346 "image_id": "TASK-" + image_text
,
1347 "flavor_id": "TASK-" + flavor_text
,
1348 "affinity_group_list": affinity_group_list
,
1349 "net_list": net_list
,
1350 "cloud_config": cloud_config
or None,
1351 "disk_list": disk_list
,
1352 "availability_zone_index": None, # TODO
1353 "availability_zone_list": None, # TODO
1359 def _process_affinity_group_params(
1360 target_affinity_group
: Dict
[str, Any
],
1361 indata
: Dict
[str, Any
],
1362 vim_info
: Dict
[str, Any
],
1363 target_record_id
: str,
1364 **kwargs
: Dict
[str, Any
],
1365 ) -> Dict
[str, Any
]:
1366 """Get affinity or anti-affinity group parameters.
1369 target_affinity_group (Dict[str, Any]): [description]
1370 indata (Dict[str, Any]): [description]
1371 vim_info (Dict[str, Any]): [description]
1372 target_record_id (str): [description]
1375 Dict[str, Any]: [description]
1379 affinity_group_data
= {
1380 "name": target_affinity_group
["name"],
1381 "type": target_affinity_group
["type"],
1382 "scope": target_affinity_group
["scope"],
1385 if target_affinity_group
.get("vim-affinity-group-id"):
1386 affinity_group_data
["vim-affinity-group-id"] = target_affinity_group
[
1387 "vim-affinity-group-id"
1390 extra_dict
["params"] = {
1391 "affinity_group_data": affinity_group_data
,
1397 def _process_recreate_vdu_params(
1398 existing_vdu
: Dict
[str, Any
],
1399 db_nsr
: Dict
[str, Any
],
1400 vim_info
: Dict
[str, Any
],
1401 target_record_id
: str,
1403 **kwargs
: Dict
[str, Any
],
1404 ) -> Dict
[str, Any
]:
1405 """Function to process VDU parameters to recreate.
1408 existing_vdu (Dict[str, Any]): [description]
1409 db_nsr (Dict[str, Any]): [description]
1410 vim_info (Dict[str, Any]): [description]
1411 target_record_id (str): [description]
1412 target_id (str): [description]
1415 Dict[str, Any]: [description]
1417 vnfr
= kwargs
.get("vnfr")
1418 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1419 # logger = kwargs.get("logger")
1420 db
= kwargs
.get("db")
1421 fs
= kwargs
.get("fs")
1422 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1428 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
1429 if vim_details_text
:
1430 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
1432 for iface_index
, interface
in enumerate(existing_vdu
["interfaces"]):
1433 if "port-security-enabled" in interface
:
1434 interface
["port_security"] = interface
.pop("port-security-enabled")
1436 if "port-security-disable-strategy" in interface
:
1437 interface
["port_security_disable_strategy"] = interface
.pop(
1438 "port-security-disable-strategy"
1443 for x
, v
in interface
.items()
1449 "port_security_disable_strategy",
1453 existing_ifaces
= existing_vdu
["vim_info"][target_id
].get(
1454 "interfaces_backup", []
1459 for i
in existing_ifaces
1460 if i
["ip_address"] == interface
["ip-address"]
1465 net_item
["net_id"] = net_id
1466 net_item
["type"] = "virtual"
1468 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1469 # TODO floating_ip: True/False (or it can be None)
1470 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1471 net_item
["use"] = "data"
1472 net_item
["model"] = interface
["type"]
1473 net_item
["type"] = interface
["type"]
1475 interface
.get("type") == "OM-MGMT"
1476 or interface
.get("mgmt-interface")
1477 or interface
.get("mgmt-vnf")
1479 net_item
["use"] = "mgmt"
1481 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1482 net_item
["use"] = "bridge"
1483 net_item
["model"] = interface
.get("type")
1485 if interface
.get("ip-address"):
1486 net_item
["ip_address"] = interface
["ip-address"]
1488 if interface
.get("mac-address"):
1489 net_item
["mac_address"] = interface
["mac-address"]
1491 net_list
.append(net_item
)
1493 if interface
.get("mgmt-vnf"):
1494 extra_dict
["mgmt_vnf_interface"] = iface_index
1495 elif interface
.get("mgmt-interface"):
1496 extra_dict
["mgmt_vdu_interface"] = iface_index
1501 if existing_vdu
.get("cloud-init"):
1502 if existing_vdu
["cloud-init"] not in vdu2cloud_init
:
1503 vdu2cloud_init
[existing_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1506 location
=existing_vdu
["cloud-init"],
1509 cloud_content_
= vdu2cloud_init
[existing_vdu
["cloud-init"]]
1510 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1511 cloud_init_content
=cloud_content_
,
1512 params
=existing_vdu
.get("additionalParams"),
1513 context
=existing_vdu
["cloud-init"],
1516 if existing_vdu
.get("boot-data-drive"):
1517 cloud_config
["boot-data-drive"] = existing_vdu
.get("boot-data-drive")
1521 if existing_vdu
.get("ssh-keys"):
1522 ssh_keys
+= existing_vdu
.get("ssh-keys")
1524 if existing_vdu
.get("ssh-access-required"):
1525 ssh_keys
.append(ro_nsr_public_key
)
1528 cloud_config
["key-pairs"] = ssh_keys
1531 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
1532 disk_list
.append({"vim_id": vol_id
["id"]})
1534 affinity_group_list
= []
1536 if existing_vdu
.get("affinity-or-anti-affinity-group-id"):
1538 for affinity_group_id
in existing_vdu
["affinity-or-anti-affinity-group-id"]:
1539 for group
in db_nsr
.get("affinity-or-anti-affinity-group"):
1541 group
["id"] == affinity_group_id
1542 and group
["vim_info"][target_id
].get("vim_id", None) is not None
1544 affinity_group
["affinity_group_id"] = group
["vim_info"][
1546 ].get("vim_id", None)
1547 affinity_group_list
.append(affinity_group
)
1549 extra_dict
["params"] = {
1550 "name": "{}-{}-{}-{}".format(
1551 db_nsr
["name"][:16],
1552 vnfr
["member-vnf-index-ref"][:16],
1553 existing_vdu
["vdu-name"][:32],
1554 existing_vdu
.get("count-index") or 0,
1556 "description": existing_vdu
["vdu-name"],
1558 "image_id": vim_details
["image"]["id"],
1559 "flavor_id": vim_details
["flavor"]["id"],
1560 "affinity_group_list": affinity_group_list
,
1561 "net_list": net_list
,
1562 "cloud_config": cloud_config
or None,
1563 "disk_list": disk_list
,
1564 "availability_zone_index": None, # TODO
1565 "availability_zone_list": None, # TODO
1570 def calculate_diff_items(
1577 tasks_by_target_record_id
,
1584 """Function that returns the incremental changes (creation, deletion)
1585 related to a specific item `item` to be done. This function should be
1586 called for NS instantiation, NS termination, NS update to add a new VNF
1587 or a new VLD, remove a VNF or VLD, etc.
1588 Item can be `net`, `flavor`, `image` or `vdu`.
1589 It takes a list of target items from indata (which came from the REST API)
1590 and compares with the existing items from db_ro_nsr, identifying the
1591 incremental changes to be done. During the comparison, it calls the method
1592 `process_params` (which was passed as parameter, and is particular for each
1596 indata (Dict[str, Any]): deployment info
1597 db_nsr: NSR record from DB
1598 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1599 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1600 item (str): element to process (net, vdu...)
1601 tasks_by_target_record_id (Dict[str, Any]):
1602 [<target_record_id>, <task>]
1603 action_id (str): action id
1604 nsr_id (str): NSR id
1605 task_index (number): task index to add to task name
1606 vnfr_id (str): VNFR id
1607 vnfr (Dict[str, Any]): VNFR info
1610 List: list with the incremental changes (deletes, creates) for each item
1611 number: current task index
1619 process_params
= None
1620 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1621 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1623 # According to the type of item, the path, the target_list,
1624 # the existing_list and the method to process params are set
1625 db_path
= self
.db_path_map
[item
]
1626 process_params
= self
.process_params_function_map
[item
]
1627 if item
in ("net", "vdu"):
1628 # This case is specific for the NS VLD (not applied to VDU)
1630 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1631 target_list
= indata
.get("ns", []).get(db_path
, [])
1632 existing_list
= db_nsr
.get(db_path
, [])
1633 # This case is common for VNF VLDs and VNF VDUs
1635 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
1637 (vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
),
1640 target_list
= target_vnf
.get(db_path
, []) if target_vnf
else []
1641 existing_list
= vnfr
.get(db_path
, [])
1642 elif item
in ("image", "flavor", "affinity-or-anti-affinity-group"):
1643 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1644 target_list
= indata
.get(item
, [])
1645 existing_list
= db_nsr
.get(item
, [])
1647 raise NsException("Item not supported: {}", item
)
1649 # ensure all the target_list elements has an "id". If not assign the index as id
1650 if target_list
is None:
1652 for target_index
, tl
in enumerate(target_list
):
1653 if tl
and not tl
.get("id"):
1654 tl
["id"] = str(target_index
)
1656 # step 1 items (networks,vdus,...) to be deleted/updated
1657 for item_index
, existing_item
in enumerate(existing_list
):
1659 (t
for t
in target_list
if t
["id"] == existing_item
["id"]),
1663 for target_vim
, existing_viminfo
in existing_item
.get(
1666 if existing_viminfo
is None:
1670 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
1672 target_viminfo
= None
1674 if target_viminfo
is None:
1676 self
._assign
_vim
(target_vim
)
1677 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
1680 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
1681 # item must be sdn-net instead of net if target_vim is a sdn
1683 target_record_id
+= ".sdn"
1686 "action_id": action_id
,
1688 "task_index": task_index
,
1693 "deployment_info": deployment_info
,
1694 "target_id": target_vim
,
1697 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1698 "target_record_id": target_record_id
,
1703 # step 2 items (networks,vdus,...) to be created
1704 for target_item
in target_list
:
1707 for item_index
, existing_item
in enumerate(existing_list
):
1708 if existing_item
["id"] == target_item
["id"]:
1712 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1713 existing_list
.append(target_item
)
1714 existing_item
= None
1716 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
1717 existing_viminfo
= None
1720 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
1722 if existing_viminfo
is not None:
1725 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
1728 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
1729 # item must be sdn-net instead of net if target_vim is a sdn
1731 target_record_id
+= ".sdn"
1734 self
.logger
.warning(
1735 "ns.calculate_diff_items target_item={}".format(target_item
)
1737 if process_params
== Ns
._process
_flavor
_params
:
1743 self
.logger
.warning(
1744 "calculate_diff_items for flavor kwargs={}".format(kwargs
)
1747 if process_params
== Ns
._process
_vdu
_params
:
1748 self
.logger
.warning(
1749 "calculate_diff_items self.fs={}".format(self
.fs
)
1756 "vdu2cloud_init": vdu2cloud_init
,
1757 "tasks_by_target_record_id": tasks_by_target_record_id
,
1758 "logger": self
.logger
,
1761 "ro_nsr_public_key": ro_nsr_public_key
,
1764 self
.logger
.warning("calculate_diff_items kwargs={}".format(kwargs
))
1766 extra_dict
= process_params(
1773 self
._assign
_vim
(target_vim
)
1776 "action_id": action_id
,
1778 "task_index": task_index
,
1782 "deployment_info": deployment_info
,
1783 "target_id": target_vim
,
1786 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1787 "target_record_id": target_record_id
,
1788 "extra_dict": extra_dict
,
1789 "common_id": target_item
.get("common_id", None),
1791 diff_items
.append(new_item
)
1792 tasks_by_target_record_id
[target_record_id
] = new_item
1795 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1797 return diff_items
, task_index
1799 def calculate_all_differences_to_deploy(
1809 tasks_by_target_record_id
,
1811 """This method calculates the ordered list of items (`changes_list`)
1812 to be created and deleted.
1815 indata (Dict[str, Any]): deployment info
1816 nsr_id (str): NSR id
1817 db_nsr: NSR record from DB
1818 db_vnfrs: VNFRS record from DB
1819 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1820 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1821 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
1822 action_id (str): action id
1823 tasks_by_target_record_id (Dict[str, Any]):
1824 [<target_record_id>, <task>]
1827 List: ordered list of items to be created and deleted.
1831 # set list with diffs:
1834 # NS vld, image and flavor
1835 for item
in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
1836 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
1837 diff_items
, task_index
= self
.calculate_diff_items(
1840 db_ro_nsr
=db_ro_nsr
,
1841 db_nsr_update
=db_nsr_update
,
1843 tasks_by_target_record_id
=tasks_by_target_record_id
,
1844 action_id
=action_id
,
1846 task_index
=task_index
,
1849 changes_list
+= diff_items
1852 for vnfr_id
, vnfr
in db_vnfrs
.items():
1853 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1854 for item
in ["net", "vdu"]:
1855 self
.logger
.debug("process VNF={} {}".format(vnfr_id
, item
))
1856 diff_items
, task_index
= self
.calculate_diff_items(
1859 db_ro_nsr
=db_ro_nsr
,
1860 db_nsr_update
=db_vnfrs_update
[vnfr
["_id"]],
1862 tasks_by_target_record_id
=tasks_by_target_record_id
,
1863 action_id
=action_id
,
1865 task_index
=task_index
,
1869 changes_list
+= diff_items
1873 def define_all_tasks(
1877 tasks_by_target_record_id
,
1879 """Function to create all the task structures obtanied from
1880 the method calculate_all_differences_to_deploy
1883 changes_list (List): ordered list of items to be created or deleted
1884 db_new_tasks (List): tasks list to be created
1885 action_id (str): action id
1886 tasks_by_target_record_id (Dict[str, Any]):
1887 [<target_record_id>, <task>]
1891 for change
in changes_list
:
1892 task
= Ns
._create
_task
(
1893 deployment_info
=change
["deployment_info"],
1894 target_id
=change
["target_id"],
1895 item
=change
["item"],
1896 action
=change
["action"],
1897 target_record
=change
["target_record"],
1898 target_record_id
=change
["target_record_id"],
1899 extra_dict
=change
.get("extra_dict", None),
1902 self
.logger
.warning("ns.define_all_tasks task={}".format(task
))
1903 tasks_by_target_record_id
[change
["target_record_id"]] = task
1904 db_new_tasks
.append(task
)
1906 if change
.get("common_id"):
1907 task
["common_id"] = change
["common_id"]
1909 def upload_all_tasks(
1914 """Function to save all tasks in the common DB
1917 db_new_tasks (List): tasks list to be created
1918 now (time): current time
1922 nb_ro_tasks
= 0 # for logging
1924 for db_task
in db_new_tasks
:
1925 target_id
= db_task
.pop("target_id")
1926 common_id
= db_task
.get("common_id")
1928 # Do not chek tasks with vim_status DELETED
1929 # because in manual heealing there are two tasks for the same vdur:
1930 # one with vim_status deleted and the other one with the actual VM status.
1936 "target_id": target_id
,
1937 "tasks.common_id": common_id
,
1938 "vim_info.vim_status.ne": "DELETED",
1940 update_dict
={"to_check_at": now
, "modified_at": now
},
1941 push
={"tasks": db_task
},
1942 fail_on_empty
=False,
1946 if not self
.db
.set_one(
1949 "target_id": target_id
,
1950 "tasks.target_record": db_task
["target_record"],
1951 "vim_info.vim_status.ne": "DELETED",
1953 update_dict
={"to_check_at": now
, "modified_at": now
},
1954 push
={"tasks": db_task
},
1955 fail_on_empty
=False,
1958 self
.logger
.debug("Updating database, Creating ro_tasks")
1959 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
1961 self
.db
.create("ro_tasks", db_ro_task
)
1964 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1965 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
1969 def upload_recreate_tasks(
1974 """Function to save recreate tasks in the common DB
1977 db_new_tasks (List): tasks list to be created
1978 now (time): current time
1982 nb_ro_tasks
= 0 # for logging
1984 for db_task
in db_new_tasks
:
1985 target_id
= db_task
.pop("target_id")
1986 self
.logger
.warning("target_id={} db_task={}".format(target_id
, db_task
))
1988 action
= db_task
.get("action", None)
1991 self
.logger
.debug("Updating database, Creating ro_tasks")
1992 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
1994 # If DELETE task: the associated created items should be removed
1995 # (except persistent volumes):
1996 if action
== "DELETE":
1997 db_ro_task
["vim_info"]["created"] = True
1998 db_ro_task
["vim_info"]["created_items"] = db_task
.get(
2001 db_ro_task
["vim_info"]["volumes_to_hold"] = db_task
.get(
2002 "volumes_to_hold", []
2004 db_ro_task
["vim_info"]["vim_id"] = db_task
.get("vim_id", None)
2007 self
.logger
.warning("upload_all_tasks db_ro_task={}".format(db_ro_task
))
2008 self
.db
.create("ro_tasks", db_ro_task
)
2011 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2012 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2016 def _prepare_created_items_for_healing(
2022 # Get created_items from ro_task
2023 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2024 for ro_task
in ro_tasks
:
2025 for task
in ro_task
["tasks"]:
2027 task
["target_record"] == target_record
2028 and task
["action"] == "CREATE"
2029 and ro_task
["vim_info"]["created_items"]
2031 created_items
= ro_task
["vim_info"]["created_items"]
2034 return created_items
2036 def _prepare_persistent_volumes_for_healing(
2041 # The associated volumes of the VM shouldn't be removed
2044 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
2045 if vim_details_text
:
2046 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
2048 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
2049 volumes_list
.append(vol_id
["id"])
2053 def prepare_changes_to_recreate(
2061 tasks_by_target_record_id
,
2063 """This method will obtain an ordered list of items (`changes_list`)
2064 to be created and deleted to meet the recreate request.
2068 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id
, indata
)
2072 # set list with diffs:
2074 db_path
= self
.db_path_map
["vdu"]
2075 target_list
= indata
.get("healVnfData", {})
2076 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
2077 ro_nsr_public_key
= db_ro_nsr
["public_key"]
2079 # Check each VNF of the target
2080 for target_vnf
in target_list
:
2081 # Find this VNF in the list from DB, raise exception if vnfInstanceId is not found
2082 vnfr_id
= target_vnf
["vnfInstanceId"]
2083 existing_vnf
= db_vnfrs
.get(vnfr_id
)
2084 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
2085 # vim_account_id = existing_vnf.get("vim-account-id", "")
2087 target_vdus
= target_vnf
.get("additionalParams", {}).get("vdu", [])
2088 # Check each VDU of this VNF
2090 # Create target_vdu_list from DB, if VDUs are not specified
2092 for existing_vdu
in existing_vnf
.get("vdur"):
2093 vdu_name
= existing_vdu
.get("vdu-name", None)
2094 vdu_index
= existing_vdu
.get("count-index", 0)
2095 vdu_to_be_healed
= {"vdu-id": vdu_name
, "count-index": vdu_index
}
2096 target_vdus
.append(vdu_to_be_healed
)
2097 for target_vdu
in target_vdus
:
2098 vdu_name
= target_vdu
.get("vdu-id", None)
2099 # For multi instance VDU count-index is mandatory
2100 # For single session VDU count-indes is 0
2101 count_index
= target_vdu
.get("count-index", 0)
2103 existing_instance
= None
2104 for instance
in existing_vnf
.get("vdur", None):
2106 instance
["vdu-name"] == vdu_name
2107 and instance
["count-index"] == count_index
2109 existing_instance
= instance
2114 target_record_id
= "{}.{}".format(db_record
, existing_instance
["id"])
2116 # The target VIM is the one already existing in DB to recreate
2117 for target_vim
, target_viminfo
in existing_instance
.get(
2120 # step 1 vdu to be deleted
2121 self
._assign
_vim
(target_vim
)
2123 "action_id": action_id
,
2125 "task_index": task_index
,
2128 target_record
= f
"{db_record}.{item_index}.vim_info.{target_vim}"
2129 created_items
= self
._prepare
_created
_items
_for
_healing
(
2130 nsr_id
, target_record
2133 volumes_to_hold
= self
._prepare
_persistent
_volumes
_for
_healing
(
2134 target_vim
, existing_instance
2137 # Specific extra params for recreate tasks:
2139 "created_items": created_items
,
2140 "vim_id": existing_instance
["vim-id"],
2141 "volumes_to_hold": volumes_to_hold
,
2144 changes_list
.append(
2146 "deployment_info": deployment_info
,
2147 "target_id": target_vim
,
2150 "target_record": target_record
,
2151 "target_record_id": target_record_id
,
2152 "extra_dict": extra_dict
,
2155 delete_task_id
= f
"{action_id}:{task_index}"
2158 # step 2 vdu to be created
2164 "vnfr": existing_vnf
,
2165 "vdu2cloud_init": vdu2cloud_init
,
2166 "tasks_by_target_record_id": tasks_by_target_record_id
,
2167 "logger": self
.logger
,
2170 "ro_nsr_public_key": ro_nsr_public_key
,
2174 extra_dict
= self
._process
_recreate
_vdu
_params
(
2183 # The CREATE task depens on the DELETE task
2184 extra_dict
["depends_on"] = [delete_task_id
]
2186 # Add volumes created from created_items if any
2187 # Ports should be deleted with delete task and automatically created with create task
2189 for k
, v
in created_items
.items():
2191 k_item
, _
, k_id
= k
.partition(":")
2192 if k_item
== "volume":
2194 except Exception as e
:
2196 "Error evaluating created item {}: {}".format(k
, e
)
2198 extra_dict
["previous_created_volumes"] = volumes
2201 "action_id": action_id
,
2203 "task_index": task_index
,
2205 self
._assign
_vim
(target_vim
)
2208 "deployment_info": deployment_info
,
2209 "target_id": target_vim
,
2212 "target_record": target_record
,
2213 "target_record_id": target_record_id
,
2214 "extra_dict": extra_dict
,
2216 changes_list
.append(new_item
)
2217 tasks_by_target_record_id
[target_record_id
] = new_item
2222 def recreate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2223 self
.logger
.debug("ns.recreate nsr_id={} indata={}".format(nsr_id
, indata
))
2224 # TODO: validate_input(indata, recreate_schema)
2225 action_id
= indata
.get("action_id", str(uuid4()))
2226 # get current deployment
2227 db_vnfrs
= {} # vnf's info indexed by _id
2229 logging_text
= "Recreate nsr_id={} action_id={} indata={}".format(
2230 nsr_id
, action_id
, indata
2232 self
.logger
.debug(logging_text
+ "Enter")
2235 step
= "Getting ns and vnfr record from db"
2236 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2238 tasks_by_target_record_id
= {}
2239 # read from db: vnf's of this ns
2240 step
= "Getting vnfrs from db"
2241 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2242 self
.logger
.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list
))
2244 if not db_vnfrs_list
:
2245 raise NsException("Cannot obtain associated VNF for ns")
2247 for vnfr
in db_vnfrs_list
:
2248 db_vnfrs
[vnfr
["_id"]] = vnfr
2251 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2252 self
.logger
.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr
))
2255 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2257 with self
.write_lock
:
2259 step
= "process NS elements"
2260 changes_list
= self
.prepare_changes_to_recreate(
2265 db_ro_nsr
=db_ro_nsr
,
2266 action_id
=action_id
,
2267 tasks_by_target_record_id
=tasks_by_target_record_id
,
2270 self
.define_all_tasks(
2271 changes_list
=changes_list
,
2272 db_new_tasks
=db_new_tasks
,
2273 tasks_by_target_record_id
=tasks_by_target_record_id
,
2276 # Delete all ro_tasks registered for the targets vdurs (target_record)
2277 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2278 # So remove all task related to target record.
2279 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2280 for change
in changes_list
:
2281 for ro_task
in ro_tasks
:
2282 for task
in ro_task
["tasks"]:
2283 if task
["target_record"] == change
["target_record"]:
2287 "_id": ro_task
["_id"],
2288 "modified_at": ro_task
["modified_at"],
2290 fail_on_empty
=False,
2293 step
= "Updating database, Appending tasks to ro_tasks"
2294 self
.upload_recreate_tasks(
2295 db_new_tasks
=db_new_tasks
,
2300 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2304 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2308 except Exception as e
:
2309 if isinstance(e
, (DbException
, NsException
)):
2311 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2314 e
= traceback_format_exc()
2315 self
.logger
.critical(
2316 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2320 raise NsException(e
)
2322 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2323 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
2324 validate_input(indata
, deploy_schema
)
2325 action_id
= indata
.get("action_id", str(uuid4()))
2327 # get current deployment
2328 db_nsr_update
= {} # update operation on nsrs
2329 db_vnfrs_update
= {}
2330 db_vnfrs
= {} # vnf's info indexed by _id
2332 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2333 self
.logger
.debug(logging_text
+ "Enter")
2336 step
= "Getting ns and vnfr record from db"
2337 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2338 self
.logger
.debug("ns.deploy: db_nsr={}".format(db_nsr
))
2340 tasks_by_target_record_id
= {}
2341 # read from db: vnf's of this ns
2342 step
= "Getting vnfrs from db"
2343 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
2345 if not db_vnfrs_list
:
2346 raise NsException("Cannot obtain associated VNF for ns")
2348 for vnfr
in db_vnfrs_list
:
2349 db_vnfrs
[vnfr
["_id"]] = vnfr
2350 db_vnfrs_update
[vnfr
["_id"]] = {}
2351 self
.logger
.debug("ns.deploy db_vnfrs={}".format(db_vnfrs
))
2354 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
2357 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
2359 # check that action_id is not in the list of actions. Suffixed with :index
2360 if action_id
in db_ro_nsr
["actions"]:
2364 new_action_id
= "{}:{}".format(action_id
, index
)
2366 if new_action_id
not in db_ro_nsr
["actions"]:
2367 action_id
= new_action_id
2370 + "Changing action_id in use to {}".format(action_id
)
2376 def _process_action(indata
):
2377 nonlocal db_new_tasks
2384 if indata
["action"]["action"] == "inject_ssh_key":
2385 key
= indata
["action"].get("key")
2386 user
= indata
["action"].get("user")
2387 password
= indata
["action"].get("password")
2389 for vnf
in indata
.get("vnf", ()):
2390 if vnf
["_id"] not in db_vnfrs
:
2391 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
2393 db_vnfr
= db_vnfrs
[vnf
["_id"]]
2395 for target_vdu
in vnf
.get("vdur", ()):
2396 vdu_index
, vdur
= next(
2399 for i_v
in enumerate(db_vnfr
["vdur"])
2400 if i_v
[1]["id"] == target_vdu
["id"]
2407 "Invalid vdu vnf={}.{}".format(
2408 vnf
["_id"], target_vdu
["id"]
2412 target_vim
, vim_info
= next(
2413 k_v
for k_v
in vdur
["vim_info"].items()
2415 self
._assign
_vim
(target_vim
)
2416 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
2417 vnf
["_id"], vdu_index
2421 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
2424 "ip_address": vdur
.get("ip-address"),
2427 "password": password
,
2428 "private_key": db_ro_nsr
["private_key"],
2429 "salt": db_ro_nsr
["_id"],
2430 "schema_version": db_ro_nsr
["_admin"][
2437 "action_id": action_id
,
2439 "task_index": task_index
,
2442 task
= Ns
._create
_task
(
2443 deployment_info
=deployment_info
,
2444 target_id
=target_vim
,
2447 target_record
=target_record
,
2448 target_record_id
=None,
2449 extra_dict
=extra_dict
,
2452 task_index
= deployment_info
.get("task_index")
2454 db_new_tasks
.append(task
)
2456 with self
.write_lock
:
2457 if indata
.get("action"):
2458 _process_action(indata
)
2460 # compute network differences
2462 step
= "process NS elements"
2463 changes_list
= self
.calculate_all_differences_to_deploy(
2468 db_ro_nsr
=db_ro_nsr
,
2469 db_nsr_update
=db_nsr_update
,
2470 db_vnfrs_update
=db_vnfrs_update
,
2471 action_id
=action_id
,
2472 tasks_by_target_record_id
=tasks_by_target_record_id
,
2474 self
.define_all_tasks(
2475 changes_list
=changes_list
,
2476 db_new_tasks
=db_new_tasks
,
2477 tasks_by_target_record_id
=tasks_by_target_record_id
,
2480 step
= "Updating database, Appending tasks to ro_tasks"
2481 self
.upload_all_tasks(
2482 db_new_tasks
=db_new_tasks
,
2486 step
= "Updating database, nsrs"
2488 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
2490 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
2492 step
= "Updating database, vnfrs={}".format(vnfr_id
)
2493 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
2496 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2500 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2504 except Exception as e
:
2505 if isinstance(e
, (DbException
, NsException
)):
2507 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2510 e
= traceback_format_exc()
2511 self
.logger
.critical(
2512 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2516 raise NsException(e
)
2518 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2519 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
2520 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2522 with self
.write_lock
:
2524 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
2525 except NsWorkerException
as e
:
2526 raise NsException(e
)
2528 return None, None, True
2530 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2532 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2533 version
, nsr_id
, action_id
, indata
2539 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
2540 global_status
= "DONE"
2543 for ro_task
in ro_tasks
:
2544 for task
in ro_task
["tasks"]:
2545 if task
and task
["action_id"] == action_id
:
2546 task_list
.append(task
)
2549 if task
["status"] == "FAILED":
2550 global_status
= "FAILED"
2551 error_text
= "Error at {} {}: {}".format(
2552 task
["action"].lower(),
2554 ro_task
["vim_info"].get("vim_message") or "unknown",
2556 details
.append(error_text
)
2557 elif task
["status"] in ("SCHEDULED", "BUILD"):
2558 if global_status
!= "FAILED":
2559 global_status
= "BUILD"
2564 "status": global_status
,
2565 "details": ". ".join(details
)
2567 else "progress {}/{}".format(done
, total
),
2569 "action_id": action_id
,
2573 return return_data
, None, True
2575 def recreate_status(
2576 self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
2578 return self
.status(session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
)
2580 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2582 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2583 session
, indata
, version
, nsr_id
, action_id
2587 return None, None, True
2589 def rebuild_start_stop_task(
2600 self
._assign
_vim
(target_vim
)
2601 target_record
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_index
)
2602 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_id
)
2604 "action_id": action_id
,
2606 "task_index": task_index
,
2609 task
= Ns
._create
_task
(
2610 deployment_info
=deployment_info
,
2611 target_id
=target_vim
,
2614 target_record
=target_record
,
2615 target_record_id
=target_record_id
,
2616 extra_dict
=extra_dict
,
2620 def rebuild_start_stop(
2621 self
, session
, action_dict
, version
, nsr_id
, *args
, **kwargs
2626 action_id
= action_dict
.get("action_id", str(uuid4()))
2628 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2629 self
.logger
.debug(logging_text
+ "Enter")
2631 action
= list(action_dict
.keys())[0]
2632 task_dict
= action_dict
.get(action
)
2633 vim_vm_id
= action_dict
.get(action
).get("vim_vm_id")
2635 if action_dict
.get("stop"):
2639 step
= "lock the operation & do task creation"
2640 with self
.write_lock
:
2641 extra_dict
["params"] = {
2642 "vim_vm_id": vim_vm_id
,
2645 task
= self
.rebuild_start_stop_task(
2646 task_dict
["vdu_id"],
2647 task_dict
["vnf_id"],
2648 task_dict
["vdu_index"],
2652 task_dict
["target_vim"],
2655 db_new_tasks
.append(task
)
2656 step
= "upload Task to db"
2657 self
.upload_all_tasks(
2658 db_new_tasks
=db_new_tasks
,
2662 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2665 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2669 except Exception as e
:
2670 if isinstance(e
, (DbException
, NsException
)):
2672 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2675 e
= traceback_format_exc()
2676 self
.logger
.critical(
2677 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2680 raise NsException(e
)
2682 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2683 nsrs
= self
.db
.get_list("nsrs", {})
2687 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
2689 return return_data
, None, True
2691 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
2692 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2695 for ro_task
in ro_tasks
:
2696 for task
in ro_task
["tasks"]:
2697 if task
["action_id"] not in return_data
:
2698 return_data
.append(task
["action_id"])
2700 return return_data
, None, True
2703 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
2705 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
2706 self
._assign
_vim
(target_vim
)
2707 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
2708 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
2710 "action_id": action_id
,
2712 "task_index": task_index
,
2715 task
= Ns
._create
_task
(
2716 deployment_info
=deployment_info
,
2717 target_id
=target_vim
,
2720 target_record
=target_record
,
2721 target_record_id
=target_record_id
,
2722 extra_dict
=extra_dict
,
2727 def migrate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2731 action_id
= indata
.get("action_id", str(uuid4()))
2733 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2734 self
.logger
.debug(logging_text
+ "Enter")
2736 vnf_instance_id
= indata
["vnfInstanceId"]
2737 step
= "Getting vnfrs from db"
2738 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
2739 vdu
= indata
.get("vdu")
2740 migrateToHost
= indata
.get("migrateToHost")
2743 with self
.write_lock
:
2745 vdu_id
= indata
["vdu"]["vduId"]
2746 vdu_count_index
= indata
["vdu"].get("vduCountIndex", 0)
2747 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2749 vdu
["vdu-id-ref"] == vdu_id
2750 and vdu
["count-index"] == vdu_count_index
2752 extra_dict
["params"] = {
2753 "vim_vm_id": vdu
["vim-id"],
2754 "migrate_host": migrateToHost
,
2755 "vdu_vim_info": vdu
["vim_info"],
2757 step
= "Creating migration task for vdu:{}".format(vdu
)
2758 task
= self
.migrate_task(
2767 db_new_tasks
.append(task
)
2771 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2772 extra_dict
["params"] = {
2773 "vim_vm_id": vdu
["vim-id"],
2774 "migrate_host": migrateToHost
,
2775 "vdu_vim_info": vdu
["vim_info"],
2777 step
= "Creating migration task for vdu:{}".format(vdu
)
2778 task
= self
.migrate_task(
2787 db_new_tasks
.append(task
)
2790 self
.upload_all_tasks(
2791 db_new_tasks
=db_new_tasks
,
2796 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2799 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2803 except Exception as e
:
2804 if isinstance(e
, (DbException
, NsException
)):
2806 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2809 e
= traceback_format_exc()
2810 self
.logger
.critical(
2811 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2814 raise NsException(e
)
2816 def verticalscale_task(
2817 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
2819 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
2820 self
._assign
_vim
(target_vim
)
2821 target_record
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu_index
)
2822 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
2824 "action_id": action_id
,
2826 "task_index": task_index
,
2829 task
= Ns
._create
_task
(
2830 deployment_info
=deployment_info
,
2831 target_id
=target_vim
,
2832 item
="verticalscale",
2834 target_record
=target_record
,
2835 target_record_id
=target_record_id
,
2836 extra_dict
=extra_dict
,
2840 def verticalscale(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
2844 action_id
= indata
.get("action_id", str(uuid4()))
2846 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
2847 self
.logger
.debug(logging_text
+ "Enter")
2849 VnfFlavorData
= indata
.get("changeVnfFlavorData")
2850 vnf_instance_id
= VnfFlavorData
["vnfInstanceId"]
2851 step
= "Getting vnfrs from db"
2852 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
2853 vduid
= VnfFlavorData
["additionalParams"]["vduid"]
2854 vduCountIndex
= VnfFlavorData
["additionalParams"]["vduCountIndex"]
2855 virtualMemory
= VnfFlavorData
["additionalParams"]["virtualMemory"]
2856 numVirtualCpu
= VnfFlavorData
["additionalParams"]["numVirtualCpu"]
2857 sizeOfStorage
= VnfFlavorData
["additionalParams"]["sizeOfStorage"]
2859 "name": vduid
+ "-flv",
2860 "ram": virtualMemory
,
2861 "vcpus": numVirtualCpu
,
2862 "disk": sizeOfStorage
,
2865 step
= "Creating Tasks for vertical scaling"
2866 with self
.write_lock
:
2867 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
2869 vdu
["vdu-id-ref"] == vduid
2870 and vdu
["count-index"] == vduCountIndex
2872 extra_dict
["params"] = {
2873 "vim_vm_id": vdu
["vim-id"],
2874 "flavor_dict": flavor_dict
,
2876 task
= self
.verticalscale_task(
2885 db_new_tasks
.append(task
)
2888 self
.upload_all_tasks(
2889 db_new_tasks
=db_new_tasks
,
2893 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
2896 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
2900 except Exception as e
:
2901 if isinstance(e
, (DbException
, NsException
)):
2903 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
2906 e
= traceback_format_exc()
2907 self
.logger
.critical(
2908 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
2911 raise NsException(e
)