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