1 # -*- coding: utf-8 -*-
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
17 from uuid
import uuid4
18 from http
import HTTPStatus
20 from copy
import copy
, deepcopy
21 from osm_nbi
.validation
import validate_input
, ValidationError
, ns_instantiate
, ns_terminate
, ns_action
, ns_scale
,\
23 from osm_nbi
.base_topic
import BaseTopic
, EngineException
, get_iterable
, deep_get
, increment_ip_mac
24 # from descriptor_topics import DescriptorTopic
25 from yaml
import safe_dump
26 from osm_common
.dbbase
import DbException
27 from osm_common
.msgbase
import MsgException
28 from osm_common
.fsbase
import FsException
29 from re
import match
# For checking that additional parameter names are valid Jinja2 identifiers
31 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
34 class NsrTopic(BaseTopic
):
37 quota_name
= "ns_instances"
38 schema_new
= ns_instantiate
40 def __init__(self
, db
, fs
, msg
, auth
):
41 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
43 def _check_descriptor_dependencies(self
, session
, descriptor
):
45 Check that the dependent descriptors exist on a new descriptor or edition
46 :param session: client session information
47 :param descriptor: descriptor to be inserted or edit
48 :return: None or raises exception
50 if not descriptor
.get("nsdId"):
52 nsd_id
= descriptor
["nsdId"]
53 if not self
.get_item_list(session
, "nsds", {"id": nsd_id
}):
54 raise EngineException("Descriptor error at nsdId='{}' references a non exist nsd".format(nsd_id
),
55 http_code
=HTTPStatus
.CONFLICT
)
58 def format_on_new(content
, project_id
=None, make_public
=False):
59 BaseTopic
.format_on_new(content
, project_id
=project_id
, make_public
=make_public
)
60 content
["_admin"]["nsState"] = "NOT_INSTANTIATED"
63 def check_conflict_on_del(self
, session
, _id
, db_content
):
65 Check that NSR is not instantiated
66 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
67 :param _id: nsr internal id
68 :param db_content: The database content of the nsr
69 :return: None or raises EngineException with the conflict
74 if nsr
["_admin"].get("nsState") == "INSTANTIATED":
75 raise EngineException("nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
76 "Launch 'terminate' operation first; or force deletion".format(_id
),
77 http_code
=HTTPStatus
.CONFLICT
)
79 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
81 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
82 Set usageState of pdu, vnfd, nsd
83 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
84 :param _id: server internal id
85 :param db_content: The database content of the descriptor
86 :param not_send_msg: To not send message (False) or store content (list) instead
87 :return: None if ok or raises EngineException with the problem
89 self
.fs
.file_delete(_id
, ignore_non_exist
=True)
90 self
.db
.del_list("nslcmops", {"nsInstanceId": _id
})
91 self
.db
.del_list("vnfrs", {"nsr-id-ref": _id
})
93 # set all used pdus as free
94 self
.db
.set_list("pdus", {"_admin.usage.nsr_id": _id
},
95 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None})
99 used_nsd_id
= nsr
.get("nsd-id")
101 # check if used by another NSR
102 nsrs_list
= self
.db
.get_one("nsrs", {"nsd-id": used_nsd_id
},
103 fail_on_empty
=False, fail_on_more
=False)
105 self
.db
.set_one("nsds", {"_id": used_nsd_id
}, {"_admin.usageState": "NOT_IN_USE"})
107 # Set VNFD usageState
108 used_vnfd_id_list
= nsr
.get("vnfd-id")
109 if used_vnfd_id_list
:
110 for used_vnfd_id
in used_vnfd_id_list
:
111 # check if used by another NSR
112 nsrs_list
= self
.db
.get_one("nsrs", {"vnfd-id": used_vnfd_id
},
113 fail_on_empty
=False, fail_on_more
=False)
115 self
.db
.set_one("vnfds", {"_id": used_vnfd_id
}, {"_admin.usageState": "NOT_IN_USE"})
117 # delete extra ro_nsrs used for internal RO module
118 self
.db
.del_one("ro_nsrs", q_filter
={"_id": _id
}, fail_on_empty
=False)
121 def _format_ns_request(ns_request
):
122 formated_request
= copy(ns_request
)
123 formated_request
.pop("additionalParamsForNs", None)
124 formated_request
.pop("additionalParamsForVnf", None)
125 return formated_request
128 def _format_additional_params(ns_request
, member_vnf_index
=None, vdu_id
=None, kdu_name
=None, descriptor
=None):
130 Get and format user additional params for NS or VNF
131 :param ns_request: User instantiation additional parameters
132 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
133 :param descriptor: If not None it check that needed parameters of descriptor are supplied
134 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
136 additional_params
= None
138 if not member_vnf_index
:
139 additional_params
= copy(ns_request
.get("additionalParamsForNs"))
140 where_
= "additionalParamsForNs"
141 elif ns_request
.get("additionalParamsForVnf"):
142 where_
= "additionalParamsForVnf[member-vnf-index={}]".format(member_vnf_index
)
143 item
= next((x
for x
in ns_request
["additionalParamsForVnf"] if x
["member-vnf-index"] == member_vnf_index
),
146 if not vdu_id
and not kdu_name
:
148 additional_params
= copy(item
.get("additionalParams")) or {}
149 if vdu_id
and item
.get("additionalParamsForVdu"):
150 item_vdu
= next((x
for x
in item
["additionalParamsForVdu"] if x
["vdu_id"] == vdu_id
), None)
151 other_params
= item_vdu
152 if item_vdu
and item_vdu
.get("additionalParams"):
153 where_
+= ".additionalParamsForVdu[vdu_id={}]".format(vdu_id
)
154 additional_params
= item_vdu
["additionalParams"]
156 additional_params
= {}
157 if item
.get("additionalParamsForKdu"):
158 item_kdu
= next((x
for x
in item
["additionalParamsForKdu"] if x
["kdu_name"] == kdu_name
), None)
159 other_params
= item_kdu
160 if item_kdu
and item_kdu
.get("additionalParams"):
161 where_
+= ".additionalParamsForKdu[kdu_name={}]".format(kdu_name
)
162 additional_params
= item_kdu
["additionalParams"]
164 if additional_params
:
165 for k
, v
in additional_params
.items():
166 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
167 if not kdu_name
and not match('^[a-zA-Z_][a-zA-Z0-9_]*$', k
):
168 raise EngineException("Invalid param name at {}:{}. Must contain only alphanumeric characters "
169 "and underscores, and cannot start with a digit"
171 # END Check that additional parameter names are valid Jinja2 identifiers
172 if not isinstance(k
, str):
173 raise EngineException("Invalid param at {}:{}. Only string keys are allowed".format(where_
, k
))
174 if "." in k
or "$" in k
:
175 raise EngineException("Invalid param at {}:{}. Keys must not contain dots or $".format(where_
, k
))
176 if isinstance(v
, (dict, tuple, list)):
177 additional_params
[k
] = "!!yaml " + safe_dump(v
)
180 # check that enough parameters are supplied for the initial-config-primitive
181 # TODO: check for cloud-init
184 initial_primitives
= None
186 vdud
= next(x
for x
in descriptor
["vdu"] if x
["id"] == vdu_id
)
187 initial_primitives
= deep_get(vdud
, ("vdu-configuration", "initial-config-primitive"))
189 initial_primitives
= deep_get(descriptor
, ("vnf-configuration", "initial-config-primitive"))
191 initial_primitives
= deep_get(descriptor
, ("ns-configuration", "initial-config-primitive"))
193 for initial_primitive
in get_iterable(initial_primitives
):
194 for param
in get_iterable(initial_primitive
.get("parameter")):
195 if param
["value"].startswith("<") and param
["value"].endswith(">"):
196 if param
["value"] in ("<rw_mgmt_ip>", "<VDU_SCALE_INFO>", "<ns_config_info>"):
198 if not additional_params
or param
["value"][1:-1] not in additional_params
:
199 raise EngineException("Parameter '{}' needed for vnfd[id={}]:vnf-configuration:"
200 "initial-config-primitive[name={}] not supplied".
201 format(param
["value"], descriptor
["id"],
202 initial_primitive
["name"]))
204 return additional_params
or None, other_params
or None
206 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
208 Creates a new nsr into database. It also creates needed vnfrs
209 :param rollback: list to append the created items at database in case a rollback must be done
210 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
211 :param indata: params to be used for the nsr
212 :param kwargs: used to override the indata descriptor
213 :param headers: http request headers
214 :return: the _id of nsr descriptor created at database. Or an exception of type
215 EngineException, ValidationError, DbException, FsException, MsgException.
216 Note: Exceptions are not captured on purpose. They should be captured at called
220 step
= "checking quotas"
221 self
.check_quota(session
)
223 step
= "validating input parameters"
224 ns_request
= self
._remove
_envelop
(indata
)
225 # Override descriptor with query string kwargs
226 self
._update
_input
_with
_kwargs
(ns_request
, kwargs
)
227 self
._validate
_input
_new
(ns_request
, session
["force"])
230 step
= "getting nsd id='{}' from database".format(ns_request
.get("nsdId"))
231 _filter
= self
._get
_project
_filter
(session
)
232 _filter
["_id"] = ns_request
["nsdId"]
233 nsd
= self
.db
.get_one("nsds", _filter
)
236 # check NSD is not disabled
237 step
= "checking nsdOperationalState"
238 if nsd
["_admin"]["operationalState"] == "DISABLED":
239 raise EngineException("nsd with id '{}' is DISABLED, and thus cannot be used to create "
240 "a network service".format(ns_request
["nsdId"]), http_code
=HTTPStatus
.CONFLICT
)
242 nsr_id
= str(uuid4())
245 step
= "filling nsr from input data"
246 additional_params
, _
= self
._format
_additional
_params
(ns_request
, descriptor
=nsd
)
248 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
249 ns_k8s_namespace
= session
["project_id"][0] if session
["project_id"] else None
250 if ns_request
and ns_request
.get("k8s-namespace"):
251 ns_k8s_namespace
= ns_request
["k8s-namespace"]
252 if additional_params
and additional_params
.get("k8s-namespace"):
253 ns_k8s_namespace
= additional_params
["k8s-namespace"]
256 "name": ns_request
["nsName"],
257 "name-ref": ns_request
["nsName"],
258 "short-name": ns_request
["nsName"],
259 "admin-status": "ENABLED",
260 "nsState": "NOT_INSTANTIATED",
261 "currentOperation": "IDLE",
262 "currentOperationID": None,
263 "errorDescription": None,
265 "deploymentStatus": None,
266 "configurationStatus": None,
268 "nsd": {k
: v
for k
, v
in nsd
.items() if k
in ("vld", "_id", "id", "constituent-vnfd", "name",
269 "ns-configuration")},
270 "datacenter": ns_request
["vimAccountId"],
271 "resource-orchestrator": "osmopenmano",
272 "description": ns_request
.get("nsDescription", ""),
273 "constituent-vnfr-ref": [],
275 "operational-status": "init", # typedef ns-operational-
276 "config-status": "init", # typedef config-states
277 "detailed-status": "scheduled",
279 "orchestration-progress": {},
280 # {"networks": {"active": 0, "total": 0}, "vms": {"active": 0, "total": 0}},
283 "nsd-name-ref": nsd
["name"],
284 "operational-events": [], # "id", "timestamp", "description", "event",
285 "nsd-ref": nsd
["id"],
286 "nsd-id": nsd
["_id"],
288 "instantiate_params": self
._format
_ns
_request
(ns_request
),
289 "additionalParamsForNs": additional_params
,
290 "ns-instance-config-ref": nsr_id
,
293 # "input-parameter": xpath, value,
294 "ssh-authorized-key": ns_request
.get("ssh_keys"), # TODO remove
295 "vld": nsd
.get("vld") or [],
299 ns_request
["nsr_id"] = nsr_id
300 if ns_request
and ns_request
.get("config-units"):
301 nsr_descriptor
["config-units"] = ns_request
["config-units"]
305 nsr_descriptor
["vld"] = nsd
["vld"]
309 for member_vnf
in nsd
.get("constituent-vnfd", ()):
310 vnfd_id
= member_vnf
["vnfd-id-ref"]
311 step
= "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
312 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
313 if vnfd_id
not in needed_vnfds
:
315 _filter
["id"] = vnfd_id
316 vnfd
= self
.db
.get_one("vnfds", _filter
, fail_on_empty
=True, fail_on_more
=True)
319 needed_vnfds
[vnfd_id
] = vnfd
320 nsr_descriptor
["vnfd-id"].append(vnfd
["_id"])
322 vnfd
= needed_vnfds
[vnfd_id
]
323 step
= "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
324 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
325 vnfr_id
= str(uuid4())
326 additional_params
, vnf_params
= self
._format
_additional
_params
(ns_request
,
327 member_vnf
["member-vnf-index"],
332 "nsr-id-ref": nsr_id
,
333 "member-vnf-index-ref": member_vnf
["member-vnf-index"],
334 "additionalParamsForVnf": additional_params
,
336 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
338 "vnfd-id": vnfd
["_id"], # not at OSM model, but useful
339 "vim-account-id": None,
341 "connection-point": [],
342 "ip-address": None, # mgmt-interface filled by LCM
344 vnf_k8s_namespace
= ns_k8s_namespace
346 if vnf_params
.get("k8s-namespace"):
347 vnf_k8s_namespace
= vnf_params
["k8s-namespace"]
348 if vnf_params
.get("config-units"):
349 vnfr_descriptor
["config-units"] = vnf_params
["config-units"]
352 if vnfd
.get("internal-vld"):
353 vnfr_descriptor
["vld"] = []
354 for vnfd_vld
in vnfd
.get("internal-vld"):
355 vnfr_descriptor
["vld"].append(
356 {key
: vnfd_vld
[key
] for key
in ("id", "vim-network-name", "vim-network-id") if key
in
359 vnfd_mgmt_cp
= vnfd
["mgmt-interface"].get("cp")
360 for cp
in vnfd
.get("connection-point", ()):
363 "connection-point-id": cp
.get("id"),
365 # "ip-address", "mac-address" # filled by LCM
366 # vim-id # TODO it would be nice having a vim port id
368 vnfr_descriptor
["connection-point"].append(vnf_cp
)
370 # Create k8s-cluster information
371 if vnfd
.get("k8s-cluster"):
372 vnfr_descriptor
["k8s-cluster"] = vnfd
["k8s-cluster"]
373 for net
in get_iterable(vnfr_descriptor
["k8s-cluster"].get("nets")):
374 if net
.get("external-connection-point-ref"):
375 for nsd_vld
in get_iterable(nsd
.get("vld")):
376 for nsd_vld_cp
in get_iterable(nsd_vld
.get("vnfd-connection-point-ref")):
377 if nsd_vld_cp
.get("vnfd-connection-point-ref") == \
378 net
["external-connection-point-ref"] and \
379 nsd_vld_cp
.get("member-vnf-index-ref") == member_vnf
["member-vnf-index"]:
380 net
["ns-vld-id"] = nsd_vld
["id"]
385 elif net
.get("internal-connection-point-ref"):
386 for vnfd_ivld
in get_iterable(vnfd
.get("internal-vld")):
387 for vnfd_ivld_icp
in get_iterable(vnfd_ivld
.get("internal-connection-point")):
388 if vnfd_ivld_icp
.get("id-ref") == net
["internal-connection-point-ref"]:
389 net
["vnf-vld-id"] = vnfd_ivld
["id"]
395 for kdu
in get_iterable(vnfd
.get("kdu")):
396 additional_params
, kdu_params
= self
._format
_additional
_params
(ns_request
,
397 member_vnf
["member-vnf-index"],
398 kdu_name
=kdu
["name"],
400 kdu_k8s_namespace
= vnf_k8s_namespace
401 kdu_model
= kdu_params
.get("kdu_model") if kdu_params
else None
402 if kdu_params
and kdu_params
.get("k8s-namespace"):
403 kdu_k8s_namespace
= kdu_params
["k8s-namespace"]
406 "additionalParams": additional_params
,
407 "k8s-namespace": kdu_k8s_namespace
,
408 "kdu-name": kdu
["name"],
409 # TODO "name": "" Name of the VDU in the VIM
410 "ip-address": None, # mgmt-interface filled by LCM
413 if kdu_params
and kdu_params
.get("config-units"):
414 kdur
["config-units"] = kdu_params
["config-units"]
415 if kdu
.get("helm-version"):
416 kdur
["helm-version"] = kdu
["helm-version"]
417 for k8s_type
in ("helm-chart", "juju-bundle"):
418 if kdu
.get(k8s_type
):
419 kdur
[k8s_type
] = kdu_model
or kdu
[k8s_type
]
420 if not vnfr_descriptor
.get("kdur"):
421 vnfr_descriptor
["kdur"] = []
422 vnfr_descriptor
["kdur"].append(kdur
)
424 for vdu
in vnfd
.get("vdu", ()):
425 additional_params
, vdu_params
= self
._format
_additional
_params
(
426 ns_request
, member_vnf
["member-vnf-index"], vdu_id
=vdu
["id"], descriptor
=vnfd
)
428 "vdu-id-ref": vdu
["id"],
429 # TODO "name": "" Name of the VDU in the VIM
430 "ip-address": None, # mgmt-interface filled by LCM
431 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
432 "internal-connection-point": [],
434 "additionalParams": additional_params
,
435 "vdu-name": vdu
["name"],
437 if vdu_params
and vdu_params
.get("config-units"):
438 vdur
["config-units"] = vdu_params
["config-units"]
439 if deep_get(vdu
, ("supplemental-boot-data", "boot-data-drive")):
440 vdur
["boot-data-drive"] = vdu
["supplemental-boot-data"]["boot-data-drive"]
441 if vdu
.get("pdu-type"):
442 vdur
["pdu-type"] = vdu
["pdu-type"]
443 vdur
["name"] = vdu
["pdu-type"]
446 flavor_data
= copy(vdu
.get("vm-flavor", {}))
447 flavor_data
["guest-epa"] = vdu
.get("guest-epa")
448 f
= next((f
for f
in nsr_descriptor
["flavor"] if
449 all(f
.get(k
) == flavor_data
[k
] for k
in flavor_data
)), None)
451 flavor_data
["name"] = vdu
["id"][:56] + "-flv"
452 flavor_data
["id"] = str(len(nsr_descriptor
["flavor"]))
453 nsr_descriptor
["flavor"].append(flavor_data
)
455 vdur
["ns-flavor-id"] = f
["id"]
459 image_data
= {"image": vdu
["image"], "image_checksum": vdu
.get("image_checksum")}
460 img
= next((f
for f
in nsr_descriptor
["image"] if
461 all(f
.get(k
) == image_data
[k
] for k
in image_data
)), None)
463 image_data
["id"] = str(len(nsr_descriptor
["image"]))
464 nsr_descriptor
["image"].append(image_data
)
466 vdur
["ns-image-id"] = img
["id"]
468 # TODO volumes: name, volume-id
469 for icp
in vdu
.get("internal-connection-point", ()):
472 "connection-point-id": icp
["id"],
473 "name": icp
.get("name"),
475 vdur
["internal-connection-point"].append(vdu_icp
)
476 for iface
in vdu
.get("interface", ()):
478 x
: iface
[x
] for x
in ("name", "ip-address", "mac-address", "internal-connection-point-ref",
479 "external-connection-point-ref") if iface
.get(x
) is not None}
480 if iface
.get("ip-address"):
481 vdu_iface
["fixed-ip"] = True
482 if iface
.get("mac-address"):
483 vdu_iface
["fixed-mac"] = True
484 if vnfd_mgmt_cp
and iface
.get("external-connection-point-ref") == vnfd_mgmt_cp
:
485 vdu_iface
["mgmt-vnf"] = True
486 if iface
.get("mgmt-interface"):
487 vdu_iface
["mgmt-interface"] = True # TODO change to mgmt-vdu
488 if iface
.get("virtual-interface"):
489 vdu_iface
.update({x
: iface
["virtual-interface"][x
] for x
in ("type", "vcpi", "bandwidth")
490 if iface
["virtual-interface"].get(x
) is not None})
492 # look for network where this interface is connected
493 if iface
.get("external-connection-point-ref"):
494 for vld_index
, nsd_vld
in enumerate(get_iterable(nsd
.get("vld"))):
495 for nsd_vld_cp
in get_iterable(nsd_vld
.get("vnfd-connection-point-ref")):
496 if nsd_vld_cp
.get("vnfd-connection-point-ref") == \
497 iface
["external-connection-point-ref"] and \
498 nsd_vld_cp
.get("member-vnf-index-ref") == member_vnf
["member-vnf-index"]:
499 vdu_iface
["ns-vld-id"] = nsd_vld
["id"]
500 # if interface is of type PCI, mark connected vld as of type PCI
501 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
502 nsr_descriptor
["vld"][vld_index
]["pci-interfaces"] = True
507 elif iface
.get("internal-connection-point-ref"):
508 for vld_index
, vnfd_ivld
in enumerate(get_iterable(vnfd
.get("internal-vld"))):
509 for vnfd_ivld_icp
in get_iterable(vnfd_ivld
.get("internal-connection-point")):
510 if vnfd_ivld_icp
.get("id-ref") == iface
["internal-connection-point-ref"]:
511 vdu_iface
["vnf-vld-id"] = vnfd_ivld
["id"]
512 if vnfd_ivld_icp
.get("ip-address"):
513 vdu_iface
["ip-address"] = vnfd_ivld_icp
["ip-address"]
514 # if interface is of type PCI, mark connected vld as of type PCI
515 if vdu_iface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
516 vnfr_descriptor
["vld"][vld_index
]["pci-interfaces"] = True
521 if iface
.get("position") is not None:
522 vdur
["interfaces"].insert(iface
["position"], vdu_iface
)
524 vdur
["interfaces"].append(vdu_iface
)
525 count
= vdu
.get("count", 1)
528 count
= int(count
) # TODO remove when descriptor serialized with payngbind
529 for index
in range(0, count
):
531 vdur
= deepcopy(vdur
)
532 for iface
in vdur
["interfaces"]:
533 if iface
.get("ip-address"):
534 iface
["ip-address"] = increment_ip_mac(iface
["ip-address"])
535 if iface
.get("mac-address"):
536 iface
["mac-address"] = increment_ip_mac(iface
["mac-address"])
538 vdur
["_id"] = str(uuid4())
539 vdur
["count-index"] = index
540 vdur
["id"] = "{}-{}".format(vdur
["vdu-id-ref"], index
)
541 vnfr_descriptor
["vdur"].append(vdur
)
543 step
= "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
544 member_vnf
["vnfd-id-ref"], member_vnf
["member-vnf-index"])
547 self
.format_on_new(vnfr_descriptor
, session
["project_id"], make_public
=session
["public"])
548 self
.db
.create("vnfrs", vnfr_descriptor
)
549 rollback
.append({"topic": "vnfrs", "_id": vnfr_id
})
550 nsr_descriptor
["constituent-vnfr-ref"].append(vnfr_id
)
552 step
= "creating nsr at database"
553 self
.format_on_new(nsr_descriptor
, session
["project_id"], make_public
=session
["public"])
554 self
.db
.create("nsrs", nsr_descriptor
)
555 rollback
.append({"topic": "nsrs", "_id": nsr_id
})
557 step
= "creating nsr temporal folder"
558 self
.fs
.mkdir(nsr_id
)
561 except (ValidationError
, EngineException
, DbException
, MsgException
, FsException
) as e
:
562 raise type(e
)("{} while '{}'".format(e
, step
), http_code
=e
.http_code
)
564 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
565 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
568 class VnfrTopic(BaseTopic
):
572 def __init__(self
, db
, fs
, msg
, auth
):
573 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
575 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
576 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
578 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
579 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
581 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
582 # Not used because vnfrs are created and deleted by NsrTopic class directly
583 raise EngineException("Method new called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
586 class NsLcmOpTopic(BaseTopic
):
589 operation_schema
= { # mapping between operation and jsonschema to validate
590 "instantiate": ns_instantiate
,
593 "terminate": ns_terminate
,
596 def __init__(self
, db
, fs
, msg
, auth
):
597 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
599 def _check_ns_operation(self
, session
, nsr
, operation
, indata
):
601 Check that user has enter right parameters for the operation
602 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
603 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
604 :param indata: descriptor with the parameters of the operation
607 vnf_member_index_to_vnfd
= {} # map between vnf_member_index to vnf descriptor.
612 def check_valid_vnf_member_index(member_vnf_index
):
613 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
614 if vnf_member_index_to_vnfd
.get(member_vnf_index
):
615 return vnf_member_index_to_vnfd
[member_vnf_index
]
616 vnfr
= self
.db
.get_one("vnfrs",
617 {"nsr-id-ref": nsr
["_id"], "member-vnf-index-ref": member_vnf_index
},
620 raise EngineException("Invalid parameter member_vnf_index='{}' is not one of the "
621 "nsd:constituent-vnfd".format(member_vnf_index
))
622 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfr
["vnfd-id"]}, fail_on_empty
=False)
624 raise EngineException("vnfd id={} has been deleted!. Operation cannot be performed".
625 format(vnfr
["vnfd-id"]))
626 vnf_member_index_to_vnfd
[member_vnf_index
] = vnfd
# add to cache, avoiding a later look for
629 def check_valid_vdu(vnfd
, vdu_id
):
630 for vdud
in get_iterable(vnfd
.get("vdu")):
631 if vdud
["id"] == vdu_id
:
634 raise EngineException("Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(vdu_id
))
636 def check_valid_kdu(vnfd
, kdu_name
):
637 for kdud
in get_iterable(vnfd
.get("kdu")):
638 if kdud
["name"] == kdu_name
:
641 raise EngineException("Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(kdu_name
))
643 def _check_vnf_instantiation_params(in_vnfd
, vnfd
):
645 for in_vdu
in get_iterable(in_vnfd
.get("vdu")):
646 for vdu
in get_iterable(vnfd
.get("vdu")):
647 if in_vdu
["id"] == vdu
["id"]:
648 for volume
in get_iterable(in_vdu
.get("volume")):
649 for volumed
in get_iterable(vdu
.get("volumes")):
650 if volumed
["name"] == volume
["name"]:
653 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
654 "volume:name='{}' is not present at vnfd:vdu:volumes list".
655 format(in_vnf
["member-vnf-index"], in_vdu
["id"],
657 for in_iface
in get_iterable(in_vdu
["interface"]):
658 for iface
in get_iterable(vdu
.get("interface")):
659 if in_iface
["name"] == iface
["name"]:
662 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
663 "interface[name='{}'] is not present at vnfd:vdu:interface"
664 .format(in_vnf
["member-vnf-index"], in_vdu
["id"],
668 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is is not present "
669 "at vnfd:vdu".format(in_vnf
["member-vnf-index"], in_vdu
["id"]))
671 for in_ivld
in get_iterable(in_vnfd
.get("internal-vld")):
672 for ivld
in get_iterable(vnfd
.get("internal-vld")):
673 if in_ivld
["name"] in (ivld
["id"], ivld
.get("name")):
674 for in_icp
in get_iterable(in_ivld
.get("internal-connection-point")):
675 for icp
in ivld
["internal-connection-point"]:
676 if in_icp
["id-ref"] == icp
["id-ref"]:
679 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
680 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
681 "vnfd:internal-vld:name/id:internal-connection-point"
682 .format(in_vnf
["member-vnf-index"], in_ivld
["name"],
686 raise EngineException("Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
687 " is not present at vnfd '{}'".format(in_vnf
["member-vnf-index"],
688 in_ivld
["name"], vnfd
["id"]))
690 def check_valid_vim_account(vim_account
):
691 if vim_account
in vim_accounts
:
694 db_filter
= self
._get
_project
_filter
(session
)
695 db_filter
["_id"] = vim_account
696 self
.db
.get_one("vim_accounts", db_filter
)
698 raise EngineException("Invalid vimAccountId='{}' not present for the project".format(vim_account
))
699 vim_accounts
.append(vim_account
)
701 def check_valid_wim_account(wim_account
):
702 if not isinstance(wim_account
, str):
704 elif wim_account
in wim_accounts
:
707 db_filter
= self
._get
_project
_filter
(session
, write
=False, show_all
=True)
708 db_filter
["_id"] = wim_account
709 self
.db
.get_one("wim_accounts", db_filter
)
711 raise EngineException("Invalid wimAccountId='{}' not present for the project".format(wim_account
))
712 wim_accounts
.append(wim_account
)
714 if operation
== "action":
715 # check vnf_member_index
716 if indata
.get("vnf_member_index"):
717 indata
["member_vnf_index"] = indata
.pop("vnf_member_index") # for backward compatibility
718 if indata
.get("member_vnf_index"):
719 vnfd
= check_valid_vnf_member_index(indata
["member_vnf_index"])
720 if indata
.get("vdu_id"):
721 vdud
= check_valid_vdu(vnfd
, indata
["vdu_id"])
722 descriptor_configuration
= vdud
.get("vdu-configuration", {}).get("config-primitive")
723 elif indata
.get("kdu_name"):
724 kdud
= check_valid_kdu(vnfd
, indata
["kdu_name"])
725 descriptor_configuration
= kdud
.get("kdu-configuration", {}).get("config-primitive")
727 descriptor_configuration
= vnfd
.get("vnf-configuration", {}).get("config-primitive")
729 descriptor_configuration
= nsd
.get("ns-configuration", {}).get("config-primitive")
731 # For k8s allows default primitives without validating the parameters
732 if indata
.get("kdu_name") and indata
["primitive"] in ("upgrade", "rollback", "status", "inspect", "readme"):
733 # TODO should be checked that rollback only can contains revsision_numbe????
734 if not indata
.get("member_vnf_index"):
735 raise EngineException("Missing action parameter 'member_vnf_index' for default KDU primitive '{}'"
736 .format(indata
["primitive"]))
738 # if not, check primitive
739 for config_primitive
in get_iterable(descriptor_configuration
):
740 if indata
["primitive"] == config_primitive
["name"]:
741 # check needed primitive_params are provided
742 if indata
.get("primitive_params"):
743 in_primitive_params_copy
= copy(indata
["primitive_params"])
745 in_primitive_params_copy
= {}
746 for paramd
in get_iterable(config_primitive
.get("parameter")):
747 if paramd
["name"] in in_primitive_params_copy
:
748 del in_primitive_params_copy
[paramd
["name"]]
749 elif not paramd
.get("default-value"):
750 raise EngineException("Needed parameter {} not provided for primitive '{}'".format(
751 paramd
["name"], indata
["primitive"]))
752 # check no extra primitive params are provided
753 if in_primitive_params_copy
:
754 raise EngineException("parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
755 list(in_primitive_params_copy
.keys()), indata
["primitive"]))
758 raise EngineException("Invalid primitive '{}' is not present at vnfd/nsd".format(indata
["primitive"]))
759 if operation
== "scale":
760 vnfd
= check_valid_vnf_member_index(indata
["scaleVnfData"]["scaleByStepData"]["member-vnf-index"])
761 for scaling_group
in get_iterable(vnfd
.get("scaling-group-descriptor")):
762 if indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"] == scaling_group
["name"]:
765 raise EngineException("Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
766 "present at vnfd:scaling-group-descriptor".format(
767 indata
["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]))
768 if operation
== "instantiate":
770 check_valid_vim_account(indata
["vimAccountId"])
771 check_valid_wim_account(indata
.get("wimAccountId"))
772 for in_vnf
in get_iterable(indata
.get("vnf")):
773 vnfd
= check_valid_vnf_member_index(in_vnf
["member-vnf-index"])
774 _check_vnf_instantiation_params(in_vnf
, vnfd
)
775 if in_vnf
.get("vimAccountId"):
776 check_valid_vim_account(in_vnf
["vimAccountId"])
778 for in_vld
in get_iterable(indata
.get("vld")):
779 check_valid_wim_account(in_vld
.get("wimAccountId"))
780 for vldd
in get_iterable(nsd
.get("vld")):
781 if in_vld
["name"] == vldd
["name"] or in_vld
["name"] == vldd
["id"]:
784 raise EngineException("Invalid parameter vld:name='{}' is not present at nsd:vld".format(
787 def _look_for_pdu(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
789 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
790 (ip_address, ...) information.
791 Modifies PDU _admin.usageState to 'IN_USE'
792 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
793 :param rollback: list with the database modifications to rollback if needed
794 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
795 :param vim_account: vim_account where this vnfr should be deployed
796 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
797 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
798 of the changed vnfr is needed
800 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
801 "vim-network-name": used at VIM
802 "name": interface name
803 "vnf-vld-id": internal VNFD vld where this interface is connected, or
804 "ns-vld-id": NSD vld where this interface is connected.
805 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
808 ifaces_forcing_vim_network
= []
809 for vdur_index
, vdur
in enumerate(get_iterable(vnfr
.get("vdur"))):
810 if not vdur
.get("pdu-type"):
812 pdu_type
= vdur
.get("pdu-type")
813 pdu_filter
= self
._get
_project
_filter
(session
)
814 pdu_filter
["vim_accounts"] = vim_account
815 pdu_filter
["type"] = pdu_type
816 pdu_filter
["_admin.operationalState"] = "ENABLED"
817 pdu_filter
["_admin.usageState"] = "NOT_IN_USE"
818 # TODO feature 1417: "shared": True,
820 available_pdus
= self
.db
.get_list("pdus", pdu_filter
)
821 for pdu
in available_pdus
:
822 # step 1 check if this pdu contains needed interfaces:
823 match_interfaces
= True
824 for vdur_interface
in vdur
["interfaces"]:
825 for pdu_interface
in pdu
["interfaces"]:
826 if pdu_interface
["name"] == vdur_interface
["name"]:
827 # TODO feature 1417: match per mgmt type
829 else: # no interface found for name
830 match_interfaces
= False
835 raise EngineException(
836 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
837 "names".format(pdu_type
, vim_account
, vnfr
["member-vnf-index-ref"], vdur
["vdu-id-ref"]))
841 "_admin.usageState": pdu
["_admin"]["usageState"],
842 "_admin.usage.vnfr_id": None,
843 "_admin.usage.nsr_id": None,
844 "_admin.usage.vdur": None,
846 self
.db
.set_one("pdus", {"_id": pdu
["_id"]},
847 {"_admin.usageState": "IN_USE",
848 "_admin.usage": {"vnfr_id": vnfr
["_id"],
849 "nsr_id": vnfr
["nsr-id-ref"],
850 "vdur": vdur
["vdu-id-ref"]}
852 rollback
.append({"topic": "pdus", "_id": pdu
["_id"], "operation": "set", "content": rollback_pdu
})
854 # step 3. Fill vnfr info by filling vdur
855 vdu_text
= "vdur.{}".format(vdur_index
)
856 vnfr_update_rollback
[vdu_text
+ ".pdu-id"] = None
857 vnfr_update
[vdu_text
+ ".pdu-id"] = pdu
["_id"]
858 for iface_index
, vdur_interface
in enumerate(vdur
["interfaces"]):
859 for pdu_interface
in pdu
["interfaces"]:
860 if pdu_interface
["name"] == vdur_interface
["name"]:
861 iface_text
= vdu_text
+ ".interfaces.{}".format(iface_index
)
862 for k
, v
in pdu_interface
.items():
863 if k
in ("ip-address", "mac-address"): # TODO: switch-xxxxx must be inserted
864 vnfr_update
[iface_text
+ ".{}".format(k
)] = v
865 vnfr_update_rollback
[iface_text
+ ".{}".format(k
)] = vdur_interface
.get(v
)
866 if pdu_interface
.get("ip-address"):
867 if vdur_interface
.get("mgmt-interface") or vdur_interface
.get("mgmt-vnf"):
868 vnfr_update_rollback
[vdu_text
+ ".ip-address"] = vdur
.get("ip-address")
869 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
870 if vdur_interface
.get("mgmt-vnf"):
871 vnfr_update_rollback
["ip-address"] = vnfr
.get("ip-address")
872 vnfr_update
["ip-address"] = pdu_interface
["ip-address"]
873 vnfr_update
[vdu_text
+ ".ip-address"] = pdu_interface
["ip-address"]
874 if pdu_interface
.get("vim-network-name") or pdu_interface
.get("vim-network-id"):
875 ifaces_forcing_vim_network
.append({
876 "name": vdur_interface
.get("vnf-vld-id") or vdur_interface
.get("ns-vld-id"),
877 "vnf-vld-id": vdur_interface
.get("vnf-vld-id"),
878 "ns-vld-id": vdur_interface
.get("ns-vld-id")})
879 if pdu_interface
.get("vim-network-id"):
880 ifaces_forcing_vim_network
[-1]["vim-network-id"] = pdu_interface
["vim-network-id"]
881 if pdu_interface
.get("vim-network-name"):
882 ifaces_forcing_vim_network
[-1]["vim-network-name"] = pdu_interface
["vim-network-name"]
885 return ifaces_forcing_vim_network
887 def _look_for_k8scluster(self
, session
, rollback
, vnfr
, vim_account
, vnfr_update
, vnfr_update_rollback
):
889 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
890 Fills vnfr.kdur with the selected k8scluster
892 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
893 :param rollback: list with the database modifications to rollback if needed
894 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
895 :param vim_account: vim_account where this vnfr should be deployed
896 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
897 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
898 of the changed vnfr is needed
900 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
901 "vim-network-name": used at VIM
902 "name": interface name
903 "vnf-vld-id": internal VNFD vld where this interface is connected, or
904 "ns-vld-id": NSD vld where this interface is connected.
905 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
908 ifaces_forcing_vim_network
= []
909 if not vnfr
.get("kdur"):
910 return ifaces_forcing_vim_network
912 kdu_filter
= self
._get
_project
_filter
(session
)
913 kdu_filter
["vim_account"] = vim_account
914 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
915 available_k8sclusters
= self
.db
.get_list("k8sclusters", kdu_filter
)
917 k8s_requirements
= {} # just for logging
918 for k8scluster
in available_k8sclusters
:
919 if not vnfr
.get("k8s-cluster"):
922 if vnfr
["k8s-cluster"].get("cni"):
923 k8s_requirements
["cni"] = vnfr
["k8s-cluster"]["cni"]
924 if not set(vnfr
["k8s-cluster"]["cni"]).intersection(k8scluster
.get("cni", ())):
926 # restrict by version
927 if vnfr
["k8s-cluster"].get("version"):
928 k8s_requirements
["version"] = vnfr
["k8s-cluster"]["version"]
929 if k8scluster
.get("k8s_version") not in vnfr
["k8s-cluster"]["version"]:
931 # restrict by number of networks
932 if vnfr
["k8s-cluster"].get("nets"):
933 k8s_requirements
["networks"] = len(vnfr
["k8s-cluster"]["nets"])
934 if not k8scluster
.get("nets") or len(k8scluster
["nets"]) < len(vnfr
["k8s-cluster"]["nets"]):
938 raise EngineException("No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}"
939 .format(k8s_requirements
, vim_account
, vnfr
["member-vnf-index-ref"]))
941 for kdur_index
, kdur
in enumerate(get_iterable(vnfr
.get("kdur"))):
942 # step 3. Fill vnfr info by filling kdur
943 kdu_text
= "kdur.{}.".format(kdur_index
)
944 vnfr_update_rollback
[kdu_text
+ "k8s-cluster.id"] = None
945 vnfr_update
[kdu_text
+ "k8s-cluster.id"] = k8scluster
["_id"]
947 # step 4. Check VIM networks that forces the selected k8s_cluster
948 if vnfr
.get("k8s-cluster") and vnfr
["k8s-cluster"].get("nets"):
949 k8scluster_net_list
= list(k8scluster
.get("nets").keys())
950 for net_index
, kdur_net
in enumerate(vnfr
["k8s-cluster"]["nets"]):
951 # get a network from k8s_cluster nets. If name matches use this, if not use other
952 if kdur_net
["id"] in k8scluster_net_list
: # name matches
953 vim_net
= k8scluster
["nets"][kdur_net
["id"]]
954 k8scluster_net_list
.remove(kdur_net
["id"])
956 vim_net
= k8scluster
["nets"][k8scluster_net_list
[0]]
957 k8scluster_net_list
.pop(0)
958 vnfr_update_rollback
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = None
959 vnfr_update
["k8s-cluster.nets.{}.vim_net".format(net_index
)] = vim_net
960 if vim_net
and (kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id")):
961 ifaces_forcing_vim_network
.append({
962 "name": kdur_net
.get("vnf-vld-id") or kdur_net
.get("ns-vld-id"),
963 "vnf-vld-id": kdur_net
.get("vnf-vld-id"),
964 "ns-vld-id": kdur_net
.get("ns-vld-id"),
965 "vim-network-name": vim_net
, # TODO can it be vim-network-id ???
967 # TODO check that this forcing is not incompatible with other forcing
968 return ifaces_forcing_vim_network
970 def _update_vnfrs(self
, session
, rollback
, nsr
, indata
):
973 vnfrs
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
977 vnfr_update_rollback
= {}
978 member_vnf_index
= vnfr
["member-vnf-index-ref"]
979 # update vim-account-id
981 vim_account
= indata
["vimAccountId"]
982 # check instantiate parameters
983 for vnf_inst_params
in get_iterable(indata
.get("vnf")):
984 if vnf_inst_params
["member-vnf-index"] != member_vnf_index
:
986 if vnf_inst_params
.get("vimAccountId"):
987 vim_account
= vnf_inst_params
.get("vimAccountId")
989 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
990 for vdu_inst_param
in get_iterable(vnf_inst_params
.get("vdu")):
991 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
992 if vdu_inst_param
["id"] != vdur
["vdu-id-ref"]:
994 for iface_inst_param
in get_iterable(vdu_inst_param
.get("interface")):
995 iface_index
, _
= next(i
for i
in enumerate(vdur
["interfaces"])
996 if i
[1]["name"] == iface_inst_param
["name"])
997 vnfr_update_text
= "vdur.{}.interfaces.{}".format(vdur_index
, iface_index
)
998 if iface_inst_param
.get("ip-address"):
999 vnfr_update
[vnfr_update_text
+ ".ip-address"] = increment_ip_mac(
1000 iface_inst_param
.get("ip-address"), vdur
.get("count-index", 0))
1001 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1002 if iface_inst_param
.get("mac-address"):
1003 vnfr_update
[vnfr_update_text
+ ".mac-address"] = increment_ip_mac(
1004 iface_inst_param
.get("mac-address"), vdur
.get("count-index", 0))
1005 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1006 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1007 # TODO update vld with the ip-profile
1008 for ivld_inst_param
in get_iterable(vnf_inst_params
.get("internal-vld")):
1009 for icp_inst_param
in get_iterable(ivld_inst_param
.get("internal-connection-point")):
1011 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1012 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1013 if iface
.get("internal-connection-point-ref") == icp_inst_param
["id-ref"]:
1014 vnfr_update_text
= "vdur.{}.interfaces.{}".format(vdur_index
, iface_index
)
1015 if icp_inst_param
.get("ip-address"):
1016 vnfr_update
[vnfr_update_text
+ ".ip-address"] = increment_ip_mac(
1017 icp_inst_param
.get("ip-address"), vdur
.get("count-index", 0))
1018 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1019 if icp_inst_param
.get("mac-address"):
1020 vnfr_update
[vnfr_update_text
+ ".mac-address"] = increment_ip_mac(
1021 icp_inst_param
.get("mac-address"), vdur
.get("count-index", 0))
1022 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1024 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1025 for vld_inst_param
in get_iterable(indata
.get("vld")):
1026 for vnfcp_inst_param
in get_iterable(vld_inst_param
.get("vnfd-connection-point-ref")):
1027 if vnfcp_inst_param
["member-vnf-index-ref"] != member_vnf_index
:
1030 for vdur_index
, vdur
in enumerate(vnfr
["vdur"]):
1031 for iface_index
, iface
in enumerate(vdur
["interfaces"]):
1032 if iface
.get("external-connection-point-ref") == \
1033 vnfcp_inst_param
["vnfd-connection-point-ref"]:
1034 vnfr_update_text
= "vdur.{}.interfaces.{}".format(vdur_index
, iface_index
)
1035 if vnfcp_inst_param
.get("ip-address"):
1036 vnfr_update
[vnfr_update_text
+ ".ip-address"] = increment_ip_mac(
1037 vnfcp_inst_param
.get("ip-address"), vdur
.get("count-index", 0))
1038 vnfr_update
[vnfr_update_text
+ ".fixed-ip"] = True
1039 if vnfcp_inst_param
.get("mac-address"):
1040 vnfr_update
[vnfr_update_text
+ ".mac-address"] = increment_ip_mac(
1041 vnfcp_inst_param
.get("mac-address"), vdur
.get("count-index", 0))
1042 vnfr_update
[vnfr_update_text
+ ".fixed-mac"] = True
1045 vnfr_update
["vim-account-id"] = vim_account
1046 vnfr_update_rollback
["vim-account-id"] = vnfr
.get("vim-account-id")
1049 ifaces_forcing_vim_network
= self
._look
_for
_pdu
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
1050 vnfr_update_rollback
)
1053 ifaces_forcing_vim_network
+= self
._look
_for
_k
8scluster
(session
, rollback
, vnfr
, vim_account
, vnfr_update
,
1054 vnfr_update_rollback
)
1055 # update database vnfr
1056 self
.db
.set_one("vnfrs", {"_id": vnfr
["_id"]}, vnfr_update
)
1057 rollback
.append({"topic": "vnfrs", "_id": vnfr
["_id"], "operation": "set", "content": vnfr_update_rollback
})
1059 # Update indada in case pdu forces to use a concrete vim-network-name
1060 # TODO check if user has already insert a vim-network-name and raises an error
1061 if not ifaces_forcing_vim_network
:
1063 for iface_info
in ifaces_forcing_vim_network
:
1064 if iface_info
.get("ns-vld-id"):
1065 if "vld" not in indata
:
1067 indata
["vld"].append({key
: iface_info
[key
] for key
in
1068 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)})
1070 elif iface_info
.get("vnf-vld-id"):
1071 if "vnf" not in indata
:
1073 indata
["vnf"].append({
1074 "member-vnf-index": member_vnf_index
,
1075 "internal-vld": [{key
: iface_info
[key
] for key
in
1076 ("name", "vim-network-name", "vim-network-id") if iface_info
.get(key
)}]
1080 def _create_nslcmop(nsr_id
, operation
, params
):
1082 Creates a ns-lcm-opp content to be stored at database.
1083 :param nsr_id: internal id of the instance
1084 :param operation: instantiate, terminate, scale, action, ...
1085 :param params: user parameters for the operation
1086 :return: dictionary following SOL005 format
1093 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1094 "queuePosition": None,
1096 "errorMessage": None,
1097 "detailedStatus": None,
1098 "statusEnteredTime": now
,
1099 "nsInstanceId": nsr_id
,
1100 "lcmOperationType": operation
,
1102 "isAutomaticInvocation": False,
1103 "operationParams": params
,
1104 "isCancelPending": False,
1106 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id
,
1107 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id
,
1112 def _get_enabled_vims(self
, session
):
1114 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1115 :param session: current session with user information
1117 db_filter
= self
._get
_project
_filter
(session
)
1118 db_filter
["_admin.operationalState"] = "ENABLED"
1119 vims
= self
.db
.get_list("vim_accounts", db_filter
)
1122 vimAccounts
.append(vim
['_id'])
1125 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None, slice_object
=False):
1127 Performs a new operation over a ns
1128 :param rollback: list to append created items at database in case a rollback must to be done
1129 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1130 :param indata: descriptor with the parameters of the operation. It must contains among others
1131 nsInstanceId: _id of the nsr to perform the operation
1132 operation: it can be: instantiate, terminate, action, TODO: update, heal
1133 :param kwargs: used to override the indata descriptor
1134 :param headers: http request headers
1135 :return: id of the nslcmops
1137 def check_if_nsr_is_not_slice_member(session
, nsr_id
):
1139 db_filter
= self
._get
_project
_filter
(session
)
1140 db_filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1141 nsis
= self
.db
.get_one("nsis", db_filter
, fail_on_empty
=False, fail_on_more
=False)
1143 raise EngineException("The NS instance {} cannot be terminated because is used by the slice {}".format(
1144 nsr_id
, nsis
["_id"]), http_code
=HTTPStatus
.CONFLICT
)
1147 # Override descriptor with query string kwargs
1148 self
._update
_input
_with
_kwargs
(indata
, kwargs
, yaml_format
=True)
1149 operation
= indata
["lcmOperationType"]
1150 nsInstanceId
= indata
["nsInstanceId"]
1152 validate_input(indata
, self
.operation_schema
[operation
])
1153 # get ns from nsr_id
1154 _filter
= BaseTopic
._get
_project
_filter
(session
)
1155 _filter
["_id"] = nsInstanceId
1156 nsr
= self
.db
.get_one("nsrs", _filter
)
1159 if operation
== "terminate" and slice_object
is False:
1160 check_if_nsr_is_not_slice_member(session
, nsr
["_id"])
1161 if not nsr
["_admin"].get("nsState") or nsr
["_admin"]["nsState"] == "NOT_INSTANTIATED":
1162 if operation
== "terminate" and indata
.get("autoremove"):
1163 # NSR must be deleted
1164 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1165 if operation
!= "instantiate":
1166 raise EngineException("ns_instance '{}' cannot be '{}' because it is not instantiated".format(
1167 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1169 if operation
== "instantiate" and not session
["force"]:
1170 raise EngineException("ns_instance '{}' cannot be '{}' because it is already instantiated".format(
1171 nsInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1172 self
._check
_ns
_operation
(session
, nsr
, operation
, indata
)
1174 if operation
== "instantiate":
1175 self
._update
_vnfrs
(session
, rollback
, nsr
, indata
)
1177 nslcmop_desc
= self
._create
_nslcmop
(nsInstanceId
, operation
, indata
)
1178 _id
= nslcmop_desc
["_id"]
1179 self
.format_on_new(nslcmop_desc
, session
["project_id"], make_public
=session
["public"])
1180 if indata
.get("placement-engine"):
1181 # Save valid vim accounts in lcm operation descriptor
1182 nslcmop_desc
['operationParams']['validVimAccounts'] = self
._get
_enabled
_vims
(session
)
1183 self
.db
.create("nslcmops", nslcmop_desc
)
1184 rollback
.append({"topic": "nslcmops", "_id": _id
})
1185 if not slice_object
:
1186 self
.msg
.write("ns", operation
, nslcmop_desc
)
1188 except ValidationError
as e
: # TODO remove try Except, it is captured at nbi.py
1189 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1190 # except DbException as e:
1191 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
1193 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1194 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1196 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1197 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1200 class NsiTopic(BaseTopic
):
1203 quota_name
= "slice_instances"
1205 def __init__(self
, db
, fs
, msg
, auth
):
1206 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1207 self
.nsrTopic
= NsrTopic(db
, fs
, msg
, auth
)
1210 def _format_ns_request(ns_request
):
1211 formated_request
= copy(ns_request
)
1212 # TODO: Add request params
1213 return formated_request
1216 def _format_addional_params(slice_request
):
1218 Get and format user additional params for NS or VNF
1219 :param slice_request: User instantiation additional parameters
1220 :return: a formatted copy of additional params or None if not supplied
1222 additional_params
= copy(slice_request
.get("additionalParamsForNsi"))
1223 if additional_params
:
1224 for k
, v
in additional_params
.items():
1225 if not isinstance(k
, str):
1226 raise EngineException("Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".
1228 if "." in k
or "$" in k
:
1229 raise EngineException("Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".
1231 if isinstance(v
, (dict, tuple, list)):
1232 additional_params
[k
] = "!!yaml " + safe_dump(v
)
1233 return additional_params
1235 def _check_descriptor_dependencies(self
, session
, descriptor
):
1237 Check that the dependent descriptors exist on a new descriptor or edition
1238 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1239 :param descriptor: descriptor to be inserted or edit
1240 :return: None or raises exception
1242 if not descriptor
.get("nst-ref"):
1244 nstd_id
= descriptor
["nst-ref"]
1245 if not self
.get_item_list(session
, "nsts", {"id": nstd_id
}):
1246 raise EngineException("Descriptor error at nst-ref='{}' references a non exist nstd".format(nstd_id
),
1247 http_code
=HTTPStatus
.CONFLICT
)
1249 def check_conflict_on_del(self
, session
, _id
, db_content
):
1251 Check that NSI is not instantiated
1252 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1253 :param _id: nsi internal id
1254 :param db_content: The database content of the _id
1255 :return: None or raises EngineException with the conflict
1257 if session
["force"]:
1260 if nsi
["_admin"].get("nsiState") == "INSTANTIATED":
1261 raise EngineException("nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
1262 "Launch 'terminate' operation first; or force deletion".format(_id
),
1263 http_code
=HTTPStatus
.CONFLICT
)
1265 def delete_extra(self
, session
, _id
, db_content
, not_send_msg
=None):
1267 Deletes associated nsilcmops from database. Deletes associated filesystem.
1268 Set usageState of nst
1269 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1270 :param _id: server internal id
1271 :param db_content: The database content of the descriptor
1272 :param not_send_msg: To not send message (False) or store content (list) instead
1273 :return: None if ok or raises EngineException with the problem
1276 # Deleting the nsrs belonging to nsir
1278 for nsrs_detailed_item
in nsir
["_admin"]["nsrs-detailed-list"]:
1279 nsr_id
= nsrs_detailed_item
["nsrId"]
1280 if nsrs_detailed_item
.get("shared"):
1281 _filter
= {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1282 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id
,
1283 "_id.ne": nsir
["_id"]}
1284 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1285 if nsi
: # last one using nsr
1288 self
.nsrTopic
.delete(session
, nsr_id
, dry_run
=False, not_send_msg
=not_send_msg
)
1289 except (DbException
, EngineException
) as e
:
1290 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1295 # delete related nsilcmops database entries
1296 self
.db
.del_list("nsilcmops", {"netsliceInstanceId": _id
})
1298 # Check and set used NST usage state
1299 nsir_admin
= nsir
.get("_admin")
1300 if nsir_admin
and nsir_admin
.get("nst-id"):
1301 # check if used by another NSI
1302 nsis_list
= self
.db
.get_one("nsis", {"nst-id": nsir_admin
["nst-id"]},
1303 fail_on_empty
=False, fail_on_more
=False)
1305 self
.db
.set_one("nsts", {"_id": nsir_admin
["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1307 # def delete(self, session, _id, dry_run=False):
1309 # Delete item by its internal _id
1310 # :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1311 # :param _id: server internal id
1312 # :param dry_run: make checking but do not delete
1313 # :return: dictionary with deleted item _id. It raises EngineException on error: not found, conflict, ...
1315 # # TODO add admin to filter, validate rights
1316 # BaseTopic.delete(self, session, _id, dry_run=True)
1320 # # Deleting the nsrs belonging to nsir
1321 # nsir = self.db.get_one("nsis", {"_id": _id})
1322 # for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
1323 # nsr_id = nsrs_detailed_item["nsrId"]
1324 # if nsrs_detailed_item.get("shared"):
1325 # _filter = {"_admin.nsrs-detailed-list.ANYINDEX.shared": True,
1326 # "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
1327 # "_id.ne": nsir["_id"]}
1328 # nsi = self.db.get_one("nsis", _filter, fail_on_empty=False, fail_on_more=False)
1329 # if nsi: # last one using nsr
1332 # self.nsrTopic.delete(session, nsr_id, dry_run=False)
1333 # except (DbException, EngineException) as e:
1334 # if e.http_code == HTTPStatus.NOT_FOUND:
1338 # # deletes NetSlice instance object
1339 # v = self.db.del_one("nsis", {"_id": _id})
1341 # # makes a temporal list of nsilcmops objects related to the _id given and deletes them from db
1342 # _filter = {"netsliceInstanceId": _id}
1343 # self.db.del_list("nsilcmops", _filter)
1345 # # Search if nst is being used by other nsi
1346 # nsir_admin = nsir.get("_admin")
1348 # if nsir_admin.get("nst-id"):
1349 # nsis_list = self.db.get_one("nsis", {"nst-id": nsir_admin["nst-id"]},
1350 # fail_on_empty=False, fail_on_more=False)
1352 # self.db.set_one("nsts", {"_id": nsir_admin["nst-id"]}, {"_admin.usageState": "NOT_IN_USE"})
1355 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1357 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
1358 :param rollback: list to append the created items at database in case a rollback must be done
1359 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1360 :param indata: params to be used for the nsir
1361 :param kwargs: used to override the indata descriptor
1362 :param headers: http request headers
1363 :return: the _id of nsi descriptor created at database
1367 step
= "checking quotas"
1368 self
.check_quota(session
)
1371 slice_request
= self
._remove
_envelop
(indata
)
1372 # Override descriptor with query string kwargs
1373 self
._update
_input
_with
_kwargs
(slice_request
, kwargs
)
1374 self
._validate
_input
_new
(slice_request
, session
["force"])
1377 step
= "getting nstd id='{}' from database".format(slice_request
.get("nstId"))
1378 _filter
= self
._get
_project
_filter
(session
)
1379 _filter
["_id"] = slice_request
["nstId"]
1380 nstd
= self
.db
.get_one("nsts", _filter
)
1381 # check NST is not disabled
1382 step
= "checking NST operationalState"
1383 if nstd
["_admin"]["operationalState"] == "DISABLED":
1384 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
1385 "instance".format(slice_request
["nstId"]), http_code
=HTTPStatus
.CONFLICT
)
1388 # check NSD is not disabled
1389 step
= "checking operationalState"
1390 if nstd
["_admin"]["operationalState"] == "DISABLED":
1391 raise EngineException("nst with id '{}' is DISABLED, and thus cannot be used to create "
1392 "a network slice".format(slice_request
["nstId"]), http_code
=HTTPStatus
.CONFLICT
)
1394 nstd
.pop("_admin", None)
1395 nstd_id
= nstd
.pop("_id", None)
1396 nsi_id
= str(uuid4())
1397 step
= "filling nsi_descriptor with input data"
1402 "name": slice_request
["nsiName"],
1403 "description": slice_request
.get("nsiDescription", ""),
1404 "datacenter": slice_request
["vimAccountId"],
1405 "nst-ref": nstd
["id"],
1406 "instantiation_parameters": slice_request
,
1407 "network-slice-template": nstd
,
1411 "additionalParamsForNsi": self
._format
_addional
_params
(slice_request
)
1414 step
= "creating nsi at database"
1415 self
.format_on_new(nsi_descriptor
, session
["project_id"], make_public
=session
["public"])
1416 nsi_descriptor
["_admin"]["nsiState"] = "NOT_INSTANTIATED"
1417 nsi_descriptor
["_admin"]["netslice-subnet"] = None
1418 nsi_descriptor
["_admin"]["deployed"] = {}
1419 nsi_descriptor
["_admin"]["deployed"]["RO"] = []
1420 nsi_descriptor
["_admin"]["nst-id"] = nstd_id
1422 # Creating netslice-vld for the RO.
1423 step
= "creating netslice-vld at database"
1425 # Building the vlds list to be deployed
1426 # From netslice descriptors, creating the initial list
1429 for netslice_vlds
in get_iterable(nstd
.get("netslice-vld")):
1430 # Getting template Instantiation parameters from NST
1431 nsi_vld
= deepcopy(netslice_vlds
)
1432 nsi_vld
["shared-nsrs-list"] = []
1433 nsi_vld
["vimAccountId"] = slice_request
["vimAccountId"]
1434 nsi_vlds
.append(nsi_vld
)
1436 nsi_descriptor
["_admin"]["netslice-vld"] = nsi_vlds
1437 # Creating netslice-subnet_record.
1441 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
1442 for member_ns
in nstd
["netslice-subnet"]:
1443 nsd_id
= member_ns
["nsd-ref"]
1444 step
= "getting nstd id='{}' constituent-nsd='{}' from database".format(
1445 member_ns
["nsd-ref"], member_ns
["id"])
1446 if nsd_id
not in needed_nsds
:
1448 _filter
["id"] = nsd_id
1449 nsd
= self
.db
.get_one("nsds", _filter
, fail_on_empty
=True, fail_on_more
=True)
1452 needed_nsds
[nsd_id
] = nsd
1454 nsd
= needed_nsds
[nsd_id
]
1455 member_ns
["_id"] = needed_nsds
[nsd_id
].get("_id")
1456 services
.append(member_ns
)
1458 step
= "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
1459 member_ns
["nsd-ref"], member_ns
["id"])
1461 # creates Network Services records (NSRs)
1462 step
= "creating nsrs at database using NsrTopic.new()"
1463 ns_params
= slice_request
.get("netslice-subnet")
1465 nsi_netslice_subnet
= []
1466 for service
in services
:
1467 # Check if the netslice-subnet is shared and if it is share if the nss exists
1470 # Is the nss shared and instantiated?
1471 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1472 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service
["nsd-ref"]
1473 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service
["id"]
1474 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1475 if nsi
and service
.get("is-shared-nss"):
1476 nsrs_detailed_list
= nsi
["_admin"]["nsrs-detailed-list"]
1477 for nsrs_detailed_item
in nsrs_detailed_list
:
1478 if nsrs_detailed_item
["nsd-id"] == service
["nsd-ref"]:
1479 if nsrs_detailed_item
["nss-id"] == service
["id"]:
1480 _id_nsr
= nsrs_detailed_item
["nsrId"]
1482 for netslice_subnet
in nsi
["_admin"]["netslice-subnet"]:
1483 if netslice_subnet
["nss-id"] == service
["id"]:
1484 indata_ns
= netslice_subnet
1488 if service
.get("instantiation-parameters"):
1489 indata_ns
= deepcopy(service
["instantiation-parameters"])
1490 # del service["instantiation-parameters"]
1492 indata_ns
["nsdId"] = service
["_id"]
1493 indata_ns
["nsName"] = slice_request
.get("nsiName") + "." + service
["id"]
1494 indata_ns
["vimAccountId"] = slice_request
.get("vimAccountId")
1495 indata_ns
["nsDescription"] = service
["description"]
1496 if slice_request
.get("ssh_keys"):
1497 indata_ns
["ssh_keys"] = slice_request
.get("ssh_keys")
1500 for ns_param
in ns_params
:
1501 if ns_param
.get("id") == service
["id"]:
1502 copy_ns_param
= deepcopy(ns_param
)
1503 del copy_ns_param
["id"]
1504 indata_ns
.update(copy_ns_param
)
1507 # Creates Nsr objects
1508 _id_nsr
, _
= self
.nsrTopic
.new(rollback
, session
, indata_ns
, kwargs
, headers
)
1509 nsrs_item
= {"nsrId": _id_nsr
, "shared": service
.get("is-shared-nss"), "nsd-id": service
["nsd-ref"],
1510 "nss-id": service
["id"], "nslcmop_instantiate": None}
1511 indata_ns
["nss-id"] = service
["id"]
1512 nsrs_list
.append(nsrs_item
)
1513 nsi_netslice_subnet
.append(indata_ns
)
1514 nsr_ref
= {"nsr-ref": _id_nsr
}
1515 nsi_descriptor
["nsr-ref-list"].append(nsr_ref
)
1517 # Adding the nsrs list to the nsi
1518 nsi_descriptor
["_admin"]["nsrs-detailed-list"] = nsrs_list
1519 nsi_descriptor
["_admin"]["netslice-subnet"] = nsi_netslice_subnet
1520 self
.db
.set_one("nsts", {"_id": slice_request
["nstId"]}, {"_admin.usageState": "IN_USE"})
1522 # Creating the entry in the database
1523 self
.db
.create("nsis", nsi_descriptor
)
1524 rollback
.append({"topic": "nsis", "_id": nsi_id
})
1526 except Exception as e
: # TODO remove try Except, it is captured at nbi.py
1527 self
.logger
.exception("Exception {} at NsiTopic.new()".format(e
), exc_info
=True)
1528 raise EngineException("Error {}: {}".format(step
, e
))
1529 except ValidationError
as e
:
1530 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1532 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1533 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1536 class NsiLcmOpTopic(BaseTopic
):
1539 operation_schema
= { # mapping between operation and jsonschema to validate
1540 "instantiate": nsi_instantiate
,
1544 def __init__(self
, db
, fs
, msg
, auth
):
1545 BaseTopic
.__init
__(self
, db
, fs
, msg
, auth
)
1546 self
.nsi_NsLcmOpTopic
= NsLcmOpTopic(self
.db
, self
.fs
, self
.msg
, self
.auth
)
1548 def _check_nsi_operation(self
, session
, nsir
, operation
, indata
):
1550 Check that user has enter right parameters for the operation
1551 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1552 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1553 :param indata: descriptor with the parameters of the operation
1557 nstd
= nsir
["network-slice-template"]
1559 def check_valid_netslice_subnet_id(nstId
):
1560 # TODO change to vnfR (??)
1561 for netslice_subnet
in nstd
["netslice-subnet"]:
1562 if nstId
== netslice_subnet
["id"]:
1563 nsd_id
= netslice_subnet
["nsd-ref"]
1564 if nsd_id
not in nsds
:
1565 _filter
= self
._get
_project
_filter
(session
)
1566 _filter
["id"] = nsd_id
1567 nsds
[nsd_id
] = self
.db
.get_one("nsds", _filter
)
1570 raise EngineException("Invalid parameter nstId='{}' is not one of the "
1571 "nst:netslice-subnet".format(nstId
))
1572 if operation
== "instantiate":
1573 # check the existance of netslice-subnet items
1574 for in_nst
in get_iterable(indata
.get("netslice-subnet")):
1575 check_valid_netslice_subnet_id(in_nst
["id"])
1577 def _create_nsilcmop(self
, session
, netsliceInstanceId
, operation
, params
):
1583 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1584 "statusEnteredTime": now
,
1585 "netsliceInstanceId": netsliceInstanceId
,
1586 "lcmOperationType": operation
,
1588 "isAutomaticInvocation": False,
1589 "operationParams": params
,
1590 "isCancelPending": False,
1592 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id
,
1593 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/" + netsliceInstanceId
,
1598 def add_shared_nsr_2vld(self
, nsir
, nsr_item
):
1599 for nst_sb_item
in nsir
["network-slice-template"].get("netslice-subnet"):
1600 if nst_sb_item
.get("is-shared-nss"):
1601 for admin_subnet_item
in nsir
["_admin"].get("netslice-subnet"):
1602 if admin_subnet_item
["nss-id"] == nst_sb_item
["id"]:
1603 for admin_vld_item
in nsir
["_admin"].get("netslice-vld"):
1604 for admin_vld_nss_cp_ref_item
in admin_vld_item
["nss-connection-point-ref"]:
1605 if admin_subnet_item
["nss-id"] == admin_vld_nss_cp_ref_item
["nss-ref"]:
1606 if not nsr_item
["nsrId"] in admin_vld_item
["shared-nsrs-list"]:
1607 admin_vld_item
["shared-nsrs-list"].append(nsr_item
["nsrId"])
1609 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
1610 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, {"_admin.netslice-vld": nsir
["_admin"].get("netslice-vld")})
1612 def new(self
, rollback
, session
, indata
=None, kwargs
=None, headers
=None):
1614 Performs a new operation over a ns
1615 :param rollback: list to append created items at database in case a rollback must to be done
1616 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1617 :param indata: descriptor with the parameters of the operation. It must contains among others
1618 netsliceInstanceId: _id of the nsir to perform the operation
1619 operation: it can be: instantiate, terminate, action, TODO: update, heal
1620 :param kwargs: used to override the indata descriptor
1621 :param headers: http request headers
1622 :return: id of the nslcmops
1625 # Override descriptor with query string kwargs
1626 self
._update
_input
_with
_kwargs
(indata
, kwargs
)
1627 operation
= indata
["lcmOperationType"]
1628 netsliceInstanceId
= indata
["netsliceInstanceId"]
1629 validate_input(indata
, self
.operation_schema
[operation
])
1631 # get nsi from netsliceInstanceId
1632 _filter
= self
._get
_project
_filter
(session
)
1633 _filter
["_id"] = netsliceInstanceId
1634 nsir
= self
.db
.get_one("nsis", _filter
)
1635 logging_prefix
= "nsi={} {} ".format(netsliceInstanceId
, operation
)
1639 if not nsir
["_admin"].get("nsiState") or nsir
["_admin"]["nsiState"] == "NOT_INSTANTIATED":
1640 if operation
== "terminate" and indata
.get("autoremove"):
1641 # NSIR must be deleted
1642 return None, None # a none in this case is used to indicate not instantiated. It can be removed
1643 if operation
!= "instantiate":
1644 raise EngineException("netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
1645 netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1647 if operation
== "instantiate" and not session
["force"]:
1648 raise EngineException("netslice_instance '{}' cannot be '{}' because it is already instantiated".
1649 format(netsliceInstanceId
, operation
), HTTPStatus
.CONFLICT
)
1651 # Creating all the NS_operation (nslcmop)
1652 # Get service list from db
1653 nsrs_list
= nsir
["_admin"]["nsrs-detailed-list"]
1655 # nslcmops_item = None
1656 for index
, nsr_item
in enumerate(nsrs_list
):
1657 nsr_id
= nsr_item
["nsrId"]
1658 if nsr_item
.get("shared"):
1659 _filter
["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
1660 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
1661 _filter
["_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"] = None
1662 _filter
["_id.ne"] = netsliceInstanceId
1663 nsi
= self
.db
.get_one("nsis", _filter
, fail_on_empty
=False, fail_on_more
=False)
1664 if operation
== "terminate":
1665 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): None}
1666 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1667 if nsi
: # other nsi is using this nsr and it needs this nsr instantiated
1668 continue # do not create nsilcmop
1670 # looks the first nsi fulfilling the conditions but not being the current NSIR
1672 nsi_nsr_item
= next(n
for n
in nsi
["_admin"]["nsrs-detailed-list"] if
1673 n
["nsrId"] == nsr_id
and n
["shared"] and
1674 n
["nslcmop_instantiate"])
1675 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1676 nslcmops
.append(nsi_nsr_item
["nslcmop_instantiate"])
1677 _update
= {"_admin.nsrs-detailed-list.{}".format(index
): nsi_nsr_item
}
1678 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1679 # continue to not create nslcmop since nsrs is shared and nsrs was created
1682 self
.add_shared_nsr_2vld(nsir
, nsr_item
)
1687 "lcmOperationType": operation
,
1688 "nsInstanceId": nsr_id
,
1689 # Including netslice_id in the ns instantiate Operation
1690 "netsliceInstanceId": netsliceInstanceId
,
1692 if operation
== "instantiate":
1693 service
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1694 indata_ns
.update(service
["instantiate_params"])
1696 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
1697 # message via kafka bus
1698 nslcmop
, _
= self
.nsi_NsLcmOpTopic
.new(rollback
, session
, indata_ns
, None, headers
,
1700 nslcmops
.append(nslcmop
)
1701 if operation
== "instantiate":
1702 _update
= {"_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(index
): nslcmop
}
1703 self
.db
.set_one("nsis", {"_id": nsir
["_id"]}, _update
)
1704 except (DbException
, EngineException
) as e
:
1705 if e
.http_code
== HTTPStatus
.NOT_FOUND
:
1706 self
.logger
.info(logging_prefix
+ "skipping NS={} because not found".format(nsr_id
))
1712 indata
["nslcmops_ids"] = nslcmops
1713 self
._check
_nsi
_operation
(session
, nsir
, operation
, indata
)
1715 nsilcmop_desc
= self
._create
_nsilcmop
(session
, netsliceInstanceId
, operation
, indata
)
1716 self
.format_on_new(nsilcmop_desc
, session
["project_id"], make_public
=session
["public"])
1717 _id
= self
.db
.create("nsilcmops", nsilcmop_desc
)
1718 rollback
.append({"topic": "nsilcmops", "_id": _id
})
1719 self
.msg
.write("nsi", operation
, nsilcmop_desc
)
1721 except ValidationError
as e
:
1722 raise EngineException(e
, HTTPStatus
.UNPROCESSABLE_ENTITY
)
1724 def delete(self
, session
, _id
, dry_run
=False, not_send_msg
=None):
1725 raise EngineException("Method delete called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)
1727 def edit(self
, session
, _id
, indata
=None, kwargs
=None, content
=None):
1728 raise EngineException("Method edit called directly", HTTPStatus
.INTERNAL_SERVER_ERROR
)