1 # -*- coding: utf-8 -*-
4 # Copyright 2018 Telefonica S.A.
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
10 # http://www.apache.org/licenses/LICENSE-2.0
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
22 import logging
.handlers
24 from jinja2
import Environment
, Template
, meta
, TemplateError
, TemplateNotFound
, TemplateSyntaxError
26 from osm_lcm
import ROclient
27 from osm_lcm
.lcm_utils
import LcmException
, LcmExceptionNoMgmtIP
, LcmBase
29 from osm_common
.dbbase
import DbException
30 from osm_common
.fsbase
import FsException
32 from n2vc
.n2vc_juju_conn
import N2VCJujuConnector
34 from copy
import copy
, deepcopy
35 from http
import HTTPStatus
37 from uuid
import uuid4
39 __author__
= "Alfonso Tierno"
42 def get_iterable(in_dict
, in_key
):
44 Similar to <dict>.get(), but if value is None, False, ..., An empty tuple is returned instead
45 :param in_dict: a dictionary
46 :param in_key: the key to look for at in_dict
47 :return: in_dict[in_var] or () if it is None or not present
49 if not in_dict
.get(in_key
):
51 return in_dict
[in_key
]
54 def populate_dict(target_dict
, key_list
, value
):
56 Update target_dict creating nested dictionaries with the key_list. Last key_list item is asigned the value.
57 Example target_dict={K: J}; key_list=[a,b,c]; target_dict will be {K: J, a: {b: {c: value}}}
58 :param target_dict: dictionary to be changed
59 :param key_list: list of keys to insert at target_dict
63 for key
in key_list
[0:-1]:
64 if key
not in target_dict
:
66 target_dict
= target_dict
[key
]
67 target_dict
[key_list
[-1]] = value
70 def deep_get(target_dict
, key_list
):
72 Get a value from target_dict entering in the nested keys. If keys does not exist, it returns None
73 Example target_dict={a: {b: 5}}; key_list=[a,b] returns 5; both key_list=[a,b,c] and key_list=[f,h] return None
74 :param target_dict: dictionary to be read
75 :param key_list: list of keys to read from target_dict
76 :return: The wanted value if exist, None otherwise
79 if not isinstance(target_dict
, dict) or key
not in target_dict
:
81 target_dict
= target_dict
[key
]
86 timeout_vca_on_error
= 5 * 60 # Time for charm from first time at blocked,error status to mark as failed
87 total_deploy_timeout
= 2 * 3600 # global timeout for deployment
88 timeout_charm_delete
= 10 * 60
89 timeout_primitive
= 10 * 60 # timeout for primitive execution
91 SUBOPERATION_STATUS_NOT_FOUND
= -1
92 SUBOPERATION_STATUS_NEW
= -2
93 SUBOPERATION_STATUS_SKIP
= -3
95 def __init__(self
, db
, msg
, fs
, lcm_tasks
, ro_config
, vca_config
, loop
):
97 Init, Connect to database, filesystem storage, and messaging
98 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
105 logger
=logging
.getLogger('lcm.ns')
109 self
.lcm_tasks
= lcm_tasks
110 self
.ro_config
= ro_config
111 self
.vca_config
= vca_config
112 if 'pubkey' in self
.vca_config
:
113 self
.vca_config
['public_key'] = self
.vca_config
['pubkey']
114 if 'cacert' in self
.vca_config
:
115 self
.vca_config
['ca_cert'] = self
.vca_config
['cacert']
117 # create N2VC connector
118 self
.n2vc
= N2VCJujuConnector(
123 url
='{}:{}'.format(self
.vca_config
['host'], self
.vca_config
['port']),
124 username
=self
.vca_config
.get('user', None),
125 vca_config
=self
.vca_config
,
126 on_update_db
=self
._on
_update
_n
2vc
_db
129 # api_proxy=vca_config.get('apiproxy')
133 self
.RO
= ROclient
.ROClient(self
.loop
, **self
.ro_config
)
135 def _on_update_n2vc_db(self
, table
, filter, path
, updated_data
):
137 self
.logger
.debug('_on_update_n2vc_db(table={}, filter={}, path={}, updated_data={})'
138 .format(table
, filter, path
, updated_data
))
140 # write NS status to database
142 nsrs_id
= filter.get('_id')
144 nsr
= self
.db
.get_one(table
=table
, q_filter
=filter)
145 # get VCA deployed list
146 vca_list
= deep_get(target_dict
=nsr
, key_list
=('_admin', 'deployed', 'VCA'))
148 ro_list
= deep_get(target_dict
=nsr
, key_list
=('_admin', 'deployed', 'RO'))
150 status
= vca
.get('status')
151 detailed_status
= vca
.get('detailed-status')
155 except Exception as e
:
156 self
.logger
.error('_on_update_n2vc_db(table={},filter={},path={},updated_data={}) Error updating db: {}'
157 .format(table
, filter, path
, updated_data
, e
))
159 def vnfd2RO(self
, vnfd
, new_id
=None, additionalParams
=None, nsrId
=None):
161 Converts creates a new vnfd descriptor for RO base on input OSM IM vnfd
162 :param vnfd: input vnfd
163 :param new_id: overrides vnf id if provided
164 :param additionalParams: Instantiation params for VNFs provided
165 :param nsrId: Id of the NSR
166 :return: copy of vnfd
169 vnfd_RO
= deepcopy(vnfd
)
170 # remove unused by RO configuration, monitoring, scaling and internal keys
171 vnfd_RO
.pop("_id", None)
172 vnfd_RO
.pop("_admin", None)
173 vnfd_RO
.pop("vnf-configuration", None)
174 vnfd_RO
.pop("monitoring-param", None)
175 vnfd_RO
.pop("scaling-group-descriptor", None)
177 vnfd_RO
["id"] = new_id
179 # parse cloud-init or cloud-init-file with the provided variables using Jinja2
180 for vdu
in get_iterable(vnfd_RO
, "vdu"):
181 cloud_init_file
= None
182 if vdu
.get("cloud-init-file"):
183 base_folder
= vnfd
["_admin"]["storage"]
184 cloud_init_file
= "{}/{}/cloud_init/{}".format(base_folder
["folder"], base_folder
["pkg-dir"],
185 vdu
["cloud-init-file"])
186 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
187 cloud_init_content
= ci_file
.read()
188 vdu
.pop("cloud-init-file", None)
189 elif vdu
.get("cloud-init"):
190 cloud_init_content
= vdu
["cloud-init"]
195 ast
= env
.parse(cloud_init_content
)
196 mandatory_vars
= meta
.find_undeclared_variables(ast
)
198 for var
in mandatory_vars
:
199 if not additionalParams
or var
not in additionalParams
.keys():
200 raise LcmException("Variable '{}' defined at vnfd[id={}]:vdu[id={}]:cloud-init/cloud-init-"
201 "file, must be provided in the instantiation parameters inside the "
202 "'additionalParamsForVnf' block".format(var
, vnfd
["id"], vdu
["id"]))
203 template
= Template(cloud_init_content
)
204 cloud_init_content
= template
.render(additionalParams
or {})
205 vdu
["cloud-init"] = cloud_init_content
208 except FsException
as e
:
209 raise LcmException("Error reading vnfd[id={}]:vdu[id={}]:cloud-init-file={}: {}".
210 format(vnfd
["id"], vdu
["id"], cloud_init_file
, e
))
211 except (TemplateError
, TemplateNotFound
, TemplateSyntaxError
) as e
:
212 raise LcmException("Error parsing Jinja2 to cloud-init content at vnfd[id={}]:vdu[id={}]: {}".
213 format(vnfd
["id"], vdu
["id"], e
))
215 def ns_params_2_RO(self
, ns_params
, nsd
, vnfd_dict
, n2vc_key_list
):
217 Creates a RO ns descriptor from OSM ns_instantiate params
218 :param ns_params: OSM instantiate params
219 :return: The RO ns descriptor
223 # TODO feature 1417: Check that no instantiation is set over PDU
224 # check if PDU forces a concrete vim-network-id and add it
225 # check if PDU contains a SDN-assist info (dpid, switch, port) and pass it to RO
227 def vim_account_2_RO(vim_account
):
228 if vim_account
in vim_2_RO
:
229 return vim_2_RO
[vim_account
]
231 db_vim
= self
.db
.get_one("vim_accounts", {"_id": vim_account
})
232 if db_vim
["_admin"]["operationalState"] != "ENABLED":
233 raise LcmException("VIM={} is not available. operationalState={}".format(
234 vim_account
, db_vim
["_admin"]["operationalState"]))
235 RO_vim_id
= db_vim
["_admin"]["deployed"]["RO"]
236 vim_2_RO
[vim_account
] = RO_vim_id
239 def wim_account_2_RO(wim_account
):
240 if isinstance(wim_account
, str):
241 if wim_account
in wim_2_RO
:
242 return wim_2_RO
[wim_account
]
244 db_wim
= self
.db
.get_one("wim_accounts", {"_id": wim_account
})
245 if db_wim
["_admin"]["operationalState"] != "ENABLED":
246 raise LcmException("WIM={} is not available. operationalState={}".format(
247 wim_account
, db_wim
["_admin"]["operationalState"]))
248 RO_wim_id
= db_wim
["_admin"]["deployed"]["RO-account"]
249 wim_2_RO
[wim_account
] = RO_wim_id
254 def ip_profile_2_RO(ip_profile
):
255 RO_ip_profile
= deepcopy((ip_profile
))
256 if "dns-server" in RO_ip_profile
:
257 if isinstance(RO_ip_profile
["dns-server"], list):
258 RO_ip_profile
["dns-address"] = []
259 for ds
in RO_ip_profile
.pop("dns-server"):
260 RO_ip_profile
["dns-address"].append(ds
['address'])
262 RO_ip_profile
["dns-address"] = RO_ip_profile
.pop("dns-server")
263 if RO_ip_profile
.get("ip-version") == "ipv4":
264 RO_ip_profile
["ip-version"] = "IPv4"
265 if RO_ip_profile
.get("ip-version") == "ipv6":
266 RO_ip_profile
["ip-version"] = "IPv6"
267 if "dhcp-params" in RO_ip_profile
:
268 RO_ip_profile
["dhcp"] = RO_ip_profile
.pop("dhcp-params")
274 # "name": ns_params["nsName"],
275 # "description": ns_params.get("nsDescription"),
276 "datacenter": vim_account_2_RO(ns_params
["vimAccountId"]),
277 "wim_account": wim_account_2_RO(ns_params
.get("wimAccountId")),
278 # "scenario": ns_params["nsdId"],
281 n2vc_key_list
= n2vc_key_list
or []
282 for vnfd_ref
, vnfd
in vnfd_dict
.items():
283 vdu_needed_access
= []
285 if vnfd
.get("vnf-configuration"):
286 ssh_required
= deep_get(vnfd
, ("vnf-configuration", "config-access", "ssh-access", "required"))
287 if ssh_required
and vnfd
.get("mgmt-interface"):
288 if vnfd
["mgmt-interface"].get("vdu-id"):
289 vdu_needed_access
.append(vnfd
["mgmt-interface"]["vdu-id"])
290 elif vnfd
["mgmt-interface"].get("cp"):
291 mgmt_cp
= vnfd
["mgmt-interface"]["cp"]
293 for vdu
in vnfd
.get("vdu", ()):
294 if vdu
.get("vdu-configuration"):
295 ssh_required
= deep_get(vdu
, ("vdu-configuration", "config-access", "ssh-access", "required"))
297 vdu_needed_access
.append(vdu
["id"])
299 for vdu_interface
in vdu
.get("interface"):
300 if vdu_interface
.get("external-connection-point-ref") and \
301 vdu_interface
["external-connection-point-ref"] == mgmt_cp
:
302 vdu_needed_access
.append(vdu
["id"])
306 if vdu_needed_access
:
307 for vnf_member
in nsd
.get("constituent-vnfd"):
308 if vnf_member
["vnfd-id-ref"] != vnfd_ref
:
310 for vdu
in vdu_needed_access
:
311 populate_dict(RO_ns_params
,
312 ("vnfs", vnf_member
["member-vnf-index"], "vdus", vdu
, "mgmt_keys"),
315 if ns_params
.get("vduImage"):
316 RO_ns_params
["vduImage"] = ns_params
["vduImage"]
318 if ns_params
.get("ssh_keys"):
319 RO_ns_params
["cloud-config"] = {"key-pairs": ns_params
["ssh_keys"]}
320 for vnf_params
in get_iterable(ns_params
, "vnf"):
321 for constituent_vnfd
in nsd
["constituent-vnfd"]:
322 if constituent_vnfd
["member-vnf-index"] == vnf_params
["member-vnf-index"]:
323 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
326 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index={} is not present at nsd:"
327 "constituent-vnfd".format(vnf_params
["member-vnf-index"]))
328 if vnf_params
.get("vimAccountId"):
329 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "datacenter"),
330 vim_account_2_RO(vnf_params
["vimAccountId"]))
332 for vdu_params
in get_iterable(vnf_params
, "vdu"):
333 # TODO feature 1417: check that this VDU exist and it is not a PDU
334 if vdu_params
.get("volume"):
335 for volume_params
in vdu_params
["volume"]:
336 if volume_params
.get("vim-volume-id"):
337 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
338 vdu_params
["id"], "devices", volume_params
["name"], "vim_id"),
339 volume_params
["vim-volume-id"])
340 if vdu_params
.get("interface"):
341 for interface_params
in vdu_params
["interface"]:
342 if interface_params
.get("ip-address"):
343 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
344 vdu_params
["id"], "interfaces", interface_params
["name"],
346 interface_params
["ip-address"])
347 if interface_params
.get("mac-address"):
348 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
349 vdu_params
["id"], "interfaces", interface_params
["name"],
351 interface_params
["mac-address"])
352 if interface_params
.get("floating-ip-required"):
353 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
354 vdu_params
["id"], "interfaces", interface_params
["name"],
356 interface_params
["floating-ip-required"])
358 for internal_vld_params
in get_iterable(vnf_params
, "internal-vld"):
359 if internal_vld_params
.get("vim-network-name"):
360 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
361 internal_vld_params
["name"], "vim-network-name"),
362 internal_vld_params
["vim-network-name"])
363 if internal_vld_params
.get("vim-network-id"):
364 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
365 internal_vld_params
["name"], "vim-network-id"),
366 internal_vld_params
["vim-network-id"])
367 if internal_vld_params
.get("ip-profile"):
368 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "networks",
369 internal_vld_params
["name"], "ip-profile"),
370 ip_profile_2_RO(internal_vld_params
["ip-profile"]))
372 for icp_params
in get_iterable(internal_vld_params
, "internal-connection-point"):
375 for vdu_descriptor
in vnf_descriptor
["vdu"]:
376 for vdu_interface
in vdu_descriptor
["interface"]:
377 if vdu_interface
.get("internal-connection-point-ref") == icp_params
["id-ref"]:
378 if icp_params
.get("ip-address"):
379 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
380 vdu_descriptor
["id"], "interfaces",
381 vdu_interface
["name"], "ip_address"),
382 icp_params
["ip-address"])
384 if icp_params
.get("mac-address"):
385 populate_dict(RO_ns_params
, ("vnfs", vnf_params
["member-vnf-index"], "vdus",
386 vdu_descriptor
["id"], "interfaces",
387 vdu_interface
["name"], "mac_address"),
388 icp_params
["mac-address"])
394 raise LcmException("Invalid instantiate parameter vnf:member-vnf-index[{}]:"
395 "internal-vld:id-ref={} is not present at vnfd:internal-"
396 "connection-point".format(vnf_params
["member-vnf-index"],
397 icp_params
["id-ref"]))
399 for vld_params
in get_iterable(ns_params
, "vld"):
400 if "ip-profile" in vld_params
:
401 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "ip-profile"),
402 ip_profile_2_RO(vld_params
["ip-profile"]))
404 if "wimAccountId" in vld_params
and vld_params
["wimAccountId"] is not None:
405 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "wim_account"),
406 wim_account_2_RO(vld_params
["wimAccountId"])),
407 if vld_params
.get("vim-network-name"):
409 if isinstance(vld_params
["vim-network-name"], dict):
410 for vim_account
, vim_net
in vld_params
["vim-network-name"].items():
411 RO_vld_sites
.append({
412 "netmap-use": vim_net
,
413 "datacenter": vim_account_2_RO(vim_account
)
415 else: # isinstance str
416 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-name"]})
418 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
419 if vld_params
.get("vim-network-id"):
421 if isinstance(vld_params
["vim-network-id"], dict):
422 for vim_account
, vim_net
in vld_params
["vim-network-id"].items():
423 RO_vld_sites
.append({
424 "netmap-use": vim_net
,
425 "datacenter": vim_account_2_RO(vim_account
)
427 else: # isinstance str
428 RO_vld_sites
.append({"netmap-use": vld_params
["vim-network-id"]})
430 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "sites"), RO_vld_sites
)
431 if vld_params
.get("ns-net"):
432 if isinstance(vld_params
["ns-net"], dict):
433 for vld_id
, instance_scenario_id
in vld_params
["ns-net"].items():
434 RO_vld_ns_net
= {"instance_scenario_id": instance_scenario_id
, "osm_id": vld_id
}
436 populate_dict(RO_ns_params
, ("networks", vld_params
["name"], "use-network"), RO_vld_ns_net
)
437 if "vnfd-connection-point-ref" in vld_params
:
438 for cp_params
in vld_params
["vnfd-connection-point-ref"]:
440 for constituent_vnfd
in nsd
["constituent-vnfd"]:
441 if constituent_vnfd
["member-vnf-index"] == cp_params
["member-vnf-index-ref"]:
442 vnf_descriptor
= vnfd_dict
[constituent_vnfd
["vnfd-id-ref"]]
446 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={} "
447 "is not present at nsd:constituent-vnfd".format(cp_params
["member-vnf-index-ref"]))
449 for vdu_descriptor
in vnf_descriptor
["vdu"]:
450 for interface_descriptor
in vdu_descriptor
["interface"]:
451 if interface_descriptor
.get("external-connection-point-ref") == \
452 cp_params
["vnfd-connection-point-ref"]:
459 "Invalid instantiate parameter vld:vnfd-connection-point-ref:member-vnf-index-ref={}:"
460 "vnfd-connection-point-ref={} is not present at vnfd={}".format(
461 cp_params
["member-vnf-index-ref"],
462 cp_params
["vnfd-connection-point-ref"],
463 vnf_descriptor
["id"]))
464 if cp_params
.get("ip-address"):
465 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
466 vdu_descriptor
["id"], "interfaces",
467 interface_descriptor
["name"], "ip_address"),
468 cp_params
["ip-address"])
469 if cp_params
.get("mac-address"):
470 populate_dict(RO_ns_params
, ("vnfs", cp_params
["member-vnf-index-ref"], "vdus",
471 vdu_descriptor
["id"], "interfaces",
472 interface_descriptor
["name"], "mac_address"),
473 cp_params
["mac-address"])
476 def scale_vnfr(self
, db_vnfr
, vdu_create
=None, vdu_delete
=None):
477 # make a copy to do not change
478 vdu_create
= copy(vdu_create
)
479 vdu_delete
= copy(vdu_delete
)
481 vdurs
= db_vnfr
.get("vdur")
484 vdu_index
= len(vdurs
)
487 vdur
= vdurs
[vdu_index
]
488 if vdur
.get("pdu-type"):
490 vdu_id_ref
= vdur
["vdu-id-ref"]
491 if vdu_create
and vdu_create
.get(vdu_id_ref
):
492 for index
in range(0, vdu_create
[vdu_id_ref
]):
493 vdur
= deepcopy(vdur
)
494 vdur
["_id"] = str(uuid4())
495 vdur
["count-index"] += 1
496 vdurs
.insert(vdu_index
+1+index
, vdur
)
497 del vdu_create
[vdu_id_ref
]
498 if vdu_delete
and vdu_delete
.get(vdu_id_ref
):
500 vdu_delete
[vdu_id_ref
] -= 1
501 if not vdu_delete
[vdu_id_ref
]:
502 del vdu_delete
[vdu_id_ref
]
503 # check all operations are done
504 if vdu_create
or vdu_delete
:
505 raise LcmException("Error scaling OUT VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
508 raise LcmException("Error scaling IN VNFR for {}. There is not any existing vnfr. Scaled to 0?".format(
511 vnfr_update
= {"vdur": vdurs
}
512 db_vnfr
["vdur"] = vdurs
513 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
515 def ns_update_nsr(self
, ns_update_nsr
, db_nsr
, nsr_desc_RO
):
517 Updates database nsr with the RO info for the created vld
518 :param ns_update_nsr: dictionary to be filled with the updated info
519 :param db_nsr: content of db_nsr. This is also modified
520 :param nsr_desc_RO: nsr descriptor from RO
521 :return: Nothing, LcmException is raised on errors
524 for vld_index
, vld
in enumerate(get_iterable(db_nsr
, "vld")):
525 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
526 if vld
["id"] != net_RO
.get("ns_net_osm_id"):
528 vld
["vim-id"] = net_RO
.get("vim_net_id")
529 vld
["name"] = net_RO
.get("vim_name")
530 vld
["status"] = net_RO
.get("status")
531 vld
["status-detailed"] = net_RO
.get("error_msg")
532 ns_update_nsr
["vld.{}".format(vld_index
)] = vld
535 raise LcmException("ns_update_nsr: Not found vld={} at RO info".format(vld
["id"]))
537 def ns_update_vnfr(self
, db_vnfrs
, nsr_desc_RO
):
539 Updates database vnfr with the RO info, e.g. ip_address, vim_id... Descriptor db_vnfrs is also updated
540 :param db_vnfrs: dictionary with member-vnf-index: vnfr-content
541 :param nsr_desc_RO: nsr descriptor from RO
542 :return: Nothing, LcmException is raised on errors
544 for vnf_index
, db_vnfr
in db_vnfrs
.items():
545 for vnf_RO
in nsr_desc_RO
["vnfs"]:
546 if vnf_RO
["member_vnf_index"] != vnf_index
:
549 if vnf_RO
.get("ip_address"):
550 db_vnfr
["ip-address"] = vnfr_update
["ip-address"] = vnf_RO
["ip_address"].split(";")[0]
551 elif not db_vnfr
.get("ip-address"):
552 raise LcmExceptionNoMgmtIP("ns member_vnf_index '{}' has no IP address".format(vnf_index
))
554 for vdu_index
, vdur
in enumerate(get_iterable(db_vnfr
, "vdur")):
555 vdur_RO_count_index
= 0
556 if vdur
.get("pdu-type"):
558 for vdur_RO
in get_iterable(vnf_RO
, "vms"):
559 if vdur
["vdu-id-ref"] != vdur_RO
["vdu_osm_id"]:
561 if vdur
["count-index"] != vdur_RO_count_index
:
562 vdur_RO_count_index
+= 1
564 vdur
["vim-id"] = vdur_RO
.get("vim_vm_id")
565 if vdur_RO
.get("ip_address"):
566 vdur
["ip-address"] = vdur_RO
["ip_address"].split(";")[0]
568 vdur
["ip-address"] = None
569 vdur
["vdu-id-ref"] = vdur_RO
.get("vdu_osm_id")
570 vdur
["name"] = vdur_RO
.get("vim_name")
571 vdur
["status"] = vdur_RO
.get("status")
572 vdur
["status-detailed"] = vdur_RO
.get("error_msg")
573 for ifacer
in get_iterable(vdur
, "interfaces"):
574 for interface_RO
in get_iterable(vdur_RO
, "interfaces"):
575 if ifacer
["name"] == interface_RO
.get("internal_name"):
576 ifacer
["ip-address"] = interface_RO
.get("ip_address")
577 ifacer
["mac-address"] = interface_RO
.get("mac_address")
580 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} interface={} "
582 .format(vnf_index
, vdur
["vdu-id-ref"], ifacer
["name"]))
583 vnfr_update
["vdur.{}".format(vdu_index
)] = vdur
586 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vdur={} count_index={} from "
587 "VIM info".format(vnf_index
, vdur
["vdu-id-ref"], vdur
["count-index"]))
589 for vld_index
, vld
in enumerate(get_iterable(db_vnfr
, "vld")):
590 for net_RO
in get_iterable(nsr_desc_RO
, "nets"):
591 if vld
["id"] != net_RO
.get("vnf_net_osm_id"):
593 vld
["vim-id"] = net_RO
.get("vim_net_id")
594 vld
["name"] = net_RO
.get("vim_name")
595 vld
["status"] = net_RO
.get("status")
596 vld
["status-detailed"] = net_RO
.get("error_msg")
597 vnfr_update
["vld.{}".format(vld_index
)] = vld
600 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} vld={} from VIM info".format(
601 vnf_index
, vld
["id"]))
603 self
.update_db_2("vnfrs", db_vnfr
["_id"], vnfr_update
)
607 raise LcmException("ns_update_vnfr: Not found member_vnf_index={} from VIM info".format(vnf_index
))
609 async def instantiate_RO(self
, logging_text
, nsr_id
, nsd
, db_nsr
,
610 db_nslcmop
, db_vnfrs
, db_vnfds_ref
, n2vc_key_list
):
613 RO_descriptor_number
= 0 # number of descriptors created at RO
614 vnf_index_2_RO_id
= {} # map between vnfd/nsd id to the id used at RO
615 start_deploy
= time()
616 ns_params
= db_nslcmop
.get("operationParams")
620 # get vnfds, instantiate at RO
621 for c_vnf
in nsd
.get("constituent-vnfd", ()):
622 member_vnf_index
= c_vnf
["member-vnf-index"]
623 vnfd
= db_vnfds_ref
[c_vnf
['vnfd-id-ref']]
624 vnfd_ref
= vnfd
["id"]
625 step
= db_nsr_update
["detailed-status"] = "Creating vnfd='{}' member_vnf_index='{}' at RO".format(
626 vnfd_ref
, member_vnf_index
)
627 # self.logger.debug(logging_text + step)
628 vnfd_id_RO
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, member_vnf_index
[:23])
629 vnf_index_2_RO_id
[member_vnf_index
] = vnfd_id_RO
630 RO_descriptor_number
+= 1
632 # look position at deployed.RO.vnfd if not present it will be appended at the end
633 for index
, vnf_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"]):
634 if vnf_deployed
["member-vnf-index"] == member_vnf_index
:
637 index
= len(db_nsr
["_admin"]["deployed"]["RO"]["vnfd"])
638 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"].append(None)
641 RO_update
= {"member-vnf-index": member_vnf_index
}
642 vnfd_list
= await self
.RO
.get_list("vnfd", filter_by
={"osm_id": vnfd_id_RO
})
644 RO_update
["id"] = vnfd_list
[0]["uuid"]
645 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' exists at RO. Using RO_id={}".
646 format(vnfd_ref
, member_vnf_index
, vnfd_list
[0]["uuid"]))
648 vnfd_RO
= self
.vnfd2RO(vnfd
, vnfd_id_RO
, db_vnfrs
[c_vnf
["member-vnf-index"]].
649 get("additionalParamsForVnf"), nsr_id
)
650 desc
= await self
.RO
.create("vnfd", descriptor
=vnfd_RO
)
651 RO_update
["id"] = desc
["uuid"]
652 self
.logger
.debug(logging_text
+ "vnfd='{}' member_vnf_index='{}' created at RO. RO_id={}".format(
653 vnfd_ref
, member_vnf_index
, desc
["uuid"]))
654 db_nsr_update
["_admin.deployed.RO.vnfd.{}".format(index
)] = RO_update
655 db_nsr
["_admin"]["deployed"]["RO"]["vnfd"][index
] = RO_update
656 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
660 step
= db_nsr_update
["detailed-status"] = "Creating nsd={} at RO".format(nsd_ref
)
661 # self.logger.debug(logging_text + step)
663 RO_osm_nsd_id
= "{}.{}.{}".format(nsr_id
, RO_descriptor_number
, nsd_ref
[:23])
664 RO_descriptor_number
+= 1
665 nsd_list
= await self
.RO
.get_list("nsd", filter_by
={"osm_id": RO_osm_nsd_id
})
667 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= nsd_list
[0]["uuid"]
668 self
.logger
.debug(logging_text
+ "nsd={} exists at RO. Using RO_id={}".format(
669 nsd_ref
, RO_nsd_uuid
))
671 nsd_RO
= deepcopy(nsd
)
672 nsd_RO
["id"] = RO_osm_nsd_id
673 nsd_RO
.pop("_id", None)
674 nsd_RO
.pop("_admin", None)
675 for c_vnf
in nsd_RO
.get("constituent-vnfd", ()):
676 member_vnf_index
= c_vnf
["member-vnf-index"]
677 c_vnf
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
678 for c_vld
in nsd_RO
.get("vld", ()):
679 for cp
in c_vld
.get("vnfd-connection-point-ref", ()):
680 member_vnf_index
= cp
["member-vnf-index-ref"]
681 cp
["vnfd-id-ref"] = vnf_index_2_RO_id
[member_vnf_index
]
683 desc
= await self
.RO
.create("nsd", descriptor
=nsd_RO
)
684 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
685 db_nsr_update
["_admin.deployed.RO.nsd_id"] = RO_nsd_uuid
= desc
["uuid"]
686 self
.logger
.debug(logging_text
+ "nsd={} created at RO. RO_id={}".format(nsd_ref
, RO_nsd_uuid
))
687 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
690 # if present use it unless in error status
691 RO_nsr_id
= deep_get(db_nsr
, ("_admin", "deployed", "RO", "nsr_id"))
694 step
= db_nsr_update
["detailed-status"] = "Looking for existing ns at RO"
695 # self.logger.debug(logging_text + step + " RO_ns_id={}".format(RO_nsr_id))
696 desc
= await self
.RO
.show("ns", RO_nsr_id
)
697 except ROclient
.ROClientException
as e
:
698 if e
.http_code
!= HTTPStatus
.NOT_FOUND
:
700 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
702 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
703 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
704 if ns_status
== "ERROR":
705 step
= db_nsr_update
["detailed-status"] = "Deleting ns at RO. RO_ns_id={}".format(RO_nsr_id
)
706 self
.logger
.debug(logging_text
+ step
)
707 await self
.RO
.delete("ns", RO_nsr_id
)
708 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
710 step
= db_nsr_update
["detailed-status"] = "Checking dependencies"
711 # self.logger.debug(logging_text + step)
713 # check if VIM is creating and wait look if previous tasks in process
714 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account", ns_params
["vimAccountId"])
716 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
717 self
.logger
.debug(logging_text
+ step
)
718 await asyncio
.wait(task_dependency
, timeout
=3600)
719 if ns_params
.get("vnf"):
720 for vnf
in ns_params
["vnf"]:
721 if "vimAccountId" in vnf
:
722 task_name
, task_dependency
= self
.lcm_tasks
.lookfor_related("vim_account",
725 step
= "Waiting for related tasks to be completed: {}".format(task_name
)
726 self
.logger
.debug(logging_text
+ step
)
727 await asyncio
.wait(task_dependency
, timeout
=3600)
729 step
= db_nsr_update
["detailed-status"] = "Checking instantiation parameters"
731 RO_ns_params
= self
.ns_params_2_RO(ns_params
, nsd
, db_vnfds_ref
, n2vc_key_list
)
733 step
= db_nsr_update
["detailed-status"] = "Deploying ns at VIM"
734 desc
= await self
.RO
.create("ns", descriptor
=RO_ns_params
, name
=db_nsr
["name"], scenario
=RO_nsd_uuid
)
735 RO_nsr_id
= db_nsr_update
["_admin.deployed.RO.nsr_id"] = desc
["uuid"]
736 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
737 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "BUILD"
738 self
.logger
.debug(logging_text
+ "ns created at RO. RO_id={}".format(desc
["uuid"]))
739 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
741 # wait until NS is ready
742 step
= ns_status_detailed
= detailed_status
= "Waiting VIM to deploy ns. RO_ns_id={}".format(RO_nsr_id
)
743 detailed_status_old
= None
744 self
.logger
.debug(logging_text
+ step
)
746 while time() <= start_deploy
+ self
.total_deploy_timeout
:
747 desc
= await self
.RO
.show("ns", RO_nsr_id
)
748 ns_status
, ns_status_info
= self
.RO
.check_ns_status(desc
)
749 db_nsr_update
["_admin.deployed.RO.nsr_status"] = ns_status
750 if ns_status
== "ERROR":
751 raise ROclient
.ROClientException(ns_status_info
)
752 elif ns_status
== "BUILD":
753 detailed_status
= ns_status_detailed
+ "; {}".format(ns_status_info
)
754 elif ns_status
== "ACTIVE":
755 step
= detailed_status
= "Waiting for management IP address reported by the VIM. Updating VNFRs"
757 self
.ns_update_vnfr(db_vnfrs
, desc
)
759 except LcmExceptionNoMgmtIP
:
762 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
763 if detailed_status
!= detailed_status_old
:
764 detailed_status_old
= db_nsr_update
["detailed-status"] = detailed_status
765 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
766 await asyncio
.sleep(5, loop
=self
.loop
)
767 else: # total_deploy_timeout
768 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
770 step
= "Updating NSR"
771 self
.ns_update_nsr(db_nsr_update
, db_nsr
, desc
)
773 db_nsr_update
["operational-status"] = "running"
774 db_nsr
["detailed-status"] = "Deployed at VIM"
775 db_nsr_update
["detailed-status"] = "Deployed at VIM"
776 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
778 step
= "Deployed at VIM"
779 self
.logger
.debug(logging_text
+ step
)
781 # wait for ip addres at RO, and optionally, insert public key in virtual machine
783 async def insert_key_ro(self
, logging_text
, nsr_id
, vnfr_id
, vdu_id
, vdu_index
, pub_key
=None, user
=None):
792 await asyncio
.sleep(10, loop
=self
.loop
)
793 # wait until NS is deployed at RO
795 db_nsrs
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
796 ro_nsr_id
= deep_get(db_nsrs
, ("_admin", "deployed", "RO", "nsr_id"))
801 if not target_vdu_id
:
802 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnfr_id
})
804 ip_address
= db_vnfr
.get("ip-address")
807 for vdur
in get_iterable(db_vnfr
, "vdur"):
808 if (vdur
["vdu-id-ref"] == vdu_id
and vdur
["count-index"] == vdu_index
) or \
809 (ip_address
and vdur
.get("ip-address") == ip_address
):
810 if vdur
["status"] == "ACTIVE":
811 target_vdu_id
= vdur
["vdu-id-ref"]
812 elif vdur
["status"] == "ERROR":
813 raise LcmException("Cannot inject ssh-key because target VM is in error state")
816 raise LcmException("Not found vnfr_id={}, vdu_index={}, vdu_index={}".format(
817 vnfr_id
, vdu_id
, vdu_index
820 if not target_vdu_id
:
823 # inject public key into machine
826 ro_vm_id
= "{}-{}".format(db_vnfr
["member-vnf-index-ref"], target_vdu_id
) # TODO add vdu_index
827 result_dict
= await self
.RO
.create_action(
829 item_id_name
=ro_nsr_id
,
830 descriptor
={"add_public_key": pub_key
, "vms": [ro_vm_id
], "user": user
}
832 # result_dict contains the format {VM-id: {vim_result: 200, description: text}}
833 if not result_dict
or not isinstance(result_dict
, dict):
834 raise LcmException("Unknown response from RO when injecting key")
835 for result
in result_dict
.values():
836 if result
.get("vim_result") == 200:
839 raise ROclient
.ROClientException("error injecting key: {}".format(
840 result
.get("description")))
842 except ROclient
.ROClientException
as e
:
845 raise LcmException("Reaching max tries injecting key. Error: {}".format(e
))
846 self
.logger
.debug(logging_text
+ "error injecting key: {}".format(e
))
848 # no user or pub_key ---> break while true
853 async def instantiate_N2VC(self
, logging_text
, vca_index
, nsi_id
, db_nsr
, db_vnfr
, vdu_id
,
854 vdu_index
, config_descriptor
, deploy_params
, base_folder
):
855 nsr_id
= db_nsr
["_id"]
856 db_update_entry
= "_admin.deployed.VCA.{}.".format(vca_index
)
857 vca_deployed
= db_nsr
["_admin"]["deployed"]["VCA"][vca_index
]
859 'collection': 'nsrs',
860 'filter': {'_id': nsr_id
},
861 'path': db_update_entry
864 logging_text
+= "member_vnf_index={} vdu_id={}, vdu_index={} "\
865 .format(db_vnfr
["member-vnf-index-ref"], vdu_id
, vdu_index
)
871 vnfr_id
= db_vnfr
["_id"]
873 namespace
= "{nsi}.{ns}".format(
874 nsi
=nsi_id
if nsi_id
else "",
877 namespace
+= "." + vnfr_id
879 namespace
+= ".{}-{}".format(vdu_id
, vdu_index
or 0)
882 artifact_path
= "/{}/{}/charms/{}".format(
883 base_folder
["folder"],
884 base_folder
["pkg-dir"],
885 config_descriptor
["juju"]["charm"]
888 is_proxy_charm
= deep_get(config_descriptor
, ('juju', 'charm')) is not None
889 if deep_get(config_descriptor
, ('juju', 'proxy')) is False:
890 is_proxy_charm
= False
892 # n2vc_redesign STEP 3.1
894 # find old ee_id if exists
895 ee_id
= vca_deployed
.get("ee_id")
897 # create or register execution environment in VCA
899 step
= "create execution environment"
900 self
.logger
.debug(logging_text
+ step
)
901 ee_id
, credentials
= await self
.n2vc
.create_execution_environment(
908 step
= "register execution envioronment"
909 # TODO wait until deployed by RO, when IP address has been filled. By pooling????
910 credentials
= {} # TODO db_credentials["ip_address"]
912 # TODO remove this when changes on IM regarding config-access:ssh-access:default-user were
913 # merged. Meanwhile let's get username from initial-config-primitive
914 if config_descriptor
.get("initial-config-primitive"):
915 for param
in config_descriptor
["initial-config-primitive"][0].get("parameter", ()):
916 if param
["name"] == "ssh-username":
917 credentials
["username"] = param
["value"]
918 if config_descriptor
.get("config-access") and config_descriptor
["config-access"].get("ssh-access"):
919 if config_descriptor
["config-access"]["ssh-access"].get("required"):
920 credentials
["username"] = \
921 config_descriptor
["config-access"]["ssh-access"].get("default-user")
923 # n2vc_redesign STEP 3.2
924 self
.logger
.debug(logging_text
+ step
)
925 ee_id
= await self
.n2vc
.register_execution_environment(
926 credentials
=credentials
,
931 # for compatibility with MON/POL modules, the need model and application name at database
932 # TODO ask to N2VC instead of assuming the format "model_name.application_name"
933 ee_id_parts
= ee_id
.split('.')
934 model_name
= ee_id_parts
[0]
935 application_name
= ee_id_parts
[1]
936 self
.update_db_2("nsrs", nsr_id
, {db_update_entry
+ "model": model_name
,
937 db_update_entry
+ "application": application_name
,
938 db_update_entry
+ "ee_id": ee_id
})
940 # n2vc_redesign STEP 3.3
941 # TODO check if already done
942 step
= "Install configuration Software"
943 self
.logger
.debug(logging_text
+ step
)
944 await self
.n2vc
.install_configuration_sw(
946 artifact_path
=artifact_path
,
950 # if SSH access is required, then get execution environment SSH public
951 required
= deep_get(config_descriptor
, ("config-access", "ssh-access", "required"))
952 if is_proxy_charm
and required
:
955 pub_key
= await self
.n2vc
.get_ee_ssh_public__key(
960 user
= deep_get(config_descriptor
, ("config-access", "ssh-access", "default-user"))
961 # insert pub_key into VM
962 # n2vc_redesign STEP 5.1
963 step
= "Insert public key into VM"
964 self
.logger
.debug(logging_text
+ step
)
966 # wait for RO (ip-address)
967 rw_mgmt_ip
= await self
.insert_key_ro(
968 logging_text
=logging_text
,
977 # store rw_mgmt_ip in deploy params for later substitution
978 self
.logger
.debug('rw_mgmt_ip={}'.format(rw_mgmt_ip
))
979 deploy_params
["rw_mgmt_ip"] = rw_mgmt_ip
981 # n2vc_redesign STEP 6 Execute initial config primitive
982 initial_config_primitive_list
= config_descriptor
.get('initial-config-primitive', [])
983 step
= 'execute initial config primitive'
985 # sort initial config primitives by 'seq'
987 initial_config_primitive_list
.sort(key
=lambda val
: int(val
['seq']))
989 self
.logger
.warn(logging_text
+ 'Cannot sort by "seq" field' + step
)
991 for initial_config_primitive
in initial_config_primitive_list
:
992 # TODO check if already done
993 primitive_params_
= self
._map
_primitive
_params
(initial_config_primitive
, {}, deploy_params
)
994 step
= "execute primitive '{}' params '{}'".format(initial_config_primitive
["name"], primitive_params_
)
995 self
.logger
.debug(logging_text
+ step
)
996 await self
.n2vc
.exec_primitive(
998 primitive_name
=initial_config_primitive
["name"],
999 params_dict
=primitive_params_
,
1002 # TODO register in database that primitive is done
1004 step
= "instantiated at VCA"
1005 self
.logger
.debug(logging_text
+ step
)
1007 except Exception as e
: # TODO not use Exception but N2VC exception
1008 raise Exception("{} {}".format(step
, e
)) from e
1009 # TODO raise N2VC exception with 'step' extra information
1011 async def instantiate(self
, nsr_id
, nslcmop_id
):
1014 :param nsr_id: ns instance to deploy
1015 :param nslcmop_id: operation to run
1019 # Try to lock HA task here
1020 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1021 if not task_is_locked_by_me
:
1022 self
.logger
.debug('instantiate() task is not locked by me')
1025 logging_text
= "Task ns={} instantiate={} ".format(nsr_id
, nslcmop_id
)
1026 self
.logger
.debug(logging_text
+ "Enter")
1028 # get all needed from database
1030 # database nsrs record
1033 # database nslcmops record
1036 # update operation on nsrs
1037 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
}
1039 # update operation on nslcmops
1040 db_nslcmop_update
= {}
1042 nslcmop_operation_state
= None
1043 db_vnfrs
= {} # vnf's info indexed by member-index
1045 # n2vc_key_list = [] # list of public keys to be injected as authorized to VMs
1046 task_instantiation_list
= []
1049 # wait for any previous tasks in process
1050 step
= "Waiting for previous tasks"
1051 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
1053 # STEP 0: Reading database (nslcmops, nsrs, nsds, vnfrs, vnfds)
1055 # read from db: operation
1056 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1057 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1060 step
= "Getting nsr={} from db".format(nsr_id
)
1061 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1062 # nsd is replicated into ns (no db read)
1064 # nsr_name = db_nsr["name"] # TODO short-name??
1066 # read from db: vnf's of this ns
1067 step
= "Getting vnfrs from db"
1068 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1070 # read from db: vnfd's for every vnf
1071 db_vnfds_ref
= {} # every vnfd data indexed by vnf name
1072 db_vnfds
= {} # every vnfd data indexed by vnf id
1073 db_vnfds_index
= {} # every vnfd data indexed by vnf member-index
1075 # for each vnf in ns, read vnfd
1076 for vnfr
in db_vnfrs_list
:
1077 db_vnfrs
[vnfr
["member-vnf-index-ref"]] = vnfr
# vnf's dict indexed by member-index: '1', '2', etc
1078 vnfd_id
= vnfr
["vnfd-id"] # vnfd uuid for this vnf
1079 vnfd_ref
= vnfr
["vnfd-ref"] # vnfd name for this vnf
1080 # if we haven't this vnfd, read it from db
1081 if vnfd_id
not in db_vnfds
:
1083 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_ref
)
1084 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1087 db_vnfds_ref
[vnfd_ref
] = vnfd
# vnfd's indexed by name
1088 db_vnfds
[vnfd_id
] = vnfd
# vnfd's indexed by id
1089 db_vnfds_index
[vnfr
["member-vnf-index-ref"]] = db_vnfds
[vnfd_id
] # vnfd's indexed by member-index
1091 # Get or generates the _admin.deployed.VCA list
1092 vca_deployed_list
= None
1093 if db_nsr
["_admin"].get("deployed"):
1094 vca_deployed_list
= db_nsr
["_admin"]["deployed"].get("VCA")
1095 if vca_deployed_list
is None:
1096 vca_deployed_list
= []
1097 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1098 # add _admin.deployed.VCA to db_nsr dictionary, value=vca_deployed_list
1099 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1100 elif isinstance(vca_deployed_list
, dict):
1101 # maintain backward compatibility. Change a dict to list at database
1102 vca_deployed_list
= list(vca_deployed_list
.values())
1103 db_nsr_update
["_admin.deployed.VCA"] = vca_deployed_list
1104 populate_dict(db_nsr
, ("_admin", "deployed", "VCA"), vca_deployed_list
)
1106 db_nsr_update
["detailed-status"] = "creating"
1107 db_nsr_update
["operational-status"] = "init"
1109 if not isinstance(deep_get(db_nsr
, ("_admin", "deployed", "RO", "vnfd")), list):
1110 populate_dict(db_nsr
, ("_admin", "deployed", "RO", "vnfd"), [])
1111 db_nsr_update
["_admin.deployed.RO.vnfd"] = []
1113 # set state to INSTANTIATED. When instantiated NBI will not delete directly
1114 db_nsr_update
["_admin.nsState"] = "INSTANTIATED"
1115 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1117 # n2vc_redesign STEP 1 Get VCA public ssh-key
1118 # feature 1429. Add n2vc public key to needed VMs
1119 n2vc_key
= await self
.n2vc
.get_public_key()
1121 # n2vc_redesign STEP 2 Deploy Network Scenario
1122 task_ro
= asyncio
.ensure_future(
1123 self
.instantiate_RO(
1124 logging_text
=logging_text
,
1128 db_nslcmop
=db_nslcmop
,
1130 db_vnfds_ref
=db_vnfds_ref
,
1131 n2vc_key_list
=[n2vc_key
]
1134 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_RO", task_ro
)
1135 task_instantiation_list
.append(task_ro
)
1137 # n2vc_redesign STEP 3 to 6 Deploy N2VC
1138 step
= "Looking for needed vnfd to configure with proxy charm"
1139 self
.logger
.debug(logging_text
+ step
)
1141 nsi_id
= None # TODO put nsi_id when this nsr belongs to a NSI
1142 # get_iterable() returns a value from a dict or empty tuple if key does not exist
1143 for c_vnf
in get_iterable(nsd
, "constituent-vnfd"):
1144 vnfd_id
= c_vnf
["vnfd-id-ref"]
1145 vnfd
= db_vnfds_ref
[vnfd_id
]
1146 member_vnf_index
= str(c_vnf
["member-vnf-index"])
1147 db_vnfr
= db_vnfrs
[member_vnf_index
]
1148 base_folder
= vnfd
["_admin"]["storage"]
1153 # Get additional parameters
1155 if db_vnfr
.get("additionalParamsForVnf"):
1156 deploy_params
= db_vnfr
["additionalParamsForVnf"].copy()
1157 for k
, v
in deploy_params
.items():
1158 if isinstance(v
, str) and v
.startswith("!!yaml "):
1159 deploy_params
[k
] = yaml
.safe_load(v
[7:])
1161 descriptor_config
= vnfd
.get("vnf-configuration")
1162 if descriptor_config
and descriptor_config
.get("juju"):
1164 logging_text
=logging_text
,
1167 nslcmop_id
=nslcmop_id
,
1172 member_vnf_index
=member_vnf_index
,
1173 vdu_index
=vdu_index
,
1175 deploy_params
=deploy_params
,
1176 descriptor_config
=descriptor_config
,
1177 base_folder
=base_folder
,
1178 task_instantiation_list
=task_instantiation_list
1181 # Deploy charms for each VDU that supports one.
1182 for vdud
in get_iterable(vnfd
, 'vdu'):
1184 descriptor_config
= vdud
.get('vdu-configuration')
1185 if descriptor_config
and descriptor_config
.get("juju"):
1186 # look for vdu index in the db_vnfr["vdu"] section
1187 # for vdur_index, vdur in enumerate(db_vnfr["vdur"]):
1188 # if vdur["vdu-id-ref"] == vdu_id:
1191 # raise LcmException("Mismatch vdu_id={} not found in the vnfr['vdur'] list for "
1192 # "member_vnf_index={}".format(vdu_id, member_vnf_index))
1193 # vdu_name = vdur.get("name")
1195 for vdu_index
in range(int(vdud
.get("count", 1))):
1196 # TODO vnfr_params["rw_mgmt_ip"] = vdur["ip-address"]
1198 logging_text
=logging_text
,
1201 nslcmop_id
=nslcmop_id
,
1206 member_vnf_index
=member_vnf_index
,
1207 vdu_index
=vdu_index
,
1209 deploy_params
=deploy_params
,
1210 descriptor_config
=descriptor_config
,
1211 base_folder
=base_folder
,
1212 task_instantiation_list
=task_instantiation_list
1215 # Check if this NS has a charm configuration
1216 descriptor_config
= nsd
.get("ns-configuration")
1217 if descriptor_config
and descriptor_config
.get("juju"):
1220 member_vnf_index
= None
1224 # Get additional parameters
1226 if db_nsr
.get("additionalParamsForNs"):
1227 deploy_params
= db_nsr
["additionalParamsForNs"].copy()
1228 for k
, v
in deploy_params
.items():
1229 if isinstance(v
, str) and v
.startswith("!!yaml "):
1230 deploy_params
[k
] = yaml
.safe_load(v
[7:])
1231 base_folder
= nsd
["_admin"]["storage"]
1233 logging_text
=logging_text
,
1236 nslcmop_id
=nslcmop_id
,
1241 member_vnf_index
=member_vnf_index
,
1242 vdu_index
=vdu_index
,
1244 deploy_params
=deploy_params
,
1245 descriptor_config
=descriptor_config
,
1246 base_folder
=base_folder
,
1247 task_instantiation_list
=task_instantiation_list
1250 # Wait until all tasks of "task_instantiation_list" have been finished
1252 # while time() <= start_deploy + self.total_deploy_timeout:
1254 timeout
= 3600 # time() - start_deploy
1255 task_instantiation_set
= set(task_instantiation_list
) # build a set with tasks
1258 if len(task_instantiation_set
) > 0:
1259 done
, pending
= await asyncio
.wait(task_instantiation_set
, timeout
=timeout
)
1261 error_text
= "timeout"
1263 if task
.cancelled():
1265 error_text
= "cancelled"
1267 exc
= task
.exception()
1269 error_text
= str(exc
)
1272 db_nsr_update
["config-status"] = "failed"
1273 error_text
= "fail configuring " + error_text
1274 db_nsr_update
["detailed-status"] = error_text
1275 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED_TEMP"
1276 db_nslcmop_update
["detailed-status"] = error_text
1277 db_nslcmop_update
["statusEnteredTime"] = time()
1280 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
1281 db_nslcmop_update
["statusEnteredTime"] = time()
1282 db_nslcmop_update
["detailed-status"] = "done"
1283 db_nsr_update
["config-status"] = "configured"
1284 db_nsr_update
["detailed-status"] = "done"
1288 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1289 self
.logger
.error(logging_text
+ "Exit Exception while '{}': {}".format(step
, e
))
1291 except asyncio
.CancelledError
:
1292 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1293 exc
= "Operation was cancelled"
1294 except Exception as e
:
1295 exc
= traceback
.format_exc()
1296 self
.logger
.critical(logging_text
+ "Exit Exception {} while '{}': {}".format(type(e
).__name
__, step
, e
),
1301 db_nsr_update
["detailed-status"] = "ERROR {}: {}".format(step
, exc
)
1302 db_nsr_update
["operational-status"] = "failed"
1304 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1305 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1306 db_nslcmop_update
["statusEnteredTime"] = time()
1309 db_nsr_update
["_admin.nslcmop"] = None
1310 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1311 if db_nslcmop_update
:
1312 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1313 except DbException
as e
:
1314 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
1315 if nslcmop_operation_state
:
1317 await self
.msg
.aiowrite("ns", "instantiated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1318 "operationState": nslcmop_operation_state
},
1320 except Exception as e
:
1321 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1323 self
.logger
.debug(logging_text
+ "Exit")
1324 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_instantiate")
1326 def _deploy_n2vc(self
, logging_text
, db_nsr
, db_vnfr
, nslcmop_id
, nsr_id
, nsi_id
, vnfd_id
, vdu_id
,
1327 member_vnf_index
, vdu_index
, vdu_name
, deploy_params
, descriptor_config
,
1328 base_folder
, task_instantiation_list
):
1329 # launch instantiate_N2VC in a asyncio task and register task object
1330 # Look where information of this charm is at database <nsrs>._admin.deployed.VCA
1331 # if not found, create one entry and update database
1333 # fill db_nsr._admin.deployed.VCA.<index>
1335 for vca_index
, vca_deployed
in enumerate(db_nsr
["_admin"]["deployed"]["VCA"]):
1336 if not vca_deployed
:
1338 if vca_deployed
.get("member-vnf-index") == member_vnf_index
and \
1339 vca_deployed
.get("vdu_id") == vdu_id
and \
1340 vca_deployed
.get("vdu_count_index", 0) == vdu_index
:
1343 # not found, create one.
1345 "member-vnf-index": member_vnf_index
,
1347 "vdu_count_index": vdu_index
,
1348 "operational-status": "init", # TODO revise
1349 "detailed-status": "", # TODO revise
1350 "step": "initial-deploy", # TODO revise
1352 "vdu_name": vdu_name
,
1355 self
.update_db_2("nsrs", nsr_id
, {"_admin.deployed.VCA.{}".format(vca_index
): vca_deployed
})
1356 db_nsr
["_admin"]["deployed"]["VCA"].append(vca_deployed
)
1359 task_n2vc
= asyncio
.ensure_future(
1360 self
.instantiate_N2VC(
1361 logging_text
=logging_text
,
1362 vca_index
=vca_index
,
1367 vdu_index
=vdu_index
,
1368 deploy_params
=deploy_params
,
1369 config_descriptor
=descriptor_config
,
1370 base_folder
=base_folder
,
1373 self
.lcm_tasks
.register("ns", nsr_id
, nslcmop_id
, "instantiate_N2VC-{}".format(vca_index
), task_n2vc
)
1374 task_instantiation_list
.append(task_n2vc
)
1376 # Check if this VNFD has a configured terminate action
1377 def _has_terminate_config_primitive(self
, vnfd
):
1378 vnf_config
= vnfd
.get("vnf-configuration")
1379 if vnf_config
and vnf_config
.get("terminate-config-primitive"):
1385 def _get_terminate_config_primitive_seq_list(vnfd
):
1386 """ Get a numerically sorted list of the sequences for this VNFD's terminate action """
1387 # No need to check for existing primitive twice, already done before
1388 vnf_config
= vnfd
.get("vnf-configuration")
1389 seq_list
= vnf_config
.get("terminate-config-primitive")
1390 # Get all 'seq' tags in seq_list, order sequences numerically, ascending.
1391 seq_list_sorted
= sorted(seq_list
, key
=lambda x
: int(x
['seq']))
1392 return seq_list_sorted
1395 def _create_nslcmop(nsr_id
, operation
, params
):
1397 Creates a ns-lcm-opp content to be stored at database.
1398 :param nsr_id: internal id of the instance
1399 :param operation: instantiate, terminate, scale, action, ...
1400 :param params: user parameters for the operation
1401 :return: dictionary following SOL005 format
1403 # Raise exception if invalid arguments
1404 if not (nsr_id
and operation
and params
):
1406 "Parameters 'nsr_id', 'operation' and 'params' needed to create primitive not provided")
1412 # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1413 "operationState": "PROCESSING",
1414 "statusEnteredTime": now
,
1415 "nsInstanceId": nsr_id
,
1416 "lcmOperationType": operation
,
1418 "isAutomaticInvocation": False,
1419 "operationParams": params
,
1420 "isCancelPending": False,
1422 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
1423 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
1428 def _get_terminate_primitive_params(self
, seq
, vnf_index
):
1429 primitive
= seq
.get('name')
1430 primitive_params
= {}
1432 "member_vnf_index": vnf_index
,
1433 "primitive": primitive
,
1434 "primitive_params": primitive_params
,
1437 return self
._map
_primitive
_params
(seq
, params
, desc_params
)
1441 def _reintent_or_skip_suboperation(self
, db_nslcmop
, op_index
):
1442 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
1443 if (op
.get('operationState') == 'COMPLETED'):
1444 # b. Skip sub-operation
1445 # _ns_execute_primitive() or RO.create_action() will NOT be executed
1446 return self
.SUBOPERATION_STATUS_SKIP
1448 # c. Reintent executing sub-operation
1449 # The sub-operation exists, and operationState != 'COMPLETED'
1450 # Update operationState = 'PROCESSING' to indicate a reintent.
1451 operationState
= 'PROCESSING'
1452 detailed_status
= 'In progress'
1453 self
._update
_suboperation
_status
(
1454 db_nslcmop
, op_index
, operationState
, detailed_status
)
1455 # Return the sub-operation index
1456 # _ns_execute_primitive() or RO.create_action() will be called from scale()
1457 # with arguments extracted from the sub-operation
1460 # Find a sub-operation where all keys in a matching dictionary must match
1461 # Returns the index of the matching sub-operation, or SUBOPERATION_STATUS_NOT_FOUND if no match
1462 def _find_suboperation(self
, db_nslcmop
, match
):
1463 if (db_nslcmop
and match
):
1464 op_list
= db_nslcmop
.get('_admin', {}).get('operations', [])
1465 for i
, op
in enumerate(op_list
):
1466 if all(op
.get(k
) == match
[k
] for k
in match
):
1468 return self
.SUBOPERATION_STATUS_NOT_FOUND
1470 # Update status for a sub-operation given its index
1471 def _update_suboperation_status(self
, db_nslcmop
, op_index
, operationState
, detailed_status
):
1472 # Update DB for HA tasks
1473 q_filter
= {'_id': db_nslcmop
['_id']}
1474 update_dict
= {'_admin.operations.{}.operationState'.format(op_index
): operationState
,
1475 '_admin.operations.{}.detailed-status'.format(op_index
): detailed_status
}
1476 self
.db
.set_one("nslcmops",
1478 update_dict
=update_dict
,
1479 fail_on_empty
=False)
1481 # Add sub-operation, return the index of the added sub-operation
1482 # Optionally, set operationState, detailed-status, and operationType
1483 # Status and type are currently set for 'scale' sub-operations:
1484 # 'operationState' : 'PROCESSING' | 'COMPLETED' | 'FAILED'
1485 # 'detailed-status' : status message
1486 # 'operationType': may be any type, in the case of scaling: 'PRE-SCALE' | 'POST-SCALE'
1487 # Status and operation type are currently only used for 'scale', but NOT for 'terminate' sub-operations.
1488 def _add_suboperation(self
, db_nslcmop
, vnf_index
, vdu_id
, vdu_count_index
, vdu_name
, primitive
,
1489 mapped_primitive_params
, operationState
=None, detailed_status
=None, operationType
=None,
1490 RO_nsr_id
=None, RO_scaling_info
=None):
1491 if not (db_nslcmop
):
1492 return self
.SUBOPERATION_STATUS_NOT_FOUND
1493 # Get the "_admin.operations" list, if it exists
1494 db_nslcmop_admin
= db_nslcmop
.get('_admin', {})
1495 op_list
= db_nslcmop_admin
.get('operations')
1496 # Create or append to the "_admin.operations" list
1497 new_op
= {'member_vnf_index': vnf_index
,
1499 'vdu_count_index': vdu_count_index
,
1500 'primitive': primitive
,
1501 'primitive_params': mapped_primitive_params
}
1503 new_op
['operationState'] = operationState
1505 new_op
['detailed-status'] = detailed_status
1507 new_op
['lcmOperationType'] = operationType
1509 new_op
['RO_nsr_id'] = RO_nsr_id
1511 new_op
['RO_scaling_info'] = RO_scaling_info
1513 # No existing operations, create key 'operations' with current operation as first list element
1514 db_nslcmop_admin
.update({'operations': [new_op
]})
1515 op_list
= db_nslcmop_admin
.get('operations')
1517 # Existing operations, append operation to list
1518 op_list
.append(new_op
)
1520 db_nslcmop_update
= {'_admin.operations': op_list
}
1521 self
.update_db_2("nslcmops", db_nslcmop
['_id'], db_nslcmop_update
)
1522 op_index
= len(op_list
) - 1
1525 # Helper methods for scale() sub-operations
1527 # pre-scale/post-scale:
1528 # Check for 3 different cases:
1529 # a. New: First time execution, return SUBOPERATION_STATUS_NEW
1530 # b. Skip: Existing sub-operation exists, operationState == 'COMPLETED', return SUBOPERATION_STATUS_SKIP
1531 # c. Reintent: Existing sub-operation exists, operationState != 'COMPLETED', return op_index to re-execute
1532 def _check_or_add_scale_suboperation(self
, db_nslcmop
, vnf_index
, vnf_config_primitive
, primitive_params
,
1533 operationType
, RO_nsr_id
=None, RO_scaling_info
=None):
1534 # Find this sub-operation
1535 if (RO_nsr_id
and RO_scaling_info
):
1536 operationType
= 'SCALE-RO'
1538 'member_vnf_index': vnf_index
,
1539 'RO_nsr_id': RO_nsr_id
,
1540 'RO_scaling_info': RO_scaling_info
,
1544 'member_vnf_index': vnf_index
,
1545 'primitive': vnf_config_primitive
,
1546 'primitive_params': primitive_params
,
1547 'lcmOperationType': operationType
1549 op_index
= self
._find
_suboperation
(db_nslcmop
, match
)
1550 if (op_index
== self
.SUBOPERATION_STATUS_NOT_FOUND
):
1551 # a. New sub-operation
1552 # The sub-operation does not exist, add it.
1553 # _ns_execute_primitive() will be called from scale() as usual, with non-modified arguments
1554 # The following parameters are set to None for all kind of scaling:
1556 vdu_count_index
= None
1558 if (RO_nsr_id
and RO_scaling_info
):
1559 vnf_config_primitive
= None
1560 primitive_params
= None
1563 RO_scaling_info
= None
1564 # Initial status for sub-operation
1565 operationState
= 'PROCESSING'
1566 detailed_status
= 'In progress'
1567 # Add sub-operation for pre/post-scaling (zero or more operations)
1568 self
._add
_suboperation
(db_nslcmop
,
1573 vnf_config_primitive
,
1580 return self
.SUBOPERATION_STATUS_NEW
1582 # Return either SUBOPERATION_STATUS_SKIP (operationState == 'COMPLETED'),
1583 # or op_index (operationState != 'COMPLETED')
1584 return self
._reintent
_or
_skip
_suboperation
(db_nslcmop
, op_index
)
1586 # Helper methods for terminate()
1588 async def _terminate_action(self
, db_nslcmop
, nslcmop_id
, nsr_id
):
1589 """ Create a primitive with params from VNFD
1590 Called from terminate() before deleting instance
1591 Calls action() to execute the primitive """
1592 logging_text
= "Task ns={} _terminate_action={} ".format(nsr_id
, nslcmop_id
)
1593 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1596 for vnfr
in db_vnfrs_list
:
1597 vnfd_id
= vnfr
["vnfd-id"]
1598 vnf_index
= vnfr
["member-vnf-index-ref"]
1599 if vnfd_id
not in db_vnfds
:
1600 step
= "Getting vnfd={} id='{}' from db".format(vnfd_id
, vnfd_id
)
1601 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
1602 db_vnfds
[vnfd_id
] = vnfd
1603 vnfd
= db_vnfds
[vnfd_id
]
1604 if not self
._has
_terminate
_config
_primitive
(vnfd
):
1606 # Get the primitive's sorted sequence list
1607 seq_list
= self
._get
_terminate
_config
_primitive
_seq
_list
(vnfd
)
1608 for seq
in seq_list
:
1609 # For each sequence in list, get primitive and call _ns_execute_primitive()
1610 step
= "Calling terminate action for vnf_member_index={} primitive={}".format(
1611 vnf_index
, seq
.get("name"))
1612 self
.logger
.debug(logging_text
+ step
)
1613 # Create the primitive for each sequence, i.e. "primitive": "touch"
1614 primitive
= seq
.get('name')
1615 mapped_primitive_params
= self
._get
_terminate
_primitive
_params
(seq
, vnf_index
)
1616 # The following 3 parameters are currently set to None for 'terminate':
1617 # vdu_id, vdu_count_index, vdu_name
1618 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
1619 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
1620 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
1622 self
._add
_suboperation
(db_nslcmop
,
1629 mapped_primitive_params
)
1630 # Sub-operations: Call _ns_execute_primitive() instead of action()
1631 # db_nsr = self.db.get_one("nsrs", {"_id": nsr_id})
1632 # nsr_deployed = db_nsr["_admin"]["deployed"]
1634 # nslcmop_operation_state, nslcmop_operation_state_detail = await self.action(
1635 # nsr_id, nslcmop_terminate_action_id)
1636 # Launch Exception if action() returns other than ['COMPLETED', 'PARTIALLY_COMPLETED']
1637 # result_ok = ['COMPLETED', 'PARTIALLY_COMPLETED']
1638 # if result not in result_ok:
1639 # raise LcmException(
1640 # "terminate_primitive_action for vnf_member_index={}",
1641 # " primitive={} fails with error {}".format(
1642 # vnf_index, seq.get("name"), result_detail))
1647 await self
.n2vc
.exec_primitive(
1649 primitive_name
=primitive
,
1650 params_dict
=mapped_primitive_params
1652 except Exception as e
:
1653 self
.logger
.error('Error executing primitive {}: {}'.format(primitive
, e
))
1655 "terminate_primitive_action for vnf_member_index={}, primitive={} fails with error {}"
1656 .format(vnf_index
, seq
.get("name"), e
),
1659 async def terminate(self
, nsr_id
, nslcmop_id
):
1661 # Try to lock HA task here
1662 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1663 if not task_is_locked_by_me
:
1666 logging_text
= "Task ns={} terminate={} ".format(nsr_id
, nslcmop_id
)
1667 self
.logger
.debug(logging_text
+ "Enter")
1671 failed_detail
= [] # annotates all failed error messages
1672 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
}
1673 db_nslcmop_update
= {}
1674 nslcmop_operation_state
= None
1675 autoremove
= False # autoremove after terminated
1677 # wait for any previous tasks in process
1678 await self
.lcm_tasks
.waitfor_related_HA("ns", 'nslcmops', nslcmop_id
)
1680 step
= "Getting nslcmop={} from db".format(nslcmop_id
)
1681 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
1682 step
= "Getting nsr={} from db".format(nsr_id
)
1683 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1684 # nsd = db_nsr["nsd"]
1685 nsr_deployed
= deepcopy(db_nsr
["_admin"].get("deployed"))
1686 if db_nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1688 # #TODO check if VIM is creating and wait
1689 # RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
1690 # Call internal terminate action
1691 await self
._terminate
_action
(db_nslcmop
, nslcmop_id
, nsr_id
)
1695 db_nsr_update
["operational-status"] = "terminating"
1696 db_nsr_update
["config-status"] = "terminating"
1700 step
= "delete execution environment"
1701 self
.logger
.debug(logging_text
+ step
)
1703 task_delete_ee
= asyncio
.ensure_future(self
.n2vc
.delete_namespace(namespace
="." + nsr_id
))
1704 pending_tasks
.append(task_delete_ee
)
1705 except Exception as e
:
1706 msg
= "Failed while deleting NS in VCA: {}".format(e
)
1707 self
.logger
.error(msg
)
1708 failed_detail
.append(msg
)
1714 RO_nsr_id
= RO_delete_action
= None
1715 if nsr_deployed
and nsr_deployed
.get("RO"):
1716 RO_nsr_id
= nsr_deployed
["RO"].get("nsr_id")
1717 RO_delete_action
= nsr_deployed
["RO"].get("nsr_delete_action_id")
1720 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] = \
1721 "Deleting ns from VIM"
1722 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1723 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1724 self
.logger
.debug(logging_text
+ step
)
1725 desc
= await self
.RO
.delete("ns", RO_nsr_id
)
1726 RO_delete_action
= desc
["action_id"]
1727 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = RO_delete_action
1728 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1729 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1730 if RO_delete_action
:
1731 # wait until NS is deleted from VIM
1732 step
= detailed_status
= "Waiting ns deleted from VIM. RO_id={} RO_delete_action={}".\
1733 format(RO_nsr_id
, RO_delete_action
)
1734 detailed_status_old
= None
1735 self
.logger
.debug(logging_text
+ step
)
1737 delete_timeout
= 20 * 60 # 20 minutes
1738 while delete_timeout
> 0:
1739 desc
= await self
.RO
.show(
1741 item_id_name
=RO_nsr_id
,
1742 extra_item
="action",
1743 extra_item_id
=RO_delete_action
)
1744 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
1745 if ns_status
== "ERROR":
1746 raise ROclient
.ROClientException(ns_status_info
)
1747 elif ns_status
== "BUILD":
1748 detailed_status
= step
+ "; {}".format(ns_status_info
)
1749 elif ns_status
== "ACTIVE":
1750 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
1751 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1754 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
1755 if detailed_status
!= detailed_status_old
:
1756 detailed_status_old
= db_nslcmop_update
["detailed-status"] = \
1757 db_nsr_update
["detailed-status"] = detailed_status
1758 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1759 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1760 await asyncio
.sleep(5, loop
=self
.loop
)
1762 else: # delete_timeout <= 0:
1763 raise ROclient
.ROClientException("Timeout waiting ns deleted from VIM")
1765 except ROclient
.ROClientException
as e
:
1766 if e
.http_code
== 404: # not found
1767 db_nsr_update
["_admin.deployed.RO.nsr_id"] = None
1768 db_nsr_update
["_admin.deployed.RO.nsr_status"] = "DELETED"
1769 db_nsr_update
["_admin.deployed.RO.nsr_delete_action_id"] = None
1770 self
.logger
.debug(logging_text
+ "RO_ns_id={} already deleted".format(RO_nsr_id
))
1771 elif e
.http_code
== 409: # conflict
1772 failed_detail
.append("RO_ns_id={} delete conflict: {}".format(RO_nsr_id
, e
))
1773 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1776 failed_detail
.append("RO_ns_id={} delete error: {}".format(RO_nsr_id
, e
))
1777 self
.logger
.error(logging_text
+ failed_detail
[-1])
1781 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("nsd_id"):
1782 RO_nsd_id
= nsr_deployed
["RO"]["nsd_id"]
1784 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1785 "Deleting nsd from RO"
1786 await self
.RO
.delete("nsd", RO_nsd_id
)
1787 self
.logger
.debug(logging_text
+ "RO_nsd_id={} deleted".format(RO_nsd_id
))
1788 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
1789 except ROclient
.ROClientException
as e
:
1790 if e
.http_code
== 404: # not found
1791 db_nsr_update
["_admin.deployed.RO.nsd_id"] = None
1792 self
.logger
.debug(logging_text
+ "RO_nsd_id={} already deleted".format(RO_nsd_id
))
1793 elif e
.http_code
== 409: # conflict
1794 failed_detail
.append("RO_nsd_id={} delete conflict: {}".format(RO_nsd_id
, e
))
1795 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1798 failed_detail
.append("RO_nsd_id={} delete error: {}".format(RO_nsd_id
, e
))
1799 self
.logger
.error(logging_text
+ failed_detail
[-1])
1802 if not RO_fail
and nsr_deployed
and nsr_deployed
.get("RO") and nsr_deployed
["RO"].get("vnfd"):
1803 for index
, vnf_deployed
in enumerate(nsr_deployed
["RO"]["vnfd"]):
1804 if not vnf_deployed
or not vnf_deployed
["id"]:
1807 RO_vnfd_id
= vnf_deployed
["id"]
1808 step
= db_nsr_update
["detailed-status"] = db_nslcmop_update
["detailed-status"] =\
1809 "Deleting member_vnf_index={} RO_vnfd_id={} from RO".format(
1810 vnf_deployed
["member-vnf-index"], RO_vnfd_id
)
1811 await self
.RO
.delete("vnfd", RO_vnfd_id
)
1812 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} deleted".format(RO_vnfd_id
))
1813 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
1814 except ROclient
.ROClientException
as e
:
1815 if e
.http_code
== 404: # not found
1816 db_nsr_update
["_admin.deployed.RO.vnfd.{}.id".format(index
)] = None
1817 self
.logger
.debug(logging_text
+ "RO_vnfd_id={} already deleted ".format(RO_vnfd_id
))
1818 elif e
.http_code
== 409: # conflict
1819 failed_detail
.append("RO_vnfd_id={} delete conflict: {}".format(RO_vnfd_id
, e
))
1820 self
.logger
.debug(logging_text
+ failed_detail
[-1])
1822 failed_detail
.append("RO_vnfd_id={} delete error: {}".format(RO_vnfd_id
, e
))
1823 self
.logger
.error(logging_text
+ failed_detail
[-1])
1826 self
.logger
.error(logging_text
+ " ;".join(failed_detail
))
1827 db_nsr_update
["operational-status"] = "failed"
1828 db_nsr_update
["detailed-status"] = "Deletion errors " + "; ".join(failed_detail
)
1829 db_nslcmop_update
["detailed-status"] = "; ".join(failed_detail
)
1830 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1831 db_nslcmop_update
["statusEnteredTime"] = time()
1833 db_nsr_update
["operational-status"] = "terminated"
1834 db_nsr_update
["detailed-status"] = "Done"
1835 db_nsr_update
["_admin.nsState"] = "NOT_INSTANTIATED"
1836 db_nslcmop_update
["detailed-status"] = "Done"
1837 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
1838 db_nslcmop_update
["statusEnteredTime"] = time()
1839 if db_nslcmop
["operationParams"].get("autoremove"):
1842 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
1843 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
1845 except asyncio
.CancelledError
:
1846 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
1847 exc
= "Operation was cancelled"
1848 except Exception as e
:
1849 exc
= traceback
.format_exc()
1850 self
.logger
.critical(logging_text
+ "Exit Exception {}".format(e
), exc_info
=True)
1852 if exc
and db_nslcmop
:
1853 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
1854 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
1855 db_nslcmop_update
["statusEnteredTime"] = time()
1857 if db_nslcmop
and db_nslcmop_update
:
1858 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
1860 db_nsr_update
["_admin.nslcmop"] = None
1861 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
1862 except DbException
as e
:
1863 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
1864 if nslcmop_operation_state
:
1866 await self
.msg
.aiowrite("ns", "terminated", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
1867 "operationState": nslcmop_operation_state
,
1868 "autoremove": autoremove
},
1870 except Exception as e
:
1871 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
1873 # wait for pending tasks
1877 self
.logger
.debug(logging_text
+ 'Waiting for terminate pending tasks...')
1878 done
, pending
= await asyncio
.wait(pending_tasks
, timeout
=3600)
1880 self
.logger
.debug(logging_text
+ 'All tasks finished...')
1882 self
.logger
.info(logging_text
+ 'There are pending tasks: {}'.format(pending
))
1884 self
.logger
.debug(logging_text
+ "Exit")
1885 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_terminate")
1888 def _map_primitive_params(primitive_desc
, params
, instantiation_params
):
1890 Generates the params to be provided to charm before executing primitive. If user does not provide a parameter,
1891 The default-value is used. If it is between < > it look for a value at instantiation_params
1892 :param primitive_desc: portion of VNFD/NSD that describes primitive
1893 :param params: Params provided by user
1894 :param instantiation_params: Instantiation params provided by user
1895 :return: a dictionary with the calculated params
1897 calculated_params
= {}
1898 for parameter
in primitive_desc
.get("parameter", ()):
1899 param_name
= parameter
["name"]
1900 if param_name
in params
:
1901 calculated_params
[param_name
] = params
[param_name
]
1902 elif "default-value" in parameter
or "value" in parameter
:
1903 if "value" in parameter
:
1904 calculated_params
[param_name
] = parameter
["value"]
1906 calculated_params
[param_name
] = parameter
["default-value"]
1907 if isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("<") \
1908 and calculated_params
[param_name
].endswith(">"):
1909 if calculated_params
[param_name
][1:-1] in instantiation_params
:
1910 calculated_params
[param_name
] = instantiation_params
[calculated_params
[param_name
][1:-1]]
1912 raise LcmException("Parameter {} needed to execute primitive {} not provided".
1913 format(calculated_params
[param_name
], primitive_desc
["name"]))
1915 raise LcmException("Parameter {} needed to execute primitive {} not provided".
1916 format(param_name
, primitive_desc
["name"]))
1918 if isinstance(calculated_params
[param_name
], (dict, list, tuple)):
1919 calculated_params
[param_name
] = yaml
.safe_dump(calculated_params
[param_name
], default_flow_style
=True,
1921 elif isinstance(calculated_params
[param_name
], str) and calculated_params
[param_name
].startswith("!!yaml "):
1922 calculated_params
[param_name
] = calculated_params
[param_name
][7:]
1923 return calculated_params
1925 async def _ns_execute_primitive(self
, db_deployed
, member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
,
1926 primitive
, primitive_params
, retries
=0, retries_interval
=30) -> str, str:
1928 # find vca_deployed record for this action
1930 for vca_deployed
in db_deployed
["VCA"]:
1931 if not vca_deployed
:
1933 if member_vnf_index
!= vca_deployed
["member-vnf-index"] or vdu_id
!= vca_deployed
["vdu_id"]:
1935 if vdu_name
and vdu_name
!= vca_deployed
["vdu_name"]:
1937 if vdu_count_index
and vdu_count_index
!= vca_deployed
["vdu_count_index"]:
1941 # vca_deployed not found
1942 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} is not "
1943 "deployed".format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
1946 ee_id
= vca_deployed
.get("ee_id")
1948 raise LcmException("charm for member_vnf_index={} vdu_id={} vdu_name={} vdu_count_index={} has not "
1949 "execution environment"
1950 .format(member_vnf_index
, vdu_id
, vdu_name
, vdu_count_index
))
1952 if primitive
== "config":
1953 primitive_params
= {"params": primitive_params
}
1957 output
= await self
.n2vc
.exec_primitive(
1959 primitive_name
=primitive
,
1960 params_dict
=primitive_params
1964 except Exception as e
:
1965 self
.logger
.debug('Error executing action {} on {} -> {}'.format(primitive
, ee_id
, e
))
1969 await asyncio
.sleep(retries_interval
, loop
=self
.loop
)
1971 return 'Cannot execute action {} on {}: {}'.format(primitive
, ee_id
, e
), 'FAIL'
1975 except Exception as e
:
1976 return 'Error executing action {}: {}'.format(primitive
, e
), 'FAIL'
1978 async def action(self
, nsr_id
, nslcmop_id
):
1980 # Try to lock HA task here
1981 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
1982 if not task_is_locked_by_me
:
1985 logging_text
= "Task ns={} action={} ".format(nsr_id
, nslcmop_id
)
1986 self
.logger
.debug(logging_text
+ "Enter")
1987 # get all needed from database
1990 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
}
1991 db_nslcmop_update
= {}
1992 nslcmop_operation_state
= None
1993 nslcmop_operation_state_detail
= None
1996 # wait for any previous tasks in process
1997 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
1999 step
= "Getting information from database"
2000 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2001 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2003 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2004 vnf_index
= db_nslcmop
["operationParams"].get("member_vnf_index")
2005 vdu_id
= db_nslcmop
["operationParams"].get("vdu_id")
2006 vdu_count_index
= db_nslcmop
["operationParams"].get("vdu_count_index")
2007 vdu_name
= db_nslcmop
["operationParams"].get("vdu_name")
2010 step
= "Getting vnfr from database"
2011 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2012 step
= "Getting vnfd from database"
2013 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2015 if db_nsr
.get("nsd"):
2016 db_nsd
= db_nsr
.get("nsd") # TODO this will be removed
2018 step
= "Getting nsd from database"
2019 db_nsd
= self
.db
.get_one("nsds", {"_id": db_nsr
["nsd-id"]})
2021 # for backward compatibility
2022 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2023 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2024 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2025 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2027 primitive
= db_nslcmop
["operationParams"]["primitive"]
2028 primitive_params
= db_nslcmop
["operationParams"]["primitive_params"]
2030 # look for primitive
2031 config_primitive_desc
= None
2033 for vdu
in get_iterable(db_vnfd
, "vdu"):
2034 if vdu_id
== vdu
["id"]:
2035 for config_primitive
in vdu
.get("vdu-configuration", {}).get("config-primitive", ()):
2036 if config_primitive
["name"] == primitive
:
2037 config_primitive_desc
= config_primitive
2040 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2041 if config_primitive
["name"] == primitive
:
2042 config_primitive_desc
= config_primitive
2045 for config_primitive
in db_nsd
.get("ns-configuration", {}).get("config-primitive", ()):
2046 if config_primitive
["name"] == primitive
:
2047 config_primitive_desc
= config_primitive
2050 if not config_primitive_desc
:
2051 raise LcmException("Primitive {} not found at [ns|vnf|vdu]-configuration:config-primitive ".
2056 if db_vnfr
.get("additionalParamsForVnf"):
2057 desc_params
.update(db_vnfr
["additionalParamsForVnf"])
2059 if db_nsr
.get("additionalParamsForVnf"):
2060 desc_params
.update(db_nsr
["additionalParamsForNs"])
2062 # TODO check if ns is in a proper status
2063 output
, detail
= await self
._ns
_execute
_primitive
(
2064 db_deployed
=nsr_deployed
,
2065 member_vnf_index
=vnf_index
,
2068 vdu_count_index
=vdu_count_index
,
2069 primitive
=primitive
,
2070 primitive_params
=self
._map
_primitive
_params
(config_primitive_desc
, primitive_params
, desc_params
))
2072 detailed_status
= output
2074 result
= 'COMPLETED'
2078 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= detailed_status
2079 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= result
2080 db_nslcmop_update
["statusEnteredTime"] = time()
2081 self
.logger
.debug(logging_text
+ " task Done with result {} {}".format(result
, detailed_status
))
2082 return # database update is called inside finally
2084 except (DbException
, LcmException
) as e
:
2085 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2087 except asyncio
.CancelledError
:
2088 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2089 exc
= "Operation was cancelled"
2090 except Exception as e
:
2091 exc
= traceback
.format_exc()
2092 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2094 if exc
and db_nslcmop
:
2095 db_nslcmop_update
["detailed-status"] = nslcmop_operation_state_detail
= \
2096 "FAILED {}: {}".format(step
, exc
)
2097 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2098 db_nslcmop_update
["statusEnteredTime"] = time()
2100 if db_nslcmop_update
:
2101 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2103 db_nsr_update
["_admin.nslcmop"] = None
2104 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2105 except DbException
as e
:
2106 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2107 self
.logger
.debug(logging_text
+ "Exit")
2108 if nslcmop_operation_state
:
2110 await self
.msg
.aiowrite("ns", "actioned", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2111 "operationState": nslcmop_operation_state
},
2113 except Exception as e
:
2114 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2115 self
.logger
.debug(logging_text
+ "Exit")
2116 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_action")
2117 return nslcmop_operation_state
, nslcmop_operation_state_detail
2119 async def scale(self
, nsr_id
, nslcmop_id
):
2121 # Try to lock HA task here
2122 task_is_locked_by_me
= self
.lcm_tasks
.lock_HA('ns', 'nslcmops', nslcmop_id
)
2123 if not task_is_locked_by_me
:
2126 logging_text
= "Task ns={} scale={} ".format(nsr_id
, nslcmop_id
)
2127 self
.logger
.debug(logging_text
+ "Enter")
2128 # get all needed from database
2131 db_nslcmop_update
= {}
2132 nslcmop_operation_state
= None
2133 db_nsr_update
= {"_admin.nslcmop": nslcmop_id
}
2135 # in case of error, indicates what part of scale was failed to put nsr at error status
2136 scale_process
= None
2137 old_operational_status
= ""
2138 old_config_status
= ""
2141 # wait for any previous tasks in process
2142 await self
.lcm_tasks
.waitfor_related_HA('ns', 'nslcmops', nslcmop_id
)
2144 step
= "Getting nslcmop from database"
2145 self
.logger
.debug(step
+ " after having waited for previous tasks to be completed")
2146 db_nslcmop
= self
.db
.get_one("nslcmops", {"_id": nslcmop_id
})
2147 step
= "Getting nsr from database"
2148 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2150 old_operational_status
= db_nsr
["operational-status"]
2151 old_config_status
= db_nsr
["config-status"]
2152 step
= "Parsing scaling parameters"
2153 # self.logger.debug(step)
2154 db_nsr_update
["operational-status"] = "scaling"
2155 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2156 nsr_deployed
= db_nsr
["_admin"].get("deployed")
2157 RO_nsr_id
= nsr_deployed
["RO"]["nsr_id"]
2158 vnf_index
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["member-vnf-index"]
2159 scaling_group
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
2160 scaling_type
= db_nslcmop
["operationParams"]["scaleVnfData"]["scaleVnfType"]
2161 # scaling_policy = db_nslcmop["operationParams"]["scaleVnfData"]["scaleByStepData"].get("scaling-policy")
2163 # for backward compatibility
2164 if nsr_deployed
and isinstance(nsr_deployed
.get("VCA"), dict):
2165 nsr_deployed
["VCA"] = list(nsr_deployed
["VCA"].values())
2166 db_nsr_update
["_admin.deployed.VCA"] = nsr_deployed
["VCA"]
2167 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2169 step
= "Getting vnfr from database"
2170 db_vnfr
= self
.db
.get_one("vnfrs", {"member-vnf-index-ref": vnf_index
, "nsr-id-ref": nsr_id
})
2171 step
= "Getting vnfd from database"
2172 db_vnfd
= self
.db
.get_one("vnfds", {"_id": db_vnfr
["vnfd-id"]})
2174 step
= "Getting scaling-group-descriptor"
2175 for scaling_descriptor
in db_vnfd
["scaling-group-descriptor"]:
2176 if scaling_descriptor
["name"] == scaling_group
:
2179 raise LcmException("input parameter 'scaleByStepData':'scaling-group-descriptor':'{}' is not present "
2180 "at vnfd:scaling-group-descriptor".format(scaling_group
))
2183 # for scaling_policy_descriptor in scaling_descriptor.get("scaling-policy", ()):
2184 # cooldown_time = scaling_policy_descriptor.get("cooldown-time", 0)
2185 # if scaling_policy and scaling_policy == scaling_policy_descriptor.get("name"):
2188 # TODO check if ns is in a proper status
2189 step
= "Sending scale order to VIM"
2191 if not db_nsr
["_admin"].get("scaling-group"):
2192 self
.update_db_2("nsrs", nsr_id
, {"_admin.scaling-group": [{"name": scaling_group
, "nb-scale-op": 0}]})
2193 admin_scale_index
= 0
2195 for admin_scale_index
, admin_scale_info
in enumerate(db_nsr
["_admin"]["scaling-group"]):
2196 if admin_scale_info
["name"] == scaling_group
:
2197 nb_scale_op
= admin_scale_info
.get("nb-scale-op", 0)
2199 else: # not found, set index one plus last element and add new entry with the name
2200 admin_scale_index
+= 1
2201 db_nsr_update
["_admin.scaling-group.{}.name".format(admin_scale_index
)] = scaling_group
2202 RO_scaling_info
= []
2203 vdu_scaling_info
= {"scaling_group_name": scaling_group
, "vdu": []}
2204 if scaling_type
== "SCALE_OUT":
2205 # count if max-instance-count is reached
2206 max_instance_count
= scaling_descriptor
.get("max-instance-count", 10)
2207 # self.logger.debug("MAX_INSTANCE_COUNT is {}".format(max_instance_count))
2208 if nb_scale_op
>= max_instance_count
:
2209 raise LcmException("reached the limit of {} (max-instance-count) "
2210 "scaling-out operations for the "
2211 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2214 vdu_scaling_info
["scaling_direction"] = "OUT"
2215 vdu_scaling_info
["vdu-create"] = {}
2216 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2217 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2218 "type": "create", "count": vdu_scale_info
.get("count", 1)})
2219 vdu_scaling_info
["vdu-create"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2221 elif scaling_type
== "SCALE_IN":
2222 # count if min-instance-count is reached
2223 min_instance_count
= 0
2224 if "min-instance-count" in scaling_descriptor
and scaling_descriptor
["min-instance-count"] is not None:
2225 min_instance_count
= int(scaling_descriptor
["min-instance-count"])
2226 if nb_scale_op
<= min_instance_count
:
2227 raise LcmException("reached the limit of {} (min-instance-count) scaling-in operations for the "
2228 "scaling-group-descriptor '{}'".format(nb_scale_op
, scaling_group
))
2230 vdu_scaling_info
["scaling_direction"] = "IN"
2231 vdu_scaling_info
["vdu-delete"] = {}
2232 for vdu_scale_info
in scaling_descriptor
["vdu"]:
2233 RO_scaling_info
.append({"osm_vdu_id": vdu_scale_info
["vdu-id-ref"], "member-vnf-index": vnf_index
,
2234 "type": "delete", "count": vdu_scale_info
.get("count", 1)})
2235 vdu_scaling_info
["vdu-delete"][vdu_scale_info
["vdu-id-ref"]] = vdu_scale_info
.get("count", 1)
2237 # update VDU_SCALING_INFO with the VDUs to delete ip_addresses
2238 vdu_create
= vdu_scaling_info
.get("vdu-create")
2239 vdu_delete
= copy(vdu_scaling_info
.get("vdu-delete"))
2240 if vdu_scaling_info
["scaling_direction"] == "IN":
2241 for vdur
in reversed(db_vnfr
["vdur"]):
2242 if vdu_delete
.get(vdur
["vdu-id-ref"]):
2243 vdu_delete
[vdur
["vdu-id-ref"]] -= 1
2244 vdu_scaling_info
["vdu"].append({
2245 "name": vdur
["name"],
2246 "vdu_id": vdur
["vdu-id-ref"],
2249 for interface
in vdur
["interfaces"]:
2250 vdu_scaling_info
["vdu"][-1]["interface"].append({
2251 "name": interface
["name"],
2252 "ip_address": interface
["ip-address"],
2253 "mac_address": interface
.get("mac-address"),
2255 vdu_delete
= vdu_scaling_info
.pop("vdu-delete")
2258 step
= "Executing pre-scale vnf-config-primitive"
2259 if scaling_descriptor
.get("scaling-config-action"):
2260 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2261 if (scaling_config_action
.get("trigger") == "pre-scale-in" and scaling_type
== "SCALE_IN") \
2262 or (scaling_config_action
.get("trigger") == "pre-scale-out" and scaling_type
== "SCALE_OUT"):
2263 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2264 step
= db_nslcmop_update
["detailed-status"] = \
2265 "executing pre-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2267 # look for primitive
2268 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2269 if config_primitive
["name"] == vnf_config_primitive
:
2273 "Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:scaling-config-action"
2274 "[vnf-config-primitive-name-ref='{}'] does not match any vnf-configuration:config-"
2275 "primitive".format(scaling_group
, config_primitive
))
2277 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2278 if db_vnfr
.get("additionalParamsForVnf"):
2279 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2281 scale_process
= "VCA"
2282 db_nsr_update
["config-status"] = "configuring pre-scaling"
2283 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2285 # Pre-scale reintent check: Check if this sub-operation has been executed before
2286 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2287 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'PRE-SCALE')
2288 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2289 # Skip sub-operation
2290 result
= 'COMPLETED'
2291 result_detail
= 'Done'
2292 self
.logger
.debug(logging_text
+
2293 "vnf_config_primitive={} Skipped sub-operation, result {} {}".format(
2294 vnf_config_primitive
, result
, result_detail
))
2296 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2297 # New sub-operation: Get index of this sub-operation
2298 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2299 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2300 format(vnf_config_primitive
))
2302 # Reintent: Get registered params for this existing sub-operation
2303 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2304 vnf_index
= op
.get('member_vnf_index')
2305 vnf_config_primitive
= op
.get('primitive')
2306 primitive_params
= op
.get('primitive_params')
2307 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2308 format(vnf_config_primitive
))
2309 # Execute the primitive, either with new (first-time) or registered (reintent) args
2310 result
, result_detail
= await self
._ns
_execute
_primitive
(
2311 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2312 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2313 vnf_config_primitive
, result
, result_detail
))
2314 # Update operationState = COMPLETED | FAILED
2315 self
._update
_suboperation
_status
(
2316 db_nslcmop
, op_index
, result
, result_detail
)
2318 if result
== "FAILED":
2319 raise LcmException(result_detail
)
2320 db_nsr_update
["config-status"] = old_config_status
2321 scale_process
= None
2325 # Should this block be skipped if 'RO_nsr_id' == None ?
2326 # if (RO_nsr_id and RO_scaling_info):
2328 scale_process
= "RO"
2329 # Scale RO reintent check: Check if this sub-operation has been executed before
2330 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2331 db_nslcmop
, vnf_index
, None, None, 'SCALE-RO', RO_nsr_id
, RO_scaling_info
)
2332 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2333 # Skip sub-operation
2334 result
= 'COMPLETED'
2335 result_detail
= 'Done'
2336 self
.logger
.debug(logging_text
+ "Skipped sub-operation RO, result {} {}".format(
2337 result
, result_detail
))
2339 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2340 # New sub-operation: Get index of this sub-operation
2341 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2342 self
.logger
.debug(logging_text
+ "New sub-operation RO")
2344 # Reintent: Get registered params for this existing sub-operation
2345 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2346 RO_nsr_id
= op
.get('RO_nsr_id')
2347 RO_scaling_info
= op
.get('RO_scaling_info')
2348 self
.logger
.debug(logging_text
+ "Sub-operation RO reintent".format(
2349 vnf_config_primitive
))
2351 RO_desc
= await self
.RO
.create_action("ns", RO_nsr_id
, {"vdu-scaling": RO_scaling_info
})
2352 db_nsr_update
["_admin.scaling-group.{}.nb-scale-op".format(admin_scale_index
)] = nb_scale_op
2353 db_nsr_update
["_admin.scaling-group.{}.time".format(admin_scale_index
)] = time()
2355 RO_nslcmop_id
= RO_desc
["instance_action_id"]
2356 db_nslcmop_update
["_admin.deploy.RO"] = RO_nslcmop_id
2358 RO_task_done
= False
2359 step
= detailed_status
= "Waiting RO_task_id={} to complete the scale action.".format(RO_nslcmop_id
)
2360 detailed_status_old
= None
2361 self
.logger
.debug(logging_text
+ step
)
2363 deployment_timeout
= 1 * 3600 # One hour
2364 while deployment_timeout
> 0:
2365 if not RO_task_done
:
2366 desc
= await self
.RO
.show("ns", item_id_name
=RO_nsr_id
, extra_item
="action",
2367 extra_item_id
=RO_nslcmop_id
)
2368 ns_status
, ns_status_info
= self
.RO
.check_action_status(desc
)
2369 if ns_status
== "ERROR":
2370 raise ROclient
.ROClientException(ns_status_info
)
2371 elif ns_status
== "BUILD":
2372 detailed_status
= step
+ "; {}".format(ns_status_info
)
2373 elif ns_status
== "ACTIVE":
2375 step
= detailed_status
= "Waiting ns ready at RO. RO_id={}".format(RO_nsr_id
)
2376 self
.logger
.debug(logging_text
+ step
)
2378 assert False, "ROclient.check_action_status returns unknown {}".format(ns_status
)
2381 if ns_status
== "ERROR":
2382 raise ROclient
.ROClientException(ns_status_info
)
2383 elif ns_status
== "BUILD":
2384 detailed_status
= step
+ "; {}".format(ns_status_info
)
2385 elif ns_status
== "ACTIVE":
2386 step
= detailed_status
= \
2387 "Waiting for management IP address reported by the VIM. Updating VNFRs"
2389 self
.scale_vnfr(db_vnfr
, vdu_create
=vdu_create
, vdu_delete
=vdu_delete
)
2392 desc
= await self
.RO
.show("ns", RO_nsr_id
)
2393 # nsr_deployed["nsr_ip"] = RO.get_ns_vnf_info(desc)
2394 self
.ns_update_vnfr({db_vnfr
["member-vnf-index-ref"]: db_vnfr
}, desc
)
2396 except LcmExceptionNoMgmtIP
:
2399 assert False, "ROclient.check_ns_status returns unknown {}".format(ns_status
)
2400 if detailed_status
!= detailed_status_old
:
2401 self
._update
_suboperation
_status
(
2402 db_nslcmop
, op_index
, 'COMPLETED', detailed_status
)
2403 detailed_status_old
= db_nslcmop_update
["detailed-status"] = detailed_status
2404 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2406 await asyncio
.sleep(5, loop
=self
.loop
)
2407 deployment_timeout
-= 5
2408 if deployment_timeout
<= 0:
2409 self
._update
_suboperation
_status
(
2410 db_nslcmop
, nslcmop_id
, op_index
, 'FAILED', "Timeout when waiting for ns to get ready")
2411 raise ROclient
.ROClientException("Timeout waiting ns to be ready")
2413 # update VDU_SCALING_INFO with the obtained ip_addresses
2414 if vdu_scaling_info
["scaling_direction"] == "OUT":
2415 for vdur
in reversed(db_vnfr
["vdur"]):
2416 if vdu_scaling_info
["vdu-create"].get(vdur
["vdu-id-ref"]):
2417 vdu_scaling_info
["vdu-create"][vdur
["vdu-id-ref"]] -= 1
2418 vdu_scaling_info
["vdu"].append({
2419 "name": vdur
["name"],
2420 "vdu_id": vdur
["vdu-id-ref"],
2423 for interface
in vdur
["interfaces"]:
2424 vdu_scaling_info
["vdu"][-1]["interface"].append({
2425 "name": interface
["name"],
2426 "ip_address": interface
["ip-address"],
2427 "mac_address": interface
.get("mac-address"),
2429 del vdu_scaling_info
["vdu-create"]
2431 self
._update
_suboperation
_status
(db_nslcmop
, op_index
, 'COMPLETED', 'Done')
2434 scale_process
= None
2436 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2439 # execute primitive service POST-SCALING
2440 step
= "Executing post-scale vnf-config-primitive"
2441 if scaling_descriptor
.get("scaling-config-action"):
2442 for scaling_config_action
in scaling_descriptor
["scaling-config-action"]:
2443 if (scaling_config_action
.get("trigger") == "post-scale-in" and scaling_type
== "SCALE_IN") \
2444 or (scaling_config_action
.get("trigger") == "post-scale-out" and scaling_type
== "SCALE_OUT"):
2445 vnf_config_primitive
= scaling_config_action
["vnf-config-primitive-name-ref"]
2446 step
= db_nslcmop_update
["detailed-status"] = \
2447 "executing post-scale scaling-config-action '{}'".format(vnf_config_primitive
)
2449 vnfr_params
= {"VDU_SCALE_INFO": vdu_scaling_info
}
2450 if db_vnfr
.get("additionalParamsForVnf"):
2451 vnfr_params
.update(db_vnfr
["additionalParamsForVnf"])
2453 # look for primitive
2454 for config_primitive
in db_vnfd
.get("vnf-configuration", {}).get("config-primitive", ()):
2455 if config_primitive
["name"] == vnf_config_primitive
:
2458 raise LcmException("Invalid vnfd descriptor at scaling-group-descriptor[name='{}']:"
2459 "scaling-config-action[vnf-config-primitive-name-ref='{}'] does not "
2460 "match any vnf-configuration:config-primitive".format(scaling_group
,
2462 scale_process
= "VCA"
2463 db_nsr_update
["config-status"] = "configuring post-scaling"
2464 primitive_params
= self
._map
_primitive
_params
(config_primitive
, {}, vnfr_params
)
2466 # Post-scale reintent check: Check if this sub-operation has been executed before
2467 op_index
= self
._check
_or
_add
_scale
_suboperation
(
2468 db_nslcmop
, nslcmop_id
, vnf_index
, vnf_config_primitive
, primitive_params
, 'POST-SCALE')
2469 if (op_index
== self
.SUBOPERATION_STATUS_SKIP
):
2470 # Skip sub-operation
2471 result
= 'COMPLETED'
2472 result_detail
= 'Done'
2473 self
.logger
.debug(logging_text
+
2474 "vnf_config_primitive={} Skipped sub-operation, result {} {}".
2475 format(vnf_config_primitive
, result
, result_detail
))
2477 if (op_index
== self
.SUBOPERATION_STATUS_NEW
):
2478 # New sub-operation: Get index of this sub-operation
2479 op_index
= len(db_nslcmop
.get('_admin', {}).get('operations')) - 1
2480 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} New sub-operation".
2481 format(vnf_config_primitive
))
2483 # Reintent: Get registered params for this existing sub-operation
2484 op
= db_nslcmop
.get('_admin', {}).get('operations', [])[op_index
]
2485 vnf_index
= op
.get('member_vnf_index')
2486 vnf_config_primitive
= op
.get('primitive')
2487 primitive_params
= op
.get('primitive_params')
2488 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Sub-operation reintent".
2489 format(vnf_config_primitive
))
2490 # Execute the primitive, either with new (first-time) or registered (reintent) args
2491 result
, result_detail
= await self
._ns
_execute
_primitive
(
2492 nsr_deployed
, vnf_index
, None, None, None, vnf_config_primitive
, primitive_params
)
2493 self
.logger
.debug(logging_text
+ "vnf_config_primitive={} Done with result {} {}".format(
2494 vnf_config_primitive
, result
, result_detail
))
2495 # Update operationState = COMPLETED | FAILED
2496 self
._update
_suboperation
_status
(
2497 db_nslcmop
, op_index
, result
, result_detail
)
2499 if result
== "FAILED":
2500 raise LcmException(result_detail
)
2501 db_nsr_update
["config-status"] = old_config_status
2502 scale_process
= None
2505 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "COMPLETED"
2506 db_nslcmop_update
["statusEnteredTime"] = time()
2507 db_nslcmop_update
["detailed-status"] = "done"
2508 db_nsr_update
["detailed-status"] = "" # "scaled {} {}".format(scaling_group, scaling_type)
2509 db_nsr_update
["operational-status"] = "running" if old_operational_status
== "failed" \
2510 else old_operational_status
2511 db_nsr_update
["config-status"] = old_config_status
2513 except (ROclient
.ROClientException
, DbException
, LcmException
) as e
:
2514 self
.logger
.error(logging_text
+ "Exit Exception {}".format(e
))
2516 except asyncio
.CancelledError
:
2517 self
.logger
.error(logging_text
+ "Cancelled Exception while '{}'".format(step
))
2518 exc
= "Operation was cancelled"
2519 except Exception as e
:
2520 exc
= traceback
.format_exc()
2521 self
.logger
.critical(logging_text
+ "Exit Exception {} {}".format(type(e
).__name
__, e
), exc_info
=True)
2525 db_nslcmop_update
["detailed-status"] = "FAILED {}: {}".format(step
, exc
)
2526 db_nslcmop_update
["operationState"] = nslcmop_operation_state
= "FAILED"
2527 db_nslcmop_update
["statusEnteredTime"] = time()
2529 db_nsr_update
["operational-status"] = old_operational_status
2530 db_nsr_update
["config-status"] = old_config_status
2531 db_nsr_update
["detailed-status"] = ""
2532 db_nsr_update
["_admin.nslcmop"] = None
2534 if "VCA" in scale_process
:
2535 db_nsr_update
["config-status"] = "failed"
2536 if "RO" in scale_process
:
2537 db_nsr_update
["operational-status"] = "failed"
2538 db_nsr_update
["detailed-status"] = "FAILED scaling nslcmop={} {}: {}".format(nslcmop_id
, step
,
2541 if db_nslcmop
and db_nslcmop_update
:
2542 self
.update_db_2("nslcmops", nslcmop_id
, db_nslcmop_update
)
2544 db_nsr_update
["_admin.nslcmop"] = None
2545 self
.update_db_2("nsrs", nsr_id
, db_nsr_update
)
2546 except DbException
as e
:
2547 self
.logger
.error(logging_text
+ "Cannot update database: {}".format(e
))
2548 if nslcmop_operation_state
:
2550 await self
.msg
.aiowrite("ns", "scaled", {"nsr_id": nsr_id
, "nslcmop_id": nslcmop_id
,
2551 "operationState": nslcmop_operation_state
},
2554 # await asyncio.sleep(cooldown_time, loop=self.loop)
2555 # await self.msg.aiowrite("ns","scaled-cooldown-time", {"nsr_id": nsr_id, "nslcmop_id": nslcmop_id})
2556 except Exception as e
:
2557 self
.logger
.error(logging_text
+ "kafka_write notification Exception {}".format(e
))
2558 self
.logger
.debug(logging_text
+ "Exit")
2559 self
.lcm_tasks
.remove("ns", nsr_id
, nslcmop_id
, "ns_scale")