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