Fix Bug 1911 Root disk cannot be a Persistent Volume
[osm/RO.git] / NG-RO / osm_ng_ro / ns.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2020 Telefonica Investigacion y Desarrollo, S.A.U.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14 # implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 ##
18
19 from http import HTTPStatus
20 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
53 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
54 min_common_version = "0.1.16"
55
56
57 class NsException(Exception):
58 def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
59 self.http_code = http_code
60 super(Exception, self).__init__(message)
61
62
63 def get_process_id():
64 """
65 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
66 will provide a random one
67 :return: Obtained ID
68 """
69 # Try getting docker id. If fails, get pid
70 try:
71 with open("/proc/self/cgroup", "r") as f:
72 text_id_ = f.readline()
73 _, _, text_id = text_id_.rpartition("/")
74 text_id = text_id.replace("\n", "")[:12]
75
76 if text_id:
77 return text_id
78 except Exception:
79 pass
80
81 # Return a random id
82 return "".join(random_choice("0123456789abcdef") for _ in range(12))
83
84
85 def versiontuple(v):
86 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
87 filled = []
88
89 for point in v.split("."):
90 filled.append(point.zfill(8))
91
92 return tuple(filled)
93
94
95 class Ns(object):
96 def __init__(self):
97 self.db = None
98 self.fs = None
99 self.msg = None
100 self.config = None
101 # self.operations = None
102 self.logger = None
103 # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
104 # If done now it will not be linked to parent not getting its handler and level
105 self.map_topic = {}
106 self.write_lock = None
107 self.vims_assigned = {}
108 self.next_worker = 0
109 self.plugins = {}
110 self.workers = []
111 self.process_params_function_map = {
112 "net": Ns._process_net_params,
113 "image": Ns._process_image_params,
114 "flavor": Ns._process_flavor_params,
115 "vdu": Ns._process_vdu_params,
116 "affinity-or-anti-affinity-group": Ns._process_affinity_group_params,
117 }
118 self.db_path_map = {
119 "net": "vld",
120 "image": "image",
121 "flavor": "flavor",
122 "vdu": "vdur",
123 "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group",
124 }
125
126 def init_db(self, target_version):
127 pass
128
129 def start(self, config):
130 """
131 Connect to database, filesystem storage, and messaging
132 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
133 :param config: Configuration of db, storage, etc
134 :return: None
135 """
136 self.config = config
137 self.config["process_id"] = get_process_id() # used for HA identity
138 self.logger = logging.getLogger("ro.ns")
139
140 # check right version of common
141 if versiontuple(common_version) < versiontuple(min_common_version):
142 raise NsException(
143 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
144 common_version, min_common_version
145 )
146 )
147
148 try:
149 if not self.db:
150 if config["database"]["driver"] == "mongo":
151 self.db = dbmongo.DbMongo()
152 self.db.db_connect(config["database"])
153 elif config["database"]["driver"] == "memory":
154 self.db = dbmemory.DbMemory()
155 self.db.db_connect(config["database"])
156 else:
157 raise NsException(
158 "Invalid configuration param '{}' at '[database]':'driver'".format(
159 config["database"]["driver"]
160 )
161 )
162
163 if not self.fs:
164 if config["storage"]["driver"] == "local":
165 self.fs = fslocal.FsLocal()
166 self.fs.fs_connect(config["storage"])
167 elif config["storage"]["driver"] == "mongo":
168 self.fs = fsmongo.FsMongo()
169 self.fs.fs_connect(config["storage"])
170 elif config["storage"]["driver"] is None:
171 pass
172 else:
173 raise NsException(
174 "Invalid configuration param '{}' at '[storage]':'driver'".format(
175 config["storage"]["driver"]
176 )
177 )
178
179 if not self.msg:
180 if config["message"]["driver"] == "local":
181 self.msg = msglocal.MsgLocal()
182 self.msg.connect(config["message"])
183 elif config["message"]["driver"] == "kafka":
184 self.msg = msgkafka.MsgKafka()
185 self.msg.connect(config["message"])
186 else:
187 raise NsException(
188 "Invalid configuration param '{}' at '[message]':'driver'".format(
189 config["message"]["driver"]
190 )
191 )
192
193 # TODO load workers to deal with exising database tasks
194
195 self.write_lock = Lock()
196 except (DbException, FsException, MsgException) as e:
197 raise NsException(str(e), http_code=e.http_code)
198
199 def get_assigned_vims(self):
200 return list(self.vims_assigned.keys())
201
202 def stop(self):
203 try:
204 if self.db:
205 self.db.db_disconnect()
206
207 if self.fs:
208 self.fs.fs_disconnect()
209
210 if self.msg:
211 self.msg.disconnect()
212
213 self.write_lock = None
214 except (DbException, FsException, MsgException) as e:
215 raise NsException(str(e), http_code=e.http_code)
216
217 for worker in self.workers:
218 worker.insert_task(("terminate",))
219
220 def _create_worker(self):
221 """
222 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
223 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
224 return the index of the assigned worker thread. Worker threads are storead at self.workers
225 """
226 # Look for a thread in idle status
227 worker_id = next(
228 (
229 i
230 for i in range(len(self.workers))
231 if self.workers[i] and self.workers[i].idle
232 ),
233 None,
234 )
235
236 if worker_id is not None:
237 # unset idle status to avoid race conditions
238 self.workers[worker_id].idle = False
239 else:
240 worker_id = len(self.workers)
241
242 if worker_id < self.config["global"]["server.ns_threads"]:
243 # create a new worker
244 self.workers.append(
245 NsWorker(worker_id, self.config, self.plugins, self.db)
246 )
247 self.workers[worker_id].start()
248 else:
249 # reached maximum number of threads, assign VIM to an existing one
250 worker_id = self.next_worker
251 self.next_worker = (self.next_worker + 1) % self.config["global"][
252 "server.ns_threads"
253 ]
254
255 return worker_id
256
257 def assign_vim(self, target_id):
258 with self.write_lock:
259 return self._assign_vim(target_id)
260
261 def _assign_vim(self, target_id):
262 if target_id not in self.vims_assigned:
263 worker_id = self.vims_assigned[target_id] = self._create_worker()
264 self.workers[worker_id].insert_task(("load_vim", target_id))
265
266 def reload_vim(self, target_id):
267 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
268 # this is because database VIM information is cached for threads working with SDN
269 with self.write_lock:
270 for worker in self.workers:
271 if worker and not worker.idle:
272 worker.insert_task(("reload_vim", target_id))
273
274 def unload_vim(self, target_id):
275 with self.write_lock:
276 return self._unload_vim(target_id)
277
278 def _unload_vim(self, target_id):
279 if target_id in self.vims_assigned:
280 worker_id = self.vims_assigned[target_id]
281 self.workers[worker_id].insert_task(("unload_vim", target_id))
282 del self.vims_assigned[target_id]
283
284 def check_vim(self, target_id):
285 with self.write_lock:
286 if target_id in self.vims_assigned:
287 worker_id = self.vims_assigned[target_id]
288 else:
289 worker_id = self._create_worker()
290
291 worker = self.workers[worker_id]
292 worker.insert_task(("check_vim", target_id))
293
294 def unload_unused_vims(self):
295 with self.write_lock:
296 vims_to_unload = []
297
298 for target_id in self.vims_assigned:
299 if not self.db.get_one(
300 "ro_tasks",
301 q_filter={
302 "target_id": target_id,
303 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
304 },
305 fail_on_empty=False,
306 ):
307 vims_to_unload.append(target_id)
308
309 for target_id in vims_to_unload:
310 self._unload_vim(target_id)
311
312 @staticmethod
313 def _get_cloud_init(
314 db: Type[DbBase],
315 fs: Type[FsBase],
316 location: str,
317 ) -> str:
318 """This method reads cloud init from a file.
319
320 Note: Not used as cloud init content is provided in the http body.
321
322 Args:
323 db (Type[DbBase]): [description]
324 fs (Type[FsBase]): [description]
325 location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
326
327 Raises:
328 NsException: [description]
329 NsException: [description]
330
331 Returns:
332 str: [description]
333 """
334 vnfd_id, _, other = location.partition(":")
335 _type, _, name = other.partition(":")
336 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
337
338 if _type == "file":
339 base_folder = vnfd["_admin"]["storage"]
340 cloud_init_file = "{}/{}/cloud_init/{}".format(
341 base_folder["folder"], base_folder["pkg-dir"], name
342 )
343
344 if not fs:
345 raise NsException(
346 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
347 cloud_init_file
348 )
349 )
350
351 with fs.file_open(cloud_init_file, "r") as ci_file:
352 cloud_init_content = ci_file.read()
353 elif _type == "vdu":
354 cloud_init_content = vnfd["vdu"][int(name)]["cloud-init"]
355 else:
356 raise NsException("Mismatch descriptor for cloud init: {}".format(location))
357
358 return cloud_init_content
359
360 @staticmethod
361 def _parse_jinja2(
362 cloud_init_content: str,
363 params: Dict[str, Any],
364 context: str,
365 ) -> str:
366 """Function that processes the cloud init to replace Jinja2 encoded parameters.
367
368 Args:
369 cloud_init_content (str): [description]
370 params (Dict[str, Any]): [description]
371 context (str): [description]
372
373 Raises:
374 NsException: [description]
375 NsException: [description]
376
377 Returns:
378 str: [description]
379 """
380 try:
381 env = Environment(undefined=StrictUndefined)
382 template = env.from_string(cloud_init_content)
383
384 return template.render(params or {})
385 except UndefinedError as e:
386 raise NsException(
387 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
388 "inside the 'additionalParamsForVnf' block".format(e, context)
389 )
390 except (TemplateError, TemplateNotFound) as e:
391 raise NsException(
392 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
393 context, e
394 )
395 )
396
397 def _create_db_ro_nsrs(self, nsr_id, now):
398 try:
399 key = rsa.generate_private_key(
400 backend=crypto_default_backend(), public_exponent=65537, key_size=2048
401 )
402 private_key = key.private_bytes(
403 crypto_serialization.Encoding.PEM,
404 crypto_serialization.PrivateFormat.PKCS8,
405 crypto_serialization.NoEncryption(),
406 )
407 public_key = key.public_key().public_bytes(
408 crypto_serialization.Encoding.OpenSSH,
409 crypto_serialization.PublicFormat.OpenSSH,
410 )
411 private_key = private_key.decode("utf8")
412 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
413 i = private_key.find("\n")
414 private_key = "-----BEGIN RSA PRIVATE KEY-----" + private_key[i:]
415 public_key = public_key.decode("utf8")
416 except Exception as e:
417 raise NsException("Cannot create ssh-keys: {}".format(e))
418
419 schema_version = "1.1"
420 private_key_encrypted = self.db.encrypt(
421 private_key, schema_version=schema_version, salt=nsr_id
422 )
423 db_content = {
424 "_id": nsr_id,
425 "_admin": {
426 "created": now,
427 "modified": now,
428 "schema_version": schema_version,
429 },
430 "public_key": public_key,
431 "private_key": private_key_encrypted,
432 "actions": [],
433 }
434 self.db.create("ro_nsrs", db_content)
435
436 return db_content
437
438 @staticmethod
439 def _create_task(
440 deployment_info: Dict[str, Any],
441 target_id: str,
442 item: str,
443 action: str,
444 target_record: str,
445 target_record_id: str,
446 extra_dict: Dict[str, Any] = None,
447 ) -> Dict[str, Any]:
448 """Function to create task dict from deployment information.
449
450 Args:
451 deployment_info (Dict[str, Any]): [description]
452 target_id (str): [description]
453 item (str): [description]
454 action (str): [description]
455 target_record (str): [description]
456 target_record_id (str): [description]
457 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
458
459 Returns:
460 Dict[str, Any]: [description]
461 """
462 task = {
463 "target_id": target_id, # it will be removed before pushing at database
464 "action_id": deployment_info.get("action_id"),
465 "nsr_id": deployment_info.get("nsr_id"),
466 "task_id": f"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
467 "status": "SCHEDULED",
468 "action": action,
469 "item": item,
470 "target_record": target_record,
471 "target_record_id": target_record_id,
472 }
473
474 if extra_dict:
475 task.update(extra_dict) # params, find_params, depends_on
476
477 deployment_info["task_index"] = deployment_info.get("task_index", 0) + 1
478
479 return task
480
481 @staticmethod
482 def _create_ro_task(
483 target_id: str,
484 task: Dict[str, Any],
485 ) -> Dict[str, Any]:
486 """Function to create an RO task from task information.
487
488 Args:
489 target_id (str): [description]
490 task (Dict[str, Any]): [description]
491
492 Returns:
493 Dict[str, Any]: [description]
494 """
495 now = time()
496
497 _id = task.get("task_id")
498 db_ro_task = {
499 "_id": _id,
500 "locked_by": None,
501 "locked_at": 0.0,
502 "target_id": target_id,
503 "vim_info": {
504 "created": False,
505 "created_items": None,
506 "vim_id": None,
507 "vim_name": None,
508 "vim_status": None,
509 "vim_details": None,
510 "refresh_at": None,
511 },
512 "modified_at": now,
513 "created_at": now,
514 "to_check_at": now,
515 "tasks": [task],
516 }
517
518 return db_ro_task
519
520 @staticmethod
521 def _process_image_params(
522 target_image: Dict[str, Any],
523 indata: Dict[str, Any],
524 vim_info: Dict[str, Any],
525 target_record_id: str,
526 **kwargs: Dict[str, Any],
527 ) -> Dict[str, Any]:
528 """Function to process VDU image parameters.
529
530 Args:
531 target_image (Dict[str, Any]): [description]
532 indata (Dict[str, Any]): [description]
533 vim_info (Dict[str, Any]): [description]
534 target_record_id (str): [description]
535
536 Returns:
537 Dict[str, Any]: [description]
538 """
539 find_params = {}
540
541 if target_image.get("image"):
542 find_params["filter_dict"] = {"name": target_image.get("image")}
543
544 if target_image.get("vim_image_id"):
545 find_params["filter_dict"] = {"id": target_image.get("vim_image_id")}
546
547 if target_image.get("image_checksum"):
548 find_params["filter_dict"] = {
549 "checksum": target_image.get("image_checksum")
550 }
551
552 return {"find_params": find_params}
553
554 @staticmethod
555 def _get_resource_allocation_params(
556 quota_descriptor: Dict[str, Any],
557 ) -> Dict[str, Any]:
558 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
559 descriptor object.
560
561 Args:
562 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
563
564 Returns:
565 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
566 """
567 quota = {}
568
569 if quota_descriptor.get("limit"):
570 quota["limit"] = int(quota_descriptor["limit"])
571
572 if quota_descriptor.get("reserve"):
573 quota["reserve"] = int(quota_descriptor["reserve"])
574
575 if quota_descriptor.get("shares"):
576 quota["shares"] = int(quota_descriptor["shares"])
577
578 return quota
579
580 @staticmethod
581 def _process_guest_epa_quota_params(
582 guest_epa_quota: Dict[str, Any],
583 epa_vcpu_set: bool,
584 ) -> Dict[str, Any]:
585 """Function to extract the guest epa quota parameters.
586
587 Args:
588 guest_epa_quota (Dict[str, Any]): [description]
589 epa_vcpu_set (bool): [description]
590
591 Returns:
592 Dict[str, Any]: [description]
593 """
594 result = {}
595
596 if guest_epa_quota.get("cpu-quota") and not epa_vcpu_set:
597 cpuquota = Ns._get_resource_allocation_params(
598 guest_epa_quota.get("cpu-quota")
599 )
600
601 if cpuquota:
602 result["cpu-quota"] = cpuquota
603
604 if guest_epa_quota.get("mem-quota"):
605 vduquota = Ns._get_resource_allocation_params(
606 guest_epa_quota.get("mem-quota")
607 )
608
609 if vduquota:
610 result["mem-quota"] = vduquota
611
612 if guest_epa_quota.get("disk-io-quota"):
613 diskioquota = Ns._get_resource_allocation_params(
614 guest_epa_quota.get("disk-io-quota")
615 )
616
617 if diskioquota:
618 result["disk-io-quota"] = diskioquota
619
620 if guest_epa_quota.get("vif-quota"):
621 vifquota = Ns._get_resource_allocation_params(
622 guest_epa_quota.get("vif-quota")
623 )
624
625 if vifquota:
626 result["vif-quota"] = vifquota
627
628 return result
629
630 @staticmethod
631 def _process_guest_epa_numa_params(
632 guest_epa_quota: Dict[str, Any],
633 ) -> Tuple[Dict[str, Any], bool]:
634 """[summary]
635
636 Args:
637 guest_epa_quota (Dict[str, Any]): [description]
638
639 Returns:
640 Tuple[Dict[str, Any], bool]: [description]
641 """
642 numa = {}
643 epa_vcpu_set = False
644
645 if guest_epa_quota.get("numa-node-policy"):
646 numa_node_policy = guest_epa_quota.get("numa-node-policy")
647
648 if numa_node_policy.get("node"):
649 numa_node = numa_node_policy["node"][0]
650
651 if numa_node.get("num-cores"):
652 numa["cores"] = numa_node["num-cores"]
653 epa_vcpu_set = True
654
655 paired_threads = numa_node.get("paired-threads", {})
656 if paired_threads.get("num-paired-threads"):
657 numa["paired-threads"] = int(
658 numa_node["paired-threads"]["num-paired-threads"]
659 )
660 epa_vcpu_set = True
661
662 if paired_threads.get("paired-thread-ids"):
663 numa["paired-threads-id"] = []
664
665 for pair in paired_threads["paired-thread-ids"]:
666 numa["paired-threads-id"].append(
667 (
668 str(pair["thread-a"]),
669 str(pair["thread-b"]),
670 )
671 )
672
673 if numa_node.get("num-threads"):
674 numa["threads"] = int(numa_node["num-threads"])
675 epa_vcpu_set = True
676
677 if numa_node.get("memory-mb"):
678 numa["memory"] = max(int(int(numa_node["memory-mb"]) / 1024), 1)
679
680 return numa, epa_vcpu_set
681
682 @staticmethod
683 def _process_guest_epa_cpu_pinning_params(
684 guest_epa_quota: Dict[str, Any],
685 vcpu_count: int,
686 epa_vcpu_set: bool,
687 ) -> Tuple[Dict[str, Any], bool]:
688 """[summary]
689
690 Args:
691 guest_epa_quota (Dict[str, Any]): [description]
692 vcpu_count (int): [description]
693 epa_vcpu_set (bool): [description]
694
695 Returns:
696 Tuple[Dict[str, Any], bool]: [description]
697 """
698 numa = {}
699 local_epa_vcpu_set = epa_vcpu_set
700
701 if (
702 guest_epa_quota.get("cpu-pinning-policy") == "DEDICATED"
703 and not epa_vcpu_set
704 ):
705 numa[
706 "cores"
707 if guest_epa_quota.get("cpu-thread-pinning-policy") != "PREFER"
708 else "threads"
709 ] = max(vcpu_count, 1)
710 local_epa_vcpu_set = True
711
712 return numa, local_epa_vcpu_set
713
714 @staticmethod
715 def _process_epa_params(
716 target_flavor: Dict[str, Any],
717 ) -> Dict[str, Any]:
718 """[summary]
719
720 Args:
721 target_flavor (Dict[str, Any]): [description]
722
723 Returns:
724 Dict[str, Any]: [description]
725 """
726 extended = {}
727 numa = {}
728
729 if target_flavor.get("guest-epa"):
730 guest_epa = target_flavor["guest-epa"]
731
732 numa, epa_vcpu_set = Ns._process_guest_epa_numa_params(
733 guest_epa_quota=guest_epa
734 )
735
736 if guest_epa.get("mempage-size"):
737 extended["mempage-size"] = guest_epa.get("mempage-size")
738
739 tmp_numa, epa_vcpu_set = Ns._process_guest_epa_cpu_pinning_params(
740 guest_epa_quota=guest_epa,
741 vcpu_count=int(target_flavor.get("vcpu-count", 1)),
742 epa_vcpu_set=epa_vcpu_set,
743 )
744 numa.update(tmp_numa)
745
746 extended.update(
747 Ns._process_guest_epa_quota_params(
748 guest_epa_quota=guest_epa,
749 epa_vcpu_set=epa_vcpu_set,
750 )
751 )
752
753 if numa:
754 extended["numas"] = [numa]
755
756 return extended
757
758 @staticmethod
759 def _process_flavor_params(
760 target_flavor: Dict[str, Any],
761 indata: Dict[str, Any],
762 vim_info: Dict[str, Any],
763 target_record_id: str,
764 **kwargs: Dict[str, Any],
765 ) -> Dict[str, Any]:
766 """[summary]
767
768 Args:
769 target_flavor (Dict[str, Any]): [description]
770 indata (Dict[str, Any]): [description]
771 vim_info (Dict[str, Any]): [description]
772 target_record_id (str): [description]
773
774 Returns:
775 Dict[str, Any]: [description]
776 """
777 flavor_data = {
778 "disk": int(target_flavor["storage-gb"]),
779 "ram": int(target_flavor["memory-mb"]),
780 "vcpus": int(target_flavor["vcpu-count"]),
781 }
782
783 target_vdur = {}
784 for vnf in indata.get("vnf", []):
785 for vdur in vnf.get("vdur", []):
786 if vdur.get("ns-flavor-id") == target_flavor["id"]:
787 target_vdur = vdur
788
789 for storage in target_vdur.get("virtual-storages", []):
790 if (
791 storage.get("type-of-storage")
792 == "etsi-nfv-descriptors:ephemeral-storage"
793 ):
794 flavor_data["ephemeral"] = int(storage.get("size-of-storage", 0))
795 elif storage.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
796 flavor_data["swap"] = int(storage.get("size-of-storage", 0))
797
798 extended = Ns._process_epa_params(target_flavor)
799 if extended:
800 flavor_data["extended"] = extended
801
802 extra_dict = {"find_params": {"flavor_data": flavor_data}}
803 flavor_data_name = flavor_data.copy()
804 flavor_data_name["name"] = target_flavor["name"]
805 extra_dict["params"] = {"flavor_data": flavor_data_name}
806
807 return extra_dict
808
809 @staticmethod
810 def _ip_profile_to_ro(
811 ip_profile: Dict[str, Any],
812 ) -> Dict[str, Any]:
813 """[summary]
814
815 Args:
816 ip_profile (Dict[str, Any]): [description]
817
818 Returns:
819 Dict[str, Any]: [description]
820 """
821 if not ip_profile:
822 return None
823
824 ro_ip_profile = {
825 "ip_version": "IPv4"
826 if "v4" in ip_profile.get("ip-version", "ipv4")
827 else "IPv6",
828 "subnet_address": ip_profile.get("subnet-address"),
829 "gateway_address": ip_profile.get("gateway-address"),
830 "dhcp_enabled": ip_profile.get("dhcp-params", {}).get("enabled", False),
831 "dhcp_start_address": ip_profile.get("dhcp-params", {}).get(
832 "start-address", None
833 ),
834 "dhcp_count": ip_profile.get("dhcp-params", {}).get("count", None),
835 }
836
837 if ip_profile.get("dns-server"):
838 ro_ip_profile["dns_address"] = ";".join(
839 [v["address"] for v in ip_profile["dns-server"] if v.get("address")]
840 )
841
842 if ip_profile.get("security-group"):
843 ro_ip_profile["security_group"] = ip_profile["security-group"]
844
845 return ro_ip_profile
846
847 @staticmethod
848 def _process_net_params(
849 target_vld: Dict[str, Any],
850 indata: Dict[str, Any],
851 vim_info: Dict[str, Any],
852 target_record_id: str,
853 **kwargs: Dict[str, Any],
854 ) -> Dict[str, Any]:
855 """Function to process network parameters.
856
857 Args:
858 target_vld (Dict[str, Any]): [description]
859 indata (Dict[str, Any]): [description]
860 vim_info (Dict[str, Any]): [description]
861 target_record_id (str): [description]
862
863 Returns:
864 Dict[str, Any]: [description]
865 """
866 extra_dict = {}
867
868 if vim_info.get("sdn"):
869 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
870 # ns_preffix = "nsrs:{}".format(nsr_id)
871 # remove the ending ".sdn
872 vld_target_record_id, _, _ = target_record_id.rpartition(".")
873 extra_dict["params"] = {
874 k: vim_info[k]
875 for k in ("sdn-ports", "target_vim", "vlds", "type")
876 if vim_info.get(k)
877 }
878
879 # TODO needed to add target_id in the dependency.
880 if vim_info.get("target_vim"):
881 extra_dict["depends_on"] = [
882 f"{vim_info.get('target_vim')} {vld_target_record_id}"
883 ]
884
885 return extra_dict
886
887 if vim_info.get("vim_network_name"):
888 extra_dict["find_params"] = {
889 "filter_dict": {
890 "name": vim_info.get("vim_network_name"),
891 },
892 }
893 elif vim_info.get("vim_network_id"):
894 extra_dict["find_params"] = {
895 "filter_dict": {
896 "id": vim_info.get("vim_network_id"),
897 },
898 }
899 elif target_vld.get("mgmt-network"):
900 extra_dict["find_params"] = {
901 "mgmt": True,
902 "name": target_vld["id"],
903 }
904 else:
905 # create
906 extra_dict["params"] = {
907 "net_name": (
908 f"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
909 ),
910 "ip_profile": Ns._ip_profile_to_ro(vim_info.get("ip_profile")),
911 "provider_network_profile": vim_info.get("provider_network"),
912 }
913
914 if not target_vld.get("underlay"):
915 extra_dict["params"]["net_type"] = "bridge"
916 else:
917 extra_dict["params"]["net_type"] = (
918 "ptp" if target_vld.get("type") == "ELINE" else "data"
919 )
920
921 return extra_dict
922
923 @staticmethod
924 def _process_vdu_params(
925 target_vdu: Dict[str, Any],
926 indata: Dict[str, Any],
927 vim_info: Dict[str, Any],
928 target_record_id: str,
929 **kwargs: Dict[str, Any],
930 ) -> Dict[str, Any]:
931 """Function to process VDU parameters.
932
933 Args:
934 target_vdu (Dict[str, Any]): [description]
935 indata (Dict[str, Any]): [description]
936 vim_info (Dict[str, Any]): [description]
937 target_record_id (str): [description]
938
939 Returns:
940 Dict[str, Any]: [description]
941 """
942 vnfr_id = kwargs.get("vnfr_id")
943 nsr_id = kwargs.get("nsr_id")
944 vnfr = kwargs.get("vnfr")
945 vdu2cloud_init = kwargs.get("vdu2cloud_init")
946 tasks_by_target_record_id = kwargs.get("tasks_by_target_record_id")
947 logger = kwargs.get("logger")
948 db = kwargs.get("db")
949 fs = kwargs.get("fs")
950 ro_nsr_public_key = kwargs.get("ro_nsr_public_key")
951
952 vnf_preffix = "vnfrs:{}".format(vnfr_id)
953 ns_preffix = "nsrs:{}".format(nsr_id)
954 image_text = ns_preffix + ":image." + target_vdu["ns-image-id"]
955 flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"]
956 extra_dict = {"depends_on": [image_text, flavor_text]}
957 net_list = []
958
959 for iface_index, interface in enumerate(target_vdu["interfaces"]):
960 if interface.get("ns-vld-id"):
961 net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
962 elif interface.get("vnf-vld-id"):
963 net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
964 else:
965 logger.error(
966 "Interface {} from vdu {} not connected to any vld".format(
967 iface_index, target_vdu["vdu-name"]
968 )
969 )
970
971 continue # interface not connected to any vld
972
973 extra_dict["depends_on"].append(net_text)
974
975 if "port-security-enabled" in interface:
976 interface["port_security"] = interface.pop("port-security-enabled")
977
978 if "port-security-disable-strategy" in interface:
979 interface["port_security_disable_strategy"] = interface.pop(
980 "port-security-disable-strategy"
981 )
982
983 net_item = {
984 x: v
985 for x, v in interface.items()
986 if x
987 in (
988 "name",
989 "vpci",
990 "port_security",
991 "port_security_disable_strategy",
992 "floating_ip",
993 )
994 }
995 net_item["net_id"] = "TASK-" + net_text
996 net_item["type"] = "virtual"
997
998 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
999 # TODO floating_ip: True/False (or it can be None)
1000 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1001 # mark the net create task as type data
1002 if deep_get(
1003 tasks_by_target_record_id,
1004 net_text,
1005 "extra_dict",
1006 "params",
1007 "net_type",
1008 ):
1009 tasks_by_target_record_id[net_text]["extra_dict"]["params"][
1010 "net_type"
1011 ] = "data"
1012
1013 net_item["use"] = "data"
1014 net_item["model"] = interface["type"]
1015 net_item["type"] = interface["type"]
1016 elif (
1017 interface.get("type") == "OM-MGMT"
1018 or interface.get("mgmt-interface")
1019 or interface.get("mgmt-vnf")
1020 ):
1021 net_item["use"] = "mgmt"
1022 else:
1023 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1024 net_item["use"] = "bridge"
1025 net_item["model"] = interface.get("type")
1026
1027 if interface.get("ip-address"):
1028 net_item["ip_address"] = interface["ip-address"]
1029
1030 if interface.get("mac-address"):
1031 net_item["mac_address"] = interface["mac-address"]
1032
1033 net_list.append(net_item)
1034
1035 if interface.get("mgmt-vnf"):
1036 extra_dict["mgmt_vnf_interface"] = iface_index
1037 elif interface.get("mgmt-interface"):
1038 extra_dict["mgmt_vdu_interface"] = iface_index
1039
1040 # cloud config
1041 cloud_config = {}
1042
1043 if target_vdu.get("cloud-init"):
1044 if target_vdu["cloud-init"] not in vdu2cloud_init:
1045 vdu2cloud_init[target_vdu["cloud-init"]] = Ns._get_cloud_init(
1046 db=db,
1047 fs=fs,
1048 location=target_vdu["cloud-init"],
1049 )
1050
1051 cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
1052 cloud_config["user-data"] = Ns._parse_jinja2(
1053 cloud_init_content=cloud_content_,
1054 params=target_vdu.get("additionalParams"),
1055 context=target_vdu["cloud-init"],
1056 )
1057
1058 if target_vdu.get("boot-data-drive"):
1059 cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
1060
1061 ssh_keys = []
1062
1063 if target_vdu.get("ssh-keys"):
1064 ssh_keys += target_vdu.get("ssh-keys")
1065
1066 if target_vdu.get("ssh-access-required"):
1067 ssh_keys.append(ro_nsr_public_key)
1068
1069 if ssh_keys:
1070 cloud_config["key-pairs"] = ssh_keys
1071
1072 persistent_root_disk = {}
1073 disk_list = []
1074 vnfd_id = vnfr["vnfd-id"]
1075 vnfd = db.get_one("vnfds", {"_id": vnfd_id})
1076 for vdu in vnfd.get("vdu", ()):
1077 if vdu["name"] == target_vdu["vdu-name"]:
1078 for vsd in vnfd.get("virtual-storage-desc", ()):
1079 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
1080 root_disk = vsd
1081 if root_disk.get(
1082 "type-of-storage"
1083 ) == "persistent-storage:persistent-storage" and root_disk.get(
1084 "size-of-storage"
1085 ):
1086 persistent_root_disk[vsd["id"]] = {
1087 "image_id": vdu.get("sw-image-desc"),
1088 "size": root_disk["size-of-storage"],
1089 }
1090 disk_list.append(persistent_root_disk[vsd["id"]])
1091
1092 if target_vdu.get("virtual-storages"):
1093 for disk in target_vdu["virtual-storages"]:
1094 if (
1095 disk.get("type-of-storage")
1096 == "persistent-storage:persistent-storage"
1097 and disk["id"] not in persistent_root_disk.keys()
1098 ):
1099 disk_list.append({"size": disk["size-of-storage"]})
1100
1101 affinity_group_list = []
1102
1103 if target_vdu.get("affinity-or-anti-affinity-group-id"):
1104 affinity_group = {}
1105 for affinity_group_id in target_vdu["affinity-or-anti-affinity-group-id"]:
1106 affinity_group_text = (
1107 ns_preffix + ":affinity-or-anti-affinity-group." + affinity_group_id
1108 )
1109
1110 extra_dict["depends_on"].append(affinity_group_text)
1111 affinity_group["affinity_group_id"] = "TASK-" + affinity_group_text
1112 affinity_group_list.append(affinity_group)
1113
1114 extra_dict["params"] = {
1115 "name": "{}-{}-{}-{}".format(
1116 indata["name"][:16],
1117 vnfr["member-vnf-index-ref"][:16],
1118 target_vdu["vdu-name"][:32],
1119 target_vdu.get("count-index") or 0,
1120 ),
1121 "description": target_vdu["vdu-name"],
1122 "start": True,
1123 "image_id": "TASK-" + image_text,
1124 "flavor_id": "TASK-" + flavor_text,
1125 "affinity_group_list": affinity_group_list,
1126 "net_list": net_list,
1127 "cloud_config": cloud_config or None,
1128 "disk_list": disk_list,
1129 "availability_zone_index": None, # TODO
1130 "availability_zone_list": None, # TODO
1131 }
1132
1133 return extra_dict
1134
1135 @staticmethod
1136 def _process_affinity_group_params(
1137 target_affinity_group: Dict[str, Any],
1138 indata: Dict[str, Any],
1139 vim_info: Dict[str, Any],
1140 target_record_id: str,
1141 **kwargs: Dict[str, Any],
1142 ) -> Dict[str, Any]:
1143 """Get affinity or anti-affinity group parameters.
1144
1145 Args:
1146 target_affinity_group (Dict[str, Any]): [description]
1147 indata (Dict[str, Any]): [description]
1148 vim_info (Dict[str, Any]): [description]
1149 target_record_id (str): [description]
1150
1151 Returns:
1152 Dict[str, Any]: [description]
1153 """
1154 extra_dict = {}
1155
1156 affinity_group_data = {
1157 "name": target_affinity_group["name"],
1158 "type": target_affinity_group["type"],
1159 "scope": target_affinity_group["scope"],
1160 }
1161
1162 extra_dict["params"] = {
1163 "affinity_group_data": affinity_group_data,
1164 }
1165
1166 return extra_dict
1167
1168 def calculate_diff_items(
1169 self,
1170 indata,
1171 db_nsr,
1172 db_ro_nsr,
1173 db_nsr_update,
1174 item,
1175 tasks_by_target_record_id,
1176 action_id,
1177 nsr_id,
1178 task_index,
1179 vnfr_id=None,
1180 vnfr=None,
1181 ):
1182 """Function that returns the incremental changes (creation, deletion)
1183 related to a specific item `item` to be done. This function should be
1184 called for NS instantiation, NS termination, NS update to add a new VNF
1185 or a new VLD, remove a VNF or VLD, etc.
1186 Item can be `net, `flavor`, `image` or `vdu`.
1187 It takes a list of target items from indata (which came from the REST API)
1188 and compares with the existing items from db_ro_nsr, identifying the
1189 incremental changes to be done. During the comparison, it calls the method
1190 `process_params` (which was passed as parameter, and is particular for each
1191 `item`)
1192
1193 Args:
1194 indata (Dict[str, Any]): deployment info
1195 db_nsr: NSR record from DB
1196 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1197 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1198 item (str): element to process (net, vdu...)
1199 tasks_by_target_record_id (Dict[str, Any]):
1200 [<target_record_id>, <task>]
1201 action_id (str): action id
1202 nsr_id (str): NSR id
1203 task_index (number): task index to add to task name
1204 vnfr_id (str): VNFR id
1205 vnfr (Dict[str, Any]): VNFR info
1206
1207 Returns:
1208 List: list with the incremental changes (deletes, creates) for each item
1209 number: current task index
1210 """
1211
1212 diff_items = []
1213 db_path = ""
1214 db_record = ""
1215 target_list = []
1216 existing_list = []
1217 process_params = None
1218 vdu2cloud_init = indata.get("cloud_init_content") or {}
1219 ro_nsr_public_key = db_ro_nsr["public_key"]
1220
1221 # According to the type of item, the path, the target_list,
1222 # the existing_list and the method to process params are set
1223 db_path = self.db_path_map[item]
1224 process_params = self.process_params_function_map[item]
1225 if item in ("net", "vdu"):
1226 if vnfr is None:
1227 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1228 target_list = indata.get("ns", []).get(db_path, [])
1229 existing_list = db_nsr.get(db_path, [])
1230 else:
1231 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
1232 target_vnf = next(
1233 (vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id),
1234 None,
1235 )
1236 target_list = target_vnf.get(db_path, []) if target_vnf else []
1237 existing_list = vnfr.get(db_path, [])
1238 elif item in ("image", "flavor", "affinity-or-anti-affinity-group"):
1239 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1240 target_list = indata.get(item, [])
1241 existing_list = db_nsr.get(item, [])
1242 else:
1243 raise NsException("Item not supported: {}", item)
1244
1245 # ensure all the target_list elements has an "id". If not assign the index as id
1246 if target_list is None:
1247 target_list = []
1248 for target_index, tl in enumerate(target_list):
1249 if tl and not tl.get("id"):
1250 tl["id"] = str(target_index)
1251
1252 # step 1 items (networks,vdus,...) to be deleted/updated
1253 for item_index, existing_item in enumerate(existing_list):
1254 target_item = next(
1255 (t for t in target_list if t["id"] == existing_item["id"]),
1256 None,
1257 )
1258
1259 for target_vim, existing_viminfo in existing_item.get(
1260 "vim_info", {}
1261 ).items():
1262 if existing_viminfo is None:
1263 continue
1264
1265 if target_item:
1266 target_viminfo = target_item.get("vim_info", {}).get(target_vim)
1267 else:
1268 target_viminfo = None
1269
1270 if target_viminfo is None:
1271 # must be deleted
1272 self._assign_vim(target_vim)
1273 target_record_id = "{}.{}".format(db_record, existing_item["id"])
1274 item_ = item
1275
1276 if target_vim.startswith("sdn"):
1277 # item must be sdn-net instead of net if target_vim is a sdn
1278 item_ = "sdn_net"
1279 target_record_id += ".sdn"
1280
1281 deployment_info = {
1282 "action_id": action_id,
1283 "nsr_id": nsr_id,
1284 "task_index": task_index,
1285 }
1286
1287 diff_items.append(
1288 {
1289 "deployment_info": deployment_info,
1290 "target_id": target_vim,
1291 "item": item_,
1292 "action": "DELETE",
1293 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1294 "target_record_id": target_record_id,
1295 }
1296 )
1297 task_index += 1
1298
1299 # step 2 items (networks,vdus,...) to be created
1300 for target_item in target_list:
1301 item_index = -1
1302
1303 for item_index, existing_item in enumerate(existing_list):
1304 if existing_item["id"] == target_item["id"]:
1305 break
1306 else:
1307 item_index += 1
1308 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1309 existing_list.append(target_item)
1310 existing_item = None
1311
1312 for target_vim, target_viminfo in target_item.get("vim_info", {}).items():
1313 existing_viminfo = None
1314
1315 if existing_item:
1316 existing_viminfo = existing_item.get("vim_info", {}).get(target_vim)
1317
1318 if existing_viminfo is not None:
1319 continue
1320
1321 target_record_id = "{}.{}".format(db_record, target_item["id"])
1322 item_ = item
1323
1324 if target_vim.startswith("sdn"):
1325 # item must be sdn-net instead of net if target_vim is a sdn
1326 item_ = "sdn_net"
1327 target_record_id += ".sdn"
1328
1329 kwargs = {}
1330 if process_params == Ns._process_vdu_params:
1331 kwargs.update(
1332 {
1333 "vnfr_id": vnfr_id,
1334 "nsr_id": nsr_id,
1335 "vnfr": vnfr,
1336 "vdu2cloud_init": vdu2cloud_init,
1337 "tasks_by_target_record_id": tasks_by_target_record_id,
1338 "logger": self.logger,
1339 "db": self.db,
1340 "fs": self.fs,
1341 "ro_nsr_public_key": ro_nsr_public_key,
1342 }
1343 )
1344
1345 extra_dict = process_params(
1346 target_item,
1347 indata,
1348 target_viminfo,
1349 target_record_id,
1350 **kwargs,
1351 )
1352 self._assign_vim(target_vim)
1353
1354 deployment_info = {
1355 "action_id": action_id,
1356 "nsr_id": nsr_id,
1357 "task_index": task_index,
1358 }
1359
1360 new_item = {
1361 "deployment_info": deployment_info,
1362 "target_id": target_vim,
1363 "item": item_,
1364 "action": "CREATE",
1365 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1366 "target_record_id": target_record_id,
1367 "extra_dict": extra_dict,
1368 "common_id": target_item.get("common_id", None),
1369 }
1370 diff_items.append(new_item)
1371 tasks_by_target_record_id[target_record_id] = new_item
1372 task_index += 1
1373
1374 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1375
1376 return diff_items, task_index
1377
1378 def calculate_all_differences_to_deploy(
1379 self,
1380 indata,
1381 nsr_id,
1382 db_nsr,
1383 db_vnfrs,
1384 db_ro_nsr,
1385 db_nsr_update,
1386 db_vnfrs_update,
1387 action_id,
1388 tasks_by_target_record_id,
1389 ):
1390 """This method calculates the ordered list of items (`changes_list`)
1391 to be created and deleted.
1392
1393 Args:
1394 indata (Dict[str, Any]): deployment info
1395 nsr_id (str): NSR id
1396 db_nsr: NSR record from DB
1397 db_vnfrs: VNFRS record from DB
1398 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1399 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1400 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
1401 action_id (str): action id
1402 tasks_by_target_record_id (Dict[str, Any]):
1403 [<target_record_id>, <task>]
1404
1405 Returns:
1406 List: ordered list of items to be created and deleted.
1407 """
1408
1409 task_index = 0
1410 # set list with diffs:
1411 changes_list = []
1412
1413 # NS vld, image and flavor
1414 for item in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
1415 self.logger.debug("process NS={} {}".format(nsr_id, item))
1416 diff_items, task_index = self.calculate_diff_items(
1417 indata=indata,
1418 db_nsr=db_nsr,
1419 db_ro_nsr=db_ro_nsr,
1420 db_nsr_update=db_nsr_update,
1421 item=item,
1422 tasks_by_target_record_id=tasks_by_target_record_id,
1423 action_id=action_id,
1424 nsr_id=nsr_id,
1425 task_index=task_index,
1426 vnfr_id=None,
1427 )
1428 changes_list += diff_items
1429
1430 # VNF vlds and vdus
1431 for vnfr_id, vnfr in db_vnfrs.items():
1432 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1433 for item in ["net", "vdu"]:
1434 self.logger.debug("process VNF={} {}".format(vnfr_id, item))
1435 diff_items, task_index = self.calculate_diff_items(
1436 indata=indata,
1437 db_nsr=db_nsr,
1438 db_ro_nsr=db_ro_nsr,
1439 db_nsr_update=db_vnfrs_update[vnfr["_id"]],
1440 item=item,
1441 tasks_by_target_record_id=tasks_by_target_record_id,
1442 action_id=action_id,
1443 nsr_id=nsr_id,
1444 task_index=task_index,
1445 vnfr_id=vnfr_id,
1446 vnfr=vnfr,
1447 )
1448 changes_list += diff_items
1449
1450 return changes_list
1451
1452 def define_all_tasks(
1453 self,
1454 changes_list,
1455 db_new_tasks,
1456 tasks_by_target_record_id,
1457 ):
1458 """Function to create all the task structures obtanied from
1459 the method calculate_all_differences_to_deploy
1460
1461 Args:
1462 changes_list (List): ordered list of items to be created or deleted
1463 db_new_tasks (List): tasks list to be created
1464 action_id (str): action id
1465 tasks_by_target_record_id (Dict[str, Any]):
1466 [<target_record_id>, <task>]
1467
1468 """
1469
1470 for change in changes_list:
1471 task = Ns._create_task(
1472 deployment_info=change["deployment_info"],
1473 target_id=change["target_id"],
1474 item=change["item"],
1475 action=change["action"],
1476 target_record=change["target_record"],
1477 target_record_id=change["target_record_id"],
1478 extra_dict=change.get("extra_dict", None),
1479 )
1480
1481 tasks_by_target_record_id[change["target_record_id"]] = task
1482 db_new_tasks.append(task)
1483
1484 if change.get("common_id"):
1485 task["common_id"] = change["common_id"]
1486
1487 def upload_all_tasks(
1488 self,
1489 db_new_tasks,
1490 now,
1491 ):
1492 """Function to save all tasks in the common DB
1493
1494 Args:
1495 db_new_tasks (List): tasks list to be created
1496 now (time): current time
1497
1498 """
1499
1500 nb_ro_tasks = 0 # for logging
1501
1502 for db_task in db_new_tasks:
1503 target_id = db_task.pop("target_id")
1504 common_id = db_task.get("common_id")
1505
1506 if common_id:
1507 if self.db.set_one(
1508 "ro_tasks",
1509 q_filter={
1510 "target_id": target_id,
1511 "tasks.common_id": common_id,
1512 },
1513 update_dict={"to_check_at": now, "modified_at": now},
1514 push={"tasks": db_task},
1515 fail_on_empty=False,
1516 ):
1517 continue
1518
1519 if not self.db.set_one(
1520 "ro_tasks",
1521 q_filter={
1522 "target_id": target_id,
1523 "tasks.target_record": db_task["target_record"],
1524 },
1525 update_dict={"to_check_at": now, "modified_at": now},
1526 push={"tasks": db_task},
1527 fail_on_empty=False,
1528 ):
1529 # Create a ro_task
1530 self.logger.debug("Updating database, Creating ro_tasks")
1531 db_ro_task = Ns._create_ro_task(target_id, db_task)
1532 nb_ro_tasks += 1
1533 self.db.create("ro_tasks", db_ro_task)
1534
1535 self.logger.debug(
1536 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1537 nb_ro_tasks, len(db_new_tasks), db_new_tasks
1538 )
1539 )
1540
1541 def deploy(self, session, indata, version, nsr_id, *args, **kwargs):
1542 self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata))
1543 validate_input(indata, deploy_schema)
1544 action_id = indata.get("action_id", str(uuid4()))
1545 task_index = 0
1546 # get current deployment
1547 db_nsr_update = {} # update operation on nsrs
1548 db_vnfrs_update = {}
1549 db_vnfrs = {} # vnf's info indexed by _id
1550 step = ""
1551 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
1552 self.logger.debug(logging_text + "Enter")
1553
1554 try:
1555 step = "Getting ns and vnfr record from db"
1556 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1557 db_new_tasks = []
1558 tasks_by_target_record_id = {}
1559 # read from db: vnf's of this ns
1560 step = "Getting vnfrs from db"
1561 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1562
1563 if not db_vnfrs_list:
1564 raise NsException("Cannot obtain associated VNF for ns")
1565
1566 for vnfr in db_vnfrs_list:
1567 db_vnfrs[vnfr["_id"]] = vnfr
1568 db_vnfrs_update[vnfr["_id"]] = {}
1569
1570 now = time()
1571 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
1572
1573 if not db_ro_nsr:
1574 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
1575
1576 # check that action_id is not in the list of actions. Suffixed with :index
1577 if action_id in db_ro_nsr["actions"]:
1578 index = 1
1579
1580 while True:
1581 new_action_id = "{}:{}".format(action_id, index)
1582
1583 if new_action_id not in db_ro_nsr["actions"]:
1584 action_id = new_action_id
1585 self.logger.debug(
1586 logging_text
1587 + "Changing action_id in use to {}".format(action_id)
1588 )
1589 break
1590
1591 index += 1
1592
1593 def _process_action(indata):
1594 nonlocal db_new_tasks
1595 nonlocal action_id
1596 nonlocal nsr_id
1597 nonlocal task_index
1598 nonlocal db_vnfrs
1599 nonlocal db_ro_nsr
1600
1601 if indata["action"]["action"] == "inject_ssh_key":
1602 key = indata["action"].get("key")
1603 user = indata["action"].get("user")
1604 password = indata["action"].get("password")
1605
1606 for vnf in indata.get("vnf", ()):
1607 if vnf["_id"] not in db_vnfrs:
1608 raise NsException("Invalid vnf={}".format(vnf["_id"]))
1609
1610 db_vnfr = db_vnfrs[vnf["_id"]]
1611
1612 for target_vdu in vnf.get("vdur", ()):
1613 vdu_index, vdur = next(
1614 (
1615 i_v
1616 for i_v in enumerate(db_vnfr["vdur"])
1617 if i_v[1]["id"] == target_vdu["id"]
1618 ),
1619 (None, None),
1620 )
1621
1622 if not vdur:
1623 raise NsException(
1624 "Invalid vdu vnf={}.{}".format(
1625 vnf["_id"], target_vdu["id"]
1626 )
1627 )
1628
1629 target_vim, vim_info = next(
1630 k_v for k_v in vdur["vim_info"].items()
1631 )
1632 self._assign_vim(target_vim)
1633 target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
1634 vnf["_id"], vdu_index
1635 )
1636 extra_dict = {
1637 "depends_on": [
1638 "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
1639 ],
1640 "params": {
1641 "ip_address": vdur.get("ip-address"),
1642 "user": user,
1643 "key": key,
1644 "password": password,
1645 "private_key": db_ro_nsr["private_key"],
1646 "salt": db_ro_nsr["_id"],
1647 "schema_version": db_ro_nsr["_admin"][
1648 "schema_version"
1649 ],
1650 },
1651 }
1652
1653 deployment_info = {
1654 "action_id": action_id,
1655 "nsr_id": nsr_id,
1656 "task_index": task_index,
1657 }
1658
1659 task = Ns._create_task(
1660 deployment_info=deployment_info,
1661 target_id=target_vim,
1662 item="vdu",
1663 action="EXEC",
1664 target_record=target_record,
1665 target_record_id=None,
1666 extra_dict=extra_dict,
1667 )
1668
1669 task_index = deployment_info.get("task_index")
1670
1671 db_new_tasks.append(task)
1672
1673 with self.write_lock:
1674 if indata.get("action"):
1675 _process_action(indata)
1676 else:
1677 # compute network differences
1678 # NS
1679 step = "process NS elements"
1680 changes_list = self.calculate_all_differences_to_deploy(
1681 indata=indata,
1682 nsr_id=nsr_id,
1683 db_nsr=db_nsr,
1684 db_vnfrs=db_vnfrs,
1685 db_ro_nsr=db_ro_nsr,
1686 db_nsr_update=db_nsr_update,
1687 db_vnfrs_update=db_vnfrs_update,
1688 action_id=action_id,
1689 tasks_by_target_record_id=tasks_by_target_record_id,
1690 )
1691 self.define_all_tasks(
1692 changes_list=changes_list,
1693 db_new_tasks=db_new_tasks,
1694 tasks_by_target_record_id=tasks_by_target_record_id,
1695 )
1696
1697 step = "Updating database, Appending tasks to ro_tasks"
1698 self.upload_all_tasks(
1699 db_new_tasks=db_new_tasks,
1700 now=now,
1701 )
1702
1703 step = "Updating database, nsrs"
1704 if db_nsr_update:
1705 self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
1706
1707 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
1708 if db_vnfr_update:
1709 step = "Updating database, vnfrs={}".format(vnfr_id)
1710 self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
1711
1712 self.logger.debug(
1713 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
1714 )
1715
1716 return (
1717 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
1718 action_id,
1719 True,
1720 )
1721 except Exception as e:
1722 if isinstance(e, (DbException, NsException)):
1723 self.logger.error(
1724 logging_text + "Exit Exception while '{}': {}".format(step, e)
1725 )
1726 else:
1727 e = traceback_format_exc()
1728 self.logger.critical(
1729 logging_text + "Exit Exception while '{}': {}".format(step, e),
1730 exc_info=True,
1731 )
1732
1733 raise NsException(e)
1734
1735 def delete(self, session, indata, version, nsr_id, *args, **kwargs):
1736 self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
1737 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
1738
1739 with self.write_lock:
1740 try:
1741 NsWorker.delete_db_tasks(self.db, nsr_id, None)
1742 except NsWorkerException as e:
1743 raise NsException(e)
1744
1745 return None, None, True
1746
1747 def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1748 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
1749 # .format(version, nsr_id, action_id, indata))
1750 task_list = []
1751 done = 0
1752 total = 0
1753 ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
1754 global_status = "DONE"
1755 details = []
1756
1757 for ro_task in ro_tasks:
1758 for task in ro_task["tasks"]:
1759 if task and task["action_id"] == action_id:
1760 task_list.append(task)
1761 total += 1
1762
1763 if task["status"] == "FAILED":
1764 global_status = "FAILED"
1765 error_text = "Error at {} {}: {}".format(
1766 task["action"].lower(),
1767 task["item"],
1768 ro_task["vim_info"].get("vim_details") or "unknown",
1769 )
1770 details.append(error_text)
1771 elif task["status"] in ("SCHEDULED", "BUILD"):
1772 if global_status != "FAILED":
1773 global_status = "BUILD"
1774 else:
1775 done += 1
1776
1777 return_data = {
1778 "status": global_status,
1779 "details": ". ".join(details)
1780 if details
1781 else "progress {}/{}".format(done, total),
1782 "nsr_id": nsr_id,
1783 "action_id": action_id,
1784 "tasks": task_list,
1785 }
1786
1787 return return_data, None, True
1788
1789 def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1790 print(
1791 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
1792 session, indata, version, nsr_id, action_id
1793 )
1794 )
1795
1796 return None, None, True
1797
1798 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1799 nsrs = self.db.get_list("nsrs", {})
1800 return_data = []
1801
1802 for ns in nsrs:
1803 return_data.append({"_id": ns["_id"], "name": ns["name"]})
1804
1805 return return_data, None, True
1806
1807 def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1808 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
1809 return_data = []
1810
1811 for ro_task in ro_tasks:
1812 for task in ro_task["tasks"]:
1813 if task["action_id"] not in return_data:
1814 return_data.append(task["action_id"])
1815
1816 return return_data, None, True