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