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