Feature 10922: Stop, start and rebuild
[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 # If the position info is provided for all the interfaces, it will be sorted
962 # according to position number ascendingly.
963 if all(i.get("position") for i in target_vdu["interfaces"]):
964 sorted_interfaces = sorted(
965 target_vdu["interfaces"],
966 key=lambda x: (x.get("position") is None, x.get("position")),
967 )
968 target_vdu["interfaces"] = sorted_interfaces
969
970 # If the position info is provided for some interfaces but not all of them, the interfaces
971 # which has specific position numbers will be placed and others' positions will not be taken care.
972 else:
973 if any(i.get("position") for i in target_vdu["interfaces"]):
974 n = len(target_vdu["interfaces"])
975 sorted_interfaces = [-1] * n
976 k, m = 0, 0
977 while k < n:
978 if target_vdu["interfaces"][k].get("position"):
979 idx = target_vdu["interfaces"][k]["position"]
980 sorted_interfaces[idx - 1] = target_vdu["interfaces"][k]
981 k += 1
982 while m < n:
983 if not target_vdu["interfaces"][m].get("position"):
984 idy = sorted_interfaces.index(-1)
985 sorted_interfaces[idy] = target_vdu["interfaces"][m]
986 m += 1
987
988 target_vdu["interfaces"] = sorted_interfaces
989
990 # If the position info is not provided for the interfaces, interfaces will be attached
991 # according to the order in the VNFD.
992 for iface_index, interface in enumerate(target_vdu["interfaces"]):
993 if interface.get("ns-vld-id"):
994 net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
995 elif interface.get("vnf-vld-id"):
996 net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
997 else:
998 logger.error(
999 "Interface {} from vdu {} not connected to any vld".format(
1000 iface_index, target_vdu["vdu-name"]
1001 )
1002 )
1003
1004 continue # interface not connected to any vld
1005
1006 extra_dict["depends_on"].append(net_text)
1007
1008 if "port-security-enabled" in interface:
1009 interface["port_security"] = interface.pop("port-security-enabled")
1010
1011 if "port-security-disable-strategy" in interface:
1012 interface["port_security_disable_strategy"] = interface.pop(
1013 "port-security-disable-strategy"
1014 )
1015
1016 net_item = {
1017 x: v
1018 for x, v in interface.items()
1019 if x
1020 in (
1021 "name",
1022 "vpci",
1023 "port_security",
1024 "port_security_disable_strategy",
1025 "floating_ip",
1026 )
1027 }
1028 net_item["net_id"] = "TASK-" + net_text
1029 net_item["type"] = "virtual"
1030
1031 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1032 # TODO floating_ip: True/False (or it can be None)
1033 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1034 # mark the net create task as type data
1035 if deep_get(
1036 tasks_by_target_record_id,
1037 net_text,
1038 "extra_dict",
1039 "params",
1040 "net_type",
1041 ):
1042 tasks_by_target_record_id[net_text]["extra_dict"]["params"][
1043 "net_type"
1044 ] = "data"
1045
1046 net_item["use"] = "data"
1047 net_item["model"] = interface["type"]
1048 net_item["type"] = interface["type"]
1049 elif (
1050 interface.get("type") == "OM-MGMT"
1051 or interface.get("mgmt-interface")
1052 or interface.get("mgmt-vnf")
1053 ):
1054 net_item["use"] = "mgmt"
1055 else:
1056 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1057 net_item["use"] = "bridge"
1058 net_item["model"] = interface.get("type")
1059
1060 if interface.get("ip-address"):
1061 net_item["ip_address"] = interface["ip-address"]
1062
1063 if interface.get("mac-address"):
1064 net_item["mac_address"] = interface["mac-address"]
1065
1066 net_list.append(net_item)
1067
1068 if interface.get("mgmt-vnf"):
1069 extra_dict["mgmt_vnf_interface"] = iface_index
1070 elif interface.get("mgmt-interface"):
1071 extra_dict["mgmt_vdu_interface"] = iface_index
1072
1073 # cloud config
1074 cloud_config = {}
1075
1076 if target_vdu.get("cloud-init"):
1077 if target_vdu["cloud-init"] not in vdu2cloud_init:
1078 vdu2cloud_init[target_vdu["cloud-init"]] = Ns._get_cloud_init(
1079 db=db,
1080 fs=fs,
1081 location=target_vdu["cloud-init"],
1082 )
1083
1084 cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
1085 cloud_config["user-data"] = Ns._parse_jinja2(
1086 cloud_init_content=cloud_content_,
1087 params=target_vdu.get("additionalParams"),
1088 context=target_vdu["cloud-init"],
1089 )
1090
1091 if target_vdu.get("boot-data-drive"):
1092 cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
1093
1094 ssh_keys = []
1095
1096 if target_vdu.get("ssh-keys"):
1097 ssh_keys += target_vdu.get("ssh-keys")
1098
1099 if target_vdu.get("ssh-access-required"):
1100 ssh_keys.append(ro_nsr_public_key)
1101
1102 if ssh_keys:
1103 cloud_config["key-pairs"] = ssh_keys
1104
1105 persistent_root_disk = {}
1106 disk_list = []
1107 vnfd_id = vnfr["vnfd-id"]
1108 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
1109 for vdu in vnfd.get("vdu", ()):
1110 if vdu["name"] == target_vdu["vdu-name"]:
1111 for vsd in vnfd.get("virtual-storage-desc", ()):
1112 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
1113 root_disk = vsd
1114 if root_disk.get(
1115 "type-of-storage"
1116 ) == "persistent-storage:persistent-storage" and root_disk.get(
1117 "size-of-storage"
1118 ):
1119 persistent_root_disk[vsd["id"]] = {
1120 "image_id": vdu.get("sw-image-desc"),
1121 "size": root_disk["size-of-storage"],
1122 }
1123 disk_list.append(persistent_root_disk[vsd["id"]])
1124
1125 if target_vdu.get("virtual-storages"):
1126 for disk in target_vdu["virtual-storages"]:
1127 if (
1128 disk.get("type-of-storage")
1129 == "persistent-storage:persistent-storage"
1130 and disk["id"] not in persistent_root_disk.keys()
1131 ):
1132 disk_list.append({"size": disk["size-of-storage"]})
1133
1134 affinity_group_list = []
1135
1136 if target_vdu.get("affinity-or-anti-affinity-group-id"):
1137 affinity_group = {}
1138 for affinity_group_id in target_vdu["affinity-or-anti-affinity-group-id"]:
1139 affinity_group_text = (
1140 ns_preffix + ":affinity-or-anti-affinity-group." + affinity_group_id
1141 )
1142
1143 extra_dict["depends_on"].append(affinity_group_text)
1144 affinity_group["affinity_group_id"] = "TASK-" + affinity_group_text
1145 affinity_group_list.append(affinity_group)
1146
1147 extra_dict["params"] = {
1148 "name": "{}-{}-{}-{}".format(
1149 indata["name"][:16],
1150 vnfr["member-vnf-index-ref"][:16],
1151 target_vdu["vdu-name"][:32],
1152 target_vdu.get("count-index") or 0,
1153 ),
1154 "description": target_vdu["vdu-name"],
1155 "start": True,
1156 "image_id": "TASK-" + image_text,
1157 "flavor_id": "TASK-" + flavor_text,
1158 "affinity_group_list": affinity_group_list,
1159 "net_list": net_list,
1160 "cloud_config": cloud_config or None,
1161 "disk_list": disk_list,
1162 "availability_zone_index": None, # TODO
1163 "availability_zone_list": None, # TODO
1164 }
1165
1166 return extra_dict
1167
1168 @staticmethod
1169 def _process_affinity_group_params(
1170 target_affinity_group: Dict[str, Any],
1171 indata: Dict[str, Any],
1172 vim_info: Dict[str, Any],
1173 target_record_id: str,
1174 **kwargs: Dict[str, Any],
1175 ) -> Dict[str, Any]:
1176 """Get affinity or anti-affinity group parameters.
1177
1178 Args:
1179 target_affinity_group (Dict[str, Any]): [description]
1180 indata (Dict[str, Any]): [description]
1181 vim_info (Dict[str, Any]): [description]
1182 target_record_id (str): [description]
1183
1184 Returns:
1185 Dict[str, Any]: [description]
1186 """
1187
1188 extra_dict = {}
1189 affinity_group_data = {
1190 "name": target_affinity_group["name"],
1191 "type": target_affinity_group["type"],
1192 "scope": target_affinity_group["scope"],
1193 }
1194
1195 if target_affinity_group.get("vim-affinity-group-id"):
1196 affinity_group_data["vim-affinity-group-id"] = target_affinity_group[
1197 "vim-affinity-group-id"
1198 ]
1199
1200 extra_dict["params"] = {
1201 "affinity_group_data": affinity_group_data,
1202 }
1203
1204 return extra_dict
1205
1206 @staticmethod
1207 def _process_recreate_vdu_params(
1208 existing_vdu: Dict[str, Any],
1209 db_nsr: Dict[str, Any],
1210 vim_info: Dict[str, Any],
1211 target_record_id: str,
1212 target_id: str,
1213 **kwargs: Dict[str, Any],
1214 ) -> Dict[str, Any]:
1215 """Function to process VDU parameters to recreate.
1216
1217 Args:
1218 existing_vdu (Dict[str, Any]): [description]
1219 db_nsr (Dict[str, Any]): [description]
1220 vim_info (Dict[str, Any]): [description]
1221 target_record_id (str): [description]
1222 target_id (str): [description]
1223
1224 Returns:
1225 Dict[str, Any]: [description]
1226 """
1227 vnfr = kwargs.get("vnfr")
1228 vdu2cloud_init = kwargs.get("vdu2cloud_init")
1229 # logger = kwargs.get("logger")
1230 db = kwargs.get("db")
1231 fs = kwargs.get("fs")
1232 ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
1233
1234 extra_dict = {}
1235 net_list = []
1236
1237 vim_details = {}
1238 vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
1239 if vim_details_text:
1240 vim_details = yaml.safe_load(f"{vim_details_text}")
1241
1242 for iface_index, interface in enumerate(existing_vdu["interfaces"]):
1243
1244 if "port-security-enabled" in interface:
1245 interface["port_security"] = interface.pop("port-security-enabled")
1246
1247 if "port-security-disable-strategy" in interface:
1248 interface["port_security_disable_strategy"] = interface.pop(
1249 "port-security-disable-strategy"
1250 )
1251
1252 net_item = {
1253 x: v
1254 for x, v in interface.items()
1255 if x
1256 in (
1257 "name",
1258 "vpci",
1259 "port_security",
1260 "port_security_disable_strategy",
1261 "floating_ip",
1262 )
1263 }
1264 existing_ifaces = existing_vdu["vim_info"][target_id].get(
1265 "interfaces_backup", []
1266 )
1267 net_id = next(
1268 (
1269 i["vim_net_id"]
1270 for i in existing_ifaces
1271 if i["ip_address"] == interface["ip-address"]
1272 ),
1273 None,
1274 )
1275
1276 net_item["net_id"] = net_id
1277 net_item["type"] = "virtual"
1278
1279 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1280 # TODO floating_ip: True/False (or it can be None)
1281 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1282 net_item["use"] = "data"
1283 net_item["model"] = interface["type"]
1284 net_item["type"] = interface["type"]
1285 elif (
1286 interface.get("type") == "OM-MGMT"
1287 or interface.get("mgmt-interface")
1288 or interface.get("mgmt-vnf")
1289 ):
1290 net_item["use"] = "mgmt"
1291 else:
1292 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1293 net_item["use"] = "bridge"
1294 net_item["model"] = interface.get("type")
1295
1296 if interface.get("ip-address"):
1297 net_item["ip_address"] = interface["ip-address"]
1298
1299 if interface.get("mac-address"):
1300 net_item["mac_address"] = interface["mac-address"]
1301
1302 net_list.append(net_item)
1303
1304 if interface.get("mgmt-vnf"):
1305 extra_dict["mgmt_vnf_interface"] = iface_index
1306 elif interface.get("mgmt-interface"):
1307 extra_dict["mgmt_vdu_interface"] = iface_index
1308
1309 # cloud config
1310 cloud_config = {}
1311
1312 if existing_vdu.get("cloud-init"):
1313 if existing_vdu["cloud-init"] not in vdu2cloud_init:
1314 vdu2cloud_init[existing_vdu["cloud-init"]] = Ns._get_cloud_init(
1315 db=db,
1316 fs=fs,
1317 location=existing_vdu["cloud-init"],
1318 )
1319
1320 cloud_content_ = vdu2cloud_init[existing_vdu["cloud-init"]]
1321 cloud_config["user-data"] = Ns._parse_jinja2(
1322 cloud_init_content=cloud_content_,
1323 params=existing_vdu.get("additionalParams"),
1324 context=existing_vdu["cloud-init"],
1325 )
1326
1327 if existing_vdu.get("boot-data-drive"):
1328 cloud_config["boot-data-drive"] = existing_vdu.get("boot-data-drive")
1329
1330 ssh_keys = []
1331
1332 if existing_vdu.get("ssh-keys"):
1333 ssh_keys += existing_vdu.get("ssh-keys")
1334
1335 if existing_vdu.get("ssh-access-required"):
1336 ssh_keys.append(ro_nsr_public_key)
1337
1338 if ssh_keys:
1339 cloud_config["key-pairs"] = ssh_keys
1340
1341 disk_list = []
1342 for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
1343 disk_list.append({"vim_id": vol_id["id"]})
1344
1345 affinity_group_list = []
1346
1347 if existing_vdu.get("affinity-or-anti-affinity-group-id"):
1348 affinity_group = {}
1349 for affinity_group_id in existing_vdu["affinity-or-anti-affinity-group-id"]:
1350 for group in db_nsr.get("affinity-or-anti-affinity-group"):
1351 if (
1352 group["id"] == affinity_group_id
1353 and group["vim_info"][target_id].get("vim_id", None) is not None
1354 ):
1355 affinity_group["affinity_group_id"] = group["vim_info"][
1356 target_id
1357 ].get("vim_id", None)
1358 affinity_group_list.append(affinity_group)
1359
1360 extra_dict["params"] = {
1361 "name": "{}-{}-{}-{}".format(
1362 db_nsr["name"][:16],
1363 vnfr["member-vnf-index-ref"][:16],
1364 existing_vdu["vdu-name"][:32],
1365 existing_vdu.get("count-index") or 0,
1366 ),
1367 "description": existing_vdu["vdu-name"],
1368 "start": True,
1369 "image_id": vim_details["image"]["id"],
1370 "flavor_id": vim_details["flavor"]["id"],
1371 "affinity_group_list": affinity_group_list,
1372 "net_list": net_list,
1373 "cloud_config": cloud_config or None,
1374 "disk_list": disk_list,
1375 "availability_zone_index": None, # TODO
1376 "availability_zone_list": None, # TODO
1377 }
1378
1379 return extra_dict
1380
1381 def calculate_diff_items(
1382 self,
1383 indata,
1384 db_nsr,
1385 db_ro_nsr,
1386 db_nsr_update,
1387 item,
1388 tasks_by_target_record_id,
1389 action_id,
1390 nsr_id,
1391 task_index,
1392 vnfr_id=None,
1393 vnfr=None,
1394 ):
1395 """Function that returns the incremental changes (creation, deletion)
1396 related to a specific item `item` to be done. This function should be
1397 called for NS instantiation, NS termination, NS update to add a new VNF
1398 or a new VLD, remove a VNF or VLD, etc.
1399 Item can be `net`, `flavor`, `image` or `vdu`.
1400 It takes a list of target items from indata (which came from the REST API)
1401 and compares with the existing items from db_ro_nsr, identifying the
1402 incremental changes to be done. During the comparison, it calls the method
1403 `process_params` (which was passed as parameter, and is particular for each
1404 `item`)
1405
1406 Args:
1407 indata (Dict[str, Any]): deployment info
1408 db_nsr: NSR record from DB
1409 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1410 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1411 item (str): element to process (net, vdu...)
1412 tasks_by_target_record_id (Dict[str, Any]):
1413 [<target_record_id>, <task>]
1414 action_id (str): action id
1415 nsr_id (str): NSR id
1416 task_index (number): task index to add to task name
1417 vnfr_id (str): VNFR id
1418 vnfr (Dict[str, Any]): VNFR info
1419
1420 Returns:
1421 List: list with the incremental changes (deletes, creates) for each item
1422 number: current task index
1423 """
1424
1425 diff_items = []
1426 db_path = ""
1427 db_record = ""
1428 target_list = []
1429 existing_list = []
1430 process_params = None
1431 vdu2cloud_init = indata.get("cloud_init_content") or {}
1432 ro_nsr_public_key = db_ro_nsr["public_key"]
1433
1434 # According to the type of item, the path, the target_list,
1435 # the existing_list and the method to process params are set
1436 db_path = self.db_path_map[item]
1437 process_params = self.process_params_function_map[item]
1438 if item in ("net", "vdu"):
1439 # This case is specific for the NS VLD (not applied to VDU)
1440 if vnfr is None:
1441 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1442 target_list = indata.get("ns", []).get(db_path, [])
1443 existing_list = db_nsr.get(db_path, [])
1444 # This case is common for VNF VLDs and VNF VDUs
1445 else:
1446 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
1447 target_vnf = next(
1448 (vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id),
1449 None,
1450 )
1451 target_list = target_vnf.get(db_path, []) if target_vnf else []
1452 existing_list = vnfr.get(db_path, [])
1453 elif item in ("image", "flavor", "affinity-or-anti-affinity-group"):
1454 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1455 target_list = indata.get(item, [])
1456 existing_list = db_nsr.get(item, [])
1457 else:
1458 raise NsException("Item not supported: {}", item)
1459
1460 # ensure all the target_list elements has an "id". If not assign the index as id
1461 if target_list is None:
1462 target_list = []
1463 for target_index, tl in enumerate(target_list):
1464 if tl and not tl.get("id"):
1465 tl["id"] = str(target_index)
1466
1467 # step 1 items (networks,vdus,...) to be deleted/updated
1468 for item_index, existing_item in enumerate(existing_list):
1469 target_item = next(
1470 (t for t in target_list if t["id"] == existing_item["id"]),
1471 None,
1472 )
1473
1474 for target_vim, existing_viminfo in existing_item.get(
1475 "vim_info", {}
1476 ).items():
1477 if existing_viminfo is None:
1478 continue
1479
1480 if target_item:
1481 target_viminfo = target_item.get("vim_info", {}).get(target_vim)
1482 else:
1483 target_viminfo = None
1484
1485 if target_viminfo is None:
1486 # must be deleted
1487 self._assign_vim(target_vim)
1488 target_record_id = "{}.{}".format(db_record, existing_item["id"])
1489 item_ = item
1490
1491 if target_vim.startswith("sdn"):
1492 # item must be sdn-net instead of net if target_vim is a sdn
1493 item_ = "sdn_net"
1494 target_record_id += ".sdn"
1495
1496 deployment_info = {
1497 "action_id": action_id,
1498 "nsr_id": nsr_id,
1499 "task_index": task_index,
1500 }
1501
1502 diff_items.append(
1503 {
1504 "deployment_info": deployment_info,
1505 "target_id": target_vim,
1506 "item": item_,
1507 "action": "DELETE",
1508 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1509 "target_record_id": target_record_id,
1510 }
1511 )
1512 task_index += 1
1513
1514 # step 2 items (networks,vdus,...) to be created
1515 for target_item in target_list:
1516 item_index = -1
1517
1518 for item_index, existing_item in enumerate(existing_list):
1519 if existing_item["id"] == target_item["id"]:
1520 break
1521 else:
1522 item_index += 1
1523 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1524 existing_list.append(target_item)
1525 existing_item = None
1526
1527 for target_vim, target_viminfo in target_item.get("vim_info", {}).items():
1528 existing_viminfo = None
1529
1530 if existing_item:
1531 existing_viminfo = existing_item.get("vim_info", {}).get(target_vim)
1532
1533 if existing_viminfo is not None:
1534 continue
1535
1536 target_record_id = "{}.{}".format(db_record, target_item["id"])
1537 item_ = item
1538
1539 if target_vim.startswith("sdn"):
1540 # item must be sdn-net instead of net if target_vim is a sdn
1541 item_ = "sdn_net"
1542 target_record_id += ".sdn"
1543
1544 kwargs = {}
1545 self.logger.warning(
1546 "ns.calculate_diff_items target_item={}".format(target_item)
1547 )
1548 if process_params == Ns._process_vdu_params:
1549 self.logger.warning(
1550 "calculate_diff_items self.fs={}".format(self.fs)
1551 )
1552 kwargs.update(
1553 {
1554 "vnfr_id": vnfr_id,
1555 "nsr_id": nsr_id,
1556 "vnfr": vnfr,
1557 "vdu2cloud_init": vdu2cloud_init,
1558 "tasks_by_target_record_id": tasks_by_target_record_id,
1559 "logger": self.logger,
1560 "db": self.db,
1561 "fs": self.fs,
1562 "ro_nsr_public_key": ro_nsr_public_key,
1563 }
1564 )
1565 self.logger.warning("calculate_diff_items kwargs={}".format(kwargs))
1566
1567 extra_dict = process_params(
1568 target_item,
1569 indata,
1570 target_viminfo,
1571 target_record_id,
1572 **kwargs,
1573 )
1574 self._assign_vim(target_vim)
1575
1576 deployment_info = {
1577 "action_id": action_id,
1578 "nsr_id": nsr_id,
1579 "task_index": task_index,
1580 }
1581
1582 new_item = {
1583 "deployment_info": deployment_info,
1584 "target_id": target_vim,
1585 "item": item_,
1586 "action": "CREATE",
1587 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1588 "target_record_id": target_record_id,
1589 "extra_dict": extra_dict,
1590 "common_id": target_item.get("common_id", None),
1591 }
1592 diff_items.append(new_item)
1593 tasks_by_target_record_id[target_record_id] = new_item
1594 task_index += 1
1595
1596 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1597
1598 return diff_items, task_index
1599
1600 def calculate_all_differences_to_deploy(
1601 self,
1602 indata,
1603 nsr_id,
1604 db_nsr,
1605 db_vnfrs,
1606 db_ro_nsr,
1607 db_nsr_update,
1608 db_vnfrs_update,
1609 action_id,
1610 tasks_by_target_record_id,
1611 ):
1612 """This method calculates the ordered list of items (`changes_list`)
1613 to be created and deleted.
1614
1615 Args:
1616 indata (Dict[str, Any]): deployment info
1617 nsr_id (str): NSR id
1618 db_nsr: NSR record from DB
1619 db_vnfrs: VNFRS record from DB
1620 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1621 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1622 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
1623 action_id (str): action id
1624 tasks_by_target_record_id (Dict[str, Any]):
1625 [<target_record_id>, <task>]
1626
1627 Returns:
1628 List: ordered list of items to be created and deleted.
1629 """
1630
1631 task_index = 0
1632 # set list with diffs:
1633 changes_list = []
1634
1635 # NS vld, image and flavor
1636 for item in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
1637 self.logger.debug("process NS={} {}".format(nsr_id, item))
1638 diff_items, task_index = self.calculate_diff_items(
1639 indata=indata,
1640 db_nsr=db_nsr,
1641 db_ro_nsr=db_ro_nsr,
1642 db_nsr_update=db_nsr_update,
1643 item=item,
1644 tasks_by_target_record_id=tasks_by_target_record_id,
1645 action_id=action_id,
1646 nsr_id=nsr_id,
1647 task_index=task_index,
1648 vnfr_id=None,
1649 )
1650 changes_list += diff_items
1651
1652 # VNF vlds and vdus
1653 for vnfr_id, vnfr in db_vnfrs.items():
1654 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1655 for item in ["net", "vdu"]:
1656 self.logger.debug("process VNF={} {}".format(vnfr_id, item))
1657 diff_items, task_index = self.calculate_diff_items(
1658 indata=indata,
1659 db_nsr=db_nsr,
1660 db_ro_nsr=db_ro_nsr,
1661 db_nsr_update=db_vnfrs_update[vnfr["_id"]],
1662 item=item,
1663 tasks_by_target_record_id=tasks_by_target_record_id,
1664 action_id=action_id,
1665 nsr_id=nsr_id,
1666 task_index=task_index,
1667 vnfr_id=vnfr_id,
1668 vnfr=vnfr,
1669 )
1670 changes_list += diff_items
1671
1672 return changes_list
1673
1674 def define_all_tasks(
1675 self,
1676 changes_list,
1677 db_new_tasks,
1678 tasks_by_target_record_id,
1679 ):
1680 """Function to create all the task structures obtanied from
1681 the method calculate_all_differences_to_deploy
1682
1683 Args:
1684 changes_list (List): ordered list of items to be created or deleted
1685 db_new_tasks (List): tasks list to be created
1686 action_id (str): action id
1687 tasks_by_target_record_id (Dict[str, Any]):
1688 [<target_record_id>, <task>]
1689
1690 """
1691
1692 for change in changes_list:
1693 task = Ns._create_task(
1694 deployment_info=change["deployment_info"],
1695 target_id=change["target_id"],
1696 item=change["item"],
1697 action=change["action"],
1698 target_record=change["target_record"],
1699 target_record_id=change["target_record_id"],
1700 extra_dict=change.get("extra_dict", None),
1701 )
1702
1703 self.logger.warning("ns.define_all_tasks task={}".format(task))
1704 tasks_by_target_record_id[change["target_record_id"]] = task
1705 db_new_tasks.append(task)
1706
1707 if change.get("common_id"):
1708 task["common_id"] = change["common_id"]
1709
1710 def upload_all_tasks(
1711 self,
1712 db_new_tasks,
1713 now,
1714 ):
1715 """Function to save all tasks in the common DB
1716
1717 Args:
1718 db_new_tasks (List): tasks list to be created
1719 now (time): current time
1720
1721 """
1722
1723 nb_ro_tasks = 0 # for logging
1724
1725 for db_task in db_new_tasks:
1726 target_id = db_task.pop("target_id")
1727 common_id = db_task.get("common_id")
1728
1729 # Do not chek tasks with vim_status DELETED
1730 # because in manual heealing there are two tasks for the same vdur:
1731 # one with vim_status deleted and the other one with the actual VM status.
1732
1733 if common_id:
1734 if self.db.set_one(
1735 "ro_tasks",
1736 q_filter={
1737 "target_id": target_id,
1738 "tasks.common_id": common_id,
1739 "vim_info.vim_status.ne": "DELETED",
1740 },
1741 update_dict={"to_check_at": now, "modified_at": now},
1742 push={"tasks": db_task},
1743 fail_on_empty=False,
1744 ):
1745 continue
1746
1747 if not self.db.set_one(
1748 "ro_tasks",
1749 q_filter={
1750 "target_id": target_id,
1751 "tasks.target_record": db_task["target_record"],
1752 "vim_info.vim_status.ne": "DELETED",
1753 },
1754 update_dict={"to_check_at": now, "modified_at": now},
1755 push={"tasks": db_task},
1756 fail_on_empty=False,
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 nb_ro_tasks += 1
1762 self.db.create("ro_tasks", db_ro_task)
1763
1764 self.logger.debug(
1765 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1766 nb_ro_tasks, len(db_new_tasks), db_new_tasks
1767 )
1768 )
1769
1770 def upload_recreate_tasks(
1771 self,
1772 db_new_tasks,
1773 now,
1774 ):
1775 """Function to save recreate tasks in the common DB
1776
1777 Args:
1778 db_new_tasks (List): tasks list to be created
1779 now (time): current time
1780
1781 """
1782
1783 nb_ro_tasks = 0 # for logging
1784
1785 for db_task in db_new_tasks:
1786 target_id = db_task.pop("target_id")
1787 self.logger.warning("target_id={} db_task={}".format(target_id, db_task))
1788
1789 action = db_task.get("action", None)
1790
1791 # Create a ro_task
1792 self.logger.debug("Updating database, Creating ro_tasks")
1793 db_ro_task = Ns._create_ro_task(target_id, db_task)
1794
1795 # If DELETE task: the associated created items should be removed
1796 # (except persistent volumes):
1797 if action == "DELETE":
1798 db_ro_task["vim_info"]["created"] = True
1799 db_ro_task["vim_info"]["created_items"] = db_task.get(
1800 "created_items", {}
1801 )
1802 db_ro_task["vim_info"]["volumes_to_hold"] = db_task.get(
1803 "volumes_to_hold", []
1804 )
1805 db_ro_task["vim_info"]["vim_id"] = db_task.get("vim_id", None)
1806
1807 nb_ro_tasks += 1
1808 self.logger.warning("upload_all_tasks db_ro_task={}".format(db_ro_task))
1809 self.db.create("ro_tasks", db_ro_task)
1810
1811 self.logger.debug(
1812 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1813 nb_ro_tasks, len(db_new_tasks), db_new_tasks
1814 )
1815 )
1816
1817 def _prepare_created_items_for_healing(
1818 self,
1819 nsr_id,
1820 target_record,
1821 ):
1822 created_items = {}
1823 # Get created_items from ro_task
1824 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
1825 for ro_task in ro_tasks:
1826 for task in ro_task["tasks"]:
1827 if (
1828 task["target_record"] == target_record
1829 and task["action"] == "CREATE"
1830 and ro_task["vim_info"]["created_items"]
1831 ):
1832 created_items = ro_task["vim_info"]["created_items"]
1833 break
1834
1835 return created_items
1836
1837 def _prepare_persistent_volumes_for_healing(
1838 self,
1839 target_id,
1840 existing_vdu,
1841 ):
1842 # The associated volumes of the VM shouldn't be removed
1843 volumes_list = []
1844 vim_details = {}
1845 vim_details_text = existing_vdu["vim_info"][target_id].get("vim_details", None)
1846 if vim_details_text:
1847 vim_details = yaml.safe_load(f"{vim_details_text}")
1848
1849 for vol_id in vim_details.get("os-extended-volumes:volumes_attached", []):
1850 volumes_list.append(vol_id["id"])
1851
1852 return volumes_list
1853
1854 def prepare_changes_to_recreate(
1855 self,
1856 indata,
1857 nsr_id,
1858 db_nsr,
1859 db_vnfrs,
1860 db_ro_nsr,
1861 action_id,
1862 tasks_by_target_record_id,
1863 ):
1864 """This method will obtain an ordered list of items (`changes_list`)
1865 to be created and deleted to meet the recreate request.
1866 """
1867
1868 self.logger.debug(
1869 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id, indata)
1870 )
1871
1872 task_index = 0
1873 # set list with diffs:
1874 changes_list = []
1875 db_path = self.db_path_map["vdu"]
1876 target_list = indata.get("healVnfData", {})
1877 vdu2cloud_init = indata.get("cloud_init_content") or {}
1878 ro_nsr_public_key = db_ro_nsr["public_key"]
1879
1880 # Check each VNF of the target
1881 for target_vnf in target_list:
1882 # Find this VNF in the list from DB
1883 vnfr_id = target_vnf.get("vnfInstanceId", None)
1884 if vnfr_id:
1885 existing_vnf = db_vnfrs.get(vnfr_id)
1886 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
1887 # vim_account_id = existing_vnf.get("vim-account-id", "")
1888
1889 # Check each VDU of this VNF
1890 for target_vdu in target_vnf["additionalParams"].get("vdu", None):
1891 vdu_name = target_vdu.get("vdu-id", None)
1892 # For multi instance VDU count-index is mandatory
1893 # For single session VDU count-indes is 0
1894 count_index = target_vdu.get("count-index", 0)
1895 item_index = 0
1896 existing_instance = None
1897 for instance in existing_vnf.get("vdur", None):
1898 if (
1899 instance["vdu-name"] == vdu_name
1900 and instance["count-index"] == count_index
1901 ):
1902 existing_instance = instance
1903 break
1904 else:
1905 item_index += 1
1906
1907 target_record_id = "{}.{}".format(db_record, existing_instance["id"])
1908
1909 # The target VIM is the one already existing in DB to recreate
1910 for target_vim, target_viminfo in existing_instance.get(
1911 "vim_info", {}
1912 ).items():
1913 # step 1 vdu to be deleted
1914 self._assign_vim(target_vim)
1915 deployment_info = {
1916 "action_id": action_id,
1917 "nsr_id": nsr_id,
1918 "task_index": task_index,
1919 }
1920
1921 target_record = f"{db_record}.{item_index}.vim_info.{target_vim}"
1922 created_items = self._prepare_created_items_for_healing(
1923 nsr_id, target_record
1924 )
1925
1926 volumes_to_hold = self._prepare_persistent_volumes_for_healing(
1927 target_vim, existing_instance
1928 )
1929
1930 # Specific extra params for recreate tasks:
1931 extra_dict = {
1932 "created_items": created_items,
1933 "vim_id": existing_instance["vim-id"],
1934 "volumes_to_hold": volumes_to_hold,
1935 }
1936
1937 changes_list.append(
1938 {
1939 "deployment_info": deployment_info,
1940 "target_id": target_vim,
1941 "item": "vdu",
1942 "action": "DELETE",
1943 "target_record": target_record,
1944 "target_record_id": target_record_id,
1945 "extra_dict": extra_dict,
1946 }
1947 )
1948 delete_task_id = f"{action_id}:{task_index}"
1949 task_index += 1
1950
1951 # step 2 vdu to be created
1952 kwargs = {}
1953 kwargs.update(
1954 {
1955 "vnfr_id": vnfr_id,
1956 "nsr_id": nsr_id,
1957 "vnfr": existing_vnf,
1958 "vdu2cloud_init": vdu2cloud_init,
1959 "tasks_by_target_record_id": tasks_by_target_record_id,
1960 "logger": self.logger,
1961 "db": self.db,
1962 "fs": self.fs,
1963 "ro_nsr_public_key": ro_nsr_public_key,
1964 }
1965 )
1966
1967 extra_dict = self._process_recreate_vdu_params(
1968 existing_instance,
1969 db_nsr,
1970 target_viminfo,
1971 target_record_id,
1972 target_vim,
1973 **kwargs,
1974 )
1975
1976 # The CREATE task depens on the DELETE task
1977 extra_dict["depends_on"] = [delete_task_id]
1978
1979 # Add volumes created from created_items if any
1980 # Ports should be deleted with delete task and automatically created with create task
1981 volumes = {}
1982 for k, v in created_items.items():
1983 try:
1984 k_item, _, k_id = k.partition(":")
1985 if k_item == "volume":
1986 volumes[k] = v
1987 except Exception as e:
1988 self.logger.error(
1989 "Error evaluating created item {}: {}".format(k, e)
1990 )
1991 extra_dict["previous_created_volumes"] = volumes
1992
1993 deployment_info = {
1994 "action_id": action_id,
1995 "nsr_id": nsr_id,
1996 "task_index": task_index,
1997 }
1998 self._assign_vim(target_vim)
1999
2000 new_item = {
2001 "deployment_info": deployment_info,
2002 "target_id": target_vim,
2003 "item": "vdu",
2004 "action": "CREATE",
2005 "target_record": target_record,
2006 "target_record_id": target_record_id,
2007 "extra_dict": extra_dict,
2008 }
2009 changes_list.append(new_item)
2010 tasks_by_target_record_id[target_record_id] = new_item
2011 task_index += 1
2012
2013 return changes_list
2014
2015 def recreate(self, session, indata, version, nsr_id, *args, **kwargs):
2016 self.logger.debug("ns.recreate nsr_id={} indata={}".format(nsr_id, indata))
2017 # TODO: validate_input(indata, recreate_schema)
2018 action_id = indata.get("action_id", str(uuid4()))
2019 # get current deployment
2020 db_vnfrs = {} # vnf's info indexed by _id
2021 step = ""
2022 logging_text = "Recreate nsr_id={} action_id={} indata={}".format(
2023 nsr_id, action_id, indata
2024 )
2025 self.logger.debug(logging_text + "Enter")
2026
2027 try:
2028 step = "Getting ns and vnfr record from db"
2029 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2030 db_new_tasks = []
2031 tasks_by_target_record_id = {}
2032 # read from db: vnf's of this ns
2033 step = "Getting vnfrs from db"
2034 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2035 self.logger.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list))
2036
2037 if not db_vnfrs_list:
2038 raise NsException("Cannot obtain associated VNF for ns")
2039
2040 for vnfr in db_vnfrs_list:
2041 db_vnfrs[vnfr["_id"]] = vnfr
2042
2043 now = time()
2044 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
2045 self.logger.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr))
2046
2047 if not db_ro_nsr:
2048 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
2049
2050 with self.write_lock:
2051 # NS
2052 step = "process NS elements"
2053 changes_list = self.prepare_changes_to_recreate(
2054 indata=indata,
2055 nsr_id=nsr_id,
2056 db_nsr=db_nsr,
2057 db_vnfrs=db_vnfrs,
2058 db_ro_nsr=db_ro_nsr,
2059 action_id=action_id,
2060 tasks_by_target_record_id=tasks_by_target_record_id,
2061 )
2062
2063 self.define_all_tasks(
2064 changes_list=changes_list,
2065 db_new_tasks=db_new_tasks,
2066 tasks_by_target_record_id=tasks_by_target_record_id,
2067 )
2068
2069 # Delete all ro_tasks registered for the targets vdurs (target_record)
2070 # If task of type CREATE exist then vim will try to get info form deleted VMs.
2071 # So remove all task related to target record.
2072 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2073 for change in changes_list:
2074 for ro_task in ro_tasks:
2075 for task in ro_task["tasks"]:
2076 if task["target_record"] == change["target_record"]:
2077 self.db.del_one(
2078 "ro_tasks",
2079 q_filter={
2080 "_id": ro_task["_id"],
2081 "modified_at": ro_task["modified_at"],
2082 },
2083 fail_on_empty=False,
2084 )
2085
2086 step = "Updating database, Appending tasks to ro_tasks"
2087 self.upload_recreate_tasks(
2088 db_new_tasks=db_new_tasks,
2089 now=now,
2090 )
2091
2092 self.logger.debug(
2093 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2094 )
2095
2096 return (
2097 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2098 action_id,
2099 True,
2100 )
2101 except Exception as e:
2102 if isinstance(e, (DbException, NsException)):
2103 self.logger.error(
2104 logging_text + "Exit Exception while '{}': {}".format(step, e)
2105 )
2106 else:
2107 e = traceback_format_exc()
2108 self.logger.critical(
2109 logging_text + "Exit Exception while '{}': {}".format(step, e),
2110 exc_info=True,
2111 )
2112
2113 raise NsException(e)
2114
2115 def deploy(self, session, indata, version, nsr_id, *args, **kwargs):
2116 self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata))
2117 validate_input(indata, deploy_schema)
2118 action_id = indata.get("action_id", str(uuid4()))
2119 task_index = 0
2120 # get current deployment
2121 db_nsr_update = {} # update operation on nsrs
2122 db_vnfrs_update = {}
2123 db_vnfrs = {} # vnf's info indexed by _id
2124 step = ""
2125 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2126 self.logger.debug(logging_text + "Enter")
2127
2128 try:
2129 step = "Getting ns and vnfr record from db"
2130 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
2131 self.logger.debug("ns.deploy: db_nsr={}".format(db_nsr))
2132 db_new_tasks = []
2133 tasks_by_target_record_id = {}
2134 # read from db: vnf's of this ns
2135 step = "Getting vnfrs from db"
2136 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
2137
2138 if not db_vnfrs_list:
2139 raise NsException("Cannot obtain associated VNF for ns")
2140
2141 for vnfr in db_vnfrs_list:
2142 db_vnfrs[vnfr["_id"]] = vnfr
2143 db_vnfrs_update[vnfr["_id"]] = {}
2144 self.logger.debug("ns.deploy db_vnfrs={}".format(db_vnfrs))
2145
2146 now = time()
2147 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
2148
2149 if not db_ro_nsr:
2150 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
2151
2152 # check that action_id is not in the list of actions. Suffixed with :index
2153 if action_id in db_ro_nsr["actions"]:
2154 index = 1
2155
2156 while True:
2157 new_action_id = "{}:{}".format(action_id, index)
2158
2159 if new_action_id not in db_ro_nsr["actions"]:
2160 action_id = new_action_id
2161 self.logger.debug(
2162 logging_text
2163 + "Changing action_id in use to {}".format(action_id)
2164 )
2165 break
2166
2167 index += 1
2168
2169 def _process_action(indata):
2170 nonlocal db_new_tasks
2171 nonlocal action_id
2172 nonlocal nsr_id
2173 nonlocal task_index
2174 nonlocal db_vnfrs
2175 nonlocal db_ro_nsr
2176
2177 if indata["action"]["action"] == "inject_ssh_key":
2178 key = indata["action"].get("key")
2179 user = indata["action"].get("user")
2180 password = indata["action"].get("password")
2181
2182 for vnf in indata.get("vnf", ()):
2183 if vnf["_id"] not in db_vnfrs:
2184 raise NsException("Invalid vnf={}".format(vnf["_id"]))
2185
2186 db_vnfr = db_vnfrs[vnf["_id"]]
2187
2188 for target_vdu in vnf.get("vdur", ()):
2189 vdu_index, vdur = next(
2190 (
2191 i_v
2192 for i_v in enumerate(db_vnfr["vdur"])
2193 if i_v[1]["id"] == target_vdu["id"]
2194 ),
2195 (None, None),
2196 )
2197
2198 if not vdur:
2199 raise NsException(
2200 "Invalid vdu vnf={}.{}".format(
2201 vnf["_id"], target_vdu["id"]
2202 )
2203 )
2204
2205 target_vim, vim_info = next(
2206 k_v for k_v in vdur["vim_info"].items()
2207 )
2208 self._assign_vim(target_vim)
2209 target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
2210 vnf["_id"], vdu_index
2211 )
2212 extra_dict = {
2213 "depends_on": [
2214 "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
2215 ],
2216 "params": {
2217 "ip_address": vdur.get("ip-address"),
2218 "user": user,
2219 "key": key,
2220 "password": password,
2221 "private_key": db_ro_nsr["private_key"],
2222 "salt": db_ro_nsr["_id"],
2223 "schema_version": db_ro_nsr["_admin"][
2224 "schema_version"
2225 ],
2226 },
2227 }
2228
2229 deployment_info = {
2230 "action_id": action_id,
2231 "nsr_id": nsr_id,
2232 "task_index": task_index,
2233 }
2234
2235 task = Ns._create_task(
2236 deployment_info=deployment_info,
2237 target_id=target_vim,
2238 item="vdu",
2239 action="EXEC",
2240 target_record=target_record,
2241 target_record_id=None,
2242 extra_dict=extra_dict,
2243 )
2244
2245 task_index = deployment_info.get("task_index")
2246
2247 db_new_tasks.append(task)
2248
2249 with self.write_lock:
2250 if indata.get("action"):
2251 _process_action(indata)
2252 else:
2253 # compute network differences
2254 # NS
2255 step = "process NS elements"
2256 changes_list = self.calculate_all_differences_to_deploy(
2257 indata=indata,
2258 nsr_id=nsr_id,
2259 db_nsr=db_nsr,
2260 db_vnfrs=db_vnfrs,
2261 db_ro_nsr=db_ro_nsr,
2262 db_nsr_update=db_nsr_update,
2263 db_vnfrs_update=db_vnfrs_update,
2264 action_id=action_id,
2265 tasks_by_target_record_id=tasks_by_target_record_id,
2266 )
2267 self.define_all_tasks(
2268 changes_list=changes_list,
2269 db_new_tasks=db_new_tasks,
2270 tasks_by_target_record_id=tasks_by_target_record_id,
2271 )
2272
2273 step = "Updating database, Appending tasks to ro_tasks"
2274 self.upload_all_tasks(
2275 db_new_tasks=db_new_tasks,
2276 now=now,
2277 )
2278
2279 step = "Updating database, nsrs"
2280 if db_nsr_update:
2281 self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
2282
2283 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
2284 if db_vnfr_update:
2285 step = "Updating database, vnfrs={}".format(vnfr_id)
2286 self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
2287
2288 self.logger.debug(
2289 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2290 )
2291
2292 return (
2293 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2294 action_id,
2295 True,
2296 )
2297 except Exception as e:
2298 if isinstance(e, (DbException, NsException)):
2299 self.logger.error(
2300 logging_text + "Exit Exception while '{}': {}".format(step, e)
2301 )
2302 else:
2303 e = traceback_format_exc()
2304 self.logger.critical(
2305 logging_text + "Exit Exception while '{}': {}".format(step, e),
2306 exc_info=True,
2307 )
2308
2309 raise NsException(e)
2310
2311 def delete(self, session, indata, version, nsr_id, *args, **kwargs):
2312 self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
2313 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
2314
2315 with self.write_lock:
2316 try:
2317 NsWorker.delete_db_tasks(self.db, nsr_id, None)
2318 except NsWorkerException as e:
2319 raise NsException(e)
2320
2321 return None, None, True
2322
2323 def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2324 self.logger.debug(
2325 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
2326 version, nsr_id, action_id, indata
2327 )
2328 )
2329 task_list = []
2330 done = 0
2331 total = 0
2332 ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
2333 global_status = "DONE"
2334 details = []
2335
2336 for ro_task in ro_tasks:
2337 for task in ro_task["tasks"]:
2338 if task and task["action_id"] == action_id:
2339 task_list.append(task)
2340 total += 1
2341
2342 if task["status"] == "FAILED":
2343 global_status = "FAILED"
2344 error_text = "Error at {} {}: {}".format(
2345 task["action"].lower(),
2346 task["item"],
2347 ro_task["vim_info"].get("vim_message") or "unknown",
2348 )
2349 details.append(error_text)
2350 elif task["status"] in ("SCHEDULED", "BUILD"):
2351 if global_status != "FAILED":
2352 global_status = "BUILD"
2353 else:
2354 done += 1
2355
2356 return_data = {
2357 "status": global_status,
2358 "details": ". ".join(details)
2359 if details
2360 else "progress {}/{}".format(done, total),
2361 "nsr_id": nsr_id,
2362 "action_id": action_id,
2363 "tasks": task_list,
2364 }
2365
2366 return return_data, None, True
2367
2368 def recreate_status(
2369 self, session, indata, version, nsr_id, action_id, *args, **kwargs
2370 ):
2371 return self.status(session, indata, version, nsr_id, action_id, *args, **kwargs)
2372
2373 def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2374 print(
2375 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
2376 session, indata, version, nsr_id, action_id
2377 )
2378 )
2379
2380 return None, None, True
2381
2382 def rebuild_start_stop_task(
2383 self,
2384 vdu_id,
2385 vnf_id,
2386 vdu_index,
2387 action_id,
2388 nsr_id,
2389 task_index,
2390 target_vim,
2391 extra_dict,
2392 ):
2393 self._assign_vim(target_vim)
2394 target_record = "vnfrs:{}:vdur.{}".format(vnf_id, vdu_index)
2395 target_record_id = "vnfrs:{}:vdur.{}".format(vnf_id, vdu_id)
2396 deployment_info = {
2397 "action_id": action_id,
2398 "nsr_id": nsr_id,
2399 "task_index": task_index,
2400 }
2401
2402 task = Ns._create_task(
2403 deployment_info=deployment_info,
2404 target_id=target_vim,
2405 item="update",
2406 action="EXEC",
2407 target_record=target_record,
2408 target_record_id=target_record_id,
2409 extra_dict=extra_dict,
2410 )
2411 return task
2412
2413 def rebuild_start_stop(
2414 self, session, action_dict, version, nsr_id, *args, **kwargs
2415 ):
2416 task_index = 0
2417 extra_dict = {}
2418 now = time()
2419 action_id = action_dict.get("action_id", str(uuid4()))
2420 step = ""
2421 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2422 self.logger.debug(logging_text + "Enter")
2423
2424 action = list(action_dict.keys())[0]
2425 task_dict = action_dict.get(action)
2426 vim_vm_id = action_dict.get(action).get("vim_vm_id")
2427
2428 if action_dict.get("stop"):
2429 action = "shutoff"
2430 db_new_tasks = []
2431 try:
2432 step = "lock the operation & do task creation"
2433 with self.write_lock:
2434 extra_dict["params"] = {
2435 "vim_vm_id": vim_vm_id,
2436 "action": action,
2437 }
2438 task = self.rebuild_start_stop_task(
2439 task_dict["vdu_id"],
2440 task_dict["vnf_id"],
2441 task_dict["vdu_index"],
2442 action_id,
2443 nsr_id,
2444 task_index,
2445 task_dict["target_vim"],
2446 extra_dict,
2447 )
2448 db_new_tasks.append(task)
2449 step = "upload Task to db"
2450 self.upload_all_tasks(
2451 db_new_tasks=db_new_tasks,
2452 now=now,
2453 )
2454 self.logger.debug(
2455 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2456 )
2457 return (
2458 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2459 action_id,
2460 True,
2461 )
2462 except Exception as e:
2463 if isinstance(e, (DbException, NsException)):
2464 self.logger.error(
2465 logging_text + "Exit Exception while '{}': {}".format(step, e)
2466 )
2467 else:
2468 e = traceback_format_exc()
2469 self.logger.critical(
2470 logging_text + "Exit Exception while '{}': {}".format(step, e),
2471 exc_info=True,
2472 )
2473 raise NsException(e)
2474
2475 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2476 nsrs = self.db.get_list("nsrs", {})
2477 return_data = []
2478
2479 for ns in nsrs:
2480 return_data.append({"_id": ns["_id"], "name": ns["name"]})
2481
2482 return return_data, None, True
2483
2484 def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
2485 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
2486 return_data = []
2487
2488 for ro_task in ro_tasks:
2489 for task in ro_task["tasks"]:
2490 if task["action_id"] not in return_data:
2491 return_data.append(task["action_id"])
2492
2493 return return_data, None, True
2494
2495 def migrate_task(
2496 self, vdu, vnf, vdu_index, action_id, nsr_id, task_index, extra_dict
2497 ):
2498 target_vim, vim_info = next(k_v for k_v in vdu["vim_info"].items())
2499 self._assign_vim(target_vim)
2500 target_record = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu_index)
2501 target_record_id = "vnfrs:{}:vdur.{}".format(vnf["_id"], vdu["id"])
2502 deployment_info = {
2503 "action_id": action_id,
2504 "nsr_id": nsr_id,
2505 "task_index": task_index,
2506 }
2507
2508 task = Ns._create_task(
2509 deployment_info=deployment_info,
2510 target_id=target_vim,
2511 item="migrate",
2512 action="EXEC",
2513 target_record=target_record,
2514 target_record_id=target_record_id,
2515 extra_dict=extra_dict,
2516 )
2517
2518 return task
2519
2520 def migrate(self, session, indata, version, nsr_id, *args, **kwargs):
2521 task_index = 0
2522 extra_dict = {}
2523 now = time()
2524 action_id = indata.get("action_id", str(uuid4()))
2525 step = ""
2526 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
2527 self.logger.debug(logging_text + "Enter")
2528 try:
2529 vnf_instance_id = indata["vnfInstanceId"]
2530 step = "Getting vnfrs from db"
2531 db_vnfr = self.db.get_one("vnfrs", {"_id": vnf_instance_id})
2532 vdu = indata.get("vdu")
2533 migrateToHost = indata.get("migrateToHost")
2534 db_new_tasks = []
2535
2536 with self.write_lock:
2537 if vdu is not None:
2538 vdu_id = indata["vdu"]["vduId"]
2539 vdu_count_index = indata["vdu"].get("vduCountIndex", 0)
2540 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
2541 if (
2542 vdu["vdu-id-ref"] == vdu_id
2543 and vdu["count-index"] == vdu_count_index
2544 ):
2545 extra_dict["params"] = {
2546 "vim_vm_id": vdu["vim-id"],
2547 "migrate_host": migrateToHost,
2548 "vdu_vim_info": vdu["vim_info"],
2549 }
2550 step = "Creating migration task for vdu:{}".format(vdu)
2551 task = self.migrate_task(
2552 vdu,
2553 db_vnfr,
2554 vdu_index,
2555 action_id,
2556 nsr_id,
2557 task_index,
2558 extra_dict,
2559 )
2560 db_new_tasks.append(task)
2561 task_index += 1
2562 break
2563 else:
2564
2565 for vdu_index, vdu in enumerate(db_vnfr["vdur"]):
2566 extra_dict["params"] = {
2567 "vim_vm_id": vdu["vim-id"],
2568 "migrate_host": migrateToHost,
2569 "vdu_vim_info": vdu["vim_info"],
2570 }
2571 step = "Creating migration task for vdu:{}".format(vdu)
2572 task = self.migrate_task(
2573 vdu,
2574 db_vnfr,
2575 vdu_index,
2576 action_id,
2577 nsr_id,
2578 task_index,
2579 extra_dict,
2580 )
2581 db_new_tasks.append(task)
2582 task_index += 1
2583
2584 self.upload_all_tasks(
2585 db_new_tasks=db_new_tasks,
2586 now=now,
2587 )
2588
2589 self.logger.debug(
2590 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
2591 )
2592 return (
2593 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
2594 action_id,
2595 True,
2596 )
2597 except Exception as e:
2598 if isinstance(e, (DbException, NsException)):
2599 self.logger.error(
2600 logging_text + "Exit Exception while '{}': {}".format(step, e)
2601 )
2602 else:
2603 e = traceback_format_exc()
2604 self.logger.critical(
2605 logging_text + "Exit Exception while '{}': {}".format(step, e),
2606 exc_info=True,
2607 )
2608 raise NsException(e)