Feature 10906: Support for Anti-Affinity groups
[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 disk_list = None
1073 if target_vdu.get("virtual-storages"):
1074 disk_list = [
1075 {"size": disk["size-of-storage"]}
1076 for disk in target_vdu["virtual-storages"]
1077 if disk.get("type-of-storage")
1078 == "persistent-storage:persistent-storage"
1079 ]
1080
1081 affinity_group_list = []
1082
1083 if target_vdu.get("affinity-or-anti-affinity-group-id"):
1084 affinity_group = {}
1085 for affinity_group_id in target_vdu["affinity-or-anti-affinity-group-id"]:
1086 affinity_group_text = (
1087 ns_preffix + ":affinity-or-anti-affinity-group." + affinity_group_id
1088 )
1089
1090 extra_dict["depends_on"].append(affinity_group_text)
1091 affinity_group["affinity_group_id"] = "TASK-" + affinity_group_text
1092 affinity_group_list.append(affinity_group)
1093
1094 extra_dict["params"] = {
1095 "name": "{}-{}-{}-{}".format(
1096 indata["name"][:16],
1097 vnfr["member-vnf-index-ref"][:16],
1098 target_vdu["vdu-name"][:32],
1099 target_vdu.get("count-index") or 0,
1100 ),
1101 "description": target_vdu["vdu-name"],
1102 "start": True,
1103 "image_id": "TASK-" + image_text,
1104 "flavor_id": "TASK-" + flavor_text,
1105 "affinity_group_list": affinity_group_list,
1106 "net_list": net_list,
1107 "cloud_config": cloud_config or None,
1108 "disk_list": disk_list,
1109 "availability_zone_index": None, # TODO
1110 "availability_zone_list": None, # TODO
1111 }
1112
1113 return extra_dict
1114
1115 @staticmethod
1116 def _process_affinity_group_params(
1117 target_affinity_group: Dict[str, Any],
1118 indata: Dict[str, Any],
1119 vim_info: Dict[str, Any],
1120 target_record_id: str,
1121 **kwargs: Dict[str, Any],
1122 ) -> Dict[str, Any]:
1123 """Get affinity or anti-affinity group parameters.
1124
1125 Args:
1126 target_affinity_group (Dict[str, Any]): [description]
1127 indata (Dict[str, Any]): [description]
1128 vim_info (Dict[str, Any]): [description]
1129 target_record_id (str): [description]
1130
1131 Returns:
1132 Dict[str, Any]: [description]
1133 """
1134 extra_dict = {}
1135
1136 affinity_group_data = {
1137 "name": target_affinity_group["name"],
1138 "type": target_affinity_group["type"],
1139 "scope": target_affinity_group["scope"],
1140 }
1141
1142 extra_dict["params"] = {
1143 "affinity_group_data": affinity_group_data,
1144 }
1145
1146 return extra_dict
1147
1148 def calculate_diff_items(
1149 self,
1150 indata,
1151 db_nsr,
1152 db_ro_nsr,
1153 db_nsr_update,
1154 item,
1155 tasks_by_target_record_id,
1156 action_id,
1157 nsr_id,
1158 task_index,
1159 vnfr_id=None,
1160 vnfr=None,
1161 ):
1162 """Function that returns the incremental changes (creation, deletion)
1163 related to a specific item `item` to be done. This function should be
1164 called for NS instantiation, NS termination, NS update to add a new VNF
1165 or a new VLD, remove a VNF or VLD, etc.
1166 Item can be `net, `flavor`, `image` or `vdu`.
1167 It takes a list of target items from indata (which came from the REST API)
1168 and compares with the existing items from db_ro_nsr, identifying the
1169 incremental changes to be done. During the comparison, it calls the method
1170 `process_params` (which was passed as parameter, and is particular for each
1171 `item`)
1172
1173 Args:
1174 indata (Dict[str, Any]): deployment info
1175 db_nsr: NSR record from DB
1176 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1177 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1178 item (str): element to process (net, vdu...)
1179 tasks_by_target_record_id (Dict[str, Any]):
1180 [<target_record_id>, <task>]
1181 action_id (str): action id
1182 nsr_id (str): NSR id
1183 task_index (number): task index to add to task name
1184 vnfr_id (str): VNFR id
1185 vnfr (Dict[str, Any]): VNFR info
1186
1187 Returns:
1188 List: list with the incremental changes (deletes, creates) for each item
1189 number: current task index
1190 """
1191
1192 diff_items = []
1193 db_path = ""
1194 db_record = ""
1195 target_list = []
1196 existing_list = []
1197 process_params = None
1198 vdu2cloud_init = indata.get("cloud_init_content") or {}
1199 ro_nsr_public_key = db_ro_nsr["public_key"]
1200
1201 # According to the type of item, the path, the target_list,
1202 # the existing_list and the method to process params are set
1203 db_path = self.db_path_map[item]
1204 process_params = self.process_params_function_map[item]
1205 if item in ("net", "vdu"):
1206 if vnfr is None:
1207 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1208 target_list = indata.get("ns", []).get(db_path, [])
1209 existing_list = db_nsr.get(db_path, [])
1210 else:
1211 db_record = "vnfrs:{}:{}".format(vnfr_id, db_path)
1212 target_vnf = next(
1213 (vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id),
1214 None,
1215 )
1216 target_list = target_vnf.get(db_path, []) if target_vnf else []
1217 existing_list = vnfr.get(db_path, [])
1218 elif item in ("image", "flavor", "affinity-or-anti-affinity-group"):
1219 db_record = "nsrs:{}:{}".format(nsr_id, db_path)
1220 target_list = indata.get(item, [])
1221 existing_list = db_nsr.get(item, [])
1222 else:
1223 raise NsException("Item not supported: {}", item)
1224
1225 # ensure all the target_list elements has an "id". If not assign the index as id
1226 if target_list is None:
1227 target_list = []
1228 for target_index, tl in enumerate(target_list):
1229 if tl and not tl.get("id"):
1230 tl["id"] = str(target_index)
1231
1232 # step 1 items (networks,vdus,...) to be deleted/updated
1233 for item_index, existing_item in enumerate(existing_list):
1234 target_item = next(
1235 (t for t in target_list if t["id"] == existing_item["id"]),
1236 None,
1237 )
1238
1239 for target_vim, existing_viminfo in existing_item.get(
1240 "vim_info", {}
1241 ).items():
1242 if existing_viminfo is None:
1243 continue
1244
1245 if target_item:
1246 target_viminfo = target_item.get("vim_info", {}).get(target_vim)
1247 else:
1248 target_viminfo = None
1249
1250 if target_viminfo is None:
1251 # must be deleted
1252 self._assign_vim(target_vim)
1253 target_record_id = "{}.{}".format(db_record, existing_item["id"])
1254 item_ = item
1255
1256 if target_vim.startswith("sdn"):
1257 # item must be sdn-net instead of net if target_vim is a sdn
1258 item_ = "sdn_net"
1259 target_record_id += ".sdn"
1260
1261 deployment_info = {
1262 "action_id": action_id,
1263 "nsr_id": nsr_id,
1264 "task_index": task_index,
1265 }
1266
1267 diff_items.append(
1268 {
1269 "deployment_info": deployment_info,
1270 "target_id": target_vim,
1271 "item": item_,
1272 "action": "DELETE",
1273 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1274 "target_record_id": target_record_id,
1275 }
1276 )
1277 task_index += 1
1278
1279 # step 2 items (networks,vdus,...) to be created
1280 for target_item in target_list:
1281 item_index = -1
1282
1283 for item_index, existing_item in enumerate(existing_list):
1284 if existing_item["id"] == target_item["id"]:
1285 break
1286 else:
1287 item_index += 1
1288 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1289 existing_list.append(target_item)
1290 existing_item = None
1291
1292 for target_vim, target_viminfo in target_item.get("vim_info", {}).items():
1293 existing_viminfo = None
1294
1295 if existing_item:
1296 existing_viminfo = existing_item.get("vim_info", {}).get(target_vim)
1297
1298 if existing_viminfo is not None:
1299 continue
1300
1301 target_record_id = "{}.{}".format(db_record, target_item["id"])
1302 item_ = item
1303
1304 if target_vim.startswith("sdn"):
1305 # item must be sdn-net instead of net if target_vim is a sdn
1306 item_ = "sdn_net"
1307 target_record_id += ".sdn"
1308
1309 kwargs = {}
1310 if process_params == Ns._process_vdu_params:
1311 kwargs.update(
1312 {
1313 "vnfr_id": vnfr_id,
1314 "nsr_id": nsr_id,
1315 "vnfr": vnfr,
1316 "vdu2cloud_init": vdu2cloud_init,
1317 "tasks_by_target_record_id": tasks_by_target_record_id,
1318 "logger": self.logger,
1319 "db": self.db,
1320 "fs": self.fs,
1321 "ro_nsr_public_key": ro_nsr_public_key,
1322 }
1323 )
1324
1325 extra_dict = process_params(
1326 target_item,
1327 indata,
1328 target_viminfo,
1329 target_record_id,
1330 **kwargs,
1331 )
1332 self._assign_vim(target_vim)
1333
1334 deployment_info = {
1335 "action_id": action_id,
1336 "nsr_id": nsr_id,
1337 "task_index": task_index,
1338 }
1339
1340 new_item = {
1341 "deployment_info": deployment_info,
1342 "target_id": target_vim,
1343 "item": item_,
1344 "action": "CREATE",
1345 "target_record": f"{db_record}.{item_index}.vim_info.{target_vim}",
1346 "target_record_id": target_record_id,
1347 "extra_dict": extra_dict,
1348 "common_id": target_item.get("common_id", None),
1349 }
1350 diff_items.append(new_item)
1351 tasks_by_target_record_id[target_record_id] = new_item
1352 task_index += 1
1353
1354 db_nsr_update[db_path + ".{}".format(item_index)] = target_item
1355
1356 return diff_items, task_index
1357
1358 def calculate_all_differences_to_deploy(
1359 self,
1360 indata,
1361 nsr_id,
1362 db_nsr,
1363 db_vnfrs,
1364 db_ro_nsr,
1365 db_nsr_update,
1366 db_vnfrs_update,
1367 action_id,
1368 tasks_by_target_record_id,
1369 ):
1370 """This method calculates the ordered list of items (`changes_list`)
1371 to be created and deleted.
1372
1373 Args:
1374 indata (Dict[str, Any]): deployment info
1375 nsr_id (str): NSR id
1376 db_nsr: NSR record from DB
1377 db_vnfrs: VNFRS record from DB
1378 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1379 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1380 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
1381 action_id (str): action id
1382 tasks_by_target_record_id (Dict[str, Any]):
1383 [<target_record_id>, <task>]
1384
1385 Returns:
1386 List: ordered list of items to be created and deleted.
1387 """
1388
1389 task_index = 0
1390 # set list with diffs:
1391 changes_list = []
1392
1393 # NS vld, image and flavor
1394 for item in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
1395 self.logger.debug("process NS={} {}".format(nsr_id, item))
1396 diff_items, task_index = self.calculate_diff_items(
1397 indata=indata,
1398 db_nsr=db_nsr,
1399 db_ro_nsr=db_ro_nsr,
1400 db_nsr_update=db_nsr_update,
1401 item=item,
1402 tasks_by_target_record_id=tasks_by_target_record_id,
1403 action_id=action_id,
1404 nsr_id=nsr_id,
1405 task_index=task_index,
1406 vnfr_id=None,
1407 )
1408 changes_list += diff_items
1409
1410 # VNF vlds and vdus
1411 for vnfr_id, vnfr in db_vnfrs.items():
1412 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1413 for item in ["net", "vdu"]:
1414 self.logger.debug("process VNF={} {}".format(vnfr_id, item))
1415 diff_items, task_index = self.calculate_diff_items(
1416 indata=indata,
1417 db_nsr=db_nsr,
1418 db_ro_nsr=db_ro_nsr,
1419 db_nsr_update=db_vnfrs_update[vnfr["_id"]],
1420 item=item,
1421 tasks_by_target_record_id=tasks_by_target_record_id,
1422 action_id=action_id,
1423 nsr_id=nsr_id,
1424 task_index=task_index,
1425 vnfr_id=vnfr_id,
1426 vnfr=vnfr,
1427 )
1428 changes_list += diff_items
1429
1430 return changes_list
1431
1432 def define_all_tasks(
1433 self,
1434 changes_list,
1435 db_new_tasks,
1436 tasks_by_target_record_id,
1437 ):
1438 """Function to create all the task structures obtanied from
1439 the method calculate_all_differences_to_deploy
1440
1441 Args:
1442 changes_list (List): ordered list of items to be created or deleted
1443 db_new_tasks (List): tasks list to be created
1444 action_id (str): action id
1445 tasks_by_target_record_id (Dict[str, Any]):
1446 [<target_record_id>, <task>]
1447
1448 """
1449
1450 for change in changes_list:
1451 task = Ns._create_task(
1452 deployment_info=change["deployment_info"],
1453 target_id=change["target_id"],
1454 item=change["item"],
1455 action=change["action"],
1456 target_record=change["target_record"],
1457 target_record_id=change["target_record_id"],
1458 extra_dict=change.get("extra_dict", None),
1459 )
1460
1461 tasks_by_target_record_id[change["target_record_id"]] = task
1462 db_new_tasks.append(task)
1463
1464 if change.get("common_id"):
1465 task["common_id"] = change["common_id"]
1466
1467 def upload_all_tasks(
1468 self,
1469 db_new_tasks,
1470 now,
1471 ):
1472 """Function to save all tasks in the common DB
1473
1474 Args:
1475 db_new_tasks (List): tasks list to be created
1476 now (time): current time
1477
1478 """
1479
1480 nb_ro_tasks = 0 # for logging
1481
1482 for db_task in db_new_tasks:
1483 target_id = db_task.pop("target_id")
1484 common_id = db_task.get("common_id")
1485
1486 if common_id:
1487 if self.db.set_one(
1488 "ro_tasks",
1489 q_filter={
1490 "target_id": target_id,
1491 "tasks.common_id": common_id,
1492 },
1493 update_dict={"to_check_at": now, "modified_at": now},
1494 push={"tasks": db_task},
1495 fail_on_empty=False,
1496 ):
1497 continue
1498
1499 if not self.db.set_one(
1500 "ro_tasks",
1501 q_filter={
1502 "target_id": target_id,
1503 "tasks.target_record": db_task["target_record"],
1504 },
1505 update_dict={"to_check_at": now, "modified_at": now},
1506 push={"tasks": db_task},
1507 fail_on_empty=False,
1508 ):
1509 # Create a ro_task
1510 self.logger.debug("Updating database, Creating ro_tasks")
1511 db_ro_task = Ns._create_ro_task(target_id, db_task)
1512 nb_ro_tasks += 1
1513 self.db.create("ro_tasks", db_ro_task)
1514
1515 self.logger.debug(
1516 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1517 nb_ro_tasks, len(db_new_tasks), db_new_tasks
1518 )
1519 )
1520
1521 def deploy(self, session, indata, version, nsr_id, *args, **kwargs):
1522 self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata))
1523 validate_input(indata, deploy_schema)
1524 action_id = indata.get("action_id", str(uuid4()))
1525 task_index = 0
1526 # get current deployment
1527 db_nsr_update = {} # update operation on nsrs
1528 db_vnfrs_update = {}
1529 db_vnfrs = {} # vnf's info indexed by _id
1530 step = ""
1531 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
1532 self.logger.debug(logging_text + "Enter")
1533
1534 try:
1535 step = "Getting ns and vnfr record from db"
1536 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1537 db_new_tasks = []
1538 tasks_by_target_record_id = {}
1539 # read from db: vnf's of this ns
1540 step = "Getting vnfrs from db"
1541 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1542
1543 if not db_vnfrs_list:
1544 raise NsException("Cannot obtain associated VNF for ns")
1545
1546 for vnfr in db_vnfrs_list:
1547 db_vnfrs[vnfr["_id"]] = vnfr
1548 db_vnfrs_update[vnfr["_id"]] = {}
1549
1550 now = time()
1551 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
1552
1553 if not db_ro_nsr:
1554 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
1555
1556 # check that action_id is not in the list of actions. Suffixed with :index
1557 if action_id in db_ro_nsr["actions"]:
1558 index = 1
1559
1560 while True:
1561 new_action_id = "{}:{}".format(action_id, index)
1562
1563 if new_action_id not in db_ro_nsr["actions"]:
1564 action_id = new_action_id
1565 self.logger.debug(
1566 logging_text
1567 + "Changing action_id in use to {}".format(action_id)
1568 )
1569 break
1570
1571 index += 1
1572
1573 def _process_action(indata):
1574 nonlocal db_new_tasks
1575 nonlocal action_id
1576 nonlocal nsr_id
1577 nonlocal task_index
1578 nonlocal db_vnfrs
1579 nonlocal db_ro_nsr
1580
1581 if indata["action"]["action"] == "inject_ssh_key":
1582 key = indata["action"].get("key")
1583 user = indata["action"].get("user")
1584 password = indata["action"].get("password")
1585
1586 for vnf in indata.get("vnf", ()):
1587 if vnf["_id"] not in db_vnfrs:
1588 raise NsException("Invalid vnf={}".format(vnf["_id"]))
1589
1590 db_vnfr = db_vnfrs[vnf["_id"]]
1591
1592 for target_vdu in vnf.get("vdur", ()):
1593 vdu_index, vdur = next(
1594 (
1595 i_v
1596 for i_v in enumerate(db_vnfr["vdur"])
1597 if i_v[1]["id"] == target_vdu["id"]
1598 ),
1599 (None, None),
1600 )
1601
1602 if not vdur:
1603 raise NsException(
1604 "Invalid vdu vnf={}.{}".format(
1605 vnf["_id"], target_vdu["id"]
1606 )
1607 )
1608
1609 target_vim, vim_info = next(
1610 k_v for k_v in vdur["vim_info"].items()
1611 )
1612 self._assign_vim(target_vim)
1613 target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
1614 vnf["_id"], vdu_index
1615 )
1616 extra_dict = {
1617 "depends_on": [
1618 "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
1619 ],
1620 "params": {
1621 "ip_address": vdur.get("ip-address"),
1622 "user": user,
1623 "key": key,
1624 "password": password,
1625 "private_key": db_ro_nsr["private_key"],
1626 "salt": db_ro_nsr["_id"],
1627 "schema_version": db_ro_nsr["_admin"][
1628 "schema_version"
1629 ],
1630 },
1631 }
1632
1633 deployment_info = {
1634 "action_id": action_id,
1635 "nsr_id": nsr_id,
1636 "task_index": task_index,
1637 }
1638
1639 task = Ns._create_task(
1640 deployment_info=deployment_info,
1641 target_id=target_vim,
1642 item="vdu",
1643 action="EXEC",
1644 target_record=target_record,
1645 target_record_id=None,
1646 extra_dict=extra_dict,
1647 )
1648
1649 task_index = deployment_info.get("task_index")
1650
1651 db_new_tasks.append(task)
1652
1653 with self.write_lock:
1654 if indata.get("action"):
1655 _process_action(indata)
1656 else:
1657 # compute network differences
1658 # NS
1659 step = "process NS elements"
1660 changes_list = self.calculate_all_differences_to_deploy(
1661 indata=indata,
1662 nsr_id=nsr_id,
1663 db_nsr=db_nsr,
1664 db_vnfrs=db_vnfrs,
1665 db_ro_nsr=db_ro_nsr,
1666 db_nsr_update=db_nsr_update,
1667 db_vnfrs_update=db_vnfrs_update,
1668 action_id=action_id,
1669 tasks_by_target_record_id=tasks_by_target_record_id,
1670 )
1671 self.define_all_tasks(
1672 changes_list=changes_list,
1673 db_new_tasks=db_new_tasks,
1674 tasks_by_target_record_id=tasks_by_target_record_id,
1675 )
1676
1677 step = "Updating database, Appending tasks to ro_tasks"
1678 self.upload_all_tasks(
1679 db_new_tasks=db_new_tasks,
1680 now=now,
1681 )
1682
1683 step = "Updating database, nsrs"
1684 if db_nsr_update:
1685 self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
1686
1687 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
1688 if db_vnfr_update:
1689 step = "Updating database, vnfrs={}".format(vnfr_id)
1690 self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
1691
1692 self.logger.debug(
1693 logging_text + "Exit. Created {} tasks".format(len(db_new_tasks))
1694 )
1695
1696 return (
1697 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
1698 action_id,
1699 True,
1700 )
1701 except Exception as e:
1702 if isinstance(e, (DbException, NsException)):
1703 self.logger.error(
1704 logging_text + "Exit Exception while '{}': {}".format(step, e)
1705 )
1706 else:
1707 e = traceback_format_exc()
1708 self.logger.critical(
1709 logging_text + "Exit Exception while '{}': {}".format(step, e),
1710 exc_info=True,
1711 )
1712
1713 raise NsException(e)
1714
1715 def delete(self, session, indata, version, nsr_id, *args, **kwargs):
1716 self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
1717 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
1718
1719 with self.write_lock:
1720 try:
1721 NsWorker.delete_db_tasks(self.db, nsr_id, None)
1722 except NsWorkerException as e:
1723 raise NsException(e)
1724
1725 return None, None, True
1726
1727 def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1728 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
1729 # .format(version, nsr_id, action_id, indata))
1730 task_list = []
1731 done = 0
1732 total = 0
1733 ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
1734 global_status = "DONE"
1735 details = []
1736
1737 for ro_task in ro_tasks:
1738 for task in ro_task["tasks"]:
1739 if task and task["action_id"] == action_id:
1740 task_list.append(task)
1741 total += 1
1742
1743 if task["status"] == "FAILED":
1744 global_status = "FAILED"
1745 error_text = "Error at {} {}: {}".format(
1746 task["action"].lower(),
1747 task["item"],
1748 ro_task["vim_info"].get("vim_details") or "unknown",
1749 )
1750 details.append(error_text)
1751 elif task["status"] in ("SCHEDULED", "BUILD"):
1752 if global_status != "FAILED":
1753 global_status = "BUILD"
1754 else:
1755 done += 1
1756
1757 return_data = {
1758 "status": global_status,
1759 "details": ". ".join(details)
1760 if details
1761 else "progress {}/{}".format(done, total),
1762 "nsr_id": nsr_id,
1763 "action_id": action_id,
1764 "tasks": task_list,
1765 }
1766
1767 return return_data, None, True
1768
1769 def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1770 print(
1771 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
1772 session, indata, version, nsr_id, action_id
1773 )
1774 )
1775
1776 return None, None, True
1777
1778 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1779 nsrs = self.db.get_list("nsrs", {})
1780 return_data = []
1781
1782 for ns in nsrs:
1783 return_data.append({"_id": ns["_id"], "name": ns["name"]})
1784
1785 return return_data, None, True
1786
1787 def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1788 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
1789 return_data = []
1790
1791 for ro_task in ro_tasks:
1792 for task in ro_task["tasks"]:
1793 if task["action_id"] not in return_data:
1794 return_data.append(task["action_id"])
1795
1796 return return_data, None, True