Feature 10909: Heal operation for VDU
[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
23 import yaml
24 from threading import Lock
25 from time import time
26 from traceback import format_exc as traceback_format_exc
27 from typing import Any, Dict, Tuple, Type
28 from uuid import uuid4
29
30 from cryptography.hazmat.backends import default_backend as crypto_default_backend
31 from cryptography.hazmat.primitives import serialization as crypto_serialization
32 from cryptography.hazmat.primitives.asymmetric import rsa
33 from jinja2 import (
34 Environment,
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
55 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
56 min_common_version = "0.1.16"
57
58
59 class NsException(Exception):
60 def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
61 self.http_code = http_code
62 super(Exception, self).__init__(message)
63
64
65 def get_process_id():
66 """
67 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
68 will provide a random one
69 :return: Obtained ID
70 """
71 # Try getting docker id. If fails, get pid
72 try:
73 with open("/proc/self/cgroup", "r") as f:
74 text_id_ = f.readline()
75 _, _, text_id = text_id_.rpartition("/")
76 text_id = text_id.replace("\n", "")[:12]
77
78 if text_id:
79 return text_id
80 except Exception:
81 pass
82
83 # Return a random id
84 return "".join(random_choice("0123456789abcdef") for _ in range(12))
85
86
87 def versiontuple(v):
88 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
89 filled = []
90
91 for point in v.split("."):
92 filled.append(point.zfill(8))
93
94 return tuple(filled)
95
96
97 class Ns(object):
98 def __init__(self):
99 self.db = None
100 self.fs = None
101 self.msg = None
102 self.config = None
103 # self.operations = None
104 self.logger = None
105 # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
106 # If done now it will not be linked to parent not getting its handler and level
107 self.map_topic = {}
108 self.write_lock = None
109 self.vims_assigned = {}
110 self.next_worker = 0
111 self.plugins = {}
112 self.workers = []
113 self.process_params_function_map = {
114 "net": Ns._process_net_params,
115 "image": Ns._process_image_params,
116 "flavor": Ns._process_flavor_params,
117 "vdu": Ns._process_vdu_params,
118 "affinity-or-anti-affinity-group": Ns._process_affinity_group_params,
119 }
120 self.db_path_map = {
121 "net": "vld",
122 "image": "image",
123 "flavor": "flavor",
124 "vdu": "vdur",
125 "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group",
126 }
127
128 def init_db(self, target_version):
129 pass
130
131 def start(self, config):
132 """
133 Connect to database, filesystem storage, and messaging
134 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
135 :param config: Configuration of db, storage, etc
136 :return: None
137 """
138 self.config = config
139 self.config["process_id"] = get_process_id() # used for HA identity
140 self.logger = logging.getLogger("ro.ns")
141
142 # check right version of common
143 if versiontuple(common_version) < versiontuple(min_common_version):
144 raise NsException(
145 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
146 common_version, min_common_version
147 )
148 )
149
150 try:
151 if not self.db:
152 if config["database"]["driver"] == "mongo":
153 self.db = dbmongo.DbMongo()
154 self.db.db_connect(config["database"])
155 elif config["database"]["driver"] == "memory":
156 self.db = dbmemory.DbMemory()
157 self.db.db_connect(config["database"])
158 else:
159 raise NsException(
160 "Invalid configuration param '{}' at '[database]':'driver'".format(
161 config["database"]["driver"]
162 )
163 )
164
165 if not self.fs:
166 if config["storage"]["driver"] == "local":
167 self.fs = fslocal.FsLocal()
168 self.fs.fs_connect(config["storage"])
169 elif config["storage"]["driver"] == "mongo":
170 self.fs = fsmongo.FsMongo()
171 self.fs.fs_connect(config["storage"])
172 elif config["storage"]["driver"] is None:
173 pass
174 else:
175 raise NsException(
176 "Invalid configuration param '{}' at '[storage]':'driver'".format(
177 config["storage"]["driver"]
178 )
179 )
180
181 if not self.msg:
182 if config["message"]["driver"] == "local":
183 self.msg = msglocal.MsgLocal()
184 self.msg.connect(config["message"])
185 elif config["message"]["driver"] == "kafka":
186 self.msg = msgkafka.MsgKafka()
187 self.msg.connect(config["message"])
188 else:
189 raise NsException(
190 "Invalid configuration param '{}' at '[message]':'driver'".format(
191 config["message"]["driver"]
192 )
193 )
194
195 # TODO load workers to deal with exising database tasks
196
197 self.write_lock = Lock()
198 except (DbException, FsException, MsgException) as e:
199 raise NsException(str(e), http_code=e.http_code)
200
201 def get_assigned_vims(self):
202 return list(self.vims_assigned.keys())
203
204 def stop(self):
205 try:
206 if self.db:
207 self.db.db_disconnect()
208
209 if self.fs:
210 self.fs.fs_disconnect()
211
212 if self.msg:
213 self.msg.disconnect()
214
215 self.write_lock = None
216 except (DbException, FsException, MsgException) as e:
217 raise NsException(str(e), http_code=e.http_code)
218
219 for worker in self.workers:
220 worker.insert_task(("terminate",))
221
222 def _create_worker(self):
223 """
224 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
225 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
226 return the index of the assigned worker thread. Worker threads are storead at self.workers
227 """
228 # Look for a thread in idle status
229 worker_id = next(
230 (
231 i
232 for i in range(len(self.workers))
233 if self.workers[i] and self.workers[i].idle
234 ),
235 None,
236 )
237
238 if worker_id is not None:
239 # unset idle status to avoid race conditions
240 self.workers[worker_id].idle = False
241 else:
242 worker_id = len(self.workers)
243
244 if worker_id < self.config["global"]["server.ns_threads"]:
245 # create a new worker
246 self.workers.append(
247 NsWorker(worker_id, self.config, self.plugins, self.db)
248 )
249 self.workers[worker_id].start()
250 else:
251 # reached maximum number of threads, assign VIM to an existing one
252 worker_id = self.next_worker
253 self.next_worker = (self.next_worker + 1) % self.config["global"][
254 "server.ns_threads"
255 ]
256
257 return worker_id
258
259 def assign_vim(self, target_id):
260 with self.write_lock:
261 return self._assign_vim(target_id)
262
263 def _assign_vim(self, target_id):
264 if target_id not in self.vims_assigned:
265 worker_id = self.vims_assigned[target_id] = self._create_worker()
266 self.workers[worker_id].insert_task(("load_vim", target_id))
267
268 def reload_vim(self, target_id):
269 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
270 # this is because database VIM information is cached for threads working with SDN
271 with self.write_lock:
272 for worker in self.workers:
273 if worker and not worker.idle:
274 worker.insert_task(("reload_vim", target_id))
275
276 def unload_vim(self, target_id):
277 with self.write_lock:
278 return self._unload_vim(target_id)
279
280 def _unload_vim(self, target_id):
281 if target_id in self.vims_assigned:
282 worker_id = self.vims_assigned[target_id]
283 self.workers[worker_id].insert_task(("unload_vim", target_id))
284 del self.vims_assigned[target_id]
285
286 def check_vim(self, target_id):
287 with self.write_lock:
288 if target_id in self.vims_assigned:
289 worker_id = self.vims_assigned[target_id]
290 else:
291 worker_id = self._create_worker()
292
293 worker = self.workers[worker_id]
294 worker.insert_task(("check_vim", target_id))
295
296 def unload_unused_vims(self):
297 with self.write_lock:
298 vims_to_unload = []
299
300 for target_id in self.vims_assigned:
301 if not self.db.get_one(
302 "ro_tasks",
303 q_filter={
304 "target_id": target_id,
305 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
306 },
307 fail_on_empty=False,
308 ):
309 vims_to_unload.append(target_id)
310
311 for target_id in vims_to_unload:
312 self._unload_vim(target_id)
313
314 @staticmethod
315 def _get_cloud_init(
316 db: Type[DbBase],
317 fs: Type[FsBase],
318 location: str,
319 ) -> str:
320 """This method reads cloud init from a file.
321
322 Note: Not used as cloud init content is provided in the http body.
323
324 Args:
325 db (Type[DbBase]): [description]
326 fs (Type[FsBase]): [description]
327 location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
328
329 Raises:
330 NsException: [description]
331 NsException: [description]
332
333 Returns:
334 str: [description]
335 """
336 vnfd_id, _, other = location.partition(":")
337 _type, _, name = other.partition(":")
338 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
339
340 if _type == "file":
341 base_folder = vnfd["_admin"]["storage"]
342 cloud_init_file = "{}/{}/cloud_init/{}".format(
343 base_folder["folder"], base_folder["pkg-dir"], name
344 )
345
346 if not fs:
347 raise NsException(
348 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
349 cloud_init_file
350 )
351 )
352
353 with fs.file_open(cloud_init_file, "r") as ci_file:
354 cloud_init_content = ci_file.read()
355 elif _type == "vdu":
356 cloud_init_content = vnfd["vdu"][int(name)]["cloud-init"]
357 else:
358 raise NsException("Mismatch descriptor for cloud init: {}".format(location))
359
360 return cloud_init_content
361
362 @staticmethod
363 def _parse_jinja2(
364 cloud_init_content: str,
365 params: Dict[str, Any],
366 context: str,
367 ) -> str:
368 """Function that processes the cloud init to replace Jinja2 encoded parameters.
369
370 Args:
371 cloud_init_content (str): [description]
372 params (Dict[str, Any]): [description]
373 context (str): [description]
374
375 Raises:
376 NsException: [description]
377 NsException: [description]
378
379 Returns:
380 str: [description]
381 """
382 try:
383 env = Environment(undefined=StrictUndefined)
384 template = env.from_string(cloud_init_content)
385
386 return template.render(params or {})
387 except UndefinedError as e:
388 raise NsException(
389 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
390 "inside the 'additionalParamsForVnf' block".format(e, context)
391 )
392 except (TemplateError, TemplateNotFound) as e:
393 raise NsException(
394 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
395 context, e
396 )
397 )
398
399 def _create_db_ro_nsrs(self, nsr_id, now):
400 try:
401 key = rsa.generate_private_key(
402 backend=crypto_default_backend(), public_exponent=65537, key_size=2048
403 )
404 private_key = key.private_bytes(
405 crypto_serialization.Encoding.PEM,
406 crypto_serialization.PrivateFormat.PKCS8,
407 crypto_serialization.NoEncryption(),
408 )
409 public_key = key.public_key().public_bytes(
410 crypto_serialization.Encoding.OpenSSH,
411 crypto_serialization.PublicFormat.OpenSSH,
412 )
413 private_key = private_key.decode("utf8")
414 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
415 i = private_key.find("\n")
416 private_key = "-----BEGIN RSA PRIVATE KEY-----" + private_key[i:]
417 public_key = public_key.decode("utf8")
418 except Exception as e:
419 raise NsException("Cannot create ssh-keys: {}".format(e))
420
421 schema_version = "1.1"
422 private_key_encrypted = self.db.encrypt(
423 private_key, schema_version=schema_version, salt=nsr_id
424 )
425 db_content = {
426 "_id": nsr_id,
427 "_admin": {
428 "created": now,
429 "modified": now,
430 "schema_version": schema_version,
431 },
432 "public_key": public_key,
433 "private_key": private_key_encrypted,
434 "actions": [],
435 }
436 self.db.create("ro_nsrs", db_content)
437
438 return db_content
439
440 @staticmethod
441 def _create_task(
442 deployment_info: Dict[str, Any],
443 target_id: str,
444 item: str,
445 action: str,
446 target_record: str,
447 target_record_id: str,
448 extra_dict: Dict[str, Any] = None,
449 ) -> Dict[str, Any]:
450 """Function to create task dict from deployment information.
451
452 Args:
453 deployment_info (Dict[str, Any]): [description]
454 target_id (str): [description]
455 item (str): [description]
456 action (str): [description]
457 target_record (str): [description]
458 target_record_id (str): [description]
459 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
460
461 Returns:
462 Dict[str, Any]: [description]
463 """
464 task = {
465 "target_id": target_id, # it will be removed before pushing at database
466 "action_id": deployment_info.get("action_id"),
467 "nsr_id": deployment_info.get("nsr_id"),
468 "task_id": f"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
469 "status": "SCHEDULED",
470 "action": action,
471 "item": item,
472 "target_record": target_record,
473 "target_record_id": target_record_id,
474 }
475
476 if extra_dict:
477 task.update(extra_dict) # params, find_params, depends_on
478
479 deployment_info["task_index"] = deployment_info.get("task_index", 0) + 1
480
481 return task
482
483 @staticmethod
484 def _create_ro_task(
485 target_id: str,
486 task: Dict[str, Any],
487 ) -> Dict[str, Any]:
488 """Function to create an RO task from task information.
489
490 Args:
491 target_id (str): [description]
492 task (Dict[str, Any]): [description]
493
494 Returns:
495 Dict[str, Any]: [description]
496 """
497 now = time()
498
499 _id = task.get("task_id")
500 db_ro_task = {
501 "_id": _id,
502 "locked_by": None,
503 "locked_at": 0.0,
504 "target_id": target_id,
505 "vim_info": {
506 "created": False,
507 "created_items": None,
508 "vim_id": None,
509 "vim_name": None,
510 "vim_status": None,
511 "vim_details": 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 (i["vim_net_id"] for i in existing_ifaces if i["ip_address"] == interface["ip-address"]),
1236 None,
1237 )
1238
1239 net_item["net_id"] = net_id
1240 net_item["type"] = "virtual"
1241
1242 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1243 # TODO floating_ip: True/False (or it can be None)
1244 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1245 net_item["use"] = "data"
1246 net_item["model"] = interface["type"]
1247 net_item["type"] = interface["type"]
1248 elif (
1249 interface.get("type") == "OM-MGMT"
1250 or interface.get("mgmt-interface")
1251 or interface.get("mgmt-vnf")
1252 ):
1253 net_item["use"] = "mgmt"
1254 else:
1255 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1256 net_item["use"] = "bridge"
1257 net_item["model"] = interface.get("type")
1258
1259 if interface.get("ip-address"):
1260 net_item["ip_address"] = interface["ip-address"]
1261
1262 if interface.get("mac-address"):
1263 net_item["mac_address"] = interface["mac-address"]
1264
1265 net_list.append(net_item)
1266
1267 if interface.get("mgmt-vnf"):
1268 extra_dict["mgmt_vnf_interface"] = iface_index
1269 elif interface.get("mgmt-interface"):
1270 extra_dict["mgmt_vdu_interface"] = iface_index
1271
1272 # cloud config
1273 cloud_config = {}
1274
1275 if existing_vdu.get("cloud-init"):
1276 if existing_vdu["cloud-init"] not in vdu2cloud_init:
1277 vdu2cloud_init[existing_vdu["cloud-init"]] = Ns._get_cloud_init(
1278 db=db,
1279 fs=fs,
1280 location=existing_vdu["cloud-init"],
1281 )
1282
1283 cloud_content_ = vdu2cloud_init[existing_vdu["cloud-init"]]
1284 cloud_config["user-data"] = Ns._parse_jinja2(
1285 cloud_init_content=cloud_content_,
1286 params=existing_vdu.get("additionalParams"),
1287 context=existing_vdu["cloud-init"],
1288 )
1289
1290 if existing_vdu.get("boot-data-drive"):
1291 cloud_config["boot-data-drive"] = existing_vdu.get("boot-data-drive")
1292
1293 ssh_keys = []
1294
1295 if existing_vdu.get("ssh-keys"):
1296 ssh_keys += existing_vdu.get("ssh-keys")
1297
1298 if existing_vdu.get("ssh-access-required"):
1299 ssh_keys.append(ro_nsr_public_key)
1300
1301 if ssh_keys:
1302 cloud_config["key-pairs"] = ssh_keys
1303
1304 disk_list = []
1305 for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
1306 disk_list.append({"vim_id": vol_id["id"]})
1307
1308 affinity_group_list = []
1309
1310 if existing_vdu.get("affinity-or-anti-affinity-group-id"):
1311 affinity_group = {}
1312 for affinity_group_id in existing_vdu["affinity-or-anti-affinity-group-id"]:
1313 for group in db_nsr.get("affinity-or-anti-affinity-group"):
1314 if group["id"] == affinity_group_id and group["vim_info"][target_id].get("vim_id", None) is not None:
1315 affinity_group["affinity_group_id"] = group["vim_info"][target_id].get("vim_id", None)
1316 affinity_group_list.append(affinity_group)
1317
1318 extra_dict["params"] = {
1319 "name": "{}-{}-{}-{}".format(
1320 db_nsr["name"][:16],
1321 vnfr["member-vnf-index-ref"][:16],
1322 existing_vdu["vdu-name"][:32],
1323 existing_vdu.get("count-index") or 0,
1324 ),
1325 "description": existing_vdu["vdu-name"],
1326 "start": True,
1327 "image_id": vim_details["image"]["id"],
1328 "flavor_id": vim_details["flavor"]["id"],
1329 "affinity_group_list": affinity_group_list,
1330 "net_list": net_list,
1331 "cloud_config": cloud_config or None,
1332 "disk_list": disk_list,
1333 "availability_zone_index": None, # TODO
1334 "availability_zone_list": None, # TODO
1335 }
1336
1337 return extra_dict
1338
1339 def calculate_diff_items(
1340 self,
1341 indata,
1342 db_nsr,
1343 db_ro_nsr,
1344 db_nsr_update,
1345 item,
1346 tasks_by_target_record_id,
1347 action_id,
1348 nsr_id,
1349 task_index,
1350 vnfr_id=None,
1351 vnfr=None,
1352 ):
1353 """Function that returns the incremental changes (creation, deletion)
1354 related to a specific item `item` to be done. This function should be
1355 called for NS instantiation, NS termination, NS update to add a new VNF
1356 or a new VLD, remove a VNF or VLD, etc.
1357 Item can be `net`, `flavor`, `image` or `vdu`.
1358 It takes a list of target items from indata (which came from the REST API)
1359 and compares with the existing items from db_ro_nsr, identifying the
1360 incremental changes to be done. During the comparison, it calls the method
1361 `process_params` (which was passed as parameter, and is particular for each
1362 `item`)
1363
1364 Args:
1365 indata (Dict[str, Any]): deployment info
1366 db_nsr: NSR record from DB
1367 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1368 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1369 item (str): element to process (net, vdu...)
1370 tasks_by_target_record_id (Dict[str, Any]):
1371 [<target_record_id>, <task>]
1372 action_id (str): action id
1373 nsr_id (str): NSR id
1374 task_index (number): task index to add to task name
1375 vnfr_id (str): VNFR id
1376 vnfr (Dict[str, Any]): VNFR info
1377
1378 Returns:
1379 List: list with the incremental changes (deletes, creates) for each item
1380 number: current task index
1381 """
1382
1383 diff_items = []
1384 db_path = ""
1385 db_record = ""
1386 target_list = []
1387 existing_list = []
1388 process_params = None
1389 vdu2cloud_init = indata.get("cloud_init_content") or {}
1390 ro_nsr_public_key = db_ro_nsr["public_key"]
1391
1392 # According to the type of item, the path, the target_list,
1393 # the existing_list and the method to process params are set
1394 db_path = self.db_path_map[item]
1395 process_params = self.process_params_function_map[item]
1396 if item in ("net", "vdu"):
1397 # This case is specific for the NS VLD (not applied to VDU)
1398 if vnfr is None:
1399 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1400 target_list = indata.get("ns", []).get(db_path, [])
1401 existing_list = db_nsr.get(db_path, [])
1402 # This case is common for VNF VLDs and VNF VDUs
1403 else:
1404 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
1405 target_vnf = next(
1406 (vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id),
1407 None,
1408 )
1409 target_list = target_vnf.get(db_path, []) if target_vnf else []
1410 existing_list = vnfr.get(db_path, [])
1411 elif item in ("image", "flavor", "affinity-or-anti-affinity-group"):
1412 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1413 target_list = indata.get(item, [])
1414 existing_list = db_nsr.get(item, [])
1415 else:
1416 raise NsException("Item not supported: {}", item)
1417
1418 # ensure all the target_list elements has an "id". If not assign the index as id
1419 if target_list is None:
1420 target_list = []
1421 for target_index, tl in enumerate(target_list):
1422 if tl and not tl.get("id"):
1423 tl["id"] = str(target_index)
1424
1425 # step 1 items (networks,vdus,...) to be deleted/updated
1426 for item_index, existing_item in enumerate(existing_list):
1427 target_item = next(
1428 (t for t in target_list if t["id"] == existing_item["id"]),
1429 None,
1430 )
1431
1432 for target_vim, existing_viminfo in existing_item.get(
1433 "vim_info", {}
1434 ).items():
1435 if existing_viminfo is None:
1436 continue
1437
1438 if target_item:
1439 target_viminfo = target_item.get("vim_info", {}).get(target_vim)
1440 else:
1441 target_viminfo = None
1442
1443 if target_viminfo is None:
1444 # must be deleted
1445 self._assign_vim(target_vim)
1446 target_record_id = "{}.{}".format(db_record, existing_item["id"])
1447 item_ = item
1448
1449 if target_vim.startswith("sdn"):
1450 # item must be sdn-net instead of net if target_vim is a sdn
1451 item_ = "sdn_net"
1452 target_record_id += ".sdn"
1453
1454 deployment_info = {
1455 "action_id": action_id,
1456 "nsr_id": nsr_id,
1457 "task_index": task_index,
1458 }
1459
1460 diff_items.append(
1461 {
1462 "deployment_info": deployment_info,
1463 "target_id": target_vim,
1464 "item": item_,
1465 "action": "DELETE",
1466 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1467 "target_record_id": target_record_id,
1468 }
1469 )
1470 task_index += 1
1471
1472 # step 2 items (networks,vdus,...) to be created
1473 for target_item in target_list:
1474 item_index = -1
1475
1476 for item_index, existing_item in enumerate(existing_list):
1477 if existing_item["id"] == target_item["id"]:
1478 break
1479 else:
1480 item_index += 1
1481 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1482 existing_list.append(target_item)
1483 existing_item = None
1484
1485 for target_vim, target_viminfo in target_item.get("vim_info", {}).items():
1486 existing_viminfo = None
1487
1488 if existing_item:
1489 existing_viminfo = existing_item.get("vim_info", {}).get(target_vim)
1490
1491 if existing_viminfo is not None:
1492 continue
1493
1494 target_record_id = "{}.{}".format(db_record, target_item["id"])
1495 item_ = item
1496
1497 if target_vim.startswith("sdn"):
1498 # item must be sdn-net instead of net if target_vim is a sdn
1499 item_ = "sdn_net"
1500 target_record_id += ".sdn"
1501
1502 kwargs = {}
1503 self.logger.warning(
1504 "ns.calculate_diff_items target_item={}".format(target_item)
1505 )
1506 if process_params == Ns._process_vdu_params:
1507 self.logger.warning(
1508 "calculate_diff_items self.fs={}".format(self.fs)
1509 )
1510 kwargs.update(
1511 {
1512 "vnfr_id": vnfr_id,
1513 "nsr_id": nsr_id,
1514 "vnfr": vnfr,
1515 "vdu2cloud_init": vdu2cloud_init,
1516 "tasks_by_target_record_id": tasks_by_target_record_id,
1517 "logger": self.logger,
1518 "db": self.db,
1519 "fs": self.fs,
1520 "ro_nsr_public_key": ro_nsr_public_key,
1521 }
1522 )
1523 self.logger.warning("calculate_diff_items kwargs={}".format(kwargs))
1524
1525 extra_dict = process_params(
1526 target_item,
1527 indata,
1528 target_viminfo,
1529 target_record_id,
1530 **kwargs,
1531 )
1532 self._assign_vim(target_vim)
1533
1534 deployment_info = {
1535 "action_id": action_id,
1536 "nsr_id": nsr_id,
1537 "task_index": task_index,
1538 }
1539
1540 new_item = {
1541 "deployment_info": deployment_info,
1542 "target_id": target_vim,
1543 "item": item_,
1544 "action": "CREATE",
1545 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1546 "target_record_id": target_record_id,
1547 "extra_dict": extra_dict,
1548 "common_id": target_item.get("common_id", None),
1549 }
1550 diff_items.append(new_item)
1551 tasks_by_target_record_id[target_record_id] = new_item
1552 task_index += 1
1553
1554 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1555
1556 return diff_items, task_index
1557
1558 def calculate_all_differences_to_deploy(
1559 self,
1560 indata,
1561 nsr_id,
1562 db_nsr,
1563 db_vnfrs,
1564 db_ro_nsr,
1565 db_nsr_update,
1566 db_vnfrs_update,
1567 action_id,
1568 tasks_by_target_record_id,
1569 ):
1570 """This method calculates the ordered list of items (`changes_list`)
1571 to be created and deleted.
1572
1573 Args:
1574 indata (Dict[str, Any]): deployment info
1575 nsr_id (str): NSR id
1576 db_nsr: NSR record from DB
1577 db_vnfrs: VNFRS record from DB
1578 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1579 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1580 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
1581 action_id (str): action id
1582 tasks_by_target_record_id (Dict[str, Any]):
1583 [<target_record_id>, <task>]
1584
1585 Returns:
1586 List: ordered list of items to be created and deleted.
1587 """
1588
1589 task_index = 0
1590 # set list with diffs:
1591 changes_list = []
1592
1593 # NS vld, image and flavor
1594 for item in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
1595 self.logger.debug("process NS={} {}".format(nsr_id, item))
1596 diff_items, task_index = self.calculate_diff_items(
1597 indata=indata,
1598 db_nsr=db_nsr,
1599 db_ro_nsr=db_ro_nsr,
1600 db_nsr_update=db_nsr_update,
1601 item=item,
1602 tasks_by_target_record_id=tasks_by_target_record_id,
1603 action_id=action_id,
1604 nsr_id=nsr_id,
1605 task_index=task_index,
1606 vnfr_id=None,
1607 )
1608 changes_list += diff_items
1609
1610 # VNF vlds and vdus
1611 for vnfr_id, vnfr in db_vnfrs.items():
1612 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1613 for item in ["net", "vdu"]:
1614 self.logger.debug("process VNF={} {}".format(vnfr_id, item))
1615 diff_items, task_index = self.calculate_diff_items(
1616 indata=indata,
1617 db_nsr=db_nsr,
1618 db_ro_nsr=db_ro_nsr,
1619 db_nsr_update=db_vnfrs_update[vnfr["_id"]],
1620 item=item,
1621 tasks_by_target_record_id=tasks_by_target_record_id,
1622 action_id=action_id,
1623 nsr_id=nsr_id,
1624 task_index=task_index,
1625 vnfr_id=vnfr_id,
1626 vnfr=vnfr,
1627 )
1628 changes_list += diff_items
1629
1630 return changes_list
1631
1632 def define_all_tasks(
1633 self,
1634 changes_list,
1635 db_new_tasks,
1636 tasks_by_target_record_id,
1637 ):
1638 """Function to create all the task structures obtanied from
1639 the method calculate_all_differences_to_deploy
1640
1641 Args:
1642 changes_list (List): ordered list of items to be created or deleted
1643 db_new_tasks (List): tasks list to be created
1644 action_id (str): action id
1645 tasks_by_target_record_id (Dict[str, Any]):
1646 [<target_record_id>, <task>]
1647
1648 """
1649
1650 for change in changes_list:
1651 task = Ns._create_task(
1652 deployment_info=change["deployment_info"],
1653 target_id=change["target_id"],
1654 item=change["item"],
1655 action=change["action"],
1656 target_record=change["target_record"],
1657 target_record_id=change["target_record_id"],
1658 extra_dict=change.get("extra_dict", None),
1659 )
1660
1661 self.logger.warning(
1662 "ns.define_all_tasks task={}".format(task)
1663 )
1664 tasks_by_target_record_id[change["target_record_id"]] = task
1665 db_new_tasks.append(task)
1666
1667 if change.get("common_id"):
1668 task["common_id"] = change["common_id"]
1669
1670 def upload_all_tasks(
1671 self,
1672 db_new_tasks,
1673 now,
1674 ):
1675 """Function to save all tasks in the common DB
1676
1677 Args:
1678 db_new_tasks (List): tasks list to be created
1679 now (time): current time
1680
1681 """
1682
1683 nb_ro_tasks = 0 # for logging
1684
1685 for db_task in db_new_tasks:
1686 target_id = db_task.pop("target_id")
1687 common_id = db_task.get("common_id")
1688
1689 if common_id:
1690 if self.db.set_one(
1691 "ro_tasks",
1692 q_filter={
1693 "target_id": target_id,
1694 "tasks.common_id": common_id,
1695 },
1696 update_dict={"to_check_at": now, "modified_at": now},
1697 push={"tasks": db_task},
1698 fail_on_empty=False,
1699 ):
1700 continue
1701
1702 if not self.db.set_one(
1703 "ro_tasks",
1704 q_filter={
1705 "target_id": target_id,
1706 "tasks.target_record": db_task["target_record"],
1707 },
1708 update_dict={"to_check_at": now, "modified_at": now},
1709 push={"tasks": db_task},
1710 fail_on_empty=False,
1711 ):
1712 # Create a ro_task
1713 self.logger.debug("Updating database, Creating ro_tasks")
1714 db_ro_task = Ns._create_ro_task(target_id, db_task)
1715 nb_ro_tasks += 1
1716 self.db.create("ro_tasks", db_ro_task)
1717
1718 self.logger.debug(
1719 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1720 nb_ro_tasks, len(db_new_tasks), db_new_tasks
1721 )
1722 )
1723
1724 def upload_recreate_tasks(
1725 self,
1726 db_new_tasks,
1727 now,
1728 ):
1729 """Function to save recreate tasks in the common DB
1730
1731 Args:
1732 db_new_tasks (List): tasks list to be created
1733 now (time): current time
1734
1735 """
1736
1737 nb_ro_tasks = 0 # for logging
1738
1739 for db_task in db_new_tasks:
1740 target_id = db_task.pop("target_id")
1741 self.logger.warning("target_id={} db_task={}".format(target_id, db_task))
1742
1743 action = db_task.get("action", None)
1744
1745 # Create a ro_task
1746 self.logger.debug("Updating database, Creating ro_tasks")
1747 db_ro_task = Ns._create_ro_task(target_id, db_task)
1748
1749 # If DELETE task: the associated created items shoud be removed
1750 # (except persistent volumes):
1751 if action == "DELETE":
1752 db_ro_task["vim_info"]["created"] = True
1753 db_ro_task["vim_info"]["created_items"] = db_task.get("created_items", {})
1754 db_ro_task["vim_info"]["vim_id"] = db_task.get("vim_id", None)
1755
1756 nb_ro_tasks += 1
1757 self.logger.warning("upload_all_tasks db_ro_task={}".format(db_ro_task))
1758 self.db.create("ro_tasks", db_ro_task)
1759
1760 self.logger.debug(
1761 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1762 nb_ro_tasks, len(db_new_tasks), db_new_tasks
1763 )
1764 )
1765
1766 def _prepare_created_items_for_healing(
1767 self,
1768 target_id,
1769 existing_vdu,
1770 ):
1771 # Only ports are considered because created volumes are persistent
1772 ports_list = {}
1773 vim_interfaces = existing_vdu["vim_info"][target_id].get("interfaces", [])
1774 for iface in vim_interfaces:
1775 ports_list["port:" + iface["vim_interface_id"]] = True
1776
1777 return ports_list
1778
1779 def _prepare_persistent_volumes_for_healing(
1780 self,
1781 target_id,
1782 existing_vdu,
1783 ):
1784 # The associated volumes of the VM shouldn't be removed
1785 volumes_list = []
1786 vim_details = {}
1787 vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
1788 if vim_details_text:
1789 vim_details = yaml.safe_load(f"{vim_details_text}")
1790
1791 for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
1792 volumes_list.append(vol_id["id"])
1793
1794 return volumes_list
1795
1796 def prepare_changes_to_recreate(
1797 self,
1798 indata,
1799 nsr_id,
1800 db_nsr,
1801 db_vnfrs,
1802 db_ro_nsr,
1803 action_id,
1804 tasks_by_target_record_id,
1805 ):
1806 """This method will obtain an ordered list of items (`changes_list`)
1807 to be created and deleted to meet the recreate request.
1808 """
1809
1810 self.logger.debug(
1811 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id, indata)
1812 )
1813
1814 task_index = 0
1815 # set list with diffs:
1816 changes_list = []
1817 db_path = self.db_path_map["vdu"]
1818 target_list = indata.get("healVnfData", {})
1819 vdu2cloud_init = indata.get("cloud_init_content") or {}
1820 ro_nsr_public_key = db_ro_nsr["public_key"]
1821
1822 # Check each VNF of the target
1823 for target_vnf in target_list:
1824 # Find this VNF in the list from DB
1825 vnfr_id = target_vnf.get("vnfInstanceId", None)
1826 if vnfr_id:
1827 existing_vnf = db_vnfrs.get(vnfr_id)
1828 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
1829 # vim_account_id = existing_vnf.get("vim-account-id", "")
1830
1831 # Check each VDU of this VNF
1832 for target_vdu in target_vnf["additionalParams"].get("vdu", None):
1833 vdu_name = target_vdu.get("vdu-id", None)
1834 # For multi instance VDU count-index is mandatory
1835 # For single session VDU count-indes is 0
1836 count_index = target_vdu.get("count-index", 0)
1837 item_index = 0
1838 existing_instance = None
1839 for instance in existing_vnf.get("vdur", None):
1840 if (instance["vdu-name"] == vdu_name and instance["count-index"] == count_index):
1841 existing_instance = instance
1842 break
1843 else:
1844 item_index += 1
1845
1846 target_record_id = "{}.{}".format(db_record, existing_instance["id"])
1847
1848 # The target VIM is the one already existing in DB to recreate
1849 for target_vim, target_viminfo in existing_instance.get(
1850 "vim_info", {}
1851 ).items():
1852 # step 1 vdu to be deleted
1853 self._assign_vim(target_vim)
1854 deployment_info = {
1855 "action_id": action_id,
1856 "nsr_id": nsr_id,
1857 "task_index": task_index,
1858 }
1859
1860 target_record = f"{db_record}.{item_index}.vim_info.{target_vim}"
1861 created_items = self._prepare_created_items_for_healing(
1862 target_vim, existing_instance
1863 )
1864
1865 volumes_to_hold = self._prepare_persistent_volumes_for_healing(
1866 target_vim, existing_instance
1867 )
1868
1869 # Specific extra params for recreate tasks:
1870 extra_dict = {
1871 "created_items": created_items,
1872 "vim_id": existing_instance["vim-id"],
1873 "volumes_to_hold": volumes_to_hold,
1874 }
1875
1876 changes_list.append(
1877 {
1878 "deployment_info": deployment_info,
1879 "target_id": target_vim,
1880 "item": "vdu",
1881 "action": "DELETE",
1882 "target_record": target_record,
1883 "target_record_id": target_record_id,
1884 "extra_dict": extra_dict,
1885 }
1886 )
1887 delete_task_id = f"{action_id}:{task_index}"
1888 task_index += 1
1889
1890 # step 2 vdu to be created
1891 kwargs = {}
1892 kwargs.update(
1893 {
1894 "vnfr_id": vnfr_id,
1895 "nsr_id": nsr_id,
1896 "vnfr": existing_vnf,
1897 "vdu2cloud_init": vdu2cloud_init,
1898 "tasks_by_target_record_id": tasks_by_target_record_id,
1899 "logger": self.logger,
1900 "db": self.db,
1901 "fs": self.fs,
1902 "ro_nsr_public_key": ro_nsr_public_key,
1903 }
1904 )
1905
1906 extra_dict = self._process_recreate_vdu_params(
1907 existing_instance,
1908 db_nsr,
1909 target_viminfo,
1910 target_record_id,
1911 target_vim,
1912 **kwargs,
1913 )
1914
1915 # The CREATE task depens on the DELETE task
1916 extra_dict["depends_on"] = [delete_task_id]
1917
1918 deployment_info = {
1919 "action_id": action_id,
1920 "nsr_id": nsr_id,
1921 "task_index": task_index,
1922 }
1923 self._assign_vim(target_vim)
1924
1925 new_item = {
1926 "deployment_info": deployment_info,
1927 "target_id": target_vim,
1928 "item": "vdu",
1929 "action": "CREATE",
1930 "target_record": target_record,
1931 "target_record_id": target_record_id,
1932 "extra_dict": extra_dict,
1933 }
1934 changes_list.append(new_item)
1935 tasks_by_target_record_id[target_record_id] = new_item
1936 task_index += 1
1937
1938 return changes_list
1939
1940 def recreate(self, session, indata, version, nsr_id, *args, **kwargs):
1941 self.logger.debug("ns.recreate nsr_id={} indata={}".format(nsr_id, indata))
1942 # TODO: validate_input(indata, recreate_schema)
1943 action_id = indata.get("action_id", str(uuid4()))
1944 # get current deployment
1945 db_vnfrs = {} # vnf's info indexed by _id
1946 step = ""
1947 logging_text = "Recreate nsr_id={} action_id={} indata={}".format(
1948 nsr_id, action_id, indata
1949 )
1950 self.logger.debug(logging_text + "Enter")
1951
1952 try:
1953 step = "Getting ns and vnfr record from db"
1954 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1955 db_new_tasks = []
1956 tasks_by_target_record_id = {}
1957 # read from db: vnf's of this ns
1958 step = "Getting vnfrs from db"
1959 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1960 self.logger.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list))
1961
1962 if not db_vnfrs_list:
1963 raise NsException("Cannot obtain associated VNF for ns")
1964
1965 for vnfr in db_vnfrs_list:
1966 db_vnfrs[vnfr["_id"]] = vnfr
1967
1968 now = time()
1969 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
1970 self.logger.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr))
1971
1972 if not db_ro_nsr:
1973 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
1974
1975 with self.write_lock:
1976 # NS
1977 step = "process NS elements"
1978 changes_list = self.prepare_changes_to_recreate(
1979 indata=indata,
1980 nsr_id=nsr_id,
1981 db_nsr=db_nsr,
1982 db_vnfrs=db_vnfrs,
1983 db_ro_nsr=db_ro_nsr,
1984 action_id=action_id,
1985 tasks_by_target_record_id=tasks_by_target_record_id,
1986 )
1987
1988 self.define_all_tasks(
1989 changes_list=changes_list,
1990 db_new_tasks=db_new_tasks,
1991 tasks_by_target_record_id=tasks_by_target_record_id,
1992 )
1993
1994 # Delete all ro_tasks registered for the targets vdurs (target_record)
1995 # If task of type CREATE exist then vim will try to get info form deleted VMs.
1996 # So remove all task related to target record.
1997 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
1998 for change in changes_list:
1999 for ro_task in ro_tasks:
2000 for task in ro_task["tasks"]:
2001 if task["target_record"] == change["target_record"]:
2002 self.db.del_one(
2003 "ro_tasks",
2004 q_filter={
2005 "_id": ro_task["_id"],
2006 "modified_at": ro_task["modified_at"],
2007 },
2008 fail_on_empty=False,
2009 )
2010
2011 step = "Updating database, Appending tasks to ro_tasks"
2012 self.upload_recreate_tasks(
2013 db_new_tasks=db_new_tasks,
2014 now=now,
2015 )
2016
2017 self.logger.debug(
2018 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2019 )
2020
2021 return (
2022 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2023 action_id,
2024 True,
2025 )
2026 except Exception as e:
2027 if isinstance(e, (DbException, NsException)):
2028 self.logger.error(
2029 logging_text + "Exit Exception while '{}': {}".format(step, e)
2030 )
2031 else:
2032 e = traceback_format_exc()
2033 self.logger.critical(
2034 logging_text + "Exit Exception while '{}': {}".format(step, e),
2035 exc_info=True,
2036 )
2037
2038 raise NsException(e)
2039
2040 def deploy(self, session, indata, version, nsr_id, *args, **kwargs):
2041 self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata))
2042 validate_input(indata, deploy_schema)
2043 action_id = indata.get("action_id", str(uuid4()))
2044 task_index = 0
2045 # get current deployment
2046 db_nsr_update = {} # update operation on nsrs
2047 db_vnfrs_update = {}
2048 db_vnfrs = {} # vnf's info indexed by _id
2049 step = ""
2050 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2051 self.logger.debug(logging_text + "Enter")
2052
2053 try:
2054 step = "Getting ns and vnfr record from db"
2055 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2056 self.logger.debug("ns.deploy: db_nsr={}".format(db_nsr))
2057 db_new_tasks = []
2058 tasks_by_target_record_id = {}
2059 # read from db: vnf's of this ns
2060 step = "Getting vnfrs from db"
2061 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2062
2063 if not db_vnfrs_list:
2064 raise NsException("Cannot obtain associated VNF for ns")
2065
2066 for vnfr in db_vnfrs_list:
2067 db_vnfrs[vnfr["_id"]] = vnfr
2068 db_vnfrs_update[vnfr["_id"]] = {}
2069 self.logger.debug("ns.deploy db_vnfrs={}".format(db_vnfrs))
2070
2071 now = time()
2072 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
2073
2074 if not db_ro_nsr:
2075 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
2076
2077 # check that action_id is not in the list of actions. Suffixed with :index
2078 if action_id in db_ro_nsr["actions"]:
2079 index = 1
2080
2081 while True:
2082 new_action_id = "{}:{}".format(action_id, index)
2083
2084 if new_action_id not in db_ro_nsr["actions"]:
2085 action_id = new_action_id
2086 self.logger.debug(
2087 logging_text
2088 + "Changing action_id in use to {}".format(action_id)
2089 )
2090 break
2091
2092 index += 1
2093
2094 def _process_action(indata):
2095 nonlocal db_new_tasks
2096 nonlocal action_id
2097 nonlocal nsr_id
2098 nonlocal task_index
2099 nonlocal db_vnfrs
2100 nonlocal db_ro_nsr
2101
2102 if indata["action"]["action"] == "inject_ssh_key":
2103 key = indata["action"].get("key")
2104 user = indata["action"].get("user")
2105 password = indata["action"].get("password")
2106
2107 for vnf in indata.get("vnf", ()):
2108 if vnf["_id"] not in db_vnfrs:
2109 raise NsException("Invalid vnf={}".format(vnf["_id"]))
2110
2111 db_vnfr = db_vnfrs[vnf["_id"]]
2112
2113 for target_vdu in vnf.get("vdur", ()):
2114 vdu_index, vdur = next(
2115 (
2116 i_v
2117 for i_v in enumerate(db_vnfr["vdur"])
2118 if i_v[1]["id"] == target_vdu["id"]
2119 ),
2120 (None, None),
2121 )
2122
2123 if not vdur:
2124 raise NsException(
2125 "Invalid vdu vnf={}.{}".format(
2126 vnf["_id"], target_vdu["id"]
2127 )
2128 )
2129
2130 target_vim, vim_info = next(
2131 k_v for k_v in vdur["vim_info"].items()
2132 )
2133 self._assign_vim(target_vim)
2134 target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
2135 vnf["_id"], vdu_index
2136 )
2137 extra_dict = {
2138 "depends_on": [
2139 "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
2140 ],
2141 "params": {
2142 "ip_address": vdur.get("ip-address"),
2143 "user": user,
2144 "key": key,
2145 "password": password,
2146 "private_key": db_ro_nsr["private_key"],
2147 "salt": db_ro_nsr["_id"],
2148 "schema_version": db_ro_nsr["_admin"][
2149 "schema_version"
2150 ],
2151 },
2152 }
2153
2154 deployment_info = {
2155 "action_id": action_id,
2156 "nsr_id": nsr_id,
2157 "task_index": task_index,
2158 }
2159
2160 task = Ns._create_task(
2161 deployment_info=deployment_info,
2162 target_id=target_vim,
2163 item="vdu",
2164 action="EXEC",
2165 target_record=target_record,
2166 target_record_id=None,
2167 extra_dict=extra_dict,
2168 )
2169
2170 task_index = deployment_info.get("task_index")
2171
2172 db_new_tasks.append(task)
2173
2174 with self.write_lock:
2175 if indata.get("action"):
2176 _process_action(indata)
2177 else:
2178 # compute network differences
2179 # NS
2180 step = "process NS elements"
2181 changes_list = self.calculate_all_differences_to_deploy(
2182 indata=indata,
2183 nsr_id=nsr_id,
2184 db_nsr=db_nsr,
2185 db_vnfrs=db_vnfrs,
2186 db_ro_nsr=db_ro_nsr,
2187 db_nsr_update=db_nsr_update,
2188 db_vnfrs_update=db_vnfrs_update,
2189 action_id=action_id,
2190 tasks_by_target_record_id=tasks_by_target_record_id,
2191 )
2192 self.define_all_tasks(
2193 changes_list=changes_list,
2194 db_new_tasks=db_new_tasks,
2195 tasks_by_target_record_id=tasks_by_target_record_id,
2196 )
2197
2198 step = "Updating database, Appending tasks to ro_tasks"
2199 self.upload_all_tasks(
2200 db_new_tasks=db_new_tasks,
2201 now=now,
2202 )
2203
2204 step = "Updating database, nsrs"
2205 if db_nsr_update:
2206 self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
2207
2208 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
2209 if db_vnfr_update:
2210 step = "Updating database, vnfrs={}".format(vnfr_id)
2211 self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
2212
2213 self.logger.debug(
2214 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2215 )
2216
2217 return (
2218 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2219 action_id,
2220 True,
2221 )
2222 except Exception as e:
2223 if isinstance(e, (DbException, NsException)):
2224 self.logger.error(
2225 logging_text + "Exit Exception while '{}': {}".format(step, e)
2226 )
2227 else:
2228 e = traceback_format_exc()
2229 self.logger.critical(
2230 logging_text + "Exit Exception while '{}': {}".format(step, e),
2231 exc_info=True,
2232 )
2233
2234 raise NsException(e)
2235
2236 def delete(self, session, indata, version, nsr_id, *args, **kwargs):
2237 self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
2238 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2239
2240 with self.write_lock:
2241 try:
2242 NsWorker.delete_db_tasks(self.db, nsr_id, None)
2243 except NsWorkerException as e:
2244 raise NsException(e)
2245
2246 return None, None, True
2247
2248 def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2249 self.logger.debug(
2250 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2251 version, nsr_id, action_id, indata
2252 )
2253 )
2254 task_list = []
2255 done = 0
2256 total = 0
2257 ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
2258 global_status = "DONE"
2259 details = []
2260
2261 for ro_task in ro_tasks:
2262 for task in ro_task["tasks"]:
2263 if task and task["action_id"] == action_id:
2264 task_list.append(task)
2265 total += 1
2266
2267 if task["status"] == "FAILED":
2268 global_status = "FAILED"
2269 error_text = "Error at {} {}: {}".format(
2270 task["action"].lower(),
2271 task["item"],
2272 ro_task["vim_info"].get("vim_details") or "unknown",
2273 )
2274 details.append(error_text)
2275 elif task["status"] in ("SCHEDULED", "BUILD"):
2276 if global_status != "FAILED":
2277 global_status = "BUILD"
2278 else:
2279 done += 1
2280
2281 return_data = {
2282 "status": global_status,
2283 "details": ". ".join(details)
2284 if details
2285 else "progress {}/{}".format(done, total),
2286 "nsr_id": nsr_id,
2287 "action_id": action_id,
2288 "tasks": task_list,
2289 }
2290
2291 return return_data, None, True
2292
2293 def recreate_status(
2294 self, session, indata, version, nsr_id, action_id, *args, **kwargs
2295 ):
2296 return self.status(session, indata, version, nsr_id, action_id, *args, **kwargs)
2297
2298 def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2299 print(
2300 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2301 session, indata, version, nsr_id, action_id
2302 )
2303 )
2304
2305 return None, None, True
2306
2307 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2308 nsrs = self.db.get_list("nsrs", {})
2309 return_data = []
2310
2311 for ns in nsrs:
2312 return_data.append({"_id": ns["_id"], "name": ns["name"]})
2313
2314 return return_data, None, True
2315
2316 def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2317 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2318 return_data = []
2319
2320 for ro_task in ro_tasks:
2321 for task in ro_task["tasks"]:
2322 if task["action_id"] not in return_data:
2323 return_data.append(task["action_id"])
2324
2325 return return_data, None, True