Fixes multiattach issues in attaching and deletion
[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 flavor_data = {
822 "disk": int(target_flavor["storage-gb"]),
823 "ram": int(target_flavor["memory-mb"]),
824 "vcpus": int(target_flavor["vcpu-count"]),
825 }
826
827 for vnf in indata.get("vnf", []):
828 for vdur in vnf.get("vdur", []):
829 if vdur.get("ns-flavor-id") == target_flavor.get("id"):
830 target_vdur = vdur
831
832 if db and isinstance(indata.get("vnf"), list):
833 vnfd_id = indata.get("vnf")[0].get("vnfd-id")
834 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
835 # check if there is persistent root disk
836 for vdu in vnfd.get("vdu", ()):
837 if vdu["name"] == target_vdur.get("vdu-name"):
838 for vsd in vnfd.get("virtual-storage-desc", ()):
839 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
840 root_disk = vsd
841 if (
842 root_disk.get("type-of-storage")
843 == "persistent-storage:persistent-storage"
844 ):
845 flavor_data["disk"] = 0
846
847 for storage in target_vdur.get("virtual-storages", []):
848 if (
849 storage.get("type-of-storage")
850 == "etsi-nfv-descriptors:ephemeral-storage"
851 ):
852 flavor_data["ephemeral"] = int(storage.get("size-of-storage", 0))
853 elif storage.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
854 flavor_data["swap"] = int(storage.get("size-of-storage", 0))
855
856 extended = Ns._process_epa_params(target_flavor)
857 if extended:
858 flavor_data["extended"] = extended
859
860 extra_dict = {"find_params": {"flavor_data": flavor_data}}
861 flavor_data_name = flavor_data.copy()
862 flavor_data_name["name"] = target_flavor["name"]
863 extra_dict["params"] = {"flavor_data": flavor_data_name}
864 return extra_dict
865
866 @staticmethod
867 def _process_net_params(
868 target_vld: Dict[str, Any],
869 indata: Dict[str, Any],
870 vim_info: Dict[str, Any],
871 target_record_id: str,
872 **kwargs: Dict[str, Any],
873 ) -> Dict[str, Any]:
874 """Function to process network parameters.
875
876 Args:
877 target_vld (Dict[str, Any]): [description]
878 indata (Dict[str, Any]): [description]
879 vim_info (Dict[str, Any]): [description]
880 target_record_id (str): [description]
881
882 Returns:
883 Dict[str, Any]: [description]
884 """
885 extra_dict = {}
886
887 if vim_info.get("sdn"):
888 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
889 # ns_preffix = "nsrs:{}".format(nsr_id)
890 # remove the ending ".sdn
891 vld_target_record_id, _, _ = target_record_id.rpartition(".")
892 extra_dict["params"] = {
893 k: vim_info[k]
894 for k in ("sdn-ports", "target_vim", "vlds", "type")
895 if vim_info.get(k)
896 }
897
898 # TODO needed to add target_id in the dependency.
899 if vim_info.get("target_vim"):
900 extra_dict["depends_on"] = [
901 f"{vim_info.get('target_vim')} {vld_target_record_id}"
902 ]
903
904 return extra_dict
905
906 if vim_info.get("vim_network_name"):
907 extra_dict["find_params"] = {
908 "filter_dict": {
909 "name": vim_info.get("vim_network_name"),
910 },
911 }
912 elif vim_info.get("vim_network_id"):
913 extra_dict["find_params"] = {
914 "filter_dict": {
915 "id": vim_info.get("vim_network_id"),
916 },
917 }
918 elif target_vld.get("mgmt-network") and not vim_info.get("provider_network"):
919 extra_dict["find_params"] = {
920 "mgmt": True,
921 "name": target_vld["id"],
922 }
923 else:
924 # create
925 extra_dict["params"] = {
926 "net_name": (
927 f"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
928 ),
929 "ip_profile": vim_info.get("ip_profile"),
930 "provider_network_profile": vim_info.get("provider_network"),
931 }
932
933 if not target_vld.get("underlay"):
934 extra_dict["params"]["net_type"] = "bridge"
935 else:
936 extra_dict["params"]["net_type"] = (
937 "ptp" if target_vld.get("type") == "ELINE" else "data"
938 )
939
940 return extra_dict
941
942 @staticmethod
943 def find_persistent_root_volumes(
944 vnfd: dict,
945 target_vdu: dict,
946 vdu_instantiation_volumes_list: list,
947 disk_list: list,
948 ) -> Dict[str, any]:
949 """Find the persistent root volumes and add them to the disk_list
950 by parsing the instantiation parameters.
951
952 Args:
953 vnfd (dict): VNF descriptor
954 target_vdu (dict): processed VDU
955 vdu_instantiation_volumes_list (list): instantiation parameters for the each VDU as a list
956 disk_list (list): to be filled up
957
958 Returns:
959 persistent_root_disk (dict): Details of persistent root disk
960
961 """
962 persistent_root_disk = {}
963 # There can be only one root disk, when we find it, it will return the result
964
965 for vdu, vsd in product(
966 vnfd.get("vdu", ()), vnfd.get("virtual-storage-desc", ())
967 ):
968 if (
969 vdu["name"] == target_vdu["vdu-name"]
970 and vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]
971 ):
972 root_disk = vsd
973 if (
974 root_disk.get("type-of-storage")
975 == "persistent-storage:persistent-storage"
976 ):
977 for vdu_volume in vdu_instantiation_volumes_list:
978 if (
979 vdu_volume["vim-volume-id"]
980 and root_disk["id"] == vdu_volume["name"]
981 ):
982 persistent_root_disk[vsd["id"]] = {
983 "vim_volume_id": vdu_volume["vim-volume-id"],
984 "image_id": vdu.get("sw-image-desc"),
985 }
986
987 disk_list.append(persistent_root_disk[vsd["id"]])
988
989 return persistent_root_disk
990
991 else:
992 if root_disk.get("size-of-storage"):
993 persistent_root_disk[vsd["id"]] = {
994 "image_id": vdu.get("sw-image-desc"),
995 "size": root_disk.get("size-of-storage"),
996 "keep": Ns.is_volume_keeping_required(root_disk),
997 }
998
999 disk_list.append(persistent_root_disk[vsd["id"]])
1000
1001 return persistent_root_disk
1002
1003 @staticmethod
1004 def find_persistent_volumes(
1005 persistent_root_disk: dict,
1006 target_vdu: dict,
1007 vdu_instantiation_volumes_list: list,
1008 disk_list: list,
1009 ) -> None:
1010 """Find the ordinary persistent volumes and add them to the disk_list
1011 by parsing the instantiation parameters.
1012
1013 Args:
1014 persistent_root_disk: persistent root disk dictionary
1015 target_vdu: processed VDU
1016 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1017 disk_list: to be filled up
1018
1019 """
1020 # Find the ordinary volumes which are not added to the persistent_root_disk
1021 persistent_disk = {}
1022 for disk in target_vdu.get("virtual-storages", {}):
1023 if (
1024 disk.get("type-of-storage") == "persistent-storage:persistent-storage"
1025 and disk["id"] not in persistent_root_disk.keys()
1026 ):
1027 for vdu_volume in vdu_instantiation_volumes_list:
1028 if vdu_volume["vim-volume-id"] and disk["id"] == vdu_volume["name"]:
1029 persistent_disk[disk["id"]] = {
1030 "vim_volume_id": vdu_volume["vim-volume-id"],
1031 }
1032 disk_list.append(persistent_disk[disk["id"]])
1033
1034 else:
1035 if disk["id"] not in persistent_disk.keys():
1036 persistent_disk[disk["id"]] = {
1037 "size": disk.get("size-of-storage"),
1038 "keep": Ns.is_volume_keeping_required(disk),
1039 }
1040 disk_list.append(persistent_disk[disk["id"]])
1041
1042 @staticmethod
1043 def is_volume_keeping_required(virtual_storage_desc: Dict[str, Any]) -> bool:
1044 """Function to decide keeping persistent volume
1045 upon VDU deletion.
1046
1047 Args:
1048 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1049
1050 Returns:
1051 bool (True/False)
1052 """
1053
1054 if not virtual_storage_desc.get("vdu-storage-requirements"):
1055 return False
1056 for item in virtual_storage_desc.get("vdu-storage-requirements", {}):
1057 if item.get("key") == "keep-volume" and item.get("value").lower() == "true":
1058 return True
1059 return False
1060
1061 @staticmethod
1062 def is_shared_volume(
1063 virtual_storage_desc: Dict[str, Any], vnfd_id: str
1064 ) -> (str, bool):
1065 """Function to decide if the volume type is multi attached or not .
1066
1067 Args:
1068 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1069 vnfd_id (str): vnfd id
1070
1071 Returns:
1072 bool (True/False)
1073 name (str) New name if it is a multiattach disk
1074 """
1075
1076 if vdu_storage_requirements := virtual_storage_desc.get(
1077 "vdu-storage-requirements", {}
1078 ):
1079 for item in vdu_storage_requirements:
1080 if (
1081 item.get("key") == "multiattach"
1082 and item.get("value").lower() == "true"
1083 ):
1084 name = f"shared-{virtual_storage_desc['id']}-{vnfd_id}"
1085 return name, True
1086 return virtual_storage_desc["id"], False
1087
1088 @staticmethod
1089 def _sort_vdu_interfaces(target_vdu: dict) -> None:
1090 """Sort the interfaces according to position number.
1091
1092 Args:
1093 target_vdu (dict): Details of VDU to be created
1094
1095 """
1096 # If the position info is provided for all the interfaces, it will be sorted
1097 # according to position number ascendingly.
1098 sorted_interfaces = sorted(
1099 target_vdu["interfaces"],
1100 key=lambda x: (x.get("position") is None, x.get("position")),
1101 )
1102 target_vdu["interfaces"] = sorted_interfaces
1103
1104 @staticmethod
1105 def _partially_locate_vdu_interfaces(target_vdu: dict) -> None:
1106 """Only place the interfaces which has specific position.
1107
1108 Args:
1109 target_vdu (dict): Details of VDU to be created
1110
1111 """
1112 # If the position info is provided for some interfaces but not all of them, the interfaces
1113 # which has specific position numbers will be placed and others' positions will not be taken care.
1114 if any(
1115 i.get("position") + 1
1116 for i in target_vdu["interfaces"]
1117 if i.get("position") is not None
1118 ):
1119 n = len(target_vdu["interfaces"])
1120 sorted_interfaces = [-1] * n
1121 k, m = 0, 0
1122
1123 while k < n:
1124 if target_vdu["interfaces"][k].get("position") is not None:
1125 if any(i.get("position") == 0 for i in target_vdu["interfaces"]):
1126 idx = target_vdu["interfaces"][k]["position"] + 1
1127 else:
1128 idx = target_vdu["interfaces"][k]["position"]
1129 sorted_interfaces[idx - 1] = target_vdu["interfaces"][k]
1130 k += 1
1131
1132 while m < n:
1133 if target_vdu["interfaces"][m].get("position") is None:
1134 idy = sorted_interfaces.index(-1)
1135 sorted_interfaces[idy] = target_vdu["interfaces"][m]
1136 m += 1
1137
1138 target_vdu["interfaces"] = sorted_interfaces
1139
1140 @staticmethod
1141 def _prepare_vdu_cloud_init(
1142 target_vdu: dict, vdu2cloud_init: dict, db: object, fs: object
1143 ) -> Dict:
1144 """Fill cloud_config dict with cloud init details.
1145
1146 Args:
1147 target_vdu (dict): Details of VDU to be created
1148 vdu2cloud_init (dict): Cloud init dict
1149 db (object): DB object
1150 fs (object): FS object
1151
1152 Returns:
1153 cloud_config (dict): Cloud config details of VDU
1154
1155 """
1156 # cloud config
1157 cloud_config = {}
1158
1159 if target_vdu.get("cloud-init"):
1160 if target_vdu["cloud-init"] not in vdu2cloud_init:
1161 vdu2cloud_init[target_vdu["cloud-init"]] = Ns._get_cloud_init(
1162 db=db,
1163 fs=fs,
1164 location=target_vdu["cloud-init"],
1165 )
1166
1167 cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
1168 cloud_config["user-data"] = Ns._parse_jinja2(
1169 cloud_init_content=cloud_content_,
1170 params=target_vdu.get("additionalParams"),
1171 context=target_vdu["cloud-init"],
1172 )
1173
1174 if target_vdu.get("boot-data-drive"):
1175 cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
1176
1177 return cloud_config
1178
1179 @staticmethod
1180 def _check_vld_information_of_interfaces(
1181 interface: dict, ns_preffix: str, vnf_preffix: str
1182 ) -> Optional[str]:
1183 """Prepare the net_text by the virtual link information for vnf and ns level.
1184 Args:
1185 interface (dict): Interface details
1186 ns_preffix (str): Prefix of NS
1187 vnf_preffix (str): Prefix of VNF
1188
1189 Returns:
1190 net_text (str): information of net
1191
1192 """
1193 net_text = ""
1194 if interface.get("ns-vld-id"):
1195 net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
1196 elif interface.get("vnf-vld-id"):
1197 net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
1198
1199 return net_text
1200
1201 @staticmethod
1202 def _prepare_interface_port_security(interface: dict) -> None:
1203 """
1204
1205 Args:
1206 interface (dict): Interface details
1207
1208 """
1209 if "port-security-enabled" in interface:
1210 interface["port_security"] = interface.pop("port-security-enabled")
1211
1212 if "port-security-disable-strategy" in interface:
1213 interface["port_security_disable_strategy"] = interface.pop(
1214 "port-security-disable-strategy"
1215 )
1216
1217 @staticmethod
1218 def _create_net_item_of_interface(interface: dict, net_text: str) -> dict:
1219 """Prepare net item including name, port security, floating ip etc.
1220
1221 Args:
1222 interface (dict): Interface details
1223 net_text (str): information of net
1224
1225 Returns:
1226 net_item (dict): Dict including net details
1227
1228 """
1229
1230 net_item = {
1231 x: v
1232 for x, v in interface.items()
1233 if x
1234 in (
1235 "name",
1236 "vpci",
1237 "port_security",
1238 "port_security_disable_strategy",
1239 "floating_ip",
1240 )
1241 }
1242 net_item["net_id"] = "TASK-" + net_text
1243 net_item["type"] = "virtual"
1244
1245 return net_item
1246
1247 @staticmethod
1248 def _prepare_type_of_interface(
1249 interface: dict, tasks_by_target_record_id: dict, net_text: str, net_item: dict
1250 ) -> None:
1251 """Fill the net item type by interface type such as SR-IOV, OM-MGMT, bridge etc.
1252
1253 Args:
1254 interface (dict): Interface details
1255 tasks_by_target_record_id (dict): Task details
1256 net_text (str): information of net
1257 net_item (dict): Dict including net details
1258
1259 """
1260 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1261 # TODO floating_ip: True/False (or it can be None)
1262
1263 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1264 # Mark the net create task as type data
1265 if deep_get(
1266 tasks_by_target_record_id,
1267 net_text,
1268 "extra_dict",
1269 "params",
1270 "net_type",
1271 ):
1272 tasks_by_target_record_id[net_text]["extra_dict"]["params"][
1273 "net_type"
1274 ] = "data"
1275
1276 net_item["use"] = "data"
1277 net_item["model"] = interface["type"]
1278 net_item["type"] = interface["type"]
1279
1280 elif (
1281 interface.get("type") == "OM-MGMT"
1282 or interface.get("mgmt-interface")
1283 or interface.get("mgmt-vnf")
1284 ):
1285 net_item["use"] = "mgmt"
1286
1287 else:
1288 # If interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1289 net_item["use"] = "bridge"
1290 net_item["model"] = interface.get("type")
1291
1292 @staticmethod
1293 def _prepare_vdu_interfaces(
1294 target_vdu: dict,
1295 extra_dict: dict,
1296 ns_preffix: str,
1297 vnf_preffix: str,
1298 logger: object,
1299 tasks_by_target_record_id: dict,
1300 net_list: list,
1301 ) -> None:
1302 """Prepare the net_item and add net_list, add mgmt interface to extra_dict.
1303
1304 Args:
1305 target_vdu (dict): VDU to be created
1306 extra_dict (dict): Dictionary to be filled
1307 ns_preffix (str): NS prefix as string
1308 vnf_preffix (str): VNF prefix as string
1309 logger (object): Logger Object
1310 tasks_by_target_record_id (dict): Task details
1311 net_list (list): Net list of VDU
1312 """
1313 for iface_index, interface in enumerate(target_vdu["interfaces"]):
1314 net_text = Ns._check_vld_information_of_interfaces(
1315 interface, ns_preffix, vnf_preffix
1316 )
1317 if not net_text:
1318 # Interface not connected to any vld
1319 logger.error(
1320 "Interface {} from vdu {} not connected to any vld".format(
1321 iface_index, target_vdu["vdu-name"]
1322 )
1323 )
1324 continue
1325
1326 extra_dict["depends_on"].append(net_text)
1327
1328 Ns._prepare_interface_port_security(interface)
1329
1330 net_item = Ns._create_net_item_of_interface(interface, net_text)
1331
1332 Ns._prepare_type_of_interface(
1333 interface, tasks_by_target_record_id, net_text, net_item
1334 )
1335
1336 if interface.get("ip-address"):
1337 net_item["ip_address"] = interface["ip-address"]
1338
1339 if interface.get("mac-address"):
1340 net_item["mac_address"] = interface["mac-address"]
1341
1342 net_list.append(net_item)
1343
1344 if interface.get("mgmt-vnf"):
1345 extra_dict["mgmt_vnf_interface"] = iface_index
1346 elif interface.get("mgmt-interface"):
1347 extra_dict["mgmt_vdu_interface"] = iface_index
1348
1349 @staticmethod
1350 def _prepare_vdu_ssh_keys(
1351 target_vdu: dict, ro_nsr_public_key: dict, cloud_config: dict
1352 ) -> None:
1353 """Add ssh keys to cloud config.
1354
1355 Args:
1356 target_vdu (dict): Details of VDU to be created
1357 ro_nsr_public_key (dict): RO NSR public Key
1358 cloud_config (dict): Cloud config details
1359
1360 """
1361 ssh_keys = []
1362
1363 if target_vdu.get("ssh-keys"):
1364 ssh_keys += target_vdu.get("ssh-keys")
1365
1366 if target_vdu.get("ssh-access-required"):
1367 ssh_keys.append(ro_nsr_public_key)
1368
1369 if ssh_keys:
1370 cloud_config["key-pairs"] = ssh_keys
1371
1372 @staticmethod
1373 def _select_persistent_root_disk(vsd: dict, vdu: dict) -> dict:
1374 """Selects the persistent root disk if exists.
1375 Args:
1376 vsd (dict): Virtual storage descriptors in VNFD
1377 vdu (dict): VNF descriptor
1378
1379 Returns:
1380 root_disk (dict): Selected persistent root disk
1381 """
1382 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
1383 root_disk = vsd
1384 if root_disk.get(
1385 "type-of-storage"
1386 ) == "persistent-storage:persistent-storage" and root_disk.get(
1387 "size-of-storage"
1388 ):
1389 return root_disk
1390
1391 @staticmethod
1392 def _add_persistent_root_disk_to_disk_list(
1393 vnfd: dict, target_vdu: dict, persistent_root_disk: dict, disk_list: list
1394 ) -> None:
1395 """Find the persistent root disk and add to disk list.
1396
1397 Args:
1398 vnfd (dict): VNF descriptor
1399 target_vdu (dict): Details of VDU to be created
1400 persistent_root_disk (dict): Details of persistent root disk
1401 disk_list (list): Disks of VDU
1402
1403 """
1404 for vdu in vnfd.get("vdu", ()):
1405 if vdu["name"] == target_vdu["vdu-name"]:
1406 for vsd in vnfd.get("virtual-storage-desc", ()):
1407 root_disk = Ns._select_persistent_root_disk(vsd, vdu)
1408 if not root_disk:
1409 continue
1410
1411 persistent_root_disk[vsd["id"]] = {
1412 "image_id": vdu.get("sw-image-desc"),
1413 "size": root_disk["size-of-storage"],
1414 "keep": Ns.is_volume_keeping_required(root_disk),
1415 }
1416 disk_list.append(persistent_root_disk[vsd["id"]])
1417 break
1418
1419 @staticmethod
1420 def _add_persistent_ordinary_disks_to_disk_list(
1421 target_vdu: dict,
1422 persistent_root_disk: dict,
1423 persistent_ordinary_disk: dict,
1424 disk_list: list,
1425 extra_dict: dict,
1426 vnf_id: str = None,
1427 nsr_id: str = None,
1428 ) -> None:
1429 """Fill the disk list by adding persistent ordinary disks.
1430
1431 Args:
1432 target_vdu (dict): Details of VDU to be created
1433 persistent_root_disk (dict): Details of persistent root disk
1434 persistent_ordinary_disk (dict): Details of persistent ordinary disk
1435 disk_list (list): Disks of VDU
1436
1437 """
1438 if target_vdu.get("virtual-storages"):
1439 for disk in target_vdu["virtual-storages"]:
1440 if (
1441 disk.get("type-of-storage")
1442 == "persistent-storage:persistent-storage"
1443 and disk["id"] not in persistent_root_disk.keys()
1444 ):
1445 name, multiattach = Ns.is_shared_volume(disk, vnf_id)
1446 persistent_ordinary_disk[disk["id"]] = {
1447 "name": name,
1448 "size": disk["size-of-storage"],
1449 "keep": Ns.is_volume_keeping_required(disk),
1450 "multiattach": multiattach,
1451 }
1452 disk_list.append(persistent_ordinary_disk[disk["id"]])
1453 if multiattach: # VDU creation has to wait for shared volumes
1454 extra_dict["depends_on"].append(
1455 f"nsrs:{nsr_id}:shared-volumes.{name}"
1456 )
1457
1458 @staticmethod
1459 def _prepare_vdu_affinity_group_list(
1460 target_vdu: dict, extra_dict: dict, ns_preffix: str
1461 ) -> List[Dict[str, any]]:
1462 """Process affinity group details to prepare affinity group list.
1463
1464 Args:
1465 target_vdu (dict): Details of VDU to be created
1466 extra_dict (dict): Dictionary to be filled
1467 ns_preffix (str): Prefix as string
1468
1469 Returns:
1470
1471 affinity_group_list (list): Affinity group details
1472
1473 """
1474 affinity_group_list = []
1475
1476 if target_vdu.get("affinity-or-anti-affinity-group-id"):
1477 for affinity_group_id in target_vdu["affinity-or-anti-affinity-group-id"]:
1478 affinity_group = {}
1479 affinity_group_text = (
1480 ns_preffix + ":affinity-or-anti-affinity-group." + affinity_group_id
1481 )
1482
1483 if not isinstance(extra_dict.get("depends_on"), list):
1484 raise NsException("Invalid extra_dict format.")
1485
1486 extra_dict["depends_on"].append(affinity_group_text)
1487 affinity_group["affinity_group_id"] = "TASK-" + affinity_group_text
1488 affinity_group_list.append(affinity_group)
1489
1490 return affinity_group_list
1491
1492 @staticmethod
1493 def _process_vdu_params(
1494 target_vdu: Dict[str, Any],
1495 indata: Dict[str, Any],
1496 vim_info: Dict[str, Any],
1497 target_record_id: str,
1498 **kwargs: Dict[str, Any],
1499 ) -> Dict[str, Any]:
1500 """Function to process VDU parameters.
1501
1502 Args:
1503 target_vdu (Dict[str, Any]): [description]
1504 indata (Dict[str, Any]): [description]
1505 vim_info (Dict[str, Any]): [description]
1506 target_record_id (str): [description]
1507
1508 Returns:
1509 Dict[str, Any]: [description]
1510 """
1511 vnfr_id = kwargs.get("vnfr_id")
1512 nsr_id = kwargs.get("nsr_id")
1513 vnfr = kwargs.get("vnfr")
1514 vdu2cloud_init = kwargs.get("vdu2cloud_init")
1515 tasks_by_target_record_id = kwargs.get("tasks_by_target_record_id")
1516 logger = kwargs.get("logger")
1517 db = kwargs.get("db")
1518 fs = kwargs.get("fs")
1519 ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1520
1521 vnf_preffix = "vnfrs:{}".format(vnfr_id)
1522 ns_preffix = "nsrs:{}".format(nsr_id)
1523 image_text = ns_preffix + ":image." + target_vdu["ns-image-id"]
1524 extra_dict = {"depends_on": [image_text]}
1525 net_list = []
1526 persistent_root_disk = {}
1527 persistent_ordinary_disk = {}
1528 vdu_instantiation_volumes_list = []
1529 vdu_instantiation_flavor_id = None
1530 disk_list = []
1531 vnfd_id = vnfr["vnfd-id"]
1532 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
1533 # If the position info is provided for all the interfaces, it will be sorted
1534 # according to position number ascendingly.
1535 if all(
1536 True if i.get("position") is not None else False
1537 for i in target_vdu["interfaces"]
1538 ):
1539 Ns._sort_vdu_interfaces(target_vdu)
1540
1541 # If the position info is provided for some interfaces but not all of them, the interfaces
1542 # which has specific position numbers will be placed and others' positions will not be taken care.
1543 else:
1544 Ns._partially_locate_vdu_interfaces(target_vdu)
1545
1546 # If the position info is not provided for the interfaces, interfaces will be attached
1547 # according to the order in the VNFD.
1548 Ns._prepare_vdu_interfaces(
1549 target_vdu,
1550 extra_dict,
1551 ns_preffix,
1552 vnf_preffix,
1553 logger,
1554 tasks_by_target_record_id,
1555 net_list,
1556 )
1557
1558 # cloud config
1559 cloud_config = Ns._prepare_vdu_cloud_init(target_vdu, vdu2cloud_init, db, fs)
1560
1561 # Prepare VDU ssh keys
1562 Ns._prepare_vdu_ssh_keys(target_vdu, ro_nsr_public_key, cloud_config)
1563
1564 if target_vdu.get("additionalParams"):
1565 vdu_instantiation_volumes_list = (
1566 target_vdu.get("additionalParams").get("OSM", {}).get("vdu_volumes")
1567 )
1568 vdu_instantiation_flavor_id = (
1569 target_vdu.get("additionalParams").get("OSM", {}).get("vim_flavor_id")
1570 )
1571
1572 # flavor id
1573 if vdu_instantiation_flavor_id:
1574 flavor_id = vdu_instantiation_flavor_id
1575 else:
1576 flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"]
1577 flavor_id = "TASK-" + flavor_text
1578 extra_dict["depends_on"].append(flavor_text)
1579
1580 if vdu_instantiation_volumes_list:
1581 # Find the root volumes and add to the disk_list
1582 persistent_root_disk = Ns.find_persistent_root_volumes(
1583 vnfd, target_vdu, vdu_instantiation_volumes_list, disk_list
1584 )
1585
1586 # Find the ordinary volumes which are not added to the persistent_root_disk
1587 # and put them to the disk list
1588 Ns.find_persistent_volumes(
1589 persistent_root_disk,
1590 target_vdu,
1591 vdu_instantiation_volumes_list,
1592 disk_list,
1593 )
1594
1595 else:
1596 # Vdu_instantiation_volumes_list is empty
1597 # First get add the persistent root disks to disk_list
1598 Ns._add_persistent_root_disk_to_disk_list(
1599 vnfd, target_vdu, persistent_root_disk, disk_list
1600 )
1601 # Add the persistent non-root disks to disk_list
1602 Ns._add_persistent_ordinary_disks_to_disk_list(
1603 target_vdu,
1604 persistent_root_disk,
1605 persistent_ordinary_disk,
1606 disk_list,
1607 extra_dict,
1608 vnfd["id"],
1609 nsr_id,
1610 )
1611
1612 affinity_group_list = Ns._prepare_vdu_affinity_group_list(
1613 target_vdu, extra_dict, ns_preffix
1614 )
1615
1616 extra_dict["params"] = {
1617 "name": "{}-{}-{}-{}".format(
1618 indata["name"][:16],
1619 vnfr["member-vnf-index-ref"][:16],
1620 target_vdu["vdu-name"][:32],
1621 target_vdu.get("count-index") or 0,
1622 ),
1623 "description": target_vdu["vdu-name"],
1624 "start": True,
1625 "image_id": "TASK-" + image_text,
1626 "flavor_id": flavor_id,
1627 "affinity_group_list": affinity_group_list,
1628 "net_list": net_list,
1629 "cloud_config": cloud_config or None,
1630 "disk_list": disk_list,
1631 "availability_zone_index": None, # TODO
1632 "availability_zone_list": None, # TODO
1633 }
1634 return extra_dict
1635
1636 @staticmethod
1637 def _process_shared_volumes_params(
1638 target_shared_volume: Dict[str, Any],
1639 indata: Dict[str, Any],
1640 vim_info: Dict[str, Any],
1641 target_record_id: str,
1642 **kwargs: Dict[str, Any],
1643 ) -> Dict[str, Any]:
1644 extra_dict = {}
1645 shared_volume_data = {
1646 "size": target_shared_volume["size-of-storage"],
1647 "name": target_shared_volume["id"],
1648 "type": target_shared_volume["type-of-storage"],
1649 "keep": Ns.is_volume_keeping_required(target_shared_volume),
1650 }
1651 extra_dict["params"] = shared_volume_data
1652 return extra_dict
1653
1654 @staticmethod
1655 def _process_affinity_group_params(
1656 target_affinity_group: Dict[str, Any],
1657 indata: Dict[str, Any],
1658 vim_info: Dict[str, Any],
1659 target_record_id: str,
1660 **kwargs: Dict[str, Any],
1661 ) -> Dict[str, Any]:
1662 """Get affinity or anti-affinity group parameters.
1663
1664 Args:
1665 target_affinity_group (Dict[str, Any]): [description]
1666 indata (Dict[str, Any]): [description]
1667 vim_info (Dict[str, Any]): [description]
1668 target_record_id (str): [description]
1669
1670 Returns:
1671 Dict[str, Any]: [description]
1672 """
1673
1674 extra_dict = {}
1675 affinity_group_data = {
1676 "name": target_affinity_group["name"],
1677 "type": target_affinity_group["type"],
1678 "scope": target_affinity_group["scope"],
1679 }
1680
1681 if target_affinity_group.get("vim-affinity-group-id"):
1682 affinity_group_data["vim-affinity-group-id"] = target_affinity_group[
1683 "vim-affinity-group-id"
1684 ]
1685
1686 extra_dict["params"] = {
1687 "affinity_group_data": affinity_group_data,
1688 }
1689 return extra_dict
1690
1691 @staticmethod
1692 def _process_recreate_vdu_params(
1693 existing_vdu: Dict[str, Any],
1694 db_nsr: Dict[str, Any],
1695 vim_info: Dict[str, Any],
1696 target_record_id: str,
1697 target_id: str,
1698 **kwargs: Dict[str, Any],
1699 ) -> Dict[str, Any]:
1700 """Function to process VDU parameters to recreate.
1701
1702 Args:
1703 existing_vdu (Dict[str, Any]): [description]
1704 db_nsr (Dict[str, Any]): [description]
1705 vim_info (Dict[str, Any]): [description]
1706 target_record_id (str): [description]
1707 target_id (str): [description]
1708
1709 Returns:
1710 Dict[str, Any]: [description]
1711 """
1712 vnfr = kwargs.get("vnfr")
1713 vdu2cloud_init = kwargs.get("vdu2cloud_init")
1714 # logger = kwargs.get("logger")
1715 db = kwargs.get("db")
1716 fs = kwargs.get("fs")
1717 ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1718
1719 extra_dict = {}
1720 net_list = []
1721
1722 vim_details = {}
1723 vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
1724
1725 if vim_details_text:
1726 vim_details = yaml.safe_load(f"{vim_details_text}")
1727
1728 for iface_index, interface in enumerate(existing_vdu["interfaces"]):
1729 if "port-security-enabled" in interface:
1730 interface["port_security"] = interface.pop("port-security-enabled")
1731
1732 if "port-security-disable-strategy" in interface:
1733 interface["port_security_disable_strategy"] = interface.pop(
1734 "port-security-disable-strategy"
1735 )
1736
1737 net_item = {
1738 x: v
1739 for x, v in interface.items()
1740 if x
1741 in (
1742 "name",
1743 "vpci",
1744 "port_security",
1745 "port_security_disable_strategy",
1746 "floating_ip",
1747 )
1748 }
1749 existing_ifaces = existing_vdu["vim_info"][target_id].get(
1750 "interfaces_backup", []
1751 )
1752 net_id = next(
1753 (
1754 i["vim_net_id"]
1755 for i in existing_ifaces
1756 if i["ip_address"] == interface["ip-address"]
1757 ),
1758 None,
1759 )
1760
1761 net_item["net_id"] = net_id
1762 net_item["type"] = "virtual"
1763
1764 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1765 # TODO floating_ip: True/False (or it can be None)
1766 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1767 net_item["use"] = "data"
1768 net_item["model"] = interface["type"]
1769 net_item["type"] = interface["type"]
1770 elif (
1771 interface.get("type") == "OM-MGMT"
1772 or interface.get("mgmt-interface")
1773 or interface.get("mgmt-vnf")
1774 ):
1775 net_item["use"] = "mgmt"
1776 else:
1777 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1778 net_item["use"] = "bridge"
1779 net_item["model"] = interface.get("type")
1780
1781 if interface.get("ip-address"):
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.{}".format(vnf_id, vdu_index)
2901 target_record_id = "vnfrs:{}:vdur.{}".format(vnf_id, vdu_id)
2902 deployment_info = {
2903 "action_id": action_id,
2904 "nsr_id": nsr_id,
2905 "task_index": task_index,
2906 }
2907
2908 task = Ns._create_task(
2909 deployment_info=deployment_info,
2910 target_id=target_vim,
2911 item="update",
2912 action="EXEC",
2913 target_record=target_record,
2914 target_record_id=target_record_id,
2915 extra_dict=extra_dict,
2916 )
2917 return task
2918
2919 def rebuild_start_stop(
2920 self, session, action_dict, version, nsr_id, *args, **kwargs
2921 ):
2922 task_index = 0
2923 extra_dict = {}
2924 now = time()
2925 action_id = action_dict.get("action_id", str(uuid4()))
2926 step = ""
2927 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2928 self.logger.debug(logging_text + "Enter")
2929
2930 action = list(action_dict.keys())[0]
2931 task_dict = action_dict.get(action)
2932 vim_vm_id = action_dict.get(action).get("vim_vm_id")
2933
2934 if action_dict.get("stop"):
2935 action = "shutoff"
2936 db_new_tasks = []
2937 try:
2938 step = "lock the operation & do task creation"
2939 with self.write_lock:
2940 extra_dict["params"] = {
2941 "vim_vm_id": vim_vm_id,
2942 "action": action,
2943 }
2944 task = self.rebuild_start_stop_task(
2945 task_dict["vdu_id"],
2946 task_dict["vnf_id"],
2947 task_dict["vdu_index"],
2948 action_id,
2949 nsr_id,
2950 task_index,
2951 task_dict["target_vim"],
2952 extra_dict,
2953 )
2954 db_new_tasks.append(task)
2955 step = "upload Task to db"
2956 self.upload_all_tasks(
2957 db_new_tasks=db_new_tasks,
2958 now=now,
2959 )
2960 self.logger.debug(
2961 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2962 )
2963 return (
2964 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2965 action_id,
2966 True,
2967 )
2968 except Exception as e:
2969 if isinstance(e, (DbException, NsException)):
2970 self.logger.error(
2971 logging_text + "Exit Exception while '{}': {}".format(step, e)
2972 )
2973 else:
2974 e = traceback_format_exc()
2975 self.logger.critical(
2976 logging_text + "Exit Exception while '{}': {}".format(step, e),
2977 exc_info=True,
2978 )
2979 raise NsException(e)
2980
2981 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2982 nsrs = self.db.get_list("nsrs", {})
2983 return_data = []
2984
2985 for ns in nsrs:
2986 return_data.append({"_id": ns["_id"], "name": ns["name"]})
2987
2988 return return_data, None, True
2989
2990 def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2991 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2992 return_data = []
2993
2994 for ro_task in ro_tasks:
2995 for task in ro_task["tasks"]:
2996 if task["action_id"] not in return_data:
2997 return_data.append(task["action_id"])
2998
2999 return return_data, None, True
3000
3001 def migrate_task(
3002 self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
3003 ):
3004 target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
3005 self._assign_vim(target_vim)
3006 target_record = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu_index)
3007 target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
3008 deployment_info = {
3009 "action_id": action_id,
3010 "nsr_id": nsr_id,
3011 "task_index": task_index,
3012 }
3013
3014 task = Ns._create_task(
3015 deployment_info=deployment_info,
3016 target_id=target_vim,
3017 item="migrate",
3018 action="EXEC",
3019 target_record=target_record,
3020 target_record_id=target_record_id,
3021 extra_dict=extra_dict,
3022 )
3023
3024 return task
3025
3026 def migrate(self, session, indata, version, nsr_id, *args, **kwargs):
3027 task_index = 0
3028 extra_dict = {}
3029 now = time()
3030 action_id = indata.get("action_id", str(uuid4()))
3031 step = ""
3032 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3033 self.logger.debug(logging_text + "Enter")
3034 try:
3035 vnf_instance_id = indata["vnfInstanceId"]
3036 step = "Getting vnfrs from db"
3037 db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
3038 vdu = indata.get("vdu")
3039 migrateToHost = indata.get("migrateToHost")
3040 db_new_tasks = []
3041
3042 with self.write_lock:
3043 if vdu is not None:
3044 vdu_id = indata["vdu"]["vduId"]
3045 vdu_count_index = indata["vdu"].get("vduCountIndex", 0)
3046 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3047 if (
3048 vdu["vdu-id-ref"] == vdu_id
3049 and vdu["count-index"] == vdu_count_index
3050 ):
3051 extra_dict["params"] = {
3052 "vim_vm_id": vdu["vim-id"],
3053 "migrate_host": migrateToHost,
3054 "vdu_vim_info": vdu["vim_info"],
3055 }
3056 step = "Creating migration task for vdu:{}".format(vdu)
3057 task = self.migrate_task(
3058 vdu,
3059 db_vnfr,
3060 vdu_index,
3061 action_id,
3062 nsr_id,
3063 task_index,
3064 extra_dict,
3065 )
3066 db_new_tasks.append(task)
3067 task_index += 1
3068 break
3069 else:
3070 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3071 extra_dict["params"] = {
3072 "vim_vm_id": vdu["vim-id"],
3073 "migrate_host": migrateToHost,
3074 "vdu_vim_info": vdu["vim_info"],
3075 }
3076 step = "Creating migration task for vdu:{}".format(vdu)
3077 task = self.migrate_task(
3078 vdu,
3079 db_vnfr,
3080 vdu_index,
3081 action_id,
3082 nsr_id,
3083 task_index,
3084 extra_dict,
3085 )
3086 db_new_tasks.append(task)
3087 task_index += 1
3088
3089 self.upload_all_tasks(
3090 db_new_tasks=db_new_tasks,
3091 now=now,
3092 )
3093
3094 self.logger.debug(
3095 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3096 )
3097 return (
3098 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3099 action_id,
3100 True,
3101 )
3102 except Exception as e:
3103 if isinstance(e, (DbException, NsException)):
3104 self.logger.error(
3105 logging_text + "Exit Exception while '{}': {}".format(step, e)
3106 )
3107 else:
3108 e = traceback_format_exc()
3109 self.logger.critical(
3110 logging_text + "Exit Exception while '{}': {}".format(step, e),
3111 exc_info=True,
3112 )
3113 raise NsException(e)
3114
3115 def verticalscale_task(
3116 self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
3117 ):
3118 target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
3119 self._assign_vim(target_vim)
3120 target_record = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu_index)
3121 target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
3122 deployment_info = {
3123 "action_id": action_id,
3124 "nsr_id": nsr_id,
3125 "task_index": task_index,
3126 }
3127
3128 task = Ns._create_task(
3129 deployment_info=deployment_info,
3130 target_id=target_vim,
3131 item="verticalscale",
3132 action="EXEC",
3133 target_record=target_record,
3134 target_record_id=target_record_id,
3135 extra_dict=extra_dict,
3136 )
3137 return task
3138
3139 def verticalscale(self, session, indata, version, nsr_id, *args, **kwargs):
3140 task_index = 0
3141 extra_dict = {}
3142 now = time()
3143 action_id = indata.get("action_id", str(uuid4()))
3144 step = ""
3145 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
3146 self.logger.debug(logging_text + "Enter")
3147 try:
3148 VnfFlavorData = indata.get("changeVnfFlavorData")
3149 vnf_instance_id = VnfFlavorData["vnfInstanceId"]
3150 step = "Getting vnfrs from db"
3151 db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
3152 vduid = VnfFlavorData["additionalParams"]["vduid"]
3153 vduCountIndex = VnfFlavorData["additionalParams"]["vduCountIndex"]
3154 virtualMemory = VnfFlavorData["additionalParams"]["virtualMemory"]
3155 numVirtualCpu = VnfFlavorData["additionalParams"]["numVirtualCpu"]
3156 sizeOfStorage = VnfFlavorData["additionalParams"]["sizeOfStorage"]
3157 flavor_dict = {
3158 "name": vduid + "-flv",
3159 "ram": virtualMemory,
3160 "vcpus": numVirtualCpu,
3161 "disk": sizeOfStorage,
3162 }
3163 db_new_tasks = []
3164 step = "Creating Tasks for vertical scaling"
3165 with self.write_lock:
3166 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
3167 if (
3168 vdu["vdu-id-ref"] == vduid
3169 and vdu["count-index"] == vduCountIndex
3170 ):
3171 extra_dict["params"] = {
3172 "vim_vm_id": vdu["vim-id"],
3173 "flavor_dict": flavor_dict,
3174 }
3175 task = self.verticalscale_task(
3176 vdu,
3177 db_vnfr,
3178 vdu_index,
3179 action_id,
3180 nsr_id,
3181 task_index,
3182 extra_dict,
3183 )
3184 db_new_tasks.append(task)
3185 task_index += 1
3186 break
3187 self.upload_all_tasks(
3188 db_new_tasks=db_new_tasks,
3189 now=now,
3190 )
3191 self.logger.debug(
3192 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
3193 )
3194 return (
3195 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
3196 action_id,
3197 True,
3198 )
3199 except Exception as e:
3200 if isinstance(e, (DbException, NsException)):
3201 self.logger.error(
3202 logging_text + "Exit Exception while '{}': {}".format(step, e)
3203 )
3204 else:
3205 e = traceback_format_exc()
3206 self.logger.critical(
3207 logging_text + "Exit Exception while '{}': {}".format(step, e),
3208 exc_info=True,
3209 )
3210 raise NsException(e)