blob: b9417f29960eb3157c12c16dcf48e8d2c072a8bf [file] [log] [blame]
tiernoc0e42e22018-05-11 11:36:10 +02001#!/usr/bin/python3
2# -*- coding: utf-8 -*-
3
4import asyncio
5import yaml
tierno275411e2018-05-16 14:33:32 +02006import logging
7import logging.handlers
8import getopt
9import functools
10import sys
tierno22f4f9c2018-06-11 18:53:39 +020011import traceback
tiernobce32152018-07-23 16:18:59 +020012import ROclient
13# from osm_lcm import version as lcm_version, version_date as lcm_version_date, ROclient
tierno98768132018-09-11 12:07:21 +020014from osm_common import dbmemory, dbmongo, fslocal, msglocal, msgkafka
15from osm_common import version as common_version
16from osm_common.dbbase import DbException, deep_update
tiernoc0e42e22018-05-11 11:36:10 +020017from osm_common.fsbase import FsException
18from osm_common.msgbase import MsgException
tierno275411e2018-05-16 14:33:32 +020019from os import environ, path
tiernoc0e42e22018-05-11 11:36:10 +020020from n2vc.vnf import N2VC
21from n2vc import version as N2VC_version
tiernoc0e42e22018-05-11 11:36:10 +020022
tiernoca2e16a2018-06-29 15:25:24 +020023from collections import OrderedDict
tiernoc0e42e22018-05-11 11:36:10 +020024from copy import deepcopy
25from http import HTTPStatus
26from time import time
27
28
tierno275411e2018-05-16 14:33:32 +020029__author__ = "Alfonso Tierno"
tierno053422d2018-07-10 12:56:43 +020030min_RO_version = [0, 5, 72]
tierno6e9d2eb2018-09-12 17:47:18 +020031min_n2vc_version = "0.0.2"
32min_common_version = "0.1.7"
tierno86aa62f2018-08-20 11:57:04 +000033# uncomment if LCM is installed as library and installed, and get them from __init__.py
tierno6e9d2eb2018-09-12 17:47:18 +020034lcm_version = '0.1.15'
35lcm_version_date = '2018-09-13'
tierno275411e2018-05-16 14:33:32 +020036
37
tierno6e9d2eb2018-09-12 17:47:18 +020038def versiontuple(v):
39 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
40 filled = []
41 for point in v.split("."):
42 filled.append(point.zfill(8))
43 return tuple(filled)
44
45
tiernoc0e42e22018-05-11 11:36:10 +020046class LcmException(Exception):
47 pass
48
49
tiernoca2e16a2018-06-29 15:25:24 +020050class TaskRegistry:
51 """
52 Implements a registry of task needed for later cancelation, look for related tasks that must be completed before
53 etc. It stores a four level dict
54 First level is the topic, ns, vim_account, sdn
55 Second level is the _id
56 Third level is the operation id
57 Fourth level is a descriptive name, the value is the task class
58 """
59
60 def __init__(self):
61 self.task_registry = {
62 "ns": {},
63 "vim_account": {},
64 "sdn": {},
65 }
66
67 def register(self, topic, _id, op_id, task_name, task):
68 """
69 Register a new task
70 :param topic: Can be "ns", "vim_account", "sdn"
71 :param _id: _id of the related item
72 :param op_id: id of the operation of the related item
73 :param task_name: Task descriptive name, as create, instantiate, terminate. Must be unique in this op_id
74 :param task: Task class
75 :return: none
76 """
77 if _id not in self.task_registry[topic]:
78 self.task_registry[topic][_id] = OrderedDict()
79 if op_id not in self.task_registry[topic][_id]:
80 self.task_registry[topic][_id][op_id] = {task_name: task}
81 else:
82 self.task_registry[topic][_id][op_id][task_name] = task
83 # print("registering task", topic, _id, op_id, task_name, task)
84
85 def remove(self, topic, _id, op_id, task_name=None):
86 """
87 When task is ended, it should removed. It ignores missing tasks
88 :param topic: Can be "ns", "vim_account", "sdn"
89 :param _id: _id of the related item
90 :param op_id: id of the operation of the related item
91 :param task_name: Task descriptive name. If note it deletes all
92 :return:
93 """
94 if not self.task_registry[topic].get(_id) or not self.task_registry[topic][_id].get(op_id):
95 return
96 if not task_name:
97 # print("deleting tasks", topic, _id, op_id, self.task_registry[topic][_id][op_id])
98 del self.task_registry[topic][_id][op_id]
99 elif task_name in self.task_registry[topic][_id][op_id]:
100 # print("deleting tasks", topic, _id, op_id, task_name, self.task_registry[topic][_id][op_id][task_name])
101 del self.task_registry[topic][_id][op_id][task_name]
102 if not self.task_registry[topic][_id][op_id]:
103 del self.task_registry[topic][_id][op_id]
104 if not self.task_registry[topic][_id]:
105 del self.task_registry[topic][_id]
106
107 def lookfor_related(self, topic, _id, my_op_id=None):
108 task_list = []
109 task_name_list = []
110 if _id not in self.task_registry[topic]:
111 return "", task_name_list
112 for op_id in reversed(self.task_registry[topic][_id]):
113 if my_op_id:
114 if my_op_id == op_id:
115 my_op_id = None # so that the next task is taken
116 continue
117
118 for task_name, task in self.task_registry[topic][_id][op_id].items():
119 task_list.append(task)
120 task_name_list.append(task_name)
121 break
122 return ", ".join(task_name_list), task_list
123
124 def cancel(self, topic, _id, target_op_id=None, target_task_name=None):
125 """
126 Cancel all active tasks of a concrete ns, vim_account, sdn identified for _id. If op_id is supplied only this is
127 cancelled, and the same with task_name
128 """
129 if not self.task_registry[topic].get(_id):
130 return
131 for op_id in reversed(self.task_registry[topic][_id]):
132 if target_op_id and target_op_id != op_id:
133 continue
134 for task_name, task in self.task_registry[topic][_id][op_id].items():
135 if target_task_name and target_task_name != task_name:
136 continue
tiernofa66d152018-08-28 10:13:45 +0000137 # result =
138 task.cancel()
139 # if result:
140 # self.logger.debug("{} _id={} order_id={} task={} cancelled".format(topic, _id, op_id, task_name))
tiernoca2e16a2018-06-29 15:25:24 +0200141
142
tiernoc0e42e22018-05-11 11:36:10 +0200143class Lcm:
144
145 def __init__(self, config_file):
146 """
147 Init, Connect to database, filesystem storage, and messaging
148 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
149 :return: None
150 """
151
152 self.db = None
153 self.msg = None
154 self.fs = None
155 self.pings_not_received = 1
156
157 # contains created tasks/futures to be able to cancel
tiernoca2e16a2018-06-29 15:25:24 +0200158 self.lcm_tasks = TaskRegistry()
tiernoc0e42e22018-05-11 11:36:10 +0200159 # logging
160 self.logger = logging.getLogger('lcm')
161 # load configuration
162 config = self.read_config_file(config_file)
163 self.config = config
tierno750b2452018-05-17 16:39:29 +0200164 self.ro_config = {
tiernoc0e42e22018-05-11 11:36:10 +0200165 "endpoint_url": "http://{}:{}/openmano".format(config["RO"]["host"], config["RO"]["port"]),
tierno750b2452018-05-17 16:39:29 +0200166 "tenant": config.get("tenant", "osm"),
tiernoc0e42e22018-05-11 11:36:10 +0200167 "logger_name": "lcm.ROclient",
168 "loglevel": "ERROR",
169 }
170
171 self.vca = config["VCA"] # TODO VCA
172 self.loop = None
173
174 # logging
175 log_format_simple = "%(asctime)s %(levelname)s %(name)s %(filename)s:%(lineno)s %(message)s"
176 log_formatter_simple = logging.Formatter(log_format_simple, datefmt='%Y-%m-%dT%H:%M:%S')
177 config["database"]["logger_name"] = "lcm.db"
178 config["storage"]["logger_name"] = "lcm.fs"
179 config["message"]["logger_name"] = "lcm.msg"
tierno86aa62f2018-08-20 11:57:04 +0000180 if config["global"].get("logfile"):
tiernoc0e42e22018-05-11 11:36:10 +0200181 file_handler = logging.handlers.RotatingFileHandler(config["global"]["logfile"],
182 maxBytes=100e6, backupCount=9, delay=0)
183 file_handler.setFormatter(log_formatter_simple)
184 self.logger.addHandler(file_handler)
tierno86aa62f2018-08-20 11:57:04 +0000185 if not config["global"].get("nologging"):
tiernoc0e42e22018-05-11 11:36:10 +0200186 str_handler = logging.StreamHandler()
187 str_handler.setFormatter(log_formatter_simple)
188 self.logger.addHandler(str_handler)
189
190 if config["global"].get("loglevel"):
191 self.logger.setLevel(config["global"]["loglevel"])
192
193 # logging other modules
194 for k1, logname in {"message": "lcm.msg", "database": "lcm.db", "storage": "lcm.fs"}.items():
195 config[k1]["logger_name"] = logname
196 logger_module = logging.getLogger(logname)
tierno86aa62f2018-08-20 11:57:04 +0000197 if config[k1].get("logfile"):
tiernoc0e42e22018-05-11 11:36:10 +0200198 file_handler = logging.handlers.RotatingFileHandler(config[k1]["logfile"],
199 maxBytes=100e6, backupCount=9, delay=0)
200 file_handler.setFormatter(log_formatter_simple)
201 logger_module.addHandler(file_handler)
tierno86aa62f2018-08-20 11:57:04 +0000202 if config[k1].get("loglevel"):
tiernoc0e42e22018-05-11 11:36:10 +0200203 logger_module.setLevel(config[k1]["loglevel"])
tierno86aa62f2018-08-20 11:57:04 +0000204 self.logger.critical("starting osm/lcm version {} {}".format(lcm_version, lcm_version_date))
tiernoc0e42e22018-05-11 11:36:10 +0200205 self.n2vc = N2VC(
206 log=self.logger,
207 server=config['VCA']['host'],
208 port=config['VCA']['port'],
209 user=config['VCA']['user'],
210 secret=config['VCA']['secret'],
211 # TODO: This should point to the base folder where charms are stored,
212 # if there is a common one (like object storage). Otherwise, leave
213 # it unset and pass it via DeployCharms
214 # artifacts=config['VCA'][''],
215 artifacts=None,
216 )
217 # check version of N2VC
218 # TODO enhance with int conversion or from distutils.version import LooseVersion
219 # or with list(map(int, version.split(".")))
tierno6e9d2eb2018-09-12 17:47:18 +0200220 if versiontuple(N2VC_version) < versiontuple(min_n2vc_version):
221 raise LcmException("Not compatible osm/N2VC version '{}'. Needed '{}' or higher".format(
222 N2VC_version, min_n2vc_version))
223 if versiontuple(common_version) < versiontuple("0.1.7"):
224 raise LcmException("Not compatible osm/common version '{}'. Needed '{}' or higher".format(
225 common_version, min_common_version))
tierno22f4f9c2018-06-11 18:53:39 +0200226
tiernoc0e42e22018-05-11 11:36:10 +0200227 try:
tierno22f4f9c2018-06-11 18:53:39 +0200228 # TODO check database version
tiernoc0e42e22018-05-11 11:36:10 +0200229 if config["database"]["driver"] == "mongo":
230 self.db = dbmongo.DbMongo()
231 self.db.db_connect(config["database"])
232 elif config["database"]["driver"] == "memory":
233 self.db = dbmemory.DbMemory()
234 self.db.db_connect(config["database"])
235 else:
236 raise LcmException("Invalid configuration param '{}' at '[database]':'driver'".format(
237 config["database"]["driver"]))
238
239 if config["storage"]["driver"] == "local":
240 self.fs = fslocal.FsLocal()
241 self.fs.fs_connect(config["storage"])
242 else:
243 raise LcmException("Invalid configuration param '{}' at '[storage]':'driver'".format(
244 config["storage"]["driver"]))
245
246 if config["message"]["driver"] == "local":
247 self.msg = msglocal.MsgLocal()
248 self.msg.connect(config["message"])
249 elif config["message"]["driver"] == "kafka":
250 self.msg = msgkafka.MsgKafka()
251 self.msg.connect(config["message"])
252 else:
253 raise LcmException("Invalid configuration param '{}' at '[message]':'driver'".format(
254 config["storage"]["driver"]))
255 except (DbException, FsException, MsgException) as e:
256 self.logger.critical(str(e), exc_info=True)
257 raise LcmException(str(e))
258
tierno22f4f9c2018-06-11 18:53:39 +0200259 async def check_RO_version(self):
260 try:
261 RO = ROclient.ROClient(self.loop, **self.ro_config)
262 RO_version = await RO.get_version()
263 if RO_version < min_RO_version:
264 raise LcmException("Not compatible osm/RO version '{}.{}.{}'. Needed '{}.{}.{}' or higher".format(
265 *RO_version, *min_RO_version
266 ))
267 except ROclient.ROClientException as e:
268 self.logger.critical("Error while conneting to osm/RO " + str(e), exc_info=True)
269 raise LcmException(str(e))
270
tiernoc0e42e22018-05-11 11:36:10 +0200271 def update_db_2(self, item, _id, _desc):
tierno22f4f9c2018-06-11 18:53:39 +0200272 """
273 Updates database with _desc information. Upon success _desc is cleared
274 :param item:
275 :param _id:
276 :param _desc:
277 :return:
278 """
279 if not _desc:
280 return
tiernoc0e42e22018-05-11 11:36:10 +0200281 try:
282 self.db.set_one(item, {"_id": _id}, _desc)
tierno22f4f9c2018-06-11 18:53:39 +0200283 _desc.clear()
tiernoc0e42e22018-05-11 11:36:10 +0200284 except DbException as e:
tierno22f4f9c2018-06-11 18:53:39 +0200285 self.logger.error("Updating {} _id={} with '{}'. Error: {}".format(item, _id, _desc, e))
tiernoc0e42e22018-05-11 11:36:10 +0200286
287 async def vim_create(self, vim_content, order_id):
288 vim_id = vim_content["_id"]
289 logging_text = "Task vim_create={} ".format(vim_id)
290 self.logger.debug(logging_text + "Enter")
291 db_vim = None
tiernoca2e16a2018-06-29 15:25:24 +0200292 db_vim_update = {}
tiernoc0e42e22018-05-11 11:36:10 +0200293 exc = None
tiernofe1c37f2018-05-17 22:58:04 +0200294 RO_sdn_id = None
tiernoc0e42e22018-05-11 11:36:10 +0200295 try:
tiernofe1c37f2018-05-17 22:58:04 +0200296 step = "Getting vim-id='{}' from db".format(vim_id)
tiernoc0e42e22018-05-11 11:36:10 +0200297 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
tiernoca2e16a2018-06-29 15:25:24 +0200298 db_vim_update["_admin.deployed.RO"] = None
tiernofe1c37f2018-05-17 22:58:04 +0200299 if vim_content.get("config") and vim_content["config"].get("sdn-controller"):
300 step = "Getting sdn-controller-id='{}' from db".format(vim_content["config"]["sdn-controller"])
301 db_sdn = self.db.get_one("sdns", {"_id": vim_content["config"]["sdn-controller"]})
302 if db_sdn.get("_admin") and db_sdn["_admin"].get("deployed") and db_sdn["_admin"]["deployed"].get("RO"):
303 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
304 else:
305 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
306 vim_content["config"]["sdn-controller"]))
tiernoc0e42e22018-05-11 11:36:10 +0200307
308 step = "Creating vim at RO"
tiernoca2e16a2018-06-29 15:25:24 +0200309 db_vim_update["_admin.detailed-status"] = step
310 self.update_db_2("vim_accounts", vim_id, db_vim_update)
tiernoc0e42e22018-05-11 11:36:10 +0200311 RO = ROclient.ROClient(self.loop, **self.ro_config)
312 vim_RO = deepcopy(vim_content)
313 vim_RO.pop("_id", None)
314 vim_RO.pop("_admin", None)
315 vim_RO.pop("schema_version", None)
316 vim_RO.pop("schema_type", None)
317 vim_RO.pop("vim_tenant_name", None)
318 vim_RO["type"] = vim_RO.pop("vim_type")
319 vim_RO.pop("vim_user", None)
320 vim_RO.pop("vim_password", None)
tiernofe1c37f2018-05-17 22:58:04 +0200321 if RO_sdn_id:
322 vim_RO["config"]["sdn-controller"] = RO_sdn_id
tiernoc0e42e22018-05-11 11:36:10 +0200323 desc = await RO.create("vim", descriptor=vim_RO)
324 RO_vim_id = desc["uuid"]
tiernoca2e16a2018-06-29 15:25:24 +0200325 db_vim_update["_admin.deployed.RO"] = RO_vim_id
tiernoc0e42e22018-05-11 11:36:10 +0200326
tiernofe1c37f2018-05-17 22:58:04 +0200327 step = "Creating vim_account at RO"
tiernoca2e16a2018-06-29 15:25:24 +0200328 db_vim_update["_admin.detailed-status"] = step
329 self.update_db_2("vim_accounts", vim_id, db_vim_update)
330
tiernofe1c37f2018-05-17 22:58:04 +0200331 vim_account_RO = {"vim_tenant_name": vim_content["vim_tenant_name"],
332 "vim_username": vim_content["vim_user"],
333 "vim_password": vim_content["vim_password"]
334 }
335 if vim_RO.get("config"):
336 vim_account_RO["config"] = vim_RO["config"]
337 if "sdn-controller" in vim_account_RO["config"]:
338 del vim_account_RO["config"]["sdn-controller"]
339 if "sdn-port-mapping" in vim_account_RO["config"]:
340 del vim_account_RO["config"]["sdn-port-mapping"]
tiernoca2e16a2018-06-29 15:25:24 +0200341 desc = await RO.attach_datacenter(RO_vim_id, descriptor=vim_account_RO)
342 db_vim_update["_admin.deployed.RO-account"] = desc["uuid"]
343 db_vim_update["_admin.operationalState"] = "ENABLED"
344 db_vim_update["_admin.detailed-status"] = "Done"
tiernoc0e42e22018-05-11 11:36:10 +0200345
tiernoca2e16a2018-06-29 15:25:24 +0200346 # await asyncio.sleep(15) # TODO remove. This is for test
347 self.logger.debug(logging_text + "Exit Ok RO_vim_id={}".format(RO_vim_id))
348 return
tiernoc0e42e22018-05-11 11:36:10 +0200349
350 except (ROclient.ROClientException, DbException) as e:
351 self.logger.error(logging_text + "Exit Exception {}".format(e))
352 exc = e
353 except Exception as e:
354 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
355 exc = e
356 finally:
357 if exc and db_vim:
tiernoca2e16a2018-06-29 15:25:24 +0200358 db_vim_update["_admin.operationalState"] = "ERROR"
359 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
360 if db_vim_update:
361 self.update_db_2("vim_accounts", vim_id, db_vim_update)
362 self.lcm_tasks.remove("vim_account", vim_id, order_id)
tiernoc0e42e22018-05-11 11:36:10 +0200363
364 async def vim_edit(self, vim_content, order_id):
365 vim_id = vim_content["_id"]
366 logging_text = "Task vim_edit={} ".format(vim_id)
367 self.logger.debug(logging_text + "Enter")
368 db_vim = None
369 exc = None
tiernofe1c37f2018-05-17 22:58:04 +0200370 RO_sdn_id = None
tiernoca2e16a2018-06-29 15:25:24 +0200371 RO_vim_id = None
372 db_vim_update = {}
tiernofe1c37f2018-05-17 22:58:04 +0200373 step = "Getting vim-id='{}' from db".format(vim_id)
tiernoc0e42e22018-05-11 11:36:10 +0200374 try:
375 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
tiernoca2e16a2018-06-29 15:25:24 +0200376
377 # look if previous tasks in process
378 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", vim_id, order_id)
379 if task_dependency:
380 step = "Waiting for related tasks to be completed: {}".format(task_name)
381 self.logger.debug(logging_text + step)
382 # TODO write this to database
383 await asyncio.wait(task_dependency, timeout=3600)
384
tiernoc0e42e22018-05-11 11:36:10 +0200385 if db_vim.get("_admin") and db_vim["_admin"].get("deployed") and db_vim["_admin"]["deployed"].get("RO"):
tiernofe1c37f2018-05-17 22:58:04 +0200386 if vim_content.get("config") and vim_content["config"].get("sdn-controller"):
387 step = "Getting sdn-controller-id='{}' from db".format(vim_content["config"]["sdn-controller"])
388 db_sdn = self.db.get_one("sdns", {"_id": vim_content["config"]["sdn-controller"]})
tiernoca2e16a2018-06-29 15:25:24 +0200389
390 # look if previous tasks in process
391 task_name, task_dependency = self.lcm_tasks.lookfor_related("sdn", db_sdn["_id"])
392 if task_dependency:
393 step = "Waiting for related tasks to be completed: {}".format(task_name)
394 self.logger.debug(logging_text + step)
395 # TODO write this to database
396 await asyncio.wait(task_dependency, timeout=3600)
397
tiernofe1c37f2018-05-17 22:58:04 +0200398 if db_sdn.get("_admin") and db_sdn["_admin"].get("deployed") and db_sdn["_admin"]["deployed"].get(
399 "RO"):
400 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
401 else:
402 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
403 vim_content["config"]["sdn-controller"]))
404
tiernoc0e42e22018-05-11 11:36:10 +0200405 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
406 step = "Editing vim at RO"
407 RO = ROclient.ROClient(self.loop, **self.ro_config)
408 vim_RO = deepcopy(vim_content)
409 vim_RO.pop("_id", None)
410 vim_RO.pop("_admin", None)
411 vim_RO.pop("schema_version", None)
412 vim_RO.pop("schema_type", None)
413 vim_RO.pop("vim_tenant_name", None)
tiernofe1c37f2018-05-17 22:58:04 +0200414 if "vim_type" in vim_RO:
415 vim_RO["type"] = vim_RO.pop("vim_type")
tiernoc0e42e22018-05-11 11:36:10 +0200416 vim_RO.pop("vim_user", None)
417 vim_RO.pop("vim_password", None)
tiernofe1c37f2018-05-17 22:58:04 +0200418 if RO_sdn_id:
419 vim_RO["config"]["sdn-controller"] = RO_sdn_id
420 # TODO make a deep update of sdn-port-mapping
tiernoc0e42e22018-05-11 11:36:10 +0200421 if vim_RO:
tierno750b2452018-05-17 16:39:29 +0200422 await RO.edit("vim", RO_vim_id, descriptor=vim_RO)
tiernoc0e42e22018-05-11 11:36:10 +0200423
424 step = "Editing vim-account at RO tenant"
tiernofe1c37f2018-05-17 22:58:04 +0200425 vim_account_RO = {}
426 if "config" in vim_content:
427 if "sdn-controller" in vim_content["config"]:
428 del vim_content["config"]["sdn-controller"]
429 if "sdn-port-mapping" in vim_content["config"]:
430 del vim_content["config"]["sdn-port-mapping"]
431 if not vim_content["config"]:
432 del vim_content["config"]
tiernoc0e42e22018-05-11 11:36:10 +0200433 for k in ("vim_tenant_name", "vim_password", "config"):
434 if k in vim_content:
tiernofe1c37f2018-05-17 22:58:04 +0200435 vim_account_RO[k] = vim_content[k]
tiernoc0e42e22018-05-11 11:36:10 +0200436 if "vim_user" in vim_content:
437 vim_content["vim_username"] = vim_content["vim_user"]
tierno93028912018-06-28 15:26:54 +0200438 # vim_account must be edited always even if empty in order to ensure changes are translated to RO
439 # vim_thread. RO will remove and relaunch a new thread for this vim_account
440 await RO.edit("vim_account", RO_vim_id, descriptor=vim_account_RO)
tiernoca2e16a2018-06-29 15:25:24 +0200441 db_vim_update["_admin.operationalState"] = "ENABLED"
tiernoc0e42e22018-05-11 11:36:10 +0200442
tiernoca2e16a2018-06-29 15:25:24 +0200443 self.logger.debug(logging_text + "Exit Ok RO_vim_id={}".format(RO_vim_id))
444 return
tiernoc0e42e22018-05-11 11:36:10 +0200445
446 except (ROclient.ROClientException, DbException) as e:
447 self.logger.error(logging_text + "Exit Exception {}".format(e))
448 exc = e
449 except Exception as e:
450 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
451 exc = e
452 finally:
453 if exc and db_vim:
tiernoca2e16a2018-06-29 15:25:24 +0200454 db_vim_update["_admin.operationalState"] = "ERROR"
455 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
456 if db_vim_update:
457 self.update_db_2("vim_accounts", vim_id, db_vim_update)
458 self.lcm_tasks.remove("vim_account", vim_id, order_id)
tiernoc0e42e22018-05-11 11:36:10 +0200459
460 async def vim_delete(self, vim_id, order_id):
461 logging_text = "Task vim_delete={} ".format(vim_id)
462 self.logger.debug(logging_text + "Enter")
463 db_vim = None
tiernoca2e16a2018-06-29 15:25:24 +0200464 db_vim_update = {}
tiernoc0e42e22018-05-11 11:36:10 +0200465 exc = None
466 step = "Getting vim from db"
467 try:
468 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
469 if db_vim.get("_admin") and db_vim["_admin"].get("deployed") and db_vim["_admin"]["deployed"].get("RO"):
470 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
471 RO = ROclient.ROClient(self.loop, **self.ro_config)
472 step = "Detaching vim from RO tenant"
473 try:
474 await RO.detach_datacenter(RO_vim_id)
475 except ROclient.ROClientException as e:
476 if e.http_code == 404: # not found
477 self.logger.debug(logging_text + "RO_vim_id={} already detached".format(RO_vim_id))
478 else:
479 raise
480
481 step = "Deleting vim from RO"
482 try:
483 await RO.delete("vim", RO_vim_id)
484 except ROclient.ROClientException as e:
485 if e.http_code == 404: # not found
486 self.logger.debug(logging_text + "RO_vim_id={} already deleted".format(RO_vim_id))
487 else:
488 raise
489 else:
490 # nothing to delete
tiernoca2e16a2018-06-29 15:25:24 +0200491 self.logger.error(logging_text + "Nohing to remove at RO")
tiernoc0e42e22018-05-11 11:36:10 +0200492 self.db.del_one("vim_accounts", {"_id": vim_id})
tiernoca2e16a2018-06-29 15:25:24 +0200493 self.logger.debug(logging_text + "Exit Ok")
494 return
tiernoc0e42e22018-05-11 11:36:10 +0200495
496 except (ROclient.ROClientException, DbException) as e:
497 self.logger.error(logging_text + "Exit Exception {}".format(e))
498 exc = e
499 except Exception as e:
500 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
501 exc = e
502 finally:
tiernoca2e16a2018-06-29 15:25:24 +0200503 self.lcm_tasks.remove("vim_account", vim_id, order_id)
tiernoc0e42e22018-05-11 11:36:10 +0200504 if exc and db_vim:
tiernoca2e16a2018-06-29 15:25:24 +0200505 db_vim_update["_admin.operationalState"] = "ERROR"
506 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
507 if db_vim_update:
508 self.update_db_2("vim_accounts", vim_id, db_vim_update)
509 self.lcm_tasks.remove("vim_account", vim_id, order_id)
tiernoc0e42e22018-05-11 11:36:10 +0200510
511 async def sdn_create(self, sdn_content, order_id):
512 sdn_id = sdn_content["_id"]
513 logging_text = "Task sdn_create={} ".format(sdn_id)
514 self.logger.debug(logging_text + "Enter")
515 db_sdn = None
tiernoca2e16a2018-06-29 15:25:24 +0200516 db_sdn_update = {}
517 RO_sdn_id = None
tiernoc0e42e22018-05-11 11:36:10 +0200518 exc = None
519 try:
520 step = "Getting sdn from db"
521 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
tiernoca2e16a2018-06-29 15:25:24 +0200522 db_sdn_update["_admin.deployed.RO"] = None
tiernoc0e42e22018-05-11 11:36:10 +0200523
524 step = "Creating sdn at RO"
525 RO = ROclient.ROClient(self.loop, **self.ro_config)
526 sdn_RO = deepcopy(sdn_content)
527 sdn_RO.pop("_id", None)
528 sdn_RO.pop("_admin", None)
529 sdn_RO.pop("schema_version", None)
530 sdn_RO.pop("schema_type", None)
531 sdn_RO.pop("description", None)
532 desc = await RO.create("sdn", descriptor=sdn_RO)
533 RO_sdn_id = desc["uuid"]
tiernoca2e16a2018-06-29 15:25:24 +0200534 db_sdn_update["_admin.deployed.RO"] = RO_sdn_id
535 db_sdn_update["_admin.operationalState"] = "ENABLED"
536 self.logger.debug(logging_text + "Exit Ok RO_sdn_id={}".format(RO_sdn_id))
537 return
tiernoc0e42e22018-05-11 11:36:10 +0200538
539 except (ROclient.ROClientException, DbException) as e:
540 self.logger.error(logging_text + "Exit Exception {}".format(e))
541 exc = e
542 except Exception as e:
543 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
544 exc = e
545 finally:
546 if exc and db_sdn:
tiernoca2e16a2018-06-29 15:25:24 +0200547 db_sdn_update["_admin.operationalState"] = "ERROR"
548 db_sdn_update["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
549 if db_sdn_update:
550 self.update_db_2("sdns", sdn_id, db_sdn_update)
551 self.lcm_tasks.remove("sdn", sdn_id, order_id)
tiernoc0e42e22018-05-11 11:36:10 +0200552
553 async def sdn_edit(self, sdn_content, order_id):
554 sdn_id = sdn_content["_id"]
555 logging_text = "Task sdn_edit={} ".format(sdn_id)
556 self.logger.debug(logging_text + "Enter")
557 db_sdn = None
tiernoca2e16a2018-06-29 15:25:24 +0200558 db_sdn_update = {}
tiernoc0e42e22018-05-11 11:36:10 +0200559 exc = None
560 step = "Getting sdn from db"
561 try:
562 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
563 if db_sdn.get("_admin") and db_sdn["_admin"].get("deployed") and db_sdn["_admin"]["deployed"].get("RO"):
564 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
565 RO = ROclient.ROClient(self.loop, **self.ro_config)
566 step = "Editing sdn at RO"
567 sdn_RO = deepcopy(sdn_content)
568 sdn_RO.pop("_id", None)
569 sdn_RO.pop("_admin", None)
570 sdn_RO.pop("schema_version", None)
571 sdn_RO.pop("schema_type", None)
572 sdn_RO.pop("description", None)
573 if sdn_RO:
tierno750b2452018-05-17 16:39:29 +0200574 await RO.edit("sdn", RO_sdn_id, descriptor=sdn_RO)
tiernoca2e16a2018-06-29 15:25:24 +0200575 db_sdn_update["_admin.operationalState"] = "ENABLED"
tiernoc0e42e22018-05-11 11:36:10 +0200576
577 self.logger.debug(logging_text + "Exit Ok RO_sdn_id".format(RO_sdn_id))
tiernoca2e16a2018-06-29 15:25:24 +0200578 return
tiernoc0e42e22018-05-11 11:36:10 +0200579
580 except (ROclient.ROClientException, DbException) as e:
581 self.logger.error(logging_text + "Exit Exception {}".format(e))
582 exc = e
583 except Exception as e:
584 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
585 exc = e
586 finally:
587 if exc and db_sdn:
tiernoca2e16a2018-06-29 15:25:24 +0200588 db_sdn["_admin.operationalState"] = "ERROR"
589 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
590 if db_sdn_update:
591 self.update_db_2("sdns", sdn_id, db_sdn_update)
592 self.lcm_tasks.remove("sdn", sdn_id, order_id)
tiernoc0e42e22018-05-11 11:36:10 +0200593
594 async def sdn_delete(self, sdn_id, order_id):
595 logging_text = "Task sdn_delete={} ".format(sdn_id)
596 self.logger.debug(logging_text + "Enter")
597 db_sdn = None
tiernoca2e16a2018-06-29 15:25:24 +0200598 db_sdn_update = {}
tiernoc0e42e22018-05-11 11:36:10 +0200599 exc = None
600 step = "Getting sdn from db"
601 try:
602 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
603 if db_sdn.get("_admin") and db_sdn["_admin"].get("deployed") and db_sdn["_admin"]["deployed"].get("RO"):
604 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
605 RO = ROclient.ROClient(self.loop, **self.ro_config)
606 step = "Deleting sdn from RO"
607 try:
608 await RO.delete("sdn", RO_sdn_id)
609 except ROclient.ROClientException as e:
610 if e.http_code == 404: # not found
611 self.logger.debug(logging_text + "RO_sdn_id={} already deleted".format(RO_sdn_id))
612 else:
613 raise
614 else:
615 # nothing to delete
616 self.logger.error(logging_text + "Skipping. There is not RO information at database")
617 self.db.del_one("sdns", {"_id": sdn_id})
618 self.logger.debug("sdn_delete task sdn_id={} Exit Ok".format(sdn_id))
tiernoca2e16a2018-06-29 15:25:24 +0200619 return
tiernoc0e42e22018-05-11 11:36:10 +0200620
621 except (ROclient.ROClientException, DbException) as e:
622 self.logger.error(logging_text + "Exit Exception {}".format(e))
623 exc = e
624 except Exception as e:
625 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
626 exc = e
627 finally:
628 if exc and db_sdn:
tiernoca2e16a2018-06-29 15:25:24 +0200629 db_sdn["_admin.operationalState"] = "ERROR"
630 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
631 if db_sdn_update:
632 self.update_db_2("sdns", sdn_id, db_sdn_update)
633 self.lcm_tasks.remove("sdn", sdn_id, order_id)
tiernoc0e42e22018-05-11 11:36:10 +0200634
635 def vnfd2RO(self, vnfd, new_id=None):
636 """
637 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
638 :param vnfd: input vnfd
639 :param new_id: overrides vnf id if provided
640 :return: copy of vnfd
641 """
642 ci_file = None
643 try:
644 vnfd_RO = deepcopy(vnfd)
645 vnfd_RO.pop("_id", None)
646 vnfd_RO.pop("_admin", None)
647 if new_id:
648 vnfd_RO["id"] = new_id
649 for vdu in vnfd_RO["vdu"]:
650 if "cloud-init-file" in vdu:
651 base_folder = vnfd["_admin"]["storage"]
652 clout_init_file = "{}/{}/cloud_init/{}".format(
653 base_folder["folder"],
654 base_folder["pkg-dir"],
655 vdu["cloud-init-file"]
656 )
657 ci_file = self.fs.file_open(clout_init_file, "r")
tierno750b2452018-05-17 16:39:29 +0200658 # TODO: detect if binary or text. Propose to read as binary and try to decode to utf8. If fails
659 # convert to base 64 or similar
tiernoc0e42e22018-05-11 11:36:10 +0200660 clout_init_content = ci_file.read()
661 ci_file.close()
662 ci_file = None
663 vdu.pop("cloud-init-file", None)
664 vdu["cloud-init"] = clout_init_content
tierno22f4f9c2018-06-11 18:53:39 +0200665 # remnove unused by RO configuration, monitoring, scaling
666 vnfd_RO.pop("vnf-configuration", None)
667 vnfd_RO.pop("monitoring-param", None)
668 vnfd_RO.pop("scaling-group-descriptor", None)
tiernoc0e42e22018-05-11 11:36:10 +0200669 return vnfd_RO
670 except FsException as e:
671 raise LcmException("Error reading file at vnfd {}: {} ".format(vnfd["_id"], e))
672 finally:
673 if ci_file:
674 ci_file.close()
675
tierno6e9d2eb2018-09-12 17:47:18 +0200676 def n2vc_callback(self, model_name, application_name, status, message, n2vc_info, task=None):
tiernoc0e42e22018-05-11 11:36:10 +0200677 """
678 Callback both for charm status change and task completion
679 :param model_name: Charm model name
680 :param application_name: Charm application name
681 :param status: Can be
682 - blocked: The unit needs manual intervention
683 - maintenance: The unit is actively deploying/configuring
684 - waiting: The unit is waiting for another charm to be ready
685 - active: The unit is deployed, configured, and ready
686 - error: The charm has failed and needs attention.
687 - terminated: The charm has been destroyed
688 - removing,
689 - removed
690 :param message: detailed message error
tierno6e9d2eb2018-09-12 17:47:18 +0200691 :param n2vc_info dictionary with information shared with instantiate task. Contains:
692 nsr_id:
693 nslcmop_id:
694 lcmOperationType: currently "instantiate"
695 deployed: dictionary with {<application>: {operational-status: <status>, detailed-status: <text>}}
696 db_update: dictionary to be filled with the changes to be wrote to database with format key.key.key: value
697 n2vc_event: event used to notify instantiation task that some change has been produced
tiernoc0e42e22018-05-11 11:36:10 +0200698 :param task: None for charm status change, or task for completion task callback
699 :return:
700 """
tiernoc0e42e22018-05-11 11:36:10 +0200701 try:
tierno6e9d2eb2018-09-12 17:47:18 +0200702 nsr_id = n2vc_info["nsr_id"]
703 deployed = n2vc_info["deployed"]
704 db_nsr_update = n2vc_info["db_update"]
705 nslcmop_id = n2vc_info["nslcmop_id"]
706 ns_operation = n2vc_info["lcmOperationType"]
707 n2vc_event = n2vc_info["n2vc_event"]
tiernobce32152018-07-23 16:18:59 +0200708 logging_text = "Task ns={} {}={} [n2vc_callback] application={}".format(nsr_id, ns_operation, nslcmop_id,
709 application_name)
tierno6e9d2eb2018-09-12 17:47:18 +0200710 vca_deployed = deployed.get(application_name)
tiernobce32152018-07-23 16:18:59 +0200711 if not vca_deployed:
712 self.logger.error(logging_text + " Not present at nsr._admin.deployed.VCA")
713 return
tiernoc0e42e22018-05-11 11:36:10 +0200714
715 if task:
716 if task.cancelled():
717 self.logger.debug(logging_text + " task Cancelled")
tierno6e9d2eb2018-09-12 17:47:18 +0200718 vca_deployed['operational-status'] = "error"
719 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(application_name)] = "error"
720 vca_deployed['detailed-status'] = "Task Cancelled"
721 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(application_name)] = "Task Cancelled"
tiernoc0e42e22018-05-11 11:36:10 +0200722
tierno6e9d2eb2018-09-12 17:47:18 +0200723 elif task.done():
tiernoc0e42e22018-05-11 11:36:10 +0200724 exc = task.exception()
725 if exc:
726 self.logger.error(logging_text + " task Exception={}".format(exc))
tierno6e9d2eb2018-09-12 17:47:18 +0200727 vca_deployed['operational-status'] = "error"
728 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(application_name)] = "error"
729 vca_deployed['detailed-status'] = str(exc)
730 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(application_name)] = str(exc)
tiernoc0e42e22018-05-11 11:36:10 +0200731 else:
732 self.logger.debug(logging_text + " task Done")
tiernoc0e42e22018-05-11 11:36:10 +0200733 # task is Done, but callback is still ongoing. So ignore
734 return
735 elif status:
736 self.logger.debug(logging_text + " Enter status={}".format(status))
tiernobce32152018-07-23 16:18:59 +0200737 if vca_deployed['operational-status'] == status:
tiernoc0e42e22018-05-11 11:36:10 +0200738 return # same status, ignore
tiernobce32152018-07-23 16:18:59 +0200739 vca_deployed['operational-status'] = status
740 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(application_name)] = status
741 vca_deployed['detailed-status'] = str(message)
742 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(application_name)] = str(message)
tiernoc0e42e22018-05-11 11:36:10 +0200743 else:
744 self.logger.critical(logging_text + " Enter with bad parameters", exc_info=True)
745 return
tierno6e9d2eb2018-09-12 17:47:18 +0200746 # wake up instantiate task
747 n2vc_event.set()
tiernoc0e42e22018-05-11 11:36:10 +0200748 except Exception as e:
tiernobce32152018-07-23 16:18:59 +0200749 self.logger.critical(logging_text + " Exception {}".format(e), exc_info=True)
tiernoc0e42e22018-05-11 11:36:10 +0200750
tierno053422d2018-07-10 12:56:43 +0200751 def ns_params_2_RO(self, ns_params, nsd, vnfd_dict):
tiernoc0e42e22018-05-11 11:36:10 +0200752 """
753 Creates a RO ns descriptor from OSM ns_instantite params
754 :param ns_params: OSM instantiate params
755 :return: The RO ns descriptor
756 """
757 vim_2_RO = {}
tierno750b2452018-05-17 16:39:29 +0200758
tiernoc0e42e22018-05-11 11:36:10 +0200759 def vim_account_2_RO(vim_account):
760 if vim_account in vim_2_RO:
761 return vim_2_RO[vim_account]
tiernoca2e16a2018-06-29 15:25:24 +0200762
tiernoc0e42e22018-05-11 11:36:10 +0200763 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
tiernoc0e42e22018-05-11 11:36:10 +0200764 if db_vim["_admin"]["operationalState"] != "ENABLED":
765 raise LcmException("VIM={} is not available. operationalState={}".format(
766 vim_account, db_vim["_admin"]["operationalState"]))
767 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
768 vim_2_RO[vim_account] = RO_vim_id
769 return RO_vim_id
770
tierno053422d2018-07-10 12:56:43 +0200771 def ip_profile_2_RO(ip_profile):
772 RO_ip_profile = deepcopy((ip_profile))
773 if "dns-server" in RO_ip_profile:
garciadeblas7876a342018-08-28 13:21:24 +0200774 if isinstance(RO_ip_profile["dns-server"], list):
775 RO_ip_profile["dns-address"] = []
776 for ds in RO_ip_profile.pop("dns-server"):
777 RO_ip_profile["dns-address"].append(ds['address'])
778 else:
779 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
tierno053422d2018-07-10 12:56:43 +0200780 if RO_ip_profile.get("ip-version") == "ipv4":
781 RO_ip_profile["ip-version"] = "IPv4"
782 if RO_ip_profile.get("ip-version") == "ipv6":
783 RO_ip_profile["ip-version"] = "IPv6"
784 if "dhcp-params" in RO_ip_profile:
785 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
786 return RO_ip_profile
787
tiernoc0e42e22018-05-11 11:36:10 +0200788 if not ns_params:
789 return None
790 RO_ns_params = {
791 # "name": ns_params["nsName"],
792 # "description": ns_params.get("nsDescription"),
793 "datacenter": vim_account_2_RO(ns_params["vimAccountId"]),
794 # "scenario": ns_params["nsdId"],
795 "vnfs": {},
796 "networks": {},
797 }
798 if ns_params.get("ssh-authorized-key"):
799 RO_ns_params["cloud-config"] = {"key-pairs": ns_params["ssh-authorized-key"]}
800 if ns_params.get("vnf"):
tierno053422d2018-07-10 12:56:43 +0200801 for vnf_params in ns_params["vnf"]:
802 for constituent_vnfd in nsd["constituent-vnfd"]:
803 if constituent_vnfd["member-vnf-index"] == vnf_params["member-vnf-index"]:
804 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
805 break
806 else:
807 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
808 "constituent-vnfd".format(vnf_params["member-vnf-index"]))
809 RO_vnf = {"vdus": {}, "networks": {}}
810 if vnf_params.get("vimAccountId"):
811 RO_vnf["datacenter"] = vim_account_2_RO(vnf_params["vimAccountId"])
812 if vnf_params.get("vdu"):
813 for vdu_params in vnf_params["vdu"]:
814 RO_vnf["vdus"][vdu_params["id"]] = {}
815 if vdu_params.get("volume"):
816 RO_vnf["vdus"][vdu_params["id"]]["devices"] = {}
817 for volume_params in vdu_params["volume"]:
818 RO_vnf["vdus"][vdu_params["id"]]["devices"][volume_params["name"]] = {}
819 if volume_params.get("vim-volume-id"):
820 RO_vnf["vdus"][vdu_params["id"]]["devices"][volume_params["name"]]["vim_id"] = \
821 volume_params["vim-volume-id"]
822 if vdu_params.get("interface"):
823 RO_vnf["vdus"][vdu_params["id"]]["interfaces"] = {}
824 for interface_params in vdu_params["interface"]:
825 RO_interface = {}
826 RO_vnf["vdus"][vdu_params["id"]]["interfaces"][interface_params["name"]] = RO_interface
827 if interface_params.get("ip-address"):
828 RO_interface["ip_address"] = interface_params["ip-address"]
829 if interface_params.get("mac-address"):
830 RO_interface["mac_address"] = interface_params["mac-address"]
831 if interface_params.get("floating-ip-required"):
832 RO_interface["floating-ip"] = interface_params["floating-ip-required"]
833 if vnf_params.get("internal-vld"):
834 for internal_vld_params in vnf_params["internal-vld"]:
835 RO_vnf["networks"][internal_vld_params["name"]] = {}
836 if internal_vld_params.get("vim-network-name"):
837 RO_vnf["networks"][internal_vld_params["name"]]["vim-network-name"] = \
838 internal_vld_params["vim-network-name"]
839 if internal_vld_params.get("ip-profile"):
840 RO_vnf["networks"][internal_vld_params["name"]]["ip-profile"] = \
841 ip_profile_2_RO(internal_vld_params["ip-profile"])
842 if internal_vld_params.get("internal-connection-point"):
843 for icp_params in internal_vld_params["internal-connection-point"]:
844 # look for interface
845 iface_found = False
846 for vdu_descriptor in vnf_descriptor["vdu"]:
847 for vdu_interface in vdu_descriptor["interface"]:
848 if vdu_interface.get("internal-connection-point-ref") == icp_params["id-ref"]:
tierno98768132018-09-11 12:07:21 +0200849 RO_interface_update = {}
850 if icp_params.get("ip-address"):
851 RO_interface_update["ip_address"] = icp_params["ip-address"]
852 if icp_params.get("mac-address"):
853 RO_interface_update["mac_address"] = icp_params["mac-address"]
854 if RO_interface_update:
855 RO_vnf_update = {"vdus": {vdu_descriptor["id"]: {
856 "interfaces": {vdu_interface["name"]: RO_interface_update}}}}
857 deep_update(RO_vnf, RO_vnf_update)
tierno053422d2018-07-10 12:56:43 +0200858 iface_found = True
859 break
860 if iface_found:
861 break
862 else:
863 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
864 "internal-vld:id-ref={} is not present at vnfd:internal-"
865 "connection-point".format(vnf_params["member-vnf-index"],
866 icp_params["id-ref"]))
867
868 if not RO_vnf["vdus"]:
869 del RO_vnf["vdus"]
870 if not RO_vnf["networks"]:
871 del RO_vnf["networks"]
tiernoc0e42e22018-05-11 11:36:10 +0200872 if RO_vnf:
tierno053422d2018-07-10 12:56:43 +0200873 RO_ns_params["vnfs"][vnf_params["member-vnf-index"]] = RO_vnf
tiernoc0e42e22018-05-11 11:36:10 +0200874 if ns_params.get("vld"):
tierno053422d2018-07-10 12:56:43 +0200875 for vld_params in ns_params["vld"]:
tiernoc0e42e22018-05-11 11:36:10 +0200876 RO_vld = {}
tierno053422d2018-07-10 12:56:43 +0200877 if "ip-profile" in vld_params:
878 RO_vld["ip-profile"] = ip_profile_2_RO(vld_params["ip-profile"])
879 if "vim-network-name" in vld_params:
tiernoc0e42e22018-05-11 11:36:10 +0200880 RO_vld["sites"] = []
tierno053422d2018-07-10 12:56:43 +0200881 if isinstance(vld_params["vim-network-name"], dict):
882 for vim_account, vim_net in vld_params["vim-network-name"].items():
tiernoc0e42e22018-05-11 11:36:10 +0200883 RO_vld["sites"].append({
884 "netmap-use": vim_net,
885 "datacenter": vim_account_2_RO(vim_account)
886 })
tierno750b2452018-05-17 16:39:29 +0200887 else: # isinstance str
tierno053422d2018-07-10 12:56:43 +0200888 RO_vld["sites"].append({"netmap-use": vld_params["vim-network-name"]})
tierno98768132018-09-11 12:07:21 +0200889 if "vnfd-connection-point-ref" in vld_params:
890 for cp_params in vld_params["vnfd-connection-point-ref"]:
891 # look for interface
892 for constituent_vnfd in nsd["constituent-vnfd"]:
893 if constituent_vnfd["member-vnf-index"] == cp_params["member-vnf-index-ref"]:
894 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
895 break
896 else:
897 raise LcmException(
898 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
899 "is not present at nsd:constituent-vnfd".format(cp_params["member-vnf-index-ref"]))
900 match_cp = False
901 for vdu_descriptor in vnf_descriptor["vdu"]:
902 for interface_descriptor in vdu_descriptor["interface"]:
903 if interface_descriptor.get("external-connection-point-ref") == \
904 cp_params["vnfd-connection-point-ref"]:
905 match_cp = True
906 break
907 if match_cp:
908 break
909 else:
910 raise LcmException(
911 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
912 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
913 cp_params["member-vnf-index-ref"],
914 cp_params["vnfd-connection-point-ref"],
915 vnf_descriptor["id"]))
916 RO_cp_params = {}
917 if cp_params.get("ip-address"):
918 RO_cp_params["ip_address"] = cp_params["ip-address"]
919 if cp_params.get("mac-address"):
920 RO_cp_params["mac_address"] = cp_params["mac-address"]
921 if RO_cp_params:
922 RO_vnf_params = {
923 cp_params["member-vnf-index-ref"]: {
924 "vdus": {
925 vdu_descriptor["id"]: {
926 "interfaces": {
927 interface_descriptor["name"]: RO_cp_params
928 }
929 }
930 }
931 }
932 }
933 deep_update(RO_ns_params["vnfs"], RO_vnf_params)
tiernoc0e42e22018-05-11 11:36:10 +0200934 if RO_vld:
tierno053422d2018-07-10 12:56:43 +0200935 RO_ns_params["networks"][vld_params["name"]] = RO_vld
tiernoc0e42e22018-05-11 11:36:10 +0200936 return RO_ns_params
937
tiernobce32152018-07-23 16:18:59 +0200938 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
tierno22f4f9c2018-06-11 18:53:39 +0200939 """
940 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
941 :param db_vnfrs:
942 :param nsr_desc_RO:
943 :return:
944 """
945 for vnf_index, db_vnfr in db_vnfrs.items():
946 for vnf_RO in nsr_desc_RO["vnfs"]:
947 if vnf_RO["member_vnf_index"] == vnf_index:
948 vnfr_update = {}
949 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO.get("ip_address")
950 vdur_list = []
951 for vdur_RO in vnf_RO.get("vms", ()):
952 vdur = {
953 "vim-id": vdur_RO.get("vim_vm_id"),
954 "ip-address": vdur_RO.get("ip_address"),
955 "vdu-id-ref": vdur_RO.get("vdu_osm_id"),
956 "name": vdur_RO.get("vim_name"),
957 "status": vdur_RO.get("status"),
958 "status-detailed": vdur_RO.get("error_msg"),
959 "interfaces": []
960 }
961
962 for interface_RO in vdur_RO.get("interfaces", ()):
963 vdur["interfaces"].append({
964 "ip-address": interface_RO.get("ip_address"),
965 "mac-address": interface_RO.get("mac_address"),
966 "name": interface_RO.get("external_name"),
967 })
968 vdur_list.append(vdur)
969 db_vnfr["vdur"] = vnfr_update["vdur"] = vdur_list
970 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
971 break
972
973 else:
tiernobce32152018-07-23 16:18:59 +0200974 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} at RO info".format(vnf_index))
tierno22f4f9c2018-06-11 18:53:39 +0200975
976 async def create_monitoring(self, nsr_id, vnf_member_index, vnfd_desc):
977 if not vnfd_desc.get("scaling-group-descriptor"):
978 return
979 for scaling_group in vnfd_desc["scaling-group-descriptor"]:
980 scaling_policy_desc = {}
981 scaling_desc = {
982 "ns_id": nsr_id,
983 "scaling_group_descriptor": {
984 "name": scaling_group["name"],
985 "scaling_policy": scaling_policy_desc
986 }
987 }
988 for scaling_policy in scaling_group.get("scaling-policy"):
989 scaling_policy_desc["scale_in_operation_type"] = scaling_policy_desc["scale_out_operation_type"] = \
990 scaling_policy["scaling-type"]
991 scaling_policy_desc["threshold_time"] = scaling_policy["threshold-time"]
992 scaling_policy_desc["cooldown_time"] = scaling_policy["cooldown-time"]
993 scaling_policy_desc["scaling_criteria"] = []
994 for scaling_criteria in scaling_policy.get("scaling-criteria"):
995 scaling_criteria_desc = {"scale_in_threshold": scaling_criteria.get("scale-in-threshold"),
996 "scale_out_threshold": scaling_criteria.get("scale-out-threshold"),
997 }
998 if not scaling_criteria.get("vnf-monitoring-param-ref"):
999 continue
1000 for monitoring_param in vnfd_desc.get("monitoring-param", ()):
1001 if monitoring_param["id"] == scaling_criteria["vnf-monitoring-param-ref"]:
1002 scaling_criteria_desc["monitoring_param"] = {
1003 "id": monitoring_param["id"],
1004 "name": monitoring_param["name"],
1005 "aggregation_type": monitoring_param.get("aggregation-type"),
1006 "vdu_name": monitoring_param.get("vdu-ref"),
1007 "vnf_member_index": vnf_member_index,
1008 }
1009
1010 scaling_policy_desc["scaling_criteria"].append(scaling_criteria_desc)
1011 break
1012 else:
1013 self.logger.error(
1014 "Task ns={} member_vnf_index={} Invalid vnfd vnf-monitoring-param-ref={} not in "
1015 "monitoring-param list".format(nsr_id, vnf_member_index,
1016 scaling_criteria["vnf-monitoring-param-ref"]))
1017
1018 await self.msg.aiowrite("lcm_pm", "configure_scaling", scaling_desc, self.loop)
1019
tiernoc0e42e22018-05-11 11:36:10 +02001020 async def ns_instantiate(self, nsr_id, nslcmop_id):
1021 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
1022 self.logger.debug(logging_text + "Enter")
1023 # get all needed from database
1024 db_nsr = None
1025 db_nslcmop = None
tierno22f4f9c2018-06-11 18:53:39 +02001026 db_nsr_update = {}
1027 db_nslcmop_update = {}
tierno6e9d2eb2018-09-12 17:47:18 +02001028 nslcmop_operation_state = None
tierno22f4f9c2018-06-11 18:53:39 +02001029 db_vnfrs = {}
1030 RO_descriptor_number = 0 # number of descriptors created at RO
1031 descriptor_id_2_RO = {} # map between vnfd/nsd id to the id used at RO
tierno6e9d2eb2018-09-12 17:47:18 +02001032 n2vc_info = {}
tiernoc0e42e22018-05-11 11:36:10 +02001033 exc = None
tiernoc0e42e22018-05-11 11:36:10 +02001034 try:
tierno35b0be72018-05-21 15:13:44 +02001035 step = "Getting nslcmop={} from db".format(nslcmop_id)
tiernoc0e42e22018-05-11 11:36:10 +02001036 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
tierno35b0be72018-05-21 15:13:44 +02001037 step = "Getting nsr={} from db".format(nsr_id)
tiernoc0e42e22018-05-11 11:36:10 +02001038 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tierno053422d2018-07-10 12:56:43 +02001039 ns_params = db_nsr.get("instantiate_params")
tiernoc0e42e22018-05-11 11:36:10 +02001040 nsd = db_nsr["nsd"]
1041 nsr_name = db_nsr["name"] # TODO short-name??
1042 needed_vnfd = {}
1043 vnfr_filter = {"nsr-id-ref": nsr_id, "member-vnf-index-ref": None}
1044 for c_vnf in nsd["constituent-vnfd"]:
1045 vnfd_id = c_vnf["vnfd-id-ref"]
1046 vnfr_filter["member-vnf-index-ref"] = c_vnf["member-vnf-index"]
tierno22f4f9c2018-06-11 18:53:39 +02001047 step = "Getting vnfr={} of nsr={} from db".format(c_vnf["member-vnf-index"], nsr_id)
1048 db_vnfrs[c_vnf["member-vnf-index"]] = self.db.get_one("vnfrs", vnfr_filter)
tiernoc0e42e22018-05-11 11:36:10 +02001049 if vnfd_id not in needed_vnfd:
1050 step = "Getting vnfd={} from db".format(vnfd_id)
1051 needed_vnfd[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
1052
1053 nsr_lcm = db_nsr["_admin"].get("deployed")
1054 if not nsr_lcm:
1055 nsr_lcm = db_nsr["_admin"]["deployed"] = {
1056 "id": nsr_id,
1057 "RO": {"vnfd_id": {}, "nsd_id": None, "nsr_id": None, "nsr_status": "SCHEDULED"},
1058 "nsr_ip": {},
1059 "VCA": {},
1060 }
tierno22f4f9c2018-06-11 18:53:39 +02001061 db_nsr_update["detailed-status"] = "creating"
1062 db_nsr_update["operational-status"] = "init"
tiernoc0e42e22018-05-11 11:36:10 +02001063
1064 RO = ROclient.ROClient(self.loop, **self.ro_config)
1065
1066 # get vnfds, instantiate at RO
1067 for vnfd_id, vnfd in needed_vnfd.items():
tierno22f4f9c2018-06-11 18:53:39 +02001068 step = db_nsr_update["detailed-status"] = "Creating vnfd={} at RO".format(vnfd_id)
tierno35b0be72018-05-21 15:13:44 +02001069 # self.logger.debug(logging_text + step)
tierno22f4f9c2018-06-11 18:53:39 +02001070 vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, vnfd_id[:23])
1071 descriptor_id_2_RO[vnfd_id] = vnfd_id_RO
1072 RO_descriptor_number += 1
tiernoc0e42e22018-05-11 11:36:10 +02001073
1074 # look if present
1075 vnfd_list = await RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
1076 if vnfd_list:
tierno22f4f9c2018-06-11 18:53:39 +02001077 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id)] = vnfd_list[0]["uuid"]
tierno35b0be72018-05-21 15:13:44 +02001078 self.logger.debug(logging_text + "vnfd={} exists at RO. Using RO_id={}".format(
tiernoc0e42e22018-05-11 11:36:10 +02001079 vnfd_id, vnfd_list[0]["uuid"]))
1080 else:
1081 vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO)
1082 desc = await RO.create("vnfd", descriptor=vnfd_RO)
tierno22f4f9c2018-06-11 18:53:39 +02001083 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id)] = desc["uuid"]
1084 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
tierno35b0be72018-05-21 15:13:44 +02001085 self.logger.debug(logging_text + "vnfd={} created at RO. RO_id={}".format(
1086 vnfd_id, desc["uuid"]))
tierno22f4f9c2018-06-11 18:53:39 +02001087 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoc0e42e22018-05-11 11:36:10 +02001088
1089 # create nsd at RO
1090 nsd_id = nsd["id"]
tierno22f4f9c2018-06-11 18:53:39 +02001091 step = db_nsr_update["detailed-status"] = "Creating nsd={} at RO".format(nsd_id)
tierno35b0be72018-05-21 15:13:44 +02001092 # self.logger.debug(logging_text + step)
tiernoc0e42e22018-05-11 11:36:10 +02001093
tierno22f4f9c2018-06-11 18:53:39 +02001094 RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_id[:23])
1095 descriptor_id_2_RO[nsd_id] = RO_osm_nsd_id
1096 RO_descriptor_number += 1
1097 nsd_list = await RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
tiernoc0e42e22018-05-11 11:36:10 +02001098 if nsd_list:
tierno22f4f9c2018-06-11 18:53:39 +02001099 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
tierno35b0be72018-05-21 15:13:44 +02001100 self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
tierno22f4f9c2018-06-11 18:53:39 +02001101 nsd_id, RO_nsd_uuid))
tiernoc0e42e22018-05-11 11:36:10 +02001102 else:
1103 nsd_RO = deepcopy(nsd)
tierno22f4f9c2018-06-11 18:53:39 +02001104 nsd_RO["id"] = RO_osm_nsd_id
tiernoc0e42e22018-05-11 11:36:10 +02001105 nsd_RO.pop("_id", None)
1106 nsd_RO.pop("_admin", None)
1107 for c_vnf in nsd_RO["constituent-vnfd"]:
1108 vnfd_id = c_vnf["vnfd-id-ref"]
tierno22f4f9c2018-06-11 18:53:39 +02001109 c_vnf["vnfd-id-ref"] = descriptor_id_2_RO[vnfd_id]
tiernoc0e42e22018-05-11 11:36:10 +02001110 desc = await RO.create("nsd", descriptor=nsd_RO)
tierno22f4f9c2018-06-11 18:53:39 +02001111 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1112 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
1113 self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_id, RO_nsd_uuid))
1114 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoc0e42e22018-05-11 11:36:10 +02001115
1116 # Crate ns at RO
1117 # if present use it unless in error status
tierno22f4f9c2018-06-11 18:53:39 +02001118 RO_nsr_id = db_nsr["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
tiernoc0e42e22018-05-11 11:36:10 +02001119 if RO_nsr_id:
1120 try:
tierno22f4f9c2018-06-11 18:53:39 +02001121 step = db_nsr_update["detailed-status"] = "Looking for existing ns at RO"
tierno35b0be72018-05-21 15:13:44 +02001122 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
tiernoc0e42e22018-05-11 11:36:10 +02001123 desc = await RO.show("ns", RO_nsr_id)
1124 except ROclient.ROClientException as e:
1125 if e.http_code != HTTPStatus.NOT_FOUND:
1126 raise
tierno22f4f9c2018-06-11 18:53:39 +02001127 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
tiernoc0e42e22018-05-11 11:36:10 +02001128 if RO_nsr_id:
1129 ns_status, ns_status_info = RO.check_ns_status(desc)
tierno22f4f9c2018-06-11 18:53:39 +02001130 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
tiernoc0e42e22018-05-11 11:36:10 +02001131 if ns_status == "ERROR":
tierno22f4f9c2018-06-11 18:53:39 +02001132 step = db_nsr_update["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id)
tierno35b0be72018-05-21 15:13:44 +02001133 self.logger.debug(logging_text + step)
tiernoc0e42e22018-05-11 11:36:10 +02001134 await RO.delete("ns", RO_nsr_id)
tierno22f4f9c2018-06-11 18:53:39 +02001135 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
tiernoc0e42e22018-05-11 11:36:10 +02001136 if not RO_nsr_id:
tierno22f4f9c2018-06-11 18:53:39 +02001137 step = db_nsr_update["detailed-status"] = "Creating ns at RO"
tierno35b0be72018-05-21 15:13:44 +02001138 # self.logger.debug(logging_text + step)
tiernoca2e16a2018-06-29 15:25:24 +02001139
1140 # check if VIM is creating and wait look if previous tasks in process
tiernoca2e16a2018-06-29 15:25:24 +02001141 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
1142 if task_dependency:
1143 step = "Waiting for related tasks to be completed: {}".format(task_name)
1144 self.logger.debug(logging_text + step)
1145 await asyncio.wait(task_dependency, timeout=3600)
1146 if ns_params.get("vnf"):
1147 for vnf in ns_params["vnf"]:
1148 if "vimAccountId" in vnf:
1149 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
1150 vnf["vimAccountId"])
1151 if task_dependency:
1152 step = "Waiting for related tasks to be completed: {}".format(task_name)
1153 self.logger.debug(logging_text + step)
1154 await asyncio.wait(task_dependency, timeout=3600)
1155
tierno053422d2018-07-10 12:56:43 +02001156 RO_ns_params = self.ns_params_2_RO(ns_params, nsd, needed_vnfd)
tiernoc0e42e22018-05-11 11:36:10 +02001157 desc = await RO.create("ns", descriptor=RO_ns_params,
1158 name=db_nsr["name"],
tierno22f4f9c2018-06-11 18:53:39 +02001159 scenario=RO_nsd_uuid)
1160 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
1161 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
1162 db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
tierno35b0be72018-05-21 15:13:44 +02001163 self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
tierno22f4f9c2018-06-11 18:53:39 +02001164 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno35b0be72018-05-21 15:13:44 +02001165
tiernoc0e42e22018-05-11 11:36:10 +02001166 # update VNFR vimAccount
1167 step = "Updating VNFR vimAcccount"
tierno22f4f9c2018-06-11 18:53:39 +02001168 for vnf_index, vnfr in db_vnfrs.items():
tiernoc0e42e22018-05-11 11:36:10 +02001169 if vnfr.get("vim-account-id"):
1170 continue
tierno22f4f9c2018-06-11 18:53:39 +02001171 vnfr_update = {"vim-account-id": db_nsr["instantiate_params"]["vimAccountId"]}
tierno09682c02018-06-27 15:06:50 +02001172 if db_nsr["instantiate_params"].get("vnf"):
1173 for vnf_params in db_nsr["instantiate_params"]["vnf"]:
1174 if vnf_params.get("member-vnf-index") == vnf_index:
1175 if vnf_params.get("vimAccountId"):
tierno22f4f9c2018-06-11 18:53:39 +02001176 vnfr_update["vim-account-id"] = vnf_params.get("vimAccountId")
tierno09682c02018-06-27 15:06:50 +02001177 break
tierno22f4f9c2018-06-11 18:53:39 +02001178 self.update_db_2("vnfrs", vnfr["_id"], vnfr_update)
tiernoc0e42e22018-05-11 11:36:10 +02001179
1180 # wait until NS is ready
tierno22f4f9c2018-06-11 18:53:39 +02001181 step = ns_status_detailed = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
1182 detailed_status_old = None
tierno35b0be72018-05-21 15:13:44 +02001183 self.logger.debug(logging_text + step)
tierno22f4f9c2018-06-11 18:53:39 +02001184
tierno750b2452018-05-17 16:39:29 +02001185 deployment_timeout = 2 * 3600 # Two hours
tiernoc0e42e22018-05-11 11:36:10 +02001186 while deployment_timeout > 0:
1187 desc = await RO.show("ns", RO_nsr_id)
1188 ns_status, ns_status_info = RO.check_ns_status(desc)
tierno22f4f9c2018-06-11 18:53:39 +02001189 db_nsr_update["admin.deployed.RO.nsr_status"] = ns_status
tiernoc0e42e22018-05-11 11:36:10 +02001190 if ns_status == "ERROR":
1191 raise ROclient.ROClientException(ns_status_info)
1192 elif ns_status == "BUILD":
tierno22f4f9c2018-06-11 18:53:39 +02001193 detailed_status = ns_status_detailed + "; {}".format(ns_status_info)
tiernoc0e42e22018-05-11 11:36:10 +02001194 elif ns_status == "ACTIVE":
tierno22f4f9c2018-06-11 18:53:39 +02001195 step = detailed_status = "Waiting for management IP address reported by the VIM"
tierno275411e2018-05-16 14:33:32 +02001196 try:
tierno22f4f9c2018-06-11 18:53:39 +02001197 nsr_lcm["nsr_ip"] = RO.get_ns_vnf_info(desc)
tierno275411e2018-05-16 14:33:32 +02001198 break
1199 except ROclient.ROClientException as e:
1200 if e.http_code != 409: # IP address is not ready return code is 409 CONFLICT
1201 raise e
tiernoc0e42e22018-05-11 11:36:10 +02001202 else:
1203 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
tierno22f4f9c2018-06-11 18:53:39 +02001204 if detailed_status != detailed_status_old:
1205 detailed_status_old = db_nsr_update["detailed-status"] = detailed_status
1206 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoc0e42e22018-05-11 11:36:10 +02001207 await asyncio.sleep(5, loop=self.loop)
1208 deployment_timeout -= 5
1209 if deployment_timeout <= 0:
1210 raise ROclient.ROClientException("Timeout waiting ns to be ready")
tierno35b0be72018-05-21 15:13:44 +02001211
tiernoc0e42e22018-05-11 11:36:10 +02001212 step = "Updating VNFRs"
tiernobce32152018-07-23 16:18:59 +02001213 self.ns_update_vnfr(db_vnfrs, desc)
tiernoc0e42e22018-05-11 11:36:10 +02001214
1215 db_nsr["detailed-status"] = "Configuring vnfr"
tierno22f4f9c2018-06-11 18:53:39 +02001216 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoc0e42e22018-05-11 11:36:10 +02001217
1218 # The parameters we'll need to deploy a charm
1219 number_to_configure = 0
1220
tierno6e9d2eb2018-09-12 17:47:18 +02001221 def deploy(vnf_index, vdu_id, mgmt_ip_address, n2vc_info, config_primitive=None):
tiernoc0e42e22018-05-11 11:36:10 +02001222 """An inner function to deploy the charm from either vnf or vdu
tiernobce32152018-07-23 16:18:59 +02001223 vnf_index is mandatory. vdu_id can be None for a vnf configuration or the id for vdu configuration
tiernoc0e42e22018-05-11 11:36:10 +02001224 """
tiernobce32152018-07-23 16:18:59 +02001225 if not mgmt_ip_address:
1226 raise LcmException("vnfd/vdu has not management ip address to configure it")
tiernoc0e42e22018-05-11 11:36:10 +02001227 # Login to the VCA.
1228 # if number_to_configure == 0:
1229 # self.logger.debug("Logging into N2VC...")
1230 # task = asyncio.ensure_future(self.n2vc.login())
1231 # yield from asyncio.wait_for(task, 30.0)
1232 # self.logger.debug("Logged into N2VC!")
1233
tierno750b2452018-05-17 16:39:29 +02001234 # # await self.n2vc.login()
tiernoc0e42e22018-05-11 11:36:10 +02001235
1236 # Note: The charm needs to exist on disk at the location
1237 # specified by charm_path.
1238 base_folder = vnfd["_admin"]["storage"]
1239 storage_params = self.fs.get_params()
1240 charm_path = "{}{}/{}/charms/{}".format(
1241 storage_params["path"],
1242 base_folder["folder"],
1243 base_folder["pkg-dir"],
1244 proxy_charm
1245 )
1246
1247 # Setup the runtime parameters for this VNF
tiernobce32152018-07-23 16:18:59 +02001248 params = {'rw_mgmt_ip': mgmt_ip_address}
1249 if config_primitive:
1250 params["initial-config-primitive"] = config_primitive
tiernoc0e42e22018-05-11 11:36:10 +02001251
1252 # ns_name will be ignored in the current version of N2VC
1253 # but will be implemented for the next point release.
1254 model_name = 'default'
tiernobce32152018-07-23 16:18:59 +02001255 vdu_id_text = "vnfd"
1256 if vdu_id:
1257 vdu_id_text = vdu_id
tiernoc0e42e22018-05-11 11:36:10 +02001258 application_name = self.n2vc.FormatApplicationName(
1259 nsr_name,
1260 vnf_index,
tiernobce32152018-07-23 16:18:59 +02001261 vdu_id_text
tiernoc0e42e22018-05-11 11:36:10 +02001262 )
tierno22f4f9c2018-06-11 18:53:39 +02001263 if not nsr_lcm.get("VCA"):
1264 nsr_lcm["VCA"] = {}
tiernobce32152018-07-23 16:18:59 +02001265 nsr_lcm["VCA"][application_name] = db_nsr_update["_admin.deployed.VCA.{}".format(application_name)] = {
1266 "member-vnf-index": vnf_index,
1267 "vdu_id": vdu_id,
tiernoc0e42e22018-05-11 11:36:10 +02001268 "model": model_name,
1269 "application": application_name,
1270 "operational-status": "init",
1271 "detailed-status": "",
1272 "vnfd_id": vnfd_id,
1273 }
tierno22f4f9c2018-06-11 18:53:39 +02001274 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoc0e42e22018-05-11 11:36:10 +02001275
tierno750b2452018-05-17 16:39:29 +02001276 self.logger.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id, charm_path,
1277 proxy_charm))
tierno6e9d2eb2018-09-12 17:47:18 +02001278 if not n2vc_info:
1279 n2vc_info["nsr_id"] = nsr_id
1280 n2vc_info["nslcmop_id"] = nslcmop_id
1281 n2vc_info["n2vc_event"] = asyncio.Event(loop=self.loop)
1282 n2vc_info["lcmOperationType"] = "instantiate"
1283 n2vc_info["deployed"] = nsr_lcm["VCA"]
1284 n2vc_info["db_update"] = db_nsr_update
tiernoc0e42e22018-05-11 11:36:10 +02001285 task = asyncio.ensure_future(
1286 self.n2vc.DeployCharms(
1287 model_name, # The network service name
1288 application_name, # The application name
1289 vnfd, # The vnf descriptor
1290 charm_path, # Path to charm
1291 params, # Runtime params, like mgmt ip
1292 {}, # for native charms only
1293 self.n2vc_callback, # Callback for status changes
tierno6e9d2eb2018-09-12 17:47:18 +02001294 n2vc_info, # Callback parameter
tiernoc0e42e22018-05-11 11:36:10 +02001295 None, # Callback parameter (task)
1296 )
1297 )
1298 task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None, None,
tierno6e9d2eb2018-09-12 17:47:18 +02001299 n2vc_info))
tiernobce32152018-07-23 16:18:59 +02001300 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "create_charm:" + application_name, task)
tiernoc0e42e22018-05-11 11:36:10 +02001301
tiernoc0e42e22018-05-11 11:36:10 +02001302 step = "Looking for needed vnfd to configure"
1303 self.logger.debug(logging_text + step)
tierno22f4f9c2018-06-11 18:53:39 +02001304
tiernoc0e42e22018-05-11 11:36:10 +02001305 for c_vnf in nsd["constituent-vnfd"]:
1306 vnfd_id = c_vnf["vnfd-id-ref"]
1307 vnf_index = str(c_vnf["member-vnf-index"])
1308 vnfd = needed_vnfd[vnfd_id]
1309
1310 # Check if this VNF has a charm configuration
1311 vnf_config = vnfd.get("vnf-configuration")
1312
1313 if vnf_config and vnf_config.get("juju"):
1314 proxy_charm = vnf_config["juju"]["charm"]
tiernobce32152018-07-23 16:18:59 +02001315 config_primitive = None
tiernoc0e42e22018-05-11 11:36:10 +02001316
1317 if proxy_charm:
1318 if 'initial-config-primitive' in vnf_config:
tiernobce32152018-07-23 16:18:59 +02001319 config_primitive = vnf_config['initial-config-primitive']
tiernoc0e42e22018-05-11 11:36:10 +02001320
tierno22f4f9c2018-06-11 18:53:39 +02001321 # Login to the VCA. If there are multiple calls to login(),
1322 # subsequent calls will be a nop and return immediately.
1323 step = "connecting to N2VC to configure vnf {}".format(vnf_index)
1324 await self.n2vc.login()
tierno6e9d2eb2018-09-12 17:47:18 +02001325 deploy(vnf_index, None, db_vnfrs[vnf_index]["ip-address"], n2vc_info, config_primitive)
tiernoc0e42e22018-05-11 11:36:10 +02001326 number_to_configure += 1
1327
1328 # Deploy charms for each VDU that supports one.
tiernobce32152018-07-23 16:18:59 +02001329 vdu_index = 0
tiernoc0e42e22018-05-11 11:36:10 +02001330 for vdu in vnfd['vdu']:
1331 vdu_config = vdu.get('vdu-configuration')
1332 proxy_charm = None
tiernobce32152018-07-23 16:18:59 +02001333 config_primitive = None
tiernoc0e42e22018-05-11 11:36:10 +02001334
1335 if vdu_config and vdu_config.get("juju"):
1336 proxy_charm = vdu_config["juju"]["charm"]
1337
1338 if 'initial-config-primitive' in vdu_config:
tiernobce32152018-07-23 16:18:59 +02001339 config_primitive = vdu_config['initial-config-primitive']
tiernoc0e42e22018-05-11 11:36:10 +02001340
1341 if proxy_charm:
tierno22f4f9c2018-06-11 18:53:39 +02001342 step = "connecting to N2VC to configure vdu {} from vnf {}".format(vdu["id"], vnf_index)
1343 await self.n2vc.login()
tiernobce32152018-07-23 16:18:59 +02001344 deploy(vnf_index, vdu["id"], db_vnfrs[vnf_index]["vdur"][vdu_index]["ip-address"],
tierno6e9d2eb2018-09-12 17:47:18 +02001345 n2vc_info, config_primitive)
tiernoc0e42e22018-05-11 11:36:10 +02001346 number_to_configure += 1
tiernobce32152018-07-23 16:18:59 +02001347 vdu_index += 1
tiernoc0e42e22018-05-11 11:36:10 +02001348
tierno6e9d2eb2018-09-12 17:47:18 +02001349 db_nsr_update["operational-status"] = "running"
1350 configuration_failed = False
tiernoc0e42e22018-05-11 11:36:10 +02001351 if number_to_configure:
tierno6e9d2eb2018-09-12 17:47:18 +02001352 old_status = "configuring: init: {}".format(number_to_configure)
1353 db_nsr_update["config-status"] = old_status
1354 db_nsr_update["detailed-status"] = old_status
1355 db_nslcmop_update["detailed-status"] = old_status
1356
1357 # wait until all are configured.
1358 while True:
1359 if db_nsr_update:
1360 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1361 if db_nslcmop_update:
1362 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1363 await n2vc_info["n2vc_event"].wait()
1364 n2vc_info["n2vc_event"].clear()
1365 all_active = True
1366 status_map = {}
1367 n2vc_error_text = [] # contain text error list. If empty no one is in error status
1368 for _, vca_info in nsr_lcm["VCA"].items():
1369 vca_status = vca_info["operational-status"]
1370 if vca_status not in status_map:
1371 # Initialize it
1372 status_map[vca_status] = 0
1373 status_map[vca_status] += 1
1374
1375 if vca_status != "active":
1376 all_active = False
1377 if vca_status in ("error", "blocked"):
1378 n2vc_error_text.append(
1379 "member_vnf_index={} vdu_id={} {}: {}".format(vca_info["member-vnf-index"],
1380 vca_info["vdu_id"], vca_status,
1381 vca_info["detailed-status"]))
1382
1383 if all_active:
1384 break
1385 elif n2vc_error_text:
1386 db_nsr_update["config-status"] = "failed"
1387 error_text = "fail configuring " + ";".join(n2vc_error_text)
1388 db_nsr_update["detailed-status"] = error_text
1389 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED_TEMP"
1390 db_nslcmop_update["detailed-status"] = error_text
1391 db_nslcmop_update["statusEnteredTime"] = time()
1392 configuration_failed = True
1393 break
1394 else:
1395 cs = "configuring: "
1396 separator = ""
1397 for status, num in status_map.items():
1398 cs += separator + "{}: {}".format(status, num)
1399 separator = ", "
1400 if old_status != cs:
1401 db_nsr_update["config-status"] = cs
1402 db_nsr_update["detailed-status"] = cs
1403 db_nslcmop_update["detailed-status"] = cs
1404 old_status = cs
1405
1406 if not configuration_failed:
1407 # all is done
1408 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
tierno22f4f9c2018-06-11 18:53:39 +02001409 db_nslcmop_update["statusEnteredTime"] = time()
1410 db_nslcmop_update["detailed-status"] = "done"
1411 db_nsr_update["config-status"] = "configured"
1412 db_nsr_update["detailed-status"] = "done"
tierno6e9d2eb2018-09-12 17:47:18 +02001413
1414 # step = "Sending monitoring parameters to PM"
tierno22f4f9c2018-06-11 18:53:39 +02001415 # for c_vnf in nsd["constituent-vnfd"]:
1416 # await self.create_monitoring(nsr_id, c_vnf["member-vnf-index"], needed_vnfd[c_vnf["vnfd-id-ref"]])
tierno22f4f9c2018-06-11 18:53:39 +02001417 return
tiernoc0e42e22018-05-11 11:36:10 +02001418
1419 except (ROclient.ROClientException, DbException, LcmException) as e:
tierno35b0be72018-05-21 15:13:44 +02001420 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
tiernoc0e42e22018-05-11 11:36:10 +02001421 exc = e
tierno22f4f9c2018-06-11 18:53:39 +02001422 except asyncio.CancelledError:
1423 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1424 exc = "Operation was cancelled"
tiernoc0e42e22018-05-11 11:36:10 +02001425 except Exception as e:
tierno22f4f9c2018-06-11 18:53:39 +02001426 exc = traceback.format_exc()
tierno35b0be72018-05-21 15:13:44 +02001427 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
1428 exc_info=True)
tiernoc0e42e22018-05-11 11:36:10 +02001429 finally:
1430 if exc:
1431 if db_nsr:
tierno22f4f9c2018-06-11 18:53:39 +02001432 db_nsr_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
1433 db_nsr_update["operational-status"] = "failed"
tiernoc0e42e22018-05-11 11:36:10 +02001434 if db_nslcmop:
tierno22f4f9c2018-06-11 18:53:39 +02001435 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
tierno6e9d2eb2018-09-12 17:47:18 +02001436 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
tierno22f4f9c2018-06-11 18:53:39 +02001437 db_nslcmop_update["statusEnteredTime"] = time()
1438 if db_nsr_update:
1439 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1440 if db_nslcmop_update:
1441 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
tierno6e9d2eb2018-09-12 17:47:18 +02001442 if nslcmop_operation_state:
1443 try:
1444 await self.msg.aiowrite("ns", "instantiated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1445 "operationState": nslcmop_operation_state})
1446 except Exception as e:
1447 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1448
1449 self.logger.debug(logging_text + "Exit")
tiernoca2e16a2018-06-29 15:25:24 +02001450 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
tiernoc0e42e22018-05-11 11:36:10 +02001451
1452 async def ns_terminate(self, nsr_id, nslcmop_id):
1453 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
1454 self.logger.debug(logging_text + "Enter")
1455 db_nsr = None
1456 db_nslcmop = None
1457 exc = None
tiernoc0e42e22018-05-11 11:36:10 +02001458 failed_detail = [] # annotates all failed error messages
1459 vca_task_list = []
1460 vca_task_dict = {}
tierno22f4f9c2018-06-11 18:53:39 +02001461 db_nsr_update = {}
1462 db_nslcmop_update = {}
tierno6e9d2eb2018-09-12 17:47:18 +02001463 nslcmop_operation_state = None
tiernoc0e42e22018-05-11 11:36:10 +02001464 try:
tierno22f4f9c2018-06-11 18:53:39 +02001465 step = "Getting nslcmop={} from db".format(nslcmop_id)
tiernoc0e42e22018-05-11 11:36:10 +02001466 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
tierno22f4f9c2018-06-11 18:53:39 +02001467 step = "Getting nsr={} from db".format(nsr_id)
tiernoc0e42e22018-05-11 11:36:10 +02001468 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1469 # nsd = db_nsr["nsd"]
tierno22f4f9c2018-06-11 18:53:39 +02001470 nsr_lcm = deepcopy(db_nsr["_admin"].get("deployed"))
tiernoc0e42e22018-05-11 11:36:10 +02001471 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
1472 return
1473 # TODO ALF remove
1474 # db_vim = self.db.get_one("vim_accounts", {"_id": db_nsr["datacenter"]})
1475 # #TODO check if VIM is creating and wait
1476 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1477
tierno22f4f9c2018-06-11 18:53:39 +02001478 db_nsr_update["operational-status"] = "terminating"
1479 db_nsr_update["config-status"] = "terminating"
tiernoc0e42e22018-05-11 11:36:10 +02001480
tierno22f4f9c2018-06-11 18:53:39 +02001481 if nsr_lcm and nsr_lcm.get("VCA"):
1482 try:
1483 step = "Scheduling configuration charms removing"
1484 db_nsr_update["detailed-status"] = "Deleting charms"
1485 self.logger.debug(logging_text + step)
1486 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernobce32152018-07-23 16:18:59 +02001487 for application_name, deploy_info in nsr_lcm["VCA"].items():
1488 if deploy_info: # TODO it would be desirable having a and deploy_info.get("deployed"):
tierno22f4f9c2018-06-11 18:53:39 +02001489 task = asyncio.ensure_future(
1490 self.n2vc.RemoveCharms(
1491 deploy_info['model'],
tiernobce32152018-07-23 16:18:59 +02001492 application_name,
tierno22f4f9c2018-06-11 18:53:39 +02001493 # self.n2vc_callback,
1494 # db_nsr,
1495 # db_nslcmop,
tierno22f4f9c2018-06-11 18:53:39 +02001496 )
tiernoc0e42e22018-05-11 11:36:10 +02001497 )
tierno22f4f9c2018-06-11 18:53:39 +02001498 vca_task_list.append(task)
tiernobce32152018-07-23 16:18:59 +02001499 vca_task_dict[application_name] = task
tierno22f4f9c2018-06-11 18:53:39 +02001500 # task.add_done_callback(functools.partial(self.n2vc_callback, deploy_info['model'],
1501 # deploy_info['application'], None, db_nsr,
1502 # db_nslcmop, vnf_index))
tiernobce32152018-07-23 16:18:59 +02001503 self.lcm_ns_tasks[nsr_id][nslcmop_id]["delete_charm:" + application_name] = task
tierno22f4f9c2018-06-11 18:53:39 +02001504 except Exception as e:
1505 self.logger.debug(logging_text + "Failed while deleting charms: {}".format(e))
tiernoc0e42e22018-05-11 11:36:10 +02001506
tierno22f4f9c2018-06-11 18:53:39 +02001507 # remove from RO
1508 RO_fail = False
tiernoc0e42e22018-05-11 11:36:10 +02001509 RO = ROclient.ROClient(self.loop, **self.ro_config)
tiernofa66d152018-08-28 10:13:45 +00001510
tiernoc0e42e22018-05-11 11:36:10 +02001511 # Delete ns
tiernofa66d152018-08-28 10:13:45 +00001512 RO_nsr_id = RO_delete_action = None
1513 if nsr_lcm and nsr_lcm.get("RO"):
1514 RO_nsr_id = nsr_lcm["RO"].get("nsr_id")
1515 RO_delete_action = nsr_lcm["RO"].get("nsr_delete_action_id")
1516 try:
1517 if RO_nsr_id:
tierno22f4f9c2018-06-11 18:53:39 +02001518 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] = "Deleting ns at RO"
tiernoc0e42e22018-05-11 11:36:10 +02001519 self.logger.debug(logging_text + step)
tiernofa66d152018-08-28 10:13:45 +00001520 desc = await RO.delete("ns", RO_nsr_id)
1521 RO_delete_action = desc["action_id"]
1522 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
tierno22f4f9c2018-06-11 18:53:39 +02001523 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1524 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
tiernofa66d152018-08-28 10:13:45 +00001525 if RO_delete_action:
1526 # wait until NS is deleted from VIM
1527 step = detailed_status = "Waiting ns deleted from VIM. RO_id={}".format(RO_nsr_id)
1528 detailed_status_old = None
1529 self.logger.debug(logging_text + step)
1530
1531 delete_timeout = 20 * 60 # 20 minutes
1532 while delete_timeout > 0:
1533 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
1534 extra_item_id=RO_delete_action)
1535 ns_status, ns_status_info = RO.check_action_status(desc)
1536 if ns_status == "ERROR":
1537 raise ROclient.ROClientException(ns_status_info)
1538 elif ns_status == "BUILD":
1539 detailed_status = step + "; {}".format(ns_status_info)
1540 elif ns_status == "ACTIVE":
1541 break
1542 else:
1543 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
1544 await asyncio.sleep(5, loop=self.loop)
1545 delete_timeout -= 5
1546 if detailed_status != detailed_status_old:
1547 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
1548 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1549 else: # delete_timeout <= 0:
1550 raise ROclient.ROClientException("Timeout waiting ns deleted from VIM")
1551
1552 except ROclient.ROClientException as e:
1553 if e.http_code == 404: # not found
1554 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
1555 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
1556 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(RO_nsr_id))
1557 elif e.http_code == 409: # conflict
1558 failed_detail.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id, e))
1559 self.logger.debug(logging_text + failed_detail[-1])
1560 RO_fail = True
1561 else:
1562 failed_detail.append("RO_ns_id={} delete error: {}".format(RO_nsr_id, e))
1563 self.logger.error(logging_text + failed_detail[-1])
1564 RO_fail = True
tiernoc0e42e22018-05-11 11:36:10 +02001565
1566 # Delete nsd
tierno22f4f9c2018-06-11 18:53:39 +02001567 if not RO_fail and nsr_lcm and nsr_lcm.get("RO") and nsr_lcm["RO"].get("nsd_id"):
1568 RO_nsd_id = nsr_lcm["RO"]["nsd_id"]
tiernoc0e42e22018-05-11 11:36:10 +02001569 try:
tierno22f4f9c2018-06-11 18:53:39 +02001570 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1571 "Deleting nsd at RO"
tierno750b2452018-05-17 16:39:29 +02001572 await RO.delete("nsd", RO_nsd_id)
tiernoc0e42e22018-05-11 11:36:10 +02001573 self.logger.debug(logging_text + "RO_nsd_id={} deleted".format(RO_nsd_id))
tierno22f4f9c2018-06-11 18:53:39 +02001574 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
tiernoc0e42e22018-05-11 11:36:10 +02001575 except ROclient.ROClientException as e:
1576 if e.http_code == 404: # not found
tierno22f4f9c2018-06-11 18:53:39 +02001577 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
tiernoc0e42e22018-05-11 11:36:10 +02001578 self.logger.debug(logging_text + "RO_nsd_id={} already deleted".format(RO_nsd_id))
tierno750b2452018-05-17 16:39:29 +02001579 elif e.http_code == 409: # conflict
tiernoc0e42e22018-05-11 11:36:10 +02001580 failed_detail.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id, e))
1581 self.logger.debug(logging_text + failed_detail[-1])
tierno22f4f9c2018-06-11 18:53:39 +02001582 RO_fail = True
tiernoc0e42e22018-05-11 11:36:10 +02001583 else:
1584 failed_detail.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id, e))
1585 self.logger.error(logging_text + failed_detail[-1])
tierno22f4f9c2018-06-11 18:53:39 +02001586 RO_fail = True
tiernoc0e42e22018-05-11 11:36:10 +02001587
tierno22f4f9c2018-06-11 18:53:39 +02001588 if not RO_fail and nsr_lcm and nsr_lcm.get("RO") and nsr_lcm["RO"].get("vnfd_id"):
1589 for vnf_id, RO_vnfd_id in nsr_lcm["RO"]["vnfd_id"].items():
1590 if not RO_vnfd_id:
1591 continue
1592 try:
1593 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1594 "Deleting vnfd={} at RO".format(vnf_id)
1595 await RO.delete("vnfd", RO_vnfd_id)
1596 self.logger.debug(logging_text + "RO_vnfd_id={} deleted".format(RO_vnfd_id))
1597 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnf_id)] = None
1598 except ROclient.ROClientException as e:
1599 if e.http_code == 404: # not found
1600 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnf_id)] = None
1601 self.logger.debug(logging_text + "RO_vnfd_id={} already deleted ".format(RO_vnfd_id))
1602 elif e.http_code == 409: # conflict
1603 failed_detail.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id, e))
1604 self.logger.debug(logging_text + failed_detail[-1])
1605 else:
1606 failed_detail.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id, e))
1607 self.logger.error(logging_text + failed_detail[-1])
tiernoc0e42e22018-05-11 11:36:10 +02001608
1609 if vca_task_list:
tierno22f4f9c2018-06-11 18:53:39 +02001610 db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1611 "Waiting for deletion of configuration charms"
1612 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1613 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tiernoc0e42e22018-05-11 11:36:10 +02001614 await asyncio.wait(vca_task_list, timeout=300)
tiernobce32152018-07-23 16:18:59 +02001615 for application_name, task in vca_task_dict.items():
tiernoc0e42e22018-05-11 11:36:10 +02001616 if task.cancelled():
tiernobce32152018-07-23 16:18:59 +02001617 failed_detail.append("VCA[{}] Deletion has been cancelled".format(application_name))
tiernoc0e42e22018-05-11 11:36:10 +02001618 elif task.done():
1619 exc = task.exception()
1620 if exc:
tiernobce32152018-07-23 16:18:59 +02001621 failed_detail.append("VCA[{}] Deletion exception: {}".format(application_name, exc))
tiernoc0e42e22018-05-11 11:36:10 +02001622 else:
tiernobce32152018-07-23 16:18:59 +02001623 db_nsr_update["_admin.deployed.VCA.{}".format(application_name)] = None
tiernoc0e42e22018-05-11 11:36:10 +02001624 else: # timeout
1625 # TODO Should it be cancelled?!!
1626 task.cancel()
tiernobce32152018-07-23 16:18:59 +02001627 failed_detail.append("VCA[{}] Deletion timeout".format(application_name))
tiernoc0e42e22018-05-11 11:36:10 +02001628
1629 if failed_detail:
1630 self.logger.error(logging_text + " ;".join(failed_detail))
tierno22f4f9c2018-06-11 18:53:39 +02001631 db_nsr_update["operational-status"] = "failed"
1632 db_nsr_update["detailed-status"] = "Deletion errors " + "; ".join(failed_detail)
1633 db_nslcmop_update["detailed-status"] = "; ".join(failed_detail)
tierno6e9d2eb2018-09-12 17:47:18 +02001634 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
tierno22f4f9c2018-06-11 18:53:39 +02001635 db_nslcmop_update["statusEnteredTime"] = time()
tiernoc0e42e22018-05-11 11:36:10 +02001636 elif db_nslcmop["operationParams"].get("autoremove"):
1637 self.db.del_one("nsrs", {"_id": nsr_id})
tierno22f4f9c2018-06-11 18:53:39 +02001638 db_nsr_update.clear()
tiernoc0e42e22018-05-11 11:36:10 +02001639 self.db.del_list("nslcmops", {"nsInstanceId": nsr_id})
tierno6e9d2eb2018-09-12 17:47:18 +02001640 nslcmop_operation_state = "COMPLETED"
tierno22f4f9c2018-06-11 18:53:39 +02001641 db_nslcmop_update.clear()
tiernoc0e42e22018-05-11 11:36:10 +02001642 self.db.del_list("vnfrs", {"nsr-id-ref": nsr_id})
tierno09682c02018-06-27 15:06:50 +02001643 self.logger.debug(logging_text + "Delete from database")
tiernoc0e42e22018-05-11 11:36:10 +02001644 else:
tierno22f4f9c2018-06-11 18:53:39 +02001645 db_nsr_update["operational-status"] = "terminated"
1646 db_nsr_update["detailed-status"] = "Done"
1647 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
1648 db_nslcmop_update["detailed-status"] = "Done"
tierno6e9d2eb2018-09-12 17:47:18 +02001649 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
tierno22f4f9c2018-06-11 18:53:39 +02001650 db_nslcmop_update["statusEnteredTime"] = time()
tiernoc0e42e22018-05-11 11:36:10 +02001651
1652 except (ROclient.ROClientException, DbException) as e:
1653 self.logger.error(logging_text + "Exit Exception {}".format(e))
1654 exc = e
tierno22f4f9c2018-06-11 18:53:39 +02001655 except asyncio.CancelledError:
1656 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1657 exc = "Operation was cancelled"
tiernoc0e42e22018-05-11 11:36:10 +02001658 except Exception as e:
tierno22f4f9c2018-06-11 18:53:39 +02001659 exc = traceback.format_exc()
tiernoc0e42e22018-05-11 11:36:10 +02001660 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
tiernoc0e42e22018-05-11 11:36:10 +02001661 finally:
1662 if exc and db_nslcmop:
tierno6e9d2eb2018-09-12 17:47:18 +02001663 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1664 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1665 db_nslcmop_update["statusEnteredTime"] = time()
tiernoc0e42e22018-05-11 11:36:10 +02001666 if db_nslcmop_update:
1667 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1668 if db_nsr_update:
1669 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno6e9d2eb2018-09-12 17:47:18 +02001670 if nslcmop_operation_state:
1671 try:
1672 await self.msg.aiowrite("ns", "terminated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1673 "operationState": nslcmop_operation_state})
1674 except Exception as e:
1675 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1676 self.logger.debug(logging_text + "Exit")
tiernoca2e16a2018-06-29 15:25:24 +02001677 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
tiernoc0e42e22018-05-11 11:36:10 +02001678
tiernobce32152018-07-23 16:18:59 +02001679 async def _ns_execute_primitive(self, db_deployed, nsr_name, member_vnf_index, vdu_id, primitive, primitive_params):
1680
1681 vdu_id_text = "vnfd"
1682 if vdu_id:
1683 vdu_id_text = vdu_id
1684 application_name = self.n2vc.FormatApplicationName(
1685 nsr_name,
1686 member_vnf_index,
1687 vdu_id_text
1688 )
1689 vca_deployed = db_deployed["VCA"].get(application_name)
tierno22f4f9c2018-06-11 18:53:39 +02001690 if not vca_deployed:
tiernobce32152018-07-23 16:18:59 +02001691 raise LcmException("charm for member_vnf_index={} vdu_id={} is not deployed".format(member_vnf_index,
1692 vdu_id))
tierno22f4f9c2018-06-11 18:53:39 +02001693 model_name = vca_deployed.get("model")
1694 application_name = vca_deployed.get("application")
1695 if not model_name or not application_name:
1696 raise LcmException("charm for member_vnf_index={} is not properly deployed".format(member_vnf_index))
1697 if vca_deployed["operational-status"] != "active":
1698 raise LcmException("charm for member_vnf_index={} operational_status={} not 'active'".format(
1699 member_vnf_index, vca_deployed["operational-status"]))
1700 callback = None # self.n2vc_callback
1701 callback_args = () # [db_nsr, db_nslcmop, member_vnf_index, None]
1702 await self.n2vc.login()
1703 task = asyncio.ensure_future(
1704 self.n2vc.ExecutePrimitive(
1705 model_name,
1706 application_name,
1707 primitive, callback,
1708 *callback_args,
1709 **primitive_params
1710 )
1711 )
1712 # task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None,
1713 # db_nsr, db_nslcmop, member_vnf_index))
1714 # self.lcm_ns_tasks[nsr_id][nslcmop_id]["action: " + primitive] = task
1715 # wait until completed with timeout
1716 await asyncio.wait((task,), timeout=600)
1717
1718 result = "FAILED" # by default
1719 result_detail = ""
1720 if task.cancelled():
1721 result_detail = "Task has been cancelled"
1722 elif task.done():
1723 exc = task.exception()
1724 if exc:
1725 result_detail = str(exc)
1726 else:
1727 # TODO revise with Adam if action is finished and ok when task is done or callback is needed
1728 result = "COMPLETED"
1729 result_detail = "Done"
1730 else: # timeout
1731 # TODO Should it be cancelled?!!
1732 task.cancel()
1733 result_detail = "timeout"
1734 return result, result_detail
1735
tiernoc0e42e22018-05-11 11:36:10 +02001736 async def ns_action(self, nsr_id, nslcmop_id):
1737 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
1738 self.logger.debug(logging_text + "Enter")
1739 # get all needed from database
1740 db_nsr = None
1741 db_nslcmop = None
tierno6e9d2eb2018-09-12 17:47:18 +02001742 db_nslcmop_update = {}
1743 nslcmop_operation_state = None
tiernoc0e42e22018-05-11 11:36:10 +02001744 exc = None
1745 try:
1746 step = "Getting information from database"
1747 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1748 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1749 nsr_lcm = db_nsr["_admin"].get("deployed")
tiernobce32152018-07-23 16:18:59 +02001750 nsr_name = db_nsr["name"]
tierno275411e2018-05-16 14:33:32 +02001751 vnf_index = db_nslcmop["operationParams"]["member_vnf_index"]
tiernobce32152018-07-23 16:18:59 +02001752 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
tiernoc0e42e22018-05-11 11:36:10 +02001753
tierno750b2452018-05-17 16:39:29 +02001754 # TODO check if ns is in a proper status
tiernoc0e42e22018-05-11 11:36:10 +02001755 primitive = db_nslcmop["operationParams"]["primitive"]
1756 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
tiernobce32152018-07-23 16:18:59 +02001757 result, result_detail = await self._ns_execute_primitive(nsr_lcm, nsr_name, vnf_index, vdu_id, primitive,
1758 primitive_params)
tierno6e9d2eb2018-09-12 17:47:18 +02001759 db_nslcmop_update["detailed-status"] = result_detail
1760 db_nslcmop_update["operationState"] = nslcmop_operation_state = result
1761 db_nslcmop_update["statusEnteredTime"] = time()
tiernoc0e42e22018-05-11 11:36:10 +02001762 self.logger.debug(logging_text + " task Done with result {} {}".format(result, result_detail))
1763 return # database update is called inside finally
1764
1765 except (DbException, LcmException) as e:
1766 self.logger.error(logging_text + "Exit Exception {}".format(e))
1767 exc = e
tierno22f4f9c2018-06-11 18:53:39 +02001768 except asyncio.CancelledError:
1769 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1770 exc = "Operation was cancelled"
tiernoc0e42e22018-05-11 11:36:10 +02001771 except Exception as e:
tierno22f4f9c2018-06-11 18:53:39 +02001772 exc = traceback.format_exc()
tiernoc0e42e22018-05-11 11:36:10 +02001773 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
tiernoc0e42e22018-05-11 11:36:10 +02001774 finally:
1775 if exc and db_nslcmop:
tierno6e9d2eb2018-09-12 17:47:18 +02001776 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1777 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1778 db_nslcmop_update["statusEnteredTime"] = time()
tiernoc0e42e22018-05-11 11:36:10 +02001779 if db_nslcmop_update:
1780 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
tierno6e9d2eb2018-09-12 17:47:18 +02001781 self.logger.debug(logging_text + "Exit")
1782 if nslcmop_operation_state:
1783 try:
1784 await self.msg.aiowrite("ns", "actioned", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1785 "operationState": nslcmop_operation_state})
1786 except Exception as e:
1787 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1788 self.logger.debug(logging_text + "Exit")
tiernoca2e16a2018-06-29 15:25:24 +02001789 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
tiernoc0e42e22018-05-11 11:36:10 +02001790
tierno22f4f9c2018-06-11 18:53:39 +02001791 async def ns_scale(self, nsr_id, nslcmop_id):
1792 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
1793 self.logger.debug(logging_text + "Enter")
1794 # get all needed from database
1795 db_nsr = None
1796 db_nslcmop = None
1797 db_nslcmop_update = {}
tierno6e9d2eb2018-09-12 17:47:18 +02001798 nslcmop_operation_state = None
tierno22f4f9c2018-06-11 18:53:39 +02001799 db_nsr_update = {}
1800 exc = None
1801 try:
1802 step = "Getting nslcmop from database"
1803 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1804 step = "Getting nsr from database"
1805 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1806 step = "Parsing scaling parameters"
tiernoca2e16a2018-06-29 15:25:24 +02001807 db_nsr_update["operational-status"] = "scaling"
1808 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno22f4f9c2018-06-11 18:53:39 +02001809 nsr_lcm = db_nsr["_admin"].get("deployed")
1810 RO_nsr_id = nsr_lcm["RO"]["nsr_id"]
1811 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
1812 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1813 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
tiernoca2e16a2018-06-29 15:25:24 +02001814 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
tierno22f4f9c2018-06-11 18:53:39 +02001815
1816 step = "Getting vnfr from database"
1817 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
1818 step = "Getting vnfd from database"
1819 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
1820 step = "Getting scaling-group-descriptor"
1821 for scaling_descriptor in db_vnfd["scaling-group-descriptor"]:
1822 if scaling_descriptor["name"] == scaling_group:
1823 break
1824 else:
1825 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
1826 "at vnfd:scaling-group-descriptor".format(scaling_group))
tiernoca2e16a2018-06-29 15:25:24 +02001827 # cooldown_time = 0
1828 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
1829 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
1830 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
1831 # break
tierno22f4f9c2018-06-11 18:53:39 +02001832
1833 # TODO check if ns is in a proper status
1834 step = "Sending scale order to RO"
1835 nb_scale_op = 0
1836 if not db_nsr["_admin"].get("scaling-group"):
1837 self.update_db_2("nsrs", nsr_id, {"_admin.scaling-group": [{"name": scaling_group, "nb-scale-op": 0}]})
1838 admin_scale_index = 0
1839 else:
1840 for admin_scale_index, admin_scale_info in enumerate(db_nsr["_admin"]["scaling-group"]):
1841 if admin_scale_info["name"] == scaling_group:
1842 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
1843 break
1844 RO_scaling_info = []
1845 vdu_scaling_info = {"scaling_group_name": scaling_group, "vdu": []}
1846 if scaling_type == "SCALE_OUT":
1847 # count if max-instance-count is reached
1848 if "max-instance-count" in scaling_descriptor and scaling_descriptor["max-instance-count"] is not None:
1849 max_instance_count = int(scaling_descriptor["max-instance-count"])
1850 if nb_scale_op >= max_instance_count:
1851 raise LcmException("reached the limit of {} (max-instance-count) scaling-out operations for the"
1852 " scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
1853 nb_scale_op = nb_scale_op + 1
1854 vdu_scaling_info["scaling_direction"] = "OUT"
1855 vdu_scaling_info["vdu-create"] = {}
1856 for vdu_scale_info in scaling_descriptor["vdu"]:
1857 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
1858 "type": "create", "count": vdu_scale_info.get("count", 1)})
1859 vdu_scaling_info["vdu-create"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
1860 elif scaling_type == "SCALE_IN":
1861 # count if min-instance-count is reached
1862 if "min-instance-count" in scaling_descriptor and scaling_descriptor["min-instance-count"] is not None:
1863 min_instance_count = int(scaling_descriptor["min-instance-count"])
1864 if nb_scale_op <= min_instance_count:
1865 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
1866 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
1867 nb_scale_op = nb_scale_op - 1
1868 vdu_scaling_info["scaling_direction"] = "IN"
1869 vdu_scaling_info["vdu-delete"] = {}
1870 for vdu_scale_info in scaling_descriptor["vdu"]:
1871 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
1872 "type": "delete", "count": vdu_scale_info.get("count", 1)})
1873 vdu_scaling_info["vdu-delete"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
1874
1875 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
1876 if vdu_scaling_info["scaling_direction"] == "IN":
1877 for vdur in reversed(db_vnfr["vdur"]):
1878 if vdu_scaling_info["vdu-delete"].get(vdur["vdu-id-ref"]):
1879 vdu_scaling_info["vdu-delete"][vdur["vdu-id-ref"]] -= 1
1880 vdu_scaling_info["vdu"].append({
1881 "name": vdur["name"],
1882 "vdu_id": vdur["vdu-id-ref"],
1883 "interface": []
1884 })
1885 for interface in vdur["interfaces"]:
1886 vdu_scaling_info["vdu"][-1]["interface"].append({
1887 "name": interface["name"],
1888 "ip_address": interface["ip-address"],
1889 "mac_address": interface.get("mac-address"),
1890 })
1891 del vdu_scaling_info["vdu-delete"]
1892
1893 # execute primitive service PRE-SCALING
1894 step = "Executing pre-scale vnf-config-primitive"
1895 if scaling_descriptor.get("scaling-config-action"):
1896 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
1897 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "pre-scale-in" \
1898 and scaling_type == "SCALE_IN":
1899 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
1900 step = db_nslcmop_update["detailed-status"] = \
1901 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive)
1902 # look for primitive
1903 primitive_params = {}
1904 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
1905 if config_primitive["name"] == vnf_config_primitive:
1906 for parameter in config_primitive.get("parameter", ()):
1907 if 'default-value' in parameter and \
1908 parameter['default-value'] == "<VDU_SCALE_INFO>":
1909 primitive_params[parameter["name"]] = yaml.safe_dump(vdu_scaling_info,
1910 default_flow_style=True,
1911 width=256)
1912 break
1913 else:
1914 raise LcmException(
1915 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
1916 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-cnfiguration:config-"
1917 "primitive".format(scaling_group, config_primitive))
1918 result, result_detail = await self._ns_execute_primitive(nsr_lcm, vnf_index,
1919 vnf_config_primitive, primitive_params)
1920 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
1921 vnf_config_primitive, result, result_detail))
1922 if result == "FAILED":
1923 raise LcmException(result_detail)
1924
1925 if RO_scaling_info:
1926 RO = ROclient.ROClient(self.loop, **self.ro_config)
1927 RO_desc = await RO.create_action("ns", RO_nsr_id, {"vdu-scaling": RO_scaling_info})
1928 db_nsr_update["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)] = nb_scale_op
1929 db_nsr_update["_admin.scaling-group.{}.time".format(admin_scale_index)] = time()
1930 # TODO mark db_nsr_update as scaling
1931 # wait until ready
1932 RO_nslcmop_id = RO_desc["instance_action_id"]
1933 db_nslcmop_update["_admin.deploy.RO"] = RO_nslcmop_id
1934
1935 RO_task_done = False
1936 step = detailed_status = "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id)
1937 detailed_status_old = None
1938 self.logger.debug(logging_text + step)
1939
1940 deployment_timeout = 1 * 3600 # One hours
1941 while deployment_timeout > 0:
1942 if not RO_task_done:
1943 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
1944 extra_item_id=RO_nslcmop_id)
1945 ns_status, ns_status_info = RO.check_action_status(desc)
1946 if ns_status == "ERROR":
1947 raise ROclient.ROClientException(ns_status_info)
1948 elif ns_status == "BUILD":
1949 detailed_status = step + "; {}".format(ns_status_info)
1950 elif ns_status == "ACTIVE":
1951 RO_task_done = True
1952 step = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
1953 self.logger.debug(logging_text + step)
1954 else:
1955 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
1956 else:
1957 desc = await RO.show("ns", RO_nsr_id)
1958 ns_status, ns_status_info = RO.check_ns_status(desc)
1959 if ns_status == "ERROR":
1960 raise ROclient.ROClientException(ns_status_info)
1961 elif ns_status == "BUILD":
1962 detailed_status = step + "; {}".format(ns_status_info)
1963 elif ns_status == "ACTIVE":
1964 step = detailed_status = "Waiting for management IP address reported by the VIM"
1965 try:
1966 desc = await RO.show("ns", RO_nsr_id)
1967 nsr_lcm["nsr_ip"] = RO.get_ns_vnf_info(desc)
1968 break
1969 except ROclient.ROClientException as e:
1970 if e.http_code != 409: # IP address is not ready return code is 409 CONFLICT
1971 raise e
1972 else:
1973 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
1974 if detailed_status != detailed_status_old:
1975 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
1976 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1977
1978 await asyncio.sleep(5, loop=self.loop)
1979 deployment_timeout -= 5
1980 if deployment_timeout <= 0:
1981 raise ROclient.ROClientException("Timeout waiting ns to be ready")
1982
1983 step = "Updating VNFRs"
tiernobce32152018-07-23 16:18:59 +02001984 self.ns_update_vnfr({db_vnfr["member-vnf-index-ref"]: db_vnfr}, desc)
tierno22f4f9c2018-06-11 18:53:39 +02001985
1986 # update VDU_SCALING_INFO with the obtained ip_addresses
1987 if vdu_scaling_info["scaling_direction"] == "OUT":
1988 for vdur in reversed(db_vnfr["vdur"]):
1989 if vdu_scaling_info["vdu-create"].get(vdur["vdu-id-ref"]):
1990 vdu_scaling_info["vdu-create"][vdur["vdu-id-ref"]] -= 1
1991 vdu_scaling_info["vdu"].append({
1992 "name": vdur["name"],
1993 "vdu_id": vdur["vdu-id-ref"],
1994 "interface": []
1995 })
1996 for interface in vdur["interfaces"]:
1997 vdu_scaling_info["vdu"][-1]["interface"].append({
1998 "name": interface["name"],
1999 "ip_address": interface["ip-address"],
2000 "mac_address": interface.get("mac-address"),
2001 })
2002 del vdu_scaling_info["vdu-create"]
2003
2004 if db_nsr_update:
2005 self.update_db_2("nsrs", nsr_id, db_nsr_update)
2006
2007 # execute primitive service POST-SCALING
2008 step = "Executing post-scale vnf-config-primitive"
2009 if scaling_descriptor.get("scaling-config-action"):
2010 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
2011 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "post-scale-out" \
2012 and scaling_type == "SCALE_OUT":
2013 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
2014 step = db_nslcmop_update["detailed-status"] = \
2015 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive)
2016 # look for primitive
2017 primitive_params = {}
2018 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
2019 if config_primitive["name"] == vnf_config_primitive:
2020 for parameter in config_primitive.get("parameter", ()):
2021 if 'default-value' in parameter and \
2022 parameter['default-value'] == "<VDU_SCALE_INFO>":
2023 primitive_params[parameter["name"]] = yaml.safe_dump(vdu_scaling_info,
2024 default_flow_style=True,
2025 width=256)
2026 break
2027 else:
2028 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2029 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
2030 "match any vnf-cnfiguration:config-primitive".format(scaling_group,
2031 config_primitive))
2032 result, result_detail = await self._ns_execute_primitive(nsr_lcm, vnf_index,
2033 vnf_config_primitive, primitive_params)
2034 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
2035 vnf_config_primitive, result, result_detail))
2036 if result == "FAILED":
2037 raise LcmException(result_detail)
2038
tierno6e9d2eb2018-09-12 17:47:18 +02002039 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
tierno22f4f9c2018-06-11 18:53:39 +02002040 db_nslcmop_update["statusEnteredTime"] = time()
2041 db_nslcmop_update["detailed-status"] = "done"
2042 db_nsr_update["detailed-status"] = "done"
tiernoca2e16a2018-06-29 15:25:24 +02002043 db_nsr_update["operational-status"] = "running"
tierno22f4f9c2018-06-11 18:53:39 +02002044 return
2045 except (ROclient.ROClientException, DbException, LcmException) as e:
2046 self.logger.error(logging_text + "Exit Exception {}".format(e))
2047 exc = e
2048 except asyncio.CancelledError:
2049 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
2050 exc = "Operation was cancelled"
2051 except Exception as e:
2052 exc = traceback.format_exc()
2053 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
2054 finally:
2055 if exc:
tierno22f4f9c2018-06-11 18:53:39 +02002056 if db_nslcmop:
tierno6e9d2eb2018-09-12 17:47:18 +02002057 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
2058 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
2059 db_nslcmop_update["statusEnteredTime"] = time()
tiernoca2e16a2018-06-29 15:25:24 +02002060 if db_nsr:
2061 db_nsr_update["operational-status"] = "FAILED {}: {}".format(step, exc),
2062 db_nsr_update["detailed-status"] = "failed"
tierno22f4f9c2018-06-11 18:53:39 +02002063 if db_nslcmop_update:
2064 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
2065 if db_nsr_update:
2066 self.update_db_2("nsrs", nsr_id, db_nsr_update)
tierno6e9d2eb2018-09-12 17:47:18 +02002067 if nslcmop_operation_state:
2068 try:
2069 await self.msg.aiowrite("ns", "scaled", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
2070 "operationState": nslcmop_operation_state})
2071 # if cooldown_time:
2072 # await asyncio.sleep(cooldown_time)
2073 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2074 except Exception as e:
2075 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
2076 self.logger.debug(logging_text + "Exit")
tiernoca2e16a2018-06-29 15:25:24 +02002077 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")
tierno22f4f9c2018-06-11 18:53:39 +02002078
tiernoc0e42e22018-05-11 11:36:10 +02002079 async def test(self, param=None):
2080 self.logger.debug("Starting/Ending test task: {}".format(param))
2081
tiernoc0e42e22018-05-11 11:36:10 +02002082 async def kafka_ping(self):
2083 self.logger.debug("Task kafka_ping Enter")
2084 consecutive_errors = 0
2085 first_start = True
2086 kafka_has_received = False
2087 self.pings_not_received = 1
2088 while True:
2089 try:
tierno750b2452018-05-17 16:39:29 +02002090 await self.msg.aiowrite("admin", "ping", {"from": "lcm", "to": "lcm"}, self.loop)
tiernoc0e42e22018-05-11 11:36:10 +02002091 # time between pings are low when it is not received and at starting
2092 wait_time = 5 if not kafka_has_received else 120
2093 if not self.pings_not_received:
2094 kafka_has_received = True
2095 self.pings_not_received += 1
2096 await asyncio.sleep(wait_time, loop=self.loop)
2097 if self.pings_not_received > 10:
2098 raise LcmException("It is not receiving pings from Kafka bus")
2099 consecutive_errors = 0
2100 first_start = False
2101 except LcmException:
2102 raise
2103 except Exception as e:
2104 # if not first_start is the first time after starting. So leave more time and wait
2105 # to allow kafka starts
2106 if consecutive_errors == 8 if not first_start else 30:
2107 self.logger.error("Task kafka_read task exit error too many errors. Exception: {}".format(e))
2108 raise
2109 consecutive_errors += 1
2110 self.logger.error("Task kafka_read retrying after Exception {}".format(e))
2111 wait_time = 1 if not first_start else 5
2112 await asyncio.sleep(wait_time, loop=self.loop)
2113
2114 async def kafka_read(self):
2115 self.logger.debug("Task kafka_read Enter")
2116 order_id = 1
2117 # future = asyncio.Future()
2118 consecutive_errors = 0
2119 first_start = True
2120 while consecutive_errors < 10:
2121 try:
2122 topics = ("admin", "ns", "vim_account", "sdn")
2123 topic, command, params = await self.msg.aioread(topics, self.loop)
tierno35b0be72018-05-21 15:13:44 +02002124 if topic != "admin" and command != "ping":
2125 self.logger.debug("Task kafka_read receives {} {}: {}".format(topic, command, params))
tiernoc0e42e22018-05-11 11:36:10 +02002126 consecutive_errors = 0
2127 first_start = False
2128 order_id += 1
2129 if command == "exit":
2130 print("Bye!")
2131 break
2132 elif command.startswith("#"):
2133 continue
2134 elif command == "echo":
2135 # just for test
2136 print(params)
2137 sys.stdout.flush()
2138 continue
2139 elif command == "test":
2140 asyncio.Task(self.test(params), loop=self.loop)
2141 continue
2142
2143 if topic == "admin":
2144 if command == "ping" and params["to"] == "lcm" and params["from"] == "lcm":
2145 self.pings_not_received = 0
2146 continue
2147 elif topic == "ns":
2148 if command == "instantiate":
2149 # self.logger.debug("Deploying NS {}".format(nsr_id))
2150 nslcmop = params
2151 nslcmop_id = nslcmop["_id"]
2152 nsr_id = nslcmop["nsInstanceId"]
2153 task = asyncio.ensure_future(self.ns_instantiate(nsr_id, nslcmop_id))
tiernoca2e16a2018-06-29 15:25:24 +02002154 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_instantiate", task)
tiernoc0e42e22018-05-11 11:36:10 +02002155 continue
2156 elif command == "terminate":
2157 # self.logger.debug("Deleting NS {}".format(nsr_id))
2158 nslcmop = params
2159 nslcmop_id = nslcmop["_id"]
2160 nsr_id = nslcmop["nsInstanceId"]
tiernoca2e16a2018-06-29 15:25:24 +02002161 self.lcm_tasks.cancel(topic, nsr_id)
tiernoc0e42e22018-05-11 11:36:10 +02002162 task = asyncio.ensure_future(self.ns_terminate(nsr_id, nslcmop_id))
tiernoca2e16a2018-06-29 15:25:24 +02002163 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_terminate", task)
tiernoc0e42e22018-05-11 11:36:10 +02002164 continue
2165 elif command == "action":
2166 # self.logger.debug("Update NS {}".format(nsr_id))
2167 nslcmop = params
2168 nslcmop_id = nslcmop["_id"]
2169 nsr_id = nslcmop["nsInstanceId"]
2170 task = asyncio.ensure_future(self.ns_action(nsr_id, nslcmop_id))
tiernoca2e16a2018-06-29 15:25:24 +02002171 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_action", task)
tiernoc0e42e22018-05-11 11:36:10 +02002172 continue
tierno22f4f9c2018-06-11 18:53:39 +02002173 elif command == "scale":
2174 # self.logger.debug("Update NS {}".format(nsr_id))
2175 nslcmop = params
2176 nslcmop_id = nslcmop["_id"]
2177 nsr_id = nslcmop["nsInstanceId"]
2178 task = asyncio.ensure_future(self.ns_scale(nsr_id, nslcmop_id))
tiernoca2e16a2018-06-29 15:25:24 +02002179 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "ns_scale", task)
tierno22f4f9c2018-06-11 18:53:39 +02002180 continue
tiernoc0e42e22018-05-11 11:36:10 +02002181 elif command == "show":
2182 try:
2183 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
tierno750b2452018-05-17 16:39:29 +02002184 print("nsr:\n _id={}\n operational-status: {}\n config-status: {}"
2185 "\n detailed-status: {}\n deploy: {}\n tasks: {}"
2186 "".format(nsr_id, db_nsr["operational-status"], db_nsr["config-status"],
2187 db_nsr["detailed-status"],
2188 db_nsr["_admin"]["deployed"], self.lcm_ns_tasks.get(nsr_id)))
tiernoc0e42e22018-05-11 11:36:10 +02002189 except Exception as e:
2190 print("nsr {} not found: {}".format(nsr_id, e))
2191 sys.stdout.flush()
2192 continue
2193 elif command == "deleted":
2194 continue # TODO cleaning of task just in case should be done
tiernoca2e16a2018-06-29 15:25:24 +02002195 elif command in ("terminated", "instantiated", "scaled", "actioned"): # "scaled-cooldown-time"
2196 continue
tiernoc0e42e22018-05-11 11:36:10 +02002197 elif topic == "vim_account":
2198 vim_id = params["_id"]
2199 if command == "create":
2200 task = asyncio.ensure_future(self.vim_create(params, order_id))
tiernoca2e16a2018-06-29 15:25:24 +02002201 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_create", task)
tiernoc0e42e22018-05-11 11:36:10 +02002202 continue
2203 elif command == "delete":
tiernoca2e16a2018-06-29 15:25:24 +02002204 self.lcm_tasks.cancel(topic, vim_id)
tiernoc0e42e22018-05-11 11:36:10 +02002205 task = asyncio.ensure_future(self.vim_delete(vim_id, order_id))
tiernoca2e16a2018-06-29 15:25:24 +02002206 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_delete", task)
tiernoc0e42e22018-05-11 11:36:10 +02002207 continue
2208 elif command == "show":
2209 print("not implemented show with vim_account")
2210 sys.stdout.flush()
2211 continue
2212 elif command == "edit":
tiernofe1c37f2018-05-17 22:58:04 +02002213 task = asyncio.ensure_future(self.vim_edit(params, order_id))
tiernoca2e16a2018-06-29 15:25:24 +02002214 self.lcm_tasks.register("vim_account", vim_id, order_id, "vim_edit", task)
tiernoc0e42e22018-05-11 11:36:10 +02002215 continue
2216 elif topic == "sdn":
2217 _sdn_id = params["_id"]
2218 if command == "create":
2219 task = asyncio.ensure_future(self.sdn_create(params, order_id))
tiernoca2e16a2018-06-29 15:25:24 +02002220 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_create", task)
tiernoc0e42e22018-05-11 11:36:10 +02002221 continue
2222 elif command == "delete":
tiernoca2e16a2018-06-29 15:25:24 +02002223 self.lcm_tasks.cancel(topic, _sdn_id)
tiernoc0e42e22018-05-11 11:36:10 +02002224 task = asyncio.ensure_future(self.sdn_delete(_sdn_id, order_id))
tiernoca2e16a2018-06-29 15:25:24 +02002225 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_delete", task)
tiernoc0e42e22018-05-11 11:36:10 +02002226 continue
2227 elif command == "edit":
tiernofe1c37f2018-05-17 22:58:04 +02002228 task = asyncio.ensure_future(self.sdn_edit(params, order_id))
tiernoca2e16a2018-06-29 15:25:24 +02002229 self.lcm_tasks.register("sdn", _sdn_id, order_id, "sdn_edit", task)
tiernoc0e42e22018-05-11 11:36:10 +02002230 continue
2231 self.logger.critical("unknown topic {} and command '{}'".format(topic, command))
2232 except Exception as e:
2233 # if not first_start is the first time after starting. So leave more time and wait
2234 # to allow kafka starts
2235 if consecutive_errors == 8 if not first_start else 30:
2236 self.logger.error("Task kafka_read task exit error too many errors. Exception: {}".format(e))
2237 raise
2238 consecutive_errors += 1
2239 self.logger.error("Task kafka_read retrying after Exception {}".format(e))
2240 wait_time = 2 if not first_start else 5
2241 await asyncio.sleep(wait_time, loop=self.loop)
2242
2243 # self.logger.debug("Task kafka_read terminating")
2244 self.logger.debug("Task kafka_read exit")
2245
2246 def start(self):
2247 self.loop = asyncio.get_event_loop()
tierno22f4f9c2018-06-11 18:53:39 +02002248
2249 # check RO version
2250 self.loop.run_until_complete(self.check_RO_version())
2251
tiernoc0e42e22018-05-11 11:36:10 +02002252 self.loop.run_until_complete(asyncio.gather(
2253 self.kafka_read(),
2254 self.kafka_ping()
2255 ))
2256 # TODO
2257 # self.logger.debug("Terminating cancelling creation tasks")
tiernoca2e16a2018-06-29 15:25:24 +02002258 # self.lcm_tasks.cancel("ALL", "create")
tiernoc0e42e22018-05-11 11:36:10 +02002259 # timeout = 200
2260 # while self.is_pending_tasks():
2261 # self.logger.debug("Task kafka_read terminating. Waiting for tasks termination")
2262 # await asyncio.sleep(2, loop=self.loop)
2263 # timeout -= 2
2264 # if not timeout:
tiernoca2e16a2018-06-29 15:25:24 +02002265 # self.lcm_tasks.cancel("ALL", "ALL")
tiernoc0e42e22018-05-11 11:36:10 +02002266 self.loop.close()
2267 self.loop = None
2268 if self.db:
2269 self.db.db_disconnect()
2270 if self.msg:
2271 self.msg.disconnect()
2272 if self.fs:
2273 self.fs.fs_disconnect()
2274
tiernoc0e42e22018-05-11 11:36:10 +02002275 def read_config_file(self, config_file):
2276 # TODO make a [ini] + yaml inside parser
2277 # the configparser library is not suitable, because it does not admit comments at the end of line,
2278 # and not parse integer or boolean
2279 try:
2280 with open(config_file) as f:
2281 conf = yaml.load(f)
2282 for k, v in environ.items():
2283 if not k.startswith("OSMLCM_"):
2284 continue
2285 k_items = k.lower().split("_")
2286 c = conf
2287 try:
2288 for k_item in k_items[1:-1]:
2289 if k_item in ("ro", "vca"):
2290 # put in capital letter
2291 k_item = k_item.upper()
2292 c = c[k_item]
2293 if k_items[-1] == "port":
2294 c[k_items[-1]] = int(v)
2295 else:
2296 c[k_items[-1]] = v
2297 except Exception as e:
2298 self.logger.warn("skipping environ '{}' on exception '{}'".format(k, e))
2299
2300 return conf
2301 except Exception as e:
2302 self.logger.critical("At config file '{}': {}".format(config_file, e))
2303 exit(1)
2304
2305
tierno275411e2018-05-16 14:33:32 +02002306def usage():
2307 print("""Usage: {} [options]
2308 -c|--config [configuration_file]: loads the configuration file (default: ./nbi.cfg)
2309 -h|--help: shows this help
2310 """.format(sys.argv[0]))
tierno750b2452018-05-17 16:39:29 +02002311 # --log-socket-host HOST: send logs to this host")
2312 # --log-socket-port PORT: send logs using this port (default: 9022)")
tierno275411e2018-05-16 14:33:32 +02002313
2314
tiernoc0e42e22018-05-11 11:36:10 +02002315if __name__ == '__main__':
tierno275411e2018-05-16 14:33:32 +02002316 try:
2317 # load parameters and configuration
2318 opts, args = getopt.getopt(sys.argv[1:], "hc:", ["config=", "help"])
2319 # TODO add "log-socket-host=", "log-socket-port=", "log-file="
2320 config_file = None
2321 for o, a in opts:
2322 if o in ("-h", "--help"):
2323 usage()
2324 sys.exit()
2325 elif o in ("-c", "--config"):
2326 config_file = a
2327 # elif o == "--log-socket-port":
2328 # log_socket_port = a
2329 # elif o == "--log-socket-host":
2330 # log_socket_host = a
2331 # elif o == "--log-file":
2332 # log_file = a
2333 else:
2334 assert False, "Unhandled option"
2335 if config_file:
2336 if not path.isfile(config_file):
2337 print("configuration file '{}' that not exist".format(config_file), file=sys.stderr)
2338 exit(1)
2339 else:
2340 for config_file in (__file__[:__file__.rfind(".")] + ".cfg", "./lcm.cfg", "/etc/osm/lcm.cfg"):
2341 if path.isfile(config_file):
2342 break
2343 else:
2344 print("No configuration file 'nbi.cfg' found neither at local folder nor at /etc/osm/", file=sys.stderr)
2345 exit(1)
2346 lcm = Lcm(config_file)
2347 lcm.start()
tierno22f4f9c2018-06-11 18:53:39 +02002348 except (LcmException, getopt.GetoptError) as e:
tierno275411e2018-05-16 14:33:32 +02002349 print(str(e), file=sys.stderr)
2350 # usage()
2351 exit(1)