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