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