Code Coverage

Cobertura Coverage Report > NG-RO.osm_ng_ro >

ns.py

Trend

Classes100%
 
Lines33%
   
Conditionals100%
 

File Coverage summary

NameClassesLinesConditionals
ns.py
100%
1/1
33%
363/1101
100%
0/0

Coverage Breakdown by Class

NameLinesConditionals
ns.py
33%
363/1101
N/A

Source

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 1 from http import HTTPStatus
20 1 from itertools import product
21 1 import logging
22 1 from random import choice as random_choice
23 1 from threading import Lock
24 1 from time import time
25 1 from traceback import format_exc as traceback_format_exc
26 1 from typing import Any, Dict, Tuple, Type
27 1 from uuid import uuid4
28
29 1 from cryptography.hazmat.backends import default_backend as crypto_default_backend
30 1 from cryptography.hazmat.primitives import serialization as crypto_serialization
31 1 from cryptography.hazmat.primitives.asymmetric import rsa
32 1 from jinja2 import (
33     Environment,
34     select_autoescape,
35     StrictUndefined,
36     TemplateError,
37     TemplateNotFound,
38     UndefinedError,
39 )
40 1 from osm_common import (
41     dbmemory,
42     dbmongo,
43     fslocal,
44     fsmongo,
45     msgkafka,
46     msglocal,
47     version as common_version,
48 )
49 1 from osm_common.dbbase import DbBase, DbException
50 1 from osm_common.fsbase import FsBase, FsException
51 1 from osm_common.msgbase import MsgException
52 1 from osm_ng_ro.ns_thread import deep_get, NsWorker, NsWorkerException
53 1 from osm_ng_ro.validation import deploy_schema, validate_input
54 1 import yaml
55
56 1 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
57 1 min_common_version = "0.1.16"
58
59
60 1 class NsException(Exception):
61 1     def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
62 1         self.http_code = http_code
63 1         super(Exception, self).__init__(message)
64
65
66 1 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 0     try:
74 0         with open("/proc/self/cgroup", "r") as f:
75 0             text_id_ = f.readline()
76 0             _, _, text_id = text_id_.rpartition("/")
77 0             text_id = text_id.replace("\n", "")[:12]
78
79 0             if text_id:
80 0                 return text_id
81 0     except Exception as error:
82 0         logging.exception(f"{error} occured while getting process id")
83
84     # Return a random id
85 0     return "".join(random_choice("0123456789abcdef") for _ in range(12))
86
87
88 1 def versiontuple(v):
89     """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
90 0     filled = []
91
92 0     for point in v.split("."):
93 0         filled.append(point.zfill(8))
94
95 0     return tuple(filled)
96
97
98 1 class Ns(object):
99 1     def __init__(self):
100 1         self.db = None
101 1         self.fs = None
102 1         self.msg = None
103 1         self.config = None
104         # self.operations = None
105 1         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 1         self.map_topic = {}
109 1         self.write_lock = None
110 1         self.vims_assigned = {}
111 1         self.next_worker = 0
112 1         self.plugins = {}
113 1         self.workers = []
114 1         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 1         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 1     def init_db(self, target_version):
130 0         pass
131
132 1     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 0         self.config = config
140 0         self.config["process_id"] = get_process_id()  # used for HA identity
141 0         self.logger = logging.getLogger("ro.ns")
142
143         # check right version of common
144 0         if versiontuple(common_version) < versiontuple(min_common_version):
145 0             raise NsException(
146                 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
147                     common_version, min_common_version
148                 )
149             )
150
151 0         try:
152 0             if not self.db:
153 0                 if config["database"]["driver"] == "mongo":
154 0                     self.db = dbmongo.DbMongo()
155 0                     self.db.db_connect(config["database"])
156 0                 elif config["database"]["driver"] == "memory":
157 0                     self.db = dbmemory.DbMemory()
158 0                     self.db.db_connect(config["database"])
159                 else:
160 0                     raise NsException(
161                         "Invalid configuration param '{}' at '[database]':'driver'".format(
162                             config["database"]["driver"]
163                         )
164                     )
165
166 0             if not self.fs:
167 0                 if config["storage"]["driver"] == "local":
168 0                     self.fs = fslocal.FsLocal()
169 0                     self.fs.fs_connect(config["storage"])
170 0                 elif config["storage"]["driver"] == "mongo":
171 0                     self.fs = fsmongo.FsMongo()
172 0                     self.fs.fs_connect(config["storage"])
173 0                 elif config["storage"]["driver"] is None:
174 0                     pass
175                 else:
176 0                     raise NsException(
177                         "Invalid configuration param '{}' at '[storage]':'driver'".format(
178                             config["storage"]["driver"]
179                         )
180                     )
181
182 0             if not self.msg:
183 0                 if config["message"]["driver"] == "local":
184 0                     self.msg = msglocal.MsgLocal()
185 0                     self.msg.connect(config["message"])
186 0                 elif config["message"]["driver"] == "kafka":
187 0                     self.msg = msgkafka.MsgKafka()
188 0                     self.msg.connect(config["message"])
189                 else:
190 0                     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 0             self.write_lock = Lock()
199 0         except (DbException, FsException, MsgException) as e:
200 0             raise NsException(str(e), http_code=e.http_code)
201
202 1     def get_assigned_vims(self):
203 0         return list(self.vims_assigned.keys())
204
205 1     def stop(self):
206 0         try:
207 0             if self.db:
208 0                 self.db.db_disconnect()
209
210 0             if self.fs:
211 0                 self.fs.fs_disconnect()
212
213 0             if self.msg:
214 0                 self.msg.disconnect()
215
216 0             self.write_lock = None
217 0         except (DbException, FsException, MsgException) as e:
218 0             raise NsException(str(e), http_code=e.http_code)
219
220 0         for worker in self.workers:
221 0             worker.insert_task(("terminate",))
222
223 1     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 0         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 0         if worker_id is not None:
240             # unset idle status to avoid race conditions
241 0             self.workers[worker_id].idle = False
242         else:
243 0             worker_id = len(self.workers)
244
245 0             if worker_id < self.config["global"]["server.ns_threads"]:
246                 # create a new worker
247 0                 self.workers.append(
248                     NsWorker(worker_id, self.config, self.plugins, self.db)
249                 )
250 0                 self.workers[worker_id].start()
251             else:
252                 # reached maximum number of threads, assign VIM to an existing one
253 0                 worker_id = self.next_worker
254 0                 self.next_worker = (self.next_worker + 1) % self.config["global"][
255                     "server.ns_threads"
256                 ]
257
258 0         return worker_id
259
260 1     def assign_vim(self, target_id):
261 0         with self.write_lock:
262 0             return self._assign_vim(target_id)
263
264 1     def _assign_vim(self, target_id):
265 0         if target_id not in self.vims_assigned:
266 0             worker_id = self.vims_assigned[target_id] = self._create_worker()
267 0             self.workers[worker_id].insert_task(("load_vim", target_id))
268
269 1     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 0         with self.write_lock:
273 0             for worker in self.workers:
274 0                 if worker and not worker.idle:
275 0                     worker.insert_task(("reload_vim", target_id))
276
277 1     def unload_vim(self, target_id):
278 0         with self.write_lock:
279 0             return self._unload_vim(target_id)
280
281 1     def _unload_vim(self, target_id):
282 0         if target_id in self.vims_assigned:
283 0             worker_id = self.vims_assigned[target_id]
284 0             self.workers[worker_id].insert_task(("unload_vim", target_id))
285 0             del self.vims_assigned[target_id]
286
287 1     def check_vim(self, target_id):
288 0         with self.write_lock:
289 0             if target_id in self.vims_assigned:
290 0                 worker_id = self.vims_assigned[target_id]
291             else:
292 0                 worker_id = self._create_worker()
293
294 0         worker = self.workers[worker_id]
295 0         worker.insert_task(("check_vim", target_id))
296
297 1     def unload_unused_vims(self):
298 0         with self.write_lock:
299 0             vims_to_unload = []
300
301 0             for target_id in self.vims_assigned:
302 0                 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 0                     vims_to_unload.append(target_id)
311
312 0             for target_id in vims_to_unload:
313 0                 self._unload_vim(target_id)
314
315 1     @staticmethod
316 1     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 1         vnfd_id, _, other = location.partition(":")
338 1         _type, _, name = other.partition(":")
339 1         vnfd = db.get_one("vnfds", {"_id": vnfd_id})
340
341 1         if _type == "file":
342 1             base_folder = vnfd["_admin"]["storage"]
343 1             cloud_init_file = "{}/{}/cloud_init/{}".format(
344                 base_folder["folder"], base_folder["pkg-dir"], name
345             )
346
347 1             if not fs:
348 1                 raise NsException(
349                     "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
350                         cloud_init_file
351                     )
352                 )
353
354 1             with fs.file_open(cloud_init_file, "r") as ci_file:
355 1                 cloud_init_content = ci_file.read()
356 1         elif _type == "vdu":
357 1             cloud_init_content = vnfd["vdu"][int(name)]["cloud-init"]
358         else:
359 1             raise NsException("Mismatch descriptor for cloud init: {}".format(location))
360
361 1         return cloud_init_content
362
363 1     @staticmethod
364 1     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 1         try:
384 1             env = Environment(
385                 undefined=StrictUndefined,
386                 autoescape=select_autoescape(default_for_string=True, default=True),
387             )
388 1             template = env.from_string(cloud_init_content)
389
390 1             return template.render(params or {})
391 1         except UndefinedError as e:
392 1             raise NsException(
393                 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
394                 "inside the 'additionalParamsForVnf' block".format(e, context)
395             )
396 1         except (TemplateError, TemplateNotFound) as e:
397 1             raise NsException(
398                 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
399                     context, e
400                 )
401             )
402
403 1     def _create_db_ro_nsrs(self, nsr_id, now):
404 0         try:
405 0             key = rsa.generate_private_key(
406                 backend=crypto_default_backend(), public_exponent=65537, key_size=2048
407             )
408 0             private_key = key.private_bytes(
409                 crypto_serialization.Encoding.PEM,
410                 crypto_serialization.PrivateFormat.PKCS8,
411                 crypto_serialization.NoEncryption(),
412             )
413 0             public_key = key.public_key().public_bytes(
414                 crypto_serialization.Encoding.OpenSSH,
415                 crypto_serialization.PublicFormat.OpenSSH,
416             )
417 0             private_key = private_key.decode("utf8")
418             # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
419 0             i = private_key.find("\n")
420 0             private_key = "-----BEGIN RSA PRIVATE KEY-----" + private_key[i:]
421 0             public_key = public_key.decode("utf8")
422 0         except Exception as e:
423 0             raise NsException("Cannot create ssh-keys: {}".format(e))
424
425 0         schema_version = "1.1"
426 0         private_key_encrypted = self.db.encrypt(
427             private_key, schema_version=schema_version, salt=nsr_id
428         )
429 0         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 0         self.db.create("ro_nsrs", db_content)
441
442 0         return db_content
443
444 1     @staticmethod
445 1     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 1         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 1         if extra_dict:
481 1             task.update(extra_dict)  # params, find_params, depends_on
482
483 1         deployment_info["task_index"] = deployment_info.get("task_index", 0) + 1
484
485 1         return task
486
487 1     @staticmethod
488 1     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 1         now = time()
502
503 1         _id = task.get("task_id")
504 1         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 1         return db_ro_task
526
527 1     @staticmethod
528 1     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 1         find_params = {}
547
548 1         if target_image.get("image"):
549 1             find_params["filter_dict"] = {"name": target_image.get("image")}
550
551 1         if target_image.get("vim_image_id"):
552 1             find_params["filter_dict"] = {"id": target_image.get("vim_image_id")}
553
554 1         if target_image.get("image_checksum"):
555 1             find_params["filter_dict"] = {
556                 "checksum": target_image.get("image_checksum")
557             }
558
559 1         return {"find_params": find_params}
560
561 1     @staticmethod
562 1     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 1         quota = {}
575
576 1         if quota_descriptor.get("limit"):
577 1             quota["limit"] = int(quota_descriptor["limit"])
578
579 1         if quota_descriptor.get("reserve"):
580 1             quota["reserve"] = int(quota_descriptor["reserve"])
581
582 1         if quota_descriptor.get("shares"):
583 1             quota["shares"] = int(quota_descriptor["shares"])
584
585 1         return quota
586
587 1     @staticmethod
588 1     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 1         result = {}
602
603 1         if guest_epa_quota.get("cpu-quota") and not epa_vcpu_set:
604 1             cpuquota = Ns._get_resource_allocation_params(
605                 guest_epa_quota.get("cpu-quota")
606             )
607
608 1             if cpuquota:
609 1                 result["cpu-quota"] = cpuquota
610
611 1         if guest_epa_quota.get("mem-quota"):
612 1             vduquota = Ns._get_resource_allocation_params(
613                 guest_epa_quota.get("mem-quota")
614             )
615
616 1             if vduquota:
617 1                 result["mem-quota"] = vduquota
618
619 1         if guest_epa_quota.get("disk-io-quota"):
620 1             diskioquota = Ns._get_resource_allocation_params(
621                 guest_epa_quota.get("disk-io-quota")
622             )
623
624 1             if diskioquota:
625 1                 result["disk-io-quota"] = diskioquota
626
627 1         if guest_epa_quota.get("vif-quota"):
628 1             vifquota = Ns._get_resource_allocation_params(
629                 guest_epa_quota.get("vif-quota")
630             )
631
632 1             if vifquota:
633 1                 result["vif-quota"] = vifquota
634
635 1         return result
636
637 1     @staticmethod
638 1     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 1         numa = {}
650 1         epa_vcpu_set = False
651
652 1         if guest_epa_quota.get("numa-node-policy"):
653 1             numa_node_policy = guest_epa_quota.get("numa-node-policy")
654
655 1             if numa_node_policy.get("node"):
656 1                 numa_node = numa_node_policy["node"][0]
657
658 1                 if numa_node.get("num-cores"):
659 1                     numa["cores"] = numa_node["num-cores"]
660 1                     epa_vcpu_set = True
661
662 1                 paired_threads = numa_node.get("paired-threads", {})
663 1                 if paired_threads.get("num-paired-threads"):
664 1                     numa["paired-threads"] = int(
665                         numa_node["paired-threads"]["num-paired-threads"]
666                     )
667 1                     epa_vcpu_set = True
668
669 1                 if paired_threads.get("paired-thread-ids"):
670 1                     numa["paired-threads-id"] = []
671
672 1                     for pair in paired_threads["paired-thread-ids"]:
673 1                         numa["paired-threads-id"].append(
674                             (
675                                 str(pair["thread-a"]),
676                                 str(pair["thread-b"]),
677                             )
678                         )
679
680 1                 if numa_node.get("num-threads"):
681 1                     numa["threads"] = int(numa_node["num-threads"])
682 1                     epa_vcpu_set = True
683
684 1                 if numa_node.get("memory-mb"):
685 1                     numa["memory"] = max(int(int(numa_node["memory-mb"]) / 1024), 1)
686
687 1         return numa, epa_vcpu_set
688
689 1     @staticmethod
690 1     def _process_guest_epa_cpu_pinning_params(
691         guest_epa_quota: Dict[str, Any],
692         vcpu_count: int,
693         epa_vcpu_set: bool,
694     ) -> Tuple[Dict[str, Any], bool]:
695         """[summary]
696
697         Args:
698             guest_epa_quota (Dict[str, Any]): [description]
699             vcpu_count (int): [description]
700             epa_vcpu_set (bool): [description]
701
702         Returns:
703             Tuple[Dict[str, Any], bool]: [description]
704         """
705 1         numa = {}
706 1         local_epa_vcpu_set = epa_vcpu_set
707
708 1         if (
709             guest_epa_quota.get("cpu-pinning-policy") == "DEDICATED"
710             and not epa_vcpu_set
711         ):
712 1             numa[
713                 "cores"
714                 if guest_epa_quota.get("cpu-thread-pinning-policy") != "PREFER"
715                 else "threads"
716             ] = max(vcpu_count, 1)
717 1             local_epa_vcpu_set = True
718
719 1         return numa, local_epa_vcpu_set
720
721 1     @staticmethod
722 1     def _process_epa_params(
723         target_flavor: Dict[str, Any],
724     ) -> Dict[str, Any]:
725         """[summary]
726
727         Args:
728             target_flavor (Dict[str, Any]): [description]
729
730         Returns:
731             Dict[str, Any]: [description]
732         """
733 1         extended = {}
734 1         numa = {}
735
736 1         if target_flavor.get("guest-epa"):
737 1             guest_epa = target_flavor["guest-epa"]
738
739 1             numa, epa_vcpu_set = Ns._process_guest_epa_numa_params(
740                 guest_epa_quota=guest_epa
741             )
742
743 1             if guest_epa.get("mempage-size"):
744 1                 extended["mempage-size"] = guest_epa.get("mempage-size")
745
746 1             tmp_numa, epa_vcpu_set = Ns._process_guest_epa_cpu_pinning_params(
747                 guest_epa_quota=guest_epa,
748                 vcpu_count=int(target_flavor.get("vcpu-count", 1)),
749                 epa_vcpu_set=epa_vcpu_set,
750             )
751 1             numa.update(tmp_numa)
752
753 1             extended.update(
754                 Ns._process_guest_epa_quota_params(
755                     guest_epa_quota=guest_epa,
756                     epa_vcpu_set=epa_vcpu_set,
757                 )
758             )
759
760 1         if numa:
761 1             extended["numas"] = [numa]
762
763 1         return extended
764
765 1     @staticmethod
766 1     def _process_flavor_params(
767         target_flavor: Dict[str, Any],
768         indata: Dict[str, Any],
769         vim_info: Dict[str, Any],
770         target_record_id: str,
771         **kwargs: Dict[str, Any],
772     ) -> Dict[str, Any]:
773         """[summary]
774
775         Args:
776             target_flavor (Dict[str, Any]): [description]
777             indata (Dict[str, Any]): [description]
778             vim_info (Dict[str, Any]): [description]
779             target_record_id (str): [description]
780
781         Returns:
782             Dict[str, Any]: [description]
783         """
784 1         db = kwargs.get("db")
785 1         target_vdur = {}
786
787 1         flavor_data = {
788             "disk": int(target_flavor["storage-gb"]),
789             "ram": int(target_flavor["memory-mb"]),
790             "vcpus": int(target_flavor["vcpu-count"]),
791         }
792
793 1         for vnf in indata.get("vnf", []):
794 1             for vdur in vnf.get("vdur", []):
795 1                 if vdur.get("ns-flavor-id") == target_flavor.get("id"):
796 1                     target_vdur = vdur
797
798 1         if db and isinstance(indata.get("vnf"), list):
799 1             vnfd_id = indata.get("vnf")[0].get("vnfd-id")
800 1             vnfd = db.get_one("vnfds", {"_id": vnfd_id})
801             # check if there is persistent root disk
802 1             for vdu in vnfd.get("vdu", ()):
803 1                 if vdu["name"] == target_vdur.get("vdu-name"):
804 1                     for vsd in vnfd.get("virtual-storage-desc", ()):
805 1                         if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
806 1                             root_disk = vsd
807 1                             if (
808                                 root_disk.get("type-of-storage")
809                                 == "persistent-storage:persistent-storage"
810                             ):
811 1                                 flavor_data["disk"] = 0
812
813 1         for storage in target_vdur.get("virtual-storages", []):
814 1             if (
815                 storage.get("type-of-storage")
816                 == "etsi-nfv-descriptors:ephemeral-storage"
817             ):
818 1                 flavor_data["ephemeral"] = int(storage.get("size-of-storage", 0))
819 1             elif storage.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
820 1                 flavor_data["swap"] = int(storage.get("size-of-storage", 0))
821
822 1         extended = Ns._process_epa_params(target_flavor)
823 1         if extended:
824 1             flavor_data["extended"] = extended
825
826 1         extra_dict = {"find_params": {"flavor_data": flavor_data}}
827 1         flavor_data_name = flavor_data.copy()
828 1         flavor_data_name["name"] = target_flavor["name"]
829 1         extra_dict["params"] = {"flavor_data": flavor_data_name}
830
831 1         return extra_dict
832
833 1     @staticmethod
834 1     def _ip_profile_to_ro(
835         ip_profile: Dict[str, Any],
836     ) -> Dict[str, Any]:
837         """[summary]
838
839         Args:
840             ip_profile (Dict[str, Any]): [description]
841
842         Returns:
843             Dict[str, Any]: [description]
844         """
845 1         if not ip_profile:
846 1             return None
847
848 1         ro_ip_profile = {
849             "ip_version": "IPv4"
850             if "v4" in ip_profile.get("ip-version", "ipv4")
851             else "IPv6",
852             "subnet_address": ip_profile.get("subnet-address"),
853             "gateway_address": ip_profile.get("gateway-address"),
854             "dhcp_enabled": ip_profile.get("dhcp-params", {}).get("enabled", False),
855             "dhcp_start_address": ip_profile.get("dhcp-params", {}).get(
856                 "start-address", None
857             ),
858             "dhcp_count": ip_profile.get("dhcp-params", {}).get("count", None),
859         }
860
861 1         if ip_profile.get("dns-server"):
862 1             ro_ip_profile["dns_address"] = ";".join(
863                 [v["address"] for v in ip_profile["dns-server"] if v.get("address")]
864             )
865
866 1         if ip_profile.get("security-group"):
867 1             ro_ip_profile["security_group"] = ip_profile["security-group"]
868
869 1         return ro_ip_profile
870
871 1     @staticmethod
872 1     def _process_net_params(
873         target_vld: Dict[str, Any],
874         indata: Dict[str, Any],
875         vim_info: Dict[str, Any],
876         target_record_id: str,
877         **kwargs: Dict[str, Any],
878     ) -> Dict[str, Any]:
879         """Function to process network parameters.
880
881         Args:
882             target_vld (Dict[str, Any]): [description]
883             indata (Dict[str, Any]): [description]
884             vim_info (Dict[str, Any]): [description]
885             target_record_id (str): [description]
886
887         Returns:
888             Dict[str, Any]: [description]
889         """
890 1         extra_dict = {}
891
892 1         if vim_info.get("sdn"):
893             # vnf_preffix = "vnfrs:{}".format(vnfr_id)
894             # ns_preffix = "nsrs:{}".format(nsr_id)
895             # remove the ending ".sdn
896 1             vld_target_record_id, _, _ = target_record_id.rpartition(".")
897 1             extra_dict["params"] = {
898                 k: vim_info[k]
899                 for k in ("sdn-ports", "target_vim", "vlds", "type")
900                 if vim_info.get(k)
901             }
902
903             # TODO needed to add target_id in the dependency.
904 1             if vim_info.get("target_vim"):
905 1                 extra_dict["depends_on"] = [
906                     f"{vim_info.get('target_vim')} {vld_target_record_id}"
907                 ]
908
909 1             return extra_dict
910
911 1         if vim_info.get("vim_network_name"):
912 1             extra_dict["find_params"] = {
913                 "filter_dict": {
914                     "name": vim_info.get("vim_network_name"),
915                 },
916             }
917 1         elif vim_info.get("vim_network_id"):
918 1             extra_dict["find_params"] = {
919                 "filter_dict": {
920                     "id": vim_info.get("vim_network_id"),
921                 },
922             }
923 1         elif target_vld.get("mgmt-network"):
924 1             extra_dict["find_params"] = {
925                 "mgmt": True,
926                 "name": target_vld["id"],
927             }
928         else:
929             # create
930 1             extra_dict["params"] = {
931                 "net_name": (
932                     f"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
933                 ),
934                 "ip_profile": Ns._ip_profile_to_ro(vim_info.get("ip_profile")),
935                 "provider_network_profile": vim_info.get("provider_network"),
936             }
937
938 1             if not target_vld.get("underlay"):
939 1                 extra_dict["params"]["net_type"] = "bridge"
940             else:
941 1                 extra_dict["params"]["net_type"] = (
942                     "ptp" if target_vld.get("type") == "ELINE" else "data"
943                 )
944
945 1         return extra_dict
946
947 1     @staticmethod
948 1     def find_persistent_root_volumes(
949         vnfd: dict,
950         target_vdu: str,
951         vdu_instantiation_volumes_list: list,
952         disk_list: list,
953     ) -> (list, dict):
954         """Find the persistent root volumes and add them to the disk_list
955         by parsing the instantiation parameters
956
957         Args:
958             vnfd:   VNFD
959             target_vdu: processed VDU
960             vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
961             disk_list:  to be filled up
962
963         Returns:
964             disk_list:  filled VDU list which is used for VDU creation
965
966         """
967 0         persistent_root_disk = {}
968
969 0         for vdu, vsd in product(
970             vnfd.get("vdu", ()), vnfd.get("virtual-storage-desc", ())
971         ):
972 0             if (
973                 vdu["name"] == target_vdu["vdu-name"]
974                 and vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]
975             ):
976 0                 root_disk = vsd
977 0                 if (
978                     root_disk.get("type-of-storage")
979                     == "persistent-storage:persistent-storage"
980                 ):
981 0                     for vdu_volume in vdu_instantiation_volumes_list:
982
983 0                         if (
984                             vdu_volume["vim-volume-id"]
985                             and root_disk["id"] == vdu_volume["name"]
986                         ):
987
988 0                             persistent_root_disk[vsd["id"]] = {
989                                 "vim_volume_id": vdu_volume["vim-volume-id"],
990                                 "image_id": vdu.get("sw-image-desc"),
991                             }
992
993 0                             disk_list.append(persistent_root_disk[vsd["id"]])
994
995                             # There can be only one root disk, when we find it, it will return the result
996 0                             return disk_list, persistent_root_disk
997
998                     else:
999
1000 0                         if root_disk.get("size-of-storage"):
1001 0                             persistent_root_disk[vsd["id"]] = {
1002                                 "image_id": vdu.get("sw-image-desc"),
1003                                 "size": root_disk.get("size-of-storage"),
1004                             }
1005
1006 0                             disk_list.append(persistent_root_disk[vsd["id"]])
1007 0                             return disk_list, persistent_root_disk
1008
1009 0         return disk_list, persistent_root_disk
1010
1011 1     @staticmethod
1012 1     def find_persistent_volumes(
1013         persistent_root_disk: dict,
1014         target_vdu: str,
1015         vdu_instantiation_volumes_list: list,
1016         disk_list: list,
1017     ) -> list:
1018         """Find the ordinary persistent volumes and add them to the disk_list
1019         by parsing the instantiation parameters
1020
1021         Args:
1022             persistent_root_disk:   persistent root disk dictionary
1023             target_vdu: processed VDU
1024             vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1025             disk_list:  to be filled up
1026
1027         Returns:
1028             disk_list:  filled VDU list which is used for VDU creation
1029
1030         """
1031         # Find the ordinary volumes which are not added to the persistent_root_disk
1032 0         persistent_disk = {}
1033 0         for disk in target_vdu.get("virtual-storages", {}):
1034 0             if (
1035                 disk.get("type-of-storage") == "persistent-storage:persistent-storage"
1036                 and disk["id"] not in persistent_root_disk.keys()
1037             ):
1038 0                 for vdu_volume in vdu_instantiation_volumes_list:
1039
1040 0                     if vdu_volume["vim-volume-id"] and disk["id"] == vdu_volume["name"]:
1041
1042 0                         persistent_disk[disk["id"]] = {
1043                             "vim_volume_id": vdu_volume["vim-volume-id"],
1044                         }
1045 0                         disk_list.append(persistent_disk[disk["id"]])
1046
1047                 else:
1048 0                     if disk["id"] not in persistent_disk.keys():
1049 0                         persistent_disk[disk["id"]] = {
1050                             "size": disk.get("size-of-storage"),
1051                         }
1052 0                         disk_list.append(persistent_disk[disk["id"]])
1053
1054 0         return disk_list
1055
1056 1     @staticmethod
1057 1     def _process_vdu_params(
1058         target_vdu: Dict[str, Any],
1059         indata: Dict[str, Any],
1060         vim_info: Dict[str, Any],
1061         target_record_id: str,
1062         **kwargs: Dict[str, Any],
1063     ) -> Dict[str, Any]:
1064         """Function to process VDU parameters.
1065
1066         Args:
1067             target_vdu (Dict[str, Any]): [description]
1068             indata (Dict[str, Any]): [description]
1069             vim_info (Dict[str, Any]): [description]
1070             target_record_id (str): [description]
1071
1072         Returns:
1073             Dict[str, Any]: [description]
1074         """
1075 1         vnfr_id = kwargs.get("vnfr_id")
1076 1         nsr_id = kwargs.get("nsr_id")
1077 1         vnfr = kwargs.get("vnfr")
1078 1         vdu2cloud_init = kwargs.get("vdu2cloud_init")
1079 1         tasks_by_target_record_id = kwargs.get("tasks_by_target_record_id")
1080 1         logger = kwargs.get("logger")
1081 1         db = kwargs.get("db")
1082 1         fs = kwargs.get("fs")
1083 1         ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1084
1085 1         vnf_preffix = "vnfrs:{}".format(vnfr_id)
1086 1         ns_preffix = "nsrs:{}".format(nsr_id)
1087 1         image_text = ns_preffix + ":image." + target_vdu["ns-image-id"]
1088 1         flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"]
1089 1         extra_dict = {"depends_on": [image_text, flavor_text]}
1090 1         net_list = []
1091
1092         # If the position info is provided for all the interfaces, it will be sorted
1093         # according to position number ascendingly.
1094 1         if all(
1095             i.get("position") + 1
1096             for i in target_vdu["interfaces"]
1097             if i.get("position") is not None
1098         ):
1099 1             sorted_interfaces = sorted(
1100                 target_vdu["interfaces"],
1101                 key=lambda x: (x.get("position") is None, x.get("position")),
1102             )
1103 1             target_vdu["interfaces"] = sorted_interfaces
1104
1105         # If the position info is provided for some interfaces but not all of them, the interfaces
1106         # which has specific position numbers will be placed and others' positions will not be taken care.
1107         else:
1108 0             if any(
1109                 i.get("position") + 1
1110                 for i in target_vdu["interfaces"]
1111                 if i.get("position") is not None
1112             ):
1113 0                 n = len(target_vdu["interfaces"])
1114 0                 sorted_interfaces = [-1] * n
1115 0                 k, m = 0, 0
1116 0                 while k < n:
1117 0                     if target_vdu["interfaces"][k].get("position"):
1118 0                         idx = target_vdu["interfaces"][k]["position"]
1119 0                         sorted_interfaces[idx - 1] = target_vdu["interfaces"][k]
1120 0                     k += 1
1121 0                 while m < n:
1122 0                     if not target_vdu["interfaces"][m].get("position"):
1123 0                         idy = sorted_interfaces.index(-1)
1124 0                         sorted_interfaces[idy] = target_vdu["interfaces"][m]
1125 0                     m += 1
1126
1127 0                 target_vdu["interfaces"] = sorted_interfaces
1128
1129         # If the position info is not provided for the interfaces, interfaces will be attached
1130         # according to the order in the VNFD.
1131 1         for iface_index, interface in enumerate(target_vdu["interfaces"]):
1132 1             if interface.get("ns-vld-id"):
1133 1                 net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
1134 0             elif interface.get("vnf-vld-id"):
1135 0                 net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
1136             else:
1137 0                 logger.error(
1138                     "Interface {} from vdu {} not connected to any vld".format(
1139                         iface_index, target_vdu["vdu-name"]
1140                     )
1141                 )
1142
1143 0                 continue  # interface not connected to any vld
1144
1145 1             extra_dict["depends_on"].append(net_text)
1146
1147 1             if "port-security-enabled" in interface:
1148 0                 interface["port_security"] = interface.pop("port-security-enabled")
1149
1150 1             if "port-security-disable-strategy" in interface:
1151 0                 interface["port_security_disable_strategy"] = interface.pop(
1152                     "port-security-disable-strategy"
1153                 )
1154
1155 1             net_item = {
1156                 x: v
1157                 for x, v in interface.items()
1158                 if x
1159                 in (
1160                     "name",
1161                     "vpci",
1162                     "port_security",
1163                     "port_security_disable_strategy",
1164                     "floating_ip",
1165                 )
1166             }
1167 1             net_item["net_id"] = "TASK-" + net_text
1168 1             net_item["type"] = "virtual"
1169
1170             # TODO mac_address: used for  SR-IOV ifaces #TODO for other types
1171             # TODO floating_ip: True/False (or it can be None)
1172 1             if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1173                 # mark the net create task as type data
1174 0                 if deep_get(
1175                     tasks_by_target_record_id,
1176                     net_text,
1177                     "extra_dict",
1178                     "params",
1179                     "net_type",
1180                 ):
1181 0                     tasks_by_target_record_id[net_text]["extra_dict"]["params"][
1182                         "net_type"
1183                     ] = "data"
1184
1185 0                 net_item["use"] = "data"
1186 0                 net_item["model"] = interface["type"]
1187 0                 net_item["type"] = interface["type"]
1188 1             elif (
1189                 interface.get("type") == "OM-MGMT"
1190                 or interface.get("mgmt-interface")
1191                 or interface.get("mgmt-vnf")
1192             ):
1193 0                 net_item["use"] = "mgmt"
1194             else:
1195                 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1196 1                 net_item["use"] = "bridge"
1197 1                 net_item["model"] = interface.get("type")
1198
1199 1             if interface.get("ip-address"):
1200 0                 net_item["ip_address"] = interface["ip-address"]
1201
1202 1             if interface.get("mac-address"):
1203 0                 net_item["mac_address"] = interface["mac-address"]
1204
1205 1             net_list.append(net_item)
1206
1207 1             if interface.get("mgmt-vnf"):
1208 0                 extra_dict["mgmt_vnf_interface"] = iface_index
1209 1             elif interface.get("mgmt-interface"):
1210 0                 extra_dict["mgmt_vdu_interface"] = iface_index
1211
1212         # cloud config
1213 1         cloud_config = {}
1214
1215 1         if target_vdu.get("cloud-init"):
1216 0             if target_vdu["cloud-init"] not in vdu2cloud_init:
1217 0                 vdu2cloud_init[target_vdu["cloud-init"]] = Ns._get_cloud_init(
1218                     db=db,
1219                     fs=fs,
1220                     location=target_vdu["cloud-init"],
1221                 )
1222
1223 0             cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
1224 0             cloud_config["user-data"] = Ns._parse_jinja2(
1225                 cloud_init_content=cloud_content_,
1226                 params=target_vdu.get("additionalParams"),
1227                 context=target_vdu["cloud-init"],
1228             )
1229
1230 1         if target_vdu.get("boot-data-drive"):
1231 0             cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
1232
1233 1         ssh_keys = []
1234
1235 1         if target_vdu.get("ssh-keys"):
1236 0             ssh_keys += target_vdu.get("ssh-keys")
1237
1238 1         if target_vdu.get("ssh-access-required"):
1239 0             ssh_keys.append(ro_nsr_public_key)
1240
1241 1         if ssh_keys:
1242 0             cloud_config["key-pairs"] = ssh_keys
1243
1244 1         persistent_root_disk = {}
1245 1         vdu_instantiation_volumes_list = []
1246 1         disk_list = []
1247 1         vnfd_id = vnfr["vnfd-id"]
1248 1         vnfd = db.get_one("vnfds", {"_id": vnfd_id})
1249
1250 1         if target_vdu.get("additionalParams"):
1251 0             vdu_instantiation_volumes_list = (
1252                 target_vdu.get("additionalParams").get("OSM").get("vdu_volumes")
1253             )
1254
1255 1         if vdu_instantiation_volumes_list:
1256
1257             # Find the root volumes and add to the disk_list
1258 0             (disk_list, persistent_root_disk,) = Ns.find_persistent_root_volumes(
1259                 vnfd, target_vdu, vdu_instantiation_volumes_list, disk_list
1260             )
1261
1262             # Find the ordinary volumes which are not added to the persistent_root_disk
1263             # and put them to the disk list
1264 0             disk_list = Ns.find_persistent_volumes(
1265                 persistent_root_disk,
1266                 target_vdu,
1267                 vdu_instantiation_volumes_list,
1268                 disk_list,
1269             )
1270
1271         else:
1272
1273             # vdu_instantiation_volumes_list is empty
1274 1             for vdu in vnfd.get("vdu", ()):
1275 1                 if vdu["name"] == target_vdu["vdu-name"]:
1276 1                     for vsd in vnfd.get("virtual-storage-desc", ()):
1277 1                         if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
1278 1                             root_disk = vsd
1279 1                             if root_disk.get(
1280                                 "type-of-storage"
1281                             ) == "persistent-storage:persistent-storage" and root_disk.get(
1282                                 "size-of-storage"
1283                             ):
1284 1                                 persistent_root_disk[vsd["id"]] = {
1285                                     "image_id": vdu.get("sw-image-desc"),
1286                                     "size": root_disk["size-of-storage"],
1287                                 }
1288 1                                 disk_list.append(persistent_root_disk[vsd["id"]])
1289
1290 1             if target_vdu.get("virtual-storages"):
1291 1                 for disk in target_vdu["virtual-storages"]:
1292 1                     if (
1293                         disk.get("type-of-storage")
1294                         == "persistent-storage:persistent-storage"
1295                         and disk["id"] not in persistent_root_disk.keys()
1296                     ):
1297 1                         disk_list.append({"size": disk["size-of-storage"]})
1298
1299 1         affinity_group_list = []
1300
1301 1         if target_vdu.get("affinity-or-anti-affinity-group-id"):
1302 0             affinity_group = {}
1303 0             for affinity_group_id in target_vdu["affinity-or-anti-affinity-group-id"]:
1304 0                 affinity_group_text = (
1305                     ns_preffix + ":affinity-or-anti-affinity-group." + affinity_group_id
1306                 )
1307
1308 0                 extra_dict["depends_on"].append(affinity_group_text)
1309 0                 affinity_group["affinity_group_id"] = "TASK-" + affinity_group_text
1310 0                 affinity_group_list.append(affinity_group)
1311
1312 1         extra_dict["params"] = {
1313             "name": "{}-{}-{}-{}".format(
1314                 indata["name"][:16],
1315                 vnfr["member-vnf-index-ref"][:16],
1316                 target_vdu["vdu-name"][:32],
1317                 target_vdu.get("count-index") or 0,
1318             ),
1319             "description": target_vdu["vdu-name"],
1320             "start": True,
1321             "image_id": "TASK-" + image_text,
1322             "flavor_id": "TASK-" + flavor_text,
1323             "affinity_group_list": affinity_group_list,
1324             "net_list": net_list,
1325             "cloud_config": cloud_config or None,
1326             "disk_list": disk_list,
1327             "availability_zone_index": None,  # TODO
1328             "availability_zone_list": None,  # TODO
1329         }
1330
1331 1         return extra_dict
1332
1333 1     @staticmethod
1334 1     def _process_affinity_group_params(
1335         target_affinity_group: Dict[str, Any],
1336         indata: Dict[str, Any],
1337         vim_info: Dict[str, Any],
1338         target_record_id: str,
1339         **kwargs: Dict[str, Any],
1340     ) -> Dict[str, Any]:
1341         """Get affinity or anti-affinity group parameters.
1342
1343         Args:
1344             target_affinity_group (Dict[str, Any]): [description]
1345             indata (Dict[str, Any]): [description]
1346             vim_info (Dict[str, Any]): [description]
1347             target_record_id (str): [description]
1348
1349         Returns:
1350             Dict[str, Any]: [description]
1351         """
1352
1353 0         extra_dict = {}
1354 0         affinity_group_data = {
1355             "name": target_affinity_group["name"],
1356             "type": target_affinity_group["type"],
1357             "scope": target_affinity_group["scope"],
1358         }
1359
1360 0         if target_affinity_group.get("vim-affinity-group-id"):
1361 0             affinity_group_data["vim-affinity-group-id"] = target_affinity_group[
1362                 "vim-affinity-group-id"
1363             ]
1364
1365 0         extra_dict["params"] = {
1366             "affinity_group_data": affinity_group_data,
1367         }
1368
1369 0         return extra_dict
1370
1371 1     @staticmethod
1372 1     def _process_recreate_vdu_params(
1373         existing_vdu: Dict[str, Any],
1374         db_nsr: Dict[str, Any],
1375         vim_info: Dict[str, Any],
1376         target_record_id: str,
1377         target_id: str,
1378         **kwargs: Dict[str, Any],
1379     ) -> Dict[str, Any]:
1380         """Function to process VDU parameters to recreate.
1381
1382         Args:
1383             existing_vdu (Dict[str, Any]): [description]
1384             db_nsr (Dict[str, Any]): [description]
1385             vim_info (Dict[str, Any]): [description]
1386             target_record_id (str): [description]
1387             target_id (str): [description]
1388
1389         Returns:
1390             Dict[str, Any]: [description]
1391         """
1392 0         vnfr = kwargs.get("vnfr")
1393 0         vdu2cloud_init = kwargs.get("vdu2cloud_init")
1394         # logger = kwargs.get("logger")
1395 0         db = kwargs.get("db")
1396 0         fs = kwargs.get("fs")
1397 0         ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1398
1399 0         extra_dict = {}
1400 0         net_list = []
1401
1402 0         vim_details = {}
1403 0         vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
1404 0         if vim_details_text:
1405 0             vim_details = yaml.safe_load(f"{vim_details_text}")
1406
1407 0         for iface_index, interface in enumerate(existing_vdu["interfaces"]):
1408
1409 0             if "port-security-enabled" in interface:
1410 0                 interface["port_security"] = interface.pop("port-security-enabled")
1411
1412 0             if "port-security-disable-strategy" in interface:
1413 0                 interface["port_security_disable_strategy"] = interface.pop(
1414                     "port-security-disable-strategy"
1415                 )
1416
1417 0             net_item = {
1418                 x: v
1419                 for x, v in interface.items()
1420                 if x
1421                 in (
1422                     "name",
1423                     "vpci",
1424                     "port_security",
1425                     "port_security_disable_strategy",
1426                     "floating_ip",
1427                 )
1428             }
1429 0             existing_ifaces = existing_vdu["vim_info"][target_id].get(
1430                 "interfaces_backup", []
1431             )
1432 0             net_id = next(
1433                 (
1434                     i["vim_net_id"]
1435                     for i in existing_ifaces
1436                     if i["ip_address"] == interface["ip-address"]
1437                 ),
1438                 None,
1439             )
1440
1441 0             net_item["net_id"] = net_id
1442 0             net_item["type"] = "virtual"
1443
1444             # TODO mac_address: used for  SR-IOV ifaces #TODO for other types
1445             # TODO floating_ip: True/False (or it can be None)
1446 0             if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1447 0                 net_item["use"] = "data"
1448 0                 net_item["model"] = interface["type"]
1449 0                 net_item["type"] = interface["type"]
1450 0             elif (
1451                 interface.get("type") == "OM-MGMT"
1452                 or interface.get("mgmt-interface")
1453                 or interface.get("mgmt-vnf")
1454             ):
1455 0                 net_item["use"] = "mgmt"
1456             else:
1457                 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1458 0                 net_item["use"] = "bridge"
1459 0                 net_item["model"] = interface.get("type")
1460
1461 0             if interface.get("ip-address"):
1462 0                 net_item["ip_address"] = interface["ip-address"]
1463
1464 0             if interface.get("mac-address"):
1465 0                 net_item["mac_address"] = interface["mac-address"]
1466
1467 0             net_list.append(net_item)
1468
1469 0             if interface.get("mgmt-vnf"):
1470 0                 extra_dict["mgmt_vnf_interface"] = iface_index
1471 0             elif interface.get("mgmt-interface"):
1472 0                 extra_dict["mgmt_vdu_interface"] = iface_index
1473
1474         # cloud config
1475 0         cloud_config = {}
1476
1477 0         if existing_vdu.get("cloud-init"):
1478 0             if existing_vdu["cloud-init"] not in vdu2cloud_init:
1479 0                 vdu2cloud_init[existing_vdu["cloud-init"]] = Ns._get_cloud_init(
1480                     db=db,
1481                     fs=fs,
1482                     location=existing_vdu["cloud-init"],
1483                 )
1484
1485 0             cloud_content_ = vdu2cloud_init[existing_vdu["cloud-init"]]
1486 0             cloud_config["user-data"] = Ns._parse_jinja2(
1487                 cloud_init_content=cloud_content_,
1488                 params=existing_vdu.get("additionalParams"),
1489                 context=existing_vdu["cloud-init"],
1490             )
1491
1492 0         if existing_vdu.get("boot-data-drive"):
1493 0             cloud_config["boot-data-drive"] = existing_vdu.get("boot-data-drive")
1494
1495 0         ssh_keys = []
1496
1497 0         if existing_vdu.get("ssh-keys"):
1498 0             ssh_keys += existing_vdu.get("ssh-keys")
1499
1500 0         if existing_vdu.get("ssh-access-required"):
1501 0             ssh_keys.append(ro_nsr_public_key)
1502
1503 0         if ssh_keys:
1504 0             cloud_config["key-pairs"] = ssh_keys
1505
1506 0         disk_list = []
1507 0         for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
1508 0             disk_list.append({"vim_id": vol_id["id"]})
1509
1510 0         affinity_group_list = []
1511
1512 0         if existing_vdu.get("affinity-or-anti-affinity-group-id"):
1513 0             affinity_group = {}
1514 0             for affinity_group_id in existing_vdu["affinity-or-anti-affinity-group-id"]:
1515 0                 for group in db_nsr.get("affinity-or-anti-affinity-group"):
1516 0                     if (
1517                         group["id"] == affinity_group_id
1518                         and group["vim_info"][target_id].get("vim_id", None) is not None
1519                     ):
1520 0                         affinity_group["affinity_group_id"] = group["vim_info"][
1521                             target_id
1522                         ].get("vim_id", None)
1523 0                         affinity_group_list.append(affinity_group)
1524
1525 0         extra_dict["params"] = {
1526             "name": "{}-{}-{}-{}".format(
1527                 db_nsr["name"][:16],
1528                 vnfr["member-vnf-index-ref"][:16],
1529                 existing_vdu["vdu-name"][:32],
1530                 existing_vdu.get("count-index") or 0,
1531             ),
1532             "description": existing_vdu["vdu-name"],
1533             "start": True,
1534             "image_id": vim_details["image"]["id"],
1535             "flavor_id": vim_details["flavor"]["id"],
1536             "affinity_group_list": affinity_group_list,
1537             "net_list": net_list,
1538             "cloud_config": cloud_config or None,
1539             "disk_list": disk_list,
1540             "availability_zone_index": None,  # TODO
1541             "availability_zone_list": None,  # TODO
1542         }
1543
1544 0         return extra_dict
1545
1546 1     def calculate_diff_items(
1547         self,
1548         indata,
1549         db_nsr,
1550         db_ro_nsr,
1551         db_nsr_update,
1552         item,
1553         tasks_by_target_record_id,
1554         action_id,
1555         nsr_id,
1556         task_index,
1557         vnfr_id=None,
1558         vnfr=None,
1559     ):
1560         """Function that returns the incremental changes (creation, deletion)
1561         related to a specific item `item` to be done. This function should be
1562         called for NS instantiation, NS termination, NS update to add a new VNF
1563         or a new VLD, remove a VNF or VLD, etc.
1564         Item can be `net`, `flavor`, `image` or `vdu`.
1565         It takes a list of target items from indata (which came from the REST API)
1566         and compares with the existing items from db_ro_nsr, identifying the
1567         incremental changes to be done. During the comparison, it calls the method
1568         `process_params` (which was passed as parameter, and is particular for each
1569         `item`)
1570
1571         Args:
1572             indata (Dict[str, Any]): deployment info
1573             db_nsr: NSR record from DB
1574             db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1575             db_nsr_update (Dict[str, Any]): NSR info to update in DB
1576             item (str): element to process (net, vdu...)
1577             tasks_by_target_record_id (Dict[str, Any]):
1578                 [<target_record_id>, <task>]
1579             action_id (str): action id
1580             nsr_id (str): NSR id
1581             task_index (number): task index to add to task name
1582             vnfr_id (str): VNFR id
1583             vnfr (Dict[str, Any]): VNFR info
1584
1585         Returns:
1586             List: list with the incremental changes (deletes, creates) for each item
1587             number: current task index
1588         """
1589
1590 0         diff_items = []
1591 0         db_path = ""
1592 0         db_record = ""
1593 0         target_list = []
1594 0         existing_list = []
1595 0         process_params = None
1596 0         vdu2cloud_init = indata.get("cloud_init_content") or {}
1597 0         ro_nsr_public_key = db_ro_nsr["public_key"]
1598
1599         # According to the type of item, the path, the target_list,
1600         # the existing_list and the method to process params are set
1601 0         db_path = self.db_path_map[item]
1602 0         process_params = self.process_params_function_map[item]
1603 0         if item in ("net", "vdu"):
1604             # This case is specific for the NS VLD (not applied to VDU)
1605 0             if vnfr is None:
1606 0                 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1607 0                 target_list = indata.get("ns", []).get(db_path, [])
1608 0                 existing_list = db_nsr.get(db_path, [])
1609             # This case is common for VNF VLDs and VNF VDUs
1610             else:
1611 0                 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
1612 0                 target_vnf = next(
1613                     (vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id),
1614                     None,
1615                 )
1616 0                 target_list = target_vnf.get(db_path, []) if target_vnf else []
1617 0                 existing_list = vnfr.get(db_path, [])
1618 0         elif item in ("image", "flavor", "affinity-or-anti-affinity-group"):
1619 0             db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1620 0             target_list = indata.get(item, [])
1621 0             existing_list = db_nsr.get(item, [])
1622         else:
1623 0             raise NsException("Item not supported: {}", item)
1624
1625         # ensure all the target_list elements has an "id". If not assign the index as id
1626 0         if target_list is None:
1627 0             target_list = []
1628 0         for target_index, tl in enumerate(target_list):
1629 0             if tl and not tl.get("id"):
1630 0                 tl["id"] = str(target_index)
1631
1632         # step 1 items (networks,vdus,...) to be deleted/updated
1633 0         for item_index, existing_item in enumerate(existing_list):
1634 0             target_item = next(
1635                 (t for t in target_list if t["id"] == existing_item["id"]),
1636                 None,
1637             )
1638
1639 0             for target_vim, existing_viminfo in existing_item.get(
1640                 "vim_info", {}
1641             ).items():
1642 0                 if existing_viminfo is None:
1643 0                     continue
1644
1645 0                 if target_item:
1646 0                     target_viminfo = target_item.get("vim_info", {}).get(target_vim)
1647                 else:
1648 0                     target_viminfo = None
1649
1650 0                 if target_viminfo is None:
1651                     # must be deleted
1652 0                     self._assign_vim(target_vim)
1653 0                     target_record_id = "{}.{}".format(db_record, existing_item["id"])
1654 0                     item_ = item
1655
1656 0                     if target_vim.startswith("sdn") or target_vim.startswith("wim"):
1657                         # item must be sdn-net instead of net if target_vim is a sdn
1658 0                         item_ = "sdn_net"
1659 0                         target_record_id += ".sdn"
1660
1661 0                     deployment_info = {
1662                         "action_id": action_id,
1663                         "nsr_id": nsr_id,
1664                         "task_index": task_index,
1665                     }
1666
1667 0                     diff_items.append(
1668                         {
1669                             "deployment_info": deployment_info,
1670                             "target_id": target_vim,
1671                             "item": item_,
1672                             "action": "DELETE",
1673                             "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1674                             "target_record_id": target_record_id,
1675                         }
1676                     )
1677 0                     task_index += 1
1678
1679         # step 2 items (networks,vdus,...) to be created
1680 0         for target_item in target_list:
1681 0             item_index = -1
1682
1683 0             for item_index, existing_item in enumerate(existing_list):
1684 0                 if existing_item["id"] == target_item["id"]:
1685 0                     break
1686             else:
1687 0                 item_index += 1
1688 0                 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1689 0                 existing_list.append(target_item)
1690 0                 existing_item = None
1691
1692 0             for target_vim, target_viminfo in target_item.get("vim_info", {}).items():
1693 0                 existing_viminfo = None
1694
1695 0                 if existing_item:
1696 0                     existing_viminfo = existing_item.get("vim_info", {}).get(target_vim)
1697
1698 0                 if existing_viminfo is not None:
1699 0                     continue
1700
1701 0                 target_record_id = "{}.{}".format(db_record, target_item["id"])
1702 0                 item_ = item
1703
1704 0                 if target_vim.startswith("sdn") or target_vim.startswith("wim"):
1705                     # item must be sdn-net instead of net if target_vim is a sdn
1706 0                     item_ = "sdn_net"
1707 0                     target_record_id += ".sdn"
1708
1709 0                 kwargs = {}
1710 0                 self.logger.debug(
1711                     "ns.calculate_diff_items target_item={}".format(target_item)
1712                 )
1713 0                 if process_params == Ns._process_flavor_params:
1714 0                     kwargs.update(
1715                         {
1716                             "db": self.db,
1717                         }
1718                     )
1719 0                     self.logger.debug(
1720                         "calculate_diff_items for flavor kwargs={}".format(kwargs)
1721                     )
1722
1723 0                 if process_params == Ns._process_vdu_params:
1724 0                     self.logger.debug("calculate_diff_items self.fs={}".format(self.fs))
1725 0                     kwargs.update(
1726                         {
1727                             "vnfr_id": vnfr_id,
1728                             "nsr_id": nsr_id,
1729                             "vnfr": vnfr,
1730                             "vdu2cloud_init": vdu2cloud_init,
1731                             "tasks_by_target_record_id": tasks_by_target_record_id,
1732                             "logger": self.logger,
1733                             "db": self.db,
1734                             "fs": self.fs,
1735                             "ro_nsr_public_key": ro_nsr_public_key,
1736                         }
1737                     )
1738 0                     self.logger.debug("calculate_diff_items kwargs={}".format(kwargs))
1739
1740 0                 extra_dict = process_params(
1741                     target_item,
1742                     indata,
1743                     target_viminfo,
1744                     target_record_id,
1745                     **kwargs,
1746                 )
1747 0                 self._assign_vim(target_vim)
1748
1749 0                 deployment_info = {
1750                     "action_id": action_id,
1751                     "nsr_id": nsr_id,
1752                     "task_index": task_index,
1753                 }
1754
1755 0                 new_item = {
1756                     "deployment_info": deployment_info,
1757                     "target_id": target_vim,
1758                     "item": item_,
1759                     "action": "CREATE",
1760                     "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1761                     "target_record_id": target_record_id,
1762                     "extra_dict": extra_dict,
1763                     "common_id": target_item.get("common_id", None),
1764                 }
1765 0                 diff_items.append(new_item)
1766 0                 tasks_by_target_record_id[target_record_id] = new_item
1767 0                 task_index += 1
1768
1769 0                 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1770
1771 0         return diff_items, task_index
1772
1773 1     def calculate_all_differences_to_deploy(
1774         self,
1775         indata,
1776         nsr_id,
1777         db_nsr,
1778         db_vnfrs,
1779         db_ro_nsr,
1780         db_nsr_update,
1781         db_vnfrs_update,
1782         action_id,
1783         tasks_by_target_record_id,
1784     ):
1785         """This method calculates the ordered list of items (`changes_list`)
1786         to be created and deleted.
1787
1788         Args:
1789             indata (Dict[str, Any]): deployment info
1790             nsr_id (str): NSR id
1791             db_nsr: NSR record from DB
1792             db_vnfrs: VNFRS record from DB
1793             db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1794             db_nsr_update (Dict[str, Any]): NSR info to update in DB
1795             db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
1796             action_id (str): action id
1797             tasks_by_target_record_id (Dict[str, Any]):
1798                 [<target_record_id>, <task>]
1799
1800         Returns:
1801             List: ordered list of items to be created and deleted.
1802         """
1803
1804 0         task_index = 0
1805         # set list with diffs:
1806 0         changes_list = []
1807
1808         # NS vld, image and flavor
1809 0         for item in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
1810 0             self.logger.debug("process NS={} {}".format(nsr_id, item))
1811 0             diff_items, task_index = self.calculate_diff_items(
1812                 indata=indata,
1813                 db_nsr=db_nsr,
1814                 db_ro_nsr=db_ro_nsr,
1815                 db_nsr_update=db_nsr_update,
1816                 item=item,
1817                 tasks_by_target_record_id=tasks_by_target_record_id,
1818                 action_id=action_id,
1819                 nsr_id=nsr_id,
1820                 task_index=task_index,
1821                 vnfr_id=None,
1822             )
1823 0             changes_list += diff_items
1824
1825         # VNF vlds and vdus
1826 0         for vnfr_id, vnfr in db_vnfrs.items():
1827             # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1828 0             for item in ["net", "vdu"]:
1829 0                 self.logger.debug("process VNF={} {}".format(vnfr_id, item))
1830 0                 diff_items, task_index = self.calculate_diff_items(
1831                     indata=indata,
1832                     db_nsr=db_nsr,
1833                     db_ro_nsr=db_ro_nsr,
1834                     db_nsr_update=db_vnfrs_update[vnfr["_id"]],
1835                     item=item,
1836                     tasks_by_target_record_id=tasks_by_target_record_id,
1837                     action_id=action_id,
1838                     nsr_id=nsr_id,
1839                     task_index=task_index,
1840                     vnfr_id=vnfr_id,
1841                     vnfr=vnfr,
1842                 )
1843 0                 changes_list += diff_items
1844
1845 0         return changes_list
1846
1847 1     def define_all_tasks(
1848         self,
1849         changes_list,
1850         db_new_tasks,
1851         tasks_by_target_record_id,
1852     ):
1853         """Function to create all the task structures obtanied from
1854         the method calculate_all_differences_to_deploy
1855
1856         Args:
1857             changes_list (List): ordered list of items to be created or deleted
1858             db_new_tasks (List): tasks list to be created
1859             action_id (str): action id
1860             tasks_by_target_record_id (Dict[str, Any]):
1861                 [<target_record_id>, <task>]
1862
1863         """
1864
1865 0         for change in changes_list:
1866 0             task = Ns._create_task(
1867                 deployment_info=change["deployment_info"],
1868                 target_id=change["target_id"],
1869                 item=change["item"],
1870                 action=change["action"],
1871                 target_record=change["target_record"],
1872                 target_record_id=change["target_record_id"],
1873                 extra_dict=change.get("extra_dict", None),
1874             )
1875
1876 0             self.logger.debug("ns.define_all_tasks task={}".format(task))
1877 0             tasks_by_target_record_id[change["target_record_id"]] = task
1878 0             db_new_tasks.append(task)
1879
1880 0             if change.get("common_id"):
1881 0                 task["common_id"] = change["common_id"]
1882
1883 1     def upload_all_tasks(
1884         self,
1885         db_new_tasks,
1886         now,
1887     ):
1888         """Function to save all tasks in the common DB
1889
1890         Args:
1891             db_new_tasks (List): tasks list to be created
1892             now (time): current time
1893
1894         """
1895
1896 0         nb_ro_tasks = 0  # for logging
1897
1898 0         for db_task in db_new_tasks:
1899 0             target_id = db_task.pop("target_id")
1900 0             common_id = db_task.get("common_id")
1901
1902             # Do not chek tasks with vim_status DELETED
1903             # because in manual heealing there are two tasks for the same vdur:
1904             #   one with vim_status deleted and the other one with the actual VM status.
1905
1906 0             if common_id:
1907 0                 if self.db.set_one(
1908                     "ro_tasks",
1909                     q_filter={
1910                         "target_id": target_id,
1911                         "tasks.common_id": common_id,
1912                         "vim_info.vim_status.ne": "DELETED",
1913                     },
1914                     update_dict={"to_check_at": now, "modified_at": now},
1915                     push={"tasks": db_task},
1916                     fail_on_empty=False,
1917                 ):
1918 0                     continue
1919
1920 0             if not self.db.set_one(
1921                 "ro_tasks",
1922                 q_filter={
1923                     "target_id": target_id,
1924                     "tasks.target_record": db_task["target_record"],
1925                     "vim_info.vim_status.ne": "DELETED",
1926                 },
1927                 update_dict={"to_check_at": now, "modified_at": now},
1928                 push={"tasks": db_task},
1929                 fail_on_empty=False,
1930             ):
1931                 # Create a ro_task
1932 0                 self.logger.debug("Updating database, Creating ro_tasks")
1933 0                 db_ro_task = Ns._create_ro_task(target_id, db_task)
1934 0                 nb_ro_tasks += 1
1935 0                 self.db.create("ro_tasks", db_ro_task)
1936
1937 0         self.logger.debug(
1938             "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1939                 nb_ro_tasks, len(db_new_tasks), db_new_tasks
1940             )
1941         )
1942
1943 1     def upload_recreate_tasks(
1944         self,
1945         db_new_tasks,
1946         now,
1947     ):
1948         """Function to save recreate tasks in the common DB
1949
1950         Args:
1951             db_new_tasks (List): tasks list to be created
1952             now (time): current time
1953
1954         """
1955
1956 0         nb_ro_tasks = 0  # for logging
1957
1958 0         for db_task in db_new_tasks:
1959 0             target_id = db_task.pop("target_id")
1960 0             self.logger.debug("target_id={} db_task={}".format(target_id, db_task))
1961
1962 0             action = db_task.get("action", None)
1963
1964             # Create a ro_task
1965 0             self.logger.debug("Updating database, Creating ro_tasks")
1966 0             db_ro_task = Ns._create_ro_task(target_id, db_task)
1967
1968             # If DELETE task: the associated created items should be removed
1969             # (except persistent volumes):
1970 0             if action == "DELETE":
1971 0                 db_ro_task["vim_info"]["created"] = True
1972 0                 db_ro_task["vim_info"]["created_items"] = db_task.get(
1973                     "created_items", {}
1974                 )
1975 0                 db_ro_task["vim_info"]["volumes_to_hold"] = db_task.get(
1976                     "volumes_to_hold", []
1977                 )
1978 0                 db_ro_task["vim_info"]["vim_id"] = db_task.get("vim_id", None)
1979
1980 0             nb_ro_tasks += 1
1981 0             self.logger.debug("upload_all_tasks db_ro_task={}".format(db_ro_task))
1982 0             self.db.create("ro_tasks", db_ro_task)
1983
1984 0         self.logger.debug(
1985             "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1986                 nb_ro_tasks, len(db_new_tasks), db_new_tasks
1987             )
1988         )
1989
1990 1     def _prepare_created_items_for_healing(
1991         self,
1992         nsr_id,
1993         target_record,
1994     ):
1995 0         created_items = {}
1996         # Get created_items from ro_task
1997 0         ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
1998 0         for ro_task in ro_tasks:
1999 0             for task in ro_task["tasks"]:
2000 0                 if (
2001                     task["target_record"] == target_record
2002                     and task["action"] == "CREATE"
2003                     and ro_task["vim_info"]["created_items"]
2004                 ):
2005 0                     created_items = ro_task["vim_info"]["created_items"]
2006 0                     break
2007
2008 0         return created_items
2009
2010 1     def _prepare_persistent_volumes_for_healing(
2011         self,
2012         target_id,
2013         existing_vdu,
2014     ):
2015         # The associated volumes of the VM shouldn't be removed
2016 0         volumes_list = []
2017 0         vim_details = {}
2018 0         vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
2019 0         if vim_details_text:
2020 0             vim_details = yaml.safe_load(f"{vim_details_text}")
2021
2022 0             for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
2023 0                 volumes_list.append(vol_id["id"])
2024
2025 0         return volumes_list
2026
2027 1     def prepare_changes_to_recreate(
2028         self,
2029         indata,
2030         nsr_id,
2031         db_nsr,
2032         db_vnfrs,
2033         db_ro_nsr,
2034         action_id,
2035         tasks_by_target_record_id,
2036     ):
2037         """This method will obtain an ordered list of items (`changes_list`)
2038         to be created and deleted to meet the recreate request.
2039         """
2040
2041 0         self.logger.debug(
2042             "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id, indata)
2043         )
2044
2045 0         task_index = 0
2046         # set list with diffs:
2047 0         changes_list = []
2048 0         db_path = self.db_path_map["vdu"]
2049 0         target_list = indata.get("healVnfData", {})
2050 0         vdu2cloud_init = indata.get("cloud_init_content") or {}
2051 0         ro_nsr_public_key = db_ro_nsr["public_key"]
2052
2053         # Check each VNF of the target
2054 0         for target_vnf in target_list:
2055             # Find this VNF in the list from DB
2056 0             vnfr_id = target_vnf.get("vnfInstanceId", None)
2057 0             if vnfr_id:
2058 0                 existing_vnf = db_vnfrs.get(vnfr_id)
2059 0                 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
2060                 # vim_account_id = existing_vnf.get("vim-account-id", "")
2061
2062             # Check each VDU of this VNF
2063 0             for target_vdu in target_vnf["additionalParams"].get("vdu", None):
2064 0                 vdu_name = target_vdu.get("vdu-id", None)
2065                 # For multi instance VDU count-index is mandatory
2066                 # For single session VDU count-indes is 0
2067 0                 count_index = target_vdu.get("count-index", 0)
2068 0                 item_index = 0
2069 0                 existing_instance = None
2070 0                 for instance in existing_vnf.get("vdur", None):
2071 0                     if (
2072                         instance["vdu-name"] == vdu_name
2073                         and instance["count-index"] == count_index
2074                     ):
2075 0                         existing_instance = instance
2076 0                         break
2077                     else:
2078 0                         item_index += 1
2079
2080 0                 target_record_id = "{}.{}".format(db_record, existing_instance["id"])
2081
2082                 # The target VIM is the one already existing in DB to recreate
2083 0                 for target_vim, target_viminfo in existing_instance.get(
2084                     "vim_info", {}
2085                 ).items():
2086                     # step 1 vdu to be deleted
2087 0                     self._assign_vim(target_vim)
2088 0                     deployment_info = {
2089                         "action_id": action_id,
2090                         "nsr_id": nsr_id,
2091                         "task_index": task_index,
2092                     }
2093
2094 0                     target_record = f"{db_record}.{item_index}.vim_info.{target_vim}"
2095 0                     created_items = self._prepare_created_items_for_healing(
2096                         nsr_id, target_record
2097                     )
2098
2099 0                     volumes_to_hold = self._prepare_persistent_volumes_for_healing(
2100                         target_vim, existing_instance
2101                     )
2102
2103                     # Specific extra params for recreate tasks:
2104 0                     extra_dict = {
2105                         "created_items": created_items,
2106                         "vim_id": existing_instance["vim-id"],
2107                         "volumes_to_hold": volumes_to_hold,
2108                     }
2109
2110 0                     changes_list.append(
2111                         {
2112                             "deployment_info": deployment_info,
2113                             "target_id": target_vim,
2114                             "item": "vdu",
2115                             "action": "DELETE",
2116                             "target_record": target_record,
2117                             "target_record_id": target_record_id,
2118                             "extra_dict": extra_dict,
2119                         }
2120                     )
2121 0                     delete_task_id = f"{action_id}:{task_index}"
2122 0                     task_index += 1
2123
2124                     # step 2 vdu to be created
2125 0                     kwargs = {}
2126 0                     kwargs.update(
2127                         {
2128                             "vnfr_id": vnfr_id,
2129                             "nsr_id": nsr_id,
2130                             "vnfr": existing_vnf,
2131                             "vdu2cloud_init": vdu2cloud_init,
2132                             "tasks_by_target_record_id": tasks_by_target_record_id,
2133                             "logger": self.logger,
2134                             "db": self.db,
2135                             "fs": self.fs,
2136                             "ro_nsr_public_key": ro_nsr_public_key,
2137                         }
2138                     )
2139
2140 0                     extra_dict = self._process_recreate_vdu_params(
2141                         existing_instance,
2142                         db_nsr,
2143                         target_viminfo,
2144                         target_record_id,
2145                         target_vim,
2146                         **kwargs,
2147                     )
2148
2149                     # The CREATE task depens on the DELETE task
2150 0                     extra_dict["depends_on"] = [delete_task_id]
2151
2152                     # Add volumes created from created_items if any
2153                     # Ports should be deleted with delete task and automatically created with create task
2154 0                     volumes = {}
2155 0                     for k, v in created_items.items():
2156 0                         try:
2157 0                             k_item, _, k_id = k.partition(":")
2158 0                             if k_item == "volume":
2159 0                                 volumes[k] = v
2160 0                         except Exception as e:
2161 0                             self.logger.error(
2162                                 "Error evaluating created item {}: {}".format(k, e)
2163                             )
2164 0                     extra_dict["previous_created_volumes"] = volumes
2165
2166 0                     deployment_info = {
2167                         "action_id": action_id,
2168                         "nsr_id": nsr_id,
2169                         "task_index": task_index,
2170                     }
2171 0                     self._assign_vim(target_vim)
2172
2173 0                     new_item = {
2174                         "deployment_info": deployment_info,
2175                         "target_id": target_vim,
2176                         "item": "vdu",
2177                         "action": "CREATE",
2178                         "target_record": target_record,
2179                         "target_record_id": target_record_id,
2180                         "extra_dict": extra_dict,
2181                     }
2182 0                     changes_list.append(new_item)
2183 0                     tasks_by_target_record_id[target_record_id] = new_item
2184 0                     task_index += 1
2185
2186 0         return changes_list
2187
2188 1     def recreate(self, session, indata, version, nsr_id, *args, **kwargs):
2189 0         self.logger.debug("ns.recreate nsr_id={} indata={}".format(nsr_id, indata))
2190         # TODO: validate_input(indata, recreate_schema)
2191 0         action_id = indata.get("action_id", str(uuid4()))
2192         # get current deployment
2193 0         db_vnfrs = {}  # vnf's info indexed by _id
2194 0         step = ""
2195 0         logging_text = "Recreate nsr_id={} action_id={} indata={}".format(
2196             nsr_id, action_id, indata
2197         )
2198 0         self.logger.debug(logging_text + "Enter")
2199
2200 0         try:
2201 0             step = "Getting ns and vnfr record from db"
2202 0             db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2203 0             db_new_tasks = []
2204 0             tasks_by_target_record_id = {}
2205             # read from db: vnf's of this ns
2206 0             step = "Getting vnfrs from db"
2207 0             db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2208 0             self.logger.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list))
2209
2210 0             if not db_vnfrs_list:
2211 0                 raise NsException("Cannot obtain associated VNF for ns")
2212
2213 0             for vnfr in db_vnfrs_list:
2214 0                 db_vnfrs[vnfr["_id"]] = vnfr
2215
2216 0             now = time()
2217 0             db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
2218 0             self.logger.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr))
2219
2220 0             if not db_ro_nsr:
2221 0                 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
2222
2223 0             with self.write_lock:
2224                 # NS
2225 0                 step = "process NS elements"
2226 0                 changes_list = self.prepare_changes_to_recreate(
2227                     indata=indata,
2228                     nsr_id=nsr_id,
2229                     db_nsr=db_nsr,
2230                     db_vnfrs=db_vnfrs,
2231                     db_ro_nsr=db_ro_nsr,
2232                     action_id=action_id,
2233                     tasks_by_target_record_id=tasks_by_target_record_id,
2234                 )
2235
2236 0                 self.define_all_tasks(
2237                     changes_list=changes_list,
2238                     db_new_tasks=db_new_tasks,
2239                     tasks_by_target_record_id=tasks_by_target_record_id,
2240                 )
2241
2242                 # Delete all ro_tasks registered for the targets vdurs (target_record)
2243                 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2244                 # So remove all task related to target record.
2245 0                 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2246 0                 for change in changes_list:
2247 0                     for ro_task in ro_tasks:
2248 0                         for task in ro_task["tasks"]:
2249 0                             if task["target_record"] == change["target_record"]:
2250 0                                 self.db.del_one(
2251                                     "ro_tasks",
2252                                     q_filter={
2253                                         "_id": ro_task["_id"],
2254                                         "modified_at": ro_task["modified_at"],
2255                                     },
2256                                     fail_on_empty=False,
2257                                 )
2258
2259 0                 step = "Updating database, Appending tasks to ro_tasks"
2260 0                 self.upload_recreate_tasks(
2261                     db_new_tasks=db_new_tasks,
2262                     now=now,
2263                 )
2264
2265 0             self.logger.debug(
2266                 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2267             )
2268
2269 0             return (
2270                 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2271                 action_id,
2272                 True,
2273             )
2274 0         except Exception as e:
2275 0             if isinstance(e, (DbException, NsException)):
2276 0                 self.logger.error(
2277                     logging_text + "Exit Exception while '{}': {}".format(step, e)
2278                 )
2279             else:
2280 0                 e = traceback_format_exc()
2281 0                 self.logger.critical(
2282                     logging_text + "Exit Exception while '{}': {}".format(step, e),
2283                     exc_info=True,
2284                 )
2285
2286 0             raise NsException(e)
2287
2288 1     def deploy(self, session, indata, version, nsr_id, *args, **kwargs):
2289 0         self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata))
2290 0         validate_input(indata, deploy_schema)
2291 0         action_id = indata.get("action_id", str(uuid4()))
2292 0         task_index = 0
2293         # get current deployment
2294 0         db_nsr_update = {}  # update operation on nsrs
2295 0         db_vnfrs_update = {}
2296 0         db_vnfrs = {}  # vnf's info indexed by _id
2297 0         step = ""
2298 0         logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2299 0         self.logger.debug(logging_text + "Enter")
2300
2301 0         try:
2302 0             step = "Getting ns and vnfr record from db"
2303 0             db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2304 0             self.logger.debug("ns.deploy: db_nsr={}".format(db_nsr))
2305 0             db_new_tasks = []
2306 0             tasks_by_target_record_id = {}
2307             # read from db: vnf's of this ns
2308 0             step = "Getting vnfrs from db"
2309 0             db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2310
2311 0             if not db_vnfrs_list:
2312 0                 raise NsException("Cannot obtain associated VNF for ns")
2313
2314 0             for vnfr in db_vnfrs_list:
2315 0                 db_vnfrs[vnfr["_id"]] = vnfr
2316 0                 db_vnfrs_update[vnfr["_id"]] = {}
2317 0             self.logger.debug("ns.deploy db_vnfrs={}".format(db_vnfrs))
2318
2319 0             now = time()
2320 0             db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
2321
2322 0             if not db_ro_nsr:
2323 0                 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
2324
2325             # check that action_id is not in the list of actions. Suffixed with :index
2326 0             if action_id in db_ro_nsr["actions"]:
2327 0                 index = 1
2328
2329                 while True:
2330 0                     new_action_id = "{}:{}".format(action_id, index)
2331
2332 0                     if new_action_id not in db_ro_nsr["actions"]:
2333 0                         action_id = new_action_id
2334 0                         self.logger.debug(
2335                             logging_text
2336                             + "Changing action_id in use to {}".format(action_id)
2337                         )
2338 0                         break
2339
2340 0                     index += 1
2341
2342 0             def _process_action(indata):
2343                 nonlocal db_new_tasks
2344                 nonlocal action_id
2345                 nonlocal nsr_id
2346                 nonlocal task_index
2347                 nonlocal db_vnfrs
2348                 nonlocal db_ro_nsr
2349
2350 0                 if indata["action"]["action"] == "inject_ssh_key":
2351 0                     key = indata["action"].get("key")
2352 0                     user = indata["action"].get("user")
2353 0                     password = indata["action"].get("password")
2354
2355 0                     for vnf in indata.get("vnf", ()):
2356 0                         if vnf["_id"] not in db_vnfrs:
2357 0                             raise NsException("Invalid vnf={}".format(vnf["_id"]))
2358
2359 0                         db_vnfr = db_vnfrs[vnf["_id"]]
2360
2361 0                         for target_vdu in vnf.get("vdur", ()):
2362 0                             vdu_index, vdur = next(
2363                                 (
2364                                     i_v
2365                                     for i_v in enumerate(db_vnfr["vdur"])
2366                                     if i_v[1]["id"] == target_vdu["id"]
2367                                 ),
2368                                 (None, None),
2369                             )
2370
2371 0                             if not vdur:
2372 0                                 raise NsException(
2373                                     "Invalid vdu vnf={}.{}".format(
2374                                         vnf["_id"], target_vdu["id"]
2375                                     )
2376                                 )
2377
2378 0                             target_vim, vim_info = next(
2379                                 k_v for k_v in vdur["vim_info"].items()
2380                             )
2381 0                             self._assign_vim(target_vim)
2382 0                             target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
2383                                 vnf["_id"], vdu_index
2384                             )
2385 0                             extra_dict = {
2386                                 "depends_on": [
2387                                     "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
2388                                 ],
2389                                 "params": {
2390                                     "ip_address": vdur.get("ip-address"),
2391                                     "user": user,
2392                                     "key": key,
2393                                     "password": password,
2394                                     "private_key": db_ro_nsr["private_key"],
2395                                     "salt": db_ro_nsr["_id"],
2396                                     "schema_version": db_ro_nsr["_admin"][
2397                                         "schema_version"
2398                                     ],
2399                                 },
2400                             }
2401
2402 0                             deployment_info = {
2403                                 "action_id": action_id,
2404                                 "nsr_id": nsr_id,
2405                                 "task_index": task_index,
2406                             }
2407
2408 0                             task = Ns._create_task(
2409                                 deployment_info=deployment_info,
2410                                 target_id=target_vim,
2411                                 item="vdu",
2412                                 action="EXEC",
2413                                 target_record=target_record,
2414                                 target_record_id=None,
2415                                 extra_dict=extra_dict,
2416                             )
2417
2418 0                             task_index = deployment_info.get("task_index")
2419
2420 0                             db_new_tasks.append(task)
2421
2422 0             with self.write_lock:
2423 0                 if indata.get("action"):
2424 0                     _process_action(indata)
2425                 else:
2426                     # compute network differences
2427                     # NS
2428 0                     step = "process NS elements"
2429 0                     changes_list = self.calculate_all_differences_to_deploy(
2430                         indata=indata,
2431                         nsr_id=nsr_id,
2432                         db_nsr=db_nsr,
2433                         db_vnfrs=db_vnfrs,
2434                         db_ro_nsr=db_ro_nsr,
2435                         db_nsr_update=db_nsr_update,
2436                         db_vnfrs_update=db_vnfrs_update,
2437                         action_id=action_id,
2438                         tasks_by_target_record_id=tasks_by_target_record_id,
2439                     )
2440 0                     self.define_all_tasks(
2441                         changes_list=changes_list,
2442                         db_new_tasks=db_new_tasks,
2443                         tasks_by_target_record_id=tasks_by_target_record_id,
2444                     )
2445
2446 0                 step = "Updating database, Appending tasks to ro_tasks"
2447 0                 self.upload_all_tasks(
2448                     db_new_tasks=db_new_tasks,
2449                     now=now,
2450                 )
2451
2452 0                 step = "Updating database, nsrs"
2453 0                 if db_nsr_update:
2454 0                     self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
2455
2456 0                 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
2457 0                     if db_vnfr_update:
2458 0                         step = "Updating database, vnfrs={}".format(vnfr_id)
2459 0                         self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
2460
2461 0             self.logger.debug(
2462                 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2463             )
2464
2465 0             return (
2466                 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2467                 action_id,
2468                 True,
2469             )
2470 0         except Exception as e:
2471 0             if isinstance(e, (DbException, NsException)):
2472 0                 self.logger.error(
2473                     logging_text + "Exit Exception while '{}': {}".format(step, e)
2474                 )
2475             else:
2476 0                 e = traceback_format_exc()
2477 0                 self.logger.critical(
2478                     logging_text + "Exit Exception while '{}': {}".format(step, e),
2479                     exc_info=True,
2480                 )
2481
2482 0             raise NsException(e)
2483
2484 1     def delete(self, session, indata, version, nsr_id, *args, **kwargs):
2485 0         self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
2486         # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2487
2488 0         with self.write_lock:
2489 0             try:
2490 0                 NsWorker.delete_db_tasks(self.db, nsr_id, None)
2491 0             except NsWorkerException as e:
2492 0                 raise NsException(e)
2493
2494 0         return None, None, True
2495
2496 1     def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2497 0         self.logger.debug(
2498             "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2499                 version, nsr_id, action_id, indata
2500             )
2501         )
2502 0         task_list = []
2503 0         done = 0
2504 0         total = 0
2505 0         ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
2506 0         global_status = "DONE"
2507 0         details = []
2508
2509 0         for ro_task in ro_tasks:
2510 0             for task in ro_task["tasks"]:
2511 0                 if task and task["action_id"] == action_id:
2512 0                     task_list.append(task)
2513 0                     total += 1
2514
2515 0                     if task["status"] == "FAILED":
2516 0                         global_status = "FAILED"
2517 0                         error_text = "Error at {} {}: {}".format(
2518                             task["action"].lower(),
2519                             task["item"],
2520                             ro_task["vim_info"].get("vim_message") or "unknown",
2521                         )
2522 0                         details.append(error_text)
2523 0                     elif task["status"] in ("SCHEDULED", "BUILD"):
2524 0                         if global_status != "FAILED":
2525 0                             global_status = "BUILD"
2526                     else:
2527 0                         done += 1
2528
2529 0         return_data = {
2530             "status": global_status,
2531             "details": ". ".join(details)
2532             if details
2533             else "progress {}/{}".format(done, total),
2534             "nsr_id": nsr_id,
2535             "action_id": action_id,
2536             "tasks": task_list,
2537         }
2538
2539 0         return return_data, None, True
2540
2541 1     def recreate_status(
2542         self, session, indata, version, nsr_id, action_id, *args, **kwargs
2543     ):
2544 0         return self.status(session, indata, version, nsr_id, action_id, *args, **kwargs)
2545
2546 1     def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2547 0         print(
2548             "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2549                 session, indata, version, nsr_id, action_id
2550             )
2551         )
2552
2553 0         return None, None, True
2554
2555 1     def rebuild_start_stop_task(
2556         self,
2557         vdu_id,
2558         vnf_id,
2559         vdu_index,
2560         action_id,
2561         nsr_id,
2562         task_index,
2563         target_vim,
2564         extra_dict,
2565     ):
2566 1         self._assign_vim(target_vim)
2567 1         target_record = "vnfrs:{}:vdur.{}".format(vnf_id, vdu_index)
2568 1         target_record_id = "vnfrs:{}:vdur.{}".format(vnf_id, vdu_id)
2569 1         deployment_info = {
2570             "action_id": action_id,
2571             "nsr_id": nsr_id,
2572             "task_index": task_index,
2573         }
2574
2575 1         task = Ns._create_task(
2576             deployment_info=deployment_info,
2577             target_id=target_vim,
2578             item="update",
2579             action="EXEC",
2580             target_record=target_record,
2581             target_record_id=target_record_id,
2582             extra_dict=extra_dict,
2583         )
2584 1         return task
2585
2586 1     def rebuild_start_stop(
2587         self, session, action_dict, version, nsr_id, *args, **kwargs
2588     ):
2589 0         task_index = 0
2590 0         extra_dict = {}
2591 0         now = time()
2592 0         action_id = action_dict.get("action_id", str(uuid4()))
2593 0         step = ""
2594 0         logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2595 0         self.logger.debug(logging_text + "Enter")
2596
2597 0         action = list(action_dict.keys())[0]
2598 0         task_dict = action_dict.get(action)
2599 0         vim_vm_id = action_dict.get(action).get("vim_vm_id")
2600
2601 0         if action_dict.get("stop"):
2602 0             action = "shutoff"
2603 0         db_new_tasks = []
2604 0         try:
2605 0             step = "lock the operation & do task creation"
2606 0             with self.write_lock:
2607 0                 extra_dict["params"] = {
2608                     "vim_vm_id": vim_vm_id,
2609                     "action": action,
2610                 }
2611 0                 task = self.rebuild_start_stop_task(
2612                     task_dict["vdu_id"],
2613                     task_dict["vnf_id"],
2614                     task_dict["vdu_index"],
2615                     action_id,
2616                     nsr_id,
2617                     task_index,
2618                     task_dict["target_vim"],
2619                     extra_dict,
2620                 )
2621 0                 db_new_tasks.append(task)
2622 0                 step = "upload Task to db"
2623 0                 self.upload_all_tasks(
2624                     db_new_tasks=db_new_tasks,
2625                     now=now,
2626                 )
2627 0                 self.logger.debug(
2628                     logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2629                 )
2630 0                 return (
2631                     {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2632                     action_id,
2633                     True,
2634                 )
2635 0         except Exception as e:
2636 0             if isinstance(e, (DbException, NsException)):
2637 0                 self.logger.error(
2638                     logging_text + "Exit Exception while '{}': {}".format(step, e)
2639                 )
2640             else:
2641 0                 e = traceback_format_exc()
2642 0                 self.logger.critical(
2643                     logging_text + "Exit Exception while '{}': {}".format(step, e),
2644                     exc_info=True,
2645                 )
2646 0             raise NsException(e)
2647
2648 1     def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2649 0         nsrs = self.db.get_list("nsrs", {})
2650 0         return_data = []
2651
2652 0         for ns in nsrs:
2653 0             return_data.append({"_id": ns["_id"], "name": ns["name"]})
2654
2655 0         return return_data, None, True
2656
2657 1     def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2658 0         ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2659 0         return_data = []
2660
2661 0         for ro_task in ro_tasks:
2662 0             for task in ro_task["tasks"]:
2663 0                 if task["action_id"] not in return_data:
2664 0                     return_data.append(task["action_id"])
2665
2666 0         return return_data, None, True
2667
2668 1     def migrate_task(
2669         self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
2670     ):
2671 1         target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
2672 1         self._assign_vim(target_vim)
2673 1         target_record = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu_index)
2674 1         target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
2675 1         deployment_info = {
2676             "action_id": action_id,
2677             "nsr_id": nsr_id,
2678             "task_index": task_index,
2679         }
2680
2681 1         task = Ns._create_task(
2682             deployment_info=deployment_info,
2683             target_id=target_vim,
2684             item="migrate",
2685             action="EXEC",
2686             target_record=target_record,
2687             target_record_id=target_record_id,
2688             extra_dict=extra_dict,
2689         )
2690
2691 1         return task
2692
2693 1     def migrate(self, session, indata, version, nsr_id, *args, **kwargs):
2694 0         task_index = 0
2695 0         extra_dict = {}
2696 0         now = time()
2697 0         action_id = indata.get("action_id", str(uuid4()))
2698 0         step = ""
2699 0         logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2700 0         self.logger.debug(logging_text + "Enter")
2701 0         try:
2702 0             vnf_instance_id = indata["vnfInstanceId"]
2703 0             step = "Getting vnfrs from db"
2704 0             db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
2705 0             vdu = indata.get("vdu")
2706 0             migrateToHost = indata.get("migrateToHost")
2707 0             db_new_tasks = []
2708
2709 0             with self.write_lock:
2710 0                 if vdu is not None:
2711 0                     vdu_id = indata["vdu"]["vduId"]
2712 0                     vdu_count_index = indata["vdu"].get("vduCountIndex", 0)
2713 0                     for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
2714 0                         if (
2715                             vdu["vdu-id-ref"] == vdu_id
2716                             and vdu["count-index"] == vdu_count_index
2717                         ):
2718 0                             extra_dict["params"] = {
2719                                 "vim_vm_id": vdu["vim-id"],
2720                                 "migrate_host": migrateToHost,
2721                                 "vdu_vim_info": vdu["vim_info"],
2722                             }
2723 0                             step = "Creating migration task for vdu:{}".format(vdu)
2724 0                             task = self.migrate_task(
2725                                 vdu,
2726                                 db_vnfr,
2727                                 vdu_index,
2728                                 action_id,
2729                                 nsr_id,
2730                                 task_index,
2731                                 extra_dict,
2732                             )
2733 0                             db_new_tasks.append(task)
2734 0                             task_index += 1
2735 0                             break
2736                 else:
2737
2738 0                     for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
2739 0                         extra_dict["params"] = {
2740                             "vim_vm_id": vdu["vim-id"],
2741                             "migrate_host": migrateToHost,
2742                             "vdu_vim_info": vdu["vim_info"],
2743                         }
2744 0                         step = "Creating migration task for vdu:{}".format(vdu)
2745 0                         task = self.migrate_task(
2746                             vdu,
2747                             db_vnfr,
2748                             vdu_index,
2749                             action_id,
2750                             nsr_id,
2751                             task_index,
2752                             extra_dict,
2753                         )
2754 0                         db_new_tasks.append(task)
2755 0                         task_index += 1
2756
2757 0                 self.upload_all_tasks(
2758                     db_new_tasks=db_new_tasks,
2759                     now=now,
2760                 )
2761
2762 0             self.logger.debug(
2763                 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2764             )
2765 0             return (
2766                 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2767                 action_id,
2768                 True,
2769             )
2770 0         except Exception as e:
2771 0             if isinstance(e, (DbException, NsException)):
2772 0                 self.logger.error(
2773                     logging_text + "Exit Exception while '{}': {}".format(step, e)
2774                 )
2775             else:
2776 0                 e = traceback_format_exc()
2777 0                 self.logger.critical(
2778                     logging_text + "Exit Exception while '{}': {}".format(step, e),
2779                     exc_info=True,
2780                 )
2781 0             raise NsException(e)
2782
2783 1     def verticalscale_task(
2784         self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
2785     ):
2786 1         target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
2787 1         self._assign_vim(target_vim)
2788 1         target_record = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu_index)
2789 1         target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
2790 1         deployment_info = {
2791             "action_id": action_id,
2792             "nsr_id": nsr_id,
2793             "task_index": task_index,
2794         }
2795
2796 1         task = Ns._create_task(
2797             deployment_info=deployment_info,
2798             target_id=target_vim,
2799             item="verticalscale",
2800             action="EXEC",
2801             target_record=target_record,
2802             target_record_id=target_record_id,
2803             extra_dict=extra_dict,
2804         )
2805 1         return task
2806
2807 1     def verticalscale(self, session, indata, version, nsr_id, *args, **kwargs):
2808 0         task_index = 0
2809 0         extra_dict = {}
2810 0         now = time()
2811 0         action_id = indata.get("action_id", str(uuid4()))
2812 0         step = ""
2813 0         logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2814 0         self.logger.debug(logging_text + "Enter")
2815 0         try:
2816 0             VnfFlavorData = indata.get("changeVnfFlavorData")
2817 0             vnf_instance_id = VnfFlavorData["vnfInstanceId"]
2818 0             step = "Getting vnfrs from db"
2819 0             db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
2820 0             vduid = VnfFlavorData["additionalParams"]["vduid"]
2821 0             vduCountIndex = VnfFlavorData["additionalParams"]["vduCountIndex"]
2822 0             virtualMemory = VnfFlavorData["additionalParams"]["virtualMemory"]
2823 0             numVirtualCpu = VnfFlavorData["additionalParams"]["numVirtualCpu"]
2824 0             sizeOfStorage = VnfFlavorData["additionalParams"]["sizeOfStorage"]
2825 0             flavor_dict = {
2826                 "name": vduid + "-flv",
2827                 "ram": virtualMemory,
2828                 "vcpus": numVirtualCpu,
2829                 "disk": sizeOfStorage,
2830             }
2831 0             db_new_tasks = []
2832 0             step = "Creating Tasks for vertical scaling"
2833 0             with self.write_lock:
2834 0                 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
2835 0                     if (
2836                         vdu["vdu-id-ref"] == vduid
2837                         and vdu["count-index"] == vduCountIndex
2838                     ):
2839 0                         extra_dict["params"] = {
2840                             "vim_vm_id": vdu["vim-id"],
2841                             "flavor_dict": flavor_dict,
2842                         }
2843 0                         task = self.verticalscale_task(
2844                             vdu,
2845                             db_vnfr,
2846                             vdu_index,
2847                             action_id,
2848                             nsr_id,
2849                             task_index,
2850                             extra_dict,
2851                         )
2852 0                         db_new_tasks.append(task)
2853 0                         task_index += 1
2854 0                         break
2855 0                 self.upload_all_tasks(
2856                     db_new_tasks=db_new_tasks,
2857                     now=now,
2858                 )
2859 0             self.logger.debug(
2860                 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2861             )
2862 0             return (
2863                 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2864                 action_id,
2865                 True,
2866             )
2867 0         except Exception as e:
2868 0             if isinstance(e, (DbException, NsException)):
2869 0                 self.logger.error(
2870                     logging_text + "Exit Exception while '{}': {}".format(step, e)
2871                 )
2872             else:
2873 0                 e = traceback_format_exc()
2874 0                 self.logger.critical(
2875                     logging_text + "Exit Exception while '{}': {}".format(step, e),
2876                     exc_info=True,
2877                 )
2878 0             raise NsException(e)