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