Extracting Ns._get_resource_allocation_params() and creating unit test
[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
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 vim_info: Dict[str, Any],
475 target_record_id: str,
476 ) -> Dict[str, Any]:
477 """Function to process VDU image parameters.
478
479 Args:
480 target_image (Dict[str, Any]): [description]
481 vim_info (Dict[str, Any]): [description]
482 target_record_id (str): [description]
483
484 Returns:
485 Dict[str, Any]: [description]
486 """
487 find_params = {}
488
489 if target_image.get("image"):
490 find_params["filter_dict"] = {"name": target_image.get("image")}
491
492 if target_image.get("vim_image_id"):
493 find_params["filter_dict"] = {"id": target_image.get("vim_image_id")}
494
495 if target_image.get("image_checksum"):
496 find_params["filter_dict"] = {
497 "checksum": target_image.get("image_checksum")
498 }
499
500 return {"find_params": find_params}
501
502 @staticmethod
503 def _get_resource_allocation_params(
504 quota_descriptor: Dict[str, Any],
505 ) -> Dict[str, Any]:
506 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
507 descriptor object.
508
509 Args:
510 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
511
512 Returns:
513 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
514 """
515 quota = {}
516
517 if quota_descriptor.get("limit"):
518 quota["limit"] = int(quota_descriptor["limit"])
519
520 if quota_descriptor.get("reserve"):
521 quota["reserve"] = int(quota_descriptor["reserve"])
522
523 if quota_descriptor.get("shares"):
524 quota["shares"] = int(quota_descriptor["shares"])
525
526 return quota
527
528 def deploy(self, session, indata, version, nsr_id, *args, **kwargs):
529 self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata))
530 validate_input(indata, deploy_schema)
531 action_id = indata.get("action_id", str(uuid4()))
532 task_index = 0
533 # get current deployment
534 db_nsr_update = {} # update operation on nsrs
535 db_vnfrs_update = {}
536 db_vnfrs = {} # vnf's info indexed by _id
537 nb_ro_tasks = 0 # for logging
538 vdu2cloud_init = indata.get("cloud_init_content") or {}
539 step = ""
540 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
541 self.logger.debug(logging_text + "Enter")
542
543 try:
544 step = "Getting ns and vnfr record from db"
545 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
546 db_new_tasks = []
547 tasks_by_target_record_id = {}
548 # read from db: vnf's of this ns
549 step = "Getting vnfrs from db"
550 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
551
552 if not db_vnfrs_list:
553 raise NsException("Cannot obtain associated VNF for ns")
554
555 for vnfr in db_vnfrs_list:
556 db_vnfrs[vnfr["_id"]] = vnfr
557 db_vnfrs_update[vnfr["_id"]] = {}
558
559 now = time()
560 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
561
562 if not db_ro_nsr:
563 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
564
565 ro_nsr_public_key = db_ro_nsr["public_key"]
566
567 # check that action_id is not in the list of actions. Suffixed with :index
568 if action_id in db_ro_nsr["actions"]:
569 index = 1
570
571 while True:
572 new_action_id = "{}:{}".format(action_id, index)
573
574 if new_action_id not in db_ro_nsr["actions"]:
575 action_id = new_action_id
576 self.logger.debug(
577 logging_text
578 + "Changing action_id in use to {}".format(action_id)
579 )
580 break
581
582 index += 1
583
584 def _process_flavor_params(target_flavor, vim_info, target_record_id):
585 nonlocal indata
586
587 flavor_data = {
588 "disk": int(target_flavor["storage-gb"]),
589 "ram": int(target_flavor["memory-mb"]),
590 "vcpus": int(target_flavor["vcpu-count"]),
591 }
592 numa = {}
593 extended = {}
594
595 target_vdur = None
596 for vnf in indata.get("vnf", []):
597 for vdur in vnf.get("vdur", []):
598 if vdur.get("ns-flavor-id") == target_flavor["id"]:
599 target_vdur = vdur
600
601 for storage in target_vdur.get("virtual-storages", []):
602 if (
603 storage.get("type-of-storage")
604 == "etsi-nfv-descriptors:ephemeral-storage"
605 ):
606 flavor_data["ephemeral"] = int(
607 storage.get("size-of-storage", 0)
608 )
609 elif (
610 storage.get("type-of-storage")
611 == "etsi-nfv-descriptors:swap-storage"
612 ):
613 flavor_data["swap"] = int(storage.get("size-of-storage", 0))
614
615 if target_flavor.get("guest-epa"):
616 extended = {}
617 epa_vcpu_set = False
618
619 if target_flavor["guest-epa"].get("numa-node-policy"):
620 numa_node_policy = target_flavor["guest-epa"].get(
621 "numa-node-policy"
622 )
623
624 if numa_node_policy.get("node"):
625 numa_node = numa_node_policy["node"][0]
626
627 if numa_node.get("num-cores"):
628 numa["cores"] = numa_node["num-cores"]
629 epa_vcpu_set = True
630
631 if numa_node.get("paired-threads"):
632 if numa_node["paired-threads"].get(
633 "num-paired-threads"
634 ):
635 numa["paired-threads"] = int(
636 numa_node["paired-threads"][
637 "num-paired-threads"
638 ]
639 )
640 epa_vcpu_set = True
641
642 if len(
643 numa_node["paired-threads"].get("paired-thread-ids")
644 ):
645 numa["paired-threads-id"] = []
646
647 for pair in numa_node["paired-threads"][
648 "paired-thread-ids"
649 ]:
650 numa["paired-threads-id"].append(
651 (
652 str(pair["thread-a"]),
653 str(pair["thread-b"]),
654 )
655 )
656
657 if numa_node.get("num-threads"):
658 numa["threads"] = int(numa_node["num-threads"])
659 epa_vcpu_set = True
660
661 if numa_node.get("memory-mb"):
662 numa["memory"] = max(
663 int(numa_node["memory-mb"] / 1024), 1
664 )
665
666 if target_flavor["guest-epa"].get("mempage-size"):
667 extended["mempage-size"] = target_flavor["guest-epa"].get(
668 "mempage-size"
669 )
670
671 if (
672 target_flavor["guest-epa"].get("cpu-pinning-policy")
673 and not epa_vcpu_set
674 ):
675 if (
676 target_flavor["guest-epa"]["cpu-pinning-policy"]
677 == "DEDICATED"
678 ):
679 if (
680 target_flavor["guest-epa"].get(
681 "cpu-thread-pinning-policy"
682 )
683 and target_flavor["guest-epa"][
684 "cpu-thread-pinning-policy"
685 ]
686 != "PREFER"
687 ):
688 numa["cores"] = max(flavor_data["vcpus"], 1)
689 else:
690 numa["threads"] = max(flavor_data["vcpus"], 1)
691
692 epa_vcpu_set = True
693
694 if target_flavor["guest-epa"].get("cpu-quota") and not epa_vcpu_set:
695 cpuquota = Ns._get_resource_allocation_params(
696 target_flavor["guest-epa"].get("cpu-quota")
697 )
698
699 if cpuquota:
700 extended["cpu-quota"] = cpuquota
701
702 if target_flavor["guest-epa"].get("mem-quota"):
703 vduquota = Ns._get_resource_allocation_params(
704 target_flavor["guest-epa"].get("mem-quota")
705 )
706
707 if vduquota:
708 extended["mem-quota"] = vduquota
709
710 if target_flavor["guest-epa"].get("disk-io-quota"):
711 diskioquota = Ns._get_resource_allocation_params(
712 target_flavor["guest-epa"].get("disk-io-quota")
713 )
714
715 if diskioquota:
716 extended["disk-io-quota"] = diskioquota
717
718 if target_flavor["guest-epa"].get("vif-quota"):
719 vifquota = Ns._get_resource_allocation_params(
720 target_flavor["guest-epa"].get("vif-quota")
721 )
722
723 if vifquota:
724 extended["vif-quota"] = vifquota
725
726 if numa:
727 extended["numas"] = [numa]
728
729 if extended:
730 flavor_data["extended"] = extended
731
732 extra_dict = {"find_params": {"flavor_data": flavor_data}}
733 flavor_data_name = flavor_data.copy()
734 flavor_data_name["name"] = target_flavor["name"]
735 extra_dict["params"] = {"flavor_data": flavor_data_name}
736
737 return extra_dict
738
739 def _ip_profile_2_ro(ip_profile):
740 if not ip_profile:
741 return None
742
743 ro_ip_profile = {
744 "ip_version": "IPv4"
745 if "v4" in ip_profile.get("ip-version", "ipv4")
746 else "IPv6",
747 "subnet_address": ip_profile.get("subnet-address"),
748 "gateway_address": ip_profile.get("gateway-address"),
749 "dhcp_enabled": ip_profile.get("dhcp-params", {}).get(
750 "enabled", False
751 ),
752 "dhcp_start_address": ip_profile.get("dhcp-params", {}).get(
753 "start-address", None
754 ),
755 "dhcp_count": ip_profile.get("dhcp-params", {}).get("count", None),
756 }
757
758 if ip_profile.get("dns-server"):
759 ro_ip_profile["dns_address"] = ";".join(
760 [v["address"] for v in ip_profile["dns-server"]]
761 )
762
763 if ip_profile.get("security-group"):
764 ro_ip_profile["security_group"] = ip_profile["security-group"]
765
766 return ro_ip_profile
767
768 def _process_net_params(target_vld, vim_info, target_record_id):
769 nonlocal indata
770 extra_dict = {}
771
772 if vim_info.get("sdn"):
773 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
774 # ns_preffix = "nsrs:{}".format(nsr_id)
775 # remove the ending ".sdn
776 vld_target_record_id, _, _ = target_record_id.rpartition(".")
777 extra_dict["params"] = {
778 k: vim_info[k]
779 for k in ("sdn-ports", "target_vim", "vlds", "type")
780 if vim_info.get(k)
781 }
782
783 # TODO needed to add target_id in the dependency.
784 if vim_info.get("target_vim"):
785 extra_dict["depends_on"] = [
786 vim_info.get("target_vim") + " " + vld_target_record_id
787 ]
788
789 return extra_dict
790
791 if vim_info.get("vim_network_name"):
792 extra_dict["find_params"] = {
793 "filter_dict": {"name": vim_info.get("vim_network_name")}
794 }
795 elif vim_info.get("vim_network_id"):
796 extra_dict["find_params"] = {
797 "filter_dict": {"id": vim_info.get("vim_network_id")}
798 }
799 elif target_vld.get("mgmt-network"):
800 extra_dict["find_params"] = {"mgmt": True, "name": target_vld["id"]}
801 else:
802 # create
803 extra_dict["params"] = {
804 "net_name": "{}-{}".format(
805 indata["name"][:16],
806 target_vld.get("name", target_vld["id"])[:16],
807 ),
808 "ip_profile": _ip_profile_2_ro(vim_info.get("ip_profile")),
809 "provider_network_profile": vim_info.get("provider_network"),
810 }
811
812 if not target_vld.get("underlay"):
813 extra_dict["params"]["net_type"] = "bridge"
814 else:
815 extra_dict["params"]["net_type"] = (
816 "ptp" if target_vld.get("type") == "ELINE" else "data"
817 )
818
819 return extra_dict
820
821 def _process_vdu_params(target_vdu, vim_info, target_record_id):
822 nonlocal vnfr_id
823 nonlocal nsr_id
824 nonlocal indata
825 nonlocal vnfr
826 nonlocal vdu2cloud_init
827 nonlocal tasks_by_target_record_id
828
829 vnf_preffix = "vnfrs:{}".format(vnfr_id)
830 ns_preffix = "nsrs:{}".format(nsr_id)
831 image_text = ns_preffix + ":image." + target_vdu["ns-image-id"]
832 flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"]
833 extra_dict = {"depends_on": [image_text, flavor_text]}
834 net_list = []
835
836 for iface_index, interface in enumerate(target_vdu["interfaces"]):
837 if interface.get("ns-vld-id"):
838 net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
839 elif interface.get("vnf-vld-id"):
840 net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
841 else:
842 self.logger.error(
843 "Interface {} from vdu {} not connected to any vld".format(
844 iface_index, target_vdu["vdu-name"]
845 )
846 )
847
848 continue # interface not connected to any vld
849
850 extra_dict["depends_on"].append(net_text)
851
852 if "port-security-enabled" in interface:
853 interface["port_security"] = interface.pop(
854 "port-security-enabled"
855 )
856
857 if "port-security-disable-strategy" in interface:
858 interface["port_security_disable_strategy"] = interface.pop(
859 "port-security-disable-strategy"
860 )
861
862 net_item = {
863 x: v
864 for x, v in interface.items()
865 if x
866 in (
867 "name",
868 "vpci",
869 "port_security",
870 "port_security_disable_strategy",
871 "floating_ip",
872 )
873 }
874 net_item["net_id"] = "TASK-" + net_text
875 net_item["type"] = "virtual"
876
877 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
878 # TODO floating_ip: True/False (or it can be None)
879 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
880 # mark the net create task as type data
881 if deep_get(
882 tasks_by_target_record_id, net_text, "params", "net_type"
883 ):
884 tasks_by_target_record_id[net_text]["params"][
885 "net_type"
886 ] = "data"
887
888 net_item["use"] = "data"
889 net_item["model"] = interface["type"]
890 net_item["type"] = interface["type"]
891 elif (
892 interface.get("type") == "OM-MGMT"
893 or interface.get("mgmt-interface")
894 or interface.get("mgmt-vnf")
895 ):
896 net_item["use"] = "mgmt"
897 else:
898 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
899 net_item["use"] = "bridge"
900 net_item["model"] = interface.get("type")
901
902 if interface.get("ip-address"):
903 net_item["ip_address"] = interface["ip-address"]
904
905 if interface.get("mac-address"):
906 net_item["mac_address"] = interface["mac-address"]
907
908 net_list.append(net_item)
909
910 if interface.get("mgmt-vnf"):
911 extra_dict["mgmt_vnf_interface"] = iface_index
912 elif interface.get("mgmt-interface"):
913 extra_dict["mgmt_vdu_interface"] = iface_index
914
915 # cloud config
916 cloud_config = {}
917
918 if target_vdu.get("cloud-init"):
919 if target_vdu["cloud-init"] not in vdu2cloud_init:
920 vdu2cloud_init[target_vdu["cloud-init"]] = self._get_cloud_init(
921 target_vdu["cloud-init"]
922 )
923
924 cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
925 cloud_config["user-data"] = self._parse_jinja2(
926 cloud_content_,
927 target_vdu.get("additionalParams"),
928 target_vdu["cloud-init"],
929 )
930
931 if target_vdu.get("boot-data-drive"):
932 cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
933
934 ssh_keys = []
935
936 if target_vdu.get("ssh-keys"):
937 ssh_keys += target_vdu.get("ssh-keys")
938
939 if target_vdu.get("ssh-access-required"):
940 ssh_keys.append(ro_nsr_public_key)
941
942 if ssh_keys:
943 cloud_config["key-pairs"] = ssh_keys
944
945 disk_list = None
946 if target_vdu.get("virtual-storages"):
947 disk_list = [
948 {"size": disk["size-of-storage"]}
949 for disk in target_vdu["virtual-storages"]
950 if disk.get("type-of-storage")
951 == "persistent-storage:persistent-storage"
952 ]
953
954 extra_dict["params"] = {
955 "name": "{}-{}-{}-{}".format(
956 indata["name"][:16],
957 vnfr["member-vnf-index-ref"][:16],
958 target_vdu["vdu-name"][:32],
959 target_vdu.get("count-index") or 0,
960 ),
961 "description": target_vdu["vdu-name"],
962 "start": True,
963 "image_id": "TASK-" + image_text,
964 "flavor_id": "TASK-" + flavor_text,
965 "net_list": net_list,
966 "cloud_config": cloud_config or None,
967 "disk_list": disk_list,
968 "availability_zone_index": None, # TODO
969 "availability_zone_list": None, # TODO
970 }
971
972 return extra_dict
973
974 def _process_items(
975 target_list,
976 existing_list,
977 db_record,
978 db_update,
979 db_path,
980 item,
981 process_params,
982 ):
983 nonlocal db_new_tasks
984 nonlocal tasks_by_target_record_id
985 nonlocal action_id
986 nonlocal nsr_id
987 nonlocal task_index
988
989 # ensure all the target_list elements has an "id". If not assign the index as id
990 for target_index, tl in enumerate(target_list):
991 if tl and not tl.get("id"):
992 tl["id"] = str(target_index)
993
994 # step 1 items (networks,vdus,...) to be deleted/updated
995 for item_index, existing_item in enumerate(existing_list):
996 target_item = next(
997 (t for t in target_list if t["id"] == existing_item["id"]), None
998 )
999
1000 for target_vim, existing_viminfo in existing_item.get(
1001 "vim_info", {}
1002 ).items():
1003 if existing_viminfo is None:
1004 continue
1005
1006 if target_item:
1007 target_viminfo = target_item.get("vim_info", {}).get(
1008 target_vim
1009 )
1010 else:
1011 target_viminfo = None
1012
1013 if target_viminfo is None:
1014 # must be deleted
1015 self._assign_vim(target_vim)
1016 target_record_id = "{}.{}".format(
1017 db_record, existing_item["id"]
1018 )
1019 item_ = item
1020
1021 if target_vim.startswith("sdn"):
1022 # item must be sdn-net instead of net if target_vim is a sdn
1023 item_ = "sdn_net"
1024 target_record_id += ".sdn"
1025
1026 deployment_info = {
1027 "action_id": action_id,
1028 "nsr_id": nsr_id,
1029 "task_index": task_index,
1030 }
1031
1032 task = Ns._create_task(
1033 deployment_info=deployment_info,
1034 target_id=target_vim,
1035 item=item_,
1036 action="DELETE",
1037 target_record=f"{db_record}.{item_index}.vim_info.{target_vim}",
1038 target_record_id=target_record_id,
1039 )
1040
1041 task_index = deployment_info.get("task_index")
1042
1043 tasks_by_target_record_id[target_record_id] = task
1044 db_new_tasks.append(task)
1045 # TODO delete
1046 # TODO check one by one the vims to be created/deleted
1047
1048 # step 2 items (networks,vdus,...) to be created
1049 for target_item in target_list:
1050 item_index = -1
1051
1052 for item_index, existing_item in enumerate(existing_list):
1053 if existing_item["id"] == target_item["id"]:
1054 break
1055 else:
1056 item_index += 1
1057 db_update[db_path + ".{}".format(item_index)] = target_item
1058 existing_list.append(target_item)
1059 existing_item = None
1060
1061 for target_vim, target_viminfo in target_item.get(
1062 "vim_info", {}
1063 ).items():
1064 existing_viminfo = None
1065
1066 if existing_item:
1067 existing_viminfo = existing_item.get("vim_info", {}).get(
1068 target_vim
1069 )
1070
1071 # TODO check if different. Delete and create???
1072 # TODO delete if not exist
1073 if existing_viminfo is not None:
1074 continue
1075
1076 target_record_id = "{}.{}".format(db_record, target_item["id"])
1077 item_ = item
1078
1079 if target_vim.startswith("sdn"):
1080 # item must be sdn-net instead of net if target_vim is a sdn
1081 item_ = "sdn_net"
1082 target_record_id += ".sdn"
1083
1084 extra_dict = process_params(
1085 target_item, target_viminfo, target_record_id
1086 )
1087 self._assign_vim(target_vim)
1088
1089 deployment_info = {
1090 "action_id": action_id,
1091 "nsr_id": nsr_id,
1092 "task_index": task_index,
1093 }
1094
1095 task = Ns._create_task(
1096 deployment_info=deployment_info,
1097 target_id=target_vim,
1098 item=item_,
1099 action="CREATE",
1100 target_record=f"{db_record}.{item_index}.vim_info.{target_vim}",
1101 target_record_id=target_record_id,
1102 extra_dict=extra_dict,
1103 )
1104
1105 task_index = deployment_info.get("task_index")
1106
1107 tasks_by_target_record_id[target_record_id] = task
1108 db_new_tasks.append(task)
1109
1110 if target_item.get("common_id"):
1111 task["common_id"] = target_item["common_id"]
1112
1113 db_update[db_path + ".{}".format(item_index)] = target_item
1114
1115 def _process_action(indata):
1116 nonlocal db_new_tasks
1117 nonlocal action_id
1118 nonlocal nsr_id
1119 nonlocal task_index
1120 nonlocal db_vnfrs
1121 nonlocal db_ro_nsr
1122
1123 if indata["action"]["action"] == "inject_ssh_key":
1124 key = indata["action"].get("key")
1125 user = indata["action"].get("user")
1126 password = indata["action"].get("password")
1127
1128 for vnf in indata.get("vnf", ()):
1129 if vnf["_id"] not in db_vnfrs:
1130 raise NsException("Invalid vnf={}".format(vnf["_id"]))
1131
1132 db_vnfr = db_vnfrs[vnf["_id"]]
1133
1134 for target_vdu in vnf.get("vdur", ()):
1135 vdu_index, vdur = next(
1136 (
1137 i_v
1138 for i_v in enumerate(db_vnfr["vdur"])
1139 if i_v[1]["id"] == target_vdu["id"]
1140 ),
1141 (None, None),
1142 )
1143
1144 if not vdur:
1145 raise NsException(
1146 "Invalid vdu vnf={}.{}".format(
1147 vnf["_id"], target_vdu["id"]
1148 )
1149 )
1150
1151 target_vim, vim_info = next(
1152 k_v for k_v in vdur["vim_info"].items()
1153 )
1154 self._assign_vim(target_vim)
1155 target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(
1156 vnf["_id"], vdu_index
1157 )
1158 extra_dict = {
1159 "depends_on": [
1160 "vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])
1161 ],
1162 "params": {
1163 "ip_address": vdur.get("ip-address"),
1164 "user": user,
1165 "key": key,
1166 "password": password,
1167 "private_key": db_ro_nsr["private_key"],
1168 "salt": db_ro_nsr["_id"],
1169 "schema_version": db_ro_nsr["_admin"][
1170 "schema_version"
1171 ],
1172 },
1173 }
1174
1175 deployment_info = {
1176 "action_id": action_id,
1177 "nsr_id": nsr_id,
1178 "task_index": task_index,
1179 }
1180
1181 task = Ns._create_task(
1182 deployment_info=deployment_info,
1183 target_id=target_vim,
1184 item="vdu",
1185 action="EXEC",
1186 target_record=target_record,
1187 target_record_id=None,
1188 extra_dict=extra_dict,
1189 )
1190
1191 task_index = deployment_info.get("task_index")
1192
1193 db_new_tasks.append(task)
1194
1195 with self.write_lock:
1196 if indata.get("action"):
1197 _process_action(indata)
1198 else:
1199 # compute network differences
1200 # NS.vld
1201 step = "process NS VLDs"
1202 _process_items(
1203 target_list=indata["ns"]["vld"] or [],
1204 existing_list=db_nsr.get("vld") or [],
1205 db_record="nsrs:{}:vld".format(nsr_id),
1206 db_update=db_nsr_update,
1207 db_path="vld",
1208 item="net",
1209 process_params=_process_net_params,
1210 )
1211
1212 step = "process NS images"
1213 _process_items(
1214 target_list=indata.get("image") or [],
1215 existing_list=db_nsr.get("image") or [],
1216 db_record="nsrs:{}:image".format(nsr_id),
1217 db_update=db_nsr_update,
1218 db_path="image",
1219 item="image",
1220 process_params=Ns._process_image_params,
1221 )
1222
1223 step = "process NS flavors"
1224 _process_items(
1225 target_list=indata.get("flavor") or [],
1226 existing_list=db_nsr.get("flavor") or [],
1227 db_record="nsrs:{}:flavor".format(nsr_id),
1228 db_update=db_nsr_update,
1229 db_path="flavor",
1230 item="flavor",
1231 process_params=_process_flavor_params,
1232 )
1233
1234 # VNF.vld
1235 for vnfr_id, vnfr in db_vnfrs.items():
1236 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1237 step = "process VNF={} VLDs".format(vnfr_id)
1238 target_vnf = next(
1239 (
1240 vnf
1241 for vnf in indata.get("vnf", ())
1242 if vnf["_id"] == vnfr_id
1243 ),
1244 None,
1245 )
1246 target_list = target_vnf.get("vld") if target_vnf else None
1247 _process_items(
1248 target_list=target_list or [],
1249 existing_list=vnfr.get("vld") or [],
1250 db_record="vnfrs:{}:vld".format(vnfr_id),
1251 db_update=db_vnfrs_update[vnfr["_id"]],
1252 db_path="vld",
1253 item="net",
1254 process_params=_process_net_params,
1255 )
1256
1257 target_list = target_vnf.get("vdur") if target_vnf else None
1258 step = "process VNF={} VDUs".format(vnfr_id)
1259 _process_items(
1260 target_list=target_list or [],
1261 existing_list=vnfr.get("vdur") or [],
1262 db_record="vnfrs:{}:vdur".format(vnfr_id),
1263 db_update=db_vnfrs_update[vnfr["_id"]],
1264 db_path="vdur",
1265 item="vdu",
1266 process_params=_process_vdu_params,
1267 )
1268
1269 for db_task in db_new_tasks:
1270 step = "Updating database, Appending tasks to ro_tasks"
1271 target_id = db_task.pop("target_id")
1272 common_id = db_task.get("common_id")
1273
1274 if common_id:
1275 if self.db.set_one(
1276 "ro_tasks",
1277 q_filter={
1278 "target_id": target_id,
1279 "tasks.common_id": common_id,
1280 },
1281 update_dict={"to_check_at": now, "modified_at": now},
1282 push={"tasks": db_task},
1283 fail_on_empty=False,
1284 ):
1285 continue
1286
1287 if not self.db.set_one(
1288 "ro_tasks",
1289 q_filter={
1290 "target_id": target_id,
1291 "tasks.target_record": db_task["target_record"],
1292 },
1293 update_dict={"to_check_at": now, "modified_at": now},
1294 push={"tasks": db_task},
1295 fail_on_empty=False,
1296 ):
1297 # Create a ro_task
1298 step = "Updating database, Creating ro_tasks"
1299 db_ro_task = Ns._create_ro_task(target_id, db_task)
1300 nb_ro_tasks += 1
1301 self.db.create("ro_tasks", db_ro_task)
1302
1303 step = "Updating database, nsrs"
1304 if db_nsr_update:
1305 self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
1306
1307 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
1308 if db_vnfr_update:
1309 step = "Updating database, vnfrs={}".format(vnfr_id)
1310 self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
1311
1312 self.logger.debug(
1313 logging_text
1314 + "Exit. Created {} ro_tasks; {} tasks".format(
1315 nb_ro_tasks, len(db_new_tasks)
1316 )
1317 )
1318
1319 return (
1320 {"status": "ok", "nsr_id": nsr_id, "action_id": action_id},
1321 action_id,
1322 True,
1323 )
1324 except Exception as e:
1325 if isinstance(e, (DbException, NsException)):
1326 self.logger.error(
1327 logging_text + "Exit Exception while '{}': {}".format(step, e)
1328 )
1329 else:
1330 e = traceback_format_exc()
1331 self.logger.critical(
1332 logging_text + "Exit Exception while '{}': {}".format(step, e),
1333 exc_info=True,
1334 )
1335
1336 raise NsException(e)
1337
1338 def delete(self, session, indata, version, nsr_id, *args, **kwargs):
1339 self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
1340 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
1341
1342 with self.write_lock:
1343 try:
1344 NsWorker.delete_db_tasks(self.db, nsr_id, None)
1345 except NsWorkerException as e:
1346 raise NsException(e)
1347
1348 return None, None, True
1349
1350 def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1351 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
1352 # .format(version, nsr_id, action_id, indata))
1353 task_list = []
1354 done = 0
1355 total = 0
1356 ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
1357 global_status = "DONE"
1358 details = []
1359
1360 for ro_task in ro_tasks:
1361 for task in ro_task["tasks"]:
1362 if task and task["action_id"] == action_id:
1363 task_list.append(task)
1364 total += 1
1365
1366 if task["status"] == "FAILED":
1367 global_status = "FAILED"
1368 error_text = "Error at {} {}: {}".format(
1369 task["action"].lower(),
1370 task["item"],
1371 ro_task["vim_info"].get("vim_details") or "unknown",
1372 )
1373 details.append(error_text)
1374 elif task["status"] in ("SCHEDULED", "BUILD"):
1375 if global_status != "FAILED":
1376 global_status = "BUILD"
1377 else:
1378 done += 1
1379
1380 return_data = {
1381 "status": global_status,
1382 "details": ". ".join(details)
1383 if details
1384 else "progress {}/{}".format(done, total),
1385 "nsr_id": nsr_id,
1386 "action_id": action_id,
1387 "tasks": task_list,
1388 }
1389
1390 return return_data, None, True
1391
1392 def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1393 print(
1394 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
1395 session, indata, version, nsr_id, action_id
1396 )
1397 )
1398
1399 return None, None, True
1400
1401 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1402 nsrs = self.db.get_list("nsrs", {})
1403 return_data = []
1404
1405 for ns in nsrs:
1406 return_data.append({"_id": ns["_id"], "name": ns["name"]})
1407
1408 return return_data, None, True
1409
1410 def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
1411 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
1412 return_data = []
1413
1414 for ro_task in ro_tasks:
1415 for task in ro_task["tasks"]:
1416 if task["action_id"] not in return_data:
1417 return_data.append(task["action_id"])
1418
1419 return return_data, None, True