Feature 10909: Heal operation for VDU. Fix virtual machine deletion and volume deleti...
[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 import logging
21 from random import choice as random_choice
22 from threading import Lock
23 from time import time
24 from traceback import format_exc as traceback_format_exc
25 from typing import Any, Dict, Tuple, Type
26 from uuid import uuid4
27
28 from cryptography.hazmat.backends import default_backend as crypto_default_backend
29 from cryptography.hazmat.primitives import serialization as crypto_serialization
30 from cryptography.hazmat.primitives.asymmetric import rsa
31 from jinja2 import (
32 Environment,
33 StrictUndefined,
34 TemplateError,
35 TemplateNotFound,
36 UndefinedError,
37 )
38 from osm_common import (
39 dbmemory,
40 dbmongo,
41 fslocal,
42 fsmongo,
43 msgkafka,
44 msglocal,
45 version as common_version,
46 )
47 from osm_common.dbbase import DbBase, DbException
48 from osm_common.fsbase import FsBase, FsException
49 from osm_common.msgbase import MsgException
50 from osm_ng_ro.ns_thread import deep_get, NsWorker, NsWorkerException
51 from osm_ng_ro.validation import deploy_schema, validate_input
52 import yaml
53
54 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
55 min_common_version = "0.1.16"
56
57
58 class NsException(Exception):
59 def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
60 self.http_code = http_code
61 super(Exception, self).__init__(message)
62
63
64 def get_process_id():
65 """
66 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
67 will provide a random one
68 :return: Obtained ID
69 """
70 # Try getting docker id. If fails, get pid
71 try:
72 with open("/proc/self/cgroup", "r") as f:
73 text_id_ = f.readline()
74 _, _, text_id = text_id_.rpartition("/")
75 text_id = text_id.replace("\n", "")[:12]
76
77 if text_id:
78 return text_id
79 except Exception:
80 pass
81
82 # Return a random id
83 return "".join(random_choice("0123456789abcdef") for _ in range(12))
84
85
86 def versiontuple(v):
87 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
88 filled = []
89
90 for point in v.split("."):
91 filled.append(point.zfill(8))
92
93 return tuple(filled)
94
95
96 class Ns(object):
97 def __init__(self):
98 self.db = None
99 self.fs = None
100 self.msg = None
101 self.config = None
102 # self.operations = None
103 self.logger = None
104 # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
105 # If done now it will not be linked to parent not getting its handler and level
106 self.map_topic = {}
107 self.write_lock = None
108 self.vims_assigned = {}
109 self.next_worker = 0
110 self.plugins = {}
111 self.workers = []
112 self.process_params_function_map = {
113 "net": Ns._process_net_params,
114 "image": Ns._process_image_params,
115 "flavor": Ns._process_flavor_params,
116 "vdu": Ns._process_vdu_params,
117 "affinity-or-anti-affinity-group": Ns._process_affinity_group_params,
118 }
119 self.db_path_map = {
120 "net": "vld",
121 "image": "image",
122 "flavor": "flavor",
123 "vdu": "vdur",
124 "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group",
125 }
126
127 def init_db(self, target_version):
128 pass
129
130 def start(self, config):
131 """
132 Connect to database, filesystem storage, and messaging
133 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
134 :param config: Configuration of db, storage, etc
135 :return: None
136 """
137 self.config = config
138 self.config["process_id"] = get_process_id() # used for HA identity
139 self.logger = logging.getLogger("ro.ns")
140
141 # check right version of common
142 if versiontuple(common_version) < versiontuple(min_common_version):
143 raise NsException(
144 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
145 common_version, min_common_version
146 )
147 )
148
149 try:
150 if not self.db:
151 if config["database"]["driver"] == "mongo":
152 self.db = dbmongo.DbMongo()
153 self.db.db_connect(config["database"])
154 elif config["database"]["driver"] == "memory":
155 self.db = dbmemory.DbMemory()
156 self.db.db_connect(config["database"])
157 else:
158 raise NsException(
159 "Invalid configuration param '{}' at '[database]':'driver'".format(
160 config["database"]["driver"]
161 )
162 )
163
164 if not self.fs:
165 if config["storage"]["driver"] == "local":
166 self.fs = fslocal.FsLocal()
167 self.fs.fs_connect(config["storage"])
168 elif config["storage"]["driver"] == "mongo":
169 self.fs = fsmongo.FsMongo()
170 self.fs.fs_connect(config["storage"])
171 elif config["storage"]["driver"] is None:
172 pass
173 else:
174 raise NsException(
175 "Invalid configuration param '{}' at '[storage]':'driver'".format(
176 config["storage"]["driver"]
177 )
178 )
179
180 if not self.msg:
181 if config["message"]["driver"] == "local":
182 self.msg = msglocal.MsgLocal()
183 self.msg.connect(config["message"])
184 elif config["message"]["driver"] == "kafka":
185 self.msg = msgkafka.MsgKafka()
186 self.msg.connect(config["message"])
187 else:
188 raise NsException(
189 "Invalid configuration param '{}' at '[message]':'driver'".format(
190 config["message"]["driver"]
191 )
192 )
193
194 # TODO load workers to deal with exising database tasks
195
196 self.write_lock = Lock()
197 except (DbException, FsException, MsgException) as e:
198 raise NsException(str(e), http_code=e.http_code)
199
200 def get_assigned_vims(self):
201 return list(self.vims_assigned.keys())
202
203 def stop(self):
204 try:
205 if self.db:
206 self.db.db_disconnect()
207
208 if self.fs:
209 self.fs.fs_disconnect()
210
211 if self.msg:
212 self.msg.disconnect()
213
214 self.write_lock = None
215 except (DbException, FsException, MsgException) as e:
216 raise NsException(str(e), http_code=e.http_code)
217
218 for worker in self.workers:
219 worker.insert_task(("terminate",))
220
221 def _create_worker(self):
222 """
223 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
224 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
225 return the index of the assigned worker thread. Worker threads are storead at self.workers
226 """
227 # Look for a thread in idle status
228 worker_id = next(
229 (
230 i
231 for i in range(len(self.workers))
232 if self.workers[i] and self.workers[i].idle
233 ),
234 None,
235 )
236
237 if worker_id is not None:
238 # unset idle status to avoid race conditions
239 self.workers[worker_id].idle = False
240 else:
241 worker_id = len(self.workers)
242
243 if worker_id < self.config["global"]["server.ns_threads"]:
244 # create a new worker
245 self.workers.append(
246 NsWorker(worker_id, self.config, self.plugins, self.db)
247 )
248 self.workers[worker_id].start()
249 else:
250 # reached maximum number of threads, assign VIM to an existing one
251 worker_id = self.next_worker
252 self.next_worker = (self.next_worker + 1) % self.config["global"][
253 "server.ns_threads"
254 ]
255
256 return worker_id
257
258 def assign_vim(self, target_id):
259 with self.write_lock:
260 return self._assign_vim(target_id)
261
262 def _assign_vim(self, target_id):
263 if target_id not in self.vims_assigned:
264 worker_id = self.vims_assigned[target_id] = self._create_worker()
265 self.workers[worker_id].insert_task(("load_vim", target_id))
266
267 def reload_vim(self, target_id):
268 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
269 # this is because database VIM information is cached for threads working with SDN
270 with self.write_lock:
271 for worker in self.workers:
272 if worker and not worker.idle:
273 worker.insert_task(("reload_vim", target_id))
274
275 def unload_vim(self, target_id):
276 with self.write_lock:
277 return self._unload_vim(target_id)
278
279 def _unload_vim(self, target_id):
280 if target_id in self.vims_assigned:
281 worker_id = self.vims_assigned[target_id]
282 self.workers[worker_id].insert_task(("unload_vim", target_id))
283 del self.vims_assigned[target_id]
284
285 def check_vim(self, target_id):
286 with self.write_lock:
287 if target_id in self.vims_assigned:
288 worker_id = self.vims_assigned[target_id]
289 else:
290 worker_id = self._create_worker()
291
292 worker = self.workers[worker_id]
293 worker.insert_task(("check_vim", target_id))
294
295 def unload_unused_vims(self):
296 with self.write_lock:
297 vims_to_unload = []
298
299 for target_id in self.vims_assigned:
300 if not self.db.get_one(
301 "ro_tasks",
302 q_filter={
303 "target_id": target_id,
304 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
305 },
306 fail_on_empty=False,
307 ):
308 vims_to_unload.append(target_id)
309
310 for target_id in vims_to_unload:
311 self._unload_vim(target_id)
312
313 @staticmethod
314 def _get_cloud_init(
315 db: Type[DbBase],
316 fs: Type[FsBase],
317 location: str,
318 ) -> str:
319 """This method reads cloud init from a file.
320
321 Note: Not used as cloud init content is provided in the http body.
322
323 Args:
324 db (Type[DbBase]): [description]
325 fs (Type[FsBase]): [description]
326 location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
327
328 Raises:
329 NsException: [description]
330 NsException: [description]
331
332 Returns:
333 str: [description]
334 """
335 vnfd_id, _, other = location.partition(":")
336 _type, _, name = other.partition(":")
337 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
338
339 if _type == "file":
340 base_folder = vnfd["_admin"]["storage"]
341 cloud_init_file = "{}/{}/cloud_init/{}".format(
342 base_folder["folder"], base_folder["pkg-dir"], name
343 )
344
345 if not fs:
346 raise NsException(
347 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
348 cloud_init_file
349 )
350 )
351
352 with fs.file_open(cloud_init_file, "r") as ci_file:
353 cloud_init_content = ci_file.read()
354 elif _type == "vdu":
355 cloud_init_content = vnfd["vdu"][int(name)]["cloud-init"]
356 else:
357 raise NsException("Mismatch descriptor for cloud init: {}".format(location))
358
359 return cloud_init_content
360
361 @staticmethod
362 def _parse_jinja2(
363 cloud_init_content: str,
364 params: Dict[str, Any],
365 context: str,
366 ) -> str:
367 """Function that processes the cloud init to replace Jinja2 encoded parameters.
368
369 Args:
370 cloud_init_content (str): [description]
371 params (Dict[str, Any]): [description]
372 context (str): [description]
373
374 Raises:
375 NsException: [description]
376 NsException: [description]
377
378 Returns:
379 str: [description]
380 """
381 try:
382 env = Environment(undefined=StrictUndefined)
383 template = env.from_string(cloud_init_content)
384
385 return template.render(params or {})
386 except UndefinedError as e:
387 raise NsException(
388 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
389 "inside the 'additionalParamsForVnf' block".format(e, context)
390 )
391 except (TemplateError, TemplateNotFound) as e:
392 raise NsException(
393 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
394 context, e
395 )
396 )
397
398 def _create_db_ro_nsrs(self, nsr_id, now):
399 try:
400 key = rsa.generate_private_key(
401 backend=crypto_default_backend(), public_exponent=65537, key_size=2048
402 )
403 private_key = key.private_bytes(
404 crypto_serialization.Encoding.PEM,
405 crypto_serialization.PrivateFormat.PKCS8,
406 crypto_serialization.NoEncryption(),
407 )
408 public_key = key.public_key().public_bytes(
409 crypto_serialization.Encoding.OpenSSH,
410 crypto_serialization.PublicFormat.OpenSSH,
411 )
412 private_key = private_key.decode("utf8")
413 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
414 i = private_key.find("\n")
415 private_key = "-----BEGIN RSA PRIVATE KEY-----" + private_key[i:]
416 public_key = public_key.decode("utf8")
417 except Exception as e:
418 raise NsException("Cannot create ssh-keys: {}".format(e))
419
420 schema_version = "1.1"
421 private_key_encrypted = self.db.encrypt(
422 private_key, schema_version=schema_version, salt=nsr_id
423 )
424 db_content = {
425 "_id": nsr_id,
426 "_admin": {
427 "created": now,
428 "modified": now,
429 "schema_version": schema_version,
430 },
431 "public_key": public_key,
432 "private_key": private_key_encrypted,
433 "actions": [],
434 }
435 self.db.create("ro_nsrs", db_content)
436
437 return db_content
438
439 @staticmethod
440 def _create_task(
441 deployment_info: Dict[str, Any],
442 target_id: str,
443 item: str,
444 action: str,
445 target_record: str,
446 target_record_id: str,
447 extra_dict: Dict[str, Any] = None,
448 ) -> Dict[str, Any]:
449 """Function to create task dict from deployment information.
450
451 Args:
452 deployment_info (Dict[str, Any]): [description]
453 target_id (str): [description]
454 item (str): [description]
455 action (str): [description]
456 target_record (str): [description]
457 target_record_id (str): [description]
458 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
459
460 Returns:
461 Dict[str, Any]: [description]
462 """
463 task = {
464 "target_id": target_id, # it will be removed before pushing at database
465 "action_id": deployment_info.get("action_id"),
466 "nsr_id": deployment_info.get("nsr_id"),
467 "task_id": f"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
468 "status": "SCHEDULED",
469 "action": action,
470 "item": item,
471 "target_record": target_record,
472 "target_record_id": target_record_id,
473 }
474
475 if extra_dict:
476 task.update(extra_dict) # params, find_params, depends_on
477
478 deployment_info["task_index"] = deployment_info.get("task_index", 0) + 1
479
480 return task
481
482 @staticmethod
483 def _create_ro_task(
484 target_id: str,
485 task: Dict[str, Any],
486 ) -> Dict[str, Any]:
487 """Function to create an RO task from task information.
488
489 Args:
490 target_id (str): [description]
491 task (Dict[str, Any]): [description]
492
493 Returns:
494 Dict[str, Any]: [description]
495 """
496 now = time()
497
498 _id = task.get("task_id")
499 db_ro_task = {
500 "_id": _id,
501 "locked_by": None,
502 "locked_at": 0.0,
503 "target_id": target_id,
504 "vim_info": {
505 "created": False,
506 "created_items": None,
507 "vim_id": None,
508 "vim_name": None,
509 "vim_status": None,
510 "vim_details": None,
511 "vim_message": None,
512 "refresh_at": None,
513 },
514 "modified_at": now,
515 "created_at": now,
516 "to_check_at": now,
517 "tasks": [task],
518 }
519
520 return db_ro_task
521
522 @staticmethod
523 def _process_image_params(
524 target_image: Dict[str, Any],
525 indata: Dict[str, Any],
526 vim_info: Dict[str, Any],
527 target_record_id: str,
528 **kwargs: Dict[str, Any],
529 ) -> Dict[str, Any]:
530 """Function to process VDU image parameters.
531
532 Args:
533 target_image (Dict[str, Any]): [description]
534 indata (Dict[str, Any]): [description]
535 vim_info (Dict[str, Any]): [description]
536 target_record_id (str): [description]
537
538 Returns:
539 Dict[str, Any]: [description]
540 """
541 find_params = {}
542
543 if target_image.get("image"):
544 find_params["filter_dict"] = {"name": target_image.get("image")}
545
546 if target_image.get("vim_image_id"):
547 find_params["filter_dict"] = {"id": target_image.get("vim_image_id")}
548
549 if target_image.get("image_checksum"):
550 find_params["filter_dict"] = {
551 "checksum": target_image.get("image_checksum")
552 }
553
554 return {"find_params": find_params}
555
556 @staticmethod
557 def _get_resource_allocation_params(
558 quota_descriptor: Dict[str, Any],
559 ) -> Dict[str, Any]:
560 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
561 descriptor object.
562
563 Args:
564 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
565
566 Returns:
567 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
568 """
569 quota = {}
570
571 if quota_descriptor.get("limit"):
572 quota["limit"] = int(quota_descriptor["limit"])
573
574 if quota_descriptor.get("reserve"):
575 quota["reserve"] = int(quota_descriptor["reserve"])
576
577 if quota_descriptor.get("shares"):
578 quota["shares"] = int(quota_descriptor["shares"])
579
580 return quota
581
582 @staticmethod
583 def _process_guest_epa_quota_params(
584 guest_epa_quota: Dict[str, Any],
585 epa_vcpu_set: bool,
586 ) -> Dict[str, Any]:
587 """Function to extract the guest epa quota parameters.
588
589 Args:
590 guest_epa_quota (Dict[str, Any]): [description]
591 epa_vcpu_set (bool): [description]
592
593 Returns:
594 Dict[str, Any]: [description]
595 """
596 result = {}
597
598 if guest_epa_quota.get("cpu-quota") and not epa_vcpu_set:
599 cpuquota = Ns._get_resource_allocation_params(
600 guest_epa_quota.get("cpu-quota")
601 )
602
603 if cpuquota:
604 result["cpu-quota"] = cpuquota
605
606 if guest_epa_quota.get("mem-quota"):
607 vduquota = Ns._get_resource_allocation_params(
608 guest_epa_quota.get("mem-quota")
609 )
610
611 if vduquota:
612 result["mem-quota"] = vduquota
613
614 if guest_epa_quota.get("disk-io-quota"):
615 diskioquota = Ns._get_resource_allocation_params(
616 guest_epa_quota.get("disk-io-quota")
617 )
618
619 if diskioquota:
620 result["disk-io-quota"] = diskioquota
621
622 if guest_epa_quota.get("vif-quota"):
623 vifquota = Ns._get_resource_allocation_params(
624 guest_epa_quota.get("vif-quota")
625 )
626
627 if vifquota:
628 result["vif-quota"] = vifquota
629
630 return result
631
632 @staticmethod
633 def _process_guest_epa_numa_params(
634 guest_epa_quota: Dict[str, Any],
635 ) -> Tuple[Dict[str, Any], bool]:
636 """[summary]
637
638 Args:
639 guest_epa_quota (Dict[str, Any]): [description]
640
641 Returns:
642 Tuple[Dict[str, Any], bool]: [description]
643 """
644 numa = {}
645 epa_vcpu_set = False
646
647 if guest_epa_quota.get("numa-node-policy"):
648 numa_node_policy = guest_epa_quota.get("numa-node-policy")
649
650 if numa_node_policy.get("node"):
651 numa_node = numa_node_policy["node"][0]
652
653 if numa_node.get("num-cores"):
654 numa["cores"] = numa_node["num-cores"]
655 epa_vcpu_set = True
656
657 paired_threads = numa_node.get("paired-threads", {})
658 if paired_threads.get("num-paired-threads"):
659 numa["paired-threads"] = int(
660 numa_node["paired-threads"]["num-paired-threads"]
661 )
662 epa_vcpu_set = True
663
664 if paired_threads.get("paired-thread-ids"):
665 numa["paired-threads-id"] = []
666
667 for pair in paired_threads["paired-thread-ids"]:
668 numa["paired-threads-id"].append(
669 (
670 str(pair["thread-a"]),
671 str(pair["thread-b"]),
672 )
673 )
674
675 if numa_node.get("num-threads"):
676 numa["threads"] = int(numa_node["num-threads"])
677 epa_vcpu_set = True
678
679 if numa_node.get("memory-mb"):
680 numa["memory"] = max(int(int(numa_node["memory-mb"]) / 1024), 1)
681
682 return numa, epa_vcpu_set
683
684 @staticmethod
685 def _process_guest_epa_cpu_pinning_params(
686 guest_epa_quota: Dict[str, Any],
687 vcpu_count: int,
688 epa_vcpu_set: bool,
689 ) -> Tuple[Dict[str, Any], bool]:
690 """[summary]
691
692 Args:
693 guest_epa_quota (Dict[str, Any]): [description]
694 vcpu_count (int): [description]
695 epa_vcpu_set (bool): [description]
696
697 Returns:
698 Tuple[Dict[str, Any], bool]: [description]
699 """
700 numa = {}
701 local_epa_vcpu_set = epa_vcpu_set
702
703 if (
704 guest_epa_quota.get("cpu-pinning-policy") == "DEDICATED"
705 and not epa_vcpu_set
706 ):
707 numa[
708 "cores"
709 if guest_epa_quota.get("cpu-thread-pinning-policy") != "PREFER"
710 else "threads"
711 ] = max(vcpu_count, 1)
712 local_epa_vcpu_set = True
713
714 return numa, local_epa_vcpu_set
715
716 @staticmethod
717 def _process_epa_params(
718 target_flavor: Dict[str, Any],
719 ) -> Dict[str, Any]:
720 """[summary]
721
722 Args:
723 target_flavor (Dict[str, Any]): [description]
724
725 Returns:
726 Dict[str, Any]: [description]
727 """
728 extended = {}
729 numa = {}
730
731 if target_flavor.get("guest-epa"):
732 guest_epa = target_flavor["guest-epa"]
733
734 numa, epa_vcpu_set = Ns._process_guest_epa_numa_params(
735 guest_epa_quota=guest_epa
736 )
737
738 if guest_epa.get("mempage-size"):
739 extended["mempage-size"] = guest_epa.get("mempage-size")
740
741 tmp_numa, epa_vcpu_set = Ns._process_guest_epa_cpu_pinning_params(
742 guest_epa_quota=guest_epa,
743 vcpu_count=int(target_flavor.get("vcpu-count", 1)),
744 epa_vcpu_set=epa_vcpu_set,
745 )
746 numa.update(tmp_numa)
747
748 extended.update(
749 Ns._process_guest_epa_quota_params(
750 guest_epa_quota=guest_epa,
751 epa_vcpu_set=epa_vcpu_set,
752 )
753 )
754
755 if numa:
756 extended["numas"] = [numa]
757
758 return extended
759
760 @staticmethod
761 def _process_flavor_params(
762 target_flavor: Dict[str, Any],
763 indata: Dict[str, Any],
764 vim_info: Dict[str, Any],
765 target_record_id: str,
766 **kwargs: Dict[str, Any],
767 ) -> Dict[str, Any]:
768 """[summary]
769
770 Args:
771 target_flavor (Dict[str, Any]): [description]
772 indata (Dict[str, Any]): [description]
773 vim_info (Dict[str, Any]): [description]
774 target_record_id (str): [description]
775
776 Returns:
777 Dict[str, Any]: [description]
778 """
779 flavor_data = {
780 "disk": int(target_flavor["storage-gb"]),
781 "ram": int(target_flavor["memory-mb"]),
782 "vcpus": int(target_flavor["vcpu-count"]),
783 }
784
785 target_vdur = {}
786 for vnf in indata.get("vnf", []):
787 for vdur in vnf.get("vdur", []):
788 if vdur.get("ns-flavor-id") == target_flavor["id"]:
789 target_vdur = vdur
790
791 for storage in target_vdur.get("virtual-storages", []):
792 if (
793 storage.get("type-of-storage")
794 == "etsi-nfv-descriptors:ephemeral-storage"
795 ):
796 flavor_data["ephemeral"] = int(storage.get("size-of-storage", 0))
797 elif storage.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
798 flavor_data["swap"] = int(storage.get("size-of-storage", 0))
799
800 extended = Ns._process_epa_params(target_flavor)
801 if extended:
802 flavor_data["extended"] = extended
803
804 extra_dict = {"find_params": {"flavor_data": flavor_data}}
805 flavor_data_name = flavor_data.copy()
806 flavor_data_name["name"] = target_flavor["name"]
807 extra_dict["params"] = {"flavor_data": flavor_data_name}
808
809 return extra_dict
810
811 @staticmethod
812 def _ip_profile_to_ro(
813 ip_profile: Dict[str, Any],
814 ) -> Dict[str, Any]:
815 """[summary]
816
817 Args:
818 ip_profile (Dict[str, Any]): [description]
819
820 Returns:
821 Dict[str, Any]: [description]
822 """
823 if not ip_profile:
824 return None
825
826 ro_ip_profile = {
827 "ip_version": "IPv4"
828 if "v4" in ip_profile.get("ip-version", "ipv4")
829 else "IPv6",
830 "subnet_address": ip_profile.get("subnet-address"),
831 "gateway_address": ip_profile.get("gateway-address"),
832 "dhcp_enabled": ip_profile.get("dhcp-params", {}).get("enabled", False),
833 "dhcp_start_address": ip_profile.get("dhcp-params", {}).get(
834 "start-address", None
835 ),
836 "dhcp_count": ip_profile.get("dhcp-params", {}).get("count", None),
837 }
838
839 if ip_profile.get("dns-server"):
840 ro_ip_profile["dns_address"] = ";".join(
841 [v["address"] for v in ip_profile["dns-server"] if v.get("address")]
842 )
843
844 if ip_profile.get("security-group"):
845 ro_ip_profile["security_group"] = ip_profile["security-group"]
846
847 return ro_ip_profile
848
849 @staticmethod
850 def _process_net_params(
851 target_vld: Dict[str, Any],
852 indata: Dict[str, Any],
853 vim_info: Dict[str, Any],
854 target_record_id: str,
855 **kwargs: Dict[str, Any],
856 ) -> Dict[str, Any]:
857 """Function to process network parameters.
858
859 Args:
860 target_vld (Dict[str, Any]): [description]
861 indata (Dict[str, Any]): [description]
862 vim_info (Dict[str, Any]): [description]
863 target_record_id (str): [description]
864
865 Returns:
866 Dict[str, Any]: [description]
867 """
868 extra_dict = {}
869
870 if vim_info.get("sdn"):
871 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
872 # ns_preffix = "nsrs:{}".format(nsr_id)
873 # remove the ending ".sdn
874 vld_target_record_id, _, _ = target_record_id.rpartition(".")
875 extra_dict["params"] = {
876 k: vim_info[k]
877 for k in ("sdn-ports", "target_vim", "vlds", "type")
878 if vim_info.get(k)
879 }
880
881 # TODO needed to add target_id in the dependency.
882 if vim_info.get("target_vim"):
883 extra_dict["depends_on"] = [
884 f"{vim_info.get('target_vim')} {vld_target_record_id}"
885 ]
886
887 return extra_dict
888
889 if vim_info.get("vim_network_name"):
890 extra_dict["find_params"] = {
891 "filter_dict": {
892 "name": vim_info.get("vim_network_name"),
893 },
894 }
895 elif vim_info.get("vim_network_id"):
896 extra_dict["find_params"] = {
897 "filter_dict": {
898 "id": vim_info.get("vim_network_id"),
899 },
900 }
901 elif target_vld.get("mgmt-network"):
902 extra_dict["find_params"] = {
903 "mgmt": True,
904 "name": target_vld["id"],
905 }
906 else:
907 # create
908 extra_dict["params"] = {
909 "net_name": (
910 f"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
911 ),
912 "ip_profile": Ns._ip_profile_to_ro(vim_info.get("ip_profile")),
913 "provider_network_profile": vim_info.get("provider_network"),
914 }
915
916 if not target_vld.get("underlay"):
917 extra_dict["params"]["net_type"] = "bridge"
918 else:
919 extra_dict["params"]["net_type"] = (
920 "ptp" if target_vld.get("type") == "ELINE" else "data"
921 )
922
923 return extra_dict
924
925 @staticmethod
926 def _process_vdu_params(
927 target_vdu: Dict[str, Any],
928 indata: Dict[str, Any],
929 vim_info: Dict[str, Any],
930 target_record_id: str,
931 **kwargs: Dict[str, Any],
932 ) -> Dict[str, Any]:
933 """Function to process VDU parameters.
934
935 Args:
936 target_vdu (Dict[str, Any]): [description]
937 indata (Dict[str, Any]): [description]
938 vim_info (Dict[str, Any]): [description]
939 target_record_id (str): [description]
940
941 Returns:
942 Dict[str, Any]: [description]
943 """
944 vnfr_id = kwargs.get("vnfr_id")
945 nsr_id = kwargs.get("nsr_id")
946 vnfr = kwargs.get("vnfr")
947 vdu2cloud_init = kwargs.get("vdu2cloud_init")
948 tasks_by_target_record_id = kwargs.get("tasks_by_target_record_id")
949 logger = kwargs.get("logger")
950 db = kwargs.get("db")
951 fs = kwargs.get("fs")
952 ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
953
954 vnf_preffix = "vnfrs:{}".format(vnfr_id)
955 ns_preffix = "nsrs:{}".format(nsr_id)
956 image_text = ns_preffix + ":image." + target_vdu["ns-image-id"]
957 flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"]
958 extra_dict = {"depends_on": [image_text, flavor_text]}
959 net_list = []
960
961 for iface_index, interface in enumerate(target_vdu["interfaces"]):
962 if interface.get("ns-vld-id"):
963 net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
964 elif interface.get("vnf-vld-id"):
965 net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
966 else:
967 logger.error(
968 "Interface {} from vdu {} not connected to any vld".format(
969 iface_index, target_vdu["vdu-name"]
970 )
971 )
972
973 continue # interface not connected to any vld
974
975 extra_dict["depends_on"].append(net_text)
976
977 if "port-security-enabled" in interface:
978 interface["port_security"] = interface.pop("port-security-enabled")
979
980 if "port-security-disable-strategy" in interface:
981 interface["port_security_disable_strategy"] = interface.pop(
982 "port-security-disable-strategy"
983 )
984
985 net_item = {
986 x: v
987 for x, v in interface.items()
988 if x
989 in (
990 "name",
991 "vpci",
992 "port_security",
993 "port_security_disable_strategy",
994 "floating_ip",
995 )
996 }
997 net_item["net_id"] = "TASK-" + net_text
998 net_item["type"] = "virtual"
999
1000 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1001 # TODO floating_ip: True/False (or it can be None)
1002 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1003 # mark the net create task as type data
1004 if deep_get(
1005 tasks_by_target_record_id,
1006 net_text,
1007 "extra_dict",
1008 "params",
1009 "net_type",
1010 ):
1011 tasks_by_target_record_id[net_text]["extra_dict"]["params"][
1012 "net_type"
1013 ] = "data"
1014
1015 net_item["use"] = "data"
1016 net_item["model"] = interface["type"]
1017 net_item["type"] = interface["type"]
1018 elif (
1019 interface.get("type") == "OM-MGMT"
1020 or interface.get("mgmt-interface")
1021 or interface.get("mgmt-vnf")
1022 ):
1023 net_item["use"] = "mgmt"
1024 else:
1025 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1026 net_item["use"] = "bridge"
1027 net_item["model"] = interface.get("type")
1028
1029 if interface.get("ip-address"):
1030 net_item["ip_address"] = interface["ip-address"]
1031
1032 if interface.get("mac-address"):
1033 net_item["mac_address"] = interface["mac-address"]
1034
1035 net_list.append(net_item)
1036
1037 if interface.get("mgmt-vnf"):
1038 extra_dict["mgmt_vnf_interface"] = iface_index
1039 elif interface.get("mgmt-interface"):
1040 extra_dict["mgmt_vdu_interface"] = iface_index
1041
1042 # cloud config
1043 cloud_config = {}
1044
1045 if target_vdu.get("cloud-init"):
1046 if target_vdu["cloud-init"] not in vdu2cloud_init:
1047 vdu2cloud_init[target_vdu["cloud-init"]] = Ns._get_cloud_init(
1048 db=db,
1049 fs=fs,
1050 location=target_vdu["cloud-init"],
1051 )
1052
1053 cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
1054 cloud_config["user-data"] = Ns._parse_jinja2(
1055 cloud_init_content=cloud_content_,
1056 params=target_vdu.get("additionalParams"),
1057 context=target_vdu["cloud-init"],
1058 )
1059
1060 if target_vdu.get("boot-data-drive"):
1061 cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
1062
1063 ssh_keys = []
1064
1065 if target_vdu.get("ssh-keys"):
1066 ssh_keys += target_vdu.get("ssh-keys")
1067
1068 if target_vdu.get("ssh-access-required"):
1069 ssh_keys.append(ro_nsr_public_key)
1070
1071 if ssh_keys:
1072 cloud_config["key-pairs"] = ssh_keys
1073
1074 persistent_root_disk = {}
1075 disk_list = []
1076 vnfd_id = vnfr["vnfd-id"]
1077 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
1078 for vdu in vnfd.get("vdu", ()):
1079 if vdu["name"] == target_vdu["vdu-name"]:
1080 for vsd in vnfd.get("virtual-storage-desc", ()):
1081 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
1082 root_disk = vsd
1083 if root_disk.get(
1084 "type-of-storage"
1085 ) == "persistent-storage:persistent-storage" and root_disk.get(
1086 "size-of-storage"
1087 ):
1088 persistent_root_disk[vsd["id"]] = {
1089 "image_id": vdu.get("sw-image-desc"),
1090 "size": root_disk["size-of-storage"],
1091 }
1092 disk_list.append(persistent_root_disk[vsd["id"]])
1093
1094 if target_vdu.get("virtual-storages"):
1095 for disk in target_vdu["virtual-storages"]:
1096 if (
1097 disk.get("type-of-storage")
1098 == "persistent-storage:persistent-storage"
1099 and disk["id"] not in persistent_root_disk.keys()
1100 ):
1101 disk_list.append({"size": disk["size-of-storage"]})
1102
1103 affinity_group_list = []
1104
1105 if target_vdu.get("affinity-or-anti-affinity-group-id"):
1106 affinity_group = {}
1107 for affinity_group_id in target_vdu["affinity-or-anti-affinity-group-id"]:
1108 affinity_group_text = (
1109 ns_preffix + ":affinity-or-anti-affinity-group." + affinity_group_id
1110 )
1111
1112 extra_dict["depends_on"].append(affinity_group_text)
1113 affinity_group["affinity_group_id"] = "TASK-" + affinity_group_text
1114 affinity_group_list.append(affinity_group)
1115
1116 extra_dict["params"] = {
1117 "name": "{}-{}-{}-{}".format(
1118 indata["name"][:16],
1119 vnfr["member-vnf-index-ref"][:16],
1120 target_vdu["vdu-name"][:32],
1121 target_vdu.get("count-index") or 0,
1122 ),
1123 "description": target_vdu["vdu-name"],
1124 "start": True,
1125 "image_id": "TASK-" + image_text,
1126 "flavor_id": "TASK-" + flavor_text,
1127 "affinity_group_list": affinity_group_list,
1128 "net_list": net_list,
1129 "cloud_config": cloud_config or None,
1130 "disk_list": disk_list,
1131 "availability_zone_index": None, # TODO
1132 "availability_zone_list": None, # TODO
1133 }
1134
1135 return extra_dict
1136
1137 @staticmethod
1138 def _process_affinity_group_params(
1139 target_affinity_group: Dict[str, Any],
1140 indata: Dict[str, Any],
1141 vim_info: Dict[str, Any],
1142 target_record_id: str,
1143 **kwargs: Dict[str, Any],
1144 ) -> Dict[str, Any]:
1145 """Get affinity or anti-affinity group parameters.
1146
1147 Args:
1148 target_affinity_group (Dict[str, Any]): [description]
1149 indata (Dict[str, Any]): [description]
1150 vim_info (Dict[str, Any]): [description]
1151 target_record_id (str): [description]
1152
1153 Returns:
1154 Dict[str, Any]: [description]
1155 """
1156
1157 extra_dict = {}
1158 affinity_group_data = {
1159 "name": target_affinity_group["name"],
1160 "type": target_affinity_group["type"],
1161 "scope": target_affinity_group["scope"],
1162 }
1163
1164 if target_affinity_group.get("vim-affinity-group-id"):
1165 affinity_group_data["vim-affinity-group-id"] = target_affinity_group[
1166 "vim-affinity-group-id"
1167 ]
1168
1169 extra_dict["params"] = {
1170 "affinity_group_data": affinity_group_data,
1171 }
1172
1173 return extra_dict
1174
1175 @staticmethod
1176 def _process_recreate_vdu_params(
1177 existing_vdu: Dict[str, Any],
1178 db_nsr: Dict[str, Any],
1179 vim_info: Dict[str, Any],
1180 target_record_id: str,
1181 target_id: str,
1182 **kwargs: Dict[str, Any],
1183 ) -> Dict[str, Any]:
1184 """Function to process VDU parameters to recreate.
1185
1186 Args:
1187 existing_vdu (Dict[str, Any]): [description]
1188 db_nsr (Dict[str, Any]): [description]
1189 vim_info (Dict[str, Any]): [description]
1190 target_record_id (str): [description]
1191 target_id (str): [description]
1192
1193 Returns:
1194 Dict[str, Any]: [description]
1195 """
1196 vnfr = kwargs.get("vnfr")
1197 vdu2cloud_init = kwargs.get("vdu2cloud_init")
1198 # logger = kwargs.get("logger")
1199 db = kwargs.get("db")
1200 fs = kwargs.get("fs")
1201 ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1202
1203 extra_dict = {}
1204 net_list = []
1205
1206 vim_details = {}
1207 vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
1208 if vim_details_text:
1209 vim_details = yaml.safe_load(f"{vim_details_text}")
1210
1211 for iface_index, interface in enumerate(existing_vdu["interfaces"]):
1212
1213 if "port-security-enabled" in interface:
1214 interface["port_security"] = interface.pop("port-security-enabled")
1215
1216 if "port-security-disable-strategy" in interface:
1217 interface["port_security_disable_strategy"] = interface.pop(
1218 "port-security-disable-strategy"
1219 )
1220
1221 net_item = {
1222 x: v
1223 for x, v in interface.items()
1224 if x
1225 in (
1226 "name",
1227 "vpci",
1228 "port_security",
1229 "port_security_disable_strategy",
1230 "floating_ip",
1231 )
1232 }
1233 existing_ifaces = existing_vdu["vim_info"][target_id].get("interfaces", [])
1234 net_id = next(
1235 (
1236 i["vim_net_id"]
1237 for i in existing_ifaces
1238 if i["ip_address"] == interface["ip-address"]
1239 ),
1240 None,
1241 )
1242
1243 net_item["net_id"] = net_id
1244 net_item["type"] = "virtual"
1245
1246 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1247 # TODO floating_ip: True/False (or it can be None)
1248 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1249 net_item["use"] = "data"
1250 net_item["model"] = interface["type"]
1251 net_item["type"] = interface["type"]
1252 elif (
1253 interface.get("type") == "OM-MGMT"
1254 or interface.get("mgmt-interface")
1255 or interface.get("mgmt-vnf")
1256 ):
1257 net_item["use"] = "mgmt"
1258 else:
1259 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1260 net_item["use"] = "bridge"
1261 net_item["model"] = interface.get("type")
1262
1263 if interface.get("ip-address"):
1264 net_item["ip_address"] = interface["ip-address"]
1265
1266 if interface.get("mac-address"):
1267 net_item["mac_address"] = interface["mac-address"]
1268
1269 net_list.append(net_item)
1270
1271 if interface.get("mgmt-vnf"):
1272 extra_dict["mgmt_vnf_interface"] = iface_index
1273 elif interface.get("mgmt-interface"):
1274 extra_dict["mgmt_vdu_interface"] = iface_index
1275
1276 # cloud config
1277 cloud_config = {}
1278
1279 if existing_vdu.get("cloud-init"):
1280 if existing_vdu["cloud-init"] not in vdu2cloud_init:
1281 vdu2cloud_init[existing_vdu["cloud-init"]] = Ns._get_cloud_init(
1282 db=db,
1283 fs=fs,
1284 location=existing_vdu["cloud-init"],
1285 )
1286
1287 cloud_content_ = vdu2cloud_init[existing_vdu["cloud-init"]]
1288 cloud_config["user-data"] = Ns._parse_jinja2(
1289 cloud_init_content=cloud_content_,
1290 params=existing_vdu.get("additionalParams"),
1291 context=existing_vdu["cloud-init"],
1292 )
1293
1294 if existing_vdu.get("boot-data-drive"):
1295 cloud_config["boot-data-drive"] = existing_vdu.get("boot-data-drive")
1296
1297 ssh_keys = []
1298
1299 if existing_vdu.get("ssh-keys"):
1300 ssh_keys += existing_vdu.get("ssh-keys")
1301
1302 if existing_vdu.get("ssh-access-required"):
1303 ssh_keys.append(ro_nsr_public_key)
1304
1305 if ssh_keys:
1306 cloud_config["key-pairs"] = ssh_keys
1307
1308 disk_list = []
1309 for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
1310 disk_list.append({"vim_id": vol_id["id"]})
1311
1312 affinity_group_list = []
1313
1314 if existing_vdu.get("affinity-or-anti-affinity-group-id"):
1315 affinity_group = {}
1316 for affinity_group_id in existing_vdu["affinity-or-anti-affinity-group-id"]:
1317 for group in db_nsr.get("affinity-or-anti-affinity-group"):
1318 if (
1319 group["id"] == affinity_group_id
1320 and group["vim_info"][target_id].get("vim_id", None) is not None
1321 ):
1322 affinity_group["affinity_group_id"] = group["vim_info"][
1323 target_id
1324 ].get("vim_id", None)
1325 affinity_group_list.append(affinity_group)
1326
1327 extra_dict["params"] = {
1328 "name": "{}-{}-{}-{}".format(
1329 db_nsr["name"][:16],
1330 vnfr["member-vnf-index-ref"][:16],
1331 existing_vdu["vdu-name"][:32],
1332 existing_vdu.get("count-index") or 0,
1333 ),
1334 "description": existing_vdu["vdu-name"],
1335 "start": True,
1336 "image_id": vim_details["image"]["id"],
1337 "flavor_id": vim_details["flavor"]["id"],
1338 "affinity_group_list": affinity_group_list,
1339 "net_list": net_list,
1340 "cloud_config": cloud_config or None,
1341 "disk_list": disk_list,
1342 "availability_zone_index": None, # TODO
1343 "availability_zone_list": None, # TODO
1344 }
1345
1346 return extra_dict
1347
1348 def calculate_diff_items(
1349 self,
1350 indata,
1351 db_nsr,
1352 db_ro_nsr,
1353 db_nsr_update,
1354 item,
1355 tasks_by_target_record_id,
1356 action_id,
1357 nsr_id,
1358 task_index,
1359 vnfr_id=None,
1360 vnfr=None,
1361 ):
1362 """Function that returns the incremental changes (creation, deletion)
1363 related to a specific item `item` to be done. This function should be
1364 called for NS instantiation, NS termination, NS update to add a new VNF
1365 or a new VLD, remove a VNF or VLD, etc.
1366 Item can be `net`, `flavor`, `image` or `vdu`.
1367 It takes a list of target items from indata (which came from the REST API)
1368 and compares with the existing items from db_ro_nsr, identifying the
1369 incremental changes to be done. During the comparison, it calls the method
1370 `process_params` (which was passed as parameter, and is particular for each
1371 `item`)
1372
1373 Args:
1374 indata (Dict[str, Any]): deployment info
1375 db_nsr: NSR record from DB
1376 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1377 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1378 item (str): element to process (net, vdu...)
1379 tasks_by_target_record_id (Dict[str, Any]):
1380 [<target_record_id>, <task>]
1381 action_id (str): action id
1382 nsr_id (str): NSR id
1383 task_index (number): task index to add to task name
1384 vnfr_id (str): VNFR id
1385 vnfr (Dict[str, Any]): VNFR info
1386
1387 Returns:
1388 List: list with the incremental changes (deletes, creates) for each item
1389 number: current task index
1390 """
1391
1392 diff_items = []
1393 db_path = ""
1394 db_record = ""
1395 target_list = []
1396 existing_list = []
1397 process_params = None
1398 vdu2cloud_init = indata.get("cloud_init_content") or {}
1399 ro_nsr_public_key = db_ro_nsr["public_key"]
1400
1401 # According to the type of item, the path, the target_list,
1402 # the existing_list and the method to process params are set
1403 db_path = self.db_path_map[item]
1404 process_params = self.process_params_function_map[item]
1405 if item in ("net", "vdu"):
1406 # This case is specific for the NS VLD (not applied to VDU)
1407 if vnfr is None:
1408 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1409 target_list = indata.get("ns", []).get(db_path, [])
1410 existing_list = db_nsr.get(db_path, [])
1411 # This case is common for VNF VLDs and VNF VDUs
1412 else:
1413 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
1414 target_vnf = next(
1415 (vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id),
1416 None,
1417 )
1418 target_list = target_vnf.get(db_path, []) if target_vnf else []
1419 existing_list = vnfr.get(db_path, [])
1420 elif item in ("image", "flavor", "affinity-or-anti-affinity-group"):
1421 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1422 target_list = indata.get(item, [])
1423 existing_list = db_nsr.get(item, [])
1424 else:
1425 raise NsException("Item not supported: {}", item)
1426
1427 # ensure all the target_list elements has an "id". If not assign the index as id
1428 if target_list is None:
1429 target_list = []
1430 for target_index, tl in enumerate(target_list):
1431 if tl and not tl.get("id"):
1432 tl["id"] = str(target_index)
1433
1434 # step 1 items (networks,vdus,...) to be deleted/updated
1435 for item_index, existing_item in enumerate(existing_list):
1436 target_item = next(
1437 (t for t in target_list if t["id"] == existing_item["id"]),
1438 None,
1439 )
1440
1441 for target_vim, existing_viminfo in existing_item.get(
1442 "vim_info", {}
1443 ).items():
1444 if existing_viminfo is None:
1445 continue
1446
1447 if target_item:
1448 target_viminfo = target_item.get("vim_info", {}).get(target_vim)
1449 else:
1450 target_viminfo = None
1451
1452 if target_viminfo is None:
1453 # must be deleted
1454 self._assign_vim(target_vim)
1455 target_record_id = "{}.{}".format(db_record, existing_item["id"])
1456 item_ = item
1457
1458 if target_vim.startswith("sdn"):
1459 # item must be sdn-net instead of net if target_vim is a sdn
1460 item_ = "sdn_net"
1461 target_record_id += ".sdn"
1462
1463 deployment_info = {
1464 "action_id": action_id,
1465 "nsr_id": nsr_id,
1466 "task_index": task_index,
1467 }
1468
1469 diff_items.append(
1470 {
1471 "deployment_info": deployment_info,
1472 "target_id": target_vim,
1473 "item": item_,
1474 "action": "DELETE",
1475 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1476 "target_record_id": target_record_id,
1477 }
1478 )
1479 task_index += 1
1480
1481 # step 2 items (networks,vdus,...) to be created
1482 for target_item in target_list:
1483 item_index = -1
1484
1485 for item_index, existing_item in enumerate(existing_list):
1486 if existing_item["id"] == target_item["id"]:
1487 break
1488 else:
1489 item_index += 1
1490 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1491 existing_list.append(target_item)
1492 existing_item = None
1493
1494 for target_vim, target_viminfo in target_item.get("vim_info", {}).items():
1495 existing_viminfo = None
1496
1497 if existing_item:
1498 existing_viminfo = existing_item.get("vim_info", {}).get(target_vim)
1499
1500 if existing_viminfo is not None:
1501 continue
1502
1503 target_record_id = "{}.{}".format(db_record, target_item["id"])
1504 item_ = item
1505
1506 if target_vim.startswith("sdn"):
1507 # item must be sdn-net instead of net if target_vim is a sdn
1508 item_ = "sdn_net"
1509 target_record_id += ".sdn"
1510
1511 kwargs = {}
1512 self.logger.warning(
1513 "ns.calculate_diff_items target_item={}".format(target_item)
1514 )
1515 if process_params == Ns._process_vdu_params:
1516 self.logger.warning(
1517 "calculate_diff_items self.fs={}".format(self.fs)
1518 )
1519 kwargs.update(
1520 {
1521 "vnfr_id": vnfr_id,
1522 "nsr_id": nsr_id,
1523 "vnfr": vnfr,
1524 "vdu2cloud_init": vdu2cloud_init,
1525 "tasks_by_target_record_id": tasks_by_target_record_id,
1526 "logger": self.logger,
1527 "db": self.db,
1528 "fs": self.fs,
1529 "ro_nsr_public_key": ro_nsr_public_key,
1530 }
1531 )
1532 self.logger.warning("calculate_diff_items kwargs={}".format(kwargs))
1533
1534 extra_dict = process_params(
1535 target_item,
1536 indata,
1537 target_viminfo,
1538 target_record_id,
1539 **kwargs,
1540 )
1541 self._assign_vim(target_vim)
1542
1543 deployment_info = {
1544 "action_id": action_id,
1545 "nsr_id": nsr_id,
1546 "task_index": task_index,
1547 }
1548
1549 new_item = {
1550 "deployment_info": deployment_info,
1551 "target_id": target_vim,
1552 "item": item_,
1553 "action": "CREATE",
1554 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1555 "target_record_id": target_record_id,
1556 "extra_dict": extra_dict,
1557 "common_id": target_item.get("common_id", None),
1558 }
1559 diff_items.append(new_item)
1560 tasks_by_target_record_id[target_record_id] = new_item
1561 task_index += 1
1562
1563 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1564
1565 return diff_items, task_index
1566
1567 def calculate_all_differences_to_deploy(
1568 self,
1569 indata,
1570 nsr_id,
1571 db_nsr,
1572 db_vnfrs,
1573 db_ro_nsr,
1574 db_nsr_update,
1575 db_vnfrs_update,
1576 action_id,
1577 tasks_by_target_record_id,
1578 ):
1579 """This method calculates the ordered list of items (`changes_list`)
1580 to be created and deleted.
1581
1582 Args:
1583 indata (Dict[str, Any]): deployment info
1584 nsr_id (str): NSR id
1585 db_nsr: NSR record from DB
1586 db_vnfrs: VNFRS record from DB
1587 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1588 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1589 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
1590 action_id (str): action id
1591 tasks_by_target_record_id (Dict[str, Any]):
1592 [<target_record_id>, <task>]
1593
1594 Returns:
1595 List: ordered list of items to be created and deleted.
1596 """
1597
1598 task_index = 0
1599 # set list with diffs:
1600 changes_list = []
1601
1602 # NS vld, image and flavor
1603 for item in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
1604 self.logger.debug("process NS={} {}".format(nsr_id, item))
1605 diff_items, task_index = self.calculate_diff_items(
1606 indata=indata,
1607 db_nsr=db_nsr,
1608 db_ro_nsr=db_ro_nsr,
1609 db_nsr_update=db_nsr_update,
1610 item=item,
1611 tasks_by_target_record_id=tasks_by_target_record_id,
1612 action_id=action_id,
1613 nsr_id=nsr_id,
1614 task_index=task_index,
1615 vnfr_id=None,
1616 )
1617 changes_list += diff_items
1618
1619 # VNF vlds and vdus
1620 for vnfr_id, vnfr in db_vnfrs.items():
1621 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1622 for item in ["net", "vdu"]:
1623 self.logger.debug("process VNF={} {}".format(vnfr_id, item))
1624 diff_items, task_index = self.calculate_diff_items(
1625 indata=indata,
1626 db_nsr=db_nsr,
1627 db_ro_nsr=db_ro_nsr,
1628 db_nsr_update=db_vnfrs_update[vnfr["_id"]],
1629 item=item,
1630 tasks_by_target_record_id=tasks_by_target_record_id,
1631 action_id=action_id,
1632 nsr_id=nsr_id,
1633 task_index=task_index,
1634 vnfr_id=vnfr_id,
1635 vnfr=vnfr,
1636 )
1637 changes_list += diff_items
1638
1639 return changes_list
1640
1641 def define_all_tasks(
1642 self,
1643 changes_list,
1644 db_new_tasks,
1645 tasks_by_target_record_id,
1646 ):
1647 """Function to create all the task structures obtanied from
1648 the method calculate_all_differences_to_deploy
1649
1650 Args:
1651 changes_list (List): ordered list of items to be created or deleted
1652 db_new_tasks (List): tasks list to be created
1653 action_id (str): action id
1654 tasks_by_target_record_id (Dict[str, Any]):
1655 [<target_record_id>, <task>]
1656
1657 """
1658
1659 for change in changes_list:
1660 task = Ns._create_task(
1661 deployment_info=change["deployment_info"],
1662 target_id=change["target_id"],
1663 item=change["item"],
1664 action=change["action"],
1665 target_record=change["target_record"],
1666 target_record_id=change["target_record_id"],
1667 extra_dict=change.get("extra_dict", None),
1668 )
1669
1670 self.logger.warning("ns.define_all_tasks task={}".format(task))
1671 tasks_by_target_record_id[change["target_record_id"]] = task
1672 db_new_tasks.append(task)
1673
1674 if change.get("common_id"):
1675 task["common_id"] = change["common_id"]
1676
1677 def upload_all_tasks(
1678 self,
1679 db_new_tasks,
1680 now,
1681 ):
1682 """Function to save all tasks in the common DB
1683
1684 Args:
1685 db_new_tasks (List): tasks list to be created
1686 now (time): current time
1687
1688 """
1689
1690 nb_ro_tasks = 0 # for logging
1691
1692 for db_task in db_new_tasks:
1693 target_id = db_task.pop("target_id")
1694 common_id = db_task.get("common_id")
1695
1696 # Do not chek tasks with vim_status DELETED
1697 # because in manual heealing there are two tasks for the same vdur:
1698 # one with vim_status deleted and the other one with the actual VM status.
1699
1700 if common_id:
1701 if self.db.set_one(
1702 "ro_tasks",
1703 q_filter={
1704 "target_id": target_id,
1705 "tasks.common_id": common_id,
1706 "vim_info.vim_status.ne": "DELETED",
1707 },
1708 update_dict={"to_check_at": now, "modified_at": now},
1709 push={"tasks": db_task},
1710 fail_on_empty=False,
1711 ):
1712 continue
1713
1714 if not self.db.set_one(
1715 "ro_tasks",
1716 q_filter={
1717 "target_id": target_id,
1718 "tasks.target_record": db_task["target_record"],
1719 "vim_info.vim_status.ne": "DELETED",
1720 },
1721 update_dict={"to_check_at": now, "modified_at": now},
1722 push={"tasks": db_task},
1723 fail_on_empty=False,
1724 ):
1725 # Create a ro_task
1726 self.logger.debug("Updating database, Creating ro_tasks")
1727 db_ro_task = Ns._create_ro_task(target_id, db_task)
1728 nb_ro_tasks += 1
1729 self.db.create("ro_tasks", db_ro_task)
1730
1731 self.logger.debug(
1732 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1733 nb_ro_tasks, len(db_new_tasks), db_new_tasks
1734 )
1735 )
1736
1737 def upload_recreate_tasks(
1738 self,
1739 db_new_tasks,
1740 now,
1741 ):
1742 """Function to save recreate tasks in the common DB
1743
1744 Args:
1745 db_new_tasks (List): tasks list to be created
1746 now (time): current time
1747
1748 """
1749
1750 nb_ro_tasks = 0 # for logging
1751
1752 for db_task in db_new_tasks:
1753 target_id = db_task.pop("target_id")
1754 self.logger.warning("target_id={} db_task={}".format(target_id, db_task))
1755
1756 action = db_task.get("action", None)
1757
1758 # Create a ro_task
1759 self.logger.debug("Updating database, Creating ro_tasks")
1760 db_ro_task = Ns._create_ro_task(target_id, db_task)
1761
1762 # If DELETE task: the associated created items should be removed
1763 # (except persistent volumes):
1764 if action == "DELETE":
1765 db_ro_task["vim_info"]["created"] = True
1766 db_ro_task["vim_info"]["created_items"] = db_task.get(
1767 "created_items", {}
1768 )
1769 db_ro_task["vim_info"]["volumes_to_hold"] = db_task.get(
1770 "volumes_to_hold", []
1771 )
1772 db_ro_task["vim_info"]["vim_id"] = db_task.get("vim_id", None)
1773
1774 nb_ro_tasks += 1
1775 self.logger.warning("upload_all_tasks db_ro_task={}".format(db_ro_task))
1776 self.db.create("ro_tasks", db_ro_task)
1777
1778 self.logger.debug(
1779 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1780 nb_ro_tasks, len(db_new_tasks), db_new_tasks
1781 )
1782 )
1783
1784 def _prepare_created_items_for_healing(
1785 self,
1786 nsr_id,
1787 target_record,
1788 ):
1789 created_items = {}
1790 # Get created_items from ro_task
1791 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
1792 for ro_task in ro_tasks:
1793 for task in ro_task["tasks"]:
1794 if (
1795 task["target_record"] == target_record
1796 and task["action"] == "CREATE"
1797 and ro_task["vim_info"]["created_items"]
1798 ):
1799 created_items = ro_task["vim_info"]["created_items"]
1800 break
1801
1802 return created_items
1803
1804 def _prepare_persistent_volumes_for_healing(
1805 self,
1806 target_id,
1807 existing_vdu,
1808 ):
1809 # The associated volumes of the VM shouldn't be removed
1810 volumes_list = []
1811 vim_details = {}
1812 vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
1813 if vim_details_text:
1814 vim_details = yaml.safe_load(f"{vim_details_text}")
1815
1816 for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
1817 volumes_list.append(vol_id["id"])
1818
1819 return volumes_list
1820
1821 def prepare_changes_to_recreate(
1822 self,
1823 indata,
1824 nsr_id,
1825 db_nsr,
1826 db_vnfrs,
1827 db_ro_nsr,
1828 action_id,
1829 tasks_by_target_record_id,
1830 ):
1831 """This method will obtain an ordered list of items (`changes_list`)
1832 to be created and deleted to meet the recreate request.
1833 """
1834
1835 self.logger.debug(
1836 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id, indata)
1837 )
1838
1839 task_index = 0
1840 # set list with diffs:
1841 changes_list = []
1842 db_path = self.db_path_map["vdu"]
1843 target_list = indata.get("healVnfData", {})
1844 vdu2cloud_init = indata.get("cloud_init_content") or {}
1845 ro_nsr_public_key = db_ro_nsr["public_key"]
1846
1847 # Check each VNF of the target
1848 for target_vnf in target_list:
1849 # Find this VNF in the list from DB
1850 vnfr_id = target_vnf.get("vnfInstanceId", None)
1851 if vnfr_id:
1852 existing_vnf = db_vnfrs.get(vnfr_id)
1853 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
1854 # vim_account_id = existing_vnf.get("vim-account-id", "")
1855
1856 # Check each VDU of this VNF
1857 for target_vdu in target_vnf["additionalParams"].get("vdu", None):
1858 vdu_name = target_vdu.get("vdu-id", None)
1859 # For multi instance VDU count-index is mandatory
1860 # For single session VDU count-indes is 0
1861 count_index = target_vdu.get("count-index", 0)
1862 item_index = 0
1863 existing_instance = None
1864 for instance in existing_vnf.get("vdur", None):
1865 if (
1866 instance["vdu-name"] == vdu_name
1867 and instance["count-index"] == count_index
1868 ):
1869 existing_instance = instance
1870 break
1871 else:
1872 item_index += 1
1873
1874 target_record_id = "{}.{}".format(db_record, existing_instance["id"])
1875
1876 # The target VIM is the one already existing in DB to recreate
1877 for target_vim, target_viminfo in existing_instance.get(
1878 "vim_info", {}
1879 ).items():
1880 # step 1 vdu to be deleted
1881 self._assign_vim(target_vim)
1882 deployment_info = {
1883 "action_id": action_id,
1884 "nsr_id": nsr_id,
1885 "task_index": task_index,
1886 }
1887
1888 target_record = f"{db_record}.{item_index}.vim_info.{target_vim}"
1889 created_items = self._prepare_created_items_for_healing(
1890 nsr_id, target_record
1891 )
1892
1893 volumes_to_hold = self._prepare_persistent_volumes_for_healing(
1894 target_vim, existing_instance
1895 )
1896
1897 # Specific extra params for recreate tasks:
1898 extra_dict = {
1899 "created_items": created_items,
1900 "vim_id": existing_instance["vim-id"],
1901 "volumes_to_hold": volumes_to_hold,
1902 }
1903
1904 changes_list.append(
1905 {
1906 "deployment_info": deployment_info,
1907 "target_id": target_vim,
1908 "item": "vdu",
1909 "action": "DELETE",
1910 "target_record": target_record,
1911 "target_record_id": target_record_id,
1912 "extra_dict": extra_dict,
1913 }
1914 )
1915 delete_task_id = f"{action_id}:{task_index}"
1916 task_index += 1
1917
1918 # step 2 vdu to be created
1919 kwargs = {}
1920 kwargs.update(
1921 {
1922 "vnfr_id": vnfr_id,
1923 "nsr_id": nsr_id,
1924 "vnfr": existing_vnf,
1925 "vdu2cloud_init": vdu2cloud_init,
1926 "tasks_by_target_record_id": tasks_by_target_record_id,
1927 "logger": self.logger,
1928 "db": self.db,
1929 "fs": self.fs,
1930 "ro_nsr_public_key": ro_nsr_public_key,
1931 }
1932 )
1933
1934 extra_dict = self._process_recreate_vdu_params(
1935 existing_instance,
1936 db_nsr,
1937 target_viminfo,
1938 target_record_id,
1939 target_vim,
1940 **kwargs,
1941 )
1942
1943 # The CREATE task depens on the DELETE task
1944 extra_dict["depends_on"] = [delete_task_id]
1945
1946 # Add volumes created from created_items if any
1947 # Ports should be deleted with delete task and automatically created with create task
1948 volumes = {}
1949 for k, v in created_items.items():
1950 try:
1951 k_item, _, k_id = k.partition(":")
1952 if k_item == "volume":
1953 volumes[k] = v
1954 except Exception as e:
1955 self.logger.error(
1956 "Error evaluating created item {}: {}".format(k, e)
1957 )
1958 extra_dict["previous_created_volumes"] = volumes
1959
1960 deployment_info = {
1961 "action_id": action_id,
1962 "nsr_id": nsr_id,
1963 "task_index": task_index,
1964 }
1965 self._assign_vim(target_vim)
1966
1967 new_item = {
1968 "deployment_info": deployment_info,
1969 "target_id": target_vim,
1970 "item": "vdu",
1971 "action": "CREATE",
1972 "target_record": target_record,
1973 "target_record_id": target_record_id,
1974 "extra_dict": extra_dict,
1975 }
1976 changes_list.append(new_item)
1977 tasks_by_target_record_id[target_record_id] = new_item
1978 task_index += 1
1979
1980 return changes_list
1981
1982 def recreate(self, session, indata, version, nsr_id, *args, **kwargs):
1983 self.logger.debug("ns.recreate nsr_id={} indata={}".format(nsr_id, indata))
1984 # TODO: validate_input(indata, recreate_schema)
1985 action_id = indata.get("action_id", str(uuid4()))
1986 # get current deployment
1987 db_vnfrs = {} # vnf's info indexed by _id
1988 step = ""
1989 logging_text = "Recreate nsr_id={} action_id={} indata={}".format(
1990 nsr_id, action_id, indata
1991 )
1992 self.logger.debug(logging_text + "Enter")
1993
1994 try:
1995 step = "Getting ns and vnfr record from db"
1996 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1997 db_new_tasks = []
1998 tasks_by_target_record_id = {}
1999 # read from db: vnf's of this ns
2000 step = "Getting vnfrs from db"
2001 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2002 self.logger.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list))
2003
2004 if not db_vnfrs_list:
2005 raise NsException("Cannot obtain associated VNF for ns")
2006
2007 for vnfr in db_vnfrs_list:
2008 db_vnfrs[vnfr["_id"]] = vnfr
2009
2010 now = time()
2011 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
2012 self.logger.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr))
2013
2014 if not db_ro_nsr:
2015 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
2016
2017 with self.write_lock:
2018 # NS
2019 step = "process NS elements"
2020 changes_list = self.prepare_changes_to_recreate(
2021 indata=indata,
2022 nsr_id=nsr_id,
2023 db_nsr=db_nsr,
2024 db_vnfrs=db_vnfrs,
2025 db_ro_nsr=db_ro_nsr,
2026 action_id=action_id,
2027 tasks_by_target_record_id=tasks_by_target_record_id,
2028 )
2029
2030 self.define_all_tasks(
2031 changes_list=changes_list,
2032 db_new_tasks=db_new_tasks,
2033 tasks_by_target_record_id=tasks_by_target_record_id,
2034 )
2035
2036 # Delete all ro_tasks registered for the targets vdurs (target_record)
2037 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2038 # So remove all task related to target record.
2039 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2040 for change in changes_list:
2041 for ro_task in ro_tasks:
2042 for task in ro_task["tasks"]:
2043 if task["target_record"] == change["target_record"]:
2044 self.db.del_one(
2045 "ro_tasks",
2046 q_filter={
2047 "_id": ro_task["_id"],
2048 "modified_at": ro_task["modified_at"],
2049 },
2050 fail_on_empty=False,
2051 )
2052
2053 step = "Updating database, Appending tasks to ro_tasks"
2054 self.upload_recreate_tasks(
2055 db_new_tasks=db_new_tasks,
2056 now=now,
2057 )
2058
2059 self.logger.debug(
2060 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2061 )
2062
2063 return (
2064 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2065 action_id,
2066 True,
2067 )
2068 except Exception as e:
2069 if isinstance(e, (DbException, NsException)):
2070 self.logger.error(
2071 logging_text + "Exit Exception while '{}': {}".format(step, e)
2072 )
2073 else:
2074 e = traceback_format_exc()
2075 self.logger.critical(
2076 logging_text + "Exit Exception while '{}': {}".format(step, e),
2077 exc_info=True,
2078 )
2079
2080 raise NsException(e)
2081
2082 def deploy(self, session, indata, version, nsr_id, *args, **kwargs):
2083 self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata))
2084 validate_input(indata, deploy_schema)
2085 action_id = indata.get("action_id", str(uuid4()))
2086 task_index = 0
2087 # get current deployment
2088 db_nsr_update = {} # update operation on nsrs
2089 db_vnfrs_update = {}
2090 db_vnfrs = {} # vnf's info indexed by _id
2091 step = ""
2092 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2093 self.logger.debug(logging_text + "Enter")
2094
2095 try:
2096 step = "Getting ns and vnfr record from db"
2097 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2098 self.logger.debug("ns.deploy: db_nsr={}".format(db_nsr))
2099 db_new_tasks = []
2100 tasks_by_target_record_id = {}
2101 # read from db: vnf's of this ns
2102 step = "Getting vnfrs from db"
2103 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2104
2105 if not db_vnfrs_list:
2106 raise NsException("Cannot obtain associated VNF for ns")
2107
2108 for vnfr in db_vnfrs_list:
2109 db_vnfrs[vnfr["_id"]] = vnfr
2110 db_vnfrs_update[vnfr["_id"]] = {}
2111 self.logger.debug("ns.deploy db_vnfrs={}".format(db_vnfrs))
2112
2113 now = time()
2114 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
2115
2116 if not db_ro_nsr:
2117 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
2118
2119 # check that action_id is not in the list of actions. Suffixed with :index
2120 if action_id in db_ro_nsr["actions"]:
2121 index = 1
2122
2123 while True:
2124 new_action_id = "{}:{}".format(action_id, index)
2125
2126 if new_action_id not in db_ro_nsr["actions"]:
2127 action_id = new_action_id
2128 self.logger.debug(
2129 logging_text
2130 + "Changing action_id in use to {}".format(action_id)
2131 )
2132 break
2133
2134 index += 1
2135
2136 def _process_action(indata):
2137 nonlocal db_new_tasks
2138 nonlocal action_id
2139 nonlocal nsr_id
2140 nonlocal task_index
2141 nonlocal db_vnfrs
2142 nonlocal db_ro_nsr
2143
2144 if indata["action"]["action"] == "inject_ssh_key":
2145 key = indata["action"].get("key")
2146 user = indata["action"].get("user")
2147 password = indata["action"].get("password")
2148
2149 for vnf in indata.get("vnf", ()):
2150 if vnf["_id"] not in db_vnfrs:
2151 raise NsException("Invalid vnf={}".format(vnf["_id"]))
2152
2153 db_vnfr = db_vnfrs[vnf["_id"]]
2154
2155 for target_vdu in vnf.get("vdur", ()):
2156 vdu_index, vdur = next(
2157 (
2158 i_v
2159 for i_v in enumerate(db_vnfr["vdur"])
2160 if i_v[1]["id"] == target_vdu["id"]
2161 ),
2162 (None, None),
2163 )
2164
2165 if not vdur:
2166 raise NsException(
2167 "Invalid vdu vnf={}.{}".format(
2168 vnf["_id"], target_vdu["id"]
2169 )
2170 )
2171
2172 target_vim, vim_info = next(
2173 k_v for k_v in vdur["vim_info"].items()
2174 )
2175 self._assign_vim(target_vim)
2176 target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
2177 vnf["_id"], vdu_index
2178 )
2179 extra_dict = {
2180 "depends_on": [
2181 "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
2182 ],
2183 "params": {
2184 "ip_address": vdur.get("ip-address"),
2185 "user": user,
2186 "key": key,
2187 "password": password,
2188 "private_key": db_ro_nsr["private_key"],
2189 "salt": db_ro_nsr["_id"],
2190 "schema_version": db_ro_nsr["_admin"][
2191 "schema_version"
2192 ],
2193 },
2194 }
2195
2196 deployment_info = {
2197 "action_id": action_id,
2198 "nsr_id": nsr_id,
2199 "task_index": task_index,
2200 }
2201
2202 task = Ns._create_task(
2203 deployment_info=deployment_info,
2204 target_id=target_vim,
2205 item="vdu",
2206 action="EXEC",
2207 target_record=target_record,
2208 target_record_id=None,
2209 extra_dict=extra_dict,
2210 )
2211
2212 task_index = deployment_info.get("task_index")
2213
2214 db_new_tasks.append(task)
2215
2216 with self.write_lock:
2217 if indata.get("action"):
2218 _process_action(indata)
2219 else:
2220 # compute network differences
2221 # NS
2222 step = "process NS elements"
2223 changes_list = self.calculate_all_differences_to_deploy(
2224 indata=indata,
2225 nsr_id=nsr_id,
2226 db_nsr=db_nsr,
2227 db_vnfrs=db_vnfrs,
2228 db_ro_nsr=db_ro_nsr,
2229 db_nsr_update=db_nsr_update,
2230 db_vnfrs_update=db_vnfrs_update,
2231 action_id=action_id,
2232 tasks_by_target_record_id=tasks_by_target_record_id,
2233 )
2234 self.define_all_tasks(
2235 changes_list=changes_list,
2236 db_new_tasks=db_new_tasks,
2237 tasks_by_target_record_id=tasks_by_target_record_id,
2238 )
2239
2240 step = "Updating database, Appending tasks to ro_tasks"
2241 self.upload_all_tasks(
2242 db_new_tasks=db_new_tasks,
2243 now=now,
2244 )
2245
2246 step = "Updating database, nsrs"
2247 if db_nsr_update:
2248 self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
2249
2250 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
2251 if db_vnfr_update:
2252 step = "Updating database, vnfrs={}".format(vnfr_id)
2253 self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
2254
2255 self.logger.debug(
2256 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2257 )
2258
2259 return (
2260 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2261 action_id,
2262 True,
2263 )
2264 except Exception as e:
2265 if isinstance(e, (DbException, NsException)):
2266 self.logger.error(
2267 logging_text + "Exit Exception while '{}': {}".format(step, e)
2268 )
2269 else:
2270 e = traceback_format_exc()
2271 self.logger.critical(
2272 logging_text + "Exit Exception while '{}': {}".format(step, e),
2273 exc_info=True,
2274 )
2275
2276 raise NsException(e)
2277
2278 def delete(self, session, indata, version, nsr_id, *args, **kwargs):
2279 self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
2280 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2281
2282 with self.write_lock:
2283 try:
2284 NsWorker.delete_db_tasks(self.db, nsr_id, None)
2285 except NsWorkerException as e:
2286 raise NsException(e)
2287
2288 return None, None, True
2289
2290 def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2291 self.logger.debug(
2292 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2293 version, nsr_id, action_id, indata
2294 )
2295 )
2296 task_list = []
2297 done = 0
2298 total = 0
2299 ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
2300 global_status = "DONE"
2301 details = []
2302
2303 for ro_task in ro_tasks:
2304 for task in ro_task["tasks"]:
2305 if task and task["action_id"] == action_id:
2306 task_list.append(task)
2307 total += 1
2308
2309 if task["status"] == "FAILED":
2310 global_status = "FAILED"
2311 error_text = "Error at {} {}: {}".format(
2312 task["action"].lower(),
2313 task["item"],
2314 ro_task["vim_info"].get("vim_message") or "unknown",
2315 )
2316 details.append(error_text)
2317 elif task["status"] in ("SCHEDULED", "BUILD"):
2318 if global_status != "FAILED":
2319 global_status = "BUILD"
2320 else:
2321 done += 1
2322
2323 return_data = {
2324 "status": global_status,
2325 "details": ". ".join(details)
2326 if details
2327 else "progress {}/{}".format(done, total),
2328 "nsr_id": nsr_id,
2329 "action_id": action_id,
2330 "tasks": task_list,
2331 }
2332
2333 return return_data, None, True
2334
2335 def recreate_status(
2336 self, session, indata, version, nsr_id, action_id, *args, **kwargs
2337 ):
2338 return self.status(session, indata, version, nsr_id, action_id, *args, **kwargs)
2339
2340 def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2341 print(
2342 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2343 session, indata, version, nsr_id, action_id
2344 )
2345 )
2346
2347 return None, None, True
2348
2349 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2350 nsrs = self.db.get_list("nsrs", {})
2351 return_data = []
2352
2353 for ns in nsrs:
2354 return_data.append({"_id": ns["_id"], "name": ns["name"]})
2355
2356 return return_data, None, True
2357
2358 def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2359 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2360 return_data = []
2361
2362 for ro_task in ro_tasks:
2363 for task in ro_task["tasks"]:
2364 if task["action_id"] not in return_data:
2365 return_data.append(task["action_id"])
2366
2367 return return_data, None, True
2368
2369 def migrate_task(
2370 self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
2371 ):
2372 target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
2373 self._assign_vim(target_vim)
2374 target_record = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu_index)
2375 target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
2376 deployment_info = {
2377 "action_id": action_id,
2378 "nsr_id": nsr_id,
2379 "task_index": task_index,
2380 }
2381
2382 task = Ns._create_task(
2383 deployment_info=deployment_info,
2384 target_id=target_vim,
2385 item="migrate",
2386 action="EXEC",
2387 target_record=target_record,
2388 target_record_id=target_record_id,
2389 extra_dict=extra_dict,
2390 )
2391
2392 return task
2393
2394 def migrate(self, session, indata, version, nsr_id, *args, **kwargs):
2395 task_index = 0
2396 extra_dict = {}
2397 now = time()
2398 action_id = indata.get("action_id", str(uuid4()))
2399 step = ""
2400 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2401 self.logger.debug(logging_text + "Enter")
2402 try:
2403 vnf_instance_id = indata["vnfInstanceId"]
2404 step = "Getting vnfrs from db"
2405 db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
2406 vdu = indata.get("vdu")
2407 migrateToHost = indata.get("migrateToHost")
2408 db_new_tasks = []
2409
2410 with self.write_lock:
2411 if vdu is not None:
2412 vdu_id = indata["vdu"]["vduId"]
2413 vdu_count_index = indata["vdu"].get("vduCountIndex", 0)
2414 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
2415 if (
2416 vdu["vdu-id-ref"] == vdu_id
2417 and vdu["count-index"] == vdu_count_index
2418 ):
2419 extra_dict["params"] = {
2420 "vim_vm_id": vdu["vim-id"],
2421 "migrate_host": migrateToHost,
2422 "vdu_vim_info": vdu["vim_info"],
2423 }
2424 step = "Creating migration task for vdu:{}".format(vdu)
2425 task = self.migrate_task(
2426 vdu,
2427 db_vnfr,
2428 vdu_index,
2429 action_id,
2430 nsr_id,
2431 task_index,
2432 extra_dict,
2433 )
2434 db_new_tasks.append(task)
2435 task_index += 1
2436 break
2437 else:
2438
2439 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
2440 extra_dict["params"] = {
2441 "vim_vm_id": vdu["vim-id"],
2442 "migrate_host": migrateToHost,
2443 "vdu_vim_info": vdu["vim_info"],
2444 }
2445 step = "Creating migration task for vdu:{}".format(vdu)
2446 task = self.migrate_task(
2447 vdu,
2448 db_vnfr,
2449 vdu_index,
2450 action_id,
2451 nsr_id,
2452 task_index,
2453 extra_dict,
2454 )
2455 db_new_tasks.append(task)
2456 task_index += 1
2457
2458 self.upload_all_tasks(
2459 db_new_tasks=db_new_tasks,
2460 now=now,
2461 )
2462
2463 self.logger.debug(
2464 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2465 )
2466 return (
2467 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2468 action_id,
2469 True,
2470 )
2471 except Exception as e:
2472 if isinstance(e, (DbException, NsException)):
2473 self.logger.error(
2474 logging_text + "Exit Exception while '{}': {}".format(step, e)
2475 )
2476 else:
2477 e = traceback_format_exc()
2478 self.logger.critical(
2479 logging_text + "Exit Exception while '{}': {}".format(step, e),
2480 exc_info=True,
2481 )
2482 raise NsException(e)