Code Coverage

Cobertura Coverage Report > NG-RO.osm_ng_ro >

ns.py

Trend

File Coverage summary

NameClassesLinesConditionals
ns.py
100%
1/1
43%
510/1182
100%
0/0

Coverage Breakdown by Class

NameLinesConditionals
ns.py
43%
510/1182
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, List, Optional, 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         numa_list = []
651 1         epa_vcpu_set = False
652
653 1         if guest_epa_quota.get("numa-node-policy"):
654 1             numa_node_policy = guest_epa_quota.get("numa-node-policy")
655
656 1             if numa_node_policy.get("node"):
657 1                 for numa_node in numa_node_policy["node"]:
658 1                     vcpu_list = []
659 1                     if numa_node.get("id"):
660 1                         numa["id"] = int(numa_node["id"])
661
662 1                     if numa_node.get("vcpu"):
663 1                         for vcpu in numa_node.get("vcpu"):
664 1                             vcpu_id = int(vcpu.get("id"))
665 1                             vcpu_list.append(vcpu_id)
666 1                         numa["vcpu"] = vcpu_list
667
668 1                     if numa_node.get("num-cores"):
669 1                         numa["cores"] = numa_node["num-cores"]
670 1                         epa_vcpu_set = True
671
672 1                     paired_threads = numa_node.get("paired-threads", {})
673 1                     if paired_threads.get("num-paired-threads"):
674 1                         numa["paired_threads"] = int(
675                             numa_node["paired-threads"]["num-paired-threads"]
676                         )
677 1                         epa_vcpu_set = True
678
679 1                     if paired_threads.get("paired-thread-ids"):
680 1                         numa["paired-threads-id"] = []
681
682 1                         for pair in paired_threads["paired-thread-ids"]:
683 1                             numa["paired-threads-id"].append(
684                                 (
685                                     str(pair["thread-a"]),
686                                     str(pair["thread-b"]),
687                                 )
688                             )
689
690 1                     if numa_node.get("num-threads"):
691 1                         numa["threads"] = int(numa_node["num-threads"])
692 1                         epa_vcpu_set = True
693
694 1                     if numa_node.get("memory-mb"):
695 1                         numa["memory"] = max(int(int(numa_node["memory-mb"]) / 1024), 1)
696
697 1                     numa_list.append(numa)
698 1                     numa = {}
699
700 1         return numa_list, epa_vcpu_set
701
702 1     @staticmethod
703 1     def _process_guest_epa_cpu_pinning_params(
704         guest_epa_quota: Dict[str, Any],
705         vcpu_count: int,
706         epa_vcpu_set: bool,
707     ) -> Tuple[Dict[str, Any], bool]:
708         """[summary]
709
710         Args:
711             guest_epa_quota (Dict[str, Any]): [description]
712             vcpu_count (int): [description]
713             epa_vcpu_set (bool): [description]
714
715         Returns:
716             Tuple[Dict[str, Any], bool]: [description]
717         """
718 1         numa = {}
719 1         local_epa_vcpu_set = epa_vcpu_set
720
721 1         if (
722             guest_epa_quota.get("cpu-pinning-policy") == "DEDICATED"
723             and not epa_vcpu_set
724         ):
725             # Pinning policy "REQUIRE" uses threads as host should support SMT architecture
726             # Pinning policy "ISOLATE" uses cores as host should not support SMT architecture
727             # Pinning policy "PREFER" uses threads in case host supports SMT architecture
728 1             numa[
729                 "cores"
730                 if guest_epa_quota.get("cpu-thread-pinning-policy") == "ISOLATE"
731                 else "threads"
732             ] = max(vcpu_count, 1)
733 1             local_epa_vcpu_set = True
734
735 1         return numa, local_epa_vcpu_set
736
737 1     @staticmethod
738 1     def _process_epa_params(
739         target_flavor: Dict[str, Any],
740     ) -> Dict[str, Any]:
741         """[summary]
742
743         Args:
744             target_flavor (Dict[str, Any]): [description]
745
746         Returns:
747             Dict[str, Any]: [description]
748         """
749 1         extended = {}
750 1         numa = {}
751 1         numa_list = []
752
753 1         if target_flavor.get("guest-epa"):
754 1             guest_epa = target_flavor["guest-epa"]
755
756 1             numa_list, epa_vcpu_set = Ns._process_guest_epa_numa_params(
757                 guest_epa_quota=guest_epa
758             )
759
760 1             if guest_epa.get("mempage-size"):
761 1                 extended["mempage-size"] = guest_epa.get("mempage-size")
762
763 1             if guest_epa.get("cpu-pinning-policy"):
764 1                 extended["cpu-pinning-policy"] = guest_epa.get("cpu-pinning-policy")
765
766 1             if guest_epa.get("cpu-thread-pinning-policy"):
767 1                 extended["cpu-thread-pinning-policy"] = guest_epa.get(
768                     "cpu-thread-pinning-policy"
769                 )
770
771 1             if guest_epa.get("numa-node-policy"):
772 1                 if guest_epa.get("numa-node-policy").get("mem-policy"):
773 1                     extended["mem-policy"] = guest_epa.get("numa-node-policy").get(
774                         "mem-policy"
775                     )
776
777 1             tmp_numa, epa_vcpu_set = Ns._process_guest_epa_cpu_pinning_params(
778                 guest_epa_quota=guest_epa,
779                 vcpu_count=int(target_flavor.get("vcpu-count", 1)),
780                 epa_vcpu_set=epa_vcpu_set,
781             )
782 1             for numa in numa_list:
783 1                 numa.update(tmp_numa)
784
785 1             extended.update(
786                 Ns._process_guest_epa_quota_params(
787                     guest_epa_quota=guest_epa,
788                     epa_vcpu_set=epa_vcpu_set,
789                 )
790             )
791
792 1         if numa:
793 1             extended["numas"] = numa_list
794
795 1         return extended
796
797 1     @staticmethod
798 1     def _process_flavor_params(
799         target_flavor: Dict[str, Any],
800         indata: Dict[str, Any],
801         vim_info: Dict[str, Any],
802         target_record_id: str,
803         **kwargs: Dict[str, Any],
804     ) -> Dict[str, Any]:
805         """[summary]
806
807         Args:
808             target_flavor (Dict[str, Any]): [description]
809             indata (Dict[str, Any]): [description]
810             vim_info (Dict[str, Any]): [description]
811             target_record_id (str): [description]
812
813         Returns:
814             Dict[str, Any]: [description]
815         """
816 1         db = kwargs.get("db")
817 1         target_vdur = {}
818
819 1         flavor_data = {
820             "disk": int(target_flavor["storage-gb"]),
821             "ram": int(target_flavor["memory-mb"]),
822             "vcpus": int(target_flavor["vcpu-count"]),
823         }
824
825 1         for vnf in indata.get("vnf", []):
826 1             for vdur in vnf.get("vdur", []):
827 1                 if vdur.get("ns-flavor-id") == target_flavor.get("id"):
828 1                     target_vdur = vdur
829
830 1         if db and isinstance(indata.get("vnf"), list):
831 1             vnfd_id = indata.get("vnf")[0].get("vnfd-id")
832 1             vnfd = db.get_one("vnfds", {"_id": vnfd_id})
833             # check if there is persistent root disk
834 1             for vdu in vnfd.get("vdu", ()):
835 1                 if vdu["name"] == target_vdur.get("vdu-name"):
836 1                     for vsd in vnfd.get("virtual-storage-desc", ()):
837 1                         if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
838 1                             root_disk = vsd
839 1                             if (
840                                 root_disk.get("type-of-storage")
841                                 == "persistent-storage:persistent-storage"
842                             ):
843 1                                 flavor_data["disk"] = 0
844
845 1         for storage in target_vdur.get("virtual-storages", []):
846 1             if (
847                 storage.get("type-of-storage")
848                 == "etsi-nfv-descriptors:ephemeral-storage"
849             ):
850 1                 flavor_data["ephemeral"] = int(storage.get("size-of-storage", 0))
851 1             elif storage.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
852 1                 flavor_data["swap"] = int(storage.get("size-of-storage", 0))
853
854 1         extended = Ns._process_epa_params(target_flavor)
855 1         if extended:
856 1             flavor_data["extended"] = extended
857
858 1         extra_dict = {"find_params": {"flavor_data": flavor_data}}
859 1         flavor_data_name = flavor_data.copy()
860 1         flavor_data_name["name"] = target_flavor["name"]
861 1         extra_dict["params"] = {"flavor_data": flavor_data_name}
862
863 1         return extra_dict
864
865 1     @staticmethod
866 1     def _ip_profile_to_ro(
867         ip_profile: Dict[str, Any],
868     ) -> Dict[str, Any]:
869         """[summary]
870
871         Args:
872             ip_profile (Dict[str, Any]): [description]
873
874         Returns:
875             Dict[str, Any]: [description]
876         """
877 1         if not ip_profile:
878 1             return None
879
880 1         ro_ip_profile = {
881             "ip_version": "IPv4"
882             if "v4" in ip_profile.get("ip-version", "ipv4")
883             else "IPv6",
884             "subnet_address": ip_profile.get("subnet-address"),
885             "gateway_address": ip_profile.get("gateway-address"),
886             "dhcp_enabled": ip_profile.get("dhcp-params", {}).get("enabled", False),
887             "dhcp_start_address": ip_profile.get("dhcp-params", {}).get(
888                 "start-address", None
889             ),
890             "dhcp_count": ip_profile.get("dhcp-params", {}).get("count", None),
891         }
892
893 1         if ip_profile.get("dns-server"):
894 1             ro_ip_profile["dns_address"] = ";".join(
895                 [v["address"] for v in ip_profile["dns-server"] if v.get("address")]
896             )
897
898 1         if ip_profile.get("security-group"):
899 1             ro_ip_profile["security_group"] = ip_profile["security-group"]
900
901 1         return ro_ip_profile
902
903 1     @staticmethod
904 1     def _process_net_params(
905         target_vld: Dict[str, Any],
906         indata: Dict[str, Any],
907         vim_info: Dict[str, Any],
908         target_record_id: str,
909         **kwargs: Dict[str, Any],
910     ) -> Dict[str, Any]:
911         """Function to process network parameters.
912
913         Args:
914             target_vld (Dict[str, Any]): [description]
915             indata (Dict[str, Any]): [description]
916             vim_info (Dict[str, Any]): [description]
917             target_record_id (str): [description]
918
919         Returns:
920             Dict[str, Any]: [description]
921         """
922 1         extra_dict = {}
923
924 1         if vim_info.get("sdn"):
925             # vnf_preffix = "vnfrs:{}".format(vnfr_id)
926             # ns_preffix = "nsrs:{}".format(nsr_id)
927             # remove the ending ".sdn
928 1             vld_target_record_id, _, _ = target_record_id.rpartition(".")
929 1             extra_dict["params"] = {
930                 k: vim_info[k]
931                 for k in ("sdn-ports", "target_vim", "vlds", "type")
932                 if vim_info.get(k)
933             }
934
935             # TODO needed to add target_id in the dependency.
936 1             if vim_info.get("target_vim"):
937 1                 extra_dict["depends_on"] = [
938                     f"{vim_info.get('target_vim')} {vld_target_record_id}"
939                 ]
940
941 1             return extra_dict
942
943 1         if vim_info.get("vim_network_name"):
944 1             extra_dict["find_params"] = {
945                 "filter_dict": {
946                     "name": vim_info.get("vim_network_name"),
947                 },
948             }
949 1         elif vim_info.get("vim_network_id"):
950 1             extra_dict["find_params"] = {
951                 "filter_dict": {
952                     "id": vim_info.get("vim_network_id"),
953                 },
954             }
955 1         elif target_vld.get("mgmt-network") and not vim_info.get("provider_network"):
956 1             extra_dict["find_params"] = {
957                 "mgmt": True,
958                 "name": target_vld["id"],
959             }
960         else:
961             # create
962 1             extra_dict["params"] = {
963                 "net_name": (
964                     f"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
965                 ),
966                 "ip_profile": Ns._ip_profile_to_ro(vim_info.get("ip_profile")),
967                 "provider_network_profile": vim_info.get("provider_network"),
968             }
969
970 1             if not target_vld.get("underlay"):
971 1                 extra_dict["params"]["net_type"] = "bridge"
972             else:
973 1                 extra_dict["params"]["net_type"] = (
974                     "ptp" if target_vld.get("type") == "ELINE" else "data"
975                 )
976
977 1         return extra_dict
978
979 1     @staticmethod
980 1     def find_persistent_root_volumes(
981         vnfd: dict,
982         target_vdu: dict,
983         vdu_instantiation_volumes_list: list,
984         disk_list: list,
985     ) -> Dict[str, any]:
986         """Find the persistent root volumes and add them to the disk_list
987         by parsing the instantiation parameters.
988
989         Args:
990             vnfd    (dict):                                 VNF descriptor
991             target_vdu      (dict):                         processed VDU
992             vdu_instantiation_volumes_list  (list):         instantiation parameters for the each VDU as a list
993             disk_list   (list):                             to be filled up
994
995         Returns:
996             persistent_root_disk    (dict):                 Details of persistent root disk
997
998         """
999 1         persistent_root_disk = {}
1000         # There can be only one root disk, when we find it, it will return the result
1001
1002 1         for vdu, vsd in product(
1003             vnfd.get("vdu", ()), vnfd.get("virtual-storage-desc", ())
1004         ):
1005 1             if (
1006                 vdu["name"] == target_vdu["vdu-name"]
1007                 and vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]
1008             ):
1009 1                 root_disk = vsd
1010 1                 if (
1011                     root_disk.get("type-of-storage")
1012                     == "persistent-storage:persistent-storage"
1013                 ):
1014 1                     for vdu_volume in vdu_instantiation_volumes_list:
1015 1                         if (
1016                             vdu_volume["vim-volume-id"]
1017                             and root_disk["id"] == vdu_volume["name"]
1018                         ):
1019 1                             persistent_root_disk[vsd["id"]] = {
1020                                 "vim_volume_id": vdu_volume["vim-volume-id"],
1021                                 "image_id": vdu.get("sw-image-desc"),
1022                             }
1023
1024 1                             disk_list.append(persistent_root_disk[vsd["id"]])
1025
1026 1                             return persistent_root_disk
1027
1028                     else:
1029 1                         if root_disk.get("size-of-storage"):
1030 1                             persistent_root_disk[vsd["id"]] = {
1031                                 "image_id": vdu.get("sw-image-desc"),
1032                                 "size": root_disk.get("size-of-storage"),
1033                             }
1034
1035 1                             disk_list.append(persistent_root_disk[vsd["id"]])
1036
1037 1                             return persistent_root_disk
1038 1                 return persistent_root_disk
1039
1040 1     @staticmethod
1041 1     def find_persistent_volumes(
1042         persistent_root_disk: dict,
1043         target_vdu: dict,
1044         vdu_instantiation_volumes_list: list,
1045         disk_list: list,
1046     ) -> None:
1047         """Find the ordinary persistent volumes and add them to the disk_list
1048         by parsing the instantiation parameters.
1049
1050         Args:
1051             persistent_root_disk:   persistent root disk dictionary
1052             target_vdu: processed VDU
1053             vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1054             disk_list:  to be filled up
1055
1056         """
1057         # Find the ordinary volumes which are not added to the persistent_root_disk
1058 1         persistent_disk = {}
1059 1         for disk in target_vdu.get("virtual-storages", {}):
1060 1             if (
1061                 disk.get("type-of-storage") == "persistent-storage:persistent-storage"
1062                 and disk["id"] not in persistent_root_disk.keys()
1063             ):
1064 1                 for vdu_volume in vdu_instantiation_volumes_list:
1065 1                     if vdu_volume["vim-volume-id"] and disk["id"] == vdu_volume["name"]:
1066 1                         persistent_disk[disk["id"]] = {
1067                             "vim_volume_id": vdu_volume["vim-volume-id"],
1068                         }
1069 1                         disk_list.append(persistent_disk[disk["id"]])
1070
1071                 else:
1072 1                     if disk["id"] not in persistent_disk.keys():
1073 1                         persistent_disk[disk["id"]] = {
1074                             "size": disk.get("size-of-storage"),
1075                         }
1076 1                         disk_list.append(persistent_disk[disk["id"]])
1077
1078 1     @staticmethod
1079 1     def _sort_vdu_interfaces(target_vdu: dict) -> None:
1080         """Sort the interfaces according to position number.
1081
1082         Args:
1083             target_vdu  (dict):     Details of VDU to be created
1084
1085         """
1086         # If the position info is provided for all the interfaces, it will be sorted
1087         # according to position number ascendingly.
1088 1         sorted_interfaces = sorted(
1089             target_vdu["interfaces"],
1090             key=lambda x: (x.get("position") is None, x.get("position")),
1091         )
1092 1         target_vdu["interfaces"] = sorted_interfaces
1093
1094 1     @staticmethod
1095 1     def _partially_locate_vdu_interfaces(target_vdu: dict) -> None:
1096         """Only place the interfaces which has specific position.
1097
1098         Args:
1099             target_vdu  (dict):     Details of VDU to be created
1100
1101         """
1102         # If the position info is provided for some interfaces but not all of them, the interfaces
1103         # which has specific position numbers will be placed and others' positions will not be taken care.
1104 1         if any(
1105             i.get("position") + 1
1106             for i in target_vdu["interfaces"]
1107             if i.get("position") is not None
1108         ):
1109 1             n = len(target_vdu["interfaces"])
1110 1             sorted_interfaces = [-1] * n
1111 1             k, m = 0, 0
1112
1113 1             while k < n:
1114 1                 if target_vdu["interfaces"][k].get("position") is not None:
1115 1                     if any(i.get("position") == 0 for i in target_vdu["interfaces"]):
1116 1                         idx = target_vdu["interfaces"][k]["position"] + 1
1117                     else:
1118 1                         idx = target_vdu["interfaces"][k]["position"]
1119 1                     sorted_interfaces[idx - 1] = target_vdu["interfaces"][k]
1120 1                 k += 1
1121
1122 1             while m < n:
1123 1                 if target_vdu["interfaces"][m].get("position") is None:
1124 1                     idy = sorted_interfaces.index(-1)
1125 1                     sorted_interfaces[idy] = target_vdu["interfaces"][m]
1126 1                 m += 1
1127
1128 1             target_vdu["interfaces"] = sorted_interfaces
1129
1130 1     @staticmethod
1131 1     def _prepare_vdu_cloud_init(
1132         target_vdu: dict, vdu2cloud_init: dict, db: object, fs: object
1133     ) -> Dict:
1134         """Fill cloud_config dict with cloud init details.
1135
1136         Args:
1137             target_vdu  (dict):         Details of VDU to be created
1138             vdu2cloud_init  (dict):     Cloud init dict
1139             db  (object):               DB object
1140             fs  (object):               FS object
1141
1142         Returns:
1143             cloud_config (dict):        Cloud config details of VDU
1144
1145         """
1146         # cloud config
1147 1         cloud_config = {}
1148
1149 1         if target_vdu.get("cloud-init"):
1150 1             if target_vdu["cloud-init"] not in vdu2cloud_init:
1151 1                 vdu2cloud_init[target_vdu["cloud-init"]] = Ns._get_cloud_init(
1152                     db=db,
1153                     fs=fs,
1154                     location=target_vdu["cloud-init"],
1155                 )
1156
1157 1             cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
1158 1             cloud_config["user-data"] = Ns._parse_jinja2(
1159                 cloud_init_content=cloud_content_,
1160                 params=target_vdu.get("additionalParams"),
1161                 context=target_vdu["cloud-init"],
1162             )
1163
1164 1         if target_vdu.get("boot-data-drive"):
1165 1             cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
1166
1167 1         return cloud_config
1168
1169 1     @staticmethod
1170 1     def _check_vld_information_of_interfaces(
1171         interface: dict, ns_preffix: str, vnf_preffix: str
1172     ) -> Optional[str]:
1173         """Prepare the net_text by the virtual link information for vnf and ns level.
1174         Args:
1175             interface   (dict):         Interface details
1176             ns_preffix  (str):          Prefix of NS
1177             vnf_preffix (str):          Prefix of VNF
1178
1179         Returns:
1180             net_text    (str):          information of net
1181
1182         """
1183 1         net_text = ""
1184 1         if interface.get("ns-vld-id"):
1185 1             net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
1186 1         elif interface.get("vnf-vld-id"):
1187 1             net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
1188
1189 1         return net_text
1190
1191 1     @staticmethod
1192 1     def _prepare_interface_port_security(interface: dict) -> None:
1193         """
1194
1195         Args:
1196             interface   (dict):     Interface details
1197
1198         """
1199 1         if "port-security-enabled" in interface:
1200 1             interface["port_security"] = interface.pop("port-security-enabled")
1201
1202 1         if "port-security-disable-strategy" in interface:
1203 1             interface["port_security_disable_strategy"] = interface.pop(
1204                 "port-security-disable-strategy"
1205             )
1206
1207 1     @staticmethod
1208 1     def _create_net_item_of_interface(interface: dict, net_text: str) -> dict:
1209         """Prepare net item including name, port security, floating ip etc.
1210
1211         Args:
1212             interface   (dict):         Interface details
1213             net_text    (str):          information of net
1214
1215         Returns:
1216             net_item    (dict):         Dict including net details
1217
1218         """
1219
1220 1         net_item = {
1221             x: v
1222             for x, v in interface.items()
1223             if x
1224             in (
1225                 "name",
1226                 "vpci",
1227                 "port_security",
1228                 "port_security_disable_strategy",
1229                 "floating_ip",
1230             )
1231         }
1232 1         net_item["net_id"] = "TASK-" + net_text
1233 1         net_item["type"] = "virtual"
1234
1235 1         return net_item
1236
1237 1     @staticmethod
1238 1     def _prepare_type_of_interface(
1239         interface: dict, tasks_by_target_record_id: dict, net_text: str, net_item: dict
1240     ) -> None:
1241         """Fill the net item type by interface type such as SR-IOV, OM-MGMT, bridge etc.
1242
1243         Args:
1244             interface   (dict):                     Interface details
1245             tasks_by_target_record_id   (dict):     Task details
1246             net_text    (str):                      information of net
1247             net_item    (dict):                     Dict including net details
1248
1249         """
1250         # TODO mac_address: used for  SR-IOV ifaces #TODO for other types
1251         # TODO floating_ip: True/False (or it can be None)
1252
1253 1         if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1254             # Mark the net create task as type data
1255 1             if deep_get(
1256                 tasks_by_target_record_id,
1257                 net_text,
1258                 "extra_dict",
1259                 "params",
1260                 "net_type",
1261             ):
1262 1                 tasks_by_target_record_id[net_text]["extra_dict"]["params"][
1263                     "net_type"
1264                 ] = "data"
1265
1266 1             net_item["use"] = "data"
1267 1             net_item["model"] = interface["type"]
1268 1             net_item["type"] = interface["type"]
1269
1270 1         elif (
1271             interface.get("type") == "OM-MGMT"
1272             or interface.get("mgmt-interface")
1273             or interface.get("mgmt-vnf")
1274         ):
1275 1             net_item["use"] = "mgmt"
1276
1277         else:
1278             # If interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1279 1             net_item["use"] = "bridge"
1280 1             net_item["model"] = interface.get("type")
1281
1282 1     @staticmethod
1283 1     def _prepare_vdu_interfaces(
1284         target_vdu: dict,
1285         extra_dict: dict,
1286         ns_preffix: str,
1287         vnf_preffix: str,
1288         logger: object,
1289         tasks_by_target_record_id: dict,
1290         net_list: list,
1291     ) -> None:
1292         """Prepare the net_item and add net_list, add mgmt interface to extra_dict.
1293
1294         Args:
1295             target_vdu  (dict):                             VDU to be created
1296             extra_dict  (dict):                             Dictionary to be filled
1297             ns_preffix  (str):                              NS prefix as string
1298             vnf_preffix (str):                              VNF prefix as string
1299             logger  (object):                               Logger Object
1300             tasks_by_target_record_id  (dict):              Task details
1301             net_list    (list):                             Net list of VDU
1302         """
1303 1         for iface_index, interface in enumerate(target_vdu["interfaces"]):
1304 1             net_text = Ns._check_vld_information_of_interfaces(
1305                 interface, ns_preffix, vnf_preffix
1306             )
1307 1             if not net_text:
1308                 # Interface not connected to any vld
1309 1                 logger.error(
1310                     "Interface {} from vdu {} not connected to any vld".format(
1311                         iface_index, target_vdu["vdu-name"]
1312                     )
1313                 )
1314 1                 continue
1315
1316 1             extra_dict["depends_on"].append(net_text)
1317
1318 1             Ns._prepare_interface_port_security(interface)
1319
1320 1             net_item = Ns._create_net_item_of_interface(interface, net_text)
1321
1322 1             Ns._prepare_type_of_interface(
1323                 interface, tasks_by_target_record_id, net_text, net_item
1324             )
1325
1326 1             if interface.get("ip-address"):
1327 1                 net_item["ip_address"] = interface["ip-address"]
1328
1329 1             if interface.get("mac-address"):
1330 1                 net_item["mac_address"] = interface["mac-address"]
1331
1332 1             net_list.append(net_item)
1333
1334 1             if interface.get("mgmt-vnf"):
1335 0                 extra_dict["mgmt_vnf_interface"] = iface_index
1336 1             elif interface.get("mgmt-interface"):
1337 1                 extra_dict["mgmt_vdu_interface"] = iface_index
1338
1339 1     @staticmethod
1340 1     def _prepare_vdu_ssh_keys(
1341         target_vdu: dict, ro_nsr_public_key: dict, cloud_config: dict
1342     ) -> None:
1343         """Add ssh keys to cloud config.
1344
1345         Args:
1346            target_vdu  (dict):                 Details of VDU to be created
1347            ro_nsr_public_key   (dict):          RO NSR public Key
1348            cloud_config  (dict):               Cloud config details
1349
1350         """
1351 1         ssh_keys = []
1352
1353 1         if target_vdu.get("ssh-keys"):
1354 1             ssh_keys += target_vdu.get("ssh-keys")
1355
1356 1         if target_vdu.get("ssh-access-required"):
1357 1             ssh_keys.append(ro_nsr_public_key)
1358
1359 1         if ssh_keys:
1360 1             cloud_config["key-pairs"] = ssh_keys
1361
1362 1     @staticmethod
1363 1     def _select_persistent_root_disk(vsd: dict, vdu: dict) -> dict:
1364         """Selects the persistent root disk if exists.
1365         Args:
1366             vsd (dict):             Virtual storage descriptors in VNFD
1367             vdu (dict):             VNF descriptor
1368
1369         Returns:
1370             root_disk   (dict):     Selected persistent root disk
1371         """
1372 1         if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
1373 1             root_disk = vsd
1374 1             if root_disk.get(
1375                 "type-of-storage"
1376             ) == "persistent-storage:persistent-storage" and root_disk.get(
1377                 "size-of-storage"
1378             ):
1379 1                 return root_disk
1380
1381 1     @staticmethod
1382 1     def _add_persistent_root_disk_to_disk_list(
1383         vnfd: dict, target_vdu: dict, persistent_root_disk: dict, disk_list: list
1384     ) -> None:
1385         """Find the persistent root disk and add to disk list.
1386
1387         Args:
1388             vnfd  (dict):                           VNF descriptor
1389             target_vdu  (dict):                     Details of VDU to be created
1390             persistent_root_disk    (dict):         Details of persistent root disk
1391             disk_list   (list):                     Disks of VDU
1392
1393         """
1394 1         for vdu in vnfd.get("vdu", ()):
1395 1             if vdu["name"] == target_vdu["vdu-name"]:
1396 1                 for vsd in vnfd.get("virtual-storage-desc", ()):
1397 1                     root_disk = Ns._select_persistent_root_disk(vsd, vdu)
1398
1399 1                     if not root_disk:
1400 1                         continue
1401
1402 1                     persistent_root_disk[vsd["id"]] = {
1403                         "image_id": vdu.get("sw-image-desc"),
1404                         "size": root_disk["size-of-storage"],
1405                     }
1406
1407 1                     disk_list.append(persistent_root_disk[vsd["id"]])
1408 1                     break
1409
1410 1     @staticmethod
1411 1     def _add_persistent_ordinary_disks_to_disk_list(
1412         target_vdu: dict,
1413         persistent_root_disk: dict,
1414         persistent_ordinary_disk: dict,
1415         disk_list: list,
1416     ) -> None:
1417         """Fill the disk list by adding persistent ordinary disks.
1418
1419         Args:
1420             target_vdu  (dict):                     Details of VDU to be created
1421             persistent_root_disk    (dict):         Details of persistent root disk
1422             persistent_ordinary_disk    (dict):     Details of persistent ordinary disk
1423             disk_list   (list):                     Disks of VDU
1424
1425         """
1426 1         if target_vdu.get("virtual-storages"):
1427 1             for disk in target_vdu["virtual-storages"]:
1428 1                 if (
1429                     disk.get("type-of-storage")
1430                     == "persistent-storage:persistent-storage"
1431                     and disk["id"] not in persistent_root_disk.keys()
1432                 ):
1433 1                     persistent_ordinary_disk[disk["id"]] = {
1434                         "size": disk["size-of-storage"],
1435                     }
1436 1                     disk_list.append(persistent_ordinary_disk[disk["id"]])
1437
1438 1     @staticmethod
1439 1     def _prepare_vdu_affinity_group_list(
1440         target_vdu: dict, extra_dict: dict, ns_preffix: str
1441     ) -> List[Dict[str, any]]:
1442         """Process affinity group details to prepare affinity group list.
1443
1444         Args:
1445             target_vdu  (dict):     Details of VDU to be created
1446             extra_dict  (dict):     Dictionary to be filled
1447             ns_preffix  (str):      Prefix as string
1448
1449         Returns:
1450
1451             affinity_group_list (list):     Affinity group details
1452
1453         """
1454 1         affinity_group_list = []
1455
1456 1         if target_vdu.get("affinity-or-anti-affinity-group-id"):
1457 1             for affinity_group_id in target_vdu["affinity-or-anti-affinity-group-id"]:
1458 1                 affinity_group = {}
1459 1                 affinity_group_text = (
1460                     ns_preffix + ":affinity-or-anti-affinity-group." + affinity_group_id
1461                 )
1462
1463 1                 if not isinstance(extra_dict.get("depends_on"), list):
1464 1                     raise NsException("Invalid extra_dict format.")
1465
1466 1                 extra_dict["depends_on"].append(affinity_group_text)
1467 1                 affinity_group["affinity_group_id"] = "TASK-" + affinity_group_text
1468 1                 affinity_group_list.append(affinity_group)
1469
1470 1         return affinity_group_list
1471
1472 1     @staticmethod
1473 1     def _process_vdu_params(
1474         target_vdu: Dict[str, Any],
1475         indata: Dict[str, Any],
1476         vim_info: Dict[str, Any],
1477         target_record_id: str,
1478         **kwargs: Dict[str, Any],
1479     ) -> Dict[str, Any]:
1480         """Function to process VDU parameters.
1481
1482         Args:
1483             target_vdu (Dict[str, Any]): [description]
1484             indata (Dict[str, Any]): [description]
1485             vim_info (Dict[str, Any]): [description]
1486             target_record_id (str): [description]
1487
1488         Returns:
1489             Dict[str, Any]: [description]
1490         """
1491 1         vnfr_id = kwargs.get("vnfr_id")
1492 1         nsr_id = kwargs.get("nsr_id")
1493 1         vnfr = kwargs.get("vnfr")
1494 1         vdu2cloud_init = kwargs.get("vdu2cloud_init")
1495 1         tasks_by_target_record_id = kwargs.get("tasks_by_target_record_id")
1496 1         logger = kwargs.get("logger")
1497 1         db = kwargs.get("db")
1498 1         fs = kwargs.get("fs")
1499 1         ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1500
1501 1         vnf_preffix = "vnfrs:{}".format(vnfr_id)
1502 1         ns_preffix = "nsrs:{}".format(nsr_id)
1503 1         image_text = ns_preffix + ":image." + target_vdu["ns-image-id"]
1504 1         flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"]
1505 1         extra_dict = {"depends_on": [image_text, flavor_text]}
1506 1         net_list = []
1507
1508 1         persistent_root_disk = {}
1509 1         persistent_ordinary_disk = {}
1510 1         vdu_instantiation_volumes_list = []
1511 1         disk_list = []
1512 1         vnfd_id = vnfr["vnfd-id"]
1513 1         vnfd = db.get_one("vnfds", {"_id": vnfd_id})
1514
1515         # If the position info is provided for all the interfaces, it will be sorted
1516         # according to position number ascendingly.
1517 1         if all(
1518             True if i.get("position") is not None else False
1519             for i in target_vdu["interfaces"]
1520         ):
1521 1             Ns._sort_vdu_interfaces(target_vdu)
1522
1523         # If the position info is provided for some interfaces but not all of them, the interfaces
1524         # which has specific position numbers will be placed and others' positions will not be taken care.
1525         else:
1526 1             Ns._partially_locate_vdu_interfaces(target_vdu)
1527
1528         # If the position info is not provided for the interfaces, interfaces will be attached
1529         # according to the order in the VNFD.
1530 1         Ns._prepare_vdu_interfaces(
1531             target_vdu,
1532             extra_dict,
1533             ns_preffix,
1534             vnf_preffix,
1535             logger,
1536             tasks_by_target_record_id,
1537             net_list,
1538         )
1539
1540         # cloud config
1541 1         cloud_config = Ns._prepare_vdu_cloud_init(target_vdu, vdu2cloud_init, db, fs)
1542
1543         # Prepare VDU ssh keys
1544 1         Ns._prepare_vdu_ssh_keys(target_vdu, ro_nsr_public_key, cloud_config)
1545
1546 1         if target_vdu.get("additionalParams"):
1547 1             vdu_instantiation_volumes_list = (
1548                 target_vdu.get("additionalParams").get("OSM").get("vdu_volumes")
1549             )
1550
1551 1         if vdu_instantiation_volumes_list:
1552             # Find the root volumes and add to the disk_list
1553 1             persistent_root_disk = Ns.find_persistent_root_volumes(
1554                 vnfd, target_vdu, vdu_instantiation_volumes_list, disk_list
1555             )
1556
1557             # Find the ordinary volumes which are not added to the persistent_root_disk
1558             # and put them to the disk list
1559 1             Ns.find_persistent_volumes(
1560                 persistent_root_disk,
1561                 target_vdu,
1562                 vdu_instantiation_volumes_list,
1563                 disk_list,
1564             )
1565
1566         else:
1567             # Vdu_instantiation_volumes_list is empty
1568             # First get add the persistent root disks to disk_list
1569 1             Ns._add_persistent_root_disk_to_disk_list(
1570                 vnfd, target_vdu, persistent_root_disk, disk_list
1571             )
1572             # Add the persistent non-root disks to disk_list
1573 1             Ns._add_persistent_ordinary_disks_to_disk_list(
1574                 target_vdu, persistent_root_disk, persistent_ordinary_disk, disk_list
1575             )
1576
1577 1         affinity_group_list = Ns._prepare_vdu_affinity_group_list(
1578             target_vdu, extra_dict, ns_preffix
1579         )
1580
1581 1         extra_dict["params"] = {
1582             "name": "{}-{}-{}-{}".format(
1583                 indata["name"][:16],
1584                 vnfr["member-vnf-index-ref"][:16],
1585                 target_vdu["vdu-name"][:32],
1586                 target_vdu.get("count-index") or 0,
1587             ),
1588             "description": target_vdu["vdu-name"],
1589             "start": True,
1590             "image_id": "TASK-" + image_text,
1591             "flavor_id": "TASK-" + flavor_text,
1592             "affinity_group_list": affinity_group_list,
1593             "net_list": net_list,
1594             "cloud_config": cloud_config or None,
1595             "disk_list": disk_list,
1596             "availability_zone_index": None,  # TODO
1597             "availability_zone_list": None,  # TODO
1598         }
1599
1600 1         return extra_dict
1601
1602 1     @staticmethod
1603 1     def _process_affinity_group_params(
1604         target_affinity_group: Dict[str, Any],
1605         indata: Dict[str, Any],
1606         vim_info: Dict[str, Any],
1607         target_record_id: str,
1608         **kwargs: Dict[str, Any],
1609     ) -> Dict[str, Any]:
1610         """Get affinity or anti-affinity group parameters.
1611
1612         Args:
1613             target_affinity_group (Dict[str, Any]): [description]
1614             indata (Dict[str, Any]): [description]
1615             vim_info (Dict[str, Any]): [description]
1616             target_record_id (str): [description]
1617
1618         Returns:
1619             Dict[str, Any]: [description]
1620         """
1621
1622 0         extra_dict = {}
1623 0         affinity_group_data = {
1624             "name": target_affinity_group["name"],
1625             "type": target_affinity_group["type"],
1626             "scope": target_affinity_group["scope"],
1627         }
1628
1629 0         if target_affinity_group.get("vim-affinity-group-id"):
1630 0             affinity_group_data["vim-affinity-group-id"] = target_affinity_group[
1631                 "vim-affinity-group-id"
1632             ]
1633
1634 0         extra_dict["params"] = {
1635             "affinity_group_data": affinity_group_data,
1636         }
1637
1638 0         return extra_dict
1639
1640 1     @staticmethod
1641 1     def _process_recreate_vdu_params(
1642         existing_vdu: Dict[str, Any],
1643         db_nsr: Dict[str, Any],
1644         vim_info: Dict[str, Any],
1645         target_record_id: str,
1646         target_id: str,
1647         **kwargs: Dict[str, Any],
1648     ) -> Dict[str, Any]:
1649         """Function to process VDU parameters to recreate.
1650
1651         Args:
1652             existing_vdu (Dict[str, Any]): [description]
1653             db_nsr (Dict[str, Any]): [description]
1654             vim_info (Dict[str, Any]): [description]
1655             target_record_id (str): [description]
1656             target_id (str): [description]
1657
1658         Returns:
1659             Dict[str, Any]: [description]
1660         """
1661 0         vnfr = kwargs.get("vnfr")
1662 0         vdu2cloud_init = kwargs.get("vdu2cloud_init")
1663         # logger = kwargs.get("logger")
1664 0         db = kwargs.get("db")
1665 0         fs = kwargs.get("fs")
1666 0         ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1667
1668 0         extra_dict = {}
1669 0         net_list = []
1670
1671 0         vim_details = {}
1672 0         vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
1673 0         if vim_details_text:
1674 0             vim_details = yaml.safe_load(f"{vim_details_text}")
1675
1676 0         for iface_index, interface in enumerate(existing_vdu["interfaces"]):
1677 0             if "port-security-enabled" in interface:
1678 0                 interface["port_security"] = interface.pop("port-security-enabled")
1679
1680 0             if "port-security-disable-strategy" in interface:
1681 0                 interface["port_security_disable_strategy"] = interface.pop(
1682                     "port-security-disable-strategy"
1683                 )
1684
1685 0             net_item = {
1686                 x: v
1687                 for x, v in interface.items()
1688                 if x
1689                 in (
1690                     "name",
1691                     "vpci",
1692                     "port_security",
1693                     "port_security_disable_strategy",
1694                     "floating_ip",
1695                 )
1696             }
1697 0             existing_ifaces = existing_vdu["vim_info"][target_id].get(
1698                 "interfaces_backup", []
1699             )
1700 0             net_id = next(
1701                 (
1702                     i["vim_net_id"]
1703                     for i in existing_ifaces
1704                     if i["ip_address"] == interface["ip-address"]
1705                 ),
1706                 None,
1707             )
1708
1709 0             net_item["net_id"] = net_id
1710 0             net_item["type"] = "virtual"
1711
1712             # TODO mac_address: used for  SR-IOV ifaces #TODO for other types
1713             # TODO floating_ip: True/False (or it can be None)
1714 0             if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1715 0                 net_item["use"] = "data"
1716 0                 net_item["model"] = interface["type"]
1717 0                 net_item["type"] = interface["type"]
1718 0             elif (
1719                 interface.get("type") == "OM-MGMT"
1720                 or interface.get("mgmt-interface")
1721                 or interface.get("mgmt-vnf")
1722             ):
1723 0                 net_item["use"] = "mgmt"
1724             else:
1725                 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1726 0                 net_item["use"] = "bridge"
1727 0                 net_item["model"] = interface.get("type")
1728
1729 0             if interface.get("ip-address"):
1730 0                 net_item["ip_address"] = interface["ip-address"]
1731
1732 0             if interface.get("mac-address"):
1733 0                 net_item["mac_address"] = interface["mac-address"]
1734
1735 0             net_list.append(net_item)
1736
1737 0             if interface.get("mgmt-vnf"):
1738 0                 extra_dict["mgmt_vnf_interface"] = iface_index
1739 0             elif interface.get("mgmt-interface"):
1740 0                 extra_dict["mgmt_vdu_interface"] = iface_index
1741
1742         # cloud config
1743 0         cloud_config = {}
1744
1745 0         if existing_vdu.get("cloud-init"):
1746 0             if existing_vdu["cloud-init"] not in vdu2cloud_init:
1747 0                 vdu2cloud_init[existing_vdu["cloud-init"]] = Ns._get_cloud_init(
1748                     db=db,
1749                     fs=fs,
1750                     location=existing_vdu["cloud-init"],
1751                 )
1752
1753 0             cloud_content_ = vdu2cloud_init[existing_vdu["cloud-init"]]
1754 0             cloud_config["user-data"] = Ns._parse_jinja2(
1755                 cloud_init_content=cloud_content_,
1756                 params=existing_vdu.get("additionalParams"),
1757                 context=existing_vdu["cloud-init"],
1758             )
1759
1760 0         if existing_vdu.get("boot-data-drive"):
1761 0             cloud_config["boot-data-drive"] = existing_vdu.get("boot-data-drive")
1762
1763 0         ssh_keys = []
1764
1765 0         if existing_vdu.get("ssh-keys"):
1766 0             ssh_keys += existing_vdu.get("ssh-keys")
1767
1768 0         if existing_vdu.get("ssh-access-required"):
1769 0             ssh_keys.append(ro_nsr_public_key)
1770
1771 0         if ssh_keys:
1772 0             cloud_config["key-pairs"] = ssh_keys
1773
1774 0         disk_list = []
1775 0         for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
1776 0             disk_list.append({"vim_id": vol_id["id"]})
1777
1778 0         affinity_group_list = []
1779
1780 0         if existing_vdu.get("affinity-or-anti-affinity-group-id"):
1781 0             affinity_group = {}
1782 0             for affinity_group_id in existing_vdu["affinity-or-anti-affinity-group-id"]:
1783 0                 for group in db_nsr.get("affinity-or-anti-affinity-group"):
1784 0                     if (
1785                         group["id"] == affinity_group_id
1786                         and group["vim_info"][target_id].get("vim_id", None) is not None
1787                     ):
1788 0                         affinity_group["affinity_group_id"] = group["vim_info"][
1789                             target_id
1790                         ].get("vim_id", None)
1791 0                         affinity_group_list.append(affinity_group)
1792
1793 0         extra_dict["params"] = {
1794             "name": "{}-{}-{}-{}".format(
1795                 db_nsr["name"][:16],
1796                 vnfr["member-vnf-index-ref"][:16],
1797                 existing_vdu["vdu-name"][:32],
1798                 existing_vdu.get("count-index") or 0,
1799             ),
1800             "description": existing_vdu["vdu-name"],
1801             "start": True,
1802             "image_id": vim_details["image"]["id"],
1803             "flavor_id": vim_details["flavor"]["id"],
1804             "affinity_group_list": affinity_group_list,
1805             "net_list": net_list,
1806             "cloud_config": cloud_config or None,
1807             "disk_list": disk_list,
1808             "availability_zone_index": None,  # TODO
1809             "availability_zone_list": None,  # TODO
1810         }
1811
1812 0         return extra_dict
1813
1814 1     def calculate_diff_items(
1815         self,
1816         indata,
1817         db_nsr,
1818         db_ro_nsr,
1819         db_nsr_update,
1820         item,
1821         tasks_by_target_record_id,
1822         action_id,
1823         nsr_id,
1824         task_index,
1825         vnfr_id=None,
1826         vnfr=None,
1827     ):
1828         """Function that returns the incremental changes (creation, deletion)
1829         related to a specific item `item` to be done. This function should be
1830         called for NS instantiation, NS termination, NS update to add a new VNF
1831         or a new VLD, remove a VNF or VLD, etc.
1832         Item can be `net`, `flavor`, `image` or `vdu`.
1833         It takes a list of target items from indata (which came from the REST API)
1834         and compares with the existing items from db_ro_nsr, identifying the
1835         incremental changes to be done. During the comparison, it calls the method
1836         `process_params` (which was passed as parameter, and is particular for each
1837         `item`)
1838
1839         Args:
1840             indata (Dict[str, Any]): deployment info
1841             db_nsr: NSR record from DB
1842             db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1843             db_nsr_update (Dict[str, Any]): NSR info to update in DB
1844             item (str): element to process (net, vdu...)
1845             tasks_by_target_record_id (Dict[str, Any]):
1846                 [<target_record_id>, <task>]
1847             action_id (str): action id
1848             nsr_id (str): NSR id
1849             task_index (number): task index to add to task name
1850             vnfr_id (str): VNFR id
1851             vnfr (Dict[str, Any]): VNFR info
1852
1853         Returns:
1854             List: list with the incremental changes (deletes, creates) for each item
1855             number: current task index
1856         """
1857
1858 0         diff_items = []
1859 0         db_path = ""
1860 0         db_record = ""
1861 0         target_list = []
1862 0         existing_list = []
1863 0         process_params = None
1864 0         vdu2cloud_init = indata.get("cloud_init_content") or {}
1865 0         ro_nsr_public_key = db_ro_nsr["public_key"]
1866
1867         # According to the type of item, the path, the target_list,
1868         # the existing_list and the method to process params are set
1869 0         db_path = self.db_path_map[item]
1870 0         process_params = self.process_params_function_map[item]
1871 0         if item in ("net", "vdu"):
1872             # This case is specific for the NS VLD (not applied to VDU)
1873 0             if vnfr is None:
1874 0                 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1875 0                 target_list = indata.get("ns", []).get(db_path, [])
1876 0                 existing_list = db_nsr.get(db_path, [])
1877             # This case is common for VNF VLDs and VNF VDUs
1878             else:
1879 0                 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
1880 0                 target_vnf = next(
1881                     (vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id),
1882                     None,
1883                 )
1884 0                 target_list = target_vnf.get(db_path, []) if target_vnf else []
1885 0                 existing_list = vnfr.get(db_path, [])
1886 0         elif item in ("image", "flavor", "affinity-or-anti-affinity-group"):
1887 0             db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1888 0             target_list = indata.get(item, [])
1889 0             existing_list = db_nsr.get(item, [])
1890         else:
1891 0             raise NsException("Item not supported: {}", item)
1892
1893         # ensure all the target_list elements has an "id". If not assign the index as id
1894 0         if target_list is None:
1895 0             target_list = []
1896 0         for target_index, tl in enumerate(target_list):
1897 0             if tl and not tl.get("id"):
1898 0                 tl["id"] = str(target_index)
1899
1900         # step 1 items (networks,vdus,...) to be deleted/updated
1901 0         for item_index, existing_item in enumerate(existing_list):
1902 0             target_item = next(
1903                 (t for t in target_list if t["id"] == existing_item["id"]),
1904                 None,
1905             )
1906
1907 0             for target_vim, existing_viminfo in existing_item.get(
1908                 "vim_info", {}
1909             ).items():
1910 0                 if existing_viminfo is None:
1911 0                     continue
1912
1913 0                 if target_item:
1914 0                     target_viminfo = target_item.get("vim_info", {}).get(target_vim)
1915                 else:
1916 0                     target_viminfo = None
1917
1918 0                 if target_viminfo is None:
1919                     # must be deleted
1920 0                     self._assign_vim(target_vim)
1921 0                     target_record_id = "{}.{}".format(db_record, existing_item["id"])
1922 0                     item_ = item
1923
1924 0                     if target_vim.startswith("sdn") or target_vim.startswith("wim"):
1925                         # item must be sdn-net instead of net if target_vim is a sdn
1926 0                         item_ = "sdn_net"
1927 0                         target_record_id += ".sdn"
1928
1929 0                     deployment_info = {
1930                         "action_id": action_id,
1931                         "nsr_id": nsr_id,
1932                         "task_index": task_index,
1933                     }
1934
1935 0                     diff_items.append(
1936                         {
1937                             "deployment_info": deployment_info,
1938                             "target_id": target_vim,
1939                             "item": item_,
1940                             "action": "DELETE",
1941                             "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1942                             "target_record_id": target_record_id,
1943                         }
1944                     )
1945 0                     task_index += 1
1946
1947         # step 2 items (networks,vdus,...) to be created
1948 0         for target_item in target_list:
1949 0             item_index = -1
1950
1951 0             for item_index, existing_item in enumerate(existing_list):
1952 0                 if existing_item["id"] == target_item["id"]:
1953 0                     break
1954             else:
1955 0                 item_index += 1
1956 0                 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1957 0                 existing_list.append(target_item)
1958 0                 existing_item = None
1959
1960 0             for target_vim, target_viminfo in target_item.get("vim_info", {}).items():
1961 0                 existing_viminfo = None
1962
1963 0                 if existing_item:
1964 0                     existing_viminfo = existing_item.get("vim_info", {}).get(target_vim)
1965
1966 0                 if existing_viminfo is not None:
1967 0                     continue
1968
1969 0                 target_record_id = "{}.{}".format(db_record, target_item["id"])
1970 0                 item_ = item
1971
1972 0                 if target_vim.startswith("sdn") or target_vim.startswith("wim"):
1973                     # item must be sdn-net instead of net if target_vim is a sdn
1974 0                     item_ = "sdn_net"
1975 0                     target_record_id += ".sdn"
1976
1977 0                 kwargs = {}
1978 0                 self.logger.warning(
1979                     "ns.calculate_diff_items target_item={}".format(target_item)
1980                 )
1981 0                 if process_params == Ns._process_flavor_params:
1982 0                     kwargs.update(
1983                         {
1984                             "db": self.db,
1985                         }
1986                     )
1987 0                     self.logger.warning(
1988                         "calculate_diff_items for flavor kwargs={}".format(kwargs)
1989                     )
1990
1991 0                 if process_params == Ns._process_vdu_params:
1992 0                     self.logger.warning(
1993                         "calculate_diff_items self.fs={}".format(self.fs)
1994                     )
1995 0                     kwargs.update(
1996                         {
1997                             "vnfr_id": vnfr_id,
1998                             "nsr_id": nsr_id,
1999                             "vnfr": vnfr,
2000                             "vdu2cloud_init": vdu2cloud_init,
2001                             "tasks_by_target_record_id": tasks_by_target_record_id,
2002                             "logger": self.logger,
2003                             "db": self.db,
2004                             "fs": self.fs,
2005                             "ro_nsr_public_key": ro_nsr_public_key,
2006                         }
2007                     )
2008 0                     self.logger.warning("calculate_diff_items kwargs={}".format(kwargs))
2009
2010 0                 extra_dict = process_params(
2011                     target_item,
2012                     indata,
2013                     target_viminfo,
2014                     target_record_id,
2015                     **kwargs,
2016                 )
2017 0                 self._assign_vim(target_vim)
2018
2019 0                 deployment_info = {
2020                     "action_id": action_id,
2021                     "nsr_id": nsr_id,
2022                     "task_index": task_index,
2023                 }
2024
2025 0                 new_item = {
2026                     "deployment_info": deployment_info,
2027                     "target_id": target_vim,
2028                     "item": item_,
2029                     "action": "CREATE",
2030                     "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
2031                     "target_record_id": target_record_id,
2032                     "extra_dict": extra_dict,
2033                     "common_id": target_item.get("common_id", None),
2034                 }
2035 0                 diff_items.append(new_item)
2036 0                 tasks_by_target_record_id[target_record_id] = new_item
2037 0                 task_index += 1
2038
2039 0                 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
2040
2041 0         return diff_items, task_index
2042
2043 1     def calculate_all_differences_to_deploy(
2044         self,
2045         indata,
2046         nsr_id,
2047         db_nsr,
2048         db_vnfrs,
2049         db_ro_nsr,
2050         db_nsr_update,
2051         db_vnfrs_update,
2052         action_id,
2053         tasks_by_target_record_id,
2054     ):
2055         """This method calculates the ordered list of items (`changes_list`)
2056         to be created and deleted.
2057
2058         Args:
2059             indata (Dict[str, Any]): deployment info
2060             nsr_id (str): NSR id
2061             db_nsr: NSR record from DB
2062             db_vnfrs: VNFRS record from DB
2063             db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2064             db_nsr_update (Dict[str, Any]): NSR info to update in DB
2065             db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
2066             action_id (str): action id
2067             tasks_by_target_record_id (Dict[str, Any]):
2068                 [<target_record_id>, <task>]
2069
2070         Returns:
2071             List: ordered list of items to be created and deleted.
2072         """
2073
2074 0         task_index = 0
2075         # set list with diffs:
2076 0         changes_list = []
2077
2078         # NS vld, image and flavor
2079 0         for item in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
2080 0             self.logger.debug("process NS={} {}".format(nsr_id, item))
2081 0             diff_items, task_index = self.calculate_diff_items(
2082                 indata=indata,
2083                 db_nsr=db_nsr,
2084                 db_ro_nsr=db_ro_nsr,
2085                 db_nsr_update=db_nsr_update,
2086                 item=item,
2087                 tasks_by_target_record_id=tasks_by_target_record_id,
2088                 action_id=action_id,
2089                 nsr_id=nsr_id,
2090                 task_index=task_index,
2091                 vnfr_id=None,
2092             )
2093 0             changes_list += diff_items
2094
2095         # VNF vlds and vdus
2096 0         for vnfr_id, vnfr in db_vnfrs.items():
2097             # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
2098 0             for item in ["net", "vdu"]:
2099 0                 self.logger.debug("process VNF={} {}".format(vnfr_id, item))
2100 0                 diff_items, task_index = self.calculate_diff_items(
2101                     indata=indata,
2102                     db_nsr=db_nsr,
2103                     db_ro_nsr=db_ro_nsr,
2104                     db_nsr_update=db_vnfrs_update[vnfr["_id"]],
2105                     item=item,
2106                     tasks_by_target_record_id=tasks_by_target_record_id,
2107                     action_id=action_id,
2108                     nsr_id=nsr_id,
2109                     task_index=task_index,
2110                     vnfr_id=vnfr_id,
2111                     vnfr=vnfr,
2112                 )
2113 0                 changes_list += diff_items
2114
2115 0         return changes_list
2116
2117 1     def define_all_tasks(
2118         self,
2119         changes_list,
2120         db_new_tasks,
2121         tasks_by_target_record_id,
2122     ):
2123         """Function to create all the task structures obtanied from
2124         the method calculate_all_differences_to_deploy
2125
2126         Args:
2127             changes_list (List): ordered list of items to be created or deleted
2128             db_new_tasks (List): tasks list to be created
2129             action_id (str): action id
2130             tasks_by_target_record_id (Dict[str, Any]):
2131                 [<target_record_id>, <task>]
2132
2133         """
2134
2135 0         for change in changes_list:
2136 0             task = Ns._create_task(
2137                 deployment_info=change["deployment_info"],
2138                 target_id=change["target_id"],
2139                 item=change["item"],
2140                 action=change["action"],
2141                 target_record=change["target_record"],
2142                 target_record_id=change["target_record_id"],
2143                 extra_dict=change.get("extra_dict", None),
2144             )
2145
2146 0             self.logger.warning("ns.define_all_tasks task={}".format(task))
2147 0             tasks_by_target_record_id[change["target_record_id"]] = task
2148 0             db_new_tasks.append(task)
2149
2150 0             if change.get("common_id"):
2151 0                 task["common_id"] = change["common_id"]
2152
2153 1     def upload_all_tasks(
2154         self,
2155         db_new_tasks,
2156         now,
2157     ):
2158         """Function to save all tasks in the common DB
2159
2160         Args:
2161             db_new_tasks (List): tasks list to be created
2162             now (time): current time
2163
2164         """
2165
2166 0         nb_ro_tasks = 0  # for logging
2167
2168 0         for db_task in db_new_tasks:
2169 0             target_id = db_task.pop("target_id")
2170 0             common_id = db_task.get("common_id")
2171
2172             # Do not chek tasks with vim_status DELETED
2173             # because in manual heealing there are two tasks for the same vdur:
2174             #   one with vim_status deleted and the other one with the actual VM status.
2175
2176 0             if common_id:
2177 0                 if self.db.set_one(
2178                     "ro_tasks",
2179                     q_filter={
2180                         "target_id": target_id,
2181                         "tasks.common_id": common_id,
2182                         "vim_info.vim_status.ne": "DELETED",
2183                     },
2184                     update_dict={"to_check_at": now, "modified_at": now},
2185                     push={"tasks": db_task},
2186                     fail_on_empty=False,
2187                 ):
2188 0                     continue
2189
2190 0             if not self.db.set_one(
2191                 "ro_tasks",
2192                 q_filter={
2193                     "target_id": target_id,
2194                     "tasks.target_record": db_task["target_record"],
2195                     "vim_info.vim_status.ne": "DELETED",
2196                 },
2197                 update_dict={"to_check_at": now, "modified_at": now},
2198                 push={"tasks": db_task},
2199                 fail_on_empty=False,
2200             ):
2201                 # Create a ro_task
2202 0                 self.logger.debug("Updating database, Creating ro_tasks")
2203 0                 db_ro_task = Ns._create_ro_task(target_id, db_task)
2204 0                 nb_ro_tasks += 1
2205 0                 self.db.create("ro_tasks", db_ro_task)
2206
2207 0         self.logger.debug(
2208             "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2209                 nb_ro_tasks, len(db_new_tasks), db_new_tasks
2210             )
2211         )
2212
2213 1     def upload_recreate_tasks(
2214         self,
2215         db_new_tasks,
2216         now,
2217     ):
2218         """Function to save recreate tasks in the common DB
2219
2220         Args:
2221             db_new_tasks (List): tasks list to be created
2222             now (time): current time
2223
2224         """
2225
2226 0         nb_ro_tasks = 0  # for logging
2227
2228 0         for db_task in db_new_tasks:
2229 0             target_id = db_task.pop("target_id")
2230 0             self.logger.warning("target_id={} db_task={}".format(target_id, db_task))
2231
2232 0             action = db_task.get("action", None)
2233
2234             # Create a ro_task
2235 0             self.logger.debug("Updating database, Creating ro_tasks")
2236 0             db_ro_task = Ns._create_ro_task(target_id, db_task)
2237
2238             # If DELETE task: the associated created items should be removed
2239             # (except persistent volumes):
2240 0             if action == "DELETE":
2241 0                 db_ro_task["vim_info"]["created"] = True
2242 0                 db_ro_task["vim_info"]["created_items"] = db_task.get(
2243                     "created_items", {}
2244                 )
2245 0                 db_ro_task["vim_info"]["volumes_to_hold"] = db_task.get(
2246                     "volumes_to_hold", []
2247                 )
2248 0                 db_ro_task["vim_info"]["vim_id"] = db_task.get("vim_id", None)
2249
2250 0             nb_ro_tasks += 1
2251 0             self.logger.warning("upload_all_tasks db_ro_task={}".format(db_ro_task))
2252 0             self.db.create("ro_tasks", db_ro_task)
2253
2254 0         self.logger.debug(
2255             "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2256                 nb_ro_tasks, len(db_new_tasks), db_new_tasks
2257             )
2258         )
2259
2260 1     def _prepare_created_items_for_healing(
2261         self,
2262         nsr_id,
2263         target_record,
2264     ):
2265 0         created_items = {}
2266         # Get created_items from ro_task
2267 0         ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2268 0         for ro_task in ro_tasks:
2269 0             for task in ro_task["tasks"]:
2270 0                 if (
2271                     task["target_record"] == target_record
2272                     and task["action"] == "CREATE"
2273                     and ro_task["vim_info"]["created_items"]
2274                 ):
2275 0                     created_items = ro_task["vim_info"]["created_items"]
2276 0                     break
2277
2278 0         return created_items
2279
2280 1     def _prepare_persistent_volumes_for_healing(
2281         self,
2282         target_id,
2283         existing_vdu,
2284     ):
2285         # The associated volumes of the VM shouldn't be removed
2286 0         volumes_list = []
2287 0         vim_details = {}
2288 0         vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
2289 0         if vim_details_text:
2290 0             vim_details = yaml.safe_load(f"{vim_details_text}")
2291
2292 0             for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
2293 0                 volumes_list.append(vol_id["id"])
2294
2295 0         return volumes_list
2296
2297 1     def prepare_changes_to_recreate(
2298         self,
2299         indata,
2300         nsr_id,
2301         db_nsr,
2302         db_vnfrs,
2303         db_ro_nsr,
2304         action_id,
2305         tasks_by_target_record_id,
2306     ):
2307         """This method will obtain an ordered list of items (`changes_list`)
2308         to be created and deleted to meet the recreate request.
2309         """
2310
2311 0         self.logger.debug(
2312             "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id, indata)
2313         )
2314
2315 0         task_index = 0
2316         # set list with diffs:
2317 0         changes_list = []
2318 0         db_path = self.db_path_map["vdu"]
2319 0         target_list = indata.get("healVnfData", {})
2320 0         vdu2cloud_init = indata.get("cloud_init_content") or {}
2321 0         ro_nsr_public_key = db_ro_nsr["public_key"]
2322
2323         # Check each VNF of the target
2324 0         for target_vnf in target_list:
2325             # Find this VNF in the list from DB, raise exception if vnfInstanceId is not found
2326 0             vnfr_id = target_vnf["vnfInstanceId"]
2327 0             existing_vnf = db_vnfrs.get(vnfr_id)
2328 0             db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
2329             # vim_account_id = existing_vnf.get("vim-account-id", "")
2330
2331 0             target_vdus = target_vnf.get("additionalParams", {}).get("vdu", [])
2332             # Check each VDU of this VNF
2333 0             if not target_vdus:
2334                 # Create target_vdu_list from DB, if VDUs are not specified
2335 0                 target_vdus = []
2336 0                 for existing_vdu in existing_vnf.get("vdur"):
2337 0                     vdu_name = existing_vdu.get("vdu-name", None)
2338 0                     vdu_index = existing_vdu.get("count-index", 0)
2339 0                     vdu_to_be_healed = {"vdu-id": vdu_name, "count-index": vdu_index}
2340 0                     target_vdus.append(vdu_to_be_healed)
2341 0             for target_vdu in target_vdus:
2342 0                 vdu_name = target_vdu.get("vdu-id", None)
2343                 # For multi instance VDU count-index is mandatory
2344                 # For single session VDU count-indes is 0
2345 0                 count_index = target_vdu.get("count-index", 0)
2346 0                 item_index = 0
2347 0                 existing_instance = None
2348 0                 for instance in existing_vnf.get("vdur", None):
2349 0                     if (
2350                         instance["vdu-name"] == vdu_name
2351                         and instance["count-index"] == count_index
2352                     ):
2353 0                         existing_instance = instance
2354 0                         break
2355                     else:
2356 0                         item_index += 1
2357
2358 0                 target_record_id = "{}.{}".format(db_record, existing_instance["id"])
2359
2360                 # The target VIM is the one already existing in DB to recreate
2361 0                 for target_vim, target_viminfo in existing_instance.get(
2362                     "vim_info", {}
2363                 ).items():
2364                     # step 1 vdu to be deleted
2365 0                     self._assign_vim(target_vim)
2366 0                     deployment_info = {
2367                         "action_id": action_id,
2368                         "nsr_id": nsr_id,
2369                         "task_index": task_index,
2370                     }
2371
2372 0                     target_record = f"{db_record}.{item_index}.vim_info.{target_vim}"
2373 0                     created_items = self._prepare_created_items_for_healing(
2374                         nsr_id, target_record
2375                     )
2376
2377 0                     volumes_to_hold = self._prepare_persistent_volumes_for_healing(
2378                         target_vim, existing_instance
2379                     )
2380
2381                     # Specific extra params for recreate tasks:
2382 0                     extra_dict = {
2383                         "created_items": created_items,
2384                         "vim_id": existing_instance["vim-id"],
2385                         "volumes_to_hold": volumes_to_hold,
2386                     }
2387
2388 0                     changes_list.append(
2389                         {
2390                             "deployment_info": deployment_info,
2391                             "target_id": target_vim,
2392                             "item": "vdu",
2393                             "action": "DELETE",
2394                             "target_record": target_record,
2395                             "target_record_id": target_record_id,
2396                             "extra_dict": extra_dict,
2397                         }
2398                     )
2399 0                     delete_task_id = f"{action_id}:{task_index}"
2400 0                     task_index += 1
2401
2402                     # step 2 vdu to be created
2403 0                     kwargs = {}
2404 0                     kwargs.update(
2405                         {
2406                             "vnfr_id": vnfr_id,
2407                             "nsr_id": nsr_id,
2408                             "vnfr": existing_vnf,
2409                             "vdu2cloud_init": vdu2cloud_init,
2410                             "tasks_by_target_record_id": tasks_by_target_record_id,
2411                             "logger": self.logger,
2412                             "db": self.db,
2413                             "fs": self.fs,
2414                             "ro_nsr_public_key": ro_nsr_public_key,
2415                         }
2416                     )
2417
2418 0                     extra_dict = self._process_recreate_vdu_params(
2419                         existing_instance,
2420                         db_nsr,
2421                         target_viminfo,
2422                         target_record_id,
2423                         target_vim,
2424                         **kwargs,
2425                     )
2426
2427                     # The CREATE task depens on the DELETE task
2428 0                     extra_dict["depends_on"] = [delete_task_id]
2429
2430                     # Add volumes created from created_items if any
2431                     # Ports should be deleted with delete task and automatically created with create task
2432 0                     volumes = {}
2433 0                     for k, v in created_items.items():
2434 0                         try:
2435 0                             k_item, _, k_id = k.partition(":")
2436 0                             if k_item == "volume":
2437 0                                 volumes[k] = v
2438 0                         except Exception as e:
2439 0                             self.logger.error(
2440                                 "Error evaluating created item {}: {}".format(k, e)
2441                             )
2442 0                     extra_dict["previous_created_volumes"] = volumes
2443
2444 0                     deployment_info = {
2445                         "action_id": action_id,
2446                         "nsr_id": nsr_id,
2447                         "task_index": task_index,
2448                     }
2449 0                     self._assign_vim(target_vim)
2450
2451 0                     new_item = {
2452                         "deployment_info": deployment_info,
2453                         "target_id": target_vim,
2454                         "item": "vdu",
2455                         "action": "CREATE",
2456                         "target_record": target_record,
2457                         "target_record_id": target_record_id,
2458                         "extra_dict": extra_dict,
2459                     }
2460 0                     changes_list.append(new_item)
2461 0                     tasks_by_target_record_id[target_record_id] = new_item
2462 0                     task_index += 1
2463
2464 0         return changes_list
2465
2466 1     def recreate(self, session, indata, version, nsr_id, *args, **kwargs):
2467 0         self.logger.debug("ns.recreate nsr_id={} indata={}".format(nsr_id, indata))
2468         # TODO: validate_input(indata, recreate_schema)
2469 0         action_id = indata.get("action_id", str(uuid4()))
2470         # get current deployment
2471 0         db_vnfrs = {}  # vnf's info indexed by _id
2472 0         step = ""
2473 0         logging_text = "Recreate nsr_id={} action_id={} indata={}".format(
2474             nsr_id, action_id, indata
2475         )
2476 0         self.logger.debug(logging_text + "Enter")
2477
2478 0         try:
2479 0             step = "Getting ns and vnfr record from db"
2480 0             db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2481 0             db_new_tasks = []
2482 0             tasks_by_target_record_id = {}
2483             # read from db: vnf's of this ns
2484 0             step = "Getting vnfrs from db"
2485 0             db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2486 0             self.logger.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list))
2487
2488 0             if not db_vnfrs_list:
2489 0                 raise NsException("Cannot obtain associated VNF for ns")
2490
2491 0             for vnfr in db_vnfrs_list:
2492 0                 db_vnfrs[vnfr["_id"]] = vnfr
2493
2494 0             now = time()
2495 0             db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
2496 0             self.logger.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr))
2497
2498 0             if not db_ro_nsr:
2499 0                 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
2500
2501 0             with self.write_lock:
2502                 # NS
2503 0                 step = "process NS elements"
2504 0                 changes_list = self.prepare_changes_to_recreate(
2505                     indata=indata,
2506                     nsr_id=nsr_id,
2507                     db_nsr=db_nsr,
2508                     db_vnfrs=db_vnfrs,
2509                     db_ro_nsr=db_ro_nsr,
2510                     action_id=action_id,
2511                     tasks_by_target_record_id=tasks_by_target_record_id,
2512                 )
2513
2514 0                 self.define_all_tasks(
2515                     changes_list=changes_list,
2516                     db_new_tasks=db_new_tasks,
2517                     tasks_by_target_record_id=tasks_by_target_record_id,
2518                 )
2519
2520                 # Delete all ro_tasks registered for the targets vdurs (target_record)
2521                 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2522                 # So remove all task related to target record.
2523 0                 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2524 0                 for change in changes_list:
2525 0                     for ro_task in ro_tasks:
2526 0                         for task in ro_task["tasks"]:
2527 0                             if task["target_record"] == change["target_record"]:
2528 0                                 self.db.del_one(
2529                                     "ro_tasks",
2530                                     q_filter={
2531                                         "_id": ro_task["_id"],
2532                                         "modified_at": ro_task["modified_at"],
2533                                     },
2534                                     fail_on_empty=False,
2535                                 )
2536
2537 0                 step = "Updating database, Appending tasks to ro_tasks"
2538 0                 self.upload_recreate_tasks(
2539                     db_new_tasks=db_new_tasks,
2540                     now=now,
2541                 )
2542
2543 0             self.logger.debug(
2544                 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2545             )
2546
2547 0             return (
2548                 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2549                 action_id,
2550                 True,
2551             )
2552 0         except Exception as e:
2553 0             if isinstance(e, (DbException, NsException)):
2554 0                 self.logger.error(
2555                     logging_text + "Exit Exception while '{}': {}".format(step, e)
2556                 )
2557             else:
2558 0                 e = traceback_format_exc()
2559 0                 self.logger.critical(
2560                     logging_text + "Exit Exception while '{}': {}".format(step, e),
2561                     exc_info=True,
2562                 )
2563
2564 0             raise NsException(e)
2565
2566 1     def deploy(self, session, indata, version, nsr_id, *args, **kwargs):
2567 0         self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata))
2568 0         validate_input(indata, deploy_schema)
2569 0         action_id = indata.get("action_id", str(uuid4()))
2570 0         task_index = 0
2571         # get current deployment
2572 0         db_nsr_update = {}  # update operation on nsrs
2573 0         db_vnfrs_update = {}
2574 0         db_vnfrs = {}  # vnf's info indexed by _id
2575 0         step = ""
2576 0         logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2577 0         self.logger.debug(logging_text + "Enter")
2578
2579 0         try:
2580 0             step = "Getting ns and vnfr record from db"
2581 0             db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2582 0             self.logger.debug("ns.deploy: db_nsr={}".format(db_nsr))
2583 0             db_new_tasks = []
2584 0             tasks_by_target_record_id = {}
2585             # read from db: vnf's of this ns
2586 0             step = "Getting vnfrs from db"
2587 0             db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2588
2589 0             if not db_vnfrs_list:
2590 0                 raise NsException("Cannot obtain associated VNF for ns")
2591
2592 0             for vnfr in db_vnfrs_list:
2593 0                 db_vnfrs[vnfr["_id"]] = vnfr
2594 0                 db_vnfrs_update[vnfr["_id"]] = {}
2595 0             self.logger.debug("ns.deploy db_vnfrs={}".format(db_vnfrs))
2596
2597 0             now = time()
2598 0             db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
2599
2600 0             if not db_ro_nsr:
2601 0                 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
2602
2603             # check that action_id is not in the list of actions. Suffixed with :index
2604 0             if action_id in db_ro_nsr["actions"]:
2605 0                 index = 1
2606
2607                 while True:
2608 0                     new_action_id = "{}:{}".format(action_id, index)
2609
2610 0                     if new_action_id not in db_ro_nsr["actions"]:
2611 0                         action_id = new_action_id
2612 0                         self.logger.debug(
2613                             logging_text
2614                             + "Changing action_id in use to {}".format(action_id)
2615                         )
2616 0                         break
2617
2618 0                     index += 1
2619
2620 0             def _process_action(indata):
2621                 nonlocal db_new_tasks
2622                 nonlocal action_id
2623                 nonlocal nsr_id
2624                 nonlocal task_index
2625                 nonlocal db_vnfrs
2626                 nonlocal db_ro_nsr
2627
2628 0                 if indata["action"]["action"] == "inject_ssh_key":
2629 0                     key = indata["action"].get("key")
2630 0                     user = indata["action"].get("user")
2631 0                     password = indata["action"].get("password")
2632
2633 0                     for vnf in indata.get("vnf", ()):
2634 0                         if vnf["_id"] not in db_vnfrs:
2635 0                             raise NsException("Invalid vnf={}".format(vnf["_id"]))
2636
2637 0                         db_vnfr = db_vnfrs[vnf["_id"]]
2638
2639 0                         for target_vdu in vnf.get("vdur", ()):
2640 0                             vdu_index, vdur = next(
2641                                 (
2642                                     i_v
2643                                     for i_v in enumerate(db_vnfr["vdur"])
2644                                     if i_v[1]["id"] == target_vdu["id"]
2645                                 ),
2646                                 (None, None),
2647                             )
2648
2649 0                             if not vdur:
2650 0                                 raise NsException(
2651                                     "Invalid vdu vnf={}.{}".format(
2652                                         vnf["_id"], target_vdu["id"]
2653                                     )
2654                                 )
2655
2656 0                             target_vim, vim_info = next(
2657                                 k_v for k_v in vdur["vim_info"].items()
2658                             )
2659 0                             self._assign_vim(target_vim)
2660 0                             target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
2661                                 vnf["_id"], vdu_index
2662                             )
2663 0                             extra_dict = {
2664                                 "depends_on": [
2665                                     "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
2666                                 ],
2667                                 "params": {
2668                                     "ip_address": vdur.get("ip-address"),
2669                                     "user": user,
2670                                     "key": key,
2671                                     "password": password,
2672                                     "private_key": db_ro_nsr["private_key"],
2673                                     "salt": db_ro_nsr["_id"],
2674                                     "schema_version": db_ro_nsr["_admin"][
2675                                         "schema_version"
2676                                     ],
2677                                 },
2678                             }
2679
2680 0                             deployment_info = {
2681                                 "action_id": action_id,
2682                                 "nsr_id": nsr_id,
2683                                 "task_index": task_index,
2684                             }
2685
2686 0                             task = Ns._create_task(
2687                                 deployment_info=deployment_info,
2688                                 target_id=target_vim,
2689                                 item="vdu",
2690                                 action="EXEC",
2691                                 target_record=target_record,
2692                                 target_record_id=None,
2693                                 extra_dict=extra_dict,
2694                             )
2695
2696 0                             task_index = deployment_info.get("task_index")
2697
2698 0                             db_new_tasks.append(task)
2699
2700 0             with self.write_lock:
2701 0                 if indata.get("action"):
2702 0                     _process_action(indata)
2703                 else:
2704                     # compute network differences
2705                     # NS
2706 0                     step = "process NS elements"
2707 0                     changes_list = self.calculate_all_differences_to_deploy(
2708                         indata=indata,
2709                         nsr_id=nsr_id,
2710                         db_nsr=db_nsr,
2711                         db_vnfrs=db_vnfrs,
2712                         db_ro_nsr=db_ro_nsr,
2713                         db_nsr_update=db_nsr_update,
2714                         db_vnfrs_update=db_vnfrs_update,
2715                         action_id=action_id,
2716                         tasks_by_target_record_id=tasks_by_target_record_id,
2717                     )
2718 0                     self.define_all_tasks(
2719                         changes_list=changes_list,
2720                         db_new_tasks=db_new_tasks,
2721                         tasks_by_target_record_id=tasks_by_target_record_id,
2722                     )
2723
2724 0                 step = "Updating database, Appending tasks to ro_tasks"
2725 0                 self.upload_all_tasks(
2726                     db_new_tasks=db_new_tasks,
2727                     now=now,
2728                 )
2729
2730 0                 step = "Updating database, nsrs"
2731 0                 if db_nsr_update:
2732 0                     self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
2733
2734 0                 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
2735 0                     if db_vnfr_update:
2736 0                         step = "Updating database, vnfrs={}".format(vnfr_id)
2737 0                         self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
2738
2739 0             self.logger.debug(
2740                 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2741             )
2742
2743 0             return (
2744                 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2745                 action_id,
2746                 True,
2747             )
2748 0         except Exception as e:
2749 0             if isinstance(e, (DbException, NsException)):
2750 0                 self.logger.error(
2751                     logging_text + "Exit Exception while '{}': {}".format(step, e)
2752                 )
2753             else:
2754 0                 e = traceback_format_exc()
2755 0                 self.logger.critical(
2756                     logging_text + "Exit Exception while '{}': {}".format(step, e),
2757                     exc_info=True,
2758                 )
2759
2760 0             raise NsException(e)
2761
2762 1     def delete(self, session, indata, version, nsr_id, *args, **kwargs):
2763 0         self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
2764         # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2765
2766 0         with self.write_lock:
2767 0             try:
2768 0                 NsWorker.delete_db_tasks(self.db, nsr_id, None)
2769 0             except NsWorkerException as e:
2770 0                 raise NsException(e)
2771
2772 0         return None, None, True
2773
2774 1     def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2775 0         self.logger.debug(
2776             "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2777                 version, nsr_id, action_id, indata
2778             )
2779         )
2780 0         task_list = []
2781 0         done = 0
2782 0         total = 0
2783 0         ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
2784 0         global_status = "DONE"
2785 0         details = []
2786
2787 0         for ro_task in ro_tasks:
2788 0             for task in ro_task["tasks"]:
2789 0                 if task and task["action_id"] == action_id:
2790 0                     task_list.append(task)
2791 0                     total += 1
2792
2793 0                     if task["status"] == "FAILED":
2794 0                         global_status = "FAILED"
2795 0                         error_text = "Error at {} {}: {}".format(
2796                             task["action"].lower(),
2797                             task["item"],
2798                             ro_task["vim_info"].get("vim_message") or "unknown",
2799                         )
2800 0                         details.append(error_text)
2801 0                     elif task["status"] in ("SCHEDULED", "BUILD"):
2802 0                         if global_status != "FAILED":
2803 0                             global_status = "BUILD"
2804                     else:
2805 0                         done += 1
2806
2807 0         return_data = {
2808             "status": global_status,
2809             "details": ". ".join(details)
2810             if details
2811             else "progress {}/{}".format(done, total),
2812             "nsr_id": nsr_id,
2813             "action_id": action_id,
2814             "tasks": task_list,
2815         }
2816
2817 0         return return_data, None, True
2818
2819 1     def recreate_status(
2820         self, session, indata, version, nsr_id, action_id, *args, **kwargs
2821     ):
2822 0         return self.status(session, indata, version, nsr_id, action_id, *args, **kwargs)
2823
2824 1     def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2825 0         print(
2826             "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2827                 session, indata, version, nsr_id, action_id
2828             )
2829         )
2830
2831 0         return None, None, True
2832
2833 1     def rebuild_start_stop_task(
2834         self,
2835         vdu_id,
2836         vnf_id,
2837         vdu_index,
2838         action_id,
2839         nsr_id,
2840         task_index,
2841         target_vim,
2842         extra_dict,
2843     ):
2844 1         self._assign_vim(target_vim)
2845 1         target_record = "vnfrs:{}:vdur.{}".format(vnf_id, vdu_index)
2846 1         target_record_id = "vnfrs:{}:vdur.{}".format(vnf_id, vdu_id)
2847 1         deployment_info = {
2848             "action_id": action_id,
2849             "nsr_id": nsr_id,
2850             "task_index": task_index,
2851         }
2852
2853 1         task = Ns._create_task(
2854             deployment_info=deployment_info,
2855             target_id=target_vim,
2856             item="update",
2857             action="EXEC",
2858             target_record=target_record,
2859             target_record_id=target_record_id,
2860             extra_dict=extra_dict,
2861         )
2862 1         return task
2863
2864 1     def rebuild_start_stop(
2865         self, session, action_dict, version, nsr_id, *args, **kwargs
2866     ):
2867 0         task_index = 0
2868 0         extra_dict = {}
2869 0         now = time()
2870 0         action_id = action_dict.get("action_id", str(uuid4()))
2871 0         step = ""
2872 0         logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2873 0         self.logger.debug(logging_text + "Enter")
2874
2875 0         action = list(action_dict.keys())[0]
2876 0         task_dict = action_dict.get(action)
2877 0         vim_vm_id = action_dict.get(action).get("vim_vm_id")
2878
2879 0         if action_dict.get("stop"):
2880 0             action = "shutoff"
2881 0         db_new_tasks = []
2882 0         try:
2883 0             step = "lock the operation & do task creation"
2884 0             with self.write_lock:
2885 0                 extra_dict["params"] = {
2886                     "vim_vm_id": vim_vm_id,
2887                     "action": action,
2888                 }
2889 0                 task = self.rebuild_start_stop_task(
2890                     task_dict["vdu_id"],
2891                     task_dict["vnf_id"],
2892                     task_dict["vdu_index"],
2893                     action_id,
2894                     nsr_id,
2895                     task_index,
2896                     task_dict["target_vim"],
2897                     extra_dict,
2898                 )
2899 0                 db_new_tasks.append(task)
2900 0                 step = "upload Task to db"
2901 0                 self.upload_all_tasks(
2902                     db_new_tasks=db_new_tasks,
2903                     now=now,
2904                 )
2905 0                 self.logger.debug(
2906                     logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2907                 )
2908 0                 return (
2909                     {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2910                     action_id,
2911                     True,
2912                 )
2913 0         except Exception as e:
2914 0             if isinstance(e, (DbException, NsException)):
2915 0                 self.logger.error(
2916                     logging_text + "Exit Exception while '{}': {}".format(step, e)
2917                 )
2918             else:
2919 0                 e = traceback_format_exc()
2920 0                 self.logger.critical(
2921                     logging_text + "Exit Exception while '{}': {}".format(step, e),
2922                     exc_info=True,
2923                 )
2924 0             raise NsException(e)
2925
2926 1     def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2927 0         nsrs = self.db.get_list("nsrs", {})
2928 0         return_data = []
2929
2930 0         for ns in nsrs:
2931 0             return_data.append({"_id": ns["_id"], "name": ns["name"]})
2932
2933 0         return return_data, None, True
2934
2935 1     def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2936 0         ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2937 0         return_data = []
2938
2939 0         for ro_task in ro_tasks:
2940 0             for task in ro_task["tasks"]:
2941 0                 if task["action_id"] not in return_data:
2942 0                     return_data.append(task["action_id"])
2943
2944 0         return return_data, None, True
2945
2946 1     def migrate_task(
2947         self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
2948     ):
2949 1         target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
2950 1         self._assign_vim(target_vim)
2951 1         target_record = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu_index)
2952 1         target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
2953 1         deployment_info = {
2954             "action_id": action_id,
2955             "nsr_id": nsr_id,
2956             "task_index": task_index,
2957         }
2958
2959 1         task = Ns._create_task(
2960             deployment_info=deployment_info,
2961             target_id=target_vim,
2962             item="migrate",
2963             action="EXEC",
2964             target_record=target_record,
2965             target_record_id=target_record_id,
2966             extra_dict=extra_dict,
2967         )
2968
2969 1         return task
2970
2971 1     def migrate(self, session, indata, version, nsr_id, *args, **kwargs):
2972 0         task_index = 0
2973 0         extra_dict = {}
2974 0         now = time()
2975 0         action_id = indata.get("action_id", str(uuid4()))
2976 0         step = ""
2977 0         logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2978 0         self.logger.debug(logging_text + "Enter")
2979 0         try:
2980 0             vnf_instance_id = indata["vnfInstanceId"]
2981 0             step = "Getting vnfrs from db"
2982 0             db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
2983 0             vdu = indata.get("vdu")
2984 0             migrateToHost = indata.get("migrateToHost")
2985 0             db_new_tasks = []
2986
2987 0             with self.write_lock:
2988 0                 if vdu is not None:
2989 0                     vdu_id = indata["vdu"]["vduId"]
2990 0                     vdu_count_index = indata["vdu"].get("vduCountIndex", 0)
2991 0                     for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
2992 0                         if (
2993                             vdu["vdu-id-ref"] == vdu_id
2994                             and vdu["count-index"] == vdu_count_index
2995                         ):
2996 0                             extra_dict["params"] = {
2997                                 "vim_vm_id": vdu["vim-id"],
2998                                 "migrate_host": migrateToHost,
2999                                 "vdu_vim_info": vdu["vim_info"],
3000                             }
3001 0                             step = "Creating migration task for vdu:{}".format(vdu)
3002 0                             task = self.migrate_task(
3003                                 vdu,
3004                                 db_vnfr,
3005                                 vdu_index,
3006                                 action_id,
3007                                 nsr_id,
3008                                 task_index,
3009                                 extra_dict,
3010                             )
3011 0                             db_new_tasks.append(task)
3012 0                             task_index += 1
3013 0                             break
3014                 else:
3015 0                     for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3016 0                         extra_dict["params"] = {
3017                             "vim_vm_id": vdu["vim-id"],
3018                             "migrate_host": migrateToHost,
3019                             "vdu_vim_info": vdu["vim_info"],
3020                         }
3021 0                         step = "Creating migration task for vdu:{}".format(vdu)
3022 0                         task = self.migrate_task(
3023                             vdu,
3024                             db_vnfr,
3025                             vdu_index,
3026                             action_id,
3027                             nsr_id,
3028                             task_index,
3029                             extra_dict,
3030                         )
3031 0                         db_new_tasks.append(task)
3032 0                         task_index += 1
3033
3034 0                 self.upload_all_tasks(
3035                     db_new_tasks=db_new_tasks,
3036                     now=now,
3037                 )
3038
3039 0             self.logger.debug(
3040                 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3041             )
3042 0             return (
3043                 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3044                 action_id,
3045                 True,
3046             )
3047 0         except Exception as e:
3048 0             if isinstance(e, (DbException, NsException)):
3049 0                 self.logger.error(
3050                     logging_text + "Exit Exception while '{}': {}".format(step, e)
3051                 )
3052             else:
3053 0                 e = traceback_format_exc()
3054 0                 self.logger.critical(
3055                     logging_text + "Exit Exception while '{}': {}".format(step, e),
3056                     exc_info=True,
3057                 )
3058 0             raise NsException(e)
3059
3060 1     def verticalscale_task(
3061         self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
3062     ):
3063 1         target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
3064 1         self._assign_vim(target_vim)
3065 1         target_record = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu_index)
3066 1         target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
3067 1         deployment_info = {
3068             "action_id": action_id,
3069             "nsr_id": nsr_id,
3070             "task_index": task_index,
3071         }
3072
3073 1         task = Ns._create_task(
3074             deployment_info=deployment_info,
3075             target_id=target_vim,
3076             item="verticalscale",
3077             action="EXEC",
3078             target_record=target_record,
3079             target_record_id=target_record_id,
3080             extra_dict=extra_dict,
3081         )
3082 1         return task
3083
3084 1     def verticalscale(self, session, indata, version, nsr_id, *args, **kwargs):
3085 0         task_index = 0
3086 0         extra_dict = {}
3087 0         now = time()
3088 0         action_id = indata.get("action_id", str(uuid4()))
3089 0         step = ""
3090 0         logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3091 0         self.logger.debug(logging_text + "Enter")
3092 0         try:
3093 0             VnfFlavorData = indata.get("changeVnfFlavorData")
3094 0             vnf_instance_id = VnfFlavorData["vnfInstanceId"]
3095 0             step = "Getting vnfrs from db"
3096 0             db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
3097 0             vduid = VnfFlavorData["additionalParams"]["vduid"]
3098 0             vduCountIndex = VnfFlavorData["additionalParams"]["vduCountIndex"]
3099 0             virtualMemory = VnfFlavorData["additionalParams"]["virtualMemory"]
3100 0             numVirtualCpu = VnfFlavorData["additionalParams"]["numVirtualCpu"]
3101 0             sizeOfStorage = VnfFlavorData["additionalParams"]["sizeOfStorage"]
3102 0             flavor_dict = {
3103                 "name": vduid + "-flv",
3104                 "ram": virtualMemory,
3105                 "vcpus": numVirtualCpu,
3106                 "disk": sizeOfStorage,
3107             }
3108 0             db_new_tasks = []
3109 0             step = "Creating Tasks for vertical scaling"
3110 0             with self.write_lock:
3111 0                 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3112 0                     if (
3113                         vdu["vdu-id-ref"] == vduid
3114                         and vdu["count-index"] == vduCountIndex
3115                     ):
3116 0                         extra_dict["params"] = {
3117                             "vim_vm_id": vdu["vim-id"],
3118                             "flavor_dict": flavor_dict,
3119                         }
3120 0                         task = self.verticalscale_task(
3121                             vdu,
3122                             db_vnfr,
3123                             vdu_index,
3124                             action_id,
3125                             nsr_id,
3126                             task_index,
3127                             extra_dict,
3128                         )
3129 0                         db_new_tasks.append(task)
3130 0                         task_index += 1
3131 0                         break
3132 0                 self.upload_all_tasks(
3133                     db_new_tasks=db_new_tasks,
3134                     now=now,
3135                 )
3136 0             self.logger.debug(
3137                 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3138             )
3139 0             return (
3140                 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3141                 action_id,
3142                 True,
3143             )
3144 0         except Exception as e:
3145 0             if isinstance(e, (DbException, NsException)):
3146 0                 self.logger.error(
3147                     logging_text + "Exit Exception while '{}': {}".format(step, e)
3148                 )
3149             else:
3150 0                 e = traceback_format_exc()
3151 0                 self.logger.critical(
3152                     logging_text + "Exit Exception while '{}': {}".format(step, e),
3153                     exc_info=True,
3154                 )
3155 0             raise NsException(e)