fix error on task_depends not defined
[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": int(target_flavor["memory-mb"]),
417 "vcpus": int(target_flavor["vcpu-count"]),
418 }
419 numa = {}
420 extended = {}
421 if target_flavor.get("guest-epa"):
422 extended = {}
423 epa_vcpu_set = False
424 if target_flavor["guest-epa"].get("numa-node-policy"):
425 numa_node_policy = target_flavor["guest-epa"].get("numa-node-policy")
426 if numa_node_policy.get("node"):
427 numa_node = numa_node_policy["node"][0]
428 if numa_node.get("num-cores"):
429 numa["cores"] = numa_node["num-cores"]
430 epa_vcpu_set = True
431 if numa_node.get("paired-threads"):
432 if numa_node["paired-threads"].get("num-paired-threads"):
433 numa["paired-threads"] = int(numa_node["paired-threads"]["num-paired-threads"])
434 epa_vcpu_set = True
435 if len(numa_node["paired-threads"].get("paired-thread-ids")):
436 numa["paired-threads-id"] = []
437 for pair in numa_node["paired-threads"]["paired-thread-ids"]:
438 numa["paired-threads-id"].append(
439 (str(pair["thread-a"]), str(pair["thread-b"]))
440 )
441 if numa_node.get("num-threads"):
442 numa["threads"] = int(numa_node["num-threads"])
443 epa_vcpu_set = True
444 if numa_node.get("memory-mb"):
445 numa["memory"] = max(int(numa_node["memory-mb"] / 1024), 1)
446 if target_flavor["guest-epa"].get("mempage-size"):
447 extended["mempage-size"] = target_flavor["guest-epa"].get("mempage-size")
448 if target_flavor["guest-epa"].get("cpu-pinning-policy") and not epa_vcpu_set:
449 if target_flavor["guest-epa"]["cpu-pinning-policy"] == "DEDICATED":
450 if target_flavor["guest-epa"].get("cpu-thread-pinning-policy") and \
451 target_flavor["guest-epa"]["cpu-thread-pinning-policy"] != "PREFER":
452 numa["cores"] = max(flavor_data["vcpus"], 1)
453 else:
454 numa["threads"] = max(flavor_data["vcpus"], 1)
455 epa_vcpu_set = True
456 if target_flavor["guest-epa"].get("cpu-quota") and not epa_vcpu_set:
457 cpuquota = _get_resource_allocation_params(target_flavor["guest-epa"].get("cpu-quota"))
458 if cpuquota:
459 extended["cpu-quota"] = cpuquota
460 if target_flavor["guest-epa"].get("mem-quota"):
461 vduquota = _get_resource_allocation_params(target_flavor["guest-epa"].get("mem-quota"))
462 if vduquota:
463 extended["mem-quota"] = vduquota
464 if target_flavor["guest-epa"].get("disk-io-quota"):
465 diskioquota = _get_resource_allocation_params(target_flavor["guest-epa"].get("disk-io-quota"))
466 if diskioquota:
467 extended["disk-io-quota"] = diskioquota
468 if target_flavor["guest-epa"].get("vif-quota"):
469 vifquota = _get_resource_allocation_params(target_flavor["guest-epa"].get("vif-quota"))
470 if vifquota:
471 extended["vif-quota"] = vifquota
472 if numa:
473 extended["numas"] = [numa]
474 if extended:
475 flavor_data["extended"] = extended
476
477 extra_dict = {"find_params": {"flavor_data": flavor_data}}
478 flavor_data_name = flavor_data.copy()
479 flavor_data_name["name"] = target_flavor["name"]
480 extra_dict["params"] = {"flavor_data": flavor_data_name}
481 return extra_dict
482
483 def _ip_profile_2_ro(ip_profile):
484 if not ip_profile:
485 return None
486 ro_ip_profile = {
487 "ip_version": "IPv4" if "v4" in ip_profile.get("ip-version", "ipv4") else "IPv6",
488 "subnet_address": ip_profile.get("subnet-address"),
489 "gateway_address": ip_profile.get("gateway-address"),
490 "dhcp_enabled": ip_profile["dhcp-params"].get("enabled", True),
491 "dhcp_start_address": ip_profile["dhcp-params"].get("start-address"),
492 "dhcp_count": ip_profile["dhcp-params"].get("count"),
493
494 }
495 if ip_profile.get("dns-server"):
496 ro_ip_profile["dns_address"] = ";".join([v["address"] for v in ip_profile["dns-server"]])
497 if ip_profile.get('security-group'):
498 ro_ip_profile["security_group"] = ip_profile['security-group']
499 return ro_ip_profile
500
501 def _process_net_params(target_vld, vim_info, target_record_id):
502 nonlocal indata
503 extra_dict = {}
504
505 if vim_info.get("sdn"):
506 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
507 # ns_preffix = "nsrs:{}".format(nsr_id)
508 vld_target_record_id, _, _ = target_record_id.rpartition(".") # remove the ending ".sdn
509 extra_dict["params"] = {k: vim_info[k] for k in ("sdn-ports", "target_vim", "vlds", "type")
510 if vim_info.get(k)}
511 # TODO needed to add target_id in the dependency.
512 if vim_info.get("target_vim"):
513 extra_dict["depends_on"] = [vim_info.get("target_vim") + " " + vld_target_record_id]
514 return extra_dict
515
516 if vim_info.get("vim_network_name"):
517 extra_dict["find_params"] = {"filter_dict": {"name": vim_info.get("vim_network_name")}}
518 elif vim_info.get("vim_network_id"):
519 extra_dict["find_params"] = {"filter_dict": {"id": vim_info.get("vim_network_id")}}
520 elif target_vld.get("mgmt-network"):
521 extra_dict["find_params"] = {"mgmt": True, "name": target_vld["id"]}
522 else:
523 # create
524 extra_dict["params"] = {
525 "net_name": "{}-{}".format(indata["name"][:16], target_vld.get("name", target_vld["id"])[:16]),
526 "ip_profile": _ip_profile_2_ro(vim_info.get('ip_profile')),
527 "provider_network_profile": vim_info.get('provider_network'),
528 }
529 if not target_vld.get("underlay"):
530 extra_dict["params"]["net_type"] = "bridge"
531 else:
532 extra_dict["params"]["net_type"] = "ptp" if target_vld.get("type") == "ELINE" else "data"
533 return extra_dict
534
535 def _process_vdu_params(target_vdu, vim_info, target_record_id):
536 nonlocal vnfr_id
537 nonlocal nsr_id
538 nonlocal indata
539 nonlocal vnfr
540 nonlocal vdu2cloud_init
541 nonlocal tasks_by_target_record_id
542 vnf_preffix = "vnfrs:{}".format(vnfr_id)
543 ns_preffix = "nsrs:{}".format(nsr_id)
544 image_text = ns_preffix + ":image." + target_vdu["ns-image-id"]
545 flavor_text = ns_preffix + ":flavor." + target_vdu["ns-flavor-id"]
546 extra_dict = {"depends_on": [image_text, flavor_text]}
547 net_list = []
548 for iface_index, interface in enumerate(target_vdu["interfaces"]):
549 if interface.get("ns-vld-id"):
550 net_text = ns_preffix + ":vld." + interface["ns-vld-id"]
551 elif interface.get("vnf-vld-id"):
552 net_text = vnf_preffix + ":vld." + interface["vnf-vld-id"]
553 else:
554 self.logger.error("Interface {} from vdu {} not connected to any vld".format(
555 iface_index, target_vdu["vdu-name"]))
556 continue # interface not connected to any vld
557 extra_dict["depends_on"].append(net_text)
558 net_item = {x: v for x, v in interface.items() if x in
559 ("name", "vpci", "port_security", "port_security_disable_strategy", "floating_ip")}
560 net_item["net_id"] = "TASK-" + net_text
561 net_item["type"] = "virtual"
562 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
563 # TODO floating_ip: True/False (or it can be None)
564 if interface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
565 # mark the net create task as type data
566 if deep_get(tasks_by_target_record_id, net_text, "params", "net_type"):
567 tasks_by_target_record_id[net_text]["params"]["net_type"] = "data"
568 net_item["use"] = "data"
569 net_item["model"] = interface["type"]
570 net_item["type"] = interface["type"]
571 elif interface.get("type") == "OM-MGMT" or interface.get("mgmt-interface") or \
572 interface.get("mgmt-vnf"):
573 net_item["use"] = "mgmt"
574 else: # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
575 net_item["use"] = "bridge"
576 net_item["model"] = interface.get("type")
577 if interface.get("ip-address"):
578 net_item["ip_address"] = interface["ip-address"]
579 if interface.get("mac-address"):
580 net_item["mac_address"] = interface["mac-address"]
581 net_list.append(net_item)
582 if interface.get("mgmt-vnf"):
583 extra_dict["mgmt_vnf_interface"] = iface_index
584 elif interface.get("mgmt-interface"):
585 extra_dict["mgmt_vdu_interface"] = iface_index
586 # cloud config
587 cloud_config = {}
588 if target_vdu.get("cloud-init"):
589 if target_vdu["cloud-init"] not in vdu2cloud_init:
590 vdu2cloud_init[target_vdu["cloud-init"]] = self._get_cloud_init(target_vdu["cloud-init"])
591 cloud_content_ = vdu2cloud_init[target_vdu["cloud-init"]]
592 cloud_config["user-data"] = self._parse_jinja2(cloud_content_, target_vdu.get("additionalParams"),
593 target_vdu["cloud-init"])
594 if target_vdu.get("boot-data-drive"):
595 cloud_config["boot-data-drive"] = target_vdu.get("boot-data-drive")
596 ssh_keys = []
597 if target_vdu.get("ssh-keys"):
598 ssh_keys += target_vdu.get("ssh-keys")
599 if target_vdu.get("ssh-access-required"):
600 ssh_keys.append(ro_nsr_public_key)
601 if ssh_keys:
602 cloud_config["key-pairs"] = ssh_keys
603
604 extra_dict["params"] = {
605 "name": "{}-{}-{}-{}".format(indata["name"][:16], vnfr["member-vnf-index-ref"][:16],
606 target_vdu["vdu-name"][:32], target_vdu.get("count-index") or 0),
607 "description": target_vdu["vdu-name"],
608 "start": True,
609 "image_id": "TASK-" + image_text,
610 "flavor_id": "TASK-" + flavor_text,
611 "net_list": net_list,
612 "cloud_config": cloud_config or None,
613 "disk_list": None, # TODO
614 "availability_zone_index": None, # TODO
615 "availability_zone_list": None, # TODO
616 }
617 return extra_dict
618
619 def _process_items(target_list, existing_list, db_record, db_update, db_path, item, process_params):
620 nonlocal db_new_tasks
621 nonlocal tasks_by_target_record_id
622 nonlocal task_index
623
624 # ensure all the target_list elements has an "id". If not assign the index as id
625 for target_index, tl in enumerate(target_list):
626 if tl and not tl.get("id"):
627 tl["id"] = str(target_index)
628
629 # step 1 items (networks,vdus,...) to be deleted/updated
630 for item_index, existing_item in enumerate(existing_list):
631 target_item = next((t for t in target_list if t["id"] == existing_item["id"]), None)
632 for target_vim, existing_viminfo in existing_item.get("vim_info", {}).items():
633 if existing_viminfo is None:
634 continue
635 if target_item:
636 target_viminfo = target_item.get("vim_info", {}).get(target_vim)
637 else:
638 target_viminfo = None
639 if target_viminfo is None:
640 # must be deleted
641 self.assign_vim(target_vim)
642 target_record_id = "{}.{}".format(db_record, existing_item["id"])
643 item_ = item
644 if target_vim.startswith("sdn"):
645 # item must be sdn-net instead of net if target_vim is a sdn
646 item_ = "sdn_net"
647 target_record_id += ".sdn"
648 task = _create_task(
649 target_vim, item_, "DELETE",
650 target_record="{}.{}.vim_info.{}".format(db_record, item_index, target_vim),
651 target_record_id=target_record_id)
652 tasks_by_target_record_id[target_record_id] = task
653 db_new_tasks.append(task)
654 # TODO delete
655 # TODO check one by one the vims to be created/deleted
656
657 # step 2 items (networks,vdus,...) to be created
658 for target_item in target_list:
659 item_index = -1
660 for item_index, existing_item in enumerate(existing_list):
661 if existing_item["id"] == target_item["id"]:
662 break
663 else:
664 item_index += 1
665 db_update[db_path + ".{}".format(item_index)] = target_item
666 existing_list.append(target_item)
667 existing_item = None
668
669 for target_vim, target_viminfo in target_item.get("vim_info", {}).items():
670 existing_viminfo = None
671 if existing_item:
672 existing_viminfo = existing_item.get("vim_info", {}).get(target_vim)
673 # TODO check if different. Delete and create???
674 # TODO delete if not exist
675 if existing_viminfo is not None:
676 continue
677
678 target_record_id = "{}.{}".format(db_record, target_item["id"])
679 item_ = item
680 if target_vim.startswith("sdn"):
681 # item must be sdn-net instead of net if target_vim is a sdn
682 item_ = "sdn_net"
683 target_record_id += ".sdn"
684 extra_dict = process_params(target_item, target_viminfo, target_record_id)
685
686 self.assign_vim(target_vim)
687 task = _create_task(
688 target_vim, item_, "CREATE",
689 target_record="{}.{}.vim_info.{}".format(db_record, item_index, target_vim),
690 target_record_id=target_record_id,
691 extra_dict=extra_dict)
692 tasks_by_target_record_id[target_record_id] = task
693 db_new_tasks.append(task)
694 if target_item.get("common_id"):
695 task["common_id"] = target_item["common_id"]
696
697 db_update[db_path + ".{}".format(item_index)] = target_item
698
699 def _process_action(indata):
700 nonlocal db_new_tasks
701 nonlocal task_index
702 nonlocal db_vnfrs
703 nonlocal db_ro_nsr
704
705 if indata["action"]["action"] == "inject_ssh_key":
706 key = indata["action"].get("key")
707 user = indata["action"].get("user")
708 password = indata["action"].get("password")
709 for vnf in indata.get("vnf", ()):
710 if vnf["_id"] not in db_vnfrs:
711 raise NsException("Invalid vnf={}".format(vnf["_id"]))
712 db_vnfr = db_vnfrs[vnf["_id"]]
713 for target_vdu in vnf.get("vdur", ()):
714 vdu_index, vdur = next((i_v for i_v in enumerate(db_vnfr["vdur"]) if
715 i_v[1]["id"] == target_vdu["id"]), (None, None))
716 if not vdur:
717 raise NsException("Invalid vdu vnf={}.{}".format(vnf["_id"], target_vdu["id"]))
718 target_vim, vim_info = next(k_v for k_v in vdur["vim_info"].items())
719 self.assign_vim(target_vim)
720 target_record = "vnfrs:{}:vdur.{}.ssh_keys".format(vnf["_id"], vdu_index)
721 extra_dict = {
722 "depends_on": ["vnfrs:{}:vdur.{}".format(vnf["_id"], vdur["id"])],
723 "params": {
724 "ip_address": vdur.get("ip-address"),
725 "user": user,
726 "key": key,
727 "password": password,
728 "private_key": db_ro_nsr["private_key"],
729 "salt": db_ro_nsr["_id"],
730 "schema_version": db_ro_nsr["_admin"]["schema_version"]
731 }
732 }
733 task = _create_task(target_vim, "vdu", "EXEC",
734 target_record=target_record,
735 target_record_id=None,
736 extra_dict=extra_dict)
737 db_new_tasks.append(task)
738
739 with self.write_lock:
740 if indata.get("action"):
741 _process_action(indata)
742 else:
743 # compute network differences
744 # NS.vld
745 step = "process NS VLDs"
746 _process_items(target_list=indata["ns"]["vld"] or [], existing_list=db_nsr.get("vld") or [],
747 db_record="nsrs:{}:vld".format(nsr_id), db_update=db_nsr_update,
748 db_path="vld", item="net", process_params=_process_net_params)
749
750 step = "process NS images"
751 _process_items(target_list=indata.get("image") or [], existing_list=db_nsr.get("image") or [],
752 db_record="nsrs:{}:image".format(nsr_id),
753 db_update=db_nsr_update, db_path="image", item="image",
754 process_params=_process_image_params)
755
756 step = "process NS flavors"
757 _process_items(target_list=indata.get("flavor") or [], existing_list=db_nsr.get("flavor") or [],
758 db_record="nsrs:{}:flavor".format(nsr_id),
759 db_update=db_nsr_update, db_path="flavor", item="flavor",
760 process_params=_process_flavor_params)
761
762 # VNF.vld
763 for vnfr_id, vnfr in db_vnfrs.items():
764 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
765 step = "process VNF={} VLDs".format(vnfr_id)
766 target_vnf = next((vnf for vnf in indata.get("vnf", ()) if vnf["_id"] == vnfr_id), None)
767 target_list = target_vnf.get("vld") if target_vnf else None
768 _process_items(target_list=target_list or [], existing_list=vnfr.get("vld") or [],
769 db_record="vnfrs:{}:vld".format(vnfr_id), db_update=db_vnfrs_update[vnfr["_id"]],
770 db_path="vld", item="net", process_params=_process_net_params)
771
772 target_list = target_vnf.get("vdur") if target_vnf else None
773 step = "process VNF={} VDUs".format(vnfr_id)
774 _process_items(target_list=target_list or [], existing_list=vnfr.get("vdur") or [],
775 db_record="vnfrs:{}:vdur".format(vnfr_id),
776 db_update=db_vnfrs_update[vnfr["_id"]], db_path="vdur", item="vdu",
777 process_params=_process_vdu_params)
778
779 for db_task in db_new_tasks:
780 step = "Updating database, Appending tasks to ro_tasks"
781 target_id = db_task.pop("target_id")
782 common_id = db_task.get("common_id")
783 if common_id:
784 if self.db.set_one("ro_tasks",
785 q_filter={"target_id": target_id,
786 "tasks.common_id": common_id},
787 update_dict={"to_check_at": now, "modified_at": now},
788 push={"tasks": db_task}, fail_on_empty=False):
789 continue
790 if not self.db.set_one("ro_tasks",
791 q_filter={"target_id": target_id,
792 "tasks.target_record": db_task["target_record"]},
793 update_dict={"to_check_at": now, "modified_at": now},
794 push={"tasks": db_task}, fail_on_empty=False):
795 # Create a ro_task
796 step = "Updating database, Creating ro_tasks"
797 db_ro_task = _create_ro_task(target_id, db_task)
798 nb_ro_tasks += 1
799 self.db.create("ro_tasks", db_ro_task)
800 step = "Updating database, nsrs"
801 if db_nsr_update:
802 self.db.set_one("nsrs", {"_id": nsr_id}, db_nsr_update)
803 for vnfr_id, db_vnfr_update in db_vnfrs_update.items():
804 if db_vnfr_update:
805 step = "Updating database, vnfrs={}".format(vnfr_id)
806 self.db.set_one("vnfrs", {"_id": vnfr_id}, db_vnfr_update)
807
808 self.logger.debug(logging_text + "Exit. Created {} ro_tasks; {} tasks".format(nb_ro_tasks,
809 len(db_new_tasks)))
810 return {"status": "ok", "nsr_id": nsr_id, "action_id": action_id}, action_id, True
811
812 except Exception as e:
813 if isinstance(e, (DbException, NsException)):
814 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
815 else:
816 e = traceback_format_exc()
817 self.logger.critical(logging_text + "Exit Exception while '{}': {}".format(step, e), exc_info=True)
818 raise NsException(e)
819
820 def delete(self, session, indata, version, nsr_id, *args, **kwargs):
821 self.logger.debug("ns.delete version={} nsr_id={}".format(version, nsr_id))
822 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
823 with self.write_lock:
824 try:
825 NsWorker.delete_db_tasks(self.db, nsr_id, None)
826 except NsWorkerException as e:
827 raise NsException(e)
828 return None, None, True
829
830 def status(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
831 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
832 # .format(version, nsr_id, action_id, indata))
833 task_list = []
834 done = 0
835 total = 0
836 ro_tasks = self.db.get_list("ro_tasks", {"tasks.action_id": action_id})
837 global_status = "DONE"
838 details = []
839 for ro_task in ro_tasks:
840 for task in ro_task["tasks"]:
841 if task and task["action_id"] == action_id:
842 task_list.append(task)
843 total += 1
844 if task["status"] == "FAILED":
845 global_status = "FAILED"
846 error_text = "Error at {} {}: {}".format(task["action"].lower(), task["item"],
847 ro_task["vim_info"].get("vim_details") or "unknown")
848 details.append(error_text)
849 elif task["status"] in ("SCHEDULED", "BUILD"):
850 if global_status != "FAILED":
851 global_status = "BUILD"
852 else:
853 done += 1
854 return_data = {
855 "status": global_status,
856 "details": ". ".join(details) if details else "progress {}/{}".format(done, total),
857 "nsr_id": nsr_id,
858 "action_id": action_id,
859 "tasks": task_list
860 }
861 return return_data, None, True
862
863 def cancel(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
864 print("ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(session, indata, version,
865 nsr_id, action_id))
866 return None, None, True
867
868 def get_deploy(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
869 nsrs = self.db.get_list("nsrs", {})
870 return_data = []
871 for ns in nsrs:
872 return_data.append({"_id": ns["_id"], "name": ns["name"]})
873 return return_data, None, True
874
875 def get_actions(self, session, indata, version, nsr_id, action_id, *args, **kwargs):
876 ro_tasks = self.db.get_list("ro_tasks", {"tasks.nsr_id": nsr_id})
877 return_data = []
878 for ro_task in ro_tasks:
879 for task in ro_task["tasks"]:
880 if task["action_id"] not in return_data:
881 return_data.append(task["action_id"])
882 return return_data, None, True