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