feature 6314: Control LCM operations over ns instance
[osm/LCM.git] / osm_lcm / ns.py
1 #!/usr/bin/python3
2 # -*- coding: utf-8 -*-
3
4 import asyncio
5 import yaml
6 import logging
7 import logging.handlers
8 import functools
9 import traceback
10
11 import ROclient
12 from lcm_utils import LcmException, LcmBase
13
14 from osm_common.dbbase import DbException, deep_update
15 from osm_common.fsbase import FsException
16 from n2vc.vnf import N2VC
17
18 from copy import deepcopy
19 from http import HTTPStatus
20 from time import time
21
22
23 __author__ = "Alfonso Tierno"
24
25
26 class NsLcm(LcmBase):
27
28 def __init__(self, db, msg, fs, lcm_tasks, ro_config, vca_config, loop):
29 """
30 Init, Connect to database, filesystem storage, and messaging
31 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
32 :return: None
33 """
34 # logging
35 self.logger = logging.getLogger('lcm.ns')
36 self.loop = loop
37 self.lcm_tasks = lcm_tasks
38
39 super().__init__(db, msg, fs, self.logger)
40
41 self.ro_config = ro_config
42
43 self.n2vc = N2VC(
44 log=self.logger,
45 server=vca_config['host'],
46 port=vca_config['port'],
47 user=vca_config['user'],
48 secret=vca_config['secret'],
49 # TODO: This should point to the base folder where charms are stored,
50 # if there is a common one (like object storage). Otherwise, leave
51 # it unset and pass it via DeployCharms
52 # artifacts=vca_config[''],
53 artifacts=None,
54 )
55
56 def vnfd2RO(self, vnfd, new_id=None):
57 """
58 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
59 :param vnfd: input vnfd
60 :param new_id: overrides vnf id if provided
61 :return: copy of vnfd
62 """
63 ci_file = None
64 try:
65 vnfd_RO = deepcopy(vnfd)
66 vnfd_RO.pop("_id", None)
67 vnfd_RO.pop("_admin", None)
68 if new_id:
69 vnfd_RO["id"] = new_id
70 for vdu in vnfd_RO["vdu"]:
71 if "cloud-init-file" in vdu:
72 base_folder = vnfd["_admin"]["storage"]
73 clout_init_file = "{}/{}/cloud_init/{}".format(
74 base_folder["folder"],
75 base_folder["pkg-dir"],
76 vdu["cloud-init-file"]
77 )
78 ci_file = self.fs.file_open(clout_init_file, "r")
79 # TODO: detect if binary or text. Propose to read as binary and try to decode to utf8. If fails
80 # convert to base 64 or similar
81 clout_init_content = ci_file.read()
82 ci_file.close()
83 ci_file = None
84 vdu.pop("cloud-init-file", None)
85 vdu["cloud-init"] = clout_init_content
86 # remnove unused by RO configuration, monitoring, scaling
87 vnfd_RO.pop("vnf-configuration", None)
88 vnfd_RO.pop("monitoring-param", None)
89 vnfd_RO.pop("scaling-group-descriptor", None)
90 return vnfd_RO
91 except FsException as e:
92 raise LcmException("Error reading file at vnfd {}: {} ".format(vnfd["_id"], e))
93 finally:
94 if ci_file:
95 ci_file.close()
96
97 def n2vc_callback(self, model_name, application_name, status, message, n2vc_info, task=None):
98 """
99 Callback both for charm status change and task completion
100 :param model_name: Charm model name
101 :param application_name: Charm application name
102 :param status: Can be
103 - blocked: The unit needs manual intervention
104 - maintenance: The unit is actively deploying/configuring
105 - waiting: The unit is waiting for another charm to be ready
106 - active: The unit is deployed, configured, and ready
107 - error: The charm has failed and needs attention.
108 - terminated: The charm has been destroyed
109 - removing,
110 - removed
111 :param message: detailed message error
112 :param n2vc_info dictionary with information shared with instantiate task. Contains:
113 nsr_id:
114 nslcmop_id:
115 lcmOperationType: currently "instantiate"
116 deployed: dictionary with {<application>: {operational-status: <status>, detailed-status: <text>}}
117 db_update: dictionary to be filled with the changes to be wrote to database with format key.key.key: value
118 n2vc_event: event used to notify instantiation task that some change has been produced
119 :param task: None for charm status change, or task for completion task callback
120 :return:
121 """
122 try:
123 nsr_id = n2vc_info["nsr_id"]
124 deployed = n2vc_info["deployed"]
125 db_nsr_update = n2vc_info["db_update"]
126 nslcmop_id = n2vc_info["nslcmop_id"]
127 ns_operation = n2vc_info["lcmOperationType"]
128 n2vc_event = n2vc_info["n2vc_event"]
129 logging_text = "Task ns={} {}={} [n2vc_callback] application={}".format(nsr_id, ns_operation, nslcmop_id,
130 application_name)
131 vca_deployed = deployed.get(application_name)
132 if not vca_deployed:
133 self.logger.error(logging_text + " Not present at nsr._admin.deployed.VCA")
134 return
135
136 if task:
137 if task.cancelled():
138 self.logger.debug(logging_text + " task Cancelled")
139 vca_deployed['operational-status'] = "error"
140 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(application_name)] = "error"
141 vca_deployed['detailed-status'] = "Task Cancelled"
142 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(application_name)] = "Task Cancelled"
143
144 elif task.done():
145 exc = task.exception()
146 if exc:
147 self.logger.error(logging_text + " task Exception={}".format(exc))
148 vca_deployed['operational-status'] = "error"
149 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(application_name)] = "error"
150 vca_deployed['detailed-status'] = str(exc)
151 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(application_name)] = str(exc)
152 else:
153 self.logger.debug(logging_text + " task Done")
154 # task is Done, but callback is still ongoing. So ignore
155 return
156 elif status:
157 self.logger.debug(logging_text + " Enter status={}".format(status))
158 if vca_deployed['operational-status'] == status:
159 return # same status, ignore
160 vca_deployed['operational-status'] = status
161 db_nsr_update["_admin.deployed.VCA.{}.operational-status".format(application_name)] = status
162 vca_deployed['detailed-status'] = str(message)
163 db_nsr_update["_admin.deployed.VCA.{}.detailed-status".format(application_name)] = str(message)
164 else:
165 self.logger.critical(logging_text + " Enter with bad parameters", exc_info=True)
166 return
167 # wake up instantiate task
168 n2vc_event.set()
169 except Exception as e:
170 self.logger.critical(logging_text + " Exception {}".format(e), exc_info=True)
171
172 def ns_params_2_RO(self, ns_params, nsd, vnfd_dict):
173 """
174 Creates a RO ns descriptor from OSM ns_instantite params
175 :param ns_params: OSM instantiate params
176 :return: The RO ns descriptor
177 """
178 vim_2_RO = {}
179
180 def vim_account_2_RO(vim_account):
181 if vim_account in vim_2_RO:
182 return vim_2_RO[vim_account]
183
184 db_vim = self.db.get_one("vim_accounts", {"_id": vim_account})
185 if db_vim["_admin"]["operationalState"] != "ENABLED":
186 raise LcmException("VIM={} is not available. operationalState={}".format(
187 vim_account, db_vim["_admin"]["operationalState"]))
188 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
189 vim_2_RO[vim_account] = RO_vim_id
190 return RO_vim_id
191
192 def ip_profile_2_RO(ip_profile):
193 RO_ip_profile = deepcopy((ip_profile))
194 if "dns-server" in RO_ip_profile:
195 if isinstance(RO_ip_profile["dns-server"], list):
196 RO_ip_profile["dns-address"] = []
197 for ds in RO_ip_profile.pop("dns-server"):
198 RO_ip_profile["dns-address"].append(ds['address'])
199 else:
200 RO_ip_profile["dns-address"] = RO_ip_profile.pop("dns-server")
201 if RO_ip_profile.get("ip-version") == "ipv4":
202 RO_ip_profile["ip-version"] = "IPv4"
203 if RO_ip_profile.get("ip-version") == "ipv6":
204 RO_ip_profile["ip-version"] = "IPv6"
205 if "dhcp-params" in RO_ip_profile:
206 RO_ip_profile["dhcp"] = RO_ip_profile.pop("dhcp-params")
207 return RO_ip_profile
208
209 if not ns_params:
210 return None
211 RO_ns_params = {
212 # "name": ns_params["nsName"],
213 # "description": ns_params.get("nsDescription"),
214 "datacenter": vim_account_2_RO(ns_params["vimAccountId"]),
215 # "scenario": ns_params["nsdId"],
216 "vnfs": {},
217 "networks": {},
218 }
219 if ns_params.get("ssh-authorized-key"):
220 RO_ns_params["cloud-config"] = {"key-pairs": ns_params["ssh-authorized-key"]}
221 if ns_params.get("vnf"):
222 for vnf_params in ns_params["vnf"]:
223 for constituent_vnfd in nsd["constituent-vnfd"]:
224 if constituent_vnfd["member-vnf-index"] == vnf_params["member-vnf-index"]:
225 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
226 break
227 else:
228 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
229 "constituent-vnfd".format(vnf_params["member-vnf-index"]))
230 RO_vnf = {"vdus": {}, "networks": {}}
231 if vnf_params.get("vimAccountId"):
232 RO_vnf["datacenter"] = vim_account_2_RO(vnf_params["vimAccountId"])
233 if vnf_params.get("vdu"):
234 for vdu_params in vnf_params["vdu"]:
235 RO_vnf["vdus"][vdu_params["id"]] = {}
236 if vdu_params.get("volume"):
237 RO_vnf["vdus"][vdu_params["id"]]["devices"] = {}
238 for volume_params in vdu_params["volume"]:
239 RO_vnf["vdus"][vdu_params["id"]]["devices"][volume_params["name"]] = {}
240 if volume_params.get("vim-volume-id"):
241 RO_vnf["vdus"][vdu_params["id"]]["devices"][volume_params["name"]]["vim_id"] = \
242 volume_params["vim-volume-id"]
243 if vdu_params.get("interface"):
244 RO_vnf["vdus"][vdu_params["id"]]["interfaces"] = {}
245 for interface_params in vdu_params["interface"]:
246 RO_interface = {}
247 RO_vnf["vdus"][vdu_params["id"]]["interfaces"][interface_params["name"]] = RO_interface
248 if interface_params.get("ip-address"):
249 RO_interface["ip_address"] = interface_params["ip-address"]
250 if interface_params.get("mac-address"):
251 RO_interface["mac_address"] = interface_params["mac-address"]
252 if interface_params.get("floating-ip-required"):
253 RO_interface["floating-ip"] = interface_params["floating-ip-required"]
254 if vnf_params.get("internal-vld"):
255 for internal_vld_params in vnf_params["internal-vld"]:
256 RO_vnf["networks"][internal_vld_params["name"]] = {}
257 if internal_vld_params.get("vim-network-name"):
258 RO_vnf["networks"][internal_vld_params["name"]]["vim-network-name"] = \
259 internal_vld_params["vim-network-name"]
260 if internal_vld_params.get("ip-profile"):
261 RO_vnf["networks"][internal_vld_params["name"]]["ip-profile"] = \
262 ip_profile_2_RO(internal_vld_params["ip-profile"])
263 if internal_vld_params.get("internal-connection-point"):
264 for icp_params in internal_vld_params["internal-connection-point"]:
265 # look for interface
266 iface_found = False
267 for vdu_descriptor in vnf_descriptor["vdu"]:
268 for vdu_interface in vdu_descriptor["interface"]:
269 if vdu_interface.get("internal-connection-point-ref") == icp_params["id-ref"]:
270 RO_interface_update = {}
271 if icp_params.get("ip-address"):
272 RO_interface_update["ip_address"] = icp_params["ip-address"]
273 if icp_params.get("mac-address"):
274 RO_interface_update["mac_address"] = icp_params["mac-address"]
275 if RO_interface_update:
276 RO_vnf_update = {"vdus": {vdu_descriptor["id"]: {
277 "interfaces": {vdu_interface["name"]: RO_interface_update}}}}
278 deep_update(RO_vnf, RO_vnf_update)
279 iface_found = True
280 break
281 if iface_found:
282 break
283 else:
284 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
285 "internal-vld:id-ref={} is not present at vnfd:internal-"
286 "connection-point".format(vnf_params["member-vnf-index"],
287 icp_params["id-ref"]))
288
289 if not RO_vnf["vdus"]:
290 del RO_vnf["vdus"]
291 if not RO_vnf["networks"]:
292 del RO_vnf["networks"]
293 if RO_vnf:
294 RO_ns_params["vnfs"][vnf_params["member-vnf-index"]] = RO_vnf
295 if ns_params.get("vld"):
296 for vld_params in ns_params["vld"]:
297 RO_vld = {}
298 if "ip-profile" in vld_params:
299 RO_vld["ip-profile"] = ip_profile_2_RO(vld_params["ip-profile"])
300 if "vim-network-name" in vld_params:
301 RO_vld["sites"] = []
302 if isinstance(vld_params["vim-network-name"], dict):
303 for vim_account, vim_net in vld_params["vim-network-name"].items():
304 RO_vld["sites"].append({
305 "netmap-use": vim_net,
306 "datacenter": vim_account_2_RO(vim_account)
307 })
308 else: # isinstance str
309 RO_vld["sites"].append({"netmap-use": vld_params["vim-network-name"]})
310 if "vnfd-connection-point-ref" in vld_params:
311 for cp_params in vld_params["vnfd-connection-point-ref"]:
312 # look for interface
313 for constituent_vnfd in nsd["constituent-vnfd"]:
314 if constituent_vnfd["member-vnf-index"] == cp_params["member-vnf-index-ref"]:
315 vnf_descriptor = vnfd_dict[constituent_vnfd["vnfd-id-ref"]]
316 break
317 else:
318 raise LcmException(
319 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
320 "is not present at nsd:constituent-vnfd".format(cp_params["member-vnf-index-ref"]))
321 match_cp = False
322 for vdu_descriptor in vnf_descriptor["vdu"]:
323 for interface_descriptor in vdu_descriptor["interface"]:
324 if interface_descriptor.get("external-connection-point-ref") == \
325 cp_params["vnfd-connection-point-ref"]:
326 match_cp = True
327 break
328 if match_cp:
329 break
330 else:
331 raise LcmException(
332 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
333 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
334 cp_params["member-vnf-index-ref"],
335 cp_params["vnfd-connection-point-ref"],
336 vnf_descriptor["id"]))
337 RO_cp_params = {}
338 if cp_params.get("ip-address"):
339 RO_cp_params["ip_address"] = cp_params["ip-address"]
340 if cp_params.get("mac-address"):
341 RO_cp_params["mac_address"] = cp_params["mac-address"]
342 if RO_cp_params:
343 RO_vnf_params = {
344 cp_params["member-vnf-index-ref"]: {
345 "vdus": {
346 vdu_descriptor["id"]: {
347 "interfaces": {
348 interface_descriptor["name"]: RO_cp_params
349 }
350 }
351 }
352 }
353 }
354 deep_update(RO_ns_params["vnfs"], RO_vnf_params)
355 if RO_vld:
356 RO_ns_params["networks"][vld_params["name"]] = RO_vld
357 return RO_ns_params
358
359 def ns_update_vnfr(self, db_vnfrs, nsr_desc_RO):
360 """
361 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
362 :param db_vnfrs:
363 :param nsr_desc_RO:
364 :return:
365 """
366 for vnf_index, db_vnfr in db_vnfrs.items():
367 for vnf_RO in nsr_desc_RO["vnfs"]:
368 if vnf_RO["member_vnf_index"] == vnf_index:
369 vnfr_update = {}
370 db_vnfr["ip-address"] = vnfr_update["ip-address"] = vnf_RO.get("ip_address")
371 vdur_list = []
372 for vdur_RO in vnf_RO.get("vms", ()):
373 vdur = {
374 "vim-id": vdur_RO.get("vim_vm_id"),
375 "ip-address": vdur_RO.get("ip_address"),
376 "vdu-id-ref": vdur_RO.get("vdu_osm_id"),
377 "name": vdur_RO.get("vim_name"),
378 "status": vdur_RO.get("status"),
379 "status-detailed": vdur_RO.get("error_msg"),
380 "interfaces": []
381 }
382
383 for interface_RO in vdur_RO.get("interfaces", ()):
384 vdur["interfaces"].append({
385 "ip-address": interface_RO.get("ip_address"),
386 "mac-address": interface_RO.get("mac_address"),
387 "name": interface_RO.get("internal_name"),
388 })
389 vdur_list.append(vdur)
390 db_vnfr["vdur"] = vnfr_update["vdur"] = vdur_list
391 self.update_db_2("vnfrs", db_vnfr["_id"], vnfr_update)
392 break
393
394 else:
395 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} at RO info".format(vnf_index))
396
397 async def create_monitoring(self, nsr_id, vnf_member_index, vnfd_desc):
398 if not vnfd_desc.get("scaling-group-descriptor"):
399 return
400 for scaling_group in vnfd_desc["scaling-group-descriptor"]:
401 scaling_policy_desc = {}
402 scaling_desc = {
403 "ns_id": nsr_id,
404 "scaling_group_descriptor": {
405 "name": scaling_group["name"],
406 "scaling_policy": scaling_policy_desc
407 }
408 }
409 for scaling_policy in scaling_group.get("scaling-policy"):
410 scaling_policy_desc["scale_in_operation_type"] = scaling_policy_desc["scale_out_operation_type"] = \
411 scaling_policy["scaling-type"]
412 scaling_policy_desc["threshold_time"] = scaling_policy["threshold-time"]
413 scaling_policy_desc["cooldown_time"] = scaling_policy["cooldown-time"]
414 scaling_policy_desc["scaling_criteria"] = []
415 for scaling_criteria in scaling_policy.get("scaling-criteria"):
416 scaling_criteria_desc = {"scale_in_threshold": scaling_criteria.get("scale-in-threshold"),
417 "scale_out_threshold": scaling_criteria.get("scale-out-threshold"),
418 }
419 if not scaling_criteria.get("vnf-monitoring-param-ref"):
420 continue
421 for monitoring_param in vnfd_desc.get("monitoring-param", ()):
422 if monitoring_param["id"] == scaling_criteria["vnf-monitoring-param-ref"]:
423 scaling_criteria_desc["monitoring_param"] = {
424 "id": monitoring_param["id"],
425 "name": monitoring_param["name"],
426 "aggregation_type": monitoring_param.get("aggregation-type"),
427 "vdu_name": monitoring_param.get("vdu-ref"),
428 "vnf_member_index": vnf_member_index,
429 }
430
431 scaling_policy_desc["scaling_criteria"].append(scaling_criteria_desc)
432 break
433 else:
434 self.logger.error(
435 "Task ns={} member_vnf_index={} Invalid vnfd vnf-monitoring-param-ref={} not in "
436 "monitoring-param list".format(nsr_id, vnf_member_index,
437 scaling_criteria["vnf-monitoring-param-ref"]))
438
439 await self.msg.aiowrite("lcm_pm", "configure_scaling", scaling_desc, self.loop)
440
441 async def instantiate(self, nsr_id, nslcmop_id):
442 logging_text = "Task ns={} instantiate={} ".format(nsr_id, nslcmop_id)
443 self.logger.debug(logging_text + "Enter")
444 # get all needed from database
445 db_nsr = None
446 db_nslcmop = None
447 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
448 db_nslcmop_update = {}
449 nslcmop_operation_state = None
450 db_vnfrs = {}
451 RO_descriptor_number = 0 # number of descriptors created at RO
452 descriptor_id_2_RO = {} # map between vnfd/nsd id to the id used at RO
453 n2vc_info = {}
454 exc = None
455 try:
456 step = "Getting nslcmop={} from db".format(nslcmop_id)
457 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
458 step = "Getting nsr={} from db".format(nsr_id)
459 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
460 ns_params = db_nsr.get("instantiate_params")
461 nsd = db_nsr["nsd"]
462 nsr_name = db_nsr["name"] # TODO short-name??
463
464 # look if previous tasks in process
465 task_name, task_dependency = self.lcm_tasks.lookfor_related("ns", nsr_id, nslcmop_id)
466 if task_dependency:
467 step = db_nslcmop_update["detailed-status"] = \
468 "Waiting for related tasks to be completed: {}".format(task_name)
469 self.logger.debug(logging_text + step)
470 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
471 _, pending = await asyncio.wait(task_dependency, timeout=3600)
472 if pending:
473 raise LcmException("Timeout waiting related tasks to be completed")
474
475 needed_vnfd = {}
476 vnfr_filter = {"nsr-id-ref": nsr_id, "member-vnf-index-ref": None}
477 for c_vnf in nsd["constituent-vnfd"]:
478 vnfd_id = c_vnf["vnfd-id-ref"]
479 vnfr_filter["member-vnf-index-ref"] = c_vnf["member-vnf-index"]
480 step = "Getting vnfr={} of nsr={} from db".format(c_vnf["member-vnf-index"], nsr_id)
481 db_vnfrs[c_vnf["member-vnf-index"]] = self.db.get_one("vnfrs", vnfr_filter)
482 if vnfd_id not in needed_vnfd:
483 step = "Getting vnfd={} from db".format(vnfd_id)
484 needed_vnfd[vnfd_id] = self.db.get_one("vnfds", {"id": vnfd_id})
485
486 nsr_lcm = db_nsr["_admin"].get("deployed")
487 if not nsr_lcm:
488 nsr_lcm = db_nsr["_admin"]["deployed"] = {
489 "id": nsr_id,
490 "RO": {"vnfd_id": {}, "nsd_id": None, "nsr_id": None, "nsr_status": "SCHEDULED"},
491 "nsr_ip": {},
492 "VCA": {},
493 }
494 db_nsr_update["detailed-status"] = "creating"
495 db_nsr_update["operational-status"] = "init"
496
497 RO = ROclient.ROClient(self.loop, **self.ro_config)
498
499 # get vnfds, instantiate at RO
500 for vnfd_id, vnfd in needed_vnfd.items():
501 step = db_nsr_update["detailed-status"] = "Creating vnfd={} at RO".format(vnfd_id)
502 # self.logger.debug(logging_text + step)
503 vnfd_id_RO = "{}.{}.{}".format(nsr_id, RO_descriptor_number, vnfd_id[:23])
504 descriptor_id_2_RO[vnfd_id] = vnfd_id_RO
505 RO_descriptor_number += 1
506
507 # look if present
508 vnfd_list = await RO.get_list("vnfd", filter_by={"osm_id": vnfd_id_RO})
509 if vnfd_list:
510 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id)] = vnfd_list[0]["uuid"]
511 self.logger.debug(logging_text + "vnfd={} exists at RO. Using RO_id={}".format(
512 vnfd_id, vnfd_list[0]["uuid"]))
513 else:
514 vnfd_RO = self.vnfd2RO(vnfd, vnfd_id_RO)
515 desc = await RO.create("vnfd", descriptor=vnfd_RO)
516 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnfd_id)] = desc["uuid"]
517 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
518 self.logger.debug(logging_text + "vnfd={} created at RO. RO_id={}".format(
519 vnfd_id, desc["uuid"]))
520 self.update_db_2("nsrs", nsr_id, db_nsr_update)
521
522 # create nsd at RO
523 nsd_id = nsd["id"]
524 step = db_nsr_update["detailed-status"] = "Creating nsd={} at RO".format(nsd_id)
525 # self.logger.debug(logging_text + step)
526
527 RO_osm_nsd_id = "{}.{}.{}".format(nsr_id, RO_descriptor_number, nsd_id[:23])
528 descriptor_id_2_RO[nsd_id] = RO_osm_nsd_id
529 RO_descriptor_number += 1
530 nsd_list = await RO.get_list("nsd", filter_by={"osm_id": RO_osm_nsd_id})
531 if nsd_list:
532 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = nsd_list[0]["uuid"]
533 self.logger.debug(logging_text + "nsd={} exists at RO. Using RO_id={}".format(
534 nsd_id, RO_nsd_uuid))
535 else:
536 nsd_RO = deepcopy(nsd)
537 nsd_RO["id"] = RO_osm_nsd_id
538 nsd_RO.pop("_id", None)
539 nsd_RO.pop("_admin", None)
540 for c_vnf in nsd_RO["constituent-vnfd"]:
541 vnfd_id = c_vnf["vnfd-id-ref"]
542 c_vnf["vnfd-id-ref"] = descriptor_id_2_RO[vnfd_id]
543 desc = await RO.create("nsd", descriptor=nsd_RO)
544 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
545 db_nsr_update["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid = desc["uuid"]
546 self.logger.debug(logging_text + "nsd={} created at RO. RO_id={}".format(nsd_id, RO_nsd_uuid))
547 self.update_db_2("nsrs", nsr_id, db_nsr_update)
548
549 # Crate ns at RO
550 # if present use it unless in error status
551 RO_nsr_id = db_nsr["_admin"].get("deployed", {}).get("RO", {}).get("nsr_id")
552 if RO_nsr_id:
553 try:
554 step = db_nsr_update["detailed-status"] = "Looking for existing ns at RO"
555 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
556 desc = await RO.show("ns", RO_nsr_id)
557 except ROclient.ROClientException as e:
558 if e.http_code != HTTPStatus.NOT_FOUND:
559 raise
560 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
561 if RO_nsr_id:
562 ns_status, ns_status_info = RO.check_ns_status(desc)
563 db_nsr_update["_admin.deployed.RO.nsr_status"] = ns_status
564 if ns_status == "ERROR":
565 step = db_nsr_update["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id)
566 self.logger.debug(logging_text + step)
567 await RO.delete("ns", RO_nsr_id)
568 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = None
569 if not RO_nsr_id:
570 step = db_nsr_update["detailed-status"] = "Checking dependencies"
571 # self.logger.debug(logging_text + step)
572
573 # check if VIM is creating and wait look if previous tasks in process
574 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", ns_params["vimAccountId"])
575 if task_dependency:
576 step = "Waiting for related tasks to be completed: {}".format(task_name)
577 self.logger.debug(logging_text + step)
578 await asyncio.wait(task_dependency, timeout=3600)
579 if ns_params.get("vnf"):
580 for vnf in ns_params["vnf"]:
581 if "vimAccountId" in vnf:
582 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account",
583 vnf["vimAccountId"])
584 if task_dependency:
585 step = "Waiting for related tasks to be completed: {}".format(task_name)
586 self.logger.debug(logging_text + step)
587 await asyncio.wait(task_dependency, timeout=3600)
588
589 step = db_nsr_update["detailed-status"] = "Checking instantiation parameters"
590 RO_ns_params = self.ns_params_2_RO(ns_params, nsd, needed_vnfd)
591 step = db_nsr_update["detailed-status"] = "Creating ns at RO"
592 desc = await RO.create("ns", descriptor=RO_ns_params,
593 name=db_nsr["name"],
594 scenario=RO_nsd_uuid)
595 RO_nsr_id = db_nsr_update["_admin.deployed.RO.nsr_id"] = desc["uuid"]
596 db_nsr_update["_admin.nsState"] = "INSTANTIATED"
597 db_nsr_update["_admin.deployed.RO.nsr_status"] = "BUILD"
598 self.logger.debug(logging_text + "ns created at RO. RO_id={}".format(desc["uuid"]))
599 self.update_db_2("nsrs", nsr_id, db_nsr_update)
600
601 # update VNFR vimAccount
602 step = "Updating VNFR vimAcccount"
603 for vnf_index, vnfr in db_vnfrs.items():
604 if vnfr.get("vim-account-id"):
605 continue
606 vnfr_update = {"vim-account-id": db_nsr["instantiate_params"]["vimAccountId"]}
607 if db_nsr["instantiate_params"].get("vnf"):
608 for vnf_params in db_nsr["instantiate_params"]["vnf"]:
609 if vnf_params.get("member-vnf-index") == vnf_index:
610 if vnf_params.get("vimAccountId"):
611 vnfr_update["vim-account-id"] = vnf_params.get("vimAccountId")
612 break
613 self.update_db_2("vnfrs", vnfr["_id"], vnfr_update)
614
615 # wait until NS is ready
616 step = ns_status_detailed = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
617 detailed_status_old = None
618 self.logger.debug(logging_text + step)
619
620 deployment_timeout = 2 * 3600 # Two hours
621 while deployment_timeout > 0:
622 desc = await RO.show("ns", RO_nsr_id)
623 ns_status, ns_status_info = RO.check_ns_status(desc)
624 db_nsr_update["admin.deployed.RO.nsr_status"] = ns_status
625 if ns_status == "ERROR":
626 raise ROclient.ROClientException(ns_status_info)
627 elif ns_status == "BUILD":
628 detailed_status = ns_status_detailed + "; {}".format(ns_status_info)
629 elif ns_status == "ACTIVE":
630 step = detailed_status = "Waiting for management IP address reported by the VIM"
631 try:
632 nsr_lcm["nsr_ip"] = RO.get_ns_vnf_info(desc)
633 break
634 except ROclient.ROClientException as e:
635 if e.http_code != 409: # IP address is not ready return code is 409 CONFLICT
636 raise e
637 else:
638 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
639 if detailed_status != detailed_status_old:
640 detailed_status_old = db_nsr_update["detailed-status"] = detailed_status
641 self.update_db_2("nsrs", nsr_id, db_nsr_update)
642 await asyncio.sleep(5, loop=self.loop)
643 deployment_timeout -= 5
644 if deployment_timeout <= 0:
645 raise ROclient.ROClientException("Timeout waiting ns to be ready")
646
647 step = "Updating VNFRs"
648 self.ns_update_vnfr(db_vnfrs, desc)
649
650 db_nsr["detailed-status"] = "Configuring vnfr"
651 self.update_db_2("nsrs", nsr_id, db_nsr_update)
652
653 # The parameters we'll need to deploy a charm
654 number_to_configure = 0
655
656 def deploy(vnf_index, vdu_id, mgmt_ip_address, n2vc_info, config_primitive=None):
657 """An inner function to deploy the charm from either vnf or vdu
658 vnf_index is mandatory. vdu_id can be None for a vnf configuration or the id for vdu configuration
659 """
660 if not mgmt_ip_address:
661 raise LcmException("vnfd/vdu has not management ip address to configure it")
662 # Login to the VCA.
663 # if number_to_configure == 0:
664 # self.logger.debug("Logging into N2VC...")
665 # task = asyncio.ensure_future(self.n2vc.login())
666 # yield from asyncio.wait_for(task, 30.0)
667 # self.logger.debug("Logged into N2VC!")
668
669 # # await self.n2vc.login()
670
671 # Note: The charm needs to exist on disk at the location
672 # specified by charm_path.
673 base_folder = vnfd["_admin"]["storage"]
674 storage_params = self.fs.get_params()
675 charm_path = "{}{}/{}/charms/{}".format(
676 storage_params["path"],
677 base_folder["folder"],
678 base_folder["pkg-dir"],
679 proxy_charm
680 )
681
682 # Setup the runtime parameters for this VNF
683 params = {'rw_mgmt_ip': mgmt_ip_address}
684 if config_primitive:
685 params["initial-config-primitive"] = config_primitive
686
687 # ns_name will be ignored in the current version of N2VC
688 # but will be implemented for the next point release.
689 model_name = 'default'
690 vdu_id_text = "vnfd"
691 if vdu_id:
692 vdu_id_text = vdu_id
693 application_name = self.n2vc.FormatApplicationName(
694 nsr_name,
695 vnf_index,
696 vdu_id_text
697 )
698 if not nsr_lcm.get("VCA"):
699 nsr_lcm["VCA"] = {}
700 nsr_lcm["VCA"][application_name] = db_nsr_update["_admin.deployed.VCA.{}".format(application_name)] = {
701 "member-vnf-index": vnf_index,
702 "vdu_id": vdu_id,
703 "model": model_name,
704 "application": application_name,
705 "operational-status": "init",
706 "detailed-status": "",
707 "vnfd_id": vnfd_id,
708 }
709 self.update_db_2("nsrs", nsr_id, db_nsr_update)
710
711 self.logger.debug("Task create_ns={} Passing artifacts path '{}' for {}".format(nsr_id, charm_path,
712 proxy_charm))
713 if not n2vc_info:
714 n2vc_info["nsr_id"] = nsr_id
715 n2vc_info["nslcmop_id"] = nslcmop_id
716 n2vc_info["n2vc_event"] = asyncio.Event(loop=self.loop)
717 n2vc_info["lcmOperationType"] = "instantiate"
718 n2vc_info["deployed"] = nsr_lcm["VCA"]
719 n2vc_info["db_update"] = db_nsr_update
720 task = asyncio.ensure_future(
721 self.n2vc.DeployCharms(
722 model_name, # The network service name
723 application_name, # The application name
724 vnfd, # The vnf descriptor
725 charm_path, # Path to charm
726 params, # Runtime params, like mgmt ip
727 {}, # for native charms only
728 self.n2vc_callback, # Callback for status changes
729 n2vc_info, # Callback parameter
730 None, # Callback parameter (task)
731 )
732 )
733 task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None, None,
734 n2vc_info))
735 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "create_charm:" + application_name, task)
736
737 step = "Looking for needed vnfd to configure"
738 self.logger.debug(logging_text + step)
739
740 for c_vnf in nsd["constituent-vnfd"]:
741 vnfd_id = c_vnf["vnfd-id-ref"]
742 vnf_index = str(c_vnf["member-vnf-index"])
743 vnfd = needed_vnfd[vnfd_id]
744
745 # Check if this VNF has a charm configuration
746 vnf_config = vnfd.get("vnf-configuration")
747
748 if vnf_config and vnf_config.get("juju"):
749 proxy_charm = vnf_config["juju"]["charm"]
750 config_primitive = None
751
752 if proxy_charm:
753 if 'initial-config-primitive' in vnf_config:
754 config_primitive = vnf_config['initial-config-primitive']
755
756 # Login to the VCA. If there are multiple calls to login(),
757 # subsequent calls will be a nop and return immediately.
758 step = "connecting to N2VC to configure vnf {}".format(vnf_index)
759 await self.n2vc.login()
760 deploy(vnf_index, None, db_vnfrs[vnf_index]["ip-address"], n2vc_info, config_primitive)
761 number_to_configure += 1
762
763 # Deploy charms for each VDU that supports one.
764 vdu_index = 0
765 for vdu in vnfd['vdu']:
766 vdu_config = vdu.get('vdu-configuration')
767 proxy_charm = None
768 config_primitive = None
769
770 if vdu_config and vdu_config.get("juju"):
771 proxy_charm = vdu_config["juju"]["charm"]
772
773 if 'initial-config-primitive' in vdu_config:
774 config_primitive = vdu_config['initial-config-primitive']
775
776 if proxy_charm:
777 step = "connecting to N2VC to configure vdu {} from vnf {}".format(vdu["id"], vnf_index)
778 await self.n2vc.login()
779 deploy(vnf_index, vdu["id"], db_vnfrs[vnf_index]["vdur"][vdu_index]["ip-address"],
780 n2vc_info, config_primitive)
781 number_to_configure += 1
782 vdu_index += 1
783
784 db_nsr_update["operational-status"] = "running"
785 configuration_failed = False
786 if number_to_configure:
787 old_status = "configuring: init: {}".format(number_to_configure)
788 db_nsr_update["config-status"] = old_status
789 db_nsr_update["detailed-status"] = old_status
790 db_nslcmop_update["detailed-status"] = old_status
791
792 # wait until all are configured.
793 while True:
794 if db_nsr_update:
795 self.update_db_2("nsrs", nsr_id, db_nsr_update)
796 if db_nslcmop_update:
797 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
798 await n2vc_info["n2vc_event"].wait()
799 n2vc_info["n2vc_event"].clear()
800 all_active = True
801 status_map = {}
802 n2vc_error_text = [] # contain text error list. If empty no one is in error status
803 for _, vca_info in nsr_lcm["VCA"].items():
804 vca_status = vca_info["operational-status"]
805 if vca_status not in status_map:
806 # Initialize it
807 status_map[vca_status] = 0
808 status_map[vca_status] += 1
809
810 if vca_status != "active":
811 all_active = False
812 if vca_status in ("error", "blocked"):
813 n2vc_error_text.append(
814 "member_vnf_index={} vdu_id={} {}: {}".format(vca_info["member-vnf-index"],
815 vca_info["vdu_id"], vca_status,
816 vca_info["detailed-status"]))
817
818 if all_active:
819 break
820 elif n2vc_error_text:
821 db_nsr_update["config-status"] = "failed"
822 error_text = "fail configuring " + ";".join(n2vc_error_text)
823 db_nsr_update["detailed-status"] = error_text
824 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED_TEMP"
825 db_nslcmop_update["detailed-status"] = error_text
826 db_nslcmop_update["statusEnteredTime"] = time()
827 configuration_failed = True
828 break
829 else:
830 cs = "configuring: "
831 separator = ""
832 for status, num in status_map.items():
833 cs += separator + "{}: {}".format(status, num)
834 separator = ", "
835 if old_status != cs:
836 db_nsr_update["config-status"] = cs
837 db_nsr_update["detailed-status"] = cs
838 db_nslcmop_update["detailed-status"] = cs
839 old_status = cs
840
841 if not configuration_failed:
842 # all is done
843 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
844 db_nslcmop_update["statusEnteredTime"] = time()
845 db_nslcmop_update["detailed-status"] = "done"
846 db_nsr_update["config-status"] = "configured"
847 db_nsr_update["detailed-status"] = "done"
848
849 # step = "Sending monitoring parameters to PM"
850 # for c_vnf in nsd["constituent-vnfd"]:
851 # await self.create_monitoring(nsr_id, c_vnf["member-vnf-index"], needed_vnfd[c_vnf["vnfd-id-ref"]])
852 return
853
854 except (ROclient.ROClientException, DbException, LcmException) as e:
855 self.logger.error(logging_text + "Exit Exception while '{}': {}".format(step, e))
856 exc = e
857 except asyncio.CancelledError:
858 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
859 exc = "Operation was cancelled"
860 except Exception as e:
861 exc = traceback.format_exc()
862 self.logger.critical(logging_text + "Exit Exception {} while '{}': {}".format(type(e).__name__, step, e),
863 exc_info=True)
864 finally:
865 if exc:
866 if db_nsr:
867 db_nsr_update["detailed-status"] = "ERROR {}: {}".format(step, exc)
868 db_nsr_update["operational-status"] = "failed"
869 if db_nslcmop:
870 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
871 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
872 db_nslcmop_update["statusEnteredTime"] = time()
873 if db_nsr:
874 db_nsr_update["_admin.nslcmop"] = None
875 self.update_db_2("nsrs", nsr_id, db_nsr_update)
876 if db_nslcmop_update:
877 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
878 if nslcmop_operation_state:
879 try:
880 await self.msg.aiowrite("ns", "instantiated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
881 "operationState": nslcmop_operation_state})
882 except Exception as e:
883 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
884
885 self.logger.debug(logging_text + "Exit")
886 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_instantiate")
887
888 async def terminate(self, nsr_id, nslcmop_id):
889 logging_text = "Task ns={} terminate={} ".format(nsr_id, nslcmop_id)
890 self.logger.debug(logging_text + "Enter")
891 db_nsr = None
892 db_nslcmop = None
893 exc = None
894 failed_detail = [] # annotates all failed error messages
895 vca_task_list = []
896 vca_task_dict = {}
897 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
898 db_nslcmop_update = {}
899 nslcmop_operation_state = None
900 try:
901 step = "Getting nslcmop={} from db".format(nslcmop_id)
902 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
903 step = "Getting nsr={} from db".format(nsr_id)
904 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
905 # nsd = db_nsr["nsd"]
906 nsr_lcm = deepcopy(db_nsr["_admin"].get("deployed"))
907 if db_nsr["_admin"]["nsState"] == "NOT_INSTANTIATED":
908 return
909 # TODO ALF remove
910 # db_vim = self.db.get_one("vim_accounts", {"_id": db_nsr["datacenter"]})
911 # #TODO check if VIM is creating and wait
912 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
913
914 db_nsr_update["operational-status"] = "terminating"
915 db_nsr_update["config-status"] = "terminating"
916
917 if nsr_lcm and nsr_lcm.get("VCA"):
918 try:
919 step = "Scheduling configuration charms removing"
920 db_nsr_update["detailed-status"] = "Deleting charms"
921 self.logger.debug(logging_text + step)
922 self.update_db_2("nsrs", nsr_id, db_nsr_update)
923 for application_name, deploy_info in nsr_lcm["VCA"].items():
924 if deploy_info: # TODO it would be desirable having a and deploy_info.get("deployed"):
925 task = asyncio.ensure_future(
926 self.n2vc.RemoveCharms(
927 deploy_info['model'],
928 application_name,
929 # self.n2vc_callback,
930 # db_nsr,
931 # db_nslcmop,
932 )
933 )
934 vca_task_list.append(task)
935 vca_task_dict[application_name] = task
936 # task.add_done_callback(functools.partial(self.n2vc_callback, deploy_info['model'],
937 # deploy_info['application'], None, db_nsr,
938 # db_nslcmop, vnf_index))
939 self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "delete_charm:" + application_name, task)
940 except Exception as e:
941 self.logger.debug(logging_text + "Failed while deleting charms: {}".format(e))
942
943 # remove from RO
944 RO_fail = False
945 RO = ROclient.ROClient(self.loop, **self.ro_config)
946
947 # Delete ns
948 RO_nsr_id = RO_delete_action = None
949 if nsr_lcm and nsr_lcm.get("RO"):
950 RO_nsr_id = nsr_lcm["RO"].get("nsr_id")
951 RO_delete_action = nsr_lcm["RO"].get("nsr_delete_action_id")
952 try:
953 if RO_nsr_id:
954 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] = "Deleting ns at RO"
955 self.logger.debug(logging_text + step)
956 desc = await RO.delete("ns", RO_nsr_id)
957 RO_delete_action = desc["action_id"]
958 db_nsr_update["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
959 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
960 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
961 if RO_delete_action:
962 # wait until NS is deleted from VIM
963 step = detailed_status = "Waiting ns deleted from VIM. RO_id={}".format(RO_nsr_id)
964 detailed_status_old = None
965 self.logger.debug(logging_text + step)
966
967 delete_timeout = 20 * 60 # 20 minutes
968 while delete_timeout > 0:
969 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
970 extra_item_id=RO_delete_action)
971 ns_status, ns_status_info = RO.check_action_status(desc)
972 if ns_status == "ERROR":
973 raise ROclient.ROClientException(ns_status_info)
974 elif ns_status == "BUILD":
975 detailed_status = step + "; {}".format(ns_status_info)
976 elif ns_status == "ACTIVE":
977 break
978 else:
979 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
980 await asyncio.sleep(5, loop=self.loop)
981 delete_timeout -= 5
982 if detailed_status != detailed_status_old:
983 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
984 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
985 else: # delete_timeout <= 0:
986 raise ROclient.ROClientException("Timeout waiting ns deleted from VIM")
987
988 except ROclient.ROClientException as e:
989 if e.http_code == 404: # not found
990 db_nsr_update["_admin.deployed.RO.nsr_id"] = None
991 db_nsr_update["_admin.deployed.RO.nsr_status"] = "DELETED"
992 self.logger.debug(logging_text + "RO_ns_id={} already deleted".format(RO_nsr_id))
993 elif e.http_code == 409: # conflict
994 failed_detail.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id, e))
995 self.logger.debug(logging_text + failed_detail[-1])
996 RO_fail = True
997 else:
998 failed_detail.append("RO_ns_id={} delete error: {}".format(RO_nsr_id, e))
999 self.logger.error(logging_text + failed_detail[-1])
1000 RO_fail = True
1001
1002 # Delete nsd
1003 if not RO_fail and nsr_lcm and nsr_lcm.get("RO") and nsr_lcm["RO"].get("nsd_id"):
1004 RO_nsd_id = nsr_lcm["RO"]["nsd_id"]
1005 try:
1006 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1007 "Deleting nsd at RO"
1008 await RO.delete("nsd", RO_nsd_id)
1009 self.logger.debug(logging_text + "RO_nsd_id={} deleted".format(RO_nsd_id))
1010 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
1011 except ROclient.ROClientException as e:
1012 if e.http_code == 404: # not found
1013 db_nsr_update["_admin.deployed.RO.nsd_id"] = None
1014 self.logger.debug(logging_text + "RO_nsd_id={} already deleted".format(RO_nsd_id))
1015 elif e.http_code == 409: # conflict
1016 failed_detail.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id, e))
1017 self.logger.debug(logging_text + failed_detail[-1])
1018 RO_fail = True
1019 else:
1020 failed_detail.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id, e))
1021 self.logger.error(logging_text + failed_detail[-1])
1022 RO_fail = True
1023
1024 if not RO_fail and nsr_lcm and nsr_lcm.get("RO") and nsr_lcm["RO"].get("vnfd_id"):
1025 for vnf_id, RO_vnfd_id in nsr_lcm["RO"]["vnfd_id"].items():
1026 if not RO_vnfd_id:
1027 continue
1028 try:
1029 step = db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1030 "Deleting vnfd={} at RO".format(vnf_id)
1031 await RO.delete("vnfd", RO_vnfd_id)
1032 self.logger.debug(logging_text + "RO_vnfd_id={} deleted".format(RO_vnfd_id))
1033 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnf_id)] = None
1034 except ROclient.ROClientException as e:
1035 if e.http_code == 404: # not found
1036 db_nsr_update["_admin.deployed.RO.vnfd_id.{}".format(vnf_id)] = None
1037 self.logger.debug(logging_text + "RO_vnfd_id={} already deleted ".format(RO_vnfd_id))
1038 elif e.http_code == 409: # conflict
1039 failed_detail.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id, e))
1040 self.logger.debug(logging_text + failed_detail[-1])
1041 else:
1042 failed_detail.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id, e))
1043 self.logger.error(logging_text + failed_detail[-1])
1044
1045 if vca_task_list:
1046 db_nsr_update["detailed-status"] = db_nslcmop_update["detailed-status"] =\
1047 "Waiting for deletion of configuration charms"
1048 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1049 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1050 await asyncio.wait(vca_task_list, timeout=300)
1051 for application_name, task in vca_task_dict.items():
1052 if task.cancelled():
1053 failed_detail.append("VCA[{}] Deletion has been cancelled".format(application_name))
1054 elif task.done():
1055 exc = task.exception()
1056 if exc:
1057 failed_detail.append("VCA[{}] Deletion exception: {}".format(application_name, exc))
1058 else:
1059 db_nsr_update["_admin.deployed.VCA.{}".format(application_name)] = None
1060 else: # timeout
1061 # TODO Should it be cancelled?!!
1062 task.cancel()
1063 failed_detail.append("VCA[{}] Deletion timeout".format(application_name))
1064
1065 if failed_detail:
1066 self.logger.error(logging_text + " ;".join(failed_detail))
1067 db_nsr_update["operational-status"] = "failed"
1068 db_nsr_update["detailed-status"] = "Deletion errors " + "; ".join(failed_detail)
1069 db_nslcmop_update["detailed-status"] = "; ".join(failed_detail)
1070 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1071 db_nslcmop_update["statusEnteredTime"] = time()
1072 elif db_nslcmop["operationParams"].get("autoremove"):
1073 self.db.del_one("nsrs", {"_id": nsr_id})
1074 db_nsr_update.clear()
1075 self.db.del_list("nslcmops", {"nsInstanceId": nsr_id})
1076 nslcmop_operation_state = "COMPLETED"
1077 db_nslcmop_update.clear()
1078 self.db.del_list("vnfrs", {"nsr-id-ref": nsr_id})
1079 self.logger.debug(logging_text + "Delete from database")
1080 else:
1081 db_nsr_update["operational-status"] = "terminated"
1082 db_nsr_update["detailed-status"] = "Done"
1083 db_nsr_update["_admin.nsState"] = "NOT_INSTANTIATED"
1084 db_nslcmop_update["detailed-status"] = "Done"
1085 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
1086 db_nslcmop_update["statusEnteredTime"] = time()
1087
1088 except (ROclient.ROClientException, DbException) as e:
1089 self.logger.error(logging_text + "Exit Exception {}".format(e))
1090 exc = e
1091 except asyncio.CancelledError:
1092 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1093 exc = "Operation was cancelled"
1094 except Exception as e:
1095 exc = traceback.format_exc()
1096 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
1097 finally:
1098 if exc and db_nslcmop:
1099 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1100 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1101 db_nslcmop_update["statusEnteredTime"] = time()
1102 if db_nslcmop_update:
1103 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1104 if db_nsr:
1105 db_nsr_update["_admin.nslcmop"] = None
1106 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1107 if nslcmop_operation_state:
1108 try:
1109 await self.msg.aiowrite("ns", "terminated", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1110 "operationState": nslcmop_operation_state})
1111 except Exception as e:
1112 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1113 self.logger.debug(logging_text + "Exit")
1114 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_terminate")
1115
1116 async def _ns_execute_primitive(self, db_deployed, nsr_name, member_vnf_index, vdu_id, primitive, primitive_params):
1117
1118 vdu_id_text = "vnfd"
1119 if vdu_id:
1120 vdu_id_text = vdu_id
1121 application_name = self.n2vc.FormatApplicationName(
1122 nsr_name,
1123 member_vnf_index,
1124 vdu_id_text
1125 )
1126 vca_deployed = db_deployed["VCA"].get(application_name)
1127 if not vca_deployed:
1128 raise LcmException("charm for member_vnf_index={} vdu_id={} is not deployed".format(member_vnf_index,
1129 vdu_id))
1130 model_name = vca_deployed.get("model")
1131 application_name = vca_deployed.get("application")
1132 if not model_name or not application_name:
1133 raise LcmException("charm for member_vnf_index={} is not properly deployed".format(member_vnf_index))
1134 if vca_deployed["operational-status"] != "active":
1135 raise LcmException("charm for member_vnf_index={} operational_status={} not 'active'".format(
1136 member_vnf_index, vca_deployed["operational-status"]))
1137 callback = None # self.n2vc_callback
1138 callback_args = () # [db_nsr, db_nslcmop, member_vnf_index, None]
1139 await self.n2vc.login()
1140 task = asyncio.ensure_future(
1141 self.n2vc.ExecutePrimitive(
1142 model_name,
1143 application_name,
1144 primitive, callback,
1145 *callback_args,
1146 **primitive_params
1147 )
1148 )
1149 # task.add_done_callback(functools.partial(self.n2vc_callback, model_name, application_name, None,
1150 # db_nsr, db_nslcmop, member_vnf_index))
1151 # self.lcm_tasks.register("ns", nsr_id, nslcmop_id, "action:" + primitive, task)
1152 # wait until completed with timeout
1153 await asyncio.wait((task,), timeout=600)
1154
1155 result = "FAILED" # by default
1156 result_detail = ""
1157 if task.cancelled():
1158 result_detail = "Task has been cancelled"
1159 elif task.done():
1160 exc = task.exception()
1161 if exc:
1162 result_detail = str(exc)
1163 else:
1164 # TODO revise with Adam if action is finished and ok when task is done or callback is needed
1165 result = "COMPLETED"
1166 result_detail = "Done"
1167 else: # timeout
1168 # TODO Should it be cancelled?!!
1169 task.cancel()
1170 result_detail = "timeout"
1171 return result, result_detail
1172
1173 async def action(self, nsr_id, nslcmop_id):
1174 logging_text = "Task ns={} action={} ".format(nsr_id, nslcmop_id)
1175 self.logger.debug(logging_text + "Enter")
1176 # get all needed from database
1177 db_nsr = None
1178 db_nslcmop = None
1179 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
1180 db_nslcmop_update = {}
1181 nslcmop_operation_state = None
1182 exc = None
1183 try:
1184 step = "Getting information from database"
1185 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1186 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1187 nsr_lcm = db_nsr["_admin"].get("deployed")
1188 nsr_name = db_nsr["name"]
1189 vnf_index = db_nslcmop["operationParams"]["member_vnf_index"]
1190 vdu_id = db_nslcmop["operationParams"].get("vdu_id")
1191
1192 # look if previous tasks in process
1193 task_name, task_dependency = self.lcm_tasks.lookfor_related("ns", nsr_id, nslcmop_id)
1194 if task_dependency:
1195 step = db_nslcmop_update["detailed-status"] = \
1196 "Waiting for related tasks to be completed: {}".format(task_name)
1197 self.logger.debug(logging_text + step)
1198 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1199 _, pending = await asyncio.wait(task_dependency, timeout=3600)
1200 if pending:
1201 raise LcmException("Timeout waiting related tasks to be completed")
1202
1203 # TODO check if ns is in a proper status
1204 primitive = db_nslcmop["operationParams"]["primitive"]
1205 primitive_params = db_nslcmop["operationParams"]["primitive_params"]
1206 result, result_detail = await self._ns_execute_primitive(nsr_lcm, nsr_name, vnf_index, vdu_id, primitive,
1207 primitive_params)
1208 db_nslcmop_update["detailed-status"] = result_detail
1209 db_nslcmop_update["operationState"] = nslcmop_operation_state = result
1210 db_nslcmop_update["statusEnteredTime"] = time()
1211 self.logger.debug(logging_text + " task Done with result {} {}".format(result, result_detail))
1212 return # database update is called inside finally
1213
1214 except (DbException, LcmException) as e:
1215 self.logger.error(logging_text + "Exit Exception {}".format(e))
1216 exc = e
1217 except asyncio.CancelledError:
1218 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1219 exc = "Operation was cancelled"
1220 except Exception as e:
1221 exc = traceback.format_exc()
1222 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
1223 finally:
1224 if exc and db_nslcmop:
1225 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1226 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1227 db_nslcmop_update["statusEnteredTime"] = time()
1228 if db_nslcmop_update:
1229 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1230 if db_nsr:
1231 db_nsr_update["_admin.nslcmop"] = None
1232 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1233 self.logger.debug(logging_text + "Exit")
1234 if nslcmop_operation_state:
1235 try:
1236 await self.msg.aiowrite("ns", "actioned", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1237 "operationState": nslcmop_operation_state})
1238 except Exception as e:
1239 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1240 self.logger.debug(logging_text + "Exit")
1241 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_action")
1242
1243 async def scale(self, nsr_id, nslcmop_id):
1244 logging_text = "Task ns={} scale={} ".format(nsr_id, nslcmop_id)
1245 self.logger.debug(logging_text + "Enter")
1246 # get all needed from database
1247 db_nsr = None
1248 db_nslcmop = None
1249 db_nslcmop_update = {}
1250 nslcmop_operation_state = None
1251 db_nsr_update = {"_admin.nslcmop": nslcmop_id}
1252 exc = None
1253 # in case of error, indicates what part of scale was failed to put nsr at error status
1254 scale_process = None
1255 old_operational_status = ""
1256 old_config_status = ""
1257 try:
1258 step = "Getting nslcmop from database"
1259 db_nslcmop = self.db.get_one("nslcmops", {"_id": nslcmop_id})
1260 step = "Getting nsr from database"
1261 db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1262 old_operational_status = db_nsr["operational-status"]
1263 old_config_status = db_nsr["config-status"]
1264
1265 # look if previous tasks in process
1266 task_name, task_dependency = self.lcm_tasks.lookfor_related("ns", nsr_id, nslcmop_id)
1267 if task_dependency:
1268 step = db_nslcmop_update["detailed-status"] = \
1269 "Waiting for related tasks to be completed: {}".format(task_name)
1270 self.logger.debug(logging_text + step)
1271 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1272 _, pending = await asyncio.wait(task_dependency, timeout=3600)
1273 if pending:
1274 raise LcmException("Timeout waiting related tasks to be completed")
1275
1276 step = "Parsing scaling parameters"
1277 db_nsr_update["operational-status"] = "scaling"
1278 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1279 nsr_lcm = db_nsr["_admin"].get("deployed")
1280 RO_nsr_id = nsr_lcm["RO"]["nsr_id"]
1281 vnf_index = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
1282 scaling_group = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1283 scaling_type = db_nslcmop["operationParams"]["scaleVnfData"]["scaleVnfType"]
1284 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
1285
1286 step = "Getting vnfr from database"
1287 db_vnfr = self.db.get_one("vnfrs", {"member-vnf-index-ref": vnf_index, "nsr-id-ref": nsr_id})
1288 step = "Getting vnfd from database"
1289 db_vnfd = self.db.get_one("vnfds", {"_id": db_vnfr["vnfd-id"]})
1290 step = "Getting scaling-group-descriptor"
1291 for scaling_descriptor in db_vnfd["scaling-group-descriptor"]:
1292 if scaling_descriptor["name"] == scaling_group:
1293 break
1294 else:
1295 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
1296 "at vnfd:scaling-group-descriptor".format(scaling_group))
1297 # cooldown_time = 0
1298 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
1299 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
1300 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
1301 # break
1302
1303 # TODO check if ns is in a proper status
1304 step = "Sending scale order to RO"
1305 nb_scale_op = 0
1306 if not db_nsr["_admin"].get("scaling-group"):
1307 self.update_db_2("nsrs", nsr_id, {"_admin.scaling-group": [{"name": scaling_group, "nb-scale-op": 0}]})
1308 admin_scale_index = 0
1309 else:
1310 for admin_scale_index, admin_scale_info in enumerate(db_nsr["_admin"]["scaling-group"]):
1311 if admin_scale_info["name"] == scaling_group:
1312 nb_scale_op = admin_scale_info.get("nb-scale-op", 0)
1313 break
1314 else: # not found, set index one plus last element and add new entry with the name
1315 admin_scale_index += 1
1316 db_nsr_update["_admin.scaling-group.{}.name".format(admin_scale_index)] = scaling_group
1317 RO_scaling_info = []
1318 vdu_scaling_info = {"scaling_group_name": scaling_group, "vdu": []}
1319 if scaling_type == "SCALE_OUT":
1320 # count if max-instance-count is reached
1321 if "max-instance-count" in scaling_descriptor and scaling_descriptor["max-instance-count"] is not None:
1322 max_instance_count = int(scaling_descriptor["max-instance-count"])
1323 if nb_scale_op >= max_instance_count:
1324 raise LcmException("reached the limit of {} (max-instance-count) scaling-out operations for the"
1325 " scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
1326 nb_scale_op = nb_scale_op + 1
1327 vdu_scaling_info["scaling_direction"] = "OUT"
1328 vdu_scaling_info["vdu-create"] = {}
1329 for vdu_scale_info in scaling_descriptor["vdu"]:
1330 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
1331 "type": "create", "count": vdu_scale_info.get("count", 1)})
1332 vdu_scaling_info["vdu-create"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
1333 elif scaling_type == "SCALE_IN":
1334 # count if min-instance-count is reached
1335 if "min-instance-count" in scaling_descriptor and scaling_descriptor["min-instance-count"] is not None:
1336 min_instance_count = int(scaling_descriptor["min-instance-count"])
1337 if nb_scale_op <= min_instance_count:
1338 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
1339 "scaling-group-descriptor '{}'".format(nb_scale_op, scaling_group))
1340 nb_scale_op = nb_scale_op - 1
1341 vdu_scaling_info["scaling_direction"] = "IN"
1342 vdu_scaling_info["vdu-delete"] = {}
1343 for vdu_scale_info in scaling_descriptor["vdu"]:
1344 RO_scaling_info.append({"osm_vdu_id": vdu_scale_info["vdu-id-ref"], "member-vnf-index": vnf_index,
1345 "type": "delete", "count": vdu_scale_info.get("count", 1)})
1346 vdu_scaling_info["vdu-delete"][vdu_scale_info["vdu-id-ref"]] = vdu_scale_info.get("count", 1)
1347
1348 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
1349 if vdu_scaling_info["scaling_direction"] == "IN":
1350 for vdur in reversed(db_vnfr["vdur"]):
1351 if vdu_scaling_info["vdu-delete"].get(vdur["vdu-id-ref"]):
1352 vdu_scaling_info["vdu-delete"][vdur["vdu-id-ref"]] -= 1
1353 vdu_scaling_info["vdu"].append({
1354 "name": vdur["name"],
1355 "vdu_id": vdur["vdu-id-ref"],
1356 "interface": []
1357 })
1358 for interface in vdur["interfaces"]:
1359 vdu_scaling_info["vdu"][-1]["interface"].append({
1360 "name": interface["name"],
1361 "ip_address": interface["ip-address"],
1362 "mac_address": interface.get("mac-address"),
1363 })
1364 del vdu_scaling_info["vdu-delete"]
1365
1366 # execute primitive service PRE-SCALING
1367 step = "Executing pre-scale vnf-config-primitive"
1368 if scaling_descriptor.get("scaling-config-action"):
1369 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
1370 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "pre-scale-in" \
1371 and scaling_type == "SCALE_IN":
1372 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
1373 step = db_nslcmop_update["detailed-status"] = \
1374 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive)
1375 # look for primitive
1376 primitive_params = {}
1377 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
1378 if config_primitive["name"] == vnf_config_primitive:
1379 for parameter in config_primitive.get("parameter", ()):
1380 if 'default-value' in parameter and \
1381 parameter['default-value'] == "<VDU_SCALE_INFO>":
1382 primitive_params[parameter["name"]] = yaml.safe_dump(vdu_scaling_info,
1383 default_flow_style=True,
1384 width=256)
1385 break
1386 else:
1387 raise LcmException(
1388 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
1389 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-cnfiguration:config-"
1390 "primitive".format(scaling_group, config_primitive))
1391 scale_process = "VCA"
1392 db_nsr_update["config-status"] = "configuring pre-scaling"
1393 result, result_detail = await self._ns_execute_primitive(nsr_lcm, vnf_index,
1394 vnf_config_primitive, primitive_params)
1395 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
1396 vnf_config_primitive, result, result_detail))
1397 if result == "FAILED":
1398 raise LcmException(result_detail)
1399 db_nsr_update["config-status"] = old_config_status
1400 scale_process = None
1401
1402 if RO_scaling_info:
1403 scale_process = "RO"
1404 RO = ROclient.ROClient(self.loop, **self.ro_config)
1405 RO_desc = await RO.create_action("ns", RO_nsr_id, {"vdu-scaling": RO_scaling_info})
1406 db_nsr_update["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index)] = nb_scale_op
1407 db_nsr_update["_admin.scaling-group.{}.time".format(admin_scale_index)] = time()
1408 # wait until ready
1409 RO_nslcmop_id = RO_desc["instance_action_id"]
1410 db_nslcmop_update["_admin.deploy.RO"] = RO_nslcmop_id
1411
1412 RO_task_done = False
1413 step = detailed_status = "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id)
1414 detailed_status_old = None
1415 self.logger.debug(logging_text + step)
1416
1417 deployment_timeout = 1 * 3600 # One hour
1418 while deployment_timeout > 0:
1419 if not RO_task_done:
1420 desc = await RO.show("ns", item_id_name=RO_nsr_id, extra_item="action",
1421 extra_item_id=RO_nslcmop_id)
1422 ns_status, ns_status_info = RO.check_action_status(desc)
1423 if ns_status == "ERROR":
1424 raise ROclient.ROClientException(ns_status_info)
1425 elif ns_status == "BUILD":
1426 detailed_status = step + "; {}".format(ns_status_info)
1427 elif ns_status == "ACTIVE":
1428 RO_task_done = True
1429 step = detailed_status = "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id)
1430 self.logger.debug(logging_text + step)
1431 else:
1432 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status)
1433 else:
1434 desc = await RO.show("ns", RO_nsr_id)
1435 ns_status, ns_status_info = RO.check_ns_status(desc)
1436 if ns_status == "ERROR":
1437 raise ROclient.ROClientException(ns_status_info)
1438 elif ns_status == "BUILD":
1439 detailed_status = step + "; {}".format(ns_status_info)
1440 elif ns_status == "ACTIVE":
1441 step = detailed_status = "Waiting for management IP address reported by the VIM"
1442 try:
1443 desc = await RO.show("ns", RO_nsr_id)
1444 nsr_lcm["nsr_ip"] = RO.get_ns_vnf_info(desc)
1445 break
1446 except ROclient.ROClientException as e:
1447 if e.http_code != 409: # IP address is not ready return code is 409 CONFLICT
1448 raise e
1449 else:
1450 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status)
1451 if detailed_status != detailed_status_old:
1452 detailed_status_old = db_nslcmop_update["detailed-status"] = detailed_status
1453 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1454
1455 await asyncio.sleep(5, loop=self.loop)
1456 deployment_timeout -= 5
1457 if deployment_timeout <= 0:
1458 raise ROclient.ROClientException("Timeout waiting ns to be ready")
1459
1460 step = "Updating VNFRs"
1461 self.ns_update_vnfr({db_vnfr["member-vnf-index-ref"]: db_vnfr}, desc)
1462
1463 # update VDU_SCALING_INFO with the obtained ip_addresses
1464 if vdu_scaling_info["scaling_direction"] == "OUT":
1465 for vdur in reversed(db_vnfr["vdur"]):
1466 if vdu_scaling_info["vdu-create"].get(vdur["vdu-id-ref"]):
1467 vdu_scaling_info["vdu-create"][vdur["vdu-id-ref"]] -= 1
1468 vdu_scaling_info["vdu"].append({
1469 "name": vdur["name"],
1470 "vdu_id": vdur["vdu-id-ref"],
1471 "interface": []
1472 })
1473 for interface in vdur["interfaces"]:
1474 vdu_scaling_info["vdu"][-1]["interface"].append({
1475 "name": interface["name"],
1476 "ip_address": interface["ip-address"],
1477 "mac_address": interface.get("mac-address"),
1478 })
1479 del vdu_scaling_info["vdu-create"]
1480
1481 scale_process = None
1482 if db_nsr_update:
1483 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1484
1485 # execute primitive service POST-SCALING
1486 step = "Executing post-scale vnf-config-primitive"
1487 if scaling_descriptor.get("scaling-config-action"):
1488 for scaling_config_action in scaling_descriptor["scaling-config-action"]:
1489 if scaling_config_action.get("trigger") and scaling_config_action["trigger"] == "post-scale-out" \
1490 and scaling_type == "SCALE_OUT":
1491 vnf_config_primitive = scaling_config_action["vnf-config-primitive-name-ref"]
1492 step = db_nslcmop_update["detailed-status"] = \
1493 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive)
1494 # look for primitive
1495 primitive_params = {}
1496 for config_primitive in db_vnfd.get("vnf-configuration", {}).get("config-primitive", ()):
1497 if config_primitive["name"] == vnf_config_primitive:
1498 for parameter in config_primitive.get("parameter", ()):
1499 if 'default-value' in parameter and \
1500 parameter['default-value'] == "<VDU_SCALE_INFO>":
1501 primitive_params[parameter["name"]] = yaml.safe_dump(vdu_scaling_info,
1502 default_flow_style=True,
1503 width=256)
1504 break
1505 else:
1506 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
1507 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
1508 "match any vnf-configuration:config-primitive".format(scaling_group,
1509 config_primitive))
1510 scale_process = "VCA"
1511 db_nsr_update["config-status"] = "configuring post-scaling"
1512
1513 result, result_detail = await self._ns_execute_primitive(nsr_lcm, vnf_index,
1514 vnf_config_primitive, primitive_params)
1515 self.logger.debug(logging_text + "vnf_config_primitive={} Done with result {} {}".format(
1516 vnf_config_primitive, result, result_detail))
1517 if result == "FAILED":
1518 raise LcmException(result_detail)
1519 db_nsr_update["config-status"] = old_config_status
1520 scale_process = None
1521
1522 db_nslcmop_update["operationState"] = nslcmop_operation_state = "COMPLETED"
1523 db_nslcmop_update["statusEnteredTime"] = time()
1524 db_nslcmop_update["detailed-status"] = "done"
1525 db_nsr_update["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
1526 db_nsr_update["operational-status"] = old_operational_status
1527 db_nsr_update["config-status"] = old_config_status
1528 return
1529 except (ROclient.ROClientException, DbException, LcmException) as e:
1530 self.logger.error(logging_text + "Exit Exception {}".format(e))
1531 exc = e
1532 except asyncio.CancelledError:
1533 self.logger.error(logging_text + "Cancelled Exception while '{}'".format(step))
1534 exc = "Operation was cancelled"
1535 except Exception as e:
1536 exc = traceback.format_exc()
1537 self.logger.critical(logging_text + "Exit Exception {} {}".format(type(e).__name__, e), exc_info=True)
1538 finally:
1539 if exc:
1540 if db_nslcmop:
1541 db_nslcmop_update["detailed-status"] = "FAILED {}: {}".format(step, exc)
1542 db_nslcmop_update["operationState"] = nslcmop_operation_state = "FAILED"
1543 db_nslcmop_update["statusEnteredTime"] = time()
1544 if db_nsr:
1545 db_nsr_update["operational-status"] = old_operational_status
1546 db_nsr_update["config-status"] = old_config_status
1547 db_nsr_update["detailed-status"] = ""
1548 db_nsr_update["_admin.nslcmop"] = None
1549 if scale_process:
1550 if "VCA" in scale_process:
1551 db_nsr_update["config-status"] = "failed"
1552 if "RO" in scale_process:
1553 db_nsr_update["operational-status"] = "failed"
1554 db_nsr_update["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id, step,
1555 exc)
1556 if db_nslcmop_update:
1557 self.update_db_2("nslcmops", nslcmop_id, db_nslcmop_update)
1558 if db_nsr:
1559 db_nsr_update["_admin.nslcmop"] = None
1560 self.update_db_2("nsrs", nsr_id, db_nsr_update)
1561 if nslcmop_operation_state:
1562 try:
1563 await self.msg.aiowrite("ns", "scaled", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id,
1564 "operationState": nslcmop_operation_state})
1565 # if cooldown_time:
1566 # await asyncio.sleep(cooldown_time)
1567 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
1568 except Exception as e:
1569 self.logger.error(logging_text + "kafka_write notification Exception {}".format(e))
1570 self.logger.debug(logging_text + "Exit")
1571 self.lcm_tasks.remove("ns", nsr_id, nslcmop_id, "ns_scale")