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