Code Coverage

Cobertura Coverage Report > NG-RO.osm_ng_ro >

ns.py

Trend

File Coverage summary

NameClassesLinesConditionals
ns.py
100%
1/1
44%
642/1450
100%
0/0

Coverage Breakdown by Class

NameLinesConditionals
ns.py
44%
642/1450
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 copy import deepcopy
20 1 from http import HTTPStatus
21 1 from itertools import product
22 1 import logging
23 1 from random import choice as random_choice
24 1 from threading import Lock
25 1 from time import time
26 1 from traceback import format_exc as traceback_format_exc
27 1 from typing import Any, Dict, List, Optional, Tuple, Type
28 1 from uuid import uuid4
29
30 1 from cryptography.hazmat.backends import default_backend as crypto_default_backend
31 1 from cryptography.hazmat.primitives import serialization as crypto_serialization
32 1 from cryptography.hazmat.primitives.asymmetric import rsa
33 1 from jinja2 import (
34     Environment,
35     select_autoescape,
36     StrictUndefined,
37     TemplateError,
38     TemplateNotFound,
39     UndefinedError,
40 )
41 1 from osm_common import (
42     dbmemory,
43     dbmongo,
44     fslocal,
45     fsmongo,
46     msgkafka,
47     msglocal,
48     version as common_version,
49 )
50 1 from osm_common.dbbase import DbBase, DbException
51 1 from osm_common.fsbase import FsBase, FsException
52 1 from osm_common.msgbase import MsgException
53 1 from osm_ng_ro.ns_thread import deep_get, NsWorker, NsWorkerException
54 1 from osm_ng_ro.validation import deploy_schema, validate_input
55 1 import yaml
56
57 1 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
58 1 min_common_version = "0.1.16"
59
60
61 1 class NsException(Exception):
62 1     def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
63 1         self.http_code = http_code
64 1         super(Exception, self).__init__(message)
65
66
67 1 def get_process_id():
68     """
69     Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
70     will provide a random one
71     :return: Obtained ID
72     """
73     # Try getting docker id. If fails, get pid
74 0     try:
75 0         with open("/proc/self/cgroup", "r") as f:
76 0             text_id_ = f.readline()
77 0             _, _, text_id = text_id_.rpartition("/")
78 0             text_id = text_id.replace("\n", "")[:12]
79
80 0             if text_id:
81 0                 return text_id
82 0     except Exception as error:
83 0         logging.exception(f"{error} occured while getting process id")
84
85     # Return a random id
86 0     return "".join(random_choice("0123456789abcdef") for _ in range(12))
87
88
89 1 def versiontuple(v):
90     """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
91 0     filled = []
92
93 0     for point in v.split("."):
94 0         filled.append(point.zfill(8))
95
96 0     return tuple(filled)
97
98
99 1 class Ns(object):
100 1     def __init__(self):
101 1         self.db = None
102 1         self.fs = None
103 1         self.msg = None
104 1         self.config = None
105         # self.operations = None
106 1         self.logger = None
107         # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
108         # If done now it will not be linked to parent not getting its handler and level
109 1         self.map_topic = {}
110 1         self.write_lock = None
111 1         self.vims_assigned = {}
112 1         self.next_worker = 0
113 1         self.plugins = {}
114 1         self.workers = []
115 1         self.process_params_function_map = {
116             "net": Ns._process_net_params,
117             "image": Ns._process_image_params,
118             "flavor": Ns._process_flavor_params,
119             "vdu": Ns._process_vdu_params,
120             "classification": Ns._process_classification_params,
121             "sfi": Ns._process_sfi_params,
122             "sf": Ns._process_sf_params,
123             "sfp": Ns._process_sfp_params,
124             "affinity-or-anti-affinity-group": Ns._process_affinity_group_params,
125             "shared-volumes": Ns._process_shared_volumes_params,
126         }
127 1         self.db_path_map = {
128             "net": "vld",
129             "image": "image",
130             "flavor": "flavor",
131             "vdu": "vdur",
132             "classification": "classification",
133             "sfi": "sfi",
134             "sf": "sf",
135             "sfp": "sfp",
136             "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group",
137             "shared-volumes": "shared-volumes",
138         }
139
140 1     def init_db(self, target_version):
141 0         pass
142
143 1     def start(self, config):
144         """
145         Connect to database, filesystem storage, and messaging
146         :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
147         :param config: Configuration of db, storage, etc
148         :return: None
149         """
150 0         self.config = config
151 0         self.config["process_id"] = get_process_id()  # used for HA identity
152 0         self.logger = logging.getLogger("ro.ns")
153
154         # check right version of common
155 0         if versiontuple(common_version) < versiontuple(min_common_version):
156 0             raise NsException(
157                 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
158                     common_version, min_common_version
159                 )
160             )
161
162 0         try:
163 0             if not self.db:
164 0                 if config["database"]["driver"] == "mongo":
165 0                     self.db = dbmongo.DbMongo()
166 0                     self.db.db_connect(config["database"])
167 0                 elif config["database"]["driver"] == "memory":
168 0                     self.db = dbmemory.DbMemory()
169 0                     self.db.db_connect(config["database"])
170                 else:
171 0                     raise NsException(
172                         "Invalid configuration param '{}' at '[database]':'driver'".format(
173                             config["database"]["driver"]
174                         )
175                     )
176
177 0             if not self.fs:
178 0                 if config["storage"]["driver"] == "local":
179 0                     self.fs = fslocal.FsLocal()
180 0                     self.fs.fs_connect(config["storage"])
181 0                 elif config["storage"]["driver"] == "mongo":
182 0                     self.fs = fsmongo.FsMongo()
183 0                     self.fs.fs_connect(config["storage"])
184 0                 elif config["storage"]["driver"] is None:
185 0                     pass
186                 else:
187 0                     raise NsException(
188                         "Invalid configuration param '{}' at '[storage]':'driver'".format(
189                             config["storage"]["driver"]
190                         )
191                     )
192
193 0             if not self.msg:
194 0                 if config["message"]["driver"] == "local":
195 0                     self.msg = msglocal.MsgLocal()
196 0                     self.msg.connect(config["message"])
197 0                 elif config["message"]["driver"] == "kafka":
198 0                     self.msg = msgkafka.MsgKafka()
199 0                     self.msg.connect(config["message"])
200                 else:
201 0                     raise NsException(
202                         "Invalid configuration param '{}' at '[message]':'driver'".format(
203                             config["message"]["driver"]
204                         )
205                     )
206
207             # TODO load workers to deal with exising database tasks
208
209 0             self.write_lock = Lock()
210 0         except (DbException, FsException, MsgException) as e:
211 0             raise NsException(str(e), http_code=e.http_code)
212
213 1     def get_assigned_vims(self):
214 0         return list(self.vims_assigned.keys())
215
216 1     def stop(self):
217 0         try:
218 0             if self.db:
219 0                 self.db.db_disconnect()
220
221 0             if self.fs:
222 0                 self.fs.fs_disconnect()
223
224 0             if self.msg:
225 0                 self.msg.disconnect()
226
227 0             self.write_lock = None
228 0         except (DbException, FsException, MsgException) as e:
229 0             raise NsException(str(e), http_code=e.http_code)
230
231 0         for worker in self.workers:
232 0             worker.insert_task(("terminate",))
233
234 1     def _create_worker(self):
235         """
236         Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
237         limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
238         return the index of the assigned worker thread. Worker threads are storead at self.workers
239         """
240         # Look for a thread in idle status
241 0         worker_id = next(
242             (
243                 i
244                 for i in range(len(self.workers))
245                 if self.workers[i] and self.workers[i].idle
246             ),
247             None,
248         )
249
250 0         if worker_id is not None:
251             # unset idle status to avoid race conditions
252 0             self.workers[worker_id].idle = False
253         else:
254 0             worker_id = len(self.workers)
255
256 0             if worker_id < self.config["global"]["server.ns_threads"]:
257                 # create a new worker
258 0                 self.workers.append(
259                     NsWorker(worker_id, self.config, self.plugins, self.db)
260                 )
261 0                 self.workers[worker_id].start()
262             else:
263                 # reached maximum number of threads, assign VIM to an existing one
264 0                 worker_id = self.next_worker
265 0                 self.next_worker = (self.next_worker + 1) % self.config["global"][
266                     "server.ns_threads"
267                 ]
268
269 0         return worker_id
270
271 1     def assign_vim(self, target_id):
272 0         with self.write_lock:
273 0             return self._assign_vim(target_id)
274
275 1     def _assign_vim(self, target_id):
276 0         if target_id not in self.vims_assigned:
277 0             worker_id = self.vims_assigned[target_id] = self._create_worker()
278 0             self.workers[worker_id].insert_task(("load_vim", target_id))
279
280 1     def reload_vim(self, target_id):
281         # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
282         # this is because database VIM information is cached for threads working with SDN
283 0         with self.write_lock:
284 0             for worker in self.workers:
285 0                 if worker and not worker.idle:
286 0                     worker.insert_task(("reload_vim", target_id))
287
288 1     def unload_vim(self, target_id):
289 0         with self.write_lock:
290 0             return self._unload_vim(target_id)
291
292 1     def _unload_vim(self, target_id):
293 0         if target_id in self.vims_assigned:
294 0             worker_id = self.vims_assigned[target_id]
295 0             self.workers[worker_id].insert_task(("unload_vim", target_id))
296 0             del self.vims_assigned[target_id]
297
298 1     def check_vim(self, target_id):
299 0         with self.write_lock:
300 0             if target_id in self.vims_assigned:
301 0                 worker_id = self.vims_assigned[target_id]
302             else:
303 0                 worker_id = self._create_worker()
304
305 0         worker = self.workers[worker_id]
306 0         worker.insert_task(("check_vim", target_id))
307
308 1     def unload_unused_vims(self):
309 0         with self.write_lock:
310 0             vims_to_unload = []
311
312 0             for target_id in self.vims_assigned:
313 0                 if not self.db.get_one(
314                     "ro_tasks",
315                     q_filter={
316                         "target_id": target_id,
317                         "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
318                     },
319                     fail_on_empty=False,
320                 ):
321 0                     vims_to_unload.append(target_id)
322
323 0             for target_id in vims_to_unload:
324 0                 self._unload_vim(target_id)
325
326 1     @staticmethod
327 1     def _get_cloud_init(
328         db: Type[DbBase],
329         fs: Type[FsBase],
330         location: str,
331     ) -> str:
332         """This method reads cloud init from a file.
333
334         Note: Not used as cloud init content is provided in the http body.
335
336         Args:
337             db (Type[DbBase]): [description]
338             fs (Type[FsBase]): [description]
339             location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
340
341         Raises:
342             NsException: [description]
343             NsException: [description]
344
345         Returns:
346             str: [description]
347         """
348 1         vnfd_id, _, other = location.partition(":")
349 1         _type, _, name = other.partition(":")
350 1         vnfd = db.get_one("vnfds", {"_id": vnfd_id})
351
352 1         if _type == "file":
353 1             base_folder = vnfd["_admin"]["storage"]
354 1             cloud_init_file = "{}/{}/cloud_init/{}".format(
355                 base_folder["folder"], base_folder["pkg-dir"], name
356             )
357
358 1             if not fs:
359 1                 raise NsException(
360                     "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
361                         cloud_init_file
362                     )
363                 )
364
365 1             with fs.file_open(cloud_init_file, "r") as ci_file:
366 1                 cloud_init_content = ci_file.read()
367 1         elif _type == "vdu":
368 1             cloud_init_content = vnfd["vdu"][int(name)]["cloud-init"]
369         else:
370 1             raise NsException("Mismatch descriptor for cloud init: {}".format(location))
371
372 1         return cloud_init_content
373
374 1     @staticmethod
375 1     def _parse_jinja2(
376         cloud_init_content: str,
377         params: Dict[str, Any],
378         context: str,
379     ) -> str:
380         """Function that processes the cloud init to replace Jinja2 encoded parameters.
381
382         Args:
383             cloud_init_content (str): [description]
384             params (Dict[str, Any]): [description]
385             context (str): [description]
386
387         Raises:
388             NsException: [description]
389             NsException: [description]
390
391         Returns:
392             str: [description]
393         """
394 1         try:
395 1             env = Environment(
396                 undefined=StrictUndefined,
397                 autoescape=select_autoescape(default_for_string=True, default=True),
398             )
399 1             template = env.from_string(cloud_init_content)
400
401 1             return template.render(params or {})
402 1         except UndefinedError as e:
403 1             raise NsException(
404                 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
405                 "inside the 'additionalParamsForVnf' block".format(e, context)
406             )
407 1         except (TemplateError, TemplateNotFound) as e:
408 1             raise NsException(
409                 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
410                     context, e
411                 )
412             )
413
414 1     def _create_db_ro_nsrs(self, nsr_id, now):
415 0         try:
416 0             key = rsa.generate_private_key(
417                 backend=crypto_default_backend(), public_exponent=65537, key_size=2048
418             )
419 0             private_key = key.private_bytes(
420                 crypto_serialization.Encoding.PEM,
421                 crypto_serialization.PrivateFormat.PKCS8,
422                 crypto_serialization.NoEncryption(),
423             )
424 0             public_key = key.public_key().public_bytes(
425                 crypto_serialization.Encoding.OpenSSH,
426                 crypto_serialization.PublicFormat.OpenSSH,
427             )
428 0             private_key = private_key.decode("utf8")
429             # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
430 0             i = private_key.find("\n")
431 0             private_key = "-----BEGIN RSA PRIVATE KEY-----" + private_key[i:]
432 0             public_key = public_key.decode("utf8")
433 0         except Exception as e:
434 0             raise NsException("Cannot create ssh-keys: {}".format(e))
435
436 0         schema_version = "1.1"
437 0         private_key_encrypted = self.db.encrypt(
438             private_key, schema_version=schema_version, salt=nsr_id
439         )
440 0         db_content = {
441             "_id": nsr_id,
442             "_admin": {
443                 "created": now,
444                 "modified": now,
445                 "schema_version": schema_version,
446             },
447             "public_key": public_key,
448             "private_key": private_key_encrypted,
449             "actions": [],
450         }
451 0         self.db.create("ro_nsrs", db_content)
452
453 0         return db_content
454
455 1     @staticmethod
456 1     def _create_task(
457         deployment_info: Dict[str, Any],
458         target_id: str,
459         item: str,
460         action: str,
461         target_record: str,
462         target_record_id: str,
463         extra_dict: Dict[str, Any] = None,
464     ) -> Dict[str, Any]:
465         """Function to create task dict from deployment information.
466
467         Args:
468             deployment_info (Dict[str, Any]): [description]
469             target_id (str): [description]
470             item (str): [description]
471             action (str): [description]
472             target_record (str): [description]
473             target_record_id (str): [description]
474             extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
475
476         Returns:
477             Dict[str, Any]: [description]
478         """
479 1         task = {
480             "target_id": target_id,  # it will be removed before pushing at database
481             "action_id": deployment_info.get("action_id"),
482             "nsr_id": deployment_info.get("nsr_id"),
483             "task_id": f"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
484             "status": "SCHEDULED",
485             "action": action,
486             "item": item,
487             "target_record": target_record,
488             "target_record_id": target_record_id,
489         }
490
491 1         if extra_dict:
492 1             task.update(extra_dict)  # params, find_params, depends_on
493
494 1         deployment_info["task_index"] = deployment_info.get("task_index", 0) + 1
495
496 1         return task
497
498 1     @staticmethod
499 1     def _create_ro_task(
500         target_id: str,
501         task: Dict[str, Any],
502     ) -> Dict[str, Any]:
503         """Function to create an RO task from task information.
504
505         Args:
506             target_id (str): [description]
507             task (Dict[str, Any]): [description]
508
509         Returns:
510             Dict[str, Any]: [description]
511         """
512 1         now = time()
513
514 1         _id = task.get("task_id")
515 1         db_ro_task = {
516             "_id": _id,
517             "locked_by": None,
518             "locked_at": 0.0,
519             "target_id": target_id,
520             "vim_info": {
521                 "created": False,
522                 "created_items": None,
523                 "vim_id": None,
524                 "vim_name": None,
525                 "vim_status": None,
526                 "vim_details": None,
527                 "vim_message": None,
528                 "refresh_at": None,
529             },
530             "modified_at": now,
531             "created_at": now,
532             "to_check_at": now,
533             "tasks": [task],
534         }
535
536 1         return db_ro_task
537
538 1     @staticmethod
539 1     def _process_image_params(
540         target_image: Dict[str, Any],
541         indata: Dict[str, Any],
542         vim_info: Dict[str, Any],
543         target_record_id: str,
544         **kwargs: Dict[str, Any],
545     ) -> Dict[str, Any]:
546         """Function to process VDU image parameters.
547
548         Args:
549             target_image (Dict[str, Any]): [description]
550             indata (Dict[str, Any]): [description]
551             vim_info (Dict[str, Any]): [description]
552             target_record_id (str): [description]
553
554         Returns:
555             Dict[str, Any]: [description]
556         """
557 1         find_params = {}
558
559 1         if target_image.get("image"):
560 1             find_params["filter_dict"] = {"name": target_image.get("image")}
561
562 1         if target_image.get("vim_image_id"):
563 1             find_params["filter_dict"] = {"id": target_image.get("vim_image_id")}
564
565 1         if target_image.get("image_checksum"):
566 1             find_params["filter_dict"] = {
567                 "checksum": target_image.get("image_checksum")
568             }
569
570 1         return {"find_params": find_params}
571
572 1     @staticmethod
573 1     def _get_resource_allocation_params(
574         quota_descriptor: Dict[str, Any],
575     ) -> Dict[str, Any]:
576         """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
577         descriptor object.
578
579         Args:
580             quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
581
582         Returns:
583             Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
584         """
585 1         quota = {}
586
587 1         if quota_descriptor.get("limit"):
588 1             quota["limit"] = int(quota_descriptor["limit"])
589
590 1         if quota_descriptor.get("reserve"):
591 1             quota["reserve"] = int(quota_descriptor["reserve"])
592
593 1         if quota_descriptor.get("shares"):
594 1             quota["shares"] = int(quota_descriptor["shares"])
595
596 1         return quota
597
598 1     @staticmethod
599 1     def _process_guest_epa_quota_params(
600         guest_epa_quota: Dict[str, Any],
601         epa_vcpu_set: bool,
602     ) -> Dict[str, Any]:
603         """Function to extract the guest epa quota parameters.
604
605         Args:
606             guest_epa_quota (Dict[str, Any]): [description]
607             epa_vcpu_set (bool): [description]
608
609         Returns:
610             Dict[str, Any]: [description]
611         """
612 1         result = {}
613
614 1         if guest_epa_quota.get("cpu-quota") and not epa_vcpu_set:
615 1             cpuquota = Ns._get_resource_allocation_params(
616                 guest_epa_quota.get("cpu-quota")
617             )
618
619 1             if cpuquota:
620 1                 result["cpu-quota"] = cpuquota
621
622 1         if guest_epa_quota.get("mem-quota"):
623 1             vduquota = Ns._get_resource_allocation_params(
624                 guest_epa_quota.get("mem-quota")
625             )
626
627 1             if vduquota:
628 1                 result["mem-quota"] = vduquota
629
630 1         if guest_epa_quota.get("disk-io-quota"):
631 1             diskioquota = Ns._get_resource_allocation_params(
632                 guest_epa_quota.get("disk-io-quota")
633             )
634
635 1             if diskioquota:
636 1                 result["disk-io-quota"] = diskioquota
637
638 1         if guest_epa_quota.get("vif-quota"):
639 1             vifquota = Ns._get_resource_allocation_params(
640                 guest_epa_quota.get("vif-quota")
641             )
642
643 1             if vifquota:
644 1                 result["vif-quota"] = vifquota
645
646 1         return result
647
648 1     @staticmethod
649 1     def _process_guest_epa_numa_params(
650         guest_epa_quota: Dict[str, Any],
651     ) -> Tuple[Dict[str, Any], bool]:
652         """[summary]
653
654         Args:
655             guest_epa_quota (Dict[str, Any]): [description]
656
657         Returns:
658             Tuple[Dict[str, Any], bool]: [description]
659         """
660 1         numa = {}
661 1         numa_list = []
662 1         epa_vcpu_set = False
663
664 1         if guest_epa_quota.get("numa-node-policy"):
665 1             numa_node_policy = guest_epa_quota.get("numa-node-policy")
666
667 1             if numa_node_policy.get("node"):
668 1                 for numa_node in numa_node_policy["node"]:
669 1                     vcpu_list = []
670 1                     if numa_node.get("id"):
671 1                         numa["id"] = int(numa_node["id"])
672
673 1                     if numa_node.get("vcpu"):
674 1                         for vcpu in numa_node.get("vcpu"):
675 1                             vcpu_id = int(vcpu.get("id"))
676 1                             vcpu_list.append(vcpu_id)
677 1                         numa["vcpu"] = vcpu_list
678
679 1                     if numa_node.get("num-cores"):
680 1                         numa["cores"] = numa_node["num-cores"]
681 1                         epa_vcpu_set = True
682
683 1                     paired_threads = numa_node.get("paired-threads", {})
684 1                     if paired_threads.get("num-paired-threads"):
685 1                         numa["paired_threads"] = int(
686                             numa_node["paired-threads"]["num-paired-threads"]
687                         )
688 1                         epa_vcpu_set = True
689
690 1                     if paired_threads.get("paired-thread-ids"):
691 1                         numa["paired-threads-id"] = []
692
693 1                         for pair in paired_threads["paired-thread-ids"]:
694 1                             numa["paired-threads-id"].append(
695                                 (
696                                     str(pair["thread-a"]),
697                                     str(pair["thread-b"]),
698                                 )
699                             )
700
701 1                     if numa_node.get("num-threads"):
702 1                         numa["threads"] = int(numa_node["num-threads"])
703 1                         epa_vcpu_set = True
704
705 1                     if numa_node.get("memory-mb"):
706 1                         numa["memory"] = max(int(int(numa_node["memory-mb"]) / 1024), 1)
707
708 1                     numa_list.append(numa)
709 1                     numa = {}
710
711 1         return numa_list, epa_vcpu_set
712
713 1     @staticmethod
714 1     def _process_guest_epa_cpu_pinning_params(
715         guest_epa_quota: Dict[str, Any],
716         vcpu_count: int,
717         epa_vcpu_set: bool,
718     ) -> Tuple[Dict[str, Any], bool]:
719         """[summary]
720
721         Args:
722             guest_epa_quota (Dict[str, Any]): [description]
723             vcpu_count (int): [description]
724             epa_vcpu_set (bool): [description]
725
726         Returns:
727             Tuple[Dict[str, Any], bool]: [description]
728         """
729 1         numa = {}
730 1         local_epa_vcpu_set = epa_vcpu_set
731
732 1         if (
733             guest_epa_quota.get("cpu-pinning-policy") == "DEDICATED"
734             and not epa_vcpu_set
735         ):
736             # Pinning policy "REQUIRE" uses threads as host should support SMT architecture
737             # Pinning policy "ISOLATE" uses cores as host should not support SMT architecture
738             # Pinning policy "PREFER" uses threads in case host supports SMT architecture
739 1             numa[
740                 "cores"
741                 if guest_epa_quota.get("cpu-thread-pinning-policy") == "ISOLATE"
742                 else "threads"
743             ] = max(vcpu_count, 1)
744 1             local_epa_vcpu_set = True
745
746 1         return numa, local_epa_vcpu_set
747
748 1     @staticmethod
749 1     def _process_epa_params(
750         target_flavor: Dict[str, Any],
751     ) -> Dict[str, Any]:
752         """[summary]
753
754         Args:
755             target_flavor (Dict[str, Any]): [description]
756
757         Returns:
758             Dict[str, Any]: [description]
759         """
760 1         extended = {}
761 1         numa = {}
762 1         numa_list = []
763
764 1         if target_flavor.get("guest-epa"):
765 1             guest_epa = target_flavor["guest-epa"]
766
767 1             numa_list, epa_vcpu_set = Ns._process_guest_epa_numa_params(
768                 guest_epa_quota=guest_epa
769             )
770
771 1             if guest_epa.get("mempage-size"):
772 1                 extended["mempage-size"] = guest_epa.get("mempage-size")
773
774 1             if guest_epa.get("cpu-pinning-policy"):
775 1                 extended["cpu-pinning-policy"] = guest_epa.get("cpu-pinning-policy")
776
777 1             if guest_epa.get("cpu-thread-pinning-policy"):
778 1                 extended["cpu-thread-pinning-policy"] = guest_epa.get(
779                     "cpu-thread-pinning-policy"
780                 )
781
782 1             if guest_epa.get("numa-node-policy"):
783 1                 if guest_epa.get("numa-node-policy").get("mem-policy"):
784 1                     extended["mem-policy"] = guest_epa.get("numa-node-policy").get(
785                         "mem-policy"
786                     )
787
788 1             tmp_numa, epa_vcpu_set = Ns._process_guest_epa_cpu_pinning_params(
789                 guest_epa_quota=guest_epa,
790                 vcpu_count=int(target_flavor.get("vcpu-count", 1)),
791                 epa_vcpu_set=epa_vcpu_set,
792             )
793 1             for numa in numa_list:
794 1                 numa.update(tmp_numa)
795
796 1             extended.update(
797                 Ns._process_guest_epa_quota_params(
798                     guest_epa_quota=guest_epa,
799                     epa_vcpu_set=epa_vcpu_set,
800                 )
801             )
802
803 1         if numa:
804 1             extended["numas"] = numa_list
805
806 1         return extended
807
808 1     @staticmethod
809 1     def _process_flavor_params(
810         target_flavor: Dict[str, Any],
811         indata: Dict[str, Any],
812         vim_info: Dict[str, Any],
813         target_record_id: str,
814         **kwargs: Dict[str, Any],
815     ) -> Dict[str, Any]:
816         """[summary]
817
818         Args:
819             target_flavor (Dict[str, Any]): [description]
820             indata (Dict[str, Any]): [description]
821             vim_info (Dict[str, Any]): [description]
822             target_record_id (str): [description]
823
824         Returns:
825             Dict[str, Any]: [description]
826         """
827 1         db = kwargs.get("db")
828 1         target_vdur = {}
829
830 1         for vnf in indata.get("vnf", []):
831 1             for vdur in vnf.get("vdur", []):
832 1                 if vdur.get("ns-flavor-id") == target_flavor.get("id"):
833 1                     target_vdur = vdur
834
835 1         vim_flavor_id = (
836             target_vdur.get("additionalParams", {}).get("OSM", {}).get("vim_flavor_id")
837         )
838 1         if vim_flavor_id:  # vim-flavor-id was passed so flavor won't be created
839 1             return {"find_params": {"vim_flavor_id": vim_flavor_id}}
840
841 1         flavor_data = {
842             "disk": int(target_flavor["storage-gb"]),
843             "ram": int(target_flavor["memory-mb"]),
844             "vcpus": int(target_flavor["vcpu-count"]),
845         }
846
847 1         if db and isinstance(indata.get("vnf"), list):
848 1             vnfd_id = indata.get("vnf")[0].get("vnfd-id")
849 1             vnfd = db.get_one("vnfds", {"_id": vnfd_id})
850             # check if there is persistent root disk
851 1             for vdu in vnfd.get("vdu", ()):
852 1                 if vdu["name"] == target_vdur.get("vdu-name"):
853 1                     for vsd in vnfd.get("virtual-storage-desc", ()):
854 1                         if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
855 1                             root_disk = vsd
856 1                             if (
857                                 root_disk.get("type-of-storage")
858                                 == "persistent-storage:persistent-storage"
859                             ):
860 1                                 flavor_data["disk"] = 0
861
862 1         for storage in target_vdur.get("virtual-storages", []):
863 1             if (
864                 storage.get("type-of-storage")
865                 == "etsi-nfv-descriptors:ephemeral-storage"
866             ):
867 1                 flavor_data["ephemeral"] = int(storage.get("size-of-storage", 0))
868 1             elif storage.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
869 1                 flavor_data["swap"] = int(storage.get("size-of-storage", 0))
870
871 1         extended = Ns._process_epa_params(target_flavor)
872 1         if extended:
873 1             flavor_data["extended"] = extended
874
875 1         extra_dict = {"find_params": {"flavor_data": flavor_data}}
876 1         flavor_data_name = flavor_data.copy()
877 1         flavor_data_name["name"] = target_flavor["name"]
878 1         extra_dict["params"] = {"flavor_data": flavor_data_name}
879 1         return extra_dict
880
881 1     @staticmethod
882 1     def _prefix_ip_address(ip_address):
883 0         if "/" not in ip_address:
884 0             ip_address += "/32"
885 0         return ip_address
886
887 1     @staticmethod
888 1     def _process_ip_proto(ip_proto):
889 0         if ip_proto:
890 0             if ip_proto == 1:
891 0                 ip_proto = "icmp"
892 0             elif ip_proto == 6:
893 0                 ip_proto = "tcp"
894 0             elif ip_proto == 17:
895 0                 ip_proto = "udp"
896 0         return ip_proto
897
898 1     @staticmethod
899 1     def _process_classification_params(
900         target_classification: Dict[str, Any],
901         indata: Dict[str, Any],
902         vim_info: Dict[str, Any],
903         target_record_id: str,
904         **kwargs: Dict[str, Any],
905     ) -> Dict[str, Any]:
906         """[summary]
907
908         Args:
909             target_classification (Dict[str, Any]): Classification dictionary parameters that needs to be processed to create resource on VIM
910             indata (Dict[str, Any]): Deployment info
911             vim_info (Dict[str, Any]):To add items created by OSM on the VIM.
912             target_record_id (str): Task record ID.
913             **kwargs (Dict[str, Any]): Used to send additional information to the task.
914
915         Returns:
916             Dict[str, Any]: Return parameters required to create classification and Items on which classification is dependent.
917         """
918 1         vnfr_id = target_classification["vnfr_id"]
919 1         vdur_id = target_classification["vdur_id"]
920 1         port_index = target_classification["ingress_port_index"]
921 1         extra_dict = {}
922
923 1         classification_data = {
924             "name": target_classification["id"],
925             "source_port_range_min": target_classification["source-port"],
926             "source_port_range_max": target_classification["source-port"],
927             "destination_port_range_min": target_classification["destination-port"],
928             "destination_port_range_max": target_classification["destination-port"],
929         }
930
931 1         classification_data["source_ip_prefix"] = Ns._prefix_ip_address(
932             target_classification["source-ip-address"]
933         )
934
935 1         classification_data["destination_ip_prefix"] = Ns._prefix_ip_address(
936             target_classification["destination-ip-address"]
937         )
938
939 1         classification_data["protocol"] = Ns._process_ip_proto(
940             int(target_classification["ip-proto"])
941         )
942
943 1         db = kwargs.get("db")
944 1         vdu_text = Ns._get_vnfr_vdur_text(db, vnfr_id, vdur_id)
945
946 1         extra_dict = {"depends_on": [vdu_text]}
947
948 1         extra_dict = {"depends_on": [vdu_text]}
949 1         classification_data["logical_source_port"] = "TASK-" + vdu_text
950 1         classification_data["logical_source_port_index"] = port_index
951
952 1         extra_dict["params"] = classification_data
953
954 1         return extra_dict
955
956 1     @staticmethod
957 1     def _process_sfi_params(
958         target_sfi: Dict[str, Any],
959         indata: Dict[str, Any],
960         vim_info: Dict[str, Any],
961         target_record_id: str,
962         **kwargs: Dict[str, Any],
963     ) -> Dict[str, Any]:
964         """[summary]
965
966         Args:
967             target_sfi (Dict[str, Any]): SFI dictionary parameters that needs to be processed to create resource on VIM
968             indata (Dict[str, Any]): deployment info
969             vim_info (Dict[str, Any]): To add items created by OSM on the VIM.
970             target_record_id (str): Task record ID.
971             **kwargs (Dict[str, Any]): Used to send additional information to the task.
972
973         Returns:
974             Dict[str, Any]: Return parameters required to create SFI and Items on which SFI is dependent.
975         """
976
977 1         vnfr_id = target_sfi["vnfr_id"]
978 1         vdur_id = target_sfi["vdur_id"]
979
980 1         sfi_data = {
981             "name": target_sfi["id"],
982             "ingress_port_index": target_sfi["ingress_port_index"],
983             "egress_port_index": target_sfi["egress_port_index"],
984         }
985
986 1         db = kwargs.get("db")
987 1         vdu_text = Ns._get_vnfr_vdur_text(db, vnfr_id, vdur_id)
988
989 1         extra_dict = {"depends_on": [vdu_text]}
990 1         sfi_data["ingress_port"] = "TASK-" + vdu_text
991 1         sfi_data["egress_port"] = "TASK-" + vdu_text
992
993 1         extra_dict["params"] = sfi_data
994
995 1         return extra_dict
996
997 1     @staticmethod
998 1     def _get_vnfr_vdur_text(db, vnfr_id, vdur_id):
999 0         vnf_preffix = "vnfrs:{}".format(vnfr_id)
1000 0         db_vnfr = db.get_one("vnfrs", {"_id": vnfr_id})
1001 0         vdur_list = []
1002 0         vdu_text = ""
1003
1004 0         if db_vnfr:
1005 0             vdur_list = [
1006                 vdur["id"] for vdur in db_vnfr["vdur"] if vdur["vdu-id-ref"] == vdur_id
1007             ]
1008
1009 0         if vdur_list:
1010 0             vdu_text = vnf_preffix + ":vdur." + vdur_list[0]
1011
1012 0         return vdu_text
1013
1014 1     @staticmethod
1015 1     def _process_sf_params(
1016         target_sf: Dict[str, Any],
1017         indata: Dict[str, Any],
1018         vim_info: Dict[str, Any],
1019         target_record_id: str,
1020         **kwargs: Dict[str, Any],
1021     ) -> Dict[str, Any]:
1022         """[summary]
1023
1024         Args:
1025             target_sf (Dict[str, Any]): SF dictionary parameters that needs to be processed to create resource on VIM
1026             indata (Dict[str, Any]): Deployment info.
1027             vim_info (Dict[str, Any]):To add items created by OSM on the VIM.
1028             target_record_id (str): Task record ID.
1029             **kwargs (Dict[str, Any]): Used to send additional information to the task.
1030
1031         Returns:
1032             Dict[str, Any]: Return parameters required to create SF and Items on which SF is dependent.
1033         """
1034
1035 1         nsr_id = kwargs.get("nsr_id", "")
1036 1         sfis = target_sf["sfis"]
1037 1         ns_preffix = "nsrs:{}".format(nsr_id)
1038 1         extra_dict = {"depends_on": [], "params": []}
1039 1         sf_data = {"name": target_sf["id"], "sfis": sfis}
1040
1041 1         for count, sfi in enumerate(sfis):
1042 1             sfi_text = ns_preffix + ":sfi." + sfi
1043 1             sfis[count] = "TASK-" + sfi_text
1044 1             extra_dict["depends_on"].append(sfi_text)
1045
1046 1         extra_dict["params"] = sf_data
1047
1048 1         return extra_dict
1049
1050 1     @staticmethod
1051 1     def _process_sfp_params(
1052         target_sfp: Dict[str, Any],
1053         indata: Dict[str, Any],
1054         vim_info: Dict[str, Any],
1055         target_record_id: str,
1056         **kwargs: Dict[str, Any],
1057     ) -> Dict[str, Any]:
1058         """[summary]
1059
1060         Args:
1061             target_sfp (Dict[str, Any]): SFP dictionary parameters that needs to be processed to create resource on VIM.
1062             indata (Dict[str, Any]): Deployment info
1063             vim_info (Dict[str, Any]):To add items created by OSM on the VIM.
1064             target_record_id (str): Task record ID.
1065             **kwargs (Dict[str, Any]): Used to send additional information to the task.
1066
1067         Returns:
1068             Dict[str, Any]: Return parameters required to create SFP and Items on which SFP is dependent.
1069         """
1070
1071 1         nsr_id = kwargs.get("nsr_id")
1072 1         sfs = target_sfp["sfs"]
1073 1         classifications = target_sfp["classifications"]
1074 1         ns_preffix = "nsrs:{}".format(nsr_id)
1075 1         extra_dict = {"depends_on": [], "params": []}
1076 1         sfp_data = {
1077             "name": target_sfp["id"],
1078             "sfs": sfs,
1079             "classifications": classifications,
1080         }
1081
1082 1         for count, sf in enumerate(sfs):
1083 1             sf_text = ns_preffix + ":sf." + sf
1084 1             sfs[count] = "TASK-" + sf_text
1085 1             extra_dict["depends_on"].append(sf_text)
1086
1087 1         for count, classi in enumerate(classifications):
1088 1             classi_text = ns_preffix + ":classification." + classi
1089 1             classifications[count] = "TASK-" + classi_text
1090 1             extra_dict["depends_on"].append(classi_text)
1091
1092 1         extra_dict["params"] = sfp_data
1093
1094 1         return extra_dict
1095
1096 1     @staticmethod
1097 1     def _process_net_params(
1098         target_vld: Dict[str, Any],
1099         indata: Dict[str, Any],
1100         vim_info: Dict[str, Any],
1101         target_record_id: str,
1102         **kwargs: Dict[str, Any],
1103     ) -> Dict[str, Any]:
1104         """Function to process network parameters.
1105
1106         Args:
1107             target_vld (Dict[str, Any]): [description]
1108             indata (Dict[str, Any]): [description]
1109             vim_info (Dict[str, Any]): [description]
1110             target_record_id (str): [description]
1111
1112         Returns:
1113             Dict[str, Any]: [description]
1114         """
1115 1         extra_dict = {}
1116
1117 1         if vim_info.get("sdn"):
1118             # vnf_preffix = "vnfrs:{}".format(vnfr_id)
1119             # ns_preffix = "nsrs:{}".format(nsr_id)
1120             # remove the ending ".sdn
1121 1             vld_target_record_id, _, _ = target_record_id.rpartition(".")
1122 1             extra_dict["params"] = {
1123                 k: vim_info[k]
1124                 for k in ("sdn-ports", "target_vim", "vlds", "type")
1125                 if vim_info.get(k)
1126             }
1127
1128             # TODO needed to add target_id in the dependency.
1129 1             if vim_info.get("target_vim"):
1130 1                 extra_dict["depends_on"] = [
1131                     f"{vim_info.get('target_vim')} {vld_target_record_id}"
1132                 ]
1133
1134 1             return extra_dict
1135
1136 1         if vim_info.get("vim_network_name"):
1137 1             extra_dict["find_params"] = {
1138                 "filter_dict": {
1139                     "name": vim_info.get("vim_network_name"),
1140                 },
1141             }
1142 1         elif vim_info.get("vim_network_id"):
1143 1             extra_dict["find_params"] = {
1144                 "filter_dict": {
1145                     "id": vim_info.get("vim_network_id"),
1146                 },
1147             }
1148 1         elif target_vld.get("mgmt-network") and not vim_info.get("provider_network"):
1149 1             extra_dict["find_params"] = {
1150                 "mgmt": True,
1151                 "name": target_vld["id"],
1152             }
1153         else:
1154             # create
1155 1             extra_dict["params"] = {
1156                 "net_name": (
1157                     f"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
1158                 ),
1159                 "ip_profile": vim_info.get("ip_profile"),
1160                 "provider_network_profile": vim_info.get("provider_network"),
1161             }
1162
1163 1             if not target_vld.get("underlay"):
1164 1                 extra_dict["params"]["net_type"] = "bridge"
1165             else:
1166 1                 extra_dict["params"]["net_type"] = (
1167                     "ptp" if target_vld.get("type") == "ELINE" else "data"
1168                 )
1169
1170 1         return extra_dict
1171
1172 1     @staticmethod
1173 1     def find_persistent_root_volumes(
1174         vnfd: dict,
1175         target_vdu: dict,
1176         vdu_instantiation_volumes_list: list,
1177         disk_list: list,
1178     ) -> Dict[str, any]:
1179         """Find the persistent root volumes and add them to the disk_list
1180         by parsing the instantiation parameters.
1181
1182         Args:
1183             vnfd    (dict):                                 VNF descriptor
1184             target_vdu      (dict):                         processed VDU
1185             vdu_instantiation_volumes_list  (list):         instantiation parameters for the each VDU as a list
1186             disk_list   (list):                             to be filled up
1187
1188         Returns:
1189             persistent_root_disk    (dict):                 Details of persistent root disk
1190
1191         """
1192 1         persistent_root_disk = {}
1193         # There can be only one root disk, when we find it, it will return the result
1194
1195 1         for vdu, vsd in product(
1196             vnfd.get("vdu", ()), vnfd.get("virtual-storage-desc", ())
1197         ):
1198 1             if (
1199                 vdu["name"] == target_vdu["vdu-name"]
1200                 and vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]
1201             ):
1202 1                 root_disk = vsd
1203 1                 if (
1204                     root_disk.get("type-of-storage")
1205                     == "persistent-storage:persistent-storage"
1206                 ):
1207 1                     for vdu_volume in vdu_instantiation_volumes_list:
1208 1                         if (
1209                             vdu_volume["vim-volume-id"]
1210                             and root_disk["id"] == vdu_volume["name"]
1211                         ):
1212 1                             persistent_root_disk[vsd["id"]] = {
1213                                 "vim_volume_id": vdu_volume["vim-volume-id"],
1214                                 "image_id": vdu.get("sw-image-desc"),
1215                             }
1216
1217 1                             disk_list.append(persistent_root_disk[vsd["id"]])
1218
1219 1                             return persistent_root_disk
1220
1221                     else:
1222 1                         if root_disk.get("size-of-storage"):
1223 1                             persistent_root_disk[vsd["id"]] = {
1224                                 "image_id": vdu.get("sw-image-desc"),
1225                                 "size": root_disk.get("size-of-storage"),
1226                                 "keep": Ns.is_volume_keeping_required(root_disk),
1227                             }
1228
1229 1                             disk_list.append(persistent_root_disk[vsd["id"]])
1230
1231 1                             return persistent_root_disk
1232 1                 return persistent_root_disk
1233
1234 1     @staticmethod
1235 1     def find_persistent_volumes(
1236         persistent_root_disk: dict,
1237         target_vdu: dict,
1238         vdu_instantiation_volumes_list: list,
1239         disk_list: list,
1240     ) -> None:
1241         """Find the ordinary persistent volumes and add them to the disk_list
1242         by parsing the instantiation parameters.
1243
1244         Args:
1245             persistent_root_disk:   persistent root disk dictionary
1246             target_vdu: processed VDU
1247             vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1248             disk_list:  to be filled up
1249
1250         """
1251         # Find the ordinary volumes which are not added to the persistent_root_disk
1252 1         persistent_disk = {}
1253 1         for disk in target_vdu.get("virtual-storages", {}):
1254 1             if (
1255                 disk.get("type-of-storage") == "persistent-storage:persistent-storage"
1256                 and disk["id"] not in persistent_root_disk.keys()
1257             ):
1258 1                 for vdu_volume in vdu_instantiation_volumes_list:
1259 1                     if vdu_volume["vim-volume-id"] and disk["id"] == vdu_volume["name"]:
1260 1                         persistent_disk[disk["id"]] = {
1261                             "vim_volume_id": vdu_volume["vim-volume-id"],
1262                         }
1263 1                         disk_list.append(persistent_disk[disk["id"]])
1264
1265                 else:
1266 1                     if disk["id"] not in persistent_disk.keys():
1267 1                         persistent_disk[disk["id"]] = {
1268                             "size": disk.get("size-of-storage"),
1269                             "keep": Ns.is_volume_keeping_required(disk),
1270                         }
1271 1                         disk_list.append(persistent_disk[disk["id"]])
1272
1273 1     @staticmethod
1274 1     def is_volume_keeping_required(virtual_storage_desc: Dict[str, Any]) -> bool:
1275         """Function to decide keeping persistent volume
1276         upon VDU deletion.
1277
1278         Args:
1279             virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1280
1281         Returns:
1282             bool (True/False)
1283         """
1284
1285 1         if not virtual_storage_desc.get("vdu-storage-requirements"):
1286 1             return False
1287 1         for item in virtual_storage_desc.get("vdu-storage-requirements", {}):
1288 1             if item.get("key") == "keep-volume" and item.get("value").lower() == "true":
1289 1                 return True
1290 1         return False
1291
1292 1     @staticmethod
1293 1     def is_shared_volume(
1294         virtual_storage_desc: Dict[str, Any], vnfd_id: str
1295     ) -> (str, bool):
1296         """Function to decide if the volume type is multi attached or not .
1297
1298         Args:
1299             virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1300             vnfd_id (str): vnfd id
1301
1302         Returns:
1303             bool (True/False)
1304             name (str) New name if it is a multiattach disk
1305         """
1306
1307 1         if vdu_storage_requirements := virtual_storage_desc.get(
1308             "vdu-storage-requirements", {}
1309         ):
1310 0             for item in vdu_storage_requirements:
1311 0                 if (
1312                     item.get("key") == "multiattach"
1313                     and item.get("value").lower() == "true"
1314                 ):
1315 0                     name = f"shared-{virtual_storage_desc['id']}-{vnfd_id}"
1316 0                     return name, True
1317 1         return virtual_storage_desc["id"], False
1318
1319 1     @staticmethod
1320 1     def _sort_vdu_interfaces(target_vdu: dict) -> None:
1321         """Sort the interfaces according to position number.
1322
1323         Args:
1324             target_vdu  (dict):     Details of VDU to be created
1325
1326         """
1327         # If the position info is provided for all the interfaces, it will be sorted
1328         # according to position number ascendingly.
1329 1         sorted_interfaces = sorted(
1330             target_vdu["interfaces"],
1331             key=lambda x: (x.get("position") is None, x.get("position")),
1332         )
1333 1         target_vdu["interfaces"] = sorted_interfaces
1334
1335 1     @staticmethod
1336 1     def _partially_locate_vdu_interfaces(target_vdu: dict) -> None:
1337         """Only place the interfaces which has specific position.
1338
1339         Args:
1340             target_vdu  (dict):     Details of VDU to be created
1341
1342         """
1343         # If the position info is provided for some interfaces but not all of them, the interfaces
1344         # which has specific position numbers will be placed and others' positions will not be taken care.
1345 1         if any(
1346             i.get("position") + 1
1347             for i in target_vdu["interfaces"]
1348             if i.get("position") is not None
1349         ):
1350 1             n = len(target_vdu["interfaces"])
1351 1             sorted_interfaces = [-1] * n
1352 1             k, m = 0, 0
1353
1354 1             while k < n:
1355 1                 if target_vdu["interfaces"][k].get("position") is not None:
1356 1                     if any(i.get("position") == 0 for i in target_vdu["interfaces"]):
1357 1                         idx = target_vdu["interfaces"][k]["position"] + 1
1358                     else:
1359 1                         idx = target_vdu["interfaces"][k]["position"]
1360 1                     sorted_interfaces[idx - 1] = target_vdu["interfaces"][k]
1361 1                 k += 1
1362
1363 1             while m < n:
1364 1                 if target_vdu["interfaces"][m].get("position") is None:
1365 1                     idy = sorted_interfaces.index(-1)
1366 1                     sorted_interfaces[idy] = target_vdu["interfaces"][m]
1367 1                 m += 1
1368
1369 1             target_vdu["interfaces"] = sorted_interfaces
1370
1371 1     @staticmethod
1372 1     def _prepare_vdu_cloud_init(
1373         target_vdu: dict, vdu2cloud_init: dict, db: object, fs: object
1374     ) -> Dict:
1375         """Fill cloud_config dict with cloud init details.
1376
1377         Args:
1378             target_vdu  (dict):         Details of VDU to be created
1379             vdu2cloud_init  (dict):     Cloud init dict
1380             db  (object):               DB object
1381             fs  (object):               FS object
1382
1383         Returns:
1384             cloud_config (dict):        Cloud config details of VDU
1385
1386         """
1387         # cloud config
1388 1         cloud_config = {}
1389
1390 1         if target_vdu.get("cloud-init"):
1391 1             if target_vdu["cloud-init"] not in vdu2cloud_init:
1392 1                 vdu2cloud_init[target_vdu["cloud-init"]] = Ns._get_cloud_init(
1393                     db=db,
1394                     fs=fs,
1395                     location=target_vdu["cloud-init"],
1396                 )
1397
1398 1             cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
1399 1             cloud_config["user-data"] = Ns._parse_jinja2(
1400                 cloud_init_content=cloud_content_,
1401                 params=target_vdu.get("additionalParams"),
1402                 context=target_vdu["cloud-init"],
1403             )
1404
1405 1         if target_vdu.get("boot-data-drive"):
1406 1             cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
1407
1408 1         return cloud_config
1409
1410 1     @staticmethod
1411 1     def _check_vld_information_of_interfaces(
1412         interface: dict, ns_preffix: str, vnf_preffix: str
1413     ) -> Optional[str]:
1414         """Prepare the net_text by the virtual link information for vnf and ns level.
1415         Args:
1416             interface   (dict):         Interface details
1417             ns_preffix  (str):          Prefix of NS
1418             vnf_preffix (str):          Prefix of VNF
1419
1420         Returns:
1421             net_text    (str):          information of net
1422
1423         """
1424 1         net_text = ""
1425 1         if interface.get("ns-vld-id"):
1426 1             net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
1427 1         elif interface.get("vnf-vld-id"):
1428 1             net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
1429
1430 1         return net_text
1431
1432 1     @staticmethod
1433 1     def _prepare_interface_port_security(interface: dict) -> None:
1434         """
1435
1436         Args:
1437             interface   (dict):     Interface details
1438
1439         """
1440 1         if "port-security-enabled" in interface:
1441 1             interface["port_security"] = interface.pop("port-security-enabled")
1442
1443 1         if "port-security-disable-strategy" in interface:
1444 1             interface["port_security_disable_strategy"] = interface.pop(
1445                 "port-security-disable-strategy"
1446             )
1447
1448 1     @staticmethod
1449 1     def _create_net_item_of_interface(interface: dict, net_text: str) -> dict:
1450         """Prepare net item including name, port security, floating ip etc.
1451
1452         Args:
1453             interface   (dict):         Interface details
1454             net_text    (str):          information of net
1455
1456         Returns:
1457             net_item    (dict):         Dict including net details
1458
1459         """
1460
1461 1         net_item = {
1462             x: v
1463             for x, v in interface.items()
1464             if x
1465             in (
1466                 "name",
1467                 "vpci",
1468                 "port_security",
1469                 "port_security_disable_strategy",
1470                 "floating_ip",
1471             )
1472         }
1473 1         net_item["net_id"] = "TASK-" + net_text
1474 1         net_item["type"] = "virtual"
1475
1476 1         return net_item
1477
1478 1     @staticmethod
1479 1     def _prepare_type_of_interface(
1480         interface: dict, tasks_by_target_record_id: dict, net_text: str, net_item: dict
1481     ) -> None:
1482         """Fill the net item type by interface type such as SR-IOV, OM-MGMT, bridge etc.
1483
1484         Args:
1485             interface   (dict):                     Interface details
1486             tasks_by_target_record_id   (dict):     Task details
1487             net_text    (str):                      information of net
1488             net_item    (dict):                     Dict including net details
1489
1490         """
1491         # TODO mac_address: used for  SR-IOV ifaces #TODO for other types
1492         # TODO floating_ip: True/False (or it can be None)
1493
1494 1         if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1495             # Mark the net create task as type data
1496 1             if deep_get(
1497                 tasks_by_target_record_id,
1498                 net_text,
1499                 "extra_dict",
1500                 "params",
1501                 "net_type",
1502             ):
1503 1                 tasks_by_target_record_id[net_text]["extra_dict"]["params"][
1504                     "net_type"
1505                 ] = "data"
1506
1507 1             net_item["use"] = "data"
1508 1             net_item["model"] = interface["type"]
1509 1             net_item["type"] = interface["type"]
1510
1511 1         elif (
1512             interface.get("type") == "OM-MGMT"
1513             or interface.get("mgmt-interface")
1514             or interface.get("mgmt-vnf")
1515         ):
1516 1             net_item["use"] = "mgmt"
1517
1518         else:
1519             # If interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1520 1             net_item["use"] = "bridge"
1521 1             net_item["model"] = interface.get("type")
1522
1523 1     @staticmethod
1524 1     def _prepare_vdu_interfaces(
1525         target_vdu: dict,
1526         extra_dict: dict,
1527         ns_preffix: str,
1528         vnf_preffix: str,
1529         logger: object,
1530         tasks_by_target_record_id: dict,
1531         net_list: list,
1532     ) -> None:
1533         """Prepare the net_item and add net_list, add mgmt interface to extra_dict.
1534
1535         Args:
1536             target_vdu  (dict):                             VDU to be created
1537             extra_dict  (dict):                             Dictionary to be filled
1538             ns_preffix  (str):                              NS prefix as string
1539             vnf_preffix (str):                              VNF prefix as string
1540             logger  (object):                               Logger Object
1541             tasks_by_target_record_id  (dict):              Task details
1542             net_list    (list):                             Net list of VDU
1543         """
1544 1         for iface_index, interface in enumerate(target_vdu["interfaces"]):
1545 1             net_text = Ns._check_vld_information_of_interfaces(
1546                 interface, ns_preffix, vnf_preffix
1547             )
1548 1             if not net_text:
1549                 # Interface not connected to any vld
1550 1                 logger.error(
1551                     "Interface {} from vdu {} not connected to any vld".format(
1552                         iface_index, target_vdu["vdu-name"]
1553                     )
1554                 )
1555 1                 continue
1556
1557 1             extra_dict["depends_on"].append(net_text)
1558
1559 1             Ns._prepare_interface_port_security(interface)
1560
1561 1             net_item = Ns._create_net_item_of_interface(interface, net_text)
1562
1563 1             Ns._prepare_type_of_interface(
1564                 interface, tasks_by_target_record_id, net_text, net_item
1565             )
1566
1567 1             if interface.get("ip-address"):
1568 1                 net_item["ip_address"] = interface["ip-address"]
1569
1570 1             if interface.get("mac-address"):
1571 1                 net_item["mac_address"] = interface["mac-address"]
1572
1573 1             net_list.append(net_item)
1574
1575 1             if interface.get("mgmt-vnf"):
1576 0                 extra_dict["mgmt_vnf_interface"] = iface_index
1577 1             elif interface.get("mgmt-interface"):
1578 1                 extra_dict["mgmt_vdu_interface"] = iface_index
1579
1580 1     @staticmethod
1581 1     def _prepare_vdu_ssh_keys(
1582         target_vdu: dict, ro_nsr_public_key: dict, cloud_config: dict
1583     ) -> None:
1584         """Add ssh keys to cloud config.
1585
1586         Args:
1587            target_vdu  (dict):                 Details of VDU to be created
1588            ro_nsr_public_key   (dict):          RO NSR public Key
1589            cloud_config  (dict):               Cloud config details
1590
1591         """
1592 1         ssh_keys = []
1593
1594 1         if target_vdu.get("ssh-keys"):
1595 1             ssh_keys += target_vdu.get("ssh-keys")
1596
1597 1         if target_vdu.get("ssh-access-required"):
1598 1             ssh_keys.append(ro_nsr_public_key)
1599
1600 1         if ssh_keys:
1601 1             cloud_config["key-pairs"] = ssh_keys
1602
1603 1     @staticmethod
1604 1     def _select_persistent_root_disk(vsd: dict, vdu: dict) -> dict:
1605         """Selects the persistent root disk if exists.
1606         Args:
1607             vsd (dict):             Virtual storage descriptors in VNFD
1608             vdu (dict):             VNF descriptor
1609
1610         Returns:
1611             root_disk   (dict):     Selected persistent root disk
1612         """
1613 1         if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
1614 1             root_disk = vsd
1615 1             if root_disk.get(
1616                 "type-of-storage"
1617             ) == "persistent-storage:persistent-storage" and root_disk.get(
1618                 "size-of-storage"
1619             ):
1620 1                 return root_disk
1621
1622 1     @staticmethod
1623 1     def _add_persistent_root_disk_to_disk_list(
1624         vnfd: dict, target_vdu: dict, persistent_root_disk: dict, disk_list: list
1625     ) -> None:
1626         """Find the persistent root disk and add to disk list.
1627
1628         Args:
1629             vnfd  (dict):                           VNF descriptor
1630             target_vdu  (dict):                     Details of VDU to be created
1631             persistent_root_disk    (dict):         Details of persistent root disk
1632             disk_list   (list):                     Disks of VDU
1633
1634         """
1635 1         for vdu in vnfd.get("vdu", ()):
1636 1             if vdu["name"] == target_vdu["vdu-name"]:
1637 1                 for vsd in vnfd.get("virtual-storage-desc", ()):
1638 1                     root_disk = Ns._select_persistent_root_disk(vsd, vdu)
1639 1                     if not root_disk:
1640 1                         continue
1641
1642 1                     persistent_root_disk[vsd["id"]] = {
1643                         "image_id": vdu.get("sw-image-desc"),
1644                         "size": root_disk["size-of-storage"],
1645                         "keep": Ns.is_volume_keeping_required(root_disk),
1646                     }
1647 1                     disk_list.append(persistent_root_disk[vsd["id"]])
1648 1                     break
1649
1650 1     @staticmethod
1651 1     def _add_persistent_ordinary_disks_to_disk_list(
1652         target_vdu: dict,
1653         persistent_root_disk: dict,
1654         persistent_ordinary_disk: dict,
1655         disk_list: list,
1656         extra_dict: dict,
1657         vnf_id: str = None,
1658         nsr_id: str = None,
1659     ) -> None:
1660         """Fill the disk list by adding persistent ordinary disks.
1661
1662         Args:
1663             target_vdu  (dict):                     Details of VDU to be created
1664             persistent_root_disk    (dict):         Details of persistent root disk
1665             persistent_ordinary_disk    (dict):     Details of persistent ordinary disk
1666             disk_list   (list):                     Disks of VDU
1667
1668         """
1669 1         if target_vdu.get("virtual-storages"):
1670 1             for disk in target_vdu["virtual-storages"]:
1671 1                 if (
1672                     disk.get("type-of-storage")
1673                     == "persistent-storage:persistent-storage"
1674                     and disk["id"] not in persistent_root_disk.keys()
1675                 ):
1676 1                     name, multiattach = Ns.is_shared_volume(disk, vnf_id)
1677 1                     persistent_ordinary_disk[disk["id"]] = {
1678                         "name": name,
1679                         "size": disk["size-of-storage"],
1680                         "keep": Ns.is_volume_keeping_required(disk),
1681                         "multiattach": multiattach,
1682                     }
1683 1                     disk_list.append(persistent_ordinary_disk[disk["id"]])
1684 1                     if multiattach:  # VDU creation has to wait for shared volumes
1685 0                         extra_dict["depends_on"].append(
1686                             f"nsrs:{nsr_id}:shared-volumes.{name}"
1687                         )
1688
1689 1     @staticmethod
1690 1     def _prepare_vdu_affinity_group_list(
1691         target_vdu: dict, extra_dict: dict, ns_preffix: str
1692     ) -> List[Dict[str, any]]:
1693         """Process affinity group details to prepare affinity group list.
1694
1695         Args:
1696             target_vdu  (dict):     Details of VDU to be created
1697             extra_dict  (dict):     Dictionary to be filled
1698             ns_preffix  (str):      Prefix as string
1699
1700         Returns:
1701
1702             affinity_group_list (list):     Affinity group details
1703
1704         """
1705 1         affinity_group_list = []
1706
1707 1         if target_vdu.get("affinity-or-anti-affinity-group-id"):
1708 1             for affinity_group_id in target_vdu["affinity-or-anti-affinity-group-id"]:
1709 1                 affinity_group = {}
1710 1                 affinity_group_text = (
1711                     ns_preffix + ":affinity-or-anti-affinity-group." + affinity_group_id
1712                 )
1713
1714 1                 if not isinstance(extra_dict.get("depends_on"), list):
1715 1                     raise NsException("Invalid extra_dict format.")
1716
1717 1                 extra_dict["depends_on"].append(affinity_group_text)
1718 1                 affinity_group["affinity_group_id"] = "TASK-" + affinity_group_text
1719 1                 affinity_group_list.append(affinity_group)
1720
1721 1         return affinity_group_list
1722
1723 1     @staticmethod
1724 1     def _process_vdu_params(
1725         target_vdu: Dict[str, Any],
1726         indata: Dict[str, Any],
1727         vim_info: Dict[str, Any],
1728         target_record_id: str,
1729         **kwargs: Dict[str, Any],
1730     ) -> Dict[str, Any]:
1731         """Function to process VDU parameters.
1732
1733         Args:
1734             target_vdu (Dict[str, Any]): [description]
1735             indata (Dict[str, Any]): [description]
1736             vim_info (Dict[str, Any]): [description]
1737             target_record_id (str): [description]
1738
1739         Returns:
1740             Dict[str, Any]: [description]
1741         """
1742 1         vnfr_id = kwargs.get("vnfr_id")
1743 1         nsr_id = kwargs.get("nsr_id")
1744 1         vnfr = kwargs.get("vnfr")
1745 1         vdu2cloud_init = kwargs.get("vdu2cloud_init")
1746 1         tasks_by_target_record_id = kwargs.get("tasks_by_target_record_id")
1747 1         logger = kwargs.get("logger")
1748 1         db = kwargs.get("db")
1749 1         fs = kwargs.get("fs")
1750 1         ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1751
1752 1         vnf_preffix = "vnfrs:{}".format(vnfr_id)
1753 1         ns_preffix = "nsrs:{}".format(nsr_id)
1754 1         image_text = ns_preffix + ":image." + target_vdu["ns-image-id"]
1755 1         flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"]
1756 1         extra_dict = {"depends_on": [image_text, flavor_text]}
1757 1         net_list = []
1758 1         persistent_root_disk = {}
1759 1         persistent_ordinary_disk = {}
1760 1         vdu_instantiation_volumes_list = []
1761 1         disk_list = []
1762 1         vnfd_id = vnfr["vnfd-id"]
1763 1         vnfd = db.get_one("vnfds", {"_id": vnfd_id})
1764         # If the position info is provided for all the interfaces, it will be sorted
1765         # according to position number ascendingly.
1766 1         if all(
1767             True if i.get("position") is not None else False
1768             for i in target_vdu["interfaces"]
1769         ):
1770 1             Ns._sort_vdu_interfaces(target_vdu)
1771
1772         # If the position info is provided for some interfaces but not all of them, the interfaces
1773         # which has specific position numbers will be placed and others' positions will not be taken care.
1774         else:
1775 1             Ns._partially_locate_vdu_interfaces(target_vdu)
1776
1777         # If the position info is not provided for the interfaces, interfaces will be attached
1778         # according to the order in the VNFD.
1779 1         Ns._prepare_vdu_interfaces(
1780             target_vdu,
1781             extra_dict,
1782             ns_preffix,
1783             vnf_preffix,
1784             logger,
1785             tasks_by_target_record_id,
1786             net_list,
1787         )
1788
1789         # cloud config
1790 1         cloud_config = Ns._prepare_vdu_cloud_init(target_vdu, vdu2cloud_init, db, fs)
1791
1792         # Prepare VDU ssh keys
1793 1         Ns._prepare_vdu_ssh_keys(target_vdu, ro_nsr_public_key, cloud_config)
1794
1795 1         if target_vdu.get("additionalParams"):
1796 1             vdu_instantiation_volumes_list = (
1797                 target_vdu.get("additionalParams").get("OSM", {}).get("vdu_volumes")
1798             )
1799
1800 1         if vdu_instantiation_volumes_list:
1801             # Find the root volumes and add to the disk_list
1802 1             persistent_root_disk = Ns.find_persistent_root_volumes(
1803                 vnfd, target_vdu, vdu_instantiation_volumes_list, disk_list
1804             )
1805
1806             # Find the ordinary volumes which are not added to the persistent_root_disk
1807             # and put them to the disk list
1808 1             Ns.find_persistent_volumes(
1809                 persistent_root_disk,
1810                 target_vdu,
1811                 vdu_instantiation_volumes_list,
1812                 disk_list,
1813             )
1814
1815         else:
1816             # Vdu_instantiation_volumes_list is empty
1817             # First get add the persistent root disks to disk_list
1818 1             Ns._add_persistent_root_disk_to_disk_list(
1819                 vnfd, target_vdu, persistent_root_disk, disk_list
1820             )
1821             # Add the persistent non-root disks to disk_list
1822 1             Ns._add_persistent_ordinary_disks_to_disk_list(
1823                 target_vdu,
1824                 persistent_root_disk,
1825                 persistent_ordinary_disk,
1826                 disk_list,
1827                 extra_dict,
1828                 vnfd["id"],
1829                 nsr_id,
1830             )
1831
1832 1         affinity_group_list = Ns._prepare_vdu_affinity_group_list(
1833             target_vdu, extra_dict, ns_preffix
1834         )
1835
1836 1         extra_dict["params"] = {
1837             "name": "{}-{}-{}-{}".format(
1838                 indata["name"][:16],
1839                 vnfr["member-vnf-index-ref"][:16],
1840                 target_vdu["vdu-name"][:32],
1841                 target_vdu.get("count-index") or 0,
1842             ),
1843             "description": target_vdu["vdu-name"],
1844             "start": True,
1845             "image_id": "TASK-" + image_text,
1846             "flavor_id": "TASK-" + flavor_text,
1847             "affinity_group_list": affinity_group_list,
1848             "net_list": net_list,
1849             "cloud_config": cloud_config or None,
1850             "disk_list": disk_list,
1851             "availability_zone_index": None,  # TODO
1852             "availability_zone_list": None,  # TODO
1853         }
1854 1         return extra_dict
1855
1856 1     @staticmethod
1857 1     def _process_shared_volumes_params(
1858         target_shared_volume: Dict[str, Any],
1859         indata: Dict[str, Any],
1860         vim_info: Dict[str, Any],
1861         target_record_id: str,
1862         **kwargs: Dict[str, Any],
1863     ) -> Dict[str, Any]:
1864 0         extra_dict = {}
1865 0         shared_volume_data = {
1866             "size": target_shared_volume["size-of-storage"],
1867             "name": target_shared_volume["id"],
1868             "type": target_shared_volume["type-of-storage"],
1869             "keep": Ns.is_volume_keeping_required(target_shared_volume),
1870         }
1871 0         extra_dict["params"] = shared_volume_data
1872 0         return extra_dict
1873
1874 1     @staticmethod
1875 1     def _process_affinity_group_params(
1876         target_affinity_group: Dict[str, Any],
1877         indata: Dict[str, Any],
1878         vim_info: Dict[str, Any],
1879         target_record_id: str,
1880         **kwargs: Dict[str, Any],
1881     ) -> Dict[str, Any]:
1882         """Get affinity or anti-affinity group parameters.
1883
1884         Args:
1885             target_affinity_group (Dict[str, Any]): [description]
1886             indata (Dict[str, Any]): [description]
1887             vim_info (Dict[str, Any]): [description]
1888             target_record_id (str): [description]
1889
1890         Returns:
1891             Dict[str, Any]: [description]
1892         """
1893
1894 0         extra_dict = {}
1895 0         affinity_group_data = {
1896             "name": target_affinity_group["name"],
1897             "type": target_affinity_group["type"],
1898             "scope": target_affinity_group["scope"],
1899         }
1900
1901 0         if target_affinity_group.get("vim-affinity-group-id"):
1902 0             affinity_group_data["vim-affinity-group-id"] = target_affinity_group[
1903                 "vim-affinity-group-id"
1904             ]
1905
1906 0         extra_dict["params"] = {
1907             "affinity_group_data": affinity_group_data,
1908         }
1909 0         return extra_dict
1910
1911 1     @staticmethod
1912 1     def _process_recreate_vdu_params(
1913         existing_vdu: Dict[str, Any],
1914         db_nsr: Dict[str, Any],
1915         vim_info: Dict[str, Any],
1916         target_record_id: str,
1917         target_id: str,
1918         **kwargs: Dict[str, Any],
1919     ) -> Dict[str, Any]:
1920         """Function to process VDU parameters to recreate.
1921
1922         Args:
1923             existing_vdu (Dict[str, Any]): [description]
1924             db_nsr (Dict[str, Any]): [description]
1925             vim_info (Dict[str, Any]): [description]
1926             target_record_id (str): [description]
1927             target_id (str): [description]
1928
1929         Returns:
1930             Dict[str, Any]: [description]
1931         """
1932 0         vnfr = kwargs.get("vnfr")
1933 0         vdu2cloud_init = kwargs.get("vdu2cloud_init")
1934         # logger = kwargs.get("logger")
1935 0         db = kwargs.get("db")
1936 0         fs = kwargs.get("fs")
1937 0         ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1938
1939 0         extra_dict = {}
1940 0         net_list = []
1941
1942 0         vim_details = {}
1943 0         vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
1944
1945 0         if vim_details_text:
1946 0             vim_details = yaml.safe_load(f"{vim_details_text}")
1947
1948 0         for iface_index, interface in enumerate(existing_vdu["interfaces"]):
1949 0             if "port-security-enabled" in interface:
1950 0                 interface["port_security"] = interface.pop("port-security-enabled")
1951
1952 0             if "port-security-disable-strategy" in interface:
1953 0                 interface["port_security_disable_strategy"] = interface.pop(
1954                     "port-security-disable-strategy"
1955                 )
1956
1957 0             net_item = {
1958                 x: v
1959                 for x, v in interface.items()
1960                 if x
1961                 in (
1962                     "name",
1963                     "vpci",
1964                     "port_security",
1965                     "port_security_disable_strategy",
1966                     "floating_ip",
1967                 )
1968             }
1969 0             existing_ifaces = existing_vdu["vim_info"][target_id].get(
1970                 "interfaces_backup", []
1971             )
1972 0             net_id = next(
1973                 (
1974                     i["vim_net_id"]
1975                     for i in existing_ifaces
1976                     if i["ip_address"] == interface["ip-address"]
1977                 ),
1978                 None,
1979             )
1980
1981 0             net_item["net_id"] = net_id
1982 0             net_item["type"] = "virtual"
1983
1984             # TODO mac_address: used for  SR-IOV ifaces #TODO for other types
1985             # TODO floating_ip: True/False (or it can be None)
1986 0             if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1987 0                 net_item["use"] = "data"
1988 0                 net_item["model"] = interface["type"]
1989 0                 net_item["type"] = interface["type"]
1990 0             elif (
1991                 interface.get("type") == "OM-MGMT"
1992                 or interface.get("mgmt-interface")
1993                 or interface.get("mgmt-vnf")
1994             ):
1995 0                 net_item["use"] = "mgmt"
1996             else:
1997                 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1998 0                 net_item["use"] = "bridge"
1999 0                 net_item["model"] = interface.get("type")
2000
2001 0             if interface.get("ip-address"):
2002 0                 net_item["ip_address"] = interface["ip-address"]
2003
2004 0             if interface.get("mac-address"):
2005 0                 net_item["mac_address"] = interface["mac-address"]
2006
2007 0             net_list.append(net_item)
2008
2009 0             if interface.get("mgmt-vnf"):
2010 0                 extra_dict["mgmt_vnf_interface"] = iface_index
2011 0             elif interface.get("mgmt-interface"):
2012 0                 extra_dict["mgmt_vdu_interface"] = iface_index
2013
2014         # cloud config
2015 0         cloud_config = {}
2016
2017 0         if existing_vdu.get("cloud-init"):
2018 0             if existing_vdu["cloud-init"] not in vdu2cloud_init:
2019 0                 vdu2cloud_init[existing_vdu["cloud-init"]] = Ns._get_cloud_init(
2020                     db=db,
2021                     fs=fs,
2022                     location=existing_vdu["cloud-init"],
2023                 )
2024
2025 0             cloud_content_ = vdu2cloud_init[existing_vdu["cloud-init"]]
2026 0             cloud_config["user-data"] = Ns._parse_jinja2(
2027                 cloud_init_content=cloud_content_,
2028                 params=existing_vdu.get("additionalParams"),
2029                 context=existing_vdu["cloud-init"],
2030             )
2031
2032 0         if existing_vdu.get("boot-data-drive"):
2033 0             cloud_config["boot-data-drive"] = existing_vdu.get("boot-data-drive")
2034
2035 0         ssh_keys = []
2036
2037 0         if existing_vdu.get("ssh-keys"):
2038 0             ssh_keys += existing_vdu.get("ssh-keys")
2039
2040 0         if existing_vdu.get("ssh-access-required"):
2041 0             ssh_keys.append(ro_nsr_public_key)
2042
2043 0         if ssh_keys:
2044 0             cloud_config["key-pairs"] = ssh_keys
2045
2046 0         disk_list = []
2047 0         for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
2048 0             disk_list.append({"vim_id": vol_id["id"]})
2049
2050 0         affinity_group_list = []
2051
2052 0         if existing_vdu.get("affinity-or-anti-affinity-group-id"):
2053 0             affinity_group = {}
2054 0             for affinity_group_id in existing_vdu["affinity-or-anti-affinity-group-id"]:
2055 0                 for group in db_nsr.get("affinity-or-anti-affinity-group"):
2056 0                     if (
2057                         group["id"] == affinity_group_id
2058                         and group["vim_info"][target_id].get("vim_id", None) is not None
2059                     ):
2060 0                         affinity_group["affinity_group_id"] = group["vim_info"][
2061                             target_id
2062                         ].get("vim_id", None)
2063 0                         affinity_group_list.append(affinity_group)
2064
2065 0         extra_dict["params"] = {
2066             "name": "{}-{}-{}-{}".format(
2067                 db_nsr["name"][:16],
2068                 vnfr["member-vnf-index-ref"][:16],
2069                 existing_vdu["vdu-name"][:32],
2070                 existing_vdu.get("count-index") or 0,
2071             ),
2072             "description": existing_vdu["vdu-name"],
2073             "start": True,
2074             "image_id": vim_details["image"]["id"],
2075             "flavor_id": vim_details["flavor"]["id"],
2076             "affinity_group_list": affinity_group_list,
2077             "net_list": net_list,
2078             "cloud_config": cloud_config or None,
2079             "disk_list": disk_list,
2080             "availability_zone_index": None,  # TODO
2081             "availability_zone_list": None,  # TODO
2082         }
2083
2084 0         return extra_dict
2085
2086 1     def calculate_diff_items(
2087         self,
2088         indata,
2089         db_nsr,
2090         db_ro_nsr,
2091         db_nsr_update,
2092         item,
2093         tasks_by_target_record_id,
2094         action_id,
2095         nsr_id,
2096         task_index,
2097         vnfr_id=None,
2098         vnfr=None,
2099     ):
2100         """Function that returns the incremental changes (creation, deletion)
2101         related to a specific item `item` to be done. This function should be
2102         called for NS instantiation, NS termination, NS update to add a new VNF
2103         or a new VLD, remove a VNF or VLD, etc.
2104         Item can be `net`, `flavor`, `image` or `vdu`.
2105         It takes a list of target items from indata (which came from the REST API)
2106         and compares with the existing items from db_ro_nsr, identifying the
2107         incremental changes to be done. During the comparison, it calls the method
2108         `process_params` (which was passed as parameter, and is particular for each
2109         `item`)
2110
2111         Args:
2112             indata (Dict[str, Any]): deployment info
2113             db_nsr: NSR record from DB
2114             db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2115             db_nsr_update (Dict[str, Any]): NSR info to update in DB
2116             item (str): element to process (net, vdu...)
2117             tasks_by_target_record_id (Dict[str, Any]):
2118                 [<target_record_id>, <task>]
2119             action_id (str): action id
2120             nsr_id (str): NSR id
2121             task_index (number): task index to add to task name
2122             vnfr_id (str): VNFR id
2123             vnfr (Dict[str, Any]): VNFR info
2124
2125         Returns:
2126             List: list with the incremental changes (deletes, creates) for each item
2127             number: current task index
2128         """
2129
2130 0         diff_items = []
2131 0         db_path = ""
2132 0         db_record = ""
2133 0         target_list = []
2134 0         existing_list = []
2135 0         process_params = None
2136 0         vdu2cloud_init = indata.get("cloud_init_content") or {}
2137 0         ro_nsr_public_key = db_ro_nsr["public_key"]
2138         # According to the type of item, the path, the target_list,
2139         # the existing_list and the method to process params are set
2140 0         db_path = self.db_path_map[item]
2141 0         process_params = self.process_params_function_map[item]
2142
2143 0         if item in ("sfp", "classification", "sf", "sfi"):
2144 0             db_record = "nsrs:{}:{}".format(nsr_id, db_path)
2145 0             target_vnffg = indata.get("vnffg", [])[0]
2146 0             target_list = target_vnffg[item]
2147 0             existing_list = db_nsr.get(item, [])
2148 0         elif item in ("net", "vdu"):
2149             # This case is specific for the NS VLD (not applied to VDU)
2150 0             if vnfr is None:
2151 0                 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
2152 0                 target_list = indata.get("ns", []).get(db_path, [])
2153 0                 existing_list = db_nsr.get(db_path, [])
2154             # This case is common for VNF VLDs and VNF VDUs
2155             else:
2156 0                 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
2157 0                 target_vnf = next(
2158                     (vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id),
2159                     None,
2160                 )
2161 0                 target_list = target_vnf.get(db_path, []) if target_vnf else []
2162 0                 existing_list = vnfr.get(db_path, [])
2163 0         elif item in (
2164             "image",
2165             "flavor",
2166             "affinity-or-anti-affinity-group",
2167             "shared-volumes",
2168         ):
2169 0             db_record = "nsrs:{}:{}".format(nsr_id, db_path)
2170 0             target_list = indata.get(item, [])
2171 0             existing_list = db_nsr.get(item, [])
2172         else:
2173 0             raise NsException("Item not supported: {}", item)
2174         # ensure all the target_list elements has an "id". If not assign the index as id
2175 0         if target_list is None:
2176 0             target_list = []
2177 0         for target_index, tl in enumerate(target_list):
2178 0             if tl and not tl.get("id"):
2179 0                 tl["id"] = str(target_index)
2180         # step 1 items (networks,vdus,...) to be deleted/updated
2181 0         for item_index, existing_item in enumerate(existing_list):
2182 0             target_item = next(
2183                 (t for t in target_list if t["id"] == existing_item["id"]),
2184                 None,
2185             )
2186 0             for target_vim, existing_viminfo in existing_item.get(
2187                 "vim_info", {}
2188             ).items():
2189 0                 if existing_viminfo is None:
2190 0                     continue
2191
2192 0                 if target_item:
2193 0                     target_viminfo = target_item.get("vim_info", {}).get(target_vim)
2194                 else:
2195 0                     target_viminfo = None
2196
2197 0                 if target_viminfo is None:
2198                     # must be deleted
2199 0                     self._assign_vim(target_vim)
2200 0                     target_record_id = "{}.{}".format(db_record, existing_item["id"])
2201 0                     item_ = item
2202
2203 0                     if target_vim.startswith("sdn") or target_vim.startswith("wim"):
2204                         # item must be sdn-net instead of net if target_vim is a sdn
2205 0                         item_ = "sdn_net"
2206 0                         target_record_id += ".sdn"
2207
2208 0                     deployment_info = {
2209                         "action_id": action_id,
2210                         "nsr_id": nsr_id,
2211                         "task_index": task_index,
2212                     }
2213
2214 0                     diff_items.append(
2215                         {
2216                             "deployment_info": deployment_info,
2217                             "target_id": target_vim,
2218                             "item": item_,
2219                             "action": "DELETE",
2220                             "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
2221                             "target_record_id": target_record_id,
2222                         }
2223                     )
2224 0                     task_index += 1
2225
2226         # step 2 items (networks,vdus,...) to be created
2227 0         for target_item in target_list:
2228 0             item_index = -1
2229 0             for item_index, existing_item in enumerate(existing_list):
2230 0                 if existing_item["id"] == target_item["id"]:
2231 0                     break
2232             else:
2233 0                 item_index += 1
2234 0                 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
2235 0                 existing_list.append(target_item)
2236 0                 existing_item = None
2237
2238 0             for target_vim, target_viminfo in target_item.get("vim_info", {}).items():
2239 0                 existing_viminfo = None
2240
2241 0                 if existing_item:
2242 0                     existing_viminfo = existing_item.get("vim_info", {}).get(target_vim)
2243
2244 0                 if existing_viminfo is not None:
2245 0                     continue
2246
2247 0                 target_record_id = "{}.{}".format(db_record, target_item["id"])
2248 0                 item_ = item
2249
2250 0                 if target_vim.startswith("sdn") or target_vim.startswith("wim"):
2251                     # item must be sdn-net instead of net if target_vim is a sdn
2252 0                     item_ = "sdn_net"
2253 0                     target_record_id += ".sdn"
2254
2255 0                 kwargs = {}
2256 0                 self.logger.debug(
2257                     "ns.calculate_diff_items target_item={}".format(target_item)
2258                 )
2259 0                 if process_params == Ns._process_flavor_params:
2260 0                     kwargs.update(
2261                         {
2262                             "db": self.db,
2263                         }
2264                     )
2265 0                     self.logger.debug(
2266                         "calculate_diff_items for flavor kwargs={}".format(kwargs)
2267                     )
2268
2269 0                 if process_params == Ns._process_vdu_params:
2270 0                     self.logger.debug("calculate_diff_items self.fs={}".format(self.fs))
2271 0                     kwargs.update(
2272                         {
2273                             "vnfr_id": vnfr_id,
2274                             "nsr_id": nsr_id,
2275                             "vnfr": vnfr,
2276                             "vdu2cloud_init": vdu2cloud_init,
2277                             "tasks_by_target_record_id": tasks_by_target_record_id,
2278                             "logger": self.logger,
2279                             "db": self.db,
2280                             "fs": self.fs,
2281                             "ro_nsr_public_key": ro_nsr_public_key,
2282                         }
2283                     )
2284 0                     self.logger.debug("calculate_diff_items kwargs={}".format(kwargs))
2285 0                 if (
2286                     process_params == Ns._process_sfi_params
2287                     or Ns._process_sf_params
2288                     or Ns._process_classification_params
2289                     or Ns._process_sfp_params
2290                 ):
2291 0                     kwargs.update({"nsr_id": nsr_id, "db": self.db})
2292
2293 0                     self.logger.debug("calculate_diff_items kwargs={}".format(kwargs))
2294
2295 0                 extra_dict = process_params(
2296                     target_item,
2297                     indata,
2298                     target_viminfo,
2299                     target_record_id,
2300                     **kwargs,
2301                 )
2302 0                 self._assign_vim(target_vim)
2303
2304 0                 deployment_info = {
2305                     "action_id": action_id,
2306                     "nsr_id": nsr_id,
2307                     "task_index": task_index,
2308                 }
2309
2310 0                 new_item = {
2311                     "deployment_info": deployment_info,
2312                     "target_id": target_vim,
2313                     "item": item_,
2314                     "action": "CREATE",
2315                     "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
2316                     "target_record_id": target_record_id,
2317                     "extra_dict": extra_dict,
2318                     "common_id": target_item.get("common_id", None),
2319                 }
2320 0                 diff_items.append(new_item)
2321 0                 tasks_by_target_record_id[target_record_id] = new_item
2322 0                 task_index += 1
2323
2324 0                 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
2325
2326 0         return diff_items, task_index
2327
2328 1     def _process_vnfgd_sfp(self, sfp):
2329 1         processed_sfp = {}
2330         # getting sfp name, sfs and classifications in sfp to store it in processed_sfp
2331 1         processed_sfp["id"] = sfp["id"]
2332 1         sfs_in_sfp = [
2333             sf["id"] for sf in sfp.get("position-desc-id", [])[0].get("cp-profile-id")
2334         ]
2335 1         classifications_in_sfp = [
2336             classi["id"]
2337             for classi in sfp.get("position-desc-id", [])[0].get("match-attributes")
2338         ]
2339
2340         # creating a list of sfp with sfs and classifications
2341 1         processed_sfp["sfs"] = sfs_in_sfp
2342 1         processed_sfp["classifications"] = classifications_in_sfp
2343
2344 1         return processed_sfp
2345
2346 1     def _process_vnfgd_sf(self, sf):
2347 1         processed_sf = {}
2348         # getting name of sf
2349 1         processed_sf["id"] = sf["id"]
2350         # getting sfis in sf
2351 1         sfis_in_sf = sf.get("constituent-profile-elements")
2352 1         sorted_sfis = sorted(sfis_in_sf, key=lambda i: i["order"])
2353         # getting sfis names
2354 1         processed_sf["sfis"] = [sfi["id"] for sfi in sorted_sfis]
2355
2356 1         return processed_sf
2357
2358 1     def _process_vnfgd_sfi(self, sfi, db_vnfrs):
2359 1         processed_sfi = {}
2360         # getting name of sfi
2361 1         processed_sfi["id"] = sfi["id"]
2362
2363         # getting ports in sfi
2364 1         ingress_port = sfi["ingress-constituent-cpd-id"]
2365 1         egress_port = sfi["egress-constituent-cpd-id"]
2366 1         sfi_vnf_member_index = sfi["constituent-base-element-id"]
2367
2368 1         processed_sfi["ingress_port"] = ingress_port
2369 1         processed_sfi["egress_port"] = egress_port
2370
2371 1         all_vnfrs = db_vnfrs.values()
2372
2373 1         sfi_vnfr = [
2374             element
2375             for element in all_vnfrs
2376             if element["member-vnf-index-ref"] == sfi_vnf_member_index
2377         ]
2378 1         processed_sfi["vnfr_id"] = sfi_vnfr[0]["id"]
2379
2380 1         sfi_vnfr_cp = sfi_vnfr[0]["connection-point"]
2381
2382 1         ingress_port_index = [
2383             c for c, element in enumerate(sfi_vnfr_cp) if element["id"] == ingress_port
2384         ]
2385 1         ingress_port_index = ingress_port_index[0]
2386
2387 1         processed_sfi["vdur_id"] = sfi_vnfr_cp[ingress_port_index][
2388             "connection-point-vdu-id"
2389         ]
2390 1         processed_sfi["ingress_port_index"] = ingress_port_index
2391 1         processed_sfi["egress_port_index"] = ingress_port_index
2392
2393 1         if egress_port != ingress_port:
2394 0             egress_port_index = [
2395                 c
2396                 for c, element in enumerate(sfi_vnfr_cp)
2397                 if element["id"] == egress_port
2398             ]
2399 0             processed_sfi["egress_port_index"] = egress_port_index
2400
2401 1         return processed_sfi
2402
2403 1     def _process_vnfgd_classification(self, classification, db_vnfrs):
2404 1         processed_classification = {}
2405
2406 1         processed_classification = deepcopy(classification)
2407 1         classi_vnf_member_index = processed_classification[
2408             "constituent-base-element-id"
2409         ]
2410 1         logical_source_port = processed_classification["constituent-cpd-id"]
2411
2412 1         all_vnfrs = db_vnfrs.values()
2413
2414 1         classi_vnfr = [
2415             element
2416             for element in all_vnfrs
2417             if element["member-vnf-index-ref"] == classi_vnf_member_index
2418         ]
2419 1         processed_classification["vnfr_id"] = classi_vnfr[0]["id"]
2420
2421 1         classi_vnfr_cp = classi_vnfr[0]["connection-point"]
2422
2423 1         ingress_port_index = [
2424             c
2425             for c, element in enumerate(classi_vnfr_cp)
2426             if element["id"] == logical_source_port
2427         ]
2428 1         ingress_port_index = ingress_port_index[0]
2429
2430 1         processed_classification["ingress_port_index"] = ingress_port_index
2431 1         processed_classification["vdur_id"] = classi_vnfr_cp[ingress_port_index][
2432             "connection-point-vdu-id"
2433         ]
2434
2435 1         return processed_classification
2436
2437 1     def _update_db_nsr_with_vnffg(self, processed_vnffg, vim_info, nsr_id):
2438         """This method used to add viminfo dict to sfi, sf sfp and classification in indata and count info in db_nsr.
2439
2440         Args:
2441             processed_vnffg (Dict[str, Any]): deployment info
2442             vim_info (Dict): dictionary to store VIM resource information
2443             nsr_id (str): NSR id
2444
2445         Returns: None
2446         """
2447
2448 0         nsr_sfi = {}
2449 0         nsr_sf = {}
2450 0         nsr_sfp = {}
2451 0         nsr_classification = {}
2452 0         db_nsr_vnffg = deepcopy(processed_vnffg)
2453
2454 0         for count, sfi in enumerate(processed_vnffg["sfi"]):
2455 0             sfi["vim_info"] = vim_info
2456 0             sfi_count = "sfi.{}".format(count)
2457 0             nsr_sfi[sfi_count] = db_nsr_vnffg["sfi"][count]
2458
2459 0         self.db.set_list("nsrs", {"_id": nsr_id}, nsr_sfi)
2460
2461 0         for count, sf in enumerate(processed_vnffg["sf"]):
2462 0             sf["vim_info"] = vim_info
2463 0             sf_count = "sf.{}".format(count)
2464 0             nsr_sf[sf_count] = db_nsr_vnffg["sf"][count]
2465
2466 0         self.db.set_list("nsrs", {"_id": nsr_id}, nsr_sf)
2467
2468 0         for count, sfp in enumerate(processed_vnffg["sfp"]):
2469 0             sfp["vim_info"] = vim_info
2470 0             sfp_count = "sfp.{}".format(count)
2471 0             nsr_sfp[sfp_count] = db_nsr_vnffg["sfp"][count]
2472
2473 0         self.db.set_list("nsrs", {"_id": nsr_id}, nsr_sfp)
2474
2475 0         for count, classi in enumerate(processed_vnffg["classification"]):
2476 0             classi["vim_info"] = vim_info
2477 0             classification_count = "classification.{}".format(count)
2478 0             nsr_classification[classification_count] = db_nsr_vnffg["classification"][
2479                 count
2480             ]
2481
2482 0             self.db.set_list("nsrs", {"_id": nsr_id}, nsr_classification)
2483
2484 1     def process_vnffgd_descriptor(
2485         self,
2486         indata: dict,
2487         nsr_id: str,
2488         db_nsr: dict,
2489         db_vnfrs: dict,
2490     ) -> dict:
2491         """This method used to process vnffgd parameters from descriptor.
2492
2493         Args:
2494             indata (Dict[str, Any]): deployment info
2495             nsr_id (str): NSR id
2496             db_nsr: NSR record from DB
2497             db_vnfrs: VNFRS record from DB
2498
2499         Returns:
2500             Dict: Processed vnffg parameters.
2501         """
2502
2503 0         processed_vnffg = {}
2504 0         vnffgd = db_nsr.get("nsd", {}).get("vnffgd")
2505 0         vnf_list = indata.get("vnf", [])
2506 0         vim_text = ""
2507
2508 0         if vnf_list:
2509 0             vim_text = "vim:" + vnf_list[0].get("vim-account-id", "")
2510
2511 0         vim_info = {}
2512 0         vim_info[vim_text] = {}
2513 0         processed_sfps = []
2514 0         processed_classifications = []
2515 0         processed_sfs = []
2516 0         processed_sfis = []
2517
2518         # setting up intial empty entries for vnffg items in mongodb.
2519 0         self.db.set_list(
2520             "nsrs",
2521             {"_id": nsr_id},
2522             {
2523                 "sfi": [],
2524                 "sf": [],
2525                 "sfp": [],
2526                 "classification": [],
2527             },
2528         )
2529
2530 0         vnffg = vnffgd[0]
2531         # getting sfps
2532 0         sfps = vnffg.get("nfpd")
2533 0         for sfp in sfps:
2534 0             processed_sfp = self._process_vnfgd_sfp(sfp)
2535             # appending the list of processed sfps
2536 0             processed_sfps.append(processed_sfp)
2537
2538             # getting sfs in sfp
2539 0             sfs = sfp.get("position-desc-id")[0].get("cp-profile-id")
2540 0             for sf in sfs:
2541 0                 processed_sf = self._process_vnfgd_sf(sf)
2542
2543                 # appending the list of processed sfs
2544 0                 processed_sfs.append(processed_sf)
2545
2546                 # getting sfis in sf
2547 0                 sfis_in_sf = sf.get("constituent-profile-elements")
2548 0                 sorted_sfis = sorted(sfis_in_sf, key=lambda i: i["order"])
2549
2550 0                 for sfi in sorted_sfis:
2551 0                     processed_sfi = self._process_vnfgd_sfi(sfi, db_vnfrs)
2552
2553 0                     processed_sfis.append(processed_sfi)
2554
2555 0             classifications = sfp.get("position-desc-id")[0].get("match-attributes")
2556             # getting classifications from sfp
2557 0             for classification in classifications:
2558 0                 processed_classification = self._process_vnfgd_classification(
2559                     classification, db_vnfrs
2560                 )
2561
2562 0                 processed_classifications.append(processed_classification)
2563
2564 0         processed_vnffg["sfi"] = processed_sfis
2565 0         processed_vnffg["sf"] = processed_sfs
2566 0         processed_vnffg["classification"] = processed_classifications
2567 0         processed_vnffg["sfp"] = processed_sfps
2568
2569         # adding viminfo dict to sfi, sf sfp and classification
2570 0         self._update_db_nsr_with_vnffg(processed_vnffg, vim_info, nsr_id)
2571
2572         # updating indata with vnffg porcessed parameters
2573 0         indata["vnffg"].append(processed_vnffg)
2574
2575 1     def calculate_all_differences_to_deploy(
2576         self,
2577         indata,
2578         nsr_id,
2579         db_nsr,
2580         db_vnfrs,
2581         db_ro_nsr,
2582         db_nsr_update,
2583         db_vnfrs_update,
2584         action_id,
2585         tasks_by_target_record_id,
2586     ):
2587         """This method calculates the ordered list of items (`changes_list`)
2588         to be created and deleted.
2589
2590         Args:
2591             indata (Dict[str, Any]): deployment info
2592             nsr_id (str): NSR id
2593             db_nsr: NSR record from DB
2594             db_vnfrs: VNFRS record from DB
2595             db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2596             db_nsr_update (Dict[str, Any]): NSR info to update in DB
2597             db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
2598             action_id (str): action id
2599             tasks_by_target_record_id (Dict[str, Any]):
2600                 [<target_record_id>, <task>]
2601
2602         Returns:
2603             List: ordered list of items to be created and deleted.
2604         """
2605
2606 0         task_index = 0
2607         # set list with diffs:
2608 0         changes_list = []
2609
2610         # processing vnffg from descriptor parameter
2611 0         vnffgd = db_nsr.get("nsd").get("vnffgd")
2612 0         if vnffgd is not None:
2613 0             indata["vnffg"] = []
2614 0             vnf_list = indata["vnf"]
2615 0             processed_vnffg = {}
2616
2617             # in case of ns-delete
2618 0             if not vnf_list:
2619 0                 processed_vnffg["sfi"] = []
2620 0                 processed_vnffg["sf"] = []
2621 0                 processed_vnffg["classification"] = []
2622 0                 processed_vnffg["sfp"] = []
2623
2624 0                 indata["vnffg"].append(processed_vnffg)
2625
2626             else:
2627 0                 self.process_vnffgd_descriptor(
2628                     indata=indata,
2629                     nsr_id=nsr_id,
2630                     db_nsr=db_nsr,
2631                     db_vnfrs=db_vnfrs,
2632                 )
2633
2634                 # getting updated db_nsr having vnffg parameters
2635 0                 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2636
2637 0                 self.logger.debug(
2638                     "After processing vnffd parameters indata={} nsr={}".format(
2639                         indata, db_nsr
2640                     )
2641                 )
2642
2643 0             for item in ["sfp", "classification", "sf", "sfi"]:
2644 0                 self.logger.debug("process NS={} {}".format(nsr_id, item))
2645 0                 diff_items, task_index = self.calculate_diff_items(
2646                     indata=indata,
2647                     db_nsr=db_nsr,
2648                     db_ro_nsr=db_ro_nsr,
2649                     db_nsr_update=db_nsr_update,
2650                     item=item,
2651                     tasks_by_target_record_id=tasks_by_target_record_id,
2652                     action_id=action_id,
2653                     nsr_id=nsr_id,
2654                     task_index=task_index,
2655                     vnfr_id=None,
2656                 )
2657 0                 changes_list += diff_items
2658
2659         # NS vld, image and flavor
2660 0         for item in [
2661             "net",
2662             "image",
2663             "flavor",
2664             "affinity-or-anti-affinity-group",
2665         ]:
2666 0             self.logger.debug("process NS={} {}".format(nsr_id, item))
2667 0             diff_items, task_index = self.calculate_diff_items(
2668                 indata=indata,
2669                 db_nsr=db_nsr,
2670                 db_ro_nsr=db_ro_nsr,
2671                 db_nsr_update=db_nsr_update,
2672                 item=item,
2673                 tasks_by_target_record_id=tasks_by_target_record_id,
2674                 action_id=action_id,
2675                 nsr_id=nsr_id,
2676                 task_index=task_index,
2677                 vnfr_id=None,
2678             )
2679 0             changes_list += diff_items
2680
2681         # VNF vlds and vdus
2682 0         for vnfr_id, vnfr in db_vnfrs.items():
2683             # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
2684 0             for item in ["net", "vdu", "shared-volumes"]:
2685 0                 self.logger.debug("process VNF={} {}".format(vnfr_id, item))
2686 0                 diff_items, task_index = self.calculate_diff_items(
2687                     indata=indata,
2688                     db_nsr=db_nsr,
2689                     db_ro_nsr=db_ro_nsr,
2690                     db_nsr_update=db_vnfrs_update[vnfr["_id"]],
2691                     item=item,
2692                     tasks_by_target_record_id=tasks_by_target_record_id,
2693                     action_id=action_id,
2694                     nsr_id=nsr_id,
2695                     task_index=task_index,
2696                     vnfr_id=vnfr_id,
2697                     vnfr=vnfr,
2698                 )
2699 0                 changes_list += diff_items
2700
2701 0         return changes_list
2702
2703 1     def define_all_tasks(
2704         self,
2705         changes_list,
2706         db_new_tasks,
2707         tasks_by_target_record_id,
2708     ):
2709         """Function to create all the task structures obtanied from
2710         the method calculate_all_differences_to_deploy
2711
2712         Args:
2713             changes_list (List): ordered list of items to be created or deleted
2714             db_new_tasks (List): tasks list to be created
2715             action_id (str): action id
2716             tasks_by_target_record_id (Dict[str, Any]):
2717                 [<target_record_id>, <task>]
2718
2719         """
2720
2721 0         for change in changes_list:
2722 0             task = Ns._create_task(
2723                 deployment_info=change["deployment_info"],
2724                 target_id=change["target_id"],
2725                 item=change["item"],
2726                 action=change["action"],
2727                 target_record=change["target_record"],
2728                 target_record_id=change["target_record_id"],
2729                 extra_dict=change.get("extra_dict", None),
2730             )
2731
2732 0             self.logger.debug("ns.define_all_tasks task={}".format(task))
2733 0             tasks_by_target_record_id[change["target_record_id"]] = task
2734 0             db_new_tasks.append(task)
2735
2736 0             if change.get("common_id"):
2737 0                 task["common_id"] = change["common_id"]
2738
2739 1     def upload_all_tasks(
2740         self,
2741         db_new_tasks,
2742         now,
2743     ):
2744         """Function to save all tasks in the common DB
2745
2746         Args:
2747             db_new_tasks (List): tasks list to be created
2748             now (time): current time
2749
2750         """
2751
2752 0         nb_ro_tasks = 0  # for logging
2753
2754 0         for db_task in db_new_tasks:
2755 0             target_id = db_task.pop("target_id")
2756 0             common_id = db_task.get("common_id")
2757
2758             # Do not chek tasks with vim_status DELETED
2759             # because in manual heealing there are two tasks for the same vdur:
2760             #   one with vim_status deleted and the other one with the actual VM status.
2761
2762 0             if common_id:
2763 0                 if self.db.set_one(
2764                     "ro_tasks",
2765                     q_filter={
2766                         "target_id": target_id,
2767                         "tasks.common_id": common_id,
2768                         "vim_info.vim_status.ne": "DELETED",
2769                     },
2770                     update_dict={"to_check_at": now, "modified_at": now},
2771                     push={"tasks": db_task},
2772                     fail_on_empty=False,
2773                 ):
2774 0                     continue
2775
2776 0             if not self.db.set_one(
2777                 "ro_tasks",
2778                 q_filter={
2779                     "target_id": target_id,
2780                     "tasks.target_record": db_task["target_record"],
2781                     "vim_info.vim_status.ne": "DELETED",
2782                 },
2783                 update_dict={"to_check_at": now, "modified_at": now},
2784                 push={"tasks": db_task},
2785                 fail_on_empty=False,
2786             ):
2787                 # Create a ro_task
2788 0                 self.logger.debug("Updating database, Creating ro_tasks")
2789 0                 db_ro_task = Ns._create_ro_task(target_id, db_task)
2790 0                 nb_ro_tasks += 1
2791 0                 self.db.create("ro_tasks", db_ro_task)
2792
2793 0         self.logger.debug(
2794             "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2795                 nb_ro_tasks, len(db_new_tasks), db_new_tasks
2796             )
2797         )
2798
2799 1     def upload_recreate_tasks(
2800         self,
2801         db_new_tasks,
2802         now,
2803     ):
2804         """Function to save recreate tasks in the common DB
2805
2806         Args:
2807             db_new_tasks (List): tasks list to be created
2808             now (time): current time
2809
2810         """
2811
2812 0         nb_ro_tasks = 0  # for logging
2813
2814 0         for db_task in db_new_tasks:
2815 0             target_id = db_task.pop("target_id")
2816 0             self.logger.debug("target_id={} db_task={}".format(target_id, db_task))
2817
2818 0             action = db_task.get("action", None)
2819
2820             # Create a ro_task
2821 0             self.logger.debug("Updating database, Creating ro_tasks")
2822 0             db_ro_task = Ns._create_ro_task(target_id, db_task)
2823
2824             # If DELETE task: the associated created items should be removed
2825             # (except persistent volumes):
2826 0             if action == "DELETE":
2827 0                 db_ro_task["vim_info"]["created"] = True
2828 0                 db_ro_task["vim_info"]["created_items"] = db_task.get(
2829                     "created_items", {}
2830                 )
2831 0                 db_ro_task["vim_info"]["volumes_to_hold"] = db_task.get(
2832                     "volumes_to_hold", []
2833                 )
2834 0                 db_ro_task["vim_info"]["vim_id"] = db_task.get("vim_id", None)
2835
2836 0             nb_ro_tasks += 1
2837 0             self.logger.debug("upload_all_tasks db_ro_task={}".format(db_ro_task))
2838 0             self.db.create("ro_tasks", db_ro_task)
2839
2840 0         self.logger.debug(
2841             "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2842                 nb_ro_tasks, len(db_new_tasks), db_new_tasks
2843             )
2844         )
2845
2846 1     def _prepare_created_items_for_healing(
2847         self,
2848         nsr_id,
2849         target_record,
2850     ):
2851 0         created_items = {}
2852         # Get created_items from ro_task
2853 0         ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2854 0         for ro_task in ro_tasks:
2855 0             for task in ro_task["tasks"]:
2856 0                 if (
2857                     task["target_record"] == target_record
2858                     and task["action"] == "CREATE"
2859                     and ro_task["vim_info"]["created_items"]
2860                 ):
2861 0                     created_items = ro_task["vim_info"]["created_items"]
2862 0                     break
2863
2864 0         return created_items
2865
2866 1     def _prepare_persistent_volumes_for_healing(
2867         self,
2868         target_id,
2869         existing_vdu,
2870     ):
2871         # The associated volumes of the VM shouldn't be removed
2872 0         volumes_list = []
2873 0         vim_details = {}
2874 0         vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
2875 0         if vim_details_text:
2876 0             vim_details = yaml.safe_load(f"{vim_details_text}")
2877
2878 0             for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
2879 0                 volumes_list.append(vol_id["id"])
2880
2881 0         return volumes_list
2882
2883 1     def prepare_changes_to_recreate(
2884         self,
2885         indata,
2886         nsr_id,
2887         db_nsr,
2888         db_vnfrs,
2889         db_ro_nsr,
2890         action_id,
2891         tasks_by_target_record_id,
2892     ):
2893         """This method will obtain an ordered list of items (`changes_list`)
2894         to be created and deleted to meet the recreate request.
2895         """
2896
2897 0         self.logger.debug(
2898             "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id, indata)
2899         )
2900
2901 0         task_index = 0
2902         # set list with diffs:
2903 0         changes_list = []
2904 0         db_path = self.db_path_map["vdu"]
2905 0         target_list = indata.get("healVnfData", {})
2906 0         vdu2cloud_init = indata.get("cloud_init_content") or {}
2907 0         ro_nsr_public_key = db_ro_nsr["public_key"]
2908
2909         # Check each VNF of the target
2910 0         for target_vnf in target_list:
2911             # Find this VNF in the list from DB, raise exception if vnfInstanceId is not found
2912 0             vnfr_id = target_vnf["vnfInstanceId"]
2913 0             existing_vnf = db_vnfrs.get(vnfr_id, {})
2914 0             db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
2915             # vim_account_id = existing_vnf.get("vim-account-id", "")
2916
2917 0             target_vdus = target_vnf.get("additionalParams", {}).get("vdu", [])
2918             # Check each VDU of this VNF
2919 0             if not target_vdus:
2920                 # Create target_vdu_list from DB, if VDUs are not specified
2921 0                 target_vdus = []
2922 0                 for existing_vdu in existing_vnf.get("vdur"):
2923 0                     vdu_name = existing_vdu.get("vdu-name", None)
2924 0                     vdu_index = existing_vdu.get("count-index", 0)
2925 0                     vdu_to_be_healed = {"vdu-id": vdu_name, "count-index": vdu_index}
2926 0                     target_vdus.append(vdu_to_be_healed)
2927 0             for target_vdu in target_vdus:
2928 0                 vdu_name = target_vdu.get("vdu-id", None)
2929                 # For multi instance VDU count-index is mandatory
2930                 # For single session VDU count-indes is 0
2931 0                 count_index = target_vdu.get("count-index", 0)
2932 0                 item_index = 0
2933 0                 existing_instance = {}
2934 0                 if existing_vnf:
2935 0                     for instance in existing_vnf.get("vdur", {}):
2936 0                         if (
2937                             instance["vdu-name"] == vdu_name
2938                             and instance["count-index"] == count_index
2939                         ):
2940 0                             existing_instance = instance
2941 0                             break
2942                         else:
2943 0                             item_index += 1
2944
2945 0                 target_record_id = "{}.{}".format(db_record, existing_instance["id"])
2946
2947                 # The target VIM is the one already existing in DB to recreate
2948 0                 for target_vim, target_viminfo in existing_instance.get(
2949                     "vim_info", {}
2950                 ).items():
2951                     # step 1 vdu to be deleted
2952 0                     self._assign_vim(target_vim)
2953 0                     deployment_info = {
2954                         "action_id": action_id,
2955                         "nsr_id": nsr_id,
2956                         "task_index": task_index,
2957                     }
2958
2959 0                     target_record = f"{db_record}.{item_index}.vim_info.{target_vim}"
2960 0                     created_items = self._prepare_created_items_for_healing(
2961                         nsr_id, target_record
2962                     )
2963
2964 0                     volumes_to_hold = self._prepare_persistent_volumes_for_healing(
2965                         target_vim, existing_instance
2966                     )
2967
2968                     # Specific extra params for recreate tasks:
2969 0                     extra_dict = {
2970                         "created_items": created_items,
2971                         "vim_id": existing_instance["vim-id"],
2972                         "volumes_to_hold": volumes_to_hold,
2973                     }
2974
2975 0                     changes_list.append(
2976                         {
2977                             "deployment_info": deployment_info,
2978                             "target_id": target_vim,
2979                             "item": "vdu",
2980                             "action": "DELETE",
2981                             "target_record": target_record,
2982                             "target_record_id": target_record_id,
2983                             "extra_dict": extra_dict,
2984                         }
2985                     )
2986 0                     delete_task_id = f"{action_id}:{task_index}"
2987 0                     task_index += 1
2988
2989                     # step 2 vdu to be created
2990 0                     kwargs = {}
2991 0                     kwargs.update(
2992                         {
2993                             "vnfr_id": vnfr_id,
2994                             "nsr_id": nsr_id,
2995                             "vnfr": existing_vnf,
2996                             "vdu2cloud_init": vdu2cloud_init,
2997                             "tasks_by_target_record_id": tasks_by_target_record_id,
2998                             "logger": self.logger,
2999                             "db": self.db,
3000                             "fs": self.fs,
3001                             "ro_nsr_public_key": ro_nsr_public_key,
3002                         }
3003                     )
3004
3005 0                     extra_dict = self._process_recreate_vdu_params(
3006                         existing_instance,
3007                         db_nsr,
3008                         target_viminfo,
3009                         target_record_id,
3010                         target_vim,
3011                         **kwargs,
3012                     )
3013
3014                     # The CREATE task depens on the DELETE task
3015 0                     extra_dict["depends_on"] = [delete_task_id]
3016
3017                     # Add volumes created from created_items if any
3018                     # Ports should be deleted with delete task and automatically created with create task
3019 0                     volumes = {}
3020 0                     for k, v in created_items.items():
3021 0                         try:
3022 0                             k_item, _, k_id = k.partition(":")
3023 0                             if k_item == "volume":
3024 0                                 volumes[k] = v
3025 0                         except Exception as e:
3026 0                             self.logger.error(
3027                                 "Error evaluating created item {}: {}".format(k, e)
3028                             )
3029 0                     extra_dict["previous_created_volumes"] = volumes
3030
3031 0                     deployment_info = {
3032                         "action_id": action_id,
3033                         "nsr_id": nsr_id,
3034                         "task_index": task_index,
3035                     }
3036 0                     self._assign_vim(target_vim)
3037
3038 0                     new_item = {
3039                         "deployment_info": deployment_info,
3040                         "target_id": target_vim,
3041                         "item": "vdu",
3042                         "action": "CREATE",
3043                         "target_record": target_record,
3044                         "target_record_id": target_record_id,
3045                         "extra_dict": extra_dict,
3046                     }
3047 0                     changes_list.append(new_item)
3048 0                     tasks_by_target_record_id[target_record_id] = new_item
3049 0                     task_index += 1
3050
3051 0         return changes_list
3052
3053 1     def recreate(self, session, indata, version, nsr_id, *args, **kwargs):
3054 0         self.logger.debug("ns.recreate nsr_id={} indata={}".format(nsr_id, indata))
3055         # TODO: validate_input(indata, recreate_schema)
3056 0         action_id = indata.get("action_id", str(uuid4()))
3057         # get current deployment
3058 0         db_vnfrs = {}  # vnf's info indexed by _id
3059 0         step = ""
3060 0         logging_text = "Recreate nsr_id={} action_id={} indata={}".format(
3061             nsr_id, action_id, indata
3062         )
3063 0         self.logger.debug(logging_text + "Enter")
3064
3065 0         try:
3066 0             step = "Getting ns and vnfr record from db"
3067 0             db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
3068 0             db_new_tasks = []
3069 0             tasks_by_target_record_id = {}
3070             # read from db: vnf's of this ns
3071 0             step = "Getting vnfrs from db"
3072 0             db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
3073 0             self.logger.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list))
3074
3075 0             if not db_vnfrs_list:
3076 0                 raise NsException("Cannot obtain associated VNF for ns")
3077
3078 0             for vnfr in db_vnfrs_list:
3079 0                 db_vnfrs[vnfr["_id"]] = vnfr
3080
3081 0             now = time()
3082 0             db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
3083 0             self.logger.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr))
3084
3085 0             if not db_ro_nsr:
3086 0                 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
3087
3088 0             with self.write_lock:
3089                 # NS
3090 0                 step = "process NS elements"
3091 0                 changes_list = self.prepare_changes_to_recreate(
3092                     indata=indata,
3093                     nsr_id=nsr_id,
3094                     db_nsr=db_nsr,
3095                     db_vnfrs=db_vnfrs,
3096                     db_ro_nsr=db_ro_nsr,
3097                     action_id=action_id,
3098                     tasks_by_target_record_id=tasks_by_target_record_id,
3099                 )
3100
3101 0                 self.define_all_tasks(
3102                     changes_list=changes_list,
3103                     db_new_tasks=db_new_tasks,
3104                     tasks_by_target_record_id=tasks_by_target_record_id,
3105                 )
3106
3107                 # Delete all ro_tasks registered for the targets vdurs (target_record)
3108                 # If task of type CREATE exist then vim will try to get info form deleted VMs.
3109                 # So remove all task related to target record.
3110 0                 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
3111 0                 for change in changes_list:
3112 0                     for ro_task in ro_tasks:
3113 0                         for task in ro_task["tasks"]:
3114 0                             if task["target_record"] == change["target_record"]:
3115 0                                 self.db.del_one(
3116                                     "ro_tasks",
3117                                     q_filter={
3118                                         "_id": ro_task["_id"],
3119                                         "modified_at": ro_task["modified_at"],
3120                                     },
3121                                     fail_on_empty=False,
3122                                 )
3123
3124 0                 step = "Updating database, Appending tasks to ro_tasks"
3125 0                 self.upload_recreate_tasks(
3126                     db_new_tasks=db_new_tasks,
3127                     now=now,
3128                 )
3129
3130 0             self.logger.debug(
3131                 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3132             )
3133
3134 0             return (
3135                 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3136                 action_id,
3137                 True,
3138             )
3139 0         except Exception as e:
3140 0             if isinstance(e, (DbException, NsException)):
3141 0                 self.logger.error(
3142                     logging_text + "Exit Exception while '{}': {}".format(step, e)
3143                 )
3144             else:
3145 0                 e = traceback_format_exc()
3146 0                 self.logger.critical(
3147                     logging_text + "Exit Exception while '{}': {}".format(step, e),
3148                     exc_info=True,
3149                 )
3150
3151 0             raise NsException(e)
3152
3153 1     def deploy(self, session, indata, version, nsr_id, *args, **kwargs):
3154 0         self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata))
3155 0         validate_input(indata, deploy_schema)
3156 0         action_id = indata.get("action_id", str(uuid4()))
3157 0         task_index = 0
3158         # get current deployment
3159 0         db_nsr_update = {}  # update operation on nsrs
3160 0         db_vnfrs_update = {}
3161 0         db_vnfrs = {}  # vnf's info indexed by _id
3162 0         step = ""
3163 0         logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3164 0         self.logger.debug(logging_text + "Enter")
3165
3166 0         try:
3167 0             step = "Getting ns and vnfr record from db"
3168 0             db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
3169 0             self.logger.debug("ns.deploy: db_nsr={}".format(db_nsr))
3170 0             db_new_tasks = []
3171 0             tasks_by_target_record_id = {}
3172             # read from db: vnf's of this ns
3173 0             step = "Getting vnfrs from db"
3174 0             db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
3175
3176 0             if not db_vnfrs_list:
3177 0                 raise NsException("Cannot obtain associated VNF for ns")
3178
3179 0             for vnfr in db_vnfrs_list:
3180 0                 db_vnfrs[vnfr["_id"]] = vnfr
3181 0                 db_vnfrs_update[vnfr["_id"]] = {}
3182 0             self.logger.debug("ns.deploy db_vnfrs={}".format(db_vnfrs))
3183
3184 0             now = time()
3185 0             db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
3186
3187 0             if not db_ro_nsr:
3188 0                 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
3189
3190             # check that action_id is not in the list of actions. Suffixed with :index
3191 0             if action_id in db_ro_nsr["actions"]:
3192 0                 index = 1
3193
3194 0                 while True:
3195 0                     new_action_id = "{}:{}".format(action_id, index)
3196
3197 0                     if new_action_id not in db_ro_nsr["actions"]:
3198 0                         action_id = new_action_id
3199 0                         self.logger.debug(
3200                             logging_text
3201                             + "Changing action_id in use to {}".format(action_id)
3202                         )
3203 0                         break
3204
3205 0                     index += 1
3206
3207 0             def _process_action(indata):
3208                 nonlocal db_new_tasks
3209                 nonlocal action_id
3210                 nonlocal nsr_id
3211                 nonlocal task_index
3212                 nonlocal db_vnfrs
3213                 nonlocal db_ro_nsr
3214
3215 0                 if indata["action"]["action"] == "inject_ssh_key":
3216 0                     key = indata["action"].get("key")
3217 0                     user = indata["action"].get("user")
3218 0                     password = indata["action"].get("password")
3219
3220 0                     for vnf in indata.get("vnf", ()):
3221 0                         if vnf["_id"] not in db_vnfrs:
3222 0                             raise NsException("Invalid vnf={}".format(vnf["_id"]))
3223
3224 0                         db_vnfr = db_vnfrs[vnf["_id"]]
3225
3226 0                         for target_vdu in vnf.get("vdur", ()):
3227 0                             vdu_index, vdur = next(
3228                                 (
3229                                     i_v
3230                                     for i_v in enumerate(db_vnfr["vdur"])
3231                                     if i_v[1]["id"] == target_vdu["id"]
3232                                 ),
3233                                 (None, None),
3234                             )
3235
3236 0                             if not vdur:
3237 0                                 raise NsException(
3238                                     "Invalid vdu vnf={}.{}".format(
3239                                         vnf["_id"], target_vdu["id"]
3240                                     )
3241                                 )
3242
3243 0                             target_vim, vim_info = next(
3244                                 k_v for k_v in vdur["vim_info"].items()
3245                             )
3246 0                             self._assign_vim(target_vim)
3247 0                             target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
3248                                 vnf["_id"], vdu_index
3249                             )
3250 0                             extra_dict = {
3251                                 "depends_on": [
3252                                     "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
3253                                 ],
3254                                 "params": {
3255                                     "ip_address": vdur.get("ip-address"),
3256                                     "user": user,
3257                                     "key": key,
3258                                     "password": password,
3259                                     "private_key": db_ro_nsr["private_key"],
3260                                     "salt": db_ro_nsr["_id"],
3261                                     "schema_version": db_ro_nsr["_admin"][
3262                                         "schema_version"
3263                                     ],
3264                                 },
3265                             }
3266
3267 0                             deployment_info = {
3268                                 "action_id": action_id,
3269                                 "nsr_id": nsr_id,
3270                                 "task_index": task_index,
3271                             }
3272
3273 0                             task = Ns._create_task(
3274                                 deployment_info=deployment_info,
3275                                 target_id=target_vim,
3276                                 item="vdu",
3277                                 action="EXEC",
3278                                 target_record=target_record,
3279                                 target_record_id=None,
3280                                 extra_dict=extra_dict,
3281                             )
3282
3283 0                             task_index = deployment_info.get("task_index")
3284
3285 0                             db_new_tasks.append(task)
3286
3287 0             with self.write_lock:
3288 0                 if indata.get("action"):
3289 0                     _process_action(indata)
3290                 else:
3291                     # compute network differences
3292                     # NS
3293 0                     step = "process NS elements"
3294 0                     changes_list = self.calculate_all_differences_to_deploy(
3295                         indata=indata,
3296                         nsr_id=nsr_id,
3297                         db_nsr=db_nsr,
3298                         db_vnfrs=db_vnfrs,
3299                         db_ro_nsr=db_ro_nsr,
3300                         db_nsr_update=db_nsr_update,
3301                         db_vnfrs_update=db_vnfrs_update,
3302                         action_id=action_id,
3303                         tasks_by_target_record_id=tasks_by_target_record_id,
3304                     )
3305 0                     self.define_all_tasks(
3306                         changes_list=changes_list,
3307                         db_new_tasks=db_new_tasks,
3308                         tasks_by_target_record_id=tasks_by_target_record_id,
3309                     )
3310
3311 0                 step = "Updating database, Appending tasks to ro_tasks"
3312 0                 self.upload_all_tasks(
3313                     db_new_tasks=db_new_tasks,
3314                     now=now,
3315                 )
3316
3317 0                 step = "Updating database, nsrs"
3318 0                 if db_nsr_update:
3319 0                     self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
3320
3321 0                 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
3322 0                     if db_vnfr_update:
3323 0                         step = "Updating database, vnfrs={}".format(vnfr_id)
3324 0                         self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
3325
3326 0             self.logger.debug(
3327                 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3328             )
3329
3330 0             return (
3331                 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3332                 action_id,
3333                 True,
3334             )
3335 0         except Exception as e:
3336 0             if isinstance(e, (DbException, NsException)):
3337 0                 self.logger.error(
3338                     logging_text + "Exit Exception while '{}': {}".format(step, e)
3339                 )
3340             else:
3341 0                 e = traceback_format_exc()
3342 0                 self.logger.critical(
3343                     logging_text + "Exit Exception while '{}': {}".format(step, e),
3344                     exc_info=True,
3345                 )
3346
3347 0             raise NsException(e)
3348
3349 1     def delete(self, session, indata, version, nsr_id, *args, **kwargs):
3350 0         self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
3351         # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
3352
3353 0         with self.write_lock:
3354 0             try:
3355 0                 NsWorker.delete_db_tasks(self.db, nsr_id, None)
3356 0             except NsWorkerException as e:
3357 0                 raise NsException(e)
3358
3359 0         return None, None, True
3360
3361 1     def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
3362 0         self.logger.debug(
3363             "ns.status version={} nsr_id={}, action_id={} indata={}".format(
3364                 version, nsr_id, action_id, indata
3365             )
3366         )
3367 0         task_list = []
3368 0         done = 0
3369 0         total = 0
3370 0         ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
3371 0         global_status = "DONE"
3372 0         details = []
3373
3374 0         for ro_task in ro_tasks:
3375 0             for task in ro_task["tasks"]:
3376 0                 if task and task["action_id"] == action_id:
3377 0                     task_list.append(task)
3378 0                     total += 1
3379
3380 0                     if task["status"] == "FAILED":
3381 0                         global_status = "FAILED"
3382 0                         error_text = "Error at {} {}: {}".format(
3383                             task["action"].lower(),
3384                             task["item"],
3385                             ro_task["vim_info"].get("vim_message") or "unknown",
3386                         )
3387 0                         details.append(error_text)
3388 0                     elif task["status"] in ("SCHEDULED", "BUILD"):
3389 0                         if global_status != "FAILED":
3390 0                             global_status = "BUILD"
3391                     else:
3392 0                         done += 1
3393
3394 0         return_data = {
3395             "status": global_status,
3396             "details": ". ".join(details)
3397             if details
3398             else "progress {}/{}".format(done, total),
3399             "nsr_id": nsr_id,
3400             "action_id": action_id,
3401             "tasks": task_list,
3402         }
3403
3404 0         return return_data, None, True
3405
3406 1     def recreate_status(
3407         self, session, indata, version, nsr_id, action_id, *args, **kwargs
3408     ):
3409 0         return self.status(session, indata, version, nsr_id, action_id, *args, **kwargs)
3410
3411 1     def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
3412 0         print(
3413             "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
3414                 session, indata, version, nsr_id, action_id
3415             )
3416         )
3417
3418 0         return None, None, True
3419
3420 1     def rebuild_start_stop_task(
3421         self,
3422         vdu_id,
3423         vnf_id,
3424         vdu_index,
3425         action_id,
3426         nsr_id,
3427         task_index,
3428         target_vim,
3429         extra_dict,
3430     ):
3431 1         self._assign_vim(target_vim)
3432 1         target_record = "vnfrs:{}:vdur.{}.vim_info.{}".format(
3433             vnf_id, vdu_index, target_vim
3434         )
3435 1         target_record_id = "vnfrs:{}:vdur.{}".format(vnf_id, vdu_id)
3436 1         deployment_info = {
3437             "action_id": action_id,
3438             "nsr_id": nsr_id,
3439             "task_index": task_index,
3440         }
3441
3442 1         task = Ns._create_task(
3443             deployment_info=deployment_info,
3444             target_id=target_vim,
3445             item="update",
3446             action="EXEC",
3447             target_record=target_record,
3448             target_record_id=target_record_id,
3449             extra_dict=extra_dict,
3450         )
3451 1         return task
3452
3453 1     def rebuild_start_stop(
3454         self, session, action_dict, version, nsr_id, *args, **kwargs
3455     ):
3456 0         task_index = 0
3457 0         extra_dict = {}
3458 0         now = time()
3459 0         action_id = action_dict.get("action_id", str(uuid4()))
3460 0         step = ""
3461 0         logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3462 0         self.logger.debug(logging_text + "Enter")
3463
3464 0         action = list(action_dict.keys())[0]
3465 0         task_dict = action_dict.get(action)
3466 0         vim_vm_id = action_dict.get(action).get("vim_vm_id")
3467
3468 0         if action_dict.get("stop"):
3469 0             action = "shutoff"
3470 0         db_new_tasks = []
3471 0         try:
3472 0             step = "lock the operation & do task creation"
3473 0             with self.write_lock:
3474 0                 extra_dict["params"] = {
3475                     "vim_vm_id": vim_vm_id,
3476                     "action": action,
3477                 }
3478 0                 task = self.rebuild_start_stop_task(
3479                     task_dict["vdu_id"],
3480                     task_dict["vnf_id"],
3481                     task_dict["vdu_index"],
3482                     action_id,
3483                     nsr_id,
3484                     task_index,
3485                     task_dict["target_vim"],
3486                     extra_dict,
3487                 )
3488 0                 db_new_tasks.append(task)
3489 0                 step = "upload Task to db"
3490 0                 self.upload_all_tasks(
3491                     db_new_tasks=db_new_tasks,
3492                     now=now,
3493                 )
3494 0                 self.logger.debug(
3495                     logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3496                 )
3497 0                 return (
3498                     {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3499                     action_id,
3500                     True,
3501                 )
3502 0         except Exception as e:
3503 0             if isinstance(e, (DbException, NsException)):
3504 0                 self.logger.error(
3505                     logging_text + "Exit Exception while '{}': {}".format(step, e)
3506                 )
3507             else:
3508 0                 e = traceback_format_exc()
3509 0                 self.logger.critical(
3510                     logging_text + "Exit Exception while '{}': {}".format(step, e),
3511                     exc_info=True,
3512                 )
3513 0             raise NsException(e)
3514
3515 1     def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
3516 0         nsrs = self.db.get_list("nsrs", {})
3517 0         return_data = []
3518
3519 0         for ns in nsrs:
3520 0             return_data.append({"_id": ns["_id"], "name": ns["name"]})
3521
3522 0         return return_data, None, True
3523
3524 1     def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
3525 0         ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
3526 0         return_data = []
3527
3528 0         for ro_task in ro_tasks:
3529 0             for task in ro_task["tasks"]:
3530 0                 if task["action_id"] not in return_data:
3531 0                     return_data.append(task["action_id"])
3532
3533 0         return return_data, None, True
3534
3535 1     def migrate_task(
3536         self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
3537     ):
3538 1         target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
3539 1         self._assign_vim(target_vim)
3540 1         target_record = "vnfrs:{}:vdur.{}.vim_info.{}".format(
3541             vnf["_id"], vdu_index, target_vim
3542         )
3543 1         target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
3544 1         deployment_info = {
3545             "action_id": action_id,
3546             "nsr_id": nsr_id,
3547             "task_index": task_index,
3548         }
3549
3550 1         task = Ns._create_task(
3551             deployment_info=deployment_info,
3552             target_id=target_vim,
3553             item="migrate",
3554             action="EXEC",
3555             target_record=target_record,
3556             target_record_id=target_record_id,
3557             extra_dict=extra_dict,
3558         )
3559
3560 1         return task
3561
3562 1     def migrate(self, session, indata, version, nsr_id, *args, **kwargs):
3563 0         task_index = 0
3564 0         extra_dict = {}
3565 0         now = time()
3566 0         action_id = indata.get("action_id", str(uuid4()))
3567 0         step = ""
3568 0         logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3569 0         self.logger.debug(logging_text + "Enter")
3570 0         try:
3571 0             vnf_instance_id = indata["vnfInstanceId"]
3572 0             step = "Getting vnfrs from db"
3573 0             db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
3574 0             vdu = indata.get("vdu")
3575 0             migrateToHost = indata.get("migrateToHost")
3576 0             db_new_tasks = []
3577
3578 0             with self.write_lock:
3579 0                 if vdu is not None:
3580 0                     vdu_id = indata["vdu"]["vduId"]
3581 0                     vdu_count_index = indata["vdu"].get("vduCountIndex", 0)
3582 0                     for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3583 0                         if (
3584                             vdu["vdu-id-ref"] == vdu_id
3585                             and vdu["count-index"] == vdu_count_index
3586                         ):
3587 0                             extra_dict["params"] = {
3588                                 "vim_vm_id": vdu["vim-id"],
3589                                 "migrate_host": migrateToHost,
3590                                 "vdu_vim_info": vdu["vim_info"],
3591                             }
3592 0                             step = "Creating migration task for vdu:{}".format(vdu)
3593 0                             task = self.migrate_task(
3594                                 vdu,
3595                                 db_vnfr,
3596                                 vdu_index,
3597                                 action_id,
3598                                 nsr_id,
3599                                 task_index,
3600                                 extra_dict,
3601                             )
3602 0                             db_new_tasks.append(task)
3603 0                             task_index += 1
3604 0                             break
3605                 else:
3606 0                     for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3607 0                         extra_dict["params"] = {
3608                             "vim_vm_id": vdu["vim-id"],
3609                             "migrate_host": migrateToHost,
3610                             "vdu_vim_info": vdu["vim_info"],
3611                         }
3612 0                         step = "Creating migration task for vdu:{}".format(vdu)
3613 0                         task = self.migrate_task(
3614                             vdu,
3615                             db_vnfr,
3616                             vdu_index,
3617                             action_id,
3618                             nsr_id,
3619                             task_index,
3620                             extra_dict,
3621                         )
3622 0                         db_new_tasks.append(task)
3623 0                         task_index += 1
3624
3625 0                 self.upload_all_tasks(
3626                     db_new_tasks=db_new_tasks,
3627                     now=now,
3628                 )
3629
3630 0             self.logger.debug(
3631                 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3632             )
3633 0             return (
3634                 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3635                 action_id,
3636                 True,
3637             )
3638 0         except Exception as e:
3639 0             if isinstance(e, (DbException, NsException)):
3640 0                 self.logger.error(
3641                     logging_text + "Exit Exception while '{}': {}".format(step, e)
3642                 )
3643             else:
3644 0                 e = traceback_format_exc()
3645 0                 self.logger.critical(
3646                     logging_text + "Exit Exception while '{}': {}".format(step, e),
3647                     exc_info=True,
3648                 )
3649 0             raise NsException(e)
3650
3651 1     def verticalscale_task(
3652         self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
3653     ):
3654 1         target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
3655 1         self._assign_vim(target_vim)
3656 1         ns_preffix = "nsrs:{}".format(nsr_id)
3657 1         flavor_text = ns_preffix + ":flavor." + vdu["ns-flavor-id"]
3658 1         extra_dict["depends_on"] = [flavor_text]
3659 1         extra_dict["params"].update({"flavor_id": "TASK-" + flavor_text})
3660 1         target_record = "vnfrs:{}:vdur.{}.vim_info.{}".format(
3661             vnf["_id"], vdu_index, target_vim
3662         )
3663 1         target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
3664 1         deployment_info = {
3665             "action_id": action_id,
3666             "nsr_id": nsr_id,
3667             "task_index": task_index,
3668         }
3669
3670 1         task = Ns._create_task(
3671             deployment_info=deployment_info,
3672             target_id=target_vim,
3673             item="verticalscale",
3674             action="EXEC",
3675             target_record=target_record,
3676             target_record_id=target_record_id,
3677             extra_dict=extra_dict,
3678         )
3679 1         return task
3680
3681 1     def verticalscale_flavor_task(
3682         self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
3683     ):
3684 0         target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
3685 0         self._assign_vim(target_vim)
3686 0         db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
3687 0         target_record = "nsrs:{}:flavor.{}.vim_info.{}".format(
3688             nsr_id, len(db_nsr["flavor"]) - 1, target_vim
3689         )
3690 0         target_record_id = "nsrs:{}:flavor.{}".format(nsr_id, len(db_nsr["flavor"]) - 1)
3691 0         deployment_info = {
3692             "action_id": action_id,
3693             "nsr_id": nsr_id,
3694             "task_index": task_index,
3695         }
3696 0         task = Ns._create_task(
3697             deployment_info=deployment_info,
3698             target_id=target_vim,
3699             item="flavor",
3700             action="CREATE",
3701             target_record=target_record,
3702             target_record_id=target_record_id,
3703             extra_dict=extra_dict,
3704         )
3705 0         return task
3706
3707 1     def verticalscale(self, session, indata, version, nsr_id, *args, **kwargs):
3708 0         task_index = 0
3709 0         extra_dict = {}
3710 0         flavor_extra_dict = {}
3711 0         now = time()
3712 0         action_id = indata.get("action_id", str(uuid4()))
3713 0         step = ""
3714 0         logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3715 0         self.logger.debug(logging_text + "Enter")
3716 0         try:
3717 0             VnfFlavorData = indata.get("changeVnfFlavorData")
3718 0             vnf_instance_id = VnfFlavorData["vnfInstanceId"]
3719 0             step = "Getting vnfrs from db"
3720 0             db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
3721 0             vduid = VnfFlavorData["additionalParams"]["vduid"]
3722 0             vduCountIndex = VnfFlavorData["additionalParams"]["vduCountIndex"]
3723 0             virtualMemory = VnfFlavorData["additionalParams"]["virtualMemory"]
3724 0             numVirtualCpu = VnfFlavorData["additionalParams"]["numVirtualCpu"]
3725 0             sizeOfStorage = VnfFlavorData["additionalParams"]["sizeOfStorage"]
3726 0             flavor_dict = {
3727                 "name": vduid + "-flv",
3728                 "ram": virtualMemory,
3729                 "vcpus": numVirtualCpu,
3730                 "disk": sizeOfStorage,
3731             }
3732 0             flavor_data = {
3733                 "ram": virtualMemory,
3734                 "vcpus": numVirtualCpu,
3735                 "disk": sizeOfStorage,
3736             }
3737 0             flavor_extra_dict["find_params"] = {"flavor_data": flavor_data}
3738 0             flavor_extra_dict["params"] = {"flavor_data": flavor_dict}
3739 0             db_new_tasks = []
3740 0             step = "Creating Tasks for vertical scaling"
3741 0             with self.write_lock:
3742 0                 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3743 0                     if (
3744                         vdu["vdu-id-ref"] == vduid
3745                         and vdu["count-index"] == vduCountIndex
3746                     ):
3747 0                         extra_dict["params"] = {
3748                             "vim_vm_id": vdu["vim-id"],
3749                             "flavor_dict": flavor_dict,
3750                             "vdu-id-ref": vdu["vdu-id-ref"],
3751                             "count-index": vdu["count-index"],
3752                             "vnf_instance_id": vnf_instance_id,
3753                         }
3754 0                         task = self.verticalscale_flavor_task(
3755                             vdu,
3756                             db_vnfr,
3757                             vdu_index,
3758                             action_id,
3759                             nsr_id,
3760                             task_index,
3761                             flavor_extra_dict,
3762                         )
3763 0                         db_new_tasks.append(task)
3764 0                         task_index += 1
3765 0                         task = self.verticalscale_task(
3766                             vdu,
3767                             db_vnfr,
3768                             vdu_index,
3769                             action_id,
3770                             nsr_id,
3771                             task_index,
3772                             extra_dict,
3773                         )
3774 0                         db_new_tasks.append(task)
3775 0                         task_index += 1
3776 0                         break
3777 0                 self.upload_all_tasks(
3778                     db_new_tasks=db_new_tasks,
3779                     now=now,
3780                 )
3781 0             self.logger.debug(
3782                 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3783             )
3784 0             return (
3785                 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3786                 action_id,
3787                 True,
3788             )
3789 0         except Exception as e:
3790 0             if isinstance(e, (DbException, NsException)):
3791 0                 self.logger.error(
3792                     logging_text + "Exit Exception while '{}': {}".format(step, e)
3793                 )
3794             else:
3795 0                 e = traceback_format_exc()
3796 0                 self.logger.critical(
3797                     logging_text + "Exit Exception while '{}': {}".format(step, e),
3798                     exc_info=True,
3799                 )
3800 0             raise NsException(e)