Reformat files according to new black validation
[osm/RO.git] / NG-RO / osm_ng_ro / ns.py
1 # -*- coding: utf-8 -*-
2
3 ##
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
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
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
14 # implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 ##
18
19 from http import HTTPStatus
20 from itertools import product
21 import logging
22 from random import choice as random_choice
23 from threading import Lock
24 from time import time
25 from traceback import format_exc as traceback_format_exc
26 from typing import Any, Dict, Tuple, Type
27 from uuid import uuid4
28
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
32 from jinja2 import (
33 Environment,
34 select_autoescape,
35 StrictUndefined,
36 TemplateError,
37 TemplateNotFound,
38 UndefinedError,
39 )
40 from osm_common import (
41 dbmemory,
42 dbmongo,
43 fslocal,
44 fsmongo,
45 msgkafka,
46 msglocal,
47 version as common_version,
48 )
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
54 import yaml
55
56 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
57 min_common_version = "0.1.16"
58
59
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)
64
65
66 def get_process_id():
67 """
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
70 :return: Obtained ID
71 """
72 # Try getting docker id. If fails, get pid
73 try:
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]
78
79 if text_id:
80 return text_id
81 except Exception as error:
82 logging.exception(f"{error} occured while getting process id")
83
84 # Return a random id
85 return "".join(random_choice("0123456789abcdef") for _ in range(12))
86
87
88 def versiontuple(v):
89 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
90 filled = []
91
92 for point in v.split("."):
93 filled.append(point.zfill(8))
94
95 return tuple(filled)
96
97
98 class Ns(object):
99 def __init__(self):
100 self.db = None
101 self.fs = None
102 self.msg = None
103 self.config = None
104 # self.operations = None
105 self.logger = 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
108 self.map_topic = {}
109 self.write_lock = None
110 self.vims_assigned = {}
111 self.next_worker = 0
112 self.plugins = {}
113 self.workers = []
114 self.process_params_function_map = {
115 "net": Ns._process_net_params,
116 "image": Ns._process_image_params,
117 "flavor": Ns._process_flavor_params,
118 "vdu": Ns._process_vdu_params,
119 "affinity-or-anti-affinity-group": Ns._process_affinity_group_params,
120 }
121 self.db_path_map = {
122 "net": "vld",
123 "image": "image",
124 "flavor": "flavor",
125 "vdu": "vdur",
126 "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group",
127 }
128
129 def init_db(self, target_version):
130 pass
131
132 def start(self, config):
133 """
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
137 :return: None
138 """
139 self.config = config
140 self.config["process_id"] = get_process_id() # used for HA identity
141 self.logger = logging.getLogger("ro.ns")
142
143 # check right version of common
144 if versiontuple(common_version) < versiontuple(min_common_version):
145 raise NsException(
146 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
147 common_version, min_common_version
148 )
149 )
150
151 try:
152 if not self.db:
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"])
159 else:
160 raise NsException(
161 "Invalid configuration param '{}' at '[database]':'driver'".format(
162 config["database"]["driver"]
163 )
164 )
165
166 if not self.fs:
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:
174 pass
175 else:
176 raise NsException(
177 "Invalid configuration param '{}' at '[storage]':'driver'".format(
178 config["storage"]["driver"]
179 )
180 )
181
182 if not self.msg:
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"])
189 else:
190 raise NsException(
191 "Invalid configuration param '{}' at '[message]':'driver'".format(
192 config["message"]["driver"]
193 )
194 )
195
196 # TODO load workers to deal with exising database tasks
197
198 self.write_lock = Lock()
199 except (DbException, FsException, MsgException) as e:
200 raise NsException(str(e), http_code=e.http_code)
201
202 def get_assigned_vims(self):
203 return list(self.vims_assigned.keys())
204
205 def stop(self):
206 try:
207 if self.db:
208 self.db.db_disconnect()
209
210 if self.fs:
211 self.fs.fs_disconnect()
212
213 if self.msg:
214 self.msg.disconnect()
215
216 self.write_lock = None
217 except (DbException, FsException, MsgException) as e:
218 raise NsException(str(e), http_code=e.http_code)
219
220 for worker in self.workers:
221 worker.insert_task(("terminate",))
222
223 def _create_worker(self):
224 """
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
228 """
229 # Look for a thread in idle status
230 worker_id = next(
231 (
232 i
233 for i in range(len(self.workers))
234 if self.workers[i] and self.workers[i].idle
235 ),
236 None,
237 )
238
239 if worker_id is not None:
240 # unset idle status to avoid race conditions
241 self.workers[worker_id].idle = False
242 else:
243 worker_id = len(self.workers)
244
245 if worker_id < self.config["global"]["server.ns_threads"]:
246 # create a new worker
247 self.workers.append(
248 NsWorker(worker_id, self.config, self.plugins, self.db)
249 )
250 self.workers[worker_id].start()
251 else:
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"][
255 "server.ns_threads"
256 ]
257
258 return worker_id
259
260 def assign_vim(self, target_id):
261 with self.write_lock:
262 return self._assign_vim(target_id)
263
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))
268
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))
276
277 def unload_vim(self, target_id):
278 with self.write_lock:
279 return self._unload_vim(target_id)
280
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]
286
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]
291 else:
292 worker_id = self._create_worker()
293
294 worker = self.workers[worker_id]
295 worker.insert_task(("check_vim", target_id))
296
297 def unload_unused_vims(self):
298 with self.write_lock:
299 vims_to_unload = []
300
301 for target_id in self.vims_assigned:
302 if not self.db.get_one(
303 "ro_tasks",
304 q_filter={
305 "target_id": target_id,
306 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
307 },
308 fail_on_empty=False,
309 ):
310 vims_to_unload.append(target_id)
311
312 for target_id in vims_to_unload:
313 self._unload_vim(target_id)
314
315 @staticmethod
316 def _get_cloud_init(
317 db: Type[DbBase],
318 fs: Type[FsBase],
319 location: str,
320 ) -> str:
321 """This method reads cloud init from a file.
322
323 Note: Not used as cloud init content is provided in the http body.
324
325 Args:
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'
329
330 Raises:
331 NsException: [description]
332 NsException: [description]
333
334 Returns:
335 str: [description]
336 """
337 vnfd_id, _, other = location.partition(":")
338 _type, _, name = other.partition(":")
339 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
340
341 if _type == "file":
342 base_folder = vnfd["_admin"]["storage"]
343 cloud_init_file = "{}/{}/cloud_init/{}".format(
344 base_folder["folder"], base_folder["pkg-dir"], name
345 )
346
347 if not fs:
348 raise NsException(
349 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
350 cloud_init_file
351 )
352 )
353
354 with fs.file_open(cloud_init_file, "r") as ci_file:
355 cloud_init_content = ci_file.read()
356 elif _type == "vdu":
357 cloud_init_content = vnfd["vdu"][int(name)]["cloud-init"]
358 else:
359 raise NsException("Mismatch descriptor for cloud init: {}".format(location))
360
361 return cloud_init_content
362
363 @staticmethod
364 def _parse_jinja2(
365 cloud_init_content: str,
366 params: Dict[str, Any],
367 context: str,
368 ) -> str:
369 """Function that processes the cloud init to replace Jinja2 encoded parameters.
370
371 Args:
372 cloud_init_content (str): [description]
373 params (Dict[str, Any]): [description]
374 context (str): [description]
375
376 Raises:
377 NsException: [description]
378 NsException: [description]
379
380 Returns:
381 str: [description]
382 """
383 try:
384 env = Environment(
385 undefined=StrictUndefined,
386 autoescape=select_autoescape(default_for_string=True, default=True),
387 )
388 template = env.from_string(cloud_init_content)
389
390 return template.render(params or {})
391 except UndefinedError as e:
392 raise NsException(
393 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
394 "inside the 'additionalParamsForVnf' block".format(e, context)
395 )
396 except (TemplateError, TemplateNotFound) as e:
397 raise NsException(
398 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
399 context, e
400 )
401 )
402
403 def _create_db_ro_nsrs(self, nsr_id, now):
404 try:
405 key = rsa.generate_private_key(
406 backend=crypto_default_backend(), public_exponent=65537, key_size=2048
407 )
408 private_key = key.private_bytes(
409 crypto_serialization.Encoding.PEM,
410 crypto_serialization.PrivateFormat.PKCS8,
411 crypto_serialization.NoEncryption(),
412 )
413 public_key = key.public_key().public_bytes(
414 crypto_serialization.Encoding.OpenSSH,
415 crypto_serialization.PublicFormat.OpenSSH,
416 )
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))
424
425 schema_version = "1.1"
426 private_key_encrypted = self.db.encrypt(
427 private_key, schema_version=schema_version, salt=nsr_id
428 )
429 db_content = {
430 "_id": nsr_id,
431 "_admin": {
432 "created": now,
433 "modified": now,
434 "schema_version": schema_version,
435 },
436 "public_key": public_key,
437 "private_key": private_key_encrypted,
438 "actions": [],
439 }
440 self.db.create("ro_nsrs", db_content)
441
442 return db_content
443
444 @staticmethod
445 def _create_task(
446 deployment_info: Dict[str, Any],
447 target_id: str,
448 item: str,
449 action: str,
450 target_record: str,
451 target_record_id: str,
452 extra_dict: Dict[str, Any] = None,
453 ) -> Dict[str, Any]:
454 """Function to create task dict from deployment information.
455
456 Args:
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.
464
465 Returns:
466 Dict[str, Any]: [description]
467 """
468 task = {
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",
474 "action": action,
475 "item": item,
476 "target_record": target_record,
477 "target_record_id": target_record_id,
478 }
479
480 if extra_dict:
481 task.update(extra_dict) # params, find_params, depends_on
482
483 deployment_info["task_index"] = deployment_info.get("task_index", 0) + 1
484
485 return task
486
487 @staticmethod
488 def _create_ro_task(
489 target_id: str,
490 task: Dict[str, Any],
491 ) -> Dict[str, Any]:
492 """Function to create an RO task from task information.
493
494 Args:
495 target_id (str): [description]
496 task (Dict[str, Any]): [description]
497
498 Returns:
499 Dict[str, Any]: [description]
500 """
501 now = time()
502
503 _id = task.get("task_id")
504 db_ro_task = {
505 "_id": _id,
506 "locked_by": None,
507 "locked_at": 0.0,
508 "target_id": target_id,
509 "vim_info": {
510 "created": False,
511 "created_items": None,
512 "vim_id": None,
513 "vim_name": None,
514 "vim_status": None,
515 "vim_details": None,
516 "vim_message": None,
517 "refresh_at": None,
518 },
519 "modified_at": now,
520 "created_at": now,
521 "to_check_at": now,
522 "tasks": [task],
523 }
524
525 return db_ro_task
526
527 @staticmethod
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],
534 ) -> Dict[str, Any]:
535 """Function to process VDU image parameters.
536
537 Args:
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]
542
543 Returns:
544 Dict[str, Any]: [description]
545 """
546 find_params = {}
547
548 if target_image.get("image"):
549 find_params["filter_dict"] = {"name": target_image.get("image")}
550
551 if target_image.get("vim_image_id"):
552 find_params["filter_dict"] = {"id": target_image.get("vim_image_id")}
553
554 if target_image.get("image_checksum"):
555 find_params["filter_dict"] = {
556 "checksum": target_image.get("image_checksum")
557 }
558
559 return {"find_params": find_params}
560
561 @staticmethod
562 def _get_resource_allocation_params(
563 quota_descriptor: Dict[str, Any],
564 ) -> Dict[str, Any]:
565 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
566 descriptor object.
567
568 Args:
569 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
570
571 Returns:
572 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
573 """
574 quota = {}
575
576 if quota_descriptor.get("limit"):
577 quota["limit"] = int(quota_descriptor["limit"])
578
579 if quota_descriptor.get("reserve"):
580 quota["reserve"] = int(quota_descriptor["reserve"])
581
582 if quota_descriptor.get("shares"):
583 quota["shares"] = int(quota_descriptor["shares"])
584
585 return quota
586
587 @staticmethod
588 def _process_guest_epa_quota_params(
589 guest_epa_quota: Dict[str, Any],
590 epa_vcpu_set: bool,
591 ) -> Dict[str, Any]:
592 """Function to extract the guest epa quota parameters.
593
594 Args:
595 guest_epa_quota (Dict[str, Any]): [description]
596 epa_vcpu_set (bool): [description]
597
598 Returns:
599 Dict[str, Any]: [description]
600 """
601 result = {}
602
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")
606 )
607
608 if cpuquota:
609 result["cpu-quota"] = cpuquota
610
611 if guest_epa_quota.get("mem-quota"):
612 vduquota = Ns._get_resource_allocation_params(
613 guest_epa_quota.get("mem-quota")
614 )
615
616 if vduquota:
617 result["mem-quota"] = vduquota
618
619 if guest_epa_quota.get("disk-io-quota"):
620 diskioquota = Ns._get_resource_allocation_params(
621 guest_epa_quota.get("disk-io-quota")
622 )
623
624 if diskioquota:
625 result["disk-io-quota"] = diskioquota
626
627 if guest_epa_quota.get("vif-quota"):
628 vifquota = Ns._get_resource_allocation_params(
629 guest_epa_quota.get("vif-quota")
630 )
631
632 if vifquota:
633 result["vif-quota"] = vifquota
634
635 return result
636
637 @staticmethod
638 def _process_guest_epa_numa_params(
639 guest_epa_quota: Dict[str, Any],
640 ) -> Tuple[Dict[str, Any], bool]:
641 """[summary]
642
643 Args:
644 guest_epa_quota (Dict[str, Any]): [description]
645
646 Returns:
647 Tuple[Dict[str, Any], bool]: [description]
648 """
649 numa = {}
650 numa_list = []
651 epa_vcpu_set = False
652
653 if guest_epa_quota.get("numa-node-policy"):
654 numa_node_policy = guest_epa_quota.get("numa-node-policy")
655
656 if numa_node_policy.get("node"):
657 for numa_node in numa_node_policy["node"]:
658 vcpu_list = []
659 if numa_node.get("id"):
660 numa["id"] = int(numa_node["id"])
661
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
667
668 if numa_node.get("num-cores"):
669 numa["cores"] = numa_node["num-cores"]
670 epa_vcpu_set = True
671
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"]
676 )
677 epa_vcpu_set = True
678
679 if paired_threads.get("paired-thread-ids"):
680 numa["paired-threads-id"] = []
681
682 for pair in paired_threads["paired-thread-ids"]:
683 numa["paired-threads-id"].append(
684 (
685 str(pair["thread-a"]),
686 str(pair["thread-b"]),
687 )
688 )
689
690 if numa_node.get("num-threads"):
691 numa["threads"] = int(numa_node["num-threads"])
692 epa_vcpu_set = True
693
694 if numa_node.get("memory-mb"):
695 numa["memory"] = max(int(int(numa_node["memory-mb"]) / 1024), 1)
696
697 numa_list.append(numa)
698 numa = {}
699
700 return numa_list, epa_vcpu_set
701
702 @staticmethod
703 def _process_guest_epa_cpu_pinning_params(
704 guest_epa_quota: Dict[str, Any],
705 vcpu_count: int,
706 epa_vcpu_set: bool,
707 ) -> Tuple[Dict[str, Any], bool]:
708 """[summary]
709
710 Args:
711 guest_epa_quota (Dict[str, Any]): [description]
712 vcpu_count (int): [description]
713 epa_vcpu_set (bool): [description]
714
715 Returns:
716 Tuple[Dict[str, Any], bool]: [description]
717 """
718 numa = {}
719 local_epa_vcpu_set = epa_vcpu_set
720
721 if (
722 guest_epa_quota.get("cpu-pinning-policy") == "DEDICATED"
723 and not epa_vcpu_set
724 ):
725 numa[
726 "cores"
727 if guest_epa_quota.get("cpu-thread-pinning-policy") != "PREFER"
728 else "threads"
729 ] = max(vcpu_count, 1)
730 local_epa_vcpu_set = True
731
732 return numa, local_epa_vcpu_set
733
734 @staticmethod
735 def _process_epa_params(
736 target_flavor: Dict[str, Any],
737 ) -> Dict[str, Any]:
738 """[summary]
739
740 Args:
741 target_flavor (Dict[str, Any]): [description]
742
743 Returns:
744 Dict[str, Any]: [description]
745 """
746 extended = {}
747 numa = {}
748 numa_list = []
749
750 if target_flavor.get("guest-epa"):
751 guest_epa = target_flavor["guest-epa"]
752
753 numa_list, epa_vcpu_set = Ns._process_guest_epa_numa_params(
754 guest_epa_quota=guest_epa
755 )
756
757 if guest_epa.get("mempage-size"):
758 extended["mempage-size"] = guest_epa.get("mempage-size")
759
760 if guest_epa.get("cpu-pinning-policy"):
761 extended["cpu-pinning-policy"] = guest_epa.get("cpu-pinning-policy")
762
763 if guest_epa.get("cpu-thread-pinning-policy"):
764 extended["cpu-thread-pinning-policy"] = guest_epa.get(
765 "cpu-thread-pinning-policy"
766 )
767
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(
771 "mem-policy"
772 )
773
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,
778 )
779 for numa in numa_list:
780 numa.update(tmp_numa)
781
782 extended.update(
783 Ns._process_guest_epa_quota_params(
784 guest_epa_quota=guest_epa,
785 epa_vcpu_set=epa_vcpu_set,
786 )
787 )
788
789 if numa:
790 extended["numas"] = numa_list
791
792 return extended
793
794 @staticmethod
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],
801 ) -> Dict[str, Any]:
802 """[summary]
803
804 Args:
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]
809
810 Returns:
811 Dict[str, Any]: [description]
812 """
813 db = kwargs.get("db")
814 target_vdur = {}
815
816 flavor_data = {
817 "disk": int(target_flavor["storage-gb"]),
818 "ram": int(target_flavor["memory-mb"]),
819 "vcpus": int(target_flavor["vcpu-count"]),
820 }
821
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"):
825 target_vdur = vdur
826
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]:
835 root_disk = vsd
836 if (
837 root_disk.get("type-of-storage")
838 == "persistent-storage:persistent-storage"
839 ):
840 flavor_data["disk"] = 0
841
842 for storage in target_vdur.get("virtual-storages", []):
843 if (
844 storage.get("type-of-storage")
845 == "etsi-nfv-descriptors:ephemeral-storage"
846 ):
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))
850
851 extended = Ns._process_epa_params(target_flavor)
852 if extended:
853 flavor_data["extended"] = extended
854
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}
859
860 return extra_dict
861
862 @staticmethod
863 def _ip_profile_to_ro(
864 ip_profile: Dict[str, Any],
865 ) -> Dict[str, Any]:
866 """[summary]
867
868 Args:
869 ip_profile (Dict[str, Any]): [description]
870
871 Returns:
872 Dict[str, Any]: [description]
873 """
874 if not ip_profile:
875 return None
876
877 ro_ip_profile = {
878 "ip_version": "IPv4"
879 if "v4" in ip_profile.get("ip-version", "ipv4")
880 else "IPv6",
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
886 ),
887 "dhcp_count": ip_profile.get("dhcp-params", {}).get("count", None),
888 }
889
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")]
893 )
894
895 if ip_profile.get("security-group"):
896 ro_ip_profile["security_group"] = ip_profile["security-group"]
897
898 return ro_ip_profile
899
900 @staticmethod
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],
907 ) -> Dict[str, Any]:
908 """Function to process network parameters.
909
910 Args:
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]
915
916 Returns:
917 Dict[str, Any]: [description]
918 """
919 extra_dict = {}
920
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"] = {
927 k: vim_info[k]
928 for k in ("sdn-ports", "target_vim", "vlds", "type")
929 if vim_info.get(k)
930 }
931
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}"
936 ]
937
938 return extra_dict
939
940 if vim_info.get("vim_network_name"):
941 extra_dict["find_params"] = {
942 "filter_dict": {
943 "name": vim_info.get("vim_network_name"),
944 },
945 }
946 elif vim_info.get("vim_network_id"):
947 extra_dict["find_params"] = {
948 "filter_dict": {
949 "id": vim_info.get("vim_network_id"),
950 },
951 }
952 elif target_vld.get("mgmt-network") and not vim_info.get("provider_network"):
953 extra_dict["find_params"] = {
954 "mgmt": True,
955 "name": target_vld["id"],
956 }
957 else:
958 # create
959 extra_dict["params"] = {
960 "net_name": (
961 f"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
962 ),
963 "ip_profile": Ns._ip_profile_to_ro(vim_info.get("ip_profile")),
964 "provider_network_profile": vim_info.get("provider_network"),
965 }
966
967 if not target_vld.get("underlay"):
968 extra_dict["params"]["net_type"] = "bridge"
969 else:
970 extra_dict["params"]["net_type"] = (
971 "ptp" if target_vld.get("type") == "ELINE" else "data"
972 )
973
974 return extra_dict
975
976 @staticmethod
977 def find_persistent_root_volumes(
978 vnfd: dict,
979 target_vdu: str,
980 vdu_instantiation_volumes_list: list,
981 disk_list: list,
982 ) -> (list, dict):
983 """Find the persistent root volumes and add them to the disk_list
984 by parsing the instantiation parameters
985
986 Args:
987 vnfd: VNFD
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
991
992 Returns:
993 disk_list: filled VDU list which is used for VDU creation
994
995 """
996 persistent_root_disk = {}
997
998 for vdu, vsd in product(
999 vnfd.get("vdu", ()), vnfd.get("virtual-storage-desc", ())
1000 ):
1001 if (
1002 vdu["name"] == target_vdu["vdu-name"]
1003 and vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]
1004 ):
1005 root_disk = vsd
1006 if (
1007 root_disk.get("type-of-storage")
1008 == "persistent-storage:persistent-storage"
1009 ):
1010 for vdu_volume in vdu_instantiation_volumes_list:
1011 if (
1012 vdu_volume["vim-volume-id"]
1013 and root_disk["id"] == vdu_volume["name"]
1014 ):
1015 persistent_root_disk[vsd["id"]] = {
1016 "vim_volume_id": vdu_volume["vim-volume-id"],
1017 "image_id": vdu.get("sw-image-desc"),
1018 }
1019
1020 disk_list.append(persistent_root_disk[vsd["id"]])
1021
1022 # There can be only one root disk, when we find it, it will return the result
1023 return disk_list, persistent_root_disk
1024
1025 else:
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"),
1030 }
1031
1032 disk_list.append(persistent_root_disk[vsd["id"]])
1033 return disk_list, persistent_root_disk
1034
1035 return disk_list, persistent_root_disk
1036
1037 @staticmethod
1038 def find_persistent_volumes(
1039 persistent_root_disk: dict,
1040 target_vdu: str,
1041 vdu_instantiation_volumes_list: list,
1042 disk_list: list,
1043 ) -> list:
1044 """Find the ordinary persistent volumes and add them to the disk_list
1045 by parsing the instantiation parameters
1046
1047 Args:
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
1052
1053 Returns:
1054 disk_list: filled VDU list which is used for VDU creation
1055
1056 """
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", {}):
1060 if (
1061 disk.get("type-of-storage") == "persistent-storage:persistent-storage"
1062 and disk["id"] not in persistent_root_disk.keys()
1063 ):
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"],
1068 }
1069 disk_list.append(persistent_disk[disk["id"]])
1070
1071 else:
1072 if disk["id"] not in persistent_disk.keys():
1073 persistent_disk[disk["id"]] = {
1074 "size": disk.get("size-of-storage"),
1075 }
1076 disk_list.append(persistent_disk[disk["id"]])
1077
1078 return disk_list
1079
1080 @staticmethod
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.
1089
1090 Args:
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]
1095
1096 Returns:
1097 Dict[str, Any]: [description]
1098 """
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")
1108
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]}
1114 net_list = []
1115
1116 # If the position info is provided for all the interfaces, it will be sorted
1117 # according to position number ascendingly.
1118 if all(
1119 i.get("position") + 1
1120 for i in target_vdu["interfaces"]
1121 if i.get("position") is not None
1122 ):
1123 sorted_interfaces = sorted(
1124 target_vdu["interfaces"],
1125 key=lambda x: (x.get("position") is None, x.get("position")),
1126 )
1127 target_vdu["interfaces"] = sorted_interfaces
1128
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.
1131 else:
1132 if any(
1133 i.get("position") + 1
1134 for i in target_vdu["interfaces"]
1135 if i.get("position") is not None
1136 ):
1137 n = len(target_vdu["interfaces"])
1138 sorted_interfaces = [-1] * n
1139 k, m = 0, 0
1140 while k < 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]
1144 k += 1
1145 while m < n:
1146 if not target_vdu["interfaces"][m].get("position"):
1147 idy = sorted_interfaces.index(-1)
1148 sorted_interfaces[idy] = target_vdu["interfaces"][m]
1149 m += 1
1150
1151 target_vdu["interfaces"] = sorted_interfaces
1152
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"]
1160 else:
1161 logger.error(
1162 "Interface {} from vdu {} not connected to any vld".format(
1163 iface_index, target_vdu["vdu-name"]
1164 )
1165 )
1166
1167 continue # interface not connected to any vld
1168
1169 extra_dict["depends_on"].append(net_text)
1170
1171 if "port-security-enabled" in interface:
1172 interface["port_security"] = interface.pop("port-security-enabled")
1173
1174 if "port-security-disable-strategy" in interface:
1175 interface["port_security_disable_strategy"] = interface.pop(
1176 "port-security-disable-strategy"
1177 )
1178
1179 net_item = {
1180 x: v
1181 for x, v in interface.items()
1182 if x
1183 in (
1184 "name",
1185 "vpci",
1186 "port_security",
1187 "port_security_disable_strategy",
1188 "floating_ip",
1189 )
1190 }
1191 net_item["net_id"] = "TASK-" + net_text
1192 net_item["type"] = "virtual"
1193
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
1198 if deep_get(
1199 tasks_by_target_record_id,
1200 net_text,
1201 "extra_dict",
1202 "params",
1203 "net_type",
1204 ):
1205 tasks_by_target_record_id[net_text]["extra_dict"]["params"][
1206 "net_type"
1207 ] = "data"
1208
1209 net_item["use"] = "data"
1210 net_item["model"] = interface["type"]
1211 net_item["type"] = interface["type"]
1212 elif (
1213 interface.get("type") == "OM-MGMT"
1214 or interface.get("mgmt-interface")
1215 or interface.get("mgmt-vnf")
1216 ):
1217 net_item["use"] = "mgmt"
1218 else:
1219 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1220 net_item["use"] = "bridge"
1221 net_item["model"] = interface.get("type")
1222
1223 if interface.get("ip-address"):
1224 net_item["ip_address"] = interface["ip-address"]
1225
1226 if interface.get("mac-address"):
1227 net_item["mac_address"] = interface["mac-address"]
1228
1229 net_list.append(net_item)
1230
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
1235
1236 # cloud config
1237 cloud_config = {}
1238
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(
1242 db=db,
1243 fs=fs,
1244 location=target_vdu["cloud-init"],
1245 )
1246
1247 cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
1248 cloud_config["user-data"] = Ns._parse_jinja2(
1249 cloud_init_content=cloud_content_,
1250 params=target_vdu.get("additionalParams"),
1251 context=target_vdu["cloud-init"],
1252 )
1253
1254 if target_vdu.get("boot-data-drive"):
1255 cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
1256
1257 ssh_keys = []
1258
1259 if target_vdu.get("ssh-keys"):
1260 ssh_keys += target_vdu.get("ssh-keys")
1261
1262 if target_vdu.get("ssh-access-required"):
1263 ssh_keys.append(ro_nsr_public_key)
1264
1265 if ssh_keys:
1266 cloud_config["key-pairs"] = ssh_keys
1267
1268 persistent_root_disk = {}
1269 vdu_instantiation_volumes_list = []
1270 disk_list = []
1271 vnfd_id = vnfr["vnfd-id"]
1272 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
1273
1274 if target_vdu.get("additionalParams"):
1275 vdu_instantiation_volumes_list = (
1276 target_vdu.get("additionalParams").get("OSM").get("vdu_volumes")
1277 )
1278
1279 if vdu_instantiation_volumes_list:
1280 # Find the root volumes and add to the disk_list
1281 (
1282 disk_list,
1283 persistent_root_disk,
1284 ) = Ns.find_persistent_root_volumes(
1285 vnfd, target_vdu, vdu_instantiation_volumes_list, disk_list
1286 )
1287
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,
1292 target_vdu,
1293 vdu_instantiation_volumes_list,
1294 disk_list,
1295 )
1296
1297 else:
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]:
1303 root_disk = vsd
1304 if root_disk.get(
1305 "type-of-storage"
1306 ) == "persistent-storage:persistent-storage" and root_disk.get(
1307 "size-of-storage"
1308 ):
1309 persistent_root_disk[vsd["id"]] = {
1310 "image_id": vdu.get("sw-image-desc"),
1311 "size": root_disk["size-of-storage"],
1312 }
1313 disk_list.append(persistent_root_disk[vsd["id"]])
1314
1315 if target_vdu.get("virtual-storages"):
1316 for disk in target_vdu["virtual-storages"]:
1317 if (
1318 disk.get("type-of-storage")
1319 == "persistent-storage:persistent-storage"
1320 and disk["id"] not in persistent_root_disk.keys()
1321 ):
1322 disk_list.append({"size": disk["size-of-storage"]})
1323
1324 affinity_group_list = []
1325
1326 if target_vdu.get("affinity-or-anti-affinity-group-id"):
1327 affinity_group = {}
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
1331 )
1332
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)
1336
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,
1343 ),
1344 "description": target_vdu["vdu-name"],
1345 "start": True,
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
1354 }
1355
1356 return extra_dict
1357
1358 @staticmethod
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.
1367
1368 Args:
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]
1373
1374 Returns:
1375 Dict[str, Any]: [description]
1376 """
1377
1378 extra_dict = {}
1379 affinity_group_data = {
1380 "name": target_affinity_group["name"],
1381 "type": target_affinity_group["type"],
1382 "scope": target_affinity_group["scope"],
1383 }
1384
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"
1388 ]
1389
1390 extra_dict["params"] = {
1391 "affinity_group_data": affinity_group_data,
1392 }
1393
1394 return extra_dict
1395
1396 @staticmethod
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,
1402 target_id: str,
1403 **kwargs: Dict[str, Any],
1404 ) -> Dict[str, Any]:
1405 """Function to process VDU parameters to recreate.
1406
1407 Args:
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]
1413
1414 Returns:
1415 Dict[str, Any]: [description]
1416 """
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")
1423
1424 extra_dict = {}
1425 net_list = []
1426
1427 vim_details = {}
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}")
1431
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")
1435
1436 if "port-security-disable-strategy" in interface:
1437 interface["port_security_disable_strategy"] = interface.pop(
1438 "port-security-disable-strategy"
1439 )
1440
1441 net_item = {
1442 x: v
1443 for x, v in interface.items()
1444 if x
1445 in (
1446 "name",
1447 "vpci",
1448 "port_security",
1449 "port_security_disable_strategy",
1450 "floating_ip",
1451 )
1452 }
1453 existing_ifaces = existing_vdu["vim_info"][target_id].get(
1454 "interfaces_backup", []
1455 )
1456 net_id = next(
1457 (
1458 i["vim_net_id"]
1459 for i in existing_ifaces
1460 if i["ip_address"] == interface["ip-address"]
1461 ),
1462 None,
1463 )
1464
1465 net_item["net_id"] = net_id
1466 net_item["type"] = "virtual"
1467
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"]
1474 elif (
1475 interface.get("type") == "OM-MGMT"
1476 or interface.get("mgmt-interface")
1477 or interface.get("mgmt-vnf")
1478 ):
1479 net_item["use"] = "mgmt"
1480 else:
1481 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1482 net_item["use"] = "bridge"
1483 net_item["model"] = interface.get("type")
1484
1485 if interface.get("ip-address"):
1486 net_item["ip_address"] = interface["ip-address"]
1487
1488 if interface.get("mac-address"):
1489 net_item["mac_address"] = interface["mac-address"]
1490
1491 net_list.append(net_item)
1492
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
1497
1498 # cloud config
1499 cloud_config = {}
1500
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(
1504 db=db,
1505 fs=fs,
1506 location=existing_vdu["cloud-init"],
1507 )
1508
1509 cloud_content_ = vdu2cloud_init[existing_vdu["cloud-init"]]
1510 cloud_config["user-data"] = Ns._parse_jinja2(
1511 cloud_init_content=cloud_content_,
1512 params=existing_vdu.get("additionalParams"),
1513 context=existing_vdu["cloud-init"],
1514 )
1515
1516 if existing_vdu.get("boot-data-drive"):
1517 cloud_config["boot-data-drive"] = existing_vdu.get("boot-data-drive")
1518
1519 ssh_keys = []
1520
1521 if existing_vdu.get("ssh-keys"):
1522 ssh_keys += existing_vdu.get("ssh-keys")
1523
1524 if existing_vdu.get("ssh-access-required"):
1525 ssh_keys.append(ro_nsr_public_key)
1526
1527 if ssh_keys:
1528 cloud_config["key-pairs"] = ssh_keys
1529
1530 disk_list = []
1531 for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
1532 disk_list.append({"vim_id": vol_id["id"]})
1533
1534 affinity_group_list = []
1535
1536 if existing_vdu.get("affinity-or-anti-affinity-group-id"):
1537 affinity_group = {}
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"):
1540 if (
1541 group["id"] == affinity_group_id
1542 and group["vim_info"][target_id].get("vim_id", None) is not None
1543 ):
1544 affinity_group["affinity_group_id"] = group["vim_info"][
1545 target_id
1546 ].get("vim_id", None)
1547 affinity_group_list.append(affinity_group)
1548
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,
1555 ),
1556 "description": existing_vdu["vdu-name"],
1557 "start": True,
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
1566 }
1567
1568 return extra_dict
1569
1570 def calculate_diff_items(
1571 self,
1572 indata,
1573 db_nsr,
1574 db_ro_nsr,
1575 db_nsr_update,
1576 item,
1577 tasks_by_target_record_id,
1578 action_id,
1579 nsr_id,
1580 task_index,
1581 vnfr_id=None,
1582 vnfr=None,
1583 ):
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
1593 `item`)
1594
1595 Args:
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
1608
1609 Returns:
1610 List: list with the incremental changes (deletes, creates) for each item
1611 number: current task index
1612 """
1613
1614 diff_items = []
1615 db_path = ""
1616 db_record = ""
1617 target_list = []
1618 existing_list = []
1619 process_params = None
1620 vdu2cloud_init = indata.get("cloud_init_content") or {}
1621 ro_nsr_public_key = db_ro_nsr["public_key"]
1622
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)
1629 if vnfr is None:
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
1634 else:
1635 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
1636 target_vnf = next(
1637 (vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id),
1638 None,
1639 )
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, [])
1646 else:
1647 raise NsException("Item not supported: {}", item)
1648
1649 # ensure all the target_list elements has an "id". If not assign the index as id
1650 if target_list is None:
1651 target_list = []
1652 for target_index, tl in enumerate(target_list):
1653 if tl and not tl.get("id"):
1654 tl["id"] = str(target_index)
1655
1656 # step 1 items (networks,vdus,...) to be deleted/updated
1657 for item_index, existing_item in enumerate(existing_list):
1658 target_item = next(
1659 (t for t in target_list if t["id"] == existing_item["id"]),
1660 None,
1661 )
1662
1663 for target_vim, existing_viminfo in existing_item.get(
1664 "vim_info", {}
1665 ).items():
1666 if existing_viminfo is None:
1667 continue
1668
1669 if target_item:
1670 target_viminfo = target_item.get("vim_info", {}).get(target_vim)
1671 else:
1672 target_viminfo = None
1673
1674 if target_viminfo is None:
1675 # must be deleted
1676 self._assign_vim(target_vim)
1677 target_record_id = "{}.{}".format(db_record, existing_item["id"])
1678 item_ = item
1679
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
1682 item_ = "sdn_net"
1683 target_record_id += ".sdn"
1684
1685 deployment_info = {
1686 "action_id": action_id,
1687 "nsr_id": nsr_id,
1688 "task_index": task_index,
1689 }
1690
1691 diff_items.append(
1692 {
1693 "deployment_info": deployment_info,
1694 "target_id": target_vim,
1695 "item": item_,
1696 "action": "DELETE",
1697 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1698 "target_record_id": target_record_id,
1699 }
1700 )
1701 task_index += 1
1702
1703 # step 2 items (networks,vdus,...) to be created
1704 for target_item in target_list:
1705 item_index = -1
1706
1707 for item_index, existing_item in enumerate(existing_list):
1708 if existing_item["id"] == target_item["id"]:
1709 break
1710 else:
1711 item_index += 1
1712 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1713 existing_list.append(target_item)
1714 existing_item = None
1715
1716 for target_vim, target_viminfo in target_item.get("vim_info", {}).items():
1717 existing_viminfo = None
1718
1719 if existing_item:
1720 existing_viminfo = existing_item.get("vim_info", {}).get(target_vim)
1721
1722 if existing_viminfo is not None:
1723 continue
1724
1725 target_record_id = "{}.{}".format(db_record, target_item["id"])
1726 item_ = item
1727
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
1730 item_ = "sdn_net"
1731 target_record_id += ".sdn"
1732
1733 kwargs = {}
1734 self.logger.warning(
1735 "ns.calculate_diff_items target_item={}".format(target_item)
1736 )
1737 if process_params == Ns._process_flavor_params:
1738 kwargs.update(
1739 {
1740 "db": self.db,
1741 }
1742 )
1743 self.logger.warning(
1744 "calculate_diff_items for flavor kwargs={}".format(kwargs)
1745 )
1746
1747 if process_params == Ns._process_vdu_params:
1748 self.logger.warning(
1749 "calculate_diff_items self.fs={}".format(self.fs)
1750 )
1751 kwargs.update(
1752 {
1753 "vnfr_id": vnfr_id,
1754 "nsr_id": nsr_id,
1755 "vnfr": vnfr,
1756 "vdu2cloud_init": vdu2cloud_init,
1757 "tasks_by_target_record_id": tasks_by_target_record_id,
1758 "logger": self.logger,
1759 "db": self.db,
1760 "fs": self.fs,
1761 "ro_nsr_public_key": ro_nsr_public_key,
1762 }
1763 )
1764 self.logger.warning("calculate_diff_items kwargs={}".format(kwargs))
1765
1766 extra_dict = process_params(
1767 target_item,
1768 indata,
1769 target_viminfo,
1770 target_record_id,
1771 **kwargs,
1772 )
1773 self._assign_vim(target_vim)
1774
1775 deployment_info = {
1776 "action_id": action_id,
1777 "nsr_id": nsr_id,
1778 "task_index": task_index,
1779 }
1780
1781 new_item = {
1782 "deployment_info": deployment_info,
1783 "target_id": target_vim,
1784 "item": item_,
1785 "action": "CREATE",
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),
1790 }
1791 diff_items.append(new_item)
1792 tasks_by_target_record_id[target_record_id] = new_item
1793 task_index += 1
1794
1795 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1796
1797 return diff_items, task_index
1798
1799 def calculate_all_differences_to_deploy(
1800 self,
1801 indata,
1802 nsr_id,
1803 db_nsr,
1804 db_vnfrs,
1805 db_ro_nsr,
1806 db_nsr_update,
1807 db_vnfrs_update,
1808 action_id,
1809 tasks_by_target_record_id,
1810 ):
1811 """This method calculates the ordered list of items (`changes_list`)
1812 to be created and deleted.
1813
1814 Args:
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>]
1825
1826 Returns:
1827 List: ordered list of items to be created and deleted.
1828 """
1829
1830 task_index = 0
1831 # set list with diffs:
1832 changes_list = []
1833
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(
1838 indata=indata,
1839 db_nsr=db_nsr,
1840 db_ro_nsr=db_ro_nsr,
1841 db_nsr_update=db_nsr_update,
1842 item=item,
1843 tasks_by_target_record_id=tasks_by_target_record_id,
1844 action_id=action_id,
1845 nsr_id=nsr_id,
1846 task_index=task_index,
1847 vnfr_id=None,
1848 )
1849 changes_list += diff_items
1850
1851 # VNF vlds and vdus
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(
1857 indata=indata,
1858 db_nsr=db_nsr,
1859 db_ro_nsr=db_ro_nsr,
1860 db_nsr_update=db_vnfrs_update[vnfr["_id"]],
1861 item=item,
1862 tasks_by_target_record_id=tasks_by_target_record_id,
1863 action_id=action_id,
1864 nsr_id=nsr_id,
1865 task_index=task_index,
1866 vnfr_id=vnfr_id,
1867 vnfr=vnfr,
1868 )
1869 changes_list += diff_items
1870
1871 return changes_list
1872
1873 def define_all_tasks(
1874 self,
1875 changes_list,
1876 db_new_tasks,
1877 tasks_by_target_record_id,
1878 ):
1879 """Function to create all the task structures obtanied from
1880 the method calculate_all_differences_to_deploy
1881
1882 Args:
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>]
1888
1889 """
1890
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),
1900 )
1901
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)
1905
1906 if change.get("common_id"):
1907 task["common_id"] = change["common_id"]
1908
1909 def upload_all_tasks(
1910 self,
1911 db_new_tasks,
1912 now,
1913 ):
1914 """Function to save all tasks in the common DB
1915
1916 Args:
1917 db_new_tasks (List): tasks list to be created
1918 now (time): current time
1919
1920 """
1921
1922 nb_ro_tasks = 0 # for logging
1923
1924 for db_task in db_new_tasks:
1925 target_id = db_task.pop("target_id")
1926 common_id = db_task.get("common_id")
1927
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.
1931
1932 if common_id:
1933 if self.db.set_one(
1934 "ro_tasks",
1935 q_filter={
1936 "target_id": target_id,
1937 "tasks.common_id": common_id,
1938 "vim_info.vim_status.ne": "DELETED",
1939 },
1940 update_dict={"to_check_at": now, "modified_at": now},
1941 push={"tasks": db_task},
1942 fail_on_empty=False,
1943 ):
1944 continue
1945
1946 if not self.db.set_one(
1947 "ro_tasks",
1948 q_filter={
1949 "target_id": target_id,
1950 "tasks.target_record": db_task["target_record"],
1951 "vim_info.vim_status.ne": "DELETED",
1952 },
1953 update_dict={"to_check_at": now, "modified_at": now},
1954 push={"tasks": db_task},
1955 fail_on_empty=False,
1956 ):
1957 # Create a ro_task
1958 self.logger.debug("Updating database, Creating ro_tasks")
1959 db_ro_task = Ns._create_ro_task(target_id, db_task)
1960 nb_ro_tasks += 1
1961 self.db.create("ro_tasks", db_ro_task)
1962
1963 self.logger.debug(
1964 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1965 nb_ro_tasks, len(db_new_tasks), db_new_tasks
1966 )
1967 )
1968
1969 def upload_recreate_tasks(
1970 self,
1971 db_new_tasks,
1972 now,
1973 ):
1974 """Function to save recreate tasks in the common DB
1975
1976 Args:
1977 db_new_tasks (List): tasks list to be created
1978 now (time): current time
1979
1980 """
1981
1982 nb_ro_tasks = 0 # for logging
1983
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))
1987
1988 action = db_task.get("action", None)
1989
1990 # Create a ro_task
1991 self.logger.debug("Updating database, Creating ro_tasks")
1992 db_ro_task = Ns._create_ro_task(target_id, db_task)
1993
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(
1999 "created_items", {}
2000 )
2001 db_ro_task["vim_info"]["volumes_to_hold"] = db_task.get(
2002 "volumes_to_hold", []
2003 )
2004 db_ro_task["vim_info"]["vim_id"] = db_task.get("vim_id", None)
2005
2006 nb_ro_tasks += 1
2007 self.logger.warning("upload_all_tasks db_ro_task={}".format(db_ro_task))
2008 self.db.create("ro_tasks", db_ro_task)
2009
2010 self.logger.debug(
2011 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2012 nb_ro_tasks, len(db_new_tasks), db_new_tasks
2013 )
2014 )
2015
2016 def _prepare_created_items_for_healing(
2017 self,
2018 nsr_id,
2019 target_record,
2020 ):
2021 created_items = {}
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"]:
2026 if (
2027 task["target_record"] == target_record
2028 and task["action"] == "CREATE"
2029 and ro_task["vim_info"]["created_items"]
2030 ):
2031 created_items = ro_task["vim_info"]["created_items"]
2032 break
2033
2034 return created_items
2035
2036 def _prepare_persistent_volumes_for_healing(
2037 self,
2038 target_id,
2039 existing_vdu,
2040 ):
2041 # The associated volumes of the VM shouldn't be removed
2042 volumes_list = []
2043 vim_details = {}
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}")
2047
2048 for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
2049 volumes_list.append(vol_id["id"])
2050
2051 return volumes_list
2052
2053 def prepare_changes_to_recreate(
2054 self,
2055 indata,
2056 nsr_id,
2057 db_nsr,
2058 db_vnfrs,
2059 db_ro_nsr,
2060 action_id,
2061 tasks_by_target_record_id,
2062 ):
2063 """This method will obtain an ordered list of items (`changes_list`)
2064 to be created and deleted to meet the recreate request.
2065 """
2066
2067 self.logger.debug(
2068 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id, indata)
2069 )
2070
2071 task_index = 0
2072 # set list with diffs:
2073 changes_list = []
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"]
2078
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", "")
2086
2087 target_vdus = target_vnf.get("additionalParams", {}).get("vdu", [])
2088 # Check each VDU of this VNF
2089 if not target_vdus:
2090 # Create target_vdu_list from DB, if VDUs are not specified
2091 target_vdus = []
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)
2102 item_index = 0
2103 existing_instance = None
2104 for instance in existing_vnf.get("vdur", None):
2105 if (
2106 instance["vdu-name"] == vdu_name
2107 and instance["count-index"] == count_index
2108 ):
2109 existing_instance = instance
2110 break
2111 else:
2112 item_index += 1
2113
2114 target_record_id = "{}.{}".format(db_record, existing_instance["id"])
2115
2116 # The target VIM is the one already existing in DB to recreate
2117 for target_vim, target_viminfo in existing_instance.get(
2118 "vim_info", {}
2119 ).items():
2120 # step 1 vdu to be deleted
2121 self._assign_vim(target_vim)
2122 deployment_info = {
2123 "action_id": action_id,
2124 "nsr_id": nsr_id,
2125 "task_index": task_index,
2126 }
2127
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
2131 )
2132
2133 volumes_to_hold = self._prepare_persistent_volumes_for_healing(
2134 target_vim, existing_instance
2135 )
2136
2137 # Specific extra params for recreate tasks:
2138 extra_dict = {
2139 "created_items": created_items,
2140 "vim_id": existing_instance["vim-id"],
2141 "volumes_to_hold": volumes_to_hold,
2142 }
2143
2144 changes_list.append(
2145 {
2146 "deployment_info": deployment_info,
2147 "target_id": target_vim,
2148 "item": "vdu",
2149 "action": "DELETE",
2150 "target_record": target_record,
2151 "target_record_id": target_record_id,
2152 "extra_dict": extra_dict,
2153 }
2154 )
2155 delete_task_id = f"{action_id}:{task_index}"
2156 task_index += 1
2157
2158 # step 2 vdu to be created
2159 kwargs = {}
2160 kwargs.update(
2161 {
2162 "vnfr_id": vnfr_id,
2163 "nsr_id": nsr_id,
2164 "vnfr": existing_vnf,
2165 "vdu2cloud_init": vdu2cloud_init,
2166 "tasks_by_target_record_id": tasks_by_target_record_id,
2167 "logger": self.logger,
2168 "db": self.db,
2169 "fs": self.fs,
2170 "ro_nsr_public_key": ro_nsr_public_key,
2171 }
2172 )
2173
2174 extra_dict = self._process_recreate_vdu_params(
2175 existing_instance,
2176 db_nsr,
2177 target_viminfo,
2178 target_record_id,
2179 target_vim,
2180 **kwargs,
2181 )
2182
2183 # The CREATE task depens on the DELETE task
2184 extra_dict["depends_on"] = [delete_task_id]
2185
2186 # Add volumes created from created_items if any
2187 # Ports should be deleted with delete task and automatically created with create task
2188 volumes = {}
2189 for k, v in created_items.items():
2190 try:
2191 k_item, _, k_id = k.partition(":")
2192 if k_item == "volume":
2193 volumes[k] = v
2194 except Exception as e:
2195 self.logger.error(
2196 "Error evaluating created item {}: {}".format(k, e)
2197 )
2198 extra_dict["previous_created_volumes"] = volumes
2199
2200 deployment_info = {
2201 "action_id": action_id,
2202 "nsr_id": nsr_id,
2203 "task_index": task_index,
2204 }
2205 self._assign_vim(target_vim)
2206
2207 new_item = {
2208 "deployment_info": deployment_info,
2209 "target_id": target_vim,
2210 "item": "vdu",
2211 "action": "CREATE",
2212 "target_record": target_record,
2213 "target_record_id": target_record_id,
2214 "extra_dict": extra_dict,
2215 }
2216 changes_list.append(new_item)
2217 tasks_by_target_record_id[target_record_id] = new_item
2218 task_index += 1
2219
2220 return changes_list
2221
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
2228 step = ""
2229 logging_text = "Recreate nsr_id={} action_id={} indata={}".format(
2230 nsr_id, action_id, indata
2231 )
2232 self.logger.debug(logging_text + "Enter")
2233
2234 try:
2235 step = "Getting ns and vnfr record from db"
2236 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2237 db_new_tasks = []
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))
2243
2244 if not db_vnfrs_list:
2245 raise NsException("Cannot obtain associated VNF for ns")
2246
2247 for vnfr in db_vnfrs_list:
2248 db_vnfrs[vnfr["_id"]] = vnfr
2249
2250 now = time()
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))
2253
2254 if not db_ro_nsr:
2255 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
2256
2257 with self.write_lock:
2258 # NS
2259 step = "process NS elements"
2260 changes_list = self.prepare_changes_to_recreate(
2261 indata=indata,
2262 nsr_id=nsr_id,
2263 db_nsr=db_nsr,
2264 db_vnfrs=db_vnfrs,
2265 db_ro_nsr=db_ro_nsr,
2266 action_id=action_id,
2267 tasks_by_target_record_id=tasks_by_target_record_id,
2268 )
2269
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,
2274 )
2275
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"]:
2284 self.db.del_one(
2285 "ro_tasks",
2286 q_filter={
2287 "_id": ro_task["_id"],
2288 "modified_at": ro_task["modified_at"],
2289 },
2290 fail_on_empty=False,
2291 )
2292
2293 step = "Updating database, Appending tasks to ro_tasks"
2294 self.upload_recreate_tasks(
2295 db_new_tasks=db_new_tasks,
2296 now=now,
2297 )
2298
2299 self.logger.debug(
2300 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2301 )
2302
2303 return (
2304 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2305 action_id,
2306 True,
2307 )
2308 except Exception as e:
2309 if isinstance(e, (DbException, NsException)):
2310 self.logger.error(
2311 logging_text + "Exit Exception while '{}': {}".format(step, e)
2312 )
2313 else:
2314 e = traceback_format_exc()
2315 self.logger.critical(
2316 logging_text + "Exit Exception while '{}': {}".format(step, e),
2317 exc_info=True,
2318 )
2319
2320 raise NsException(e)
2321
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()))
2326 task_index = 0
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
2331 step = ""
2332 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2333 self.logger.debug(logging_text + "Enter")
2334
2335 try:
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))
2339 db_new_tasks = []
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})
2344
2345 if not db_vnfrs_list:
2346 raise NsException("Cannot obtain associated VNF for ns")
2347
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))
2352
2353 now = time()
2354 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
2355
2356 if not db_ro_nsr:
2357 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
2358
2359 # check that action_id is not in the list of actions. Suffixed with :index
2360 if action_id in db_ro_nsr["actions"]:
2361 index = 1
2362
2363 while True:
2364 new_action_id = "{}:{}".format(action_id, index)
2365
2366 if new_action_id not in db_ro_nsr["actions"]:
2367 action_id = new_action_id
2368 self.logger.debug(
2369 logging_text
2370 + "Changing action_id in use to {}".format(action_id)
2371 )
2372 break
2373
2374 index += 1
2375
2376 def _process_action(indata):
2377 nonlocal db_new_tasks
2378 nonlocal action_id
2379 nonlocal nsr_id
2380 nonlocal task_index
2381 nonlocal db_vnfrs
2382 nonlocal db_ro_nsr
2383
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")
2388
2389 for vnf in indata.get("vnf", ()):
2390 if vnf["_id"] not in db_vnfrs:
2391 raise NsException("Invalid vnf={}".format(vnf["_id"]))
2392
2393 db_vnfr = db_vnfrs[vnf["_id"]]
2394
2395 for target_vdu in vnf.get("vdur", ()):
2396 vdu_index, vdur = next(
2397 (
2398 i_v
2399 for i_v in enumerate(db_vnfr["vdur"])
2400 if i_v[1]["id"] == target_vdu["id"]
2401 ),
2402 (None, None),
2403 )
2404
2405 if not vdur:
2406 raise NsException(
2407 "Invalid vdu vnf={}.{}".format(
2408 vnf["_id"], target_vdu["id"]
2409 )
2410 )
2411
2412 target_vim, vim_info = next(
2413 k_v for k_v in vdur["vim_info"].items()
2414 )
2415 self._assign_vim(target_vim)
2416 target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
2417 vnf["_id"], vdu_index
2418 )
2419 extra_dict = {
2420 "depends_on": [
2421 "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
2422 ],
2423 "params": {
2424 "ip_address": vdur.get("ip-address"),
2425 "user": user,
2426 "key": key,
2427 "password": password,
2428 "private_key": db_ro_nsr["private_key"],
2429 "salt": db_ro_nsr["_id"],
2430 "schema_version": db_ro_nsr["_admin"][
2431 "schema_version"
2432 ],
2433 },
2434 }
2435
2436 deployment_info = {
2437 "action_id": action_id,
2438 "nsr_id": nsr_id,
2439 "task_index": task_index,
2440 }
2441
2442 task = Ns._create_task(
2443 deployment_info=deployment_info,
2444 target_id=target_vim,
2445 item="vdu",
2446 action="EXEC",
2447 target_record=target_record,
2448 target_record_id=None,
2449 extra_dict=extra_dict,
2450 )
2451
2452 task_index = deployment_info.get("task_index")
2453
2454 db_new_tasks.append(task)
2455
2456 with self.write_lock:
2457 if indata.get("action"):
2458 _process_action(indata)
2459 else:
2460 # compute network differences
2461 # NS
2462 step = "process NS elements"
2463 changes_list = self.calculate_all_differences_to_deploy(
2464 indata=indata,
2465 nsr_id=nsr_id,
2466 db_nsr=db_nsr,
2467 db_vnfrs=db_vnfrs,
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,
2473 )
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,
2478 )
2479
2480 step = "Updating database, Appending tasks to ro_tasks"
2481 self.upload_all_tasks(
2482 db_new_tasks=db_new_tasks,
2483 now=now,
2484 )
2485
2486 step = "Updating database, nsrs"
2487 if db_nsr_update:
2488 self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
2489
2490 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
2491 if db_vnfr_update:
2492 step = "Updating database, vnfrs={}".format(vnfr_id)
2493 self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
2494
2495 self.logger.debug(
2496 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2497 )
2498
2499 return (
2500 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2501 action_id,
2502 True,
2503 )
2504 except Exception as e:
2505 if isinstance(e, (DbException, NsException)):
2506 self.logger.error(
2507 logging_text + "Exit Exception while '{}': {}".format(step, e)
2508 )
2509 else:
2510 e = traceback_format_exc()
2511 self.logger.critical(
2512 logging_text + "Exit Exception while '{}': {}".format(step, e),
2513 exc_info=True,
2514 )
2515
2516 raise NsException(e)
2517
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})
2521
2522 with self.write_lock:
2523 try:
2524 NsWorker.delete_db_tasks(self.db, nsr_id, None)
2525 except NsWorkerException as e:
2526 raise NsException(e)
2527
2528 return None, None, True
2529
2530 def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2531 self.logger.debug(
2532 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2533 version, nsr_id, action_id, indata
2534 )
2535 )
2536 task_list = []
2537 done = 0
2538 total = 0
2539 ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
2540 global_status = "DONE"
2541 details = []
2542
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)
2547 total += 1
2548
2549 if task["status"] == "FAILED":
2550 global_status = "FAILED"
2551 error_text = "Error at {} {}: {}".format(
2552 task["action"].lower(),
2553 task["item"],
2554 ro_task["vim_info"].get("vim_message") or "unknown",
2555 )
2556 details.append(error_text)
2557 elif task["status"] in ("SCHEDULED", "BUILD"):
2558 if global_status != "FAILED":
2559 global_status = "BUILD"
2560 else:
2561 done += 1
2562
2563 return_data = {
2564 "status": global_status,
2565 "details": ". ".join(details)
2566 if details
2567 else "progress {}/{}".format(done, total),
2568 "nsr_id": nsr_id,
2569 "action_id": action_id,
2570 "tasks": task_list,
2571 }
2572
2573 return return_data, None, True
2574
2575 def recreate_status(
2576 self, session, indata, version, nsr_id, action_id, *args, **kwargs
2577 ):
2578 return self.status(session, indata, version, nsr_id, action_id, *args, **kwargs)
2579
2580 def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2581 print(
2582 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2583 session, indata, version, nsr_id, action_id
2584 )
2585 )
2586
2587 return None, None, True
2588
2589 def rebuild_start_stop_task(
2590 self,
2591 vdu_id,
2592 vnf_id,
2593 vdu_index,
2594 action_id,
2595 nsr_id,
2596 task_index,
2597 target_vim,
2598 extra_dict,
2599 ):
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)
2603 deployment_info = {
2604 "action_id": action_id,
2605 "nsr_id": nsr_id,
2606 "task_index": task_index,
2607 }
2608
2609 task = Ns._create_task(
2610 deployment_info=deployment_info,
2611 target_id=target_vim,
2612 item="update",
2613 action="EXEC",
2614 target_record=target_record,
2615 target_record_id=target_record_id,
2616 extra_dict=extra_dict,
2617 )
2618 return task
2619
2620 def rebuild_start_stop(
2621 self, session, action_dict, version, nsr_id, *args, **kwargs
2622 ):
2623 task_index = 0
2624 extra_dict = {}
2625 now = time()
2626 action_id = action_dict.get("action_id", str(uuid4()))
2627 step = ""
2628 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2629 self.logger.debug(logging_text + "Enter")
2630
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")
2634
2635 if action_dict.get("stop"):
2636 action = "shutoff"
2637 db_new_tasks = []
2638 try:
2639 step = "lock the operation & do task creation"
2640 with self.write_lock:
2641 extra_dict["params"] = {
2642 "vim_vm_id": vim_vm_id,
2643 "action": action,
2644 }
2645 task = self.rebuild_start_stop_task(
2646 task_dict["vdu_id"],
2647 task_dict["vnf_id"],
2648 task_dict["vdu_index"],
2649 action_id,
2650 nsr_id,
2651 task_index,
2652 task_dict["target_vim"],
2653 extra_dict,
2654 )
2655 db_new_tasks.append(task)
2656 step = "upload Task to db"
2657 self.upload_all_tasks(
2658 db_new_tasks=db_new_tasks,
2659 now=now,
2660 )
2661 self.logger.debug(
2662 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2663 )
2664 return (
2665 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2666 action_id,
2667 True,
2668 )
2669 except Exception as e:
2670 if isinstance(e, (DbException, NsException)):
2671 self.logger.error(
2672 logging_text + "Exit Exception while '{}': {}".format(step, e)
2673 )
2674 else:
2675 e = traceback_format_exc()
2676 self.logger.critical(
2677 logging_text + "Exit Exception while '{}': {}".format(step, e),
2678 exc_info=True,
2679 )
2680 raise NsException(e)
2681
2682 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2683 nsrs = self.db.get_list("nsrs", {})
2684 return_data = []
2685
2686 for ns in nsrs:
2687 return_data.append({"_id": ns["_id"], "name": ns["name"]})
2688
2689 return return_data, None, True
2690
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})
2693 return_data = []
2694
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"])
2699
2700 return return_data, None, True
2701
2702 def migrate_task(
2703 self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
2704 ):
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"])
2709 deployment_info = {
2710 "action_id": action_id,
2711 "nsr_id": nsr_id,
2712 "task_index": task_index,
2713 }
2714
2715 task = Ns._create_task(
2716 deployment_info=deployment_info,
2717 target_id=target_vim,
2718 item="migrate",
2719 action="EXEC",
2720 target_record=target_record,
2721 target_record_id=target_record_id,
2722 extra_dict=extra_dict,
2723 )
2724
2725 return task
2726
2727 def migrate(self, session, indata, version, nsr_id, *args, **kwargs):
2728 task_index = 0
2729 extra_dict = {}
2730 now = time()
2731 action_id = indata.get("action_id", str(uuid4()))
2732 step = ""
2733 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2734 self.logger.debug(logging_text + "Enter")
2735 try:
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")
2741 db_new_tasks = []
2742
2743 with self.write_lock:
2744 if vdu is not None:
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"]):
2748 if (
2749 vdu["vdu-id-ref"] == vdu_id
2750 and vdu["count-index"] == vdu_count_index
2751 ):
2752 extra_dict["params"] = {
2753 "vim_vm_id": vdu["vim-id"],
2754 "migrate_host": migrateToHost,
2755 "vdu_vim_info": vdu["vim_info"],
2756 }
2757 step = "Creating migration task for vdu:{}".format(vdu)
2758 task = self.migrate_task(
2759 vdu,
2760 db_vnfr,
2761 vdu_index,
2762 action_id,
2763 nsr_id,
2764 task_index,
2765 extra_dict,
2766 )
2767 db_new_tasks.append(task)
2768 task_index += 1
2769 break
2770 else:
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"],
2776 }
2777 step = "Creating migration task for vdu:{}".format(vdu)
2778 task = self.migrate_task(
2779 vdu,
2780 db_vnfr,
2781 vdu_index,
2782 action_id,
2783 nsr_id,
2784 task_index,
2785 extra_dict,
2786 )
2787 db_new_tasks.append(task)
2788 task_index += 1
2789
2790 self.upload_all_tasks(
2791 db_new_tasks=db_new_tasks,
2792 now=now,
2793 )
2794
2795 self.logger.debug(
2796 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2797 )
2798 return (
2799 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2800 action_id,
2801 True,
2802 )
2803 except Exception as e:
2804 if isinstance(e, (DbException, NsException)):
2805 self.logger.error(
2806 logging_text + "Exit Exception while '{}': {}".format(step, e)
2807 )
2808 else:
2809 e = traceback_format_exc()
2810 self.logger.critical(
2811 logging_text + "Exit Exception while '{}': {}".format(step, e),
2812 exc_info=True,
2813 )
2814 raise NsException(e)
2815
2816 def verticalscale_task(
2817 self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
2818 ):
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"])
2823 deployment_info = {
2824 "action_id": action_id,
2825 "nsr_id": nsr_id,
2826 "task_index": task_index,
2827 }
2828
2829 task = Ns._create_task(
2830 deployment_info=deployment_info,
2831 target_id=target_vim,
2832 item="verticalscale",
2833 action="EXEC",
2834 target_record=target_record,
2835 target_record_id=target_record_id,
2836 extra_dict=extra_dict,
2837 )
2838 return task
2839
2840 def verticalscale(self, session, indata, version, nsr_id, *args, **kwargs):
2841 task_index = 0
2842 extra_dict = {}
2843 now = time()
2844 action_id = indata.get("action_id", str(uuid4()))
2845 step = ""
2846 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2847 self.logger.debug(logging_text + "Enter")
2848 try:
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"]
2858 flavor_dict = {
2859 "name": vduid + "-flv",
2860 "ram": virtualMemory,
2861 "vcpus": numVirtualCpu,
2862 "disk": sizeOfStorage,
2863 }
2864 db_new_tasks = []
2865 step = "Creating Tasks for vertical scaling"
2866 with self.write_lock:
2867 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
2868 if (
2869 vdu["vdu-id-ref"] == vduid
2870 and vdu["count-index"] == vduCountIndex
2871 ):
2872 extra_dict["params"] = {
2873 "vim_vm_id": vdu["vim-id"],
2874 "flavor_dict": flavor_dict,
2875 }
2876 task = self.verticalscale_task(
2877 vdu,
2878 db_vnfr,
2879 vdu_index,
2880 action_id,
2881 nsr_id,
2882 task_index,
2883 extra_dict,
2884 )
2885 db_new_tasks.append(task)
2886 task_index += 1
2887 break
2888 self.upload_all_tasks(
2889 db_new_tasks=db_new_tasks,
2890 now=now,
2891 )
2892 self.logger.debug(
2893 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2894 )
2895 return (
2896 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2897 action_id,
2898 True,
2899 )
2900 except Exception as e:
2901 if isinstance(e, (DbException, NsException)):
2902 self.logger.error(
2903 logging_text + "Exit Exception while '{}': {}".format(step, e)
2904 )
2905 else:
2906 e = traceback_format_exc()
2907 self.logger.critical(
2908 logging_text + "Exit Exception while '{}': {}".format(step, e),
2909 exc_info=True,
2910 )
2911 raise NsException(e)