a9c5ec0a894c231af940147767fde4fe265698d3
[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 logging
20 # import yaml
21 from traceback import format_exc as traceback_format_exc
22 from osm_ng_ro.ns_thread import NsWorker, NsWorkerException, deep_get
23 from osm_ng_ro.validation import validate_input, deploy_schema
24 from osm_common import dbmongo, dbmemory, fslocal, fsmongo, msglocal, msgkafka, version as common_version
25 from osm_common.dbbase import DbException
26 from osm_common.fsbase import FsException
27 from osm_common.msgbase import MsgException
28 from http import HTTPStatus
29 from uuid import uuid4
30 from threading import Lock
31 from random import choice as random_choice
32 from time import time
33 from jinja2 import Environment, TemplateError, TemplateNotFound, StrictUndefined, UndefinedError
34 from cryptography.hazmat.primitives import serialization as crypto_serialization
35 from cryptography.hazmat.primitives.asymmetric import rsa
36 from cryptography.hazmat.backends import default_backend as crypto_default_backend
37
38 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
39 min_common_version = "0.1.16"
40
41
42 class NsException(Exception):
43
44 def __init__(self, message, http_code=HTTPStatus.BAD_REQUEST):
45 self.http_code = http_code
46 super(Exception, self).__init__(message)
47
48
49 def get_process_id():
50 """
51 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
52 will provide a random one
53 :return: Obtained ID
54 """
55 # Try getting docker id. If fails, get pid
56 try:
57 with open("/proc/self/cgroup", "r") as f:
58 text_id_ = f.readline()
59 _, _, text_id = text_id_.rpartition("/")
60 text_id = text_id.replace("\n", "")[:12]
61 if text_id:
62 return text_id
63 except Exception:
64 pass
65 # Return a random id
66 return "".join(random_choice("0123456789abcdef") for _ in range(12))
67
68
69 def versiontuple(v):
70 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
71 filled = []
72 for point in v.split("."):
73 filled.append(point.zfill(8))
74 return tuple(filled)
75
76
77 class Ns(object):
78
79 def __init__(self):
80 self.db = None
81 self.fs = None
82 self.msg = None
83 self.config = None
84 # self.operations = None
85 self.logger = None
86 # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
87 # If done now it will not be linked to parent not getting its handler and level
88 self.map_topic = {}
89 self.write_lock = None
90 self.assignment = {}
91 self.assignment_list = []
92 self.next_worker = 0
93 self.plugins = {}
94 self.workers = []
95
96 def init_db(self, target_version):
97 pass
98
99 def start(self, config):
100 """
101 Connect to database, filesystem storage, and messaging
102 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
103 :param config: Configuration of db, storage, etc
104 :return: None
105 """
106 self.config = config
107 self.config["process_id"] = get_process_id() # used for HA identity
108 self.logger = logging.getLogger("ro.ns")
109 # check right version of common
110 if versiontuple(common_version) < versiontuple(min_common_version):
111 raise NsException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
112 common_version, min_common_version))
113
114 try:
115 if not self.db:
116 if config["database"]["driver"] == "mongo":
117 self.db = dbmongo.DbMongo()
118 self.db.db_connect(config["database"])
119 elif config["database"]["driver"] == "memory":
120 self.db = dbmemory.DbMemory()
121 self.db.db_connect(config["database"])
122 else:
123 raise NsException("Invalid configuration param '{}' at '[database]':'driver'".format(
124 config["database"]["driver"]))
125 if not self.fs:
126 if config["storage"]["driver"] == "local":
127 self.fs = fslocal.FsLocal()
128 self.fs.fs_connect(config["storage"])
129 elif config["storage"]["driver"] == "mongo":
130 self.fs = fsmongo.FsMongo()
131 self.fs.fs_connect(config["storage"])
132 elif config["storage"]["driver"] is None:
133 pass
134 else:
135 raise NsException("Invalid configuration param '{}' at '[storage]':'driver'".format(
136 config["storage"]["driver"]))
137 if not self.msg:
138 if config["message"]["driver"] == "local":
139 self.msg = msglocal.MsgLocal()
140 self.msg.connect(config["message"])
141 elif config["message"]["driver"] == "kafka":
142 self.msg = msgkafka.MsgKafka()
143 self.msg.connect(config["message"])
144 else:
145 raise NsException("Invalid configuration param '{}' at '[message]':'driver'".format(
146 config["message"]["driver"]))
147
148 # TODO load workers to deal with exising database tasks
149
150 self.write_lock = Lock()
151 except (DbException, FsException, MsgException) as e:
152 raise NsException(str(e), http_code=e.http_code)
153
154 def stop(self):
155 try:
156 if self.db:
157 self.db.db_disconnect()
158 if self.fs:
159 self.fs.fs_disconnect()
160 if self.msg:
161 self.msg.disconnect()
162 self.write_lock = None
163 except (DbException, FsException, MsgException) as e:
164 raise NsException(str(e), http_code=e.http_code)
165 for worker in self.workers:
166 worker.insert_task(("terminate",))
167
168 def _create_worker(self, target_id, load=True):
169 # Look for a thread not alive
170 worker_id = next((i for i in range(len(self.workers)) if not self.workers[i].is_alive()), None)
171 if worker_id:
172 # re-start worker
173 self.workers[worker_id].start()
174 else:
175 worker_id = len(self.workers)
176 if worker_id < self.config["global"]["server.ns_threads"]:
177 # create a new worker
178 self.workers.append(NsWorker(worker_id, self.config, self.plugins, self.db))
179 self.workers[worker_id].start()
180 else:
181 # reached maximum number of threads, assign VIM to an existing one
182 worker_id = self.next_worker
183 self.next_worker = (self.next_worker + 1) % self.config["global"]["server.ns_threads"]
184 if load:
185 self.workers[worker_id].insert_task(("load_vim", target_id))
186 return worker_id
187
188 def assign_vim(self, target_id):
189 if target_id not in self.assignment:
190 self.assignment[target_id] = self._create_worker(target_id)
191 self.assignment_list.append(target_id)
192
193 def reload_vim(self, target_id):
194 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
195 # this is because database VIM information is cached for threads working with SDN
196 # if target_id in self.assignment:
197 # worker_id = self.assignment[target_id]
198 # self.workers[worker_id].insert_task(("reload_vim", target_id))
199 for worker in self.workers:
200 if worker.is_alive():
201 worker.insert_task(("reload_vim", target_id))
202
203 def unload_vim(self, target_id):
204 if target_id in self.assignment:
205 worker_id = self.assignment[target_id]
206 self.workers[worker_id].insert_task(("unload_vim", target_id))
207 del self.assignment[target_id]
208 self.assignment_list.remove(target_id)
209
210 def check_vim(self, target_id):
211 if target_id in self.assignment:
212 worker_id = self.assignment[target_id]
213 else:
214 worker_id = self._create_worker(target_id, load=False)
215
216 worker = self.workers[worker_id]
217 worker.insert_task(("check_vim", target_id))
218
219 def _get_cloud_init(self, where):
220 """
221
222 :param where: can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
223 :return:
224 """
225 vnfd_id, _, other = where.partition(":")
226 _type, _, name = other.partition(":")
227 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
228 if _type == "file":
229 base_folder = vnfd["_admin"]["storage"]
230 cloud_init_file = "{}/{}/cloud_init/{}".format(base_folder["folder"], base_folder["pkg-dir"], name)
231 if not self.fs:
232 raise NsException("Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver"
233 .format(cloud_init_file))
234 with self.fs.file_open(cloud_init_file, "r") as ci_file:
235 cloud_init_content = ci_file.read()
236 elif _type == "vdu":
237 cloud_init_content = vnfd["vdu"][int(name)]["cloud-init"]
238 else:
239 raise NsException("Mismatch descriptor for cloud init: {}".format(where))
240 return cloud_init_content
241
242 def _parse_jinja2(self, cloud_init_content, params, context):
243
244 try:
245 env = Environment(undefined=StrictUndefined)
246 template = env.from_string(cloud_init_content)
247 return template.render(params or {})
248 except UndefinedError as e:
249 raise NsException(
250 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
251 "inside the 'additionalParamsForVnf' block".format(e, context))
252 except (TemplateError, TemplateNotFound) as e:
253 raise NsException("Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(context, e))
254
255 def _create_db_ro_nsrs(self, nsr_id, now):
256 try:
257 key = rsa.generate_private_key(
258 backend=crypto_default_backend(),
259 public_exponent=65537,
260 key_size=2048
261 )
262 private_key = key.private_bytes(
263 crypto_serialization.Encoding.PEM,
264 crypto_serialization.PrivateFormat.PKCS8,
265 crypto_serialization.NoEncryption())
266 public_key = key.public_key().public_bytes(
267 crypto_serialization.Encoding.OpenSSH,
268 crypto_serialization.PublicFormat.OpenSSH
269 )
270 private_key = private_key.decode('utf8')
271 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
272 i = private_key.find("\n")
273 private_key = "-----BEGIN RSA PRIVATE KEY-----" + private_key[i:]
274 public_key = public_key.decode('utf8')
275 except Exception as e:
276 raise NsException("Cannot create ssh-keys: {}".format(e))
277
278 schema_version = "1.1"
279 private_key_encrypted = self.db.encrypt(private_key, schema_version=schema_version, salt=nsr_id)
280 db_content = {
281 "_id": nsr_id,
282 "_admin": {
283 "created": now,
284 "modified": now,
285 "schema_version": schema_version
286 },
287 "public_key": public_key,
288 "private_key": private_key_encrypted,
289 "actions": [],
290 }
291 self.db.create("ro_nsrs", db_content)
292 return db_content
293
294 def deploy(self, session, indata, version, nsr_id, *args, **kwargs):
295 self.logger.debug("ns.deploy nsr_id={} indata={}".format(nsr_id, indata))
296 validate_input(indata, deploy_schema)
297 action_id = indata.get("action_id", str(uuid4()))
298 task_index = 0
299 # get current deployment
300 db_nsr_update = {} # update operation on nsrs
301 db_vnfrs_update = {}
302 db_vnfrs = {} # vnf's info indexed by _id
303 nb_ro_tasks = 0 # for logging
304 vdu2cloud_init = indata.get("cloud_init_content") or {}
305 step = ''
306 logging_text = "Task deploy nsr_id={} action_id={} ".format(nsr_id, action_id)
307 self.logger.debug(logging_text + "Enter")
308 try:
309 step = "Getting ns and vnfr record from db"
310 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
311 db_new_tasks = []
312 tasks_by_target_record_id = {}
313 # read from db: vnf's of this ns
314 step = "Getting vnfrs from db"
315 db_vnfrs_list = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
316 if not db_vnfrs_list:
317 raise NsException("Cannot obtain associated VNF for ns")
318 for vnfr in db_vnfrs_list:
319 db_vnfrs[vnfr["_id"]] = vnfr
320 db_vnfrs_update[vnfr["_id"]] = {}
321 now = time()
322 db_ro_nsr = self.db.get_one("ro_nsrs", {"_id": nsr_id}, fail_on_empty=False)
323 if not db_ro_nsr:
324 db_ro_nsr = self._create_db_ro_nsrs(nsr_id, now)
325 ro_nsr_public_key = db_ro_nsr["public_key"]
326
327 # check that action_id is not in the list of actions. Suffixed with :index
328 if action_id in db_ro_nsr["actions"]:
329 index = 1
330 while True:
331 new_action_id = "{}:{}".format(action_id, index)
332 if new_action_id not in db_ro_nsr["actions"]:
333 action_id = new_action_id
334 self.logger.debug(logging_text + "Changing action_id in use to {}".format(action_id))
335 break
336 index += 1
337
338 def _create_task(target_id, item, action, target_record, target_record_id, extra_dict=None):
339 nonlocal task_index
340 nonlocal action_id
341 nonlocal nsr_id
342
343 task = {
344 "target_id": target_id, # it will be removed before pushing at database
345 "action_id": action_id,
346 "nsr_id": nsr_id,
347 "task_id": "{}:{}".format(action_id, task_index),
348 "status": "SCHEDULED",
349 "action": action,
350 "item": item,
351 "target_record": target_record,
352 "target_record_id": target_record_id,
353 }
354 if extra_dict:
355 task.update(extra_dict) # params, find_params, depends_on
356 task_index += 1
357 return task
358
359 def _create_ro_task(target_id, task):
360 nonlocal action_id
361 nonlocal task_index
362 nonlocal now
363
364 _id = task["task_id"]
365 db_ro_task = {
366 "_id": _id,
367 "locked_by": None,
368 "locked_at": 0.0,
369 "target_id": target_id,
370 "vim_info": {
371 "created": False,
372 "created_items": None,
373 "vim_id": None,
374 "vim_name": None,
375 "vim_status": None,
376 "vim_details": None,
377 "refresh_at": None,
378 },
379 "modified_at": now,
380 "created_at": now,
381 "to_check_at": now,
382 "tasks": [task],
383 }
384 return db_ro_task
385
386 def _process_image_params(target_image, vim_info, target_record_id):
387 find_params = {}
388 if target_image.get("image"):
389 find_params["filter_dict"] = {"name": target_image.get("image")}
390 if target_image.get("vim_image_id"):
391 find_params["filter_dict"] = {"id": target_image.get("vim_image_id")}
392 if target_image.get("image_checksum"):
393 find_params["filter_dict"] = {"checksum": target_image.get("image_checksum")}
394 return {"find_params": find_params}
395
396 def _process_flavor_params(target_flavor, vim_info, target_record_id):
397
398 def _get_resource_allocation_params(quota_descriptor):
399 """
400 read the quota_descriptor from vnfd and fetch the resource allocation properties from the
401 descriptor object
402 :param quota_descriptor: cpu/mem/vif/disk-io quota descriptor
403 :return: quota params for limit, reserve, shares from the descriptor object
404 """
405 quota = {}
406 if quota_descriptor.get("limit"):
407 quota["limit"] = int(quota_descriptor["limit"])
408 if quota_descriptor.get("reserve"):
409 quota["reserve"] = int(quota_descriptor["reserve"])
410 if quota_descriptor.get("shares"):
411 quota["shares"] = int(quota_descriptor["shares"])
412 return quota
413
414 flavor_data = {
415 "disk": int(target_flavor["storage-gb"]),
416 # "ram": max(int(target_flavor["memory-mb"]) // 1024, 1),
417 # ^ TODO manage at vim_connectors MB instead of GB
418 "ram": int(target_flavor["memory-mb"]),
419 "vcpus": target_flavor["vcpu-count"],
420 }
421 numa = {}
422 extended = {}
423 if target_flavor.get("guest-epa"):
424 extended = {}
425 epa_vcpu_set = False
426 if target_flavor["guest-epa"].get("numa-node-policy"):
427 numa_node_policy = target_flavor["guest-epa"].get("numa-node-policy")
428 if numa_node_policy.get("node"):
429 numa_node = numa_node_policy["node"][0]
430 if numa_node.get("num-cores"):
431 numa["cores"] = numa_node["num-cores"]
432 epa_vcpu_set = True
433 if numa_node.get("paired-threads"):
434 if numa_node["paired-threads"].get("num-paired-threads"):
435 numa["paired-threads"] = int(numa_node["paired-threads"]["num-paired-threads"])
436 epa_vcpu_set = True
437 if len(numa_node["paired-threads"].get("paired-thread-ids")):
438 numa["paired-threads-id"] = []
439 for pair in numa_node["paired-threads"]["paired-thread-ids"]:
440 numa["paired-threads-id"].append(
441 (str(pair["thread-a"]), str(pair["thread-b"]))
442 )
443 if numa_node.get("num-threads"):
444 numa["threads"] = int(numa_node["num-threads"])
445 epa_vcpu_set = True
446 if numa_node.get("memory-mb"):
447 numa["memory"] = max(int(numa_node["memory-mb"] / 1024), 1)
448 if target_flavor["guest-epa"].get("mempage-size"):
449 extended["mempage-size"] = target_flavor["guest-epa"].get("mempage-size")
450 if target_flavor["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set:
451 if target_flavor["guest-epa"]["cpu-pinning-policy"] == "DEDICATED":
452 if target_flavor["guest-epa"].get("cpu-thread-pinning-policy") and \
453 target_flavor["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER":
454 numa["cores"] = max(flavor_data["vcpus"], 1)
455 else:
456 numa["threads"] = max(flavor_data["vcpus"], 1)
457 epa_vcpu_set = True
458 if target_flavor["guest-epa"].get("cpu-quota") and not epa_vcpu_set:
459 cpuquota = _get_resource_allocation_params(target_flavor["guest-epa"].get("cpu-quota"))
460 if cpuquota:
461 extended["cpu-quota"] = cpuquota
462 if target_flavor["guest-epa"].get("mem-quota"):
463 vduquota = _get_resource_allocation_params(target_flavor["guest-epa"].get("mem-quota"))
464 if vduquota:
465 extended["mem-quota"] = vduquota
466 if target_flavor["guest-epa"].get("disk-io-quota"):
467 diskioquota = _get_resource_allocation_params(target_flavor["guest-epa"].get("disk-io-quota"))
468 if diskioquota:
469 extended["disk-io-quota"] = diskioquota
470 if target_flavor["guest-epa"].get("vif-quota"):
471 vifquota = _get_resource_allocation_params(target_flavor["guest-epa"].get("vif-quota"))
472 if vifquota:
473 extended["vif-quota"] = vifquota
474 if numa:
475 extended["numas"] = [numa]
476 if extended:
477 flavor_data["extended"] = extended
478
479 extra_dict = {"find_params": {"flavor_data": flavor_data}}
480 flavor_data_name = flavor_data.copy()
481 flavor_data_name["name"] = target_flavor["name"]
482 extra_dict["params"] = {"flavor_data": flavor_data_name}
483 return extra_dict
484
485 def _ip_profile_2_ro(ip_profile):
486 if not ip_profile:
487 return None
488 ro_ip_profile = {
489 "ip_version": "IPv4" if "v4" in ip_profile.get("ip-version", "ipv4") else "IPv6",
490 "subnet_address": ip_profile.get("subnet-address"),
491 "gateway_address": ip_profile.get("gateway-address"),
492 "dhcp_enabled": ip_profile["dhcp-params"].get("enabled", True),
493 "dhcp_start_address": ip_profile["dhcp-params"].get("start-address"),
494 "dhcp_count": ip_profile["dhcp-params"].get("count"),
495
496 }
497 if ip_profile.get("dns-server"):
498 ro_ip_profile["dns_address"] = ";".join([v["address"] for v in ip_profile["dns-server"]])
499 if ip_profile.get('security-group'):
500 ro_ip_profile["security_group"] = ip_profile['security-group']
501 return ro_ip_profile
502
503 def _process_net_params(target_vld, vim_info, target_record_id):
504 nonlocal indata
505 extra_dict = {}
506
507 if vim_info.get("sdn"):
508 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
509 # ns_preffix = "nsrs:{}".format(nsr_id)
510 vld_target_record_id, _, _ = target_record_id.rpartition(".") # remove the ending ".sdn
511 extra_dict["params"] = {k: vim_info[k] for k in ("sdn-ports", "target_vim", "vlds", "type")
512 if vim_info.get(k)}
513 # TODO needed to add target_id in the dependency.
514 if vim_info.get("target_vim"):
515 extra_dict["depends_on"] = [vim_info.get("target_vim") + " " + vld_target_record_id]
516 return extra_dict
517
518 if vim_info.get("vim_network_name"):
519 extra_dict["find_params"] = {"filter_dict": {"name": vim_info.get("vim_network_name")}}
520 elif vim_info.get("vim_network_id"):
521 extra_dict["find_params"] = {"filter_dict": {"id": vim_info.get("vim_network_id")}}
522 elif target_vld.get("mgmt-network"):
523 extra_dict["find_params"] = {"mgmt": True, "name": target_vld["id"]}
524 else:
525 # create
526 extra_dict["params"] = {
527 "net_name": "{}-{}".format(indata["name"][:16], target_vld.get("name", target_vld["id"])[:16]),
528 "ip_profile": _ip_profile_2_ro(vim_info.get('ip_profile')),
529 "provider_network_profile": vim_info.get('provider_network'),
530 }
531 if not target_vld.get("underlay"):
532 extra_dict["params"]["net_type"] = "bridge"
533 else:
534 extra_dict["params"]["net_type"] = "ptp" if target_vld.get("type") == "ELINE" else "data"
535 return extra_dict
536
537 def _process_vdu_params(target_vdu, vim_info, target_record_id):
538 nonlocal vnfr_id
539 nonlocal nsr_id
540 nonlocal indata
541 nonlocal vnfr
542 nonlocal vdu2cloud_init
543 nonlocal tasks_by_target_record_id
544 vnf_preffix = "vnfrs:{}".format(vnfr_id)
545 ns_preffix = "nsrs:{}".format(nsr_id)
546 image_text = ns_preffix + ":image." + target_vdu["ns-image-id"]
547 flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"]
548 extra_dict = {"depends_on": [image_text, flavor_text]}
549 net_list = []
550 for iface_index, interface in enumerate(target_vdu["interfaces"]):
551 if interface.get("ns-vld-id"):
552 net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
553 else:
554 net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
555 extra_dict["depends_on"].append(net_text)
556 net_item = {x: v for x, v in interface.items() if x in
557 ("name", "vpci", "port_security", "port_security_disable_strategy", "floating_ip")}
558 net_item["net_id"] = "TASK-" + net_text
559 net_item["type"] = "virtual"
560 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
561 # TODO floating_ip: True/False (or it can be None)
562 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
563 # mark the net create task as type data
564 if deep_get(tasks_by_target_record_id, net_text, "params", "net_type"):
565 tasks_by_target_record_id[net_text]["params"]["net_type"] = "data"
566 net_item["use"] = "data"
567 net_item["model"] = interface["type"]
568 net_item["type"] = interface["type"]
569 elif interface.get("type") == "OM-MGMT" or interface.get("mgmt-interface") or \
570 interface.get("mgmt-vnf"):
571 net_item["use"] = "mgmt"
572 else: # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
573 net_item["use"] = "bridge"
574 net_item["model"] = interface.get("type")
575 if interface.get("ip-address"):
576 net_item["ip_address"] = interface["ip-address"]
577 if interface.get("mac-address"):
578 net_item["mac_address"] = interface["mac-address"]
579 net_list.append(net_item)
580 if interface.get("mgmt-vnf"):
581 extra_dict["mgmt_vnf_interface"] = iface_index
582 elif interface.get("mgmt-interface"):
583 extra_dict["mgmt_vdu_interface"] = iface_index
584 # cloud config
585 cloud_config = {}
586 if target_vdu.get("cloud-init"):
587 if target_vdu["cloud-init"] not in vdu2cloud_init:
588 vdu2cloud_init[target_vdu["cloud-init"]] = self._get_cloud_init(target_vdu["cloud-init"])
589 cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
590 cloud_config["user-data"] = self._parse_jinja2(cloud_content_, target_vdu.get("additionalParams"),
591 target_vdu["cloud-init"])
592 if target_vdu.get("boot-data-drive"):
593 cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
594 ssh_keys = []
595 if target_vdu.get("ssh-keys"):
596 ssh_keys += target_vdu.get("ssh-keys")
597 if target_vdu.get("ssh-access-required"):
598 ssh_keys.append(ro_nsr_public_key)
599 if ssh_keys:
600 cloud_config["key-pairs"] = ssh_keys
601
602 extra_dict["params"] = {
603 "name": "{}-{}-{}-{}".format(indata["name"][:16], vnfr["member-vnf-index-ref"][:16],
604 target_vdu["vdu-name"][:32], target_vdu.get("count-index") or 0),
605 "description": target_vdu["vdu-name"],
606 "start": True,
607 "image_id": "TASK-" + image_text,
608 "flavor_id": "TASK-" + flavor_text,
609 "net_list": net_list,
610 "cloud_config": cloud_config or None,
611 "disk_list": None, # TODO
612 "availability_zone_index": None, # TODO
613 "availability_zone_list": None, # TODO
614 }
615 return extra_dict
616
617 def _process_items(target_list, existing_list, db_record, db_update, db_path, item, process_params):
618 nonlocal db_new_tasks
619 nonlocal tasks_by_target_record_id
620 nonlocal task_index
621
622 # ensure all the target_list elements has an "id". If not assign the index as id
623 for target_index, tl in enumerate(target_list):
624 if tl and not tl.get("id"):
625 tl["id"] = str(target_index)
626
627 # step 1 items (networks,vdus,...) to be deleted/updated
628 for item_index, existing_item in enumerate(existing_list):
629 target_item = next((t for t in target_list if t["id"] == existing_item["id"]), None)
630 for target_vim, existing_viminfo in existing_item.get("vim_info", {}).items():
631 if existing_viminfo is None:
632 continue
633 if target_item:
634 target_viminfo = target_item.get("vim_info", {}).get(target_vim)
635 else:
636 target_viminfo = None
637 if target_viminfo is None:
638 # must be deleted
639 self.assign_vim(target_vim)
640 target_record_id = "{}.{}".format(db_record, existing_item["id"])
641 item_ = item
642 if target_vim.startswith("sdn"):
643 # item must be sdn-net instead of net if target_vim is a sdn
644 item_ = "sdn_net"
645 target_record_id += ".sdn"
646 task = _create_task(
647 target_vim, item_, "DELETE",
648 target_record="{}.{}.vim_info.{}".format(db_record, item_index, target_vim),
649 target_record_id=target_record_id)
650 tasks_by_target_record_id[target_record_id] = task
651 db_new_tasks.append(task)
652 # TODO delete
653 # TODO check one by one the vims to be created/deleted
654
655 # step 2 items (networks,vdus,...) to be created
656 for target_item in target_list:
657 item_index = -1
658 for item_index, existing_item in enumerate(existing_list):
659 if existing_item["id"] == target_item["id"]:
660 break
661 else:
662 item_index += 1
663 db_update[db_path + ".{}".format(item_index)] = target_item
664 existing_list.append(target_item)
665 existing_item = None
666
667 for target_vim, target_viminfo in target_item.get("vim_info", {}).items():
668 existing_viminfo = None
669 if existing_item:
670 existing_viminfo = existing_item.get("vim_info", {}).get(target_vim)
671 # TODO check if different. Delete and create???
672 # TODO delete if not exist
673 if existing_viminfo is not None:
674 continue
675
676 target_record_id = "{}.{}".format(db_record, target_item["id"])
677 item_ = item
678 if target_vim.startswith("sdn"):
679 # item must be sdn-net instead of net if target_vim is a sdn
680 item_ = "sdn_net"
681 target_record_id += ".sdn"
682 extra_dict = process_params(target_item, target_viminfo, target_record_id)
683
684 self.assign_vim(target_vim)
685 task = _create_task(
686 target_vim, item_, "CREATE",
687 target_record="{}.{}.vim_info.{}".format(db_record, item_index, target_vim),
688 target_record_id=target_record_id,
689 extra_dict=extra_dict)
690 tasks_by_target_record_id[target_record_id] = task
691 db_new_tasks.append(task)
692 if target_item.get("common_id"):
693 task["common_id"] = target_item["common_id"]
694
695 db_update[db_path + ".{}".format(item_index)] = target_item
696
697 def _process_action(indata):
698 nonlocal db_new_tasks
699 nonlocal task_index
700 nonlocal db_vnfrs
701 nonlocal db_ro_nsr
702
703 if indata["action"]["action"] == "inject_ssh_key":
704 key = indata["action"].get("key")
705 user = indata["action"].get("user")
706 password = indata["action"].get("password")
707 for vnf in indata.get("vnf", ()):
708 if vnf["_id"] not in db_vnfrs:
709 raise NsException("Invalid vnf={}".format(vnf["_id"]))
710 db_vnfr = db_vnfrs[vnf["_id"]]
711 for target_vdu in vnf.get("vdur", ()):
712 vdu_index, vdur = next((i_v for i_v in enumerate(db_vnfr["vdur"]) if
713 i_v[1]["id"] == target_vdu["id"]), (None, None))
714 if not vdur:
715 raise NsException("Invalid vdu vnf={}.{}".format(vnf["_id"], target_vdu["id"]))
716 target_vim, vim_info = next(k_v for k_v in vdur["vim_info"].items())
717 self.assign_vim(target_vim)
718 target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(vnf["_id"], vdu_index)
719 extra_dict = {
720 "depends_on": ["vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])],
721 "params": {
722 "ip_address": vdur.get("ip-address"),
723 "user": user,
724 "key": key,
725 "password": password,
726 "private_key": db_ro_nsr["private_key"],
727 "salt": db_ro_nsr["_id"],
728 "schema_version": db_ro_nsr["_admin"]["schema_version"]
729 }
730 }
731 task = _create_task(target_vim, "vdu", "EXEC",
732 target_record=target_record,
733 target_record_id=None,
734 extra_dict=extra_dict)
735 db_new_tasks.append(task)
736
737 with self.write_lock:
738 if indata.get("action"):
739 _process_action(indata)
740 else:
741 # compute network differences
742 # NS.vld
743 step = "process NS VLDs"
744 _process_items(target_list=indata["ns"]["vld"] or [], existing_list=db_nsr.get("vld") or [],
745 db_record="nsrs:{}:vld".format(nsr_id), db_update=db_nsr_update,
746 db_path="vld", item="net", process_params=_process_net_params)
747
748 step = "process NS images"
749 _process_items(target_list=indata.get("image") or [], existing_list=db_nsr.get("image") or [],
750 db_record="nsrs:{}:image".format(nsr_id),
751 db_update=db_nsr_update, db_path="image", item="image",
752 process_params=_process_image_params)
753
754 step = "process NS flavors"
755 _process_items(target_list=indata.get("flavor") or [], existing_list=db_nsr.get("flavor") or [],
756 db_record="nsrs:{}:flavor".format(nsr_id),
757 db_update=db_nsr_update, db_path="flavor", item="flavor",
758 process_params=_process_flavor_params)
759
760 # VNF.vld
761 for vnfr_id, vnfr in db_vnfrs.items():
762 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
763 step = "process VNF={} VLDs".format(vnfr_id)
764 target_vnf = next((vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id), None)
765 target_list = target_vnf.get("vld") if target_vnf else None
766 _process_items(target_list=target_list or [], existing_list=vnfr.get("vld") or [],
767 db_record="vnfrs:{}:vld".format(vnfr_id), db_update=db_vnfrs_update[vnfr["_id"]],
768 db_path="vld", item="net", process_params=_process_net_params)
769
770 target_list = target_vnf.get("vdur") if target_vnf else None
771 step = "process VNF={} VDUs".format(vnfr_id)
772 _process_items(target_list=target_list or [], existing_list=vnfr.get("vdur") or [],
773 db_record="vnfrs:{}:vdur".format(vnfr_id),
774 db_update=db_vnfrs_update[vnfr["_id"]], db_path="vdur", item="vdu",
775 process_params=_process_vdu_params)
776
777 for db_task in db_new_tasks:
778 step = "Updating database, Appending tasks to ro_tasks"
779 target_id = db_task.pop("target_id")
780 common_id = db_task.get("common_id")
781 if common_id:
782 if self.db.set_one("ro_tasks",
783 q_filter={"target_id": target_id,
784 "tasks.common_id": common_id},
785 update_dict={"to_check_at": now, "modified_at": now},
786 push={"tasks": db_task}, fail_on_empty=False):
787 continue
788 if not self.db.set_one("ro_tasks",
789 q_filter={"target_id": target_id,
790 "tasks.target_record": db_task["target_record"]},
791 update_dict={"to_check_at": now, "modified_at": now},
792 push={"tasks": db_task}, fail_on_empty=False):
793 # Create a ro_task
794 step = "Updating database, Creating ro_tasks"
795 db_ro_task = _create_ro_task(target_id, db_task)
796 nb_ro_tasks += 1
797 self.db.create("ro_tasks", db_ro_task)
798 step = "Updating database, nsrs"
799 if db_nsr_update:
800 self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
801 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
802 if db_vnfr_update:
803 step = "Updating database, vnfrs={}".format(vnfr_id)
804 self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
805
806 self.logger.debug(logging_text + "Exit. Created {} ro_tasks; {} tasks".format(nb_ro_tasks,
807 len(db_new_tasks)))
808 return {"status": "ok", "nsr_id": nsr_id, "action_id": action_id}, action_id, True
809
810 except Exception as e:
811 if isinstance(e, (DbException, NsException)):
812 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
813 else:
814 e = traceback_format_exc()
815 self.logger.critical(logging_text + "Exit Exception while '{}': {}".format(step, e), exc_info=True)
816 raise NsException(e)
817
818 def delete(self, session, indata, version, nsr_id, *args, **kwargs):
819 self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
820 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
821 with self.write_lock:
822 try:
823 NsWorker.delete_db_tasks(self.db, nsr_id, None)
824 except NsWorkerException as e:
825 raise NsException(e)
826 return None, None, True
827
828 def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
829 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
830 # .format(version, nsr_id, action_id, indata))
831 task_list = []
832 done = 0
833 total = 0
834 ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
835 global_status = "DONE"
836 details = []
837 for ro_task in ro_tasks:
838 for task in ro_task["tasks"]:
839 if task and task["action_id"] == action_id:
840 task_list.append(task)
841 total += 1
842 if task["status"] == "FAILED":
843 global_status = "FAILED"
844 error_text = "Error at {} {}: {}".format(task["action"].lower(), task["item"],
845 ro_task["vim_info"].get("vim_details") or "unknown")
846 details.append(error_text)
847 elif task["status"] in ("SCHEDULED", "BUILD"):
848 if global_status != "FAILED":
849 global_status = "BUILD"
850 else:
851 done += 1
852 return_data = {
853 "status": global_status,
854 "details": ". ".join(details) if details else "progress {}/{}".format(done, total),
855 "nsr_id": nsr_id,
856 "action_id": action_id,
857 "tasks": task_list
858 }
859 return return_data, None, True
860
861 def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
862 print("ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(session, indata, version,
863 nsr_id, action_id))
864 return None, None, True
865
866 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
867 nsrs = self.db.get_list("nsrs", {})
868 return_data = []
869 for ns in nsrs:
870 return_data.append({"_id": ns["_id"], "name": ns["name"]})
871 return return_data, None, True
872
873 def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
874 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
875 return_data = []
876 for ro_task in ro_tasks:
877 for task in ro_task["tasks"]:
878 if task["action_id"] not in return_data:
879 return_data.append(task["action_id"])
880 return return_data, None, True