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