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