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