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