7bfff0b3e65c569ebf2ebedbb473d2dee6991dea
[osm/NBI.git] / osm_nbi / instance_topics.py
1 # -*- coding: utf-8 -*-
2
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
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
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
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 # import logging
17 import json
18 from uuid import uuid4
19 from http import HTTPStatus
20 from time import time
21 from copy import copy, deepcopy
22 from osm_nbi.validation import (
23 validate_input,
24 ValidationError,
25 ns_instantiate,
26 ns_terminate,
27 ns_action,
28 ns_scale,
29 ns_update,
30 nsi_instantiate,
31 ns_migrate,
32 )
33 from osm_nbi.base_topic import (
34 BaseTopic,
35 EngineException,
36 get_iterable,
37 deep_get,
38 increment_ip_mac,
39 )
40 from yaml import safe_dump
41 from osm_common.dbbase import DbException
42 from osm_common.msgbase import MsgException
43 from osm_common.fsbase import FsException
44 from osm_nbi import utils
45 from re import (
46 match,
47 ) # For checking that additional parameter names are valid Jinja2 identifiers
48
49 __author__ = "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
50
51
52 class NsrTopic(BaseTopic):
53 topic = "nsrs"
54 topic_msg = "ns"
55 quota_name = "ns_instances"
56 schema_new = ns_instantiate
57
58 def __init__(self, db, fs, msg, auth):
59 BaseTopic.__init__(self, db, fs, msg, auth)
60
61 def _check_descriptor_dependencies(self, session, descriptor):
62 """
63 Check that the dependent descriptors exist on a new descriptor or edition
64 :param session: client session information
65 :param descriptor: descriptor to be inserted or edit
66 :return: None or raises exception
67 """
68 if not descriptor.get("nsdId"):
69 return
70 nsd_id = descriptor["nsdId"]
71 if not self.get_item_list(session, "nsds", {"id": nsd_id}):
72 raise EngineException(
73 "Descriptor error at nsdId='{}' references a non exist nsd".format(
74 nsd_id
75 ),
76 http_code=HTTPStatus.CONFLICT,
77 )
78
79 @staticmethod
80 def format_on_new(content, project_id=None, make_public=False):
81 BaseTopic.format_on_new(content, project_id=project_id, make_public=make_public)
82 content["_admin"]["nsState"] = "NOT_INSTANTIATED"
83 return None
84
85 def check_conflict_on_del(self, session, _id, db_content):
86 """
87 Check that NSR is not instantiated
88 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
89 :param _id: nsr internal id
90 :param db_content: The database content of the nsr
91 :return: None or raises EngineException with the conflict
92 """
93 if session["force"]:
94 return
95 nsr = db_content
96 if nsr["_admin"].get("nsState") == "INSTANTIATED":
97 raise EngineException(
98 "nsr '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
99 "Launch 'terminate' operation first; or force deletion".format(_id),
100 http_code=HTTPStatus.CONFLICT,
101 )
102
103 def delete_extra(self, session, _id, db_content, not_send_msg=None):
104 """
105 Deletes associated nslcmops and vnfrs from database. Deletes associated filesystem.
106 Set usageState of pdu, vnfd, nsd
107 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
108 :param _id: server internal id
109 :param db_content: The database content of the descriptor
110 :param not_send_msg: To not send message (False) or store content (list) instead
111 :return: None if ok or raises EngineException with the problem
112 """
113 self.fs.file_delete(_id, ignore_non_exist=True)
114 self.db.del_list("nslcmops", {"nsInstanceId": _id})
115 self.db.del_list("vnfrs", {"nsr-id-ref": _id})
116
117 # set all used pdus as free
118 self.db.set_list(
119 "pdus",
120 {"_admin.usage.nsr_id": _id},
121 {"_admin.usageState": "NOT_IN_USE", "_admin.usage": None},
122 )
123
124 # Set NSD usageState
125 nsr = db_content
126 used_nsd_id = nsr.get("nsd-id")
127 if used_nsd_id:
128 # check if used by another NSR
129 nsrs_list = self.db.get_one(
130 "nsrs", {"nsd-id": used_nsd_id}, fail_on_empty=False, fail_on_more=False
131 )
132 if not nsrs_list:
133 self.db.set_one(
134 "nsds", {"_id": used_nsd_id}, {"_admin.usageState": "NOT_IN_USE"}
135 )
136
137 # Set VNFD usageState
138 used_vnfd_id_list = nsr.get("vnfd-id")
139 if used_vnfd_id_list:
140 for used_vnfd_id in used_vnfd_id_list:
141 # check if used by another NSR
142 nsrs_list = self.db.get_one(
143 "nsrs",
144 {"vnfd-id": used_vnfd_id},
145 fail_on_empty=False,
146 fail_on_more=False,
147 )
148 if not nsrs_list:
149 self.db.set_one(
150 "vnfds",
151 {"_id": used_vnfd_id},
152 {"_admin.usageState": "NOT_IN_USE"},
153 )
154
155 # delete extra ro_nsrs used for internal RO module
156 self.db.del_one("ro_nsrs", q_filter={"_id": _id}, fail_on_empty=False)
157
158 @staticmethod
159 def _format_ns_request(ns_request):
160 formated_request = copy(ns_request)
161 formated_request.pop("additionalParamsForNs", None)
162 formated_request.pop("additionalParamsForVnf", None)
163 return formated_request
164
165 @staticmethod
166 def _format_additional_params(
167 ns_request, member_vnf_index=None, vdu_id=None, kdu_name=None, descriptor=None
168 ):
169 """
170 Get and format user additional params for NS or VNF
171 :param ns_request: User instantiation additional parameters
172 :param member_vnf_index: None for extract NS params, or member_vnf_index to extract VNF params
173 :param descriptor: If not None it check that needed parameters of descriptor are supplied
174 :return: tuple with a formatted copy of additional params or None if not supplied, plus other parameters
175 """
176 additional_params = None
177 other_params = None
178 if not member_vnf_index:
179 additional_params = copy(ns_request.get("additionalParamsForNs"))
180 where_ = "additionalParamsForNs"
181 elif ns_request.get("additionalParamsForVnf"):
182 where_ = "additionalParamsForVnf[member-vnf-index={}]".format(
183 member_vnf_index
184 )
185 item = next(
186 (
187 x
188 for x in ns_request["additionalParamsForVnf"]
189 if x["member-vnf-index"] == member_vnf_index
190 ),
191 None,
192 )
193 if item:
194 if not vdu_id and not kdu_name:
195 other_params = item
196 additional_params = copy(item.get("additionalParams")) or {}
197 if vdu_id and item.get("additionalParamsForVdu"):
198 item_vdu = next(
199 (
200 x
201 for x in item["additionalParamsForVdu"]
202 if x["vdu_id"] == vdu_id
203 ),
204 None,
205 )
206 other_params = item_vdu
207 if item_vdu and item_vdu.get("additionalParams"):
208 where_ += ".additionalParamsForVdu[vdu_id={}]".format(vdu_id)
209 additional_params = item_vdu["additionalParams"]
210 if kdu_name:
211 additional_params = {}
212 if item.get("additionalParamsForKdu"):
213 item_kdu = next(
214 (
215 x
216 for x in item["additionalParamsForKdu"]
217 if x["kdu_name"] == kdu_name
218 ),
219 None,
220 )
221 other_params = item_kdu
222 if item_kdu and item_kdu.get("additionalParams"):
223 where_ += ".additionalParamsForKdu[kdu_name={}]".format(
224 kdu_name
225 )
226 additional_params = item_kdu["additionalParams"]
227
228 if additional_params:
229 for k, v in additional_params.items():
230 # BEGIN Check that additional parameter names are valid Jinja2 identifiers if target is not Kdu
231 if not kdu_name and not match("^[a-zA-Z_][a-zA-Z0-9_]*$", k):
232 raise EngineException(
233 "Invalid param name at {}:{}. Must contain only alphanumeric characters "
234 "and underscores, and cannot start with a digit".format(
235 where_, k
236 )
237 )
238 # END Check that additional parameter names are valid Jinja2 identifiers
239 if not isinstance(k, str):
240 raise EngineException(
241 "Invalid param at {}:{}. Only string keys are allowed".format(
242 where_, k
243 )
244 )
245 if "$" in k:
246 raise EngineException(
247 "Invalid param at {}:{}. Keys must not contain $ symbol".format(
248 where_, k
249 )
250 )
251 if isinstance(v, (dict, tuple, list)):
252 additional_params[k] = "!!yaml " + safe_dump(v)
253 if kdu_name:
254 additional_params = json.dumps(additional_params)
255
256 if descriptor:
257 for df in descriptor.get("df", []):
258 # check that enough parameters are supplied for the initial-config-primitive
259 # TODO: check for cloud-init
260 if member_vnf_index:
261 initial_primitives = []
262 if (
263 "lcm-operations-configuration" in df
264 and "operate-vnf-op-config"
265 in df["lcm-operations-configuration"]
266 ):
267 for config in df["lcm-operations-configuration"][
268 "operate-vnf-op-config"
269 ].get("day1-2", []):
270 for primitive in get_iterable(
271 config.get("initial-config-primitive")
272 ):
273 initial_primitives.append(primitive)
274 else:
275 initial_primitives = deep_get(
276 descriptor, ("ns-configuration", "initial-config-primitive")
277 )
278
279 for initial_primitive in get_iterable(initial_primitives):
280 for param in get_iterable(initial_primitive.get("parameter")):
281 if param["value"].startswith("<") and param["value"].endswith(
282 ">"
283 ):
284 if param["value"] in (
285 "<rw_mgmt_ip>",
286 "<VDU_SCALE_INFO>",
287 "<ns_config_info>",
288 ):
289 continue
290 if (
291 not additional_params
292 or param["value"][1:-1] not in additional_params
293 ):
294 raise EngineException(
295 "Parameter '{}' needed for vnfd[id={}]:day1-2 configuration:"
296 "initial-config-primitive[name={}] not supplied".format(
297 param["value"],
298 descriptor["id"],
299 initial_primitive["name"],
300 )
301 )
302
303 return additional_params or None, other_params or None
304
305 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
306 """
307 Creates a new nsr into database. It also creates needed vnfrs
308 :param rollback: list to append the created items at database in case a rollback must be done
309 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
310 :param indata: params to be used for the nsr
311 :param kwargs: used to override the indata descriptor
312 :param headers: http request headers
313 :return: the _id of nsr descriptor created at database. Or an exception of type
314 EngineException, ValidationError, DbException, FsException, MsgException.
315 Note: Exceptions are not captured on purpose. They should be captured at called
316 """
317 try:
318 step = "checking quotas"
319 self.check_quota(session)
320
321 step = "validating input parameters"
322 ns_request = self._remove_envelop(indata)
323 self._update_input_with_kwargs(ns_request, kwargs)
324 ns_request = self._validate_input_new(ns_request, session["force"])
325
326 step = "getting nsd id='{}' from database".format(ns_request.get("nsdId"))
327 nsd = self._get_nsd_from_db(ns_request["nsdId"], session)
328 ns_k8s_namespace = self._get_ns_k8s_namespace(nsd, ns_request, session)
329
330 step = "checking nsdOperationalState"
331 self._check_nsd_operational_state(nsd, ns_request)
332
333 step = "filling nsr from input data"
334 nsr_id = str(uuid4())
335 nsr_descriptor = self._create_nsr_descriptor_from_nsd(
336 nsd, ns_request, nsr_id, session
337 )
338
339 # Create VNFRs
340 needed_vnfds = {}
341 # TODO: Change for multiple df support
342 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
343 for vnfp in vnf_profiles:
344 vnfd_id = vnfp.get("vnfd-id")
345 vnf_index = vnfp.get("id")
346 step = (
347 "getting vnfd id='{}' constituent-vnfd='{}' from database".format(
348 vnfd_id, vnf_index
349 )
350 )
351 if vnfd_id not in needed_vnfds:
352 vnfd = self._get_vnfd_from_db(vnfd_id, session)
353 if "revision" in vnfd["_admin"]:
354 vnfd["revision"] = vnfd["_admin"]["revision"]
355 vnfd.pop("_admin")
356 needed_vnfds[vnfd_id] = vnfd
357 nsr_descriptor["vnfd-id"].append(vnfd["_id"])
358 else:
359 vnfd = needed_vnfds[vnfd_id]
360
361 step = "filling vnfr vnfd-id='{}' constituent-vnfd='{}'".format(
362 vnfd_id, vnf_index
363 )
364 vnfr_descriptor = self._create_vnfr_descriptor_from_vnfd(
365 nsd,
366 vnfd,
367 vnfd_id,
368 vnf_index,
369 nsr_descriptor,
370 ns_request,
371 ns_k8s_namespace,
372 )
373
374 step = "creating vnfr vnfd-id='{}' constituent-vnfd='{}' at database".format(
375 vnfd_id, vnf_index
376 )
377 self._add_vnfr_to_db(vnfr_descriptor, rollback, session)
378 nsr_descriptor["constituent-vnfr-ref"].append(vnfr_descriptor["id"])
379
380 step = "creating nsr at database"
381 self._add_nsr_to_db(nsr_descriptor, rollback, session)
382
383 step = "creating nsr temporal folder"
384 self.fs.mkdir(nsr_id)
385
386 return nsr_id, None
387 except (
388 ValidationError,
389 EngineException,
390 DbException,
391 MsgException,
392 FsException,
393 ) as e:
394 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
395
396 def _get_nsd_from_db(self, nsd_id, session):
397 _filter = self._get_project_filter(session)
398 _filter["_id"] = nsd_id
399 return self.db.get_one("nsds", _filter)
400
401 def _get_vnfd_from_db(self, vnfd_id, session):
402 _filter = self._get_project_filter(session)
403 _filter["id"] = vnfd_id
404 vnfd = self.db.get_one("vnfds", _filter, fail_on_empty=True, fail_on_more=True)
405 return vnfd
406
407 def _add_nsr_to_db(self, nsr_descriptor, rollback, session):
408 self.format_on_new(
409 nsr_descriptor, session["project_id"], make_public=session["public"]
410 )
411 self.db.create("nsrs", nsr_descriptor)
412 rollback.append({"topic": "nsrs", "_id": nsr_descriptor["id"]})
413
414 def _add_vnfr_to_db(self, vnfr_descriptor, rollback, session):
415 self.format_on_new(
416 vnfr_descriptor, session["project_id"], make_public=session["public"]
417 )
418 self.db.create("vnfrs", vnfr_descriptor)
419 rollback.append({"topic": "vnfrs", "_id": vnfr_descriptor["id"]})
420
421 def _check_nsd_operational_state(self, nsd, ns_request):
422 if nsd["_admin"]["operationalState"] == "DISABLED":
423 raise EngineException(
424 "nsd with id '{}' is DISABLED, and thus cannot be used to create "
425 "a network service".format(ns_request["nsdId"]),
426 http_code=HTTPStatus.CONFLICT,
427 )
428
429 def _get_ns_k8s_namespace(self, nsd, ns_request, session):
430 additional_params, _ = self._format_additional_params(
431 ns_request, descriptor=nsd
432 )
433 # use for k8s-namespace from ns_request or additionalParamsForNs. By default, the project_id
434 ns_k8s_namespace = session["project_id"][0] if session["project_id"] else None
435 if ns_request and ns_request.get("k8s-namespace"):
436 ns_k8s_namespace = ns_request["k8s-namespace"]
437 if additional_params and additional_params.get("k8s-namespace"):
438 ns_k8s_namespace = additional_params["k8s-namespace"]
439
440 return ns_k8s_namespace
441
442 def _add_flavor_to_nsr(self, vdu, vnfd, nsr_descriptor):
443 flavor_data = {}
444 guest_epa = {}
445 # Find this vdu compute and storage descriptors
446 vdu_virtual_compute = {}
447 vdu_virtual_storage = {}
448 for vcd in vnfd.get("virtual-compute-desc", ()):
449 if vcd.get("id") == vdu.get("virtual-compute-desc"):
450 vdu_virtual_compute = vcd
451 for vsd in vnfd.get("virtual-storage-desc", ()):
452 if vsd.get("id") == vdu.get("virtual-storage-desc", [[]])[0]:
453 vdu_virtual_storage = vsd
454 # Get this vdu vcpus, memory and storage info for flavor_data
455 if vdu_virtual_compute.get("virtual-cpu", {}).get(
456 "num-virtual-cpu"
457 ):
458 flavor_data["vcpu-count"] = vdu_virtual_compute["virtual-cpu"][
459 "num-virtual-cpu"
460 ]
461 if vdu_virtual_compute.get("virtual-memory", {}).get("size"):
462 flavor_data["memory-mb"] = (
463 float(vdu_virtual_compute["virtual-memory"]["size"])
464 * 1024.0
465 )
466 if vdu_virtual_storage.get("size-of-storage"):
467 flavor_data["storage-gb"] = vdu_virtual_storage[
468 "size-of-storage"
469 ]
470 # Get this vdu EPA info for guest_epa
471 if vdu_virtual_compute.get("virtual-cpu", {}).get("cpu-quota"):
472 guest_epa["cpu-quota"] = vdu_virtual_compute["virtual-cpu"][
473 "cpu-quota"
474 ]
475 if vdu_virtual_compute.get("virtual-cpu", {}).get("pinning"):
476 vcpu_pinning = vdu_virtual_compute["virtual-cpu"]["pinning"]
477 if vcpu_pinning.get("thread-policy"):
478 guest_epa["cpu-thread-pinning-policy"] = vcpu_pinning[
479 "thread-policy"
480 ]
481 if vcpu_pinning.get("policy"):
482 cpu_policy = (
483 "SHARED"
484 if vcpu_pinning["policy"] == "dynamic"
485 else "DEDICATED"
486 )
487 guest_epa["cpu-pinning-policy"] = cpu_policy
488 if vdu_virtual_compute.get("virtual-memory", {}).get("mem-quota"):
489 guest_epa["mem-quota"] = vdu_virtual_compute["virtual-memory"][
490 "mem-quota"
491 ]
492 if vdu_virtual_compute.get("virtual-memory", {}).get(
493 "mempage-size"
494 ):
495 guest_epa["mempage-size"] = vdu_virtual_compute[
496 "virtual-memory"
497 ]["mempage-size"]
498 if vdu_virtual_compute.get("virtual-memory", {}).get(
499 "numa-node-policy"
500 ):
501 guest_epa["numa-node-policy"] = vdu_virtual_compute[
502 "virtual-memory"
503 ]["numa-node-policy"]
504 if vdu_virtual_storage.get("disk-io-quota"):
505 guest_epa["disk-io-quota"] = vdu_virtual_storage[
506 "disk-io-quota"
507 ]
508
509 if guest_epa:
510 flavor_data["guest-epa"] = guest_epa
511
512 flavor_data["name"] = vdu["id"][:56] + "-flv"
513 flavor_data["id"] = str(len(nsr_descriptor["flavor"]))
514 nsr_descriptor["flavor"].append(flavor_data)
515
516 def _create_nsr_descriptor_from_nsd(self, nsd, ns_request, nsr_id, session):
517 now = time()
518 additional_params, _ = self._format_additional_params(
519 ns_request, descriptor=nsd
520 )
521
522 nsr_descriptor = {
523 "name": ns_request["nsName"],
524 "name-ref": ns_request["nsName"],
525 "short-name": ns_request["nsName"],
526 "admin-status": "ENABLED",
527 "nsState": "NOT_INSTANTIATED",
528 "currentOperation": "IDLE",
529 "currentOperationID": None,
530 "errorDescription": None,
531 "errorDetail": None,
532 "deploymentStatus": None,
533 "configurationStatus": None,
534 "vcaStatus": None,
535 "nsd": {k: v for k, v in nsd.items()},
536 "datacenter": ns_request["vimAccountId"],
537 "resource-orchestrator": "osmopenmano",
538 "description": ns_request.get("nsDescription", ""),
539 "constituent-vnfr-ref": [],
540 "operational-status": "init", # typedef ns-operational-
541 "config-status": "init", # typedef config-states
542 "detailed-status": "scheduled",
543 "orchestration-progress": {},
544 "create-time": now,
545 "nsd-name-ref": nsd["name"],
546 "operational-events": [], # "id", "timestamp", "description", "event",
547 "nsd-ref": nsd["id"],
548 "nsd-id": nsd["_id"],
549 "vnfd-id": [],
550 "instantiate_params": self._format_ns_request(ns_request),
551 "additionalParamsForNs": additional_params,
552 "ns-instance-config-ref": nsr_id,
553 "id": nsr_id,
554 "_id": nsr_id,
555 "ssh-authorized-key": ns_request.get("ssh_keys"), # TODO remove
556 "flavor": [],
557 "image": [],
558 "affinity-or-anti-affinity-group": [],
559 }
560 ns_request["nsr_id"] = nsr_id
561 if ns_request and ns_request.get("config-units"):
562 nsr_descriptor["config-units"] = ns_request["config-units"]
563 # Create vld
564 if nsd.get("virtual-link-desc"):
565 nsr_vld = deepcopy(nsd.get("virtual-link-desc", []))
566 # Fill each vld with vnfd-connection-point-ref data
567 # TODO: Change for multiple df support
568 all_vld_connection_point_data = {vld.get("id"): [] for vld in nsr_vld}
569 vnf_profiles = nsd.get("df", [[]])[0].get("vnf-profile", ())
570 for vnf_profile in vnf_profiles:
571 for vlc in vnf_profile.get("virtual-link-connectivity", ()):
572 for cpd in vlc.get("constituent-cpd-id", ()):
573 all_vld_connection_point_data[
574 vlc.get("virtual-link-profile-id")
575 ].append(
576 {
577 "member-vnf-index-ref": cpd.get(
578 "constituent-base-element-id"
579 ),
580 "vnfd-connection-point-ref": cpd.get(
581 "constituent-cpd-id"
582 ),
583 "vnfd-id-ref": vnf_profile.get("vnfd-id"),
584 }
585 )
586
587 vnfd = self._get_vnfd_from_db(vnf_profile.get("vnfd-id"), session)
588 vnfd.pop("_admin")
589
590 for vdu in vnfd.get("vdu", ()):
591 self._add_flavor_to_nsr(vdu, vnfd, nsr_descriptor)
592 sw_image_id = vdu.get("sw-image-desc")
593 if sw_image_id:
594 image_data = self._get_image_data_from_vnfd(vnfd, sw_image_id)
595 self._add_image_to_nsr(nsr_descriptor, image_data)
596
597 # also add alternative images to the list of images
598 for alt_image in vdu.get("alternative-sw-image-desc", ()):
599 image_data = self._get_image_data_from_vnfd(vnfd, alt_image)
600 self._add_image_to_nsr(nsr_descriptor, image_data)
601
602 # Add Affinity or Anti-affinity group information to NSR
603 vdu_profiles = vnfd.get("df", [[]])[0].get("vdu-profile", ())
604 affinity_group_prefix_name = "{}-{}".format(
605 nsr_descriptor["name"][:16], vnf_profile.get("id")[:16]
606 )
607
608 for vdu_profile in vdu_profiles:
609 affinity_group_data = {}
610 for affinity_group in vdu_profile.get(
611 "affinity-or-anti-affinity-group", ()
612 ):
613 affinity_group_data = (
614 self._get_affinity_or_anti_affinity_group_data_from_vnfd(
615 vnfd, affinity_group["id"]
616 )
617 )
618 affinity_group_data["member-vnf-index"] = vnf_profile.get("id")
619 self._add_affinity_or_anti_affinity_group_to_nsr(
620 nsr_descriptor,
621 affinity_group_data,
622 affinity_group_prefix_name,
623 )
624
625 for vld in nsr_vld:
626 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
627 vld.get("id"), []
628 )
629 vld["name"] = vld["id"]
630 nsr_descriptor["vld"] = nsr_vld
631
632 return nsr_descriptor
633
634 def _get_affinity_or_anti_affinity_group_data_from_vnfd(
635 self, vnfd, affinity_group_id
636 ):
637 """
638 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
639 """
640 affinity_group = utils.find_in_list(
641 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()),
642 lambda ag: ag["id"] == affinity_group_id,
643 )
644 affinity_group_data = {}
645 if affinity_group:
646 if affinity_group.get("id"):
647 affinity_group_data["ag-id"] = affinity_group["id"]
648 if affinity_group.get("type"):
649 affinity_group_data["type"] = affinity_group["type"]
650 if affinity_group.get("scope"):
651 affinity_group_data["scope"] = affinity_group["scope"]
652 return affinity_group_data
653
654 def _add_affinity_or_anti_affinity_group_to_nsr(
655 self, nsr_descriptor, affinity_group_data, affinity_group_prefix_name
656 ):
657 """
658 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
659 """
660 affinity_group = next(
661 (
662 f
663 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
664 if all(f.get(k) == affinity_group_data[k] for k in affinity_group_data)
665 ),
666 None,
667 )
668 if not affinity_group:
669 affinity_group_data["id"] = str(
670 len(nsr_descriptor["affinity-or-anti-affinity-group"])
671 )
672 affinity_group_data["name"] = "{}-{}".format(
673 affinity_group_prefix_name, affinity_group_data["ag-id"][:32]
674 )
675 nsr_descriptor["affinity-or-anti-affinity-group"].append(
676 affinity_group_data
677 )
678
679 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
680 sw_image_desc = utils.find_in_list(
681 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
682 )
683 image_data = {}
684 if sw_image_desc.get("image"):
685 image_data["image"] = sw_image_desc["image"]
686 if sw_image_desc.get("checksum"):
687 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
688 if sw_image_desc.get("vim-type"):
689 image_data["vim-type"] = sw_image_desc["vim-type"]
690 return image_data
691
692 def _add_image_to_nsr(self, nsr_descriptor, image_data):
693 """
694 Adds image to nsr checking first it is not already added
695 """
696 img = next(
697 (
698 f
699 for f in nsr_descriptor["image"]
700 if all(f.get(k) == image_data[k] for k in image_data)
701 ),
702 None,
703 )
704 if not img:
705 image_data["id"] = str(len(nsr_descriptor["image"]))
706 nsr_descriptor["image"].append(image_data)
707
708 def _create_vnfr_descriptor_from_vnfd(
709 self,
710 nsd,
711 vnfd,
712 vnfd_id,
713 vnf_index,
714 nsr_descriptor,
715 ns_request,
716 ns_k8s_namespace,
717 ):
718 vnfr_id = str(uuid4())
719 nsr_id = nsr_descriptor["id"]
720 now = time()
721 additional_params, vnf_params = self._format_additional_params(
722 ns_request, vnf_index, descriptor=vnfd
723 )
724
725 vnfr_descriptor = {
726 "id": vnfr_id,
727 "_id": vnfr_id,
728 "nsr-id-ref": nsr_id,
729 "member-vnf-index-ref": vnf_index,
730 "additionalParamsForVnf": additional_params,
731 "created-time": now,
732 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
733 "vnfd-ref": vnfd_id,
734 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
735 "vim-account-id": None,
736 "vca-id": None,
737 "vdur": [],
738 "connection-point": [],
739 "ip-address": None, # mgmt-interface filled by LCM
740 }
741
742 # Revision backwards compatility. Only specify the revision in the record if
743 # the original VNFD has a revision.
744 if "revision" in vnfd:
745 vnfr_descriptor["revision"] = vnfd["revision"]
746
747
748 vnf_k8s_namespace = ns_k8s_namespace
749 if vnf_params:
750 if vnf_params.get("k8s-namespace"):
751 vnf_k8s_namespace = vnf_params["k8s-namespace"]
752 if vnf_params.get("config-units"):
753 vnfr_descriptor["config-units"] = vnf_params["config-units"]
754
755 # Create vld
756 if vnfd.get("int-virtual-link-desc"):
757 vnfr_descriptor["vld"] = []
758 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
759 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
760
761 for cp in vnfd.get("ext-cpd", ()):
762 vnf_cp = {
763 "name": cp.get("id"),
764 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
765 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
766 "id": cp.get("id"),
767 # "ip-address", "mac-address" # filled by LCM
768 # vim-id # TODO it would be nice having a vim port id
769 }
770 vnfr_descriptor["connection-point"].append(vnf_cp)
771
772 # Create k8s-cluster information
773 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
774 if vnfd.get("k8s-cluster"):
775 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
776 all_k8s_cluster_nets_cpds = {}
777 for cpd in get_iterable(vnfd.get("ext-cpd")):
778 if cpd.get("k8s-cluster-net"):
779 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
780 "id"
781 )
782 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
783 if net.get("id") in all_k8s_cluster_nets_cpds:
784 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
785 net.get("id")
786 ]
787
788 # update kdus
789 for kdu in get_iterable(vnfd.get("kdu")):
790 additional_params, kdu_params = self._format_additional_params(
791 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
792 )
793 kdu_k8s_namespace = vnf_k8s_namespace
794 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
795 if kdu_params and kdu_params.get("k8s-namespace"):
796 kdu_k8s_namespace = kdu_params["k8s-namespace"]
797
798 kdu_deployment_name = ""
799 if kdu_params and kdu_params.get("kdu-deployment-name"):
800 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
801
802 kdur = {
803 "additionalParams": additional_params,
804 "k8s-namespace": kdu_k8s_namespace,
805 "kdu-deployment-name": kdu_deployment_name,
806 "kdu-name": kdu["name"],
807 # TODO "name": "" Name of the VDU in the VIM
808 "ip-address": None, # mgmt-interface filled by LCM
809 "k8s-cluster": {},
810 }
811 if kdu_params and kdu_params.get("config-units"):
812 kdur["config-units"] = kdu_params["config-units"]
813 if kdu.get("helm-version"):
814 kdur["helm-version"] = kdu["helm-version"]
815 for k8s_type in ("helm-chart", "juju-bundle"):
816 if kdu.get(k8s_type):
817 kdur[k8s_type] = kdu_model or kdu[k8s_type]
818 if not vnfr_descriptor.get("kdur"):
819 vnfr_descriptor["kdur"] = []
820 vnfr_descriptor["kdur"].append(kdur)
821
822 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
823
824 for vdu in vnfd.get("vdu", ()):
825 vdu_mgmt_cp = []
826 try:
827 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
828 "operate-vnf-op-config"
829 ]["day1-2"]
830 vdu_config = utils.find_in_list(
831 configs, lambda config: config["id"] == vdu["id"]
832 )
833 except Exception:
834 vdu_config = None
835
836 try:
837 vdu_instantiation_level = utils.find_in_list(
838 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
839 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
840 )
841 except Exception:
842 vdu_instantiation_level = None
843
844 if vdu_config:
845 external_connection_ee = utils.filter_in_list(
846 vdu_config.get("execution-environment-list", []),
847 lambda ee: "external-connection-point-ref" in ee,
848 )
849 for ee in external_connection_ee:
850 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
851
852 additional_params, vdu_params = self._format_additional_params(
853 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
854 )
855
856 try:
857 vdu_virtual_storage_descriptors = utils.filter_in_list(
858 vnfd.get("virtual-storage-desc", []),
859 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"]
860 )
861 except Exception:
862 vdu_virtual_storage_descriptors = []
863 vdur = {
864 "vdu-id-ref": vdu["id"],
865 # TODO "name": "" Name of the VDU in the VIM
866 "ip-address": None, # mgmt-interface filled by LCM
867 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
868 "internal-connection-point": [],
869 "interfaces": [],
870 "additionalParams": additional_params,
871 "vdu-name": vdu["name"],
872 "virtual-storages": vdu_virtual_storage_descriptors
873 }
874 if vdu_params and vdu_params.get("config-units"):
875 vdur["config-units"] = vdu_params["config-units"]
876 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
877 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
878 "boot-data-drive"
879 ]
880 if vdu.get("pdu-type"):
881 vdur["pdu-type"] = vdu["pdu-type"]
882 vdur["name"] = vdu["pdu-type"]
883 # TODO volumes: name, volume-id
884 for icp in vdu.get("int-cpd", ()):
885 vdu_icp = {
886 "id": icp["id"],
887 "connection-point-id": icp["id"],
888 "name": icp.get("id"),
889 }
890
891 vdur["internal-connection-point"].append(vdu_icp)
892
893 for iface in icp.get("virtual-network-interface-requirement", ()):
894 iface_fields = ("name", "mac-address")
895 vdu_iface = {
896 x: iface[x] for x in iface_fields if iface.get(x) is not None
897 }
898
899 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
900 if "port-security-enabled" in icp:
901 vdu_iface["port-security-enabled"] = icp[
902 "port-security-enabled"
903 ]
904
905 if "port-security-disable-strategy" in icp:
906 vdu_iface["port-security-disable-strategy"] = icp[
907 "port-security-disable-strategy"
908 ]
909
910 for ext_cp in vnfd.get("ext-cpd", ()):
911 if not ext_cp.get("int-cpd"):
912 continue
913 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
914 continue
915 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
916 vdu_iface["external-connection-point-ref"] = ext_cp.get(
917 "id"
918 )
919
920 if "port-security-enabled" in ext_cp:
921 vdu_iface["port-security-enabled"] = ext_cp[
922 "port-security-enabled"
923 ]
924
925 if "port-security-disable-strategy" in ext_cp:
926 vdu_iface["port-security-disable-strategy"] = ext_cp[
927 "port-security-disable-strategy"
928 ]
929
930 break
931
932 if (
933 vnfd_mgmt_cp
934 and vdu_iface.get("external-connection-point-ref")
935 == vnfd_mgmt_cp
936 ):
937 vdu_iface["mgmt-vnf"] = True
938 vdu_iface["mgmt-interface"] = True
939
940 for ecp in vdu_mgmt_cp:
941 if vdu_iface.get("external-connection-point-ref") == ecp:
942 vdu_iface["mgmt-interface"] = True
943
944 if iface.get("virtual-interface"):
945 vdu_iface.update(deepcopy(iface["virtual-interface"]))
946
947 # look for network where this interface is connected
948 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
949 if iface_ext_cp:
950 # TODO: Change for multiple df support
951 for df in get_iterable(nsd.get("df")):
952 for vnf_profile in get_iterable(df.get("vnf-profile")):
953 for vlc_index, vlc in enumerate(
954 get_iterable(
955 vnf_profile.get("virtual-link-connectivity")
956 )
957 ):
958 for cpd in get_iterable(
959 vlc.get("constituent-cpd-id")
960 ):
961 if (
962 cpd.get("constituent-cpd-id")
963 == iface_ext_cp
964 ):
965 vdu_iface["ns-vld-id"] = vlc.get(
966 "virtual-link-profile-id"
967 )
968 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
969 if vdu_iface.get("type") in (
970 "SR-IOV",
971 "PCI-PASSTHROUGH",
972 ):
973 nsr_descriptor["vld"][vlc_index][
974 "pci-interfaces"
975 ] = True
976 break
977 elif vdu_iface.get("internal-connection-point-ref"):
978 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
979 # TODO: store fixed IP address in the record (if it exists in the ICP)
980 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
981 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
982 ivld_index = utils.find_index_in_list(
983 vnfd.get("int-virtual-link-desc", ()),
984 lambda ivld: ivld["id"]
985 == icp.get("int-virtual-link-desc"),
986 )
987 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
988
989 vdur["interfaces"].append(vdu_iface)
990
991 if vdu.get("sw-image-desc"):
992 sw_image = utils.find_in_list(
993 vnfd.get("sw-image-desc", ()),
994 lambda image: image["id"] == vdu.get("sw-image-desc"),
995 )
996 nsr_sw_image_data = utils.find_in_list(
997 nsr_descriptor["image"],
998 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
999 )
1000 vdur["ns-image-id"] = nsr_sw_image_data["id"]
1001
1002 if vdu.get("alternative-sw-image-desc"):
1003 alt_image_ids = []
1004 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
1005 sw_image = utils.find_in_list(
1006 vnfd.get("sw-image-desc", ()),
1007 lambda image: image["id"] == alt_image_id,
1008 )
1009 nsr_sw_image_data = utils.find_in_list(
1010 nsr_descriptor["image"],
1011 lambda nsr_image: (
1012 nsr_image.get("image") == sw_image.get("image")
1013 ),
1014 )
1015 alt_image_ids.append(nsr_sw_image_data["id"])
1016 vdur["alt-image-ids"] = alt_image_ids
1017
1018 flavor_data_name = vdu["id"][:56] + "-flv"
1019 nsr_flavor_desc = utils.find_in_list(
1020 nsr_descriptor["flavor"],
1021 lambda flavor: flavor["name"] == flavor_data_name,
1022 )
1023
1024 if nsr_flavor_desc:
1025 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
1026
1027 # Adding Affinity groups information to vdur
1028 try:
1029 vdu_profile_affinity_group = utils.find_in_list(
1030 vnfd.get("df")[0]["vdu-profile"],
1031 lambda a_vdu: a_vdu["id"] == vdu["id"],
1032 )
1033 except Exception:
1034 vdu_profile_affinity_group = None
1035
1036 if vdu_profile_affinity_group:
1037 affinity_group_ids = []
1038 for affinity_group in vdu_profile_affinity_group.get(
1039 "affinity-or-anti-affinity-group", ()
1040 ):
1041 vdu_affinity_group = utils.find_in_list(
1042 vdu_profile_affinity_group.get(
1043 "affinity-or-anti-affinity-group", ()
1044 ),
1045 lambda ag_fp: ag_fp["id"] == affinity_group["id"],
1046 )
1047 nsr_affinity_group = utils.find_in_list(
1048 nsr_descriptor["affinity-or-anti-affinity-group"],
1049 lambda nsr_ag: (
1050 nsr_ag.get("ag-id") == vdu_affinity_group.get("id")
1051 and nsr_ag.get("member-vnf-index")
1052 == vnfr_descriptor.get("member-vnf-index-ref")
1053 ),
1054 )
1055 # Update Affinity Group VIM name if VDU instantiation parameter is present
1056 if vnf_params and vnf_params.get("affinity-or-anti-affinity-group"):
1057 vnf_params_affinity_group = utils.find_in_list(
1058 vnf_params["affinity-or-anti-affinity-group"],
1059 lambda vnfp_ag: (
1060 vnfp_ag.get("id") == vdu_affinity_group.get("id")
1061 ),
1062 )
1063 if vnf_params_affinity_group.get("vim-affinity-group-id"):
1064 nsr_affinity_group[
1065 "vim-affinity-group-id"
1066 ] = vnf_params_affinity_group["vim-affinity-group-id"]
1067 affinity_group_ids.append(nsr_affinity_group["id"])
1068 vdur["affinity-or-anti-affinity-group-id"] = affinity_group_ids
1069
1070 if vdu_instantiation_level:
1071 count = vdu_instantiation_level.get("number-of-instances")
1072 else:
1073 count = 1
1074
1075 for index in range(0, count):
1076 vdur = deepcopy(vdur)
1077 for iface in vdur["interfaces"]:
1078 if iface.get("ip-address") and index != 0:
1079 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
1080 if iface.get("mac-address") and index != 0:
1081 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1082
1083 vdur["_id"] = str(uuid4())
1084 vdur["id"] = vdur["_id"]
1085 vdur["count-index"] = index
1086 vnfr_descriptor["vdur"].append(vdur)
1087
1088 return vnfr_descriptor
1089
1090 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1091 """
1092 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1093 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1094 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1095 :param ns_instance_content: ns instance content
1096 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1097 :return: None
1098 """
1099 time_now, time_delta = time(), time() - ns_instance_content["_admin"]["modified"]
1100 force_refresh = isinstance(filter_q, dict) and filter_q.get('vcaStatusRefresh') == 'true'
1101 threshold_reached = time_delta > 120
1102 if force_refresh or threshold_reached:
1103 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1104 ns_instance_content["_admin"]["modified"] = time_now
1105 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1106 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
1107 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
1108 nslcmop_desc["_admin"].pop("nsState")
1109 self.msg.write("ns", operation, nslcmop_desc)
1110 return
1111
1112 def show(self, session, _id, filter_q=None, api_req=False):
1113 """
1114 Get complete information on an ns instance.
1115 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1116 :param _id: string, ns instance id
1117 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1118 :param api_req: True if this call is serving an external API request. False if serving internal request.
1119 :return: dictionary, raise exception if not found.
1120 """
1121 ns_instance_content = super().show(session, _id, api_req)
1122 self.vca_status_refresh(session, ns_instance_content, filter_q)
1123 return ns_instance_content
1124
1125 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1126 raise EngineException(
1127 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1128 )
1129
1130
1131 class VnfrTopic(BaseTopic):
1132 topic = "vnfrs"
1133 topic_msg = None
1134
1135 def __init__(self, db, fs, msg, auth):
1136 BaseTopic.__init__(self, db, fs, msg, auth)
1137
1138 def delete(self, session, _id, dry_run=False, not_send_msg=None):
1139 raise EngineException(
1140 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1141 )
1142
1143 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1144 raise EngineException(
1145 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1146 )
1147
1148 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1149 # Not used because vnfrs are created and deleted by NsrTopic class directly
1150 raise EngineException(
1151 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1152 )
1153
1154
1155 class NsLcmOpTopic(BaseTopic):
1156 topic = "nslcmops"
1157 topic_msg = "ns"
1158 operation_schema = { # mapping between operation and jsonschema to validate
1159 "instantiate": ns_instantiate,
1160 "action": ns_action,
1161 "update": ns_update,
1162 "scale": ns_scale,
1163 "terminate": ns_terminate,
1164 "migrate": ns_migrate,
1165 }
1166
1167 def __init__(self, db, fs, msg, auth):
1168 BaseTopic.__init__(self, db, fs, msg, auth)
1169 self.nsrtopic = NsrTopic(db, fs, msg, auth)
1170
1171 def _check_ns_operation(self, session, nsr, operation, indata):
1172 """
1173 Check that user has enter right parameters for the operation
1174 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1175 :param operation: it can be: instantiate, terminate, action, update. TODO: heal
1176 :param indata: descriptor with the parameters of the operation
1177 :return: None
1178 """
1179 if operation == "action":
1180 self._check_action_ns_operation(indata, nsr)
1181 elif operation == "scale":
1182 self._check_scale_ns_operation(indata, nsr)
1183 elif operation == "update":
1184 self._check_update_ns_operation(indata, nsr)
1185 elif operation == "instantiate":
1186 self._check_instantiate_ns_operation(indata, nsr, session)
1187
1188 def _check_action_ns_operation(self, indata, nsr):
1189 nsd = nsr["nsd"]
1190 # check vnf_member_index
1191 if indata.get("vnf_member_index"):
1192 indata["member_vnf_index"] = indata.pop(
1193 "vnf_member_index"
1194 ) # for backward compatibility
1195 if indata.get("member_vnf_index"):
1196 vnfd = self._get_vnfd_from_vnf_member_index(
1197 indata["member_vnf_index"], nsr["_id"]
1198 )
1199 try:
1200 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1201 "operate-vnf-op-config"
1202 ]["day1-2"]
1203 except Exception:
1204 configs = []
1205
1206 if indata.get("vdu_id"):
1207 self._check_valid_vdu(vnfd, indata["vdu_id"])
1208 descriptor_configuration = utils.find_in_list(
1209 configs, lambda config: config["id"] == indata["vdu_id"]
1210 )
1211 elif indata.get("kdu_name"):
1212 self._check_valid_kdu(vnfd, indata["kdu_name"])
1213 descriptor_configuration = utils.find_in_list(
1214 configs, lambda config: config["id"] == indata.get("kdu_name")
1215 )
1216 else:
1217 descriptor_configuration = utils.find_in_list(
1218 configs, lambda config: config["id"] == vnfd["id"]
1219 )
1220 if descriptor_configuration is not None:
1221 descriptor_configuration = descriptor_configuration.get(
1222 "config-primitive"
1223 )
1224 else: # use a NSD
1225 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1226 "config-primitive"
1227 )
1228
1229 # For k8s allows default primitives without validating the parameters
1230 if indata.get("kdu_name") and indata["primitive"] in (
1231 "upgrade",
1232 "rollback",
1233 "status",
1234 "inspect",
1235 "readme",
1236 ):
1237 # TODO should be checked that rollback only can contains revsision_numbe????
1238 if not indata.get("member_vnf_index"):
1239 raise EngineException(
1240 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1241 indata["primitive"]
1242 )
1243 )
1244 return
1245 # if not, check primitive
1246 for config_primitive in get_iterable(descriptor_configuration):
1247 if indata["primitive"] == config_primitive["name"]:
1248 # check needed primitive_params are provided
1249 if indata.get("primitive_params"):
1250 in_primitive_params_copy = copy(indata["primitive_params"])
1251 else:
1252 in_primitive_params_copy = {}
1253 for paramd in get_iterable(config_primitive.get("parameter")):
1254 if paramd["name"] in in_primitive_params_copy:
1255 del in_primitive_params_copy[paramd["name"]]
1256 elif not paramd.get("default-value"):
1257 raise EngineException(
1258 "Needed parameter {} not provided for primitive '{}'".format(
1259 paramd["name"], indata["primitive"]
1260 )
1261 )
1262 # check no extra primitive params are provided
1263 if in_primitive_params_copy:
1264 raise EngineException(
1265 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1266 list(in_primitive_params_copy.keys()), indata["primitive"]
1267 )
1268 )
1269 break
1270 else:
1271 raise EngineException(
1272 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1273 indata["primitive"]
1274 )
1275 )
1276
1277 def _check_update_ns_operation(self, indata, nsr) -> None:
1278 """Validates the ns-update request according to updateType
1279
1280 If updateType is CHANGE_VNFPKG:
1281 - it checks the vnfInstanceId, whether it's available under ns instance
1282 - it checks the vnfdId whether it matches with the vnfd-id in the vnf-record of specified VNF.
1283 Otherwise exception will be raised.
1284 If updateType is REMOVE_VNF:
1285 - it checks if the vnfInstanceId is available in the ns instance
1286 - Otherwise exception will be raised.
1287
1288 Args:
1289 indata: includes updateType such as CHANGE_VNFPKG,
1290 nsr: network service record
1291
1292 Raises:
1293 EngineException:
1294 a meaningful error if given update parameters are not proper such as
1295 "Error in validating ns-update request: <ID> does not match
1296 with the vnfd-id of vnfinstance
1297 http_code=HTTPStatus.UNPROCESSABLE_ENTITY"
1298
1299 """
1300 try:
1301 if indata["updateType"] == "CHANGE_VNFPKG":
1302 # vnfInstanceId, nsInstanceId, vnfdId are mandatory
1303 vnf_instance_id = indata["changeVnfPackageData"]["vnfInstanceId"]
1304 ns_instance_id = indata["nsInstanceId"]
1305 vnfd_id_2update = indata["changeVnfPackageData"]["vnfdId"]
1306
1307 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1308
1309 raise EngineException(
1310 f"Error in validating ns-update request: vnf {vnf_instance_id} does not "
1311 f"belong to NS {ns_instance_id}",
1312 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1313 )
1314
1315 # Getting vnfrs through the ns_instance_id
1316 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": ns_instance_id})
1317 constituent_vnfd_id = next(
1318 (
1319 vnfr["vnfd-id"]
1320 for vnfr in vnfrs
1321 if vnfr["id"] == vnf_instance_id
1322 ),
1323 None,
1324 )
1325
1326 # Check the given vnfd-id belongs to given vnf instance
1327 if constituent_vnfd_id and (vnfd_id_2update != constituent_vnfd_id):
1328
1329 raise EngineException(
1330 f"Error in validating ns-update request: vnfd-id {vnfd_id_2update} does not "
1331 f"match with the vnfd-id: {constituent_vnfd_id} of VNF instance: {vnf_instance_id}",
1332 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1333 )
1334
1335 # Validating the ns update timeout
1336 if (
1337 indata.get("timeout_ns_update")
1338 and indata["timeout_ns_update"] < 300
1339 ):
1340 raise EngineException(
1341 "Error in validating ns-update request: {} second is not enough "
1342 "to upgrade the VNF instance: {}".format(
1343 indata["timeout_ns_update"], vnf_instance_id
1344 ),
1345 http_code=HTTPStatus.UNPROCESSABLE_ENTITY,
1346 )
1347 elif indata["updateType"] == "REMOVE_VNF":
1348 vnf_instance_id = indata["removeVnfInstanceId"]
1349 ns_instance_id = indata["nsInstanceId"]
1350 if vnf_instance_id not in nsr["constituent-vnfr-ref"]:
1351 raise EngineException(
1352 "Invalid VNF Instance Id. '{}' is not "
1353 "present in the NS '{}'".format(vnf_instance_id, ns_instance_id)
1354 )
1355
1356 except (
1357 DbException,
1358 AttributeError,
1359 IndexError,
1360 KeyError,
1361 ValueError,
1362 ) as e:
1363 raise type(e)(
1364 "Ns update request could not be processed with error: {}.".format(e)
1365 )
1366
1367 def _check_scale_ns_operation(self, indata, nsr):
1368 vnfd = self._get_vnfd_from_vnf_member_index(
1369 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1370 )
1371 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
1372 if (
1373 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1374 == scaling_aspect["id"]
1375 ):
1376 break
1377 else:
1378 raise EngineException(
1379 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1380 "present at vnfd:scaling-aspect".format(
1381 indata["scaleVnfData"]["scaleByStepData"][
1382 "scaling-group-descriptor"
1383 ]
1384 )
1385 )
1386
1387 def _check_instantiate_ns_operation(self, indata, nsr, session):
1388 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
1389 vim_accounts = []
1390 wim_accounts = []
1391 nsd = nsr["nsd"]
1392 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1393 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1394 for in_vnf in get_iterable(indata.get("vnf")):
1395 member_vnf_index = in_vnf["member-vnf-index"]
1396 if vnf_member_index_to_vnfd.get(member_vnf_index):
1397 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
1398 else:
1399 vnfd = self._get_vnfd_from_vnf_member_index(
1400 member_vnf_index, nsr["_id"]
1401 )
1402 vnf_member_index_to_vnfd[
1403 member_vnf_index
1404 ] = vnfd # add to cache, avoiding a later look for
1405 self._check_vnf_instantiation_params(in_vnf, vnfd)
1406 if in_vnf.get("vimAccountId"):
1407 self._check_valid_vim_account(
1408 in_vnf["vimAccountId"], vim_accounts, session
1409 )
1410
1411 for in_vld in get_iterable(indata.get("vld")):
1412 self._check_valid_wim_account(
1413 in_vld.get("wimAccountId"), wim_accounts, session
1414 )
1415 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1416 if in_vld["name"] == vldd["id"]:
1417 break
1418 else:
1419 raise EngineException(
1420 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1421 in_vld["name"]
1422 )
1423 )
1424
1425 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1426 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1427 vnfr = self.db.get_one(
1428 "vnfrs",
1429 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1430 fail_on_empty=False,
1431 )
1432 if not vnfr:
1433 raise EngineException(
1434 "Invalid parameter member_vnf_index='{}' is not one of the "
1435 "nsd:constituent-vnfd".format(member_vnf_index)
1436 )
1437
1438 ## Backwards compatibility: if there is no revision, get it from the one and only VNFD entry
1439 if "revision" in vnfr:
1440 vnfd_revision = vnfr["vnfd-id"] + ":" + str(vnfr["revision"])
1441 vnfd = self.db.get_one("vnfds_revisions", {"_id": vnfd_revision}, fail_on_empty=False)
1442 else:
1443 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
1444
1445 if not vnfd:
1446 raise EngineException(
1447 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1448 vnfr["vnfd-id"]
1449 )
1450 )
1451 return vnfd
1452
1453 def _check_valid_vdu(self, vnfd, vdu_id):
1454 for vdud in get_iterable(vnfd.get("vdu")):
1455 if vdud["id"] == vdu_id:
1456 return vdud
1457 else:
1458 raise EngineException(
1459 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1460 vdu_id
1461 )
1462 )
1463
1464 def _check_valid_kdu(self, vnfd, kdu_name):
1465 for kdud in get_iterable(vnfd.get("kdu")):
1466 if kdud["name"] == kdu_name:
1467 return kdud
1468 else:
1469 raise EngineException(
1470 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1471 kdu_name
1472 )
1473 )
1474
1475 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1476 for in_vdu in get_iterable(in_vnf.get("vdu")):
1477 for vdu in get_iterable(vnfd.get("vdu")):
1478 if in_vdu["id"] == vdu["id"]:
1479 for volume in get_iterable(in_vdu.get("volume")):
1480 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
1481 if volumed["id"] == volume["name"]:
1482 break
1483 else:
1484 raise EngineException(
1485 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1486 "volume:name='{}' is not present at "
1487 "vnfd:vdu:virtual-storage-desc list".format(
1488 in_vnf["member-vnf-index"],
1489 in_vdu["id"],
1490 volume["id"],
1491 )
1492 )
1493
1494 vdu_if_names = set()
1495 for cpd in get_iterable(vdu.get("int-cpd")):
1496 for iface in get_iterable(
1497 cpd.get("virtual-network-interface-requirement")
1498 ):
1499 vdu_if_names.add(iface.get("name"))
1500
1501 for in_iface in get_iterable(in_vdu["interface"]):
1502 if in_iface["name"] in vdu_if_names:
1503 break
1504 else:
1505 raise EngineException(
1506 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1507 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1508 in_vnf["member-vnf-index"],
1509 in_vdu["id"],
1510 in_iface["name"],
1511 )
1512 )
1513 break
1514
1515 else:
1516 raise EngineException(
1517 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1518 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1519 )
1520
1521 vnfd_ivlds_cpds = {
1522 ivld.get("id"): set()
1523 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1524 }
1525 for vdu in get_iterable(vnfd.get("vdu")):
1526 for cpd in get_iterable(vnfd.get("int-cpd")):
1527 if cpd.get("int-virtual-link-desc"):
1528 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1529
1530 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1531 if in_ivld.get("name") in vnfd_ivlds_cpds:
1532 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1533 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
1534 break
1535 else:
1536 raise EngineException(
1537 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1538 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1539 "vnfd:internal-vld:name/id:internal-connection-point".format(
1540 in_vnf["member-vnf-index"],
1541 in_ivld["name"],
1542 in_icp["id-ref"],
1543 )
1544 )
1545 else:
1546 raise EngineException(
1547 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1548 " is not present at vnfd '{}'".format(
1549 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1550 )
1551 )
1552
1553 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1554 if vim_account in vim_accounts:
1555 return
1556 try:
1557 db_filter = self._get_project_filter(session)
1558 db_filter["_id"] = vim_account
1559 self.db.get_one("vim_accounts", db_filter)
1560 except Exception:
1561 raise EngineException(
1562 "Invalid vimAccountId='{}' not present for the project".format(
1563 vim_account
1564 )
1565 )
1566 vim_accounts.append(vim_account)
1567
1568 def _get_vim_account(self, vim_id: str, session):
1569 try:
1570 db_filter = self._get_project_filter(session)
1571 db_filter["_id"] = vim_id
1572 return self.db.get_one("vim_accounts", db_filter)
1573 except Exception:
1574 raise EngineException(
1575 "Invalid vimAccountId='{}' not present for the project".format(
1576 vim_id
1577 )
1578 )
1579
1580 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1581 if not isinstance(wim_account, str):
1582 return
1583 if wim_account in wim_accounts:
1584 return
1585 try:
1586 db_filter = self._get_project_filter(session, write=False, show_all=True)
1587 db_filter["_id"] = wim_account
1588 self.db.get_one("wim_accounts", db_filter)
1589 except Exception:
1590 raise EngineException(
1591 "Invalid wimAccountId='{}' not present for the project".format(
1592 wim_account
1593 )
1594 )
1595 wim_accounts.append(wim_account)
1596
1597 def _look_for_pdu(
1598 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1599 ):
1600 """
1601 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1602 (ip_address, ...) information.
1603 Modifies PDU _admin.usageState to 'IN_USE'
1604 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1605 :param rollback: list with the database modifications to rollback if needed
1606 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1607 :param vim_account: vim_account where this vnfr should be deployed
1608 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1609 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1610 of the changed vnfr is needed
1611
1612 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1613 "vim-network-name": used at VIM
1614 "name": interface name
1615 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1616 "ns-vld-id": NSD vld where this interface is connected.
1617 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1618 """
1619
1620 ifaces_forcing_vim_network = []
1621 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1622 if not vdur.get("pdu-type"):
1623 continue
1624 pdu_type = vdur.get("pdu-type")
1625 pdu_filter = self._get_project_filter(session)
1626 pdu_filter["vim_accounts"] = vim_account
1627 pdu_filter["type"] = pdu_type
1628 pdu_filter["_admin.operationalState"] = "ENABLED"
1629 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
1630 # TODO feature 1417: "shared": True,
1631
1632 available_pdus = self.db.get_list("pdus", pdu_filter)
1633 for pdu in available_pdus:
1634 # step 1 check if this pdu contains needed interfaces:
1635 match_interfaces = True
1636 for vdur_interface in vdur["interfaces"]:
1637 for pdu_interface in pdu["interfaces"]:
1638 if pdu_interface["name"] == vdur_interface["name"]:
1639 # TODO feature 1417: match per mgmt type
1640 break
1641 else: # no interface found for name
1642 match_interfaces = False
1643 break
1644 if match_interfaces:
1645 break
1646 else:
1647 raise EngineException(
1648 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1649 "names".format(
1650 pdu_type,
1651 vim_account,
1652 vnfr["member-vnf-index-ref"],
1653 vdur["vdu-id-ref"],
1654 )
1655 )
1656
1657 # step 2. Update pdu
1658 rollback_pdu = {
1659 "_admin.usageState": pdu["_admin"]["usageState"],
1660 "_admin.usage.vnfr_id": None,
1661 "_admin.usage.nsr_id": None,
1662 "_admin.usage.vdur": None,
1663 }
1664 self.db.set_one(
1665 "pdus",
1666 {"_id": pdu["_id"]},
1667 {
1668 "_admin.usageState": "IN_USE",
1669 "_admin.usage": {
1670 "vnfr_id": vnfr["_id"],
1671 "nsr_id": vnfr["nsr-id-ref"],
1672 "vdur": vdur["vdu-id-ref"],
1673 },
1674 },
1675 )
1676 rollback.append(
1677 {
1678 "topic": "pdus",
1679 "_id": pdu["_id"],
1680 "operation": "set",
1681 "content": rollback_pdu,
1682 }
1683 )
1684
1685 # step 3. Fill vnfr info by filling vdur
1686 vdu_text = "vdur.{}".format(vdur_index)
1687 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
1688 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1689 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1690 for pdu_interface in pdu["interfaces"]:
1691 if pdu_interface["name"] == vdur_interface["name"]:
1692 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1693 for k, v in pdu_interface.items():
1694 if k in (
1695 "ip-address",
1696 "mac-address",
1697 ): # TODO: switch-xxxxx must be inserted
1698 vnfr_update[iface_text + ".{}".format(k)] = v
1699 vnfr_update_rollback[
1700 iface_text + ".{}".format(k)
1701 ] = vdur_interface.get(v)
1702 if pdu_interface.get("ip-address"):
1703 if vdur_interface.get(
1704 "mgmt-interface"
1705 ) or vdur_interface.get("mgmt-vnf"):
1706 vnfr_update_rollback[
1707 vdu_text + ".ip-address"
1708 ] = vdur.get("ip-address")
1709 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1710 "ip-address"
1711 ]
1712 if vdur_interface.get("mgmt-vnf"):
1713 vnfr_update_rollback["ip-address"] = vnfr.get(
1714 "ip-address"
1715 )
1716 vnfr_update["ip-address"] = pdu_interface["ip-address"]
1717 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1718 "ip-address"
1719 ]
1720 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1721 "vim-network-id"
1722 ):
1723 ifaces_forcing_vim_network.append(
1724 {
1725 "name": vdur_interface.get("vnf-vld-id")
1726 or vdur_interface.get("ns-vld-id"),
1727 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1728 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1729 }
1730 )
1731 if pdu_interface.get("vim-network-id"):
1732 ifaces_forcing_vim_network[-1][
1733 "vim-network-id"
1734 ] = pdu_interface["vim-network-id"]
1735 if pdu_interface.get("vim-network-name"):
1736 ifaces_forcing_vim_network[-1][
1737 "vim-network-name"
1738 ] = pdu_interface["vim-network-name"]
1739 break
1740
1741 return ifaces_forcing_vim_network
1742
1743 def _look_for_k8scluster(
1744 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1745 ):
1746 """
1747 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1748 Fills vnfr.kdur with the selected k8scluster
1749
1750 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1751 :param rollback: list with the database modifications to rollback if needed
1752 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1753 :param vim_account: vim_account where this vnfr should be deployed
1754 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1755 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1756 of the changed vnfr is needed
1757
1758 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1759 "vim-network-name": used at VIM
1760 "name": interface name
1761 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1762 "ns-vld-id": NSD vld where this interface is connected.
1763 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1764 """
1765
1766 ifaces_forcing_vim_network = []
1767 if not vnfr.get("kdur"):
1768 return ifaces_forcing_vim_network
1769
1770 kdu_filter = self._get_project_filter(session)
1771 kdu_filter["vim_account"] = vim_account
1772 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1773 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1774
1775 k8s_requirements = {} # just for logging
1776 for k8scluster in available_k8sclusters:
1777 if not vnfr.get("k8s-cluster"):
1778 break
1779 # restrict by cni
1780 if vnfr["k8s-cluster"].get("cni"):
1781 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
1782 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1783 k8scluster.get("cni", ())
1784 ):
1785 continue
1786 # restrict by version
1787 if vnfr["k8s-cluster"].get("version"):
1788 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1789 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1790 continue
1791 # restrict by number of networks
1792 if vnfr["k8s-cluster"].get("nets"):
1793 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
1794 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1795 vnfr["k8s-cluster"]["nets"]
1796 ):
1797 continue
1798 break
1799 else:
1800 raise EngineException(
1801 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1802 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1803 )
1804 )
1805
1806 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
1807 # step 3. Fill vnfr info by filling kdur
1808 kdu_text = "kdur.{}.".format(kdur_index)
1809 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1810 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1811
1812 # step 4. Check VIM networks that forces the selected k8s_cluster
1813 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1814 k8scluster_net_list = list(k8scluster.get("nets").keys())
1815 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1816 # get a network from k8s_cluster nets. If name matches use this, if not use other
1817 if kdur_net["id"] in k8scluster_net_list: # name matches
1818 vim_net = k8scluster["nets"][kdur_net["id"]]
1819 k8scluster_net_list.remove(kdur_net["id"])
1820 else:
1821 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1822 k8scluster_net_list.pop(0)
1823 vnfr_update_rollback[
1824 "k8s-cluster.nets.{}.vim_net".format(net_index)
1825 ] = None
1826 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
1827 if vim_net and (
1828 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1829 ):
1830 ifaces_forcing_vim_network.append(
1831 {
1832 "name": kdur_net.get("vnf-vld-id")
1833 or kdur_net.get("ns-vld-id"),
1834 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1835 "ns-vld-id": kdur_net.get("ns-vld-id"),
1836 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1837 }
1838 )
1839 # TODO check that this forcing is not incompatible with other forcing
1840 return ifaces_forcing_vim_network
1841
1842 def _update_vnfrs_from_nsd(self, nsr):
1843 try:
1844 nsr_id = nsr["_id"]
1845 nsd = nsr["nsd"]
1846
1847 step = "Getting vnf_profiles from nsd"
1848 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1849 vld_fixed_ip_connection_point_data = {}
1850
1851 step = "Getting ip-address info from vnf_profile if it exists"
1852 for vnfp in vnf_profiles:
1853 # Checking ip-address info from nsd.vnf_profile and storing
1854 for vlc in vnfp.get("virtual-link-connectivity", ()):
1855 for cpd in vlc.get("constituent-cpd-id", ()):
1856 if cpd.get("ip-address"):
1857 step = "Storing ip-address info"
1858 vld_fixed_ip_connection_point_data.update({vlc.get("virtual-link-profile-id") + '.' + cpd.get("constituent-base-element-id"): {
1859 "vnfd-connection-point-ref": cpd.get(
1860 "constituent-cpd-id"),
1861 "ip-address": cpd.get(
1862 "ip-address")}})
1863
1864 # Inserting ip address to vnfr
1865 if len(vld_fixed_ip_connection_point_data) > 0:
1866 step = "Getting vnfrs"
1867 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1868 for item in vld_fixed_ip_connection_point_data.keys():
1869 step = "Filtering vnfrs"
1870 vnfr = next(filter(lambda vnfr: vnfr["member-vnf-index-ref"] == item.split('.')[1], vnfrs), None)
1871 if vnfr:
1872 vnfr_update = {}
1873 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1874 for iface_index, iface in enumerate(vdur["interfaces"]):
1875 step = "Looking for matched interface"
1876 if (
1877 iface.get("external-connection-point-ref")
1878 == vld_fixed_ip_connection_point_data[item].get("vnfd-connection-point-ref") and
1879 iface.get("ns-vld-id") == item.split('.')[0]
1880
1881 ):
1882 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1883 vdur_index, iface_index
1884 )
1885 step = "Storing info in order to update vnfr"
1886 vnfr_update[
1887 vnfr_update_text + ".ip-address"
1888 ] = increment_ip_mac(
1889 vld_fixed_ip_connection_point_data[item].get("ip-address"),
1890 vdur.get("count-index", 0), )
1891 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1892
1893 step = "updating vnfr at database"
1894 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1895 except (
1896 ValidationError,
1897 EngineException,
1898 DbException,
1899 MsgException,
1900 FsException,
1901 ) as e:
1902 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1903
1904 def _update_vnfrs(self, session, rollback, nsr, indata):
1905 # get vnfr
1906 nsr_id = nsr["_id"]
1907 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1908
1909 for vnfr in vnfrs:
1910 vnfr_update = {}
1911 vnfr_update_rollback = {}
1912 member_vnf_index = vnfr["member-vnf-index-ref"]
1913 # update vim-account-id
1914
1915 vim_account = indata["vimAccountId"]
1916 vca_id = self._get_vim_account(vim_account, session).get("vca")
1917 # check instantiate parameters
1918 for vnf_inst_params in get_iterable(indata.get("vnf")):
1919 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1920 continue
1921 if vnf_inst_params.get("vimAccountId"):
1922 vim_account = vnf_inst_params.get("vimAccountId")
1923 vca_id = self._get_vim_account(vim_account, session).get("vca")
1924
1925 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1926 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1927 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1928 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1929 continue
1930 for iface_inst_param in get_iterable(
1931 vdu_inst_param.get("interface")
1932 ):
1933 iface_index, _ = next(
1934 i
1935 for i in enumerate(vdur["interfaces"])
1936 if i[1]["name"] == iface_inst_param["name"]
1937 )
1938 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1939 vdur_index, iface_index
1940 )
1941 if iface_inst_param.get("ip-address"):
1942 vnfr_update[
1943 vnfr_update_text + ".ip-address"
1944 ] = increment_ip_mac(
1945 iface_inst_param.get("ip-address"),
1946 vdur.get("count-index", 0),
1947 )
1948 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1949 if iface_inst_param.get("mac-address"):
1950 vnfr_update[
1951 vnfr_update_text + ".mac-address"
1952 ] = increment_ip_mac(
1953 iface_inst_param.get("mac-address"),
1954 vdur.get("count-index", 0),
1955 )
1956 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
1957 if iface_inst_param.get("floating-ip-required"):
1958 vnfr_update[
1959 vnfr_update_text + ".floating-ip-required"
1960 ] = True
1961 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1962 # TODO update vld with the ip-profile
1963 for ivld_inst_param in get_iterable(
1964 vnf_inst_params.get("internal-vld")
1965 ):
1966 for icp_inst_param in get_iterable(
1967 ivld_inst_param.get("internal-connection-point")
1968 ):
1969 # look for iface
1970 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1971 for iface_index, iface in enumerate(vdur["interfaces"]):
1972 if (
1973 iface.get("internal-connection-point-ref")
1974 == icp_inst_param["id-ref"]
1975 ):
1976 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1977 vdur_index, iface_index
1978 )
1979 if icp_inst_param.get("ip-address"):
1980 vnfr_update[
1981 vnfr_update_text + ".ip-address"
1982 ] = increment_ip_mac(
1983 icp_inst_param.get("ip-address"),
1984 vdur.get("count-index", 0),
1985 )
1986 vnfr_update[
1987 vnfr_update_text + ".fixed-ip"
1988 ] = True
1989 if icp_inst_param.get("mac-address"):
1990 vnfr_update[
1991 vnfr_update_text + ".mac-address"
1992 ] = increment_ip_mac(
1993 icp_inst_param.get("mac-address"),
1994 vdur.get("count-index", 0),
1995 )
1996 vnfr_update[
1997 vnfr_update_text + ".fixed-mac"
1998 ] = True
1999 break
2000 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
2001 for vld_inst_param in get_iterable(indata.get("vld")):
2002 for vnfcp_inst_param in get_iterable(
2003 vld_inst_param.get("vnfd-connection-point-ref")
2004 ):
2005 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
2006 continue
2007 # look for iface
2008 for vdur_index, vdur in enumerate(vnfr["vdur"]):
2009 for iface_index, iface in enumerate(vdur["interfaces"]):
2010 if (
2011 iface.get("external-connection-point-ref")
2012 == vnfcp_inst_param["vnfd-connection-point-ref"]
2013 ):
2014 vnfr_update_text = "vdur.{}.interfaces.{}".format(
2015 vdur_index, iface_index
2016 )
2017 if vnfcp_inst_param.get("ip-address"):
2018 vnfr_update[
2019 vnfr_update_text + ".ip-address"
2020 ] = increment_ip_mac(
2021 vnfcp_inst_param.get("ip-address"),
2022 vdur.get("count-index", 0),
2023 )
2024 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
2025 if vnfcp_inst_param.get("mac-address"):
2026 vnfr_update[
2027 vnfr_update_text + ".mac-address"
2028 ] = increment_ip_mac(
2029 vnfcp_inst_param.get("mac-address"),
2030 vdur.get("count-index", 0),
2031 )
2032 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
2033 break
2034
2035 vnfr_update["vim-account-id"] = vim_account
2036 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
2037
2038 if vca_id:
2039 vnfr_update["vca-id"] = vca_id
2040 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
2041
2042 # get pdu
2043 ifaces_forcing_vim_network = self._look_for_pdu(
2044 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2045 )
2046
2047 # get kdus
2048 ifaces_forcing_vim_network += self._look_for_k8scluster(
2049 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
2050 )
2051 # update database vnfr
2052 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
2053 rollback.append(
2054 {
2055 "topic": "vnfrs",
2056 "_id": vnfr["_id"],
2057 "operation": "set",
2058 "content": vnfr_update_rollback,
2059 }
2060 )
2061
2062 # Update indada in case pdu forces to use a concrete vim-network-name
2063 # TODO check if user has already insert a vim-network-name and raises an error
2064 if not ifaces_forcing_vim_network:
2065 continue
2066 for iface_info in ifaces_forcing_vim_network:
2067 if iface_info.get("ns-vld-id"):
2068 if "vld" not in indata:
2069 indata["vld"] = []
2070 indata["vld"].append(
2071 {
2072 key: iface_info[key]
2073 for key in ("name", "vim-network-name", "vim-network-id")
2074 if iface_info.get(key)
2075 }
2076 )
2077
2078 elif iface_info.get("vnf-vld-id"):
2079 if "vnf" not in indata:
2080 indata["vnf"] = []
2081 indata["vnf"].append(
2082 {
2083 "member-vnf-index": member_vnf_index,
2084 "internal-vld": [
2085 {
2086 key: iface_info[key]
2087 for key in (
2088 "name",
2089 "vim-network-name",
2090 "vim-network-id",
2091 )
2092 if iface_info.get(key)
2093 }
2094 ],
2095 }
2096 )
2097
2098 @staticmethod
2099 def _create_nslcmop(nsr_id, operation, params):
2100 """
2101 Creates a ns-lcm-opp content to be stored at database.
2102 :param nsr_id: internal id of the instance
2103 :param operation: instantiate, terminate, scale, action, update ...
2104 :param params: user parameters for the operation
2105 :return: dictionary following SOL005 format
2106 """
2107 now = time()
2108 _id = str(uuid4())
2109 nslcmop = {
2110 "id": _id,
2111 "_id": _id,
2112 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2113 "queuePosition": None,
2114 "stage": None,
2115 "errorMessage": None,
2116 "detailedStatus": None,
2117 "statusEnteredTime": now,
2118 "nsInstanceId": nsr_id,
2119 "lcmOperationType": operation,
2120 "startTime": now,
2121 "isAutomaticInvocation": False,
2122 "operationParams": params,
2123 "isCancelPending": False,
2124 "links": {
2125 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
2126 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
2127 },
2128 }
2129 return nslcmop
2130
2131 def _get_enabled_vims(self, session):
2132 """
2133 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
2134 :param session: current session with user information
2135 """
2136 db_filter = self._get_project_filter(session)
2137 db_filter["_admin.operationalState"] = "ENABLED"
2138 vims = self.db.get_list("vim_accounts", db_filter)
2139 vimAccounts = []
2140 for vim in vims:
2141 vimAccounts.append(vim["_id"])
2142 return vimAccounts
2143
2144 def new(
2145 self,
2146 rollback,
2147 session,
2148 indata=None,
2149 kwargs=None,
2150 headers=None,
2151 slice_object=False,
2152 ):
2153 """
2154 Performs a new operation over a ns
2155 :param rollback: list to append created items at database in case a rollback must to be done
2156 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2157 :param indata: descriptor with the parameters of the operation. It must contains among others
2158 nsInstanceId: _id of the nsr to perform the operation
2159 operation: it can be: instantiate, terminate, action, update TODO: heal
2160 :param kwargs: used to override the indata descriptor
2161 :param headers: http request headers
2162 :return: id of the nslcmops
2163 """
2164
2165 def check_if_nsr_is_not_slice_member(session, nsr_id):
2166 nsis = None
2167 db_filter = self._get_project_filter(session)
2168 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2169 nsis = self.db.get_one(
2170 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2171 )
2172 if nsis:
2173 raise EngineException(
2174 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2175 nsr_id, nsis["_id"]
2176 ),
2177 http_code=HTTPStatus.CONFLICT,
2178 )
2179
2180 try:
2181 # Override descriptor with query string kwargs
2182 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
2183 operation = indata["lcmOperationType"]
2184 nsInstanceId = indata["nsInstanceId"]
2185
2186 validate_input(indata, self.operation_schema[operation])
2187 # get ns from nsr_id
2188 _filter = BaseTopic._get_project_filter(session)
2189 _filter["_id"] = nsInstanceId
2190 nsr = self.db.get_one("nsrs", _filter)
2191
2192 # initial checking
2193 if operation == "terminate" and slice_object is False:
2194 check_if_nsr_is_not_slice_member(session, nsr["_id"])
2195 if (
2196 not nsr["_admin"].get("nsState")
2197 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2198 ):
2199 if operation == "terminate" and indata.get("autoremove"):
2200 # NSR must be deleted
2201 return (
2202 None,
2203 None,
2204 ) # a none in this case is used to indicate not instantiated. It can be removed
2205 if operation != "instantiate":
2206 raise EngineException(
2207 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2208 nsInstanceId, operation
2209 ),
2210 HTTPStatus.CONFLICT,
2211 )
2212 else:
2213 if operation == "instantiate" and not session["force"]:
2214 raise EngineException(
2215 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2216 nsInstanceId, operation
2217 ),
2218 HTTPStatus.CONFLICT,
2219 )
2220 self._check_ns_operation(session, nsr, operation, indata)
2221 if (indata.get("primitive_params")):
2222 indata["primitive_params"] = json.dumps(indata["primitive_params"])
2223 elif (indata.get("additionalParamsForVnf")):
2224 indata["additionalParamsForVnf"] = json.dumps(indata["additionalParamsForVnf"])
2225
2226 if operation == "instantiate":
2227 self._update_vnfrs_from_nsd(nsr)
2228 self._update_vnfrs(session, rollback, nsr, indata)
2229 if (operation == "update") and (indata["updateType"] == "CHANGE_VNFPKG"):
2230 nsr_update = {}
2231 vnfd_id = indata["changeVnfPackageData"]["vnfdId"]
2232 vnfd = self.db.get_one("vnfds", {"_id": vnfd_id})
2233 nsd = self.db.get_one("nsds", {"_id": nsr["nsd-id"]})
2234 ns_request = nsr["instantiate_params"]
2235 vnfr = self.db.get_one("vnfrs", {"_id": indata["changeVnfPackageData"]["vnfInstanceId"]})
2236 latest_vnfd_revision = vnfd["_admin"].get("revision")
2237 vnfr_vnfd_revision = vnfr.get("revision")
2238 old_vnfd_id = vnfd_id + ":" + str(vnfr_vnfd_revision)
2239 old_db_vnfd = self.db.get_one("vnfds_revisions", {"_id": old_vnfd_id})
2240 old_sw_version = old_db_vnfd["software-version"]
2241 new_sw_version = vnfd["software-version"]
2242 if new_sw_version != old_sw_version:
2243 vnf_index = vnfr["member-vnf-index-ref"]
2244 self.logger.info("nsr {}".format(nsr))
2245 for vdu in vnfd["vdu"]:
2246 self.nsrtopic._add_flavor_to_nsr(vdu, vnfd, nsr)
2247 sw_image_id = vdu.get("sw-image-desc")
2248 if sw_image_id:
2249 image_data = self.nsrtopic._get_image_data_from_vnfd(vnfd, sw_image_id)
2250 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2251 for alt_image in vdu.get("alternative-sw-image-desc", ()):
2252 image_data = self.nsrtopic._get_image_data_from_vnfd(vnfd, alt_image)
2253 self.nsrtopic._add_image_to_nsr(nsr, image_data)
2254 nsr_update["image"] = nsr["image"]
2255 nsr_update["flavor"] = nsr["flavor"]
2256 self.db.set_one("nsrs", {"_id": nsr["_id"]}, nsr_update)
2257 ns_k8s_namespace = self.nsrtopic._get_ns_k8s_namespace(nsd, ns_request, session)
2258 vnfr_descriptor = self.nsrtopic._create_vnfr_descriptor_from_vnfd(
2259 nsd,
2260 vnfd,
2261 vnfd_id,
2262 vnf_index,
2263 nsr,
2264 ns_request,
2265 ns_k8s_namespace,
2266 )
2267 indata["newVdur"] = vnfr_descriptor["vdur"]
2268 # self.logger.info("vnfr_descriptor {}".format(vnfr_descriptor))
2269 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
2270 _id = nslcmop_desc["_id"]
2271 self.format_on_new(
2272 nslcmop_desc, session["project_id"], make_public=session["public"]
2273 )
2274 if indata.get("placement-engine"):
2275 # Save valid vim accounts in lcm operation descriptor
2276 nslcmop_desc["operationParams"][
2277 "validVimAccounts"
2278 ] = self._get_enabled_vims(session)
2279 self.db.create("nslcmops", nslcmop_desc)
2280 rollback.append({"topic": "nslcmops", "_id": _id})
2281 if not slice_object:
2282 self.msg.write("ns", operation, nslcmop_desc)
2283 return _id, None
2284 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
2285 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2286 # except DbException as e:
2287 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2288
2289 def delete(self, session, _id, dry_run=False, not_send_msg=None):
2290 raise EngineException(
2291 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2292 )
2293
2294 def edit(self, session, _id, indata=None, kwargs=None, content=None):
2295 raise EngineException(
2296 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2297 )
2298
2299
2300 class NsiTopic(BaseTopic):
2301 topic = "nsis"
2302 topic_msg = "nsi"
2303 quota_name = "slice_instances"
2304
2305 def __init__(self, db, fs, msg, auth):
2306 BaseTopic.__init__(self, db, fs, msg, auth)
2307 self.nsrTopic = NsrTopic(db, fs, msg, auth)
2308
2309 @staticmethod
2310 def _format_ns_request(ns_request):
2311 formated_request = copy(ns_request)
2312 # TODO: Add request params
2313 return formated_request
2314
2315 @staticmethod
2316 def _format_addional_params(slice_request):
2317 """
2318 Get and format user additional params for NS or VNF
2319 :param slice_request: User instantiation additional parameters
2320 :return: a formatted copy of additional params or None if not supplied
2321 """
2322 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2323 if additional_params:
2324 for k, v in additional_params.items():
2325 if not isinstance(k, str):
2326 raise EngineException(
2327 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2328 k
2329 )
2330 )
2331 if "." in k or "$" in k:
2332 raise EngineException(
2333 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2334 k
2335 )
2336 )
2337 if isinstance(v, (dict, tuple, list)):
2338 additional_params[k] = "!!yaml " + safe_dump(v)
2339 return additional_params
2340
2341 def _check_descriptor_dependencies(self, session, descriptor):
2342 """
2343 Check that the dependent descriptors exist on a new descriptor or edition
2344 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2345 :param descriptor: descriptor to be inserted or edit
2346 :return: None or raises exception
2347 """
2348 if not descriptor.get("nst-ref"):
2349 return
2350 nstd_id = descriptor["nst-ref"]
2351 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
2352 raise EngineException(
2353 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2354 nstd_id
2355 ),
2356 http_code=HTTPStatus.CONFLICT,
2357 )
2358
2359 def check_conflict_on_del(self, session, _id, db_content):
2360 """
2361 Check that NSI is not instantiated
2362 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2363 :param _id: nsi internal id
2364 :param db_content: The database content of the _id
2365 :return: None or raises EngineException with the conflict
2366 """
2367 if session["force"]:
2368 return
2369 nsi = db_content
2370 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
2371 raise EngineException(
2372 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2373 "Launch 'terminate' operation first; or force deletion".format(_id),
2374 http_code=HTTPStatus.CONFLICT,
2375 )
2376
2377 def delete_extra(self, session, _id, db_content, not_send_msg=None):
2378 """
2379 Deletes associated nsilcmops from database. Deletes associated filesystem.
2380 Set usageState of nst
2381 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2382 :param _id: server internal id
2383 :param db_content: The database content of the descriptor
2384 :param not_send_msg: To not send message (False) or store content (list) instead
2385 :return: None if ok or raises EngineException with the problem
2386 """
2387
2388 # Deleting the nsrs belonging to nsir
2389 nsir = db_content
2390 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2391 nsr_id = nsrs_detailed_item["nsrId"]
2392 if nsrs_detailed_item.get("shared"):
2393 _filter = {
2394 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2395 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2396 "_id.ne": nsir["_id"],
2397 }
2398 nsi = self.db.get_one(
2399 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2400 )
2401 if nsi: # last one using nsr
2402 continue
2403 try:
2404 self.nsrTopic.delete(
2405 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2406 )
2407 except (DbException, EngineException) as e:
2408 if e.http_code == HTTPStatus.NOT_FOUND:
2409 pass
2410 else:
2411 raise
2412
2413 # delete related nsilcmops database entries
2414 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
2415
2416 # Check and set used NST usage state
2417 nsir_admin = nsir.get("_admin")
2418 if nsir_admin and nsir_admin.get("nst-id"):
2419 # check if used by another NSI
2420 nsis_list = self.db.get_one(
2421 "nsis",
2422 {"nst-id": nsir_admin["nst-id"]},
2423 fail_on_empty=False,
2424 fail_on_more=False,
2425 )
2426 if not nsis_list:
2427 self.db.set_one(
2428 "nsts",
2429 {"_id": nsir_admin["nst-id"]},
2430 {"_admin.usageState": "NOT_IN_USE"},
2431 )
2432
2433 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
2434 """
2435 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2436 :param rollback: list to append the created items at database in case a rollback must be done
2437 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2438 :param indata: params to be used for the nsir
2439 :param kwargs: used to override the indata descriptor
2440 :param headers: http request headers
2441 :return: the _id of nsi descriptor created at database
2442 """
2443
2444 try:
2445 step = "checking quotas"
2446 self.check_quota(session)
2447
2448 step = ""
2449 slice_request = self._remove_envelop(indata)
2450 # Override descriptor with query string kwargs
2451 self._update_input_with_kwargs(slice_request, kwargs)
2452 slice_request = self._validate_input_new(slice_request, session["force"])
2453
2454 # look for nstd
2455 step = "getting nstd id='{}' from database".format(
2456 slice_request.get("nstId")
2457 )
2458 _filter = self._get_project_filter(session)
2459 _filter["_id"] = slice_request["nstId"]
2460 nstd = self.db.get_one("nsts", _filter)
2461 # check NST is not disabled
2462 step = "checking NST operationalState"
2463 if nstd["_admin"]["operationalState"] == "DISABLED":
2464 raise EngineException(
2465 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2466 "instance".format(slice_request["nstId"]),
2467 http_code=HTTPStatus.CONFLICT,
2468 )
2469 del _filter["_id"]
2470
2471 # check NSD is not disabled
2472 step = "checking operationalState"
2473 if nstd["_admin"]["operationalState"] == "DISABLED":
2474 raise EngineException(
2475 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2476 "a network slice".format(slice_request["nstId"]),
2477 http_code=HTTPStatus.CONFLICT,
2478 )
2479
2480 nstd.pop("_admin", None)
2481 nstd_id = nstd.pop("_id", None)
2482 nsi_id = str(uuid4())
2483 step = "filling nsi_descriptor with input data"
2484
2485 # Creating the NSIR
2486 nsi_descriptor = {
2487 "id": nsi_id,
2488 "name": slice_request["nsiName"],
2489 "description": slice_request.get("nsiDescription", ""),
2490 "datacenter": slice_request["vimAccountId"],
2491 "nst-ref": nstd["id"],
2492 "instantiation_parameters": slice_request,
2493 "network-slice-template": nstd,
2494 "nsr-ref-list": [],
2495 "vlr-list": [],
2496 "_id": nsi_id,
2497 "additionalParamsForNsi": self._format_addional_params(slice_request),
2498 }
2499
2500 step = "creating nsi at database"
2501 self.format_on_new(
2502 nsi_descriptor, session["project_id"], make_public=session["public"]
2503 )
2504 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2505 nsi_descriptor["_admin"]["netslice-subnet"] = None
2506 nsi_descriptor["_admin"]["deployed"] = {}
2507 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2508 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2509
2510 # Creating netslice-vld for the RO.
2511 step = "creating netslice-vld at database"
2512
2513 # Building the vlds list to be deployed
2514 # From netslice descriptors, creating the initial list
2515 nsi_vlds = []
2516
2517 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2518 # Getting template Instantiation parameters from NST
2519 nsi_vld = deepcopy(netslice_vlds)
2520 nsi_vld["shared-nsrs-list"] = []
2521 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2522 nsi_vlds.append(nsi_vld)
2523
2524 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
2525 # Creating netslice-subnet_record.
2526 needed_nsds = {}
2527 services = []
2528
2529 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2530 for member_ns in nstd["netslice-subnet"]:
2531 nsd_id = member_ns["nsd-ref"]
2532 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
2533 member_ns["nsd-ref"], member_ns["id"]
2534 )
2535 if nsd_id not in needed_nsds:
2536 # Obtain nsd
2537 _filter["id"] = nsd_id
2538 nsd = self.db.get_one(
2539 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2540 )
2541 del _filter["id"]
2542 nsd.pop("_admin")
2543 needed_nsds[nsd_id] = nsd
2544 else:
2545 nsd = needed_nsds[nsd_id]
2546 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2547 services.append(member_ns)
2548
2549 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2550 member_ns["nsd-ref"], member_ns["id"]
2551 )
2552
2553 # creates Network Services records (NSRs)
2554 step = "creating nsrs at database using NsrTopic.new()"
2555 ns_params = slice_request.get("netslice-subnet")
2556 nsrs_list = []
2557 nsi_netslice_subnet = []
2558 for service in services:
2559 # Check if the netslice-subnet is shared and if it is share if the nss exists
2560 _id_nsr = None
2561 indata_ns = {}
2562 # Is the nss shared and instantiated?
2563 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2564 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2565 "nsd-ref"
2566 ]
2567 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
2568 nsi = self.db.get_one(
2569 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2570 )
2571 if nsi and service.get("is-shared-nss"):
2572 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2573 for nsrs_detailed_item in nsrs_detailed_list:
2574 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
2575 if nsrs_detailed_item["nss-id"] == service["id"]:
2576 _id_nsr = nsrs_detailed_item["nsrId"]
2577 break
2578 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2579 if netslice_subnet["nss-id"] == service["id"]:
2580 indata_ns = netslice_subnet
2581 break
2582 else:
2583 indata_ns = {}
2584 if service.get("instantiation-parameters"):
2585 indata_ns = deepcopy(service["instantiation-parameters"])
2586 # del service["instantiation-parameters"]
2587
2588 indata_ns["nsdId"] = service["_id"]
2589 indata_ns["nsName"] = (
2590 slice_request.get("nsiName") + "." + service["id"]
2591 )
2592 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2593 indata_ns["nsDescription"] = service["description"]
2594 if slice_request.get("ssh_keys"):
2595 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
2596
2597 if ns_params:
2598 for ns_param in ns_params:
2599 if ns_param.get("id") == service["id"]:
2600 copy_ns_param = deepcopy(ns_param)
2601 del copy_ns_param["id"]
2602 indata_ns.update(copy_ns_param)
2603 break
2604
2605 # Creates Nsr objects
2606 _id_nsr, _ = self.nsrTopic.new(
2607 rollback, session, indata_ns, kwargs, headers
2608 )
2609 nsrs_item = {
2610 "nsrId": _id_nsr,
2611 "shared": service.get("is-shared-nss"),
2612 "nsd-id": service["nsd-ref"],
2613 "nss-id": service["id"],
2614 "nslcmop_instantiate": None,
2615 }
2616 indata_ns["nss-id"] = service["id"]
2617 nsrs_list.append(nsrs_item)
2618 nsi_netslice_subnet.append(indata_ns)
2619 nsr_ref = {"nsr-ref": _id_nsr}
2620 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
2621
2622 # Adding the nsrs list to the nsi
2623 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
2624 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2625 self.db.set_one(
2626 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2627 )
2628
2629 # Creating the entry in the database
2630 self.db.create("nsis", nsi_descriptor)
2631 rollback.append({"topic": "nsis", "_id": nsi_id})
2632 return nsi_id, None
2633 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2634 self.logger.exception(
2635 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2636 )
2637 raise EngineException("Error {}: {}".format(step, e))
2638 except ValidationError as e:
2639 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2640
2641 def edit(self, session, _id, indata=None, kwargs=None, content=None):
2642 raise EngineException(
2643 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2644 )
2645
2646
2647 class NsiLcmOpTopic(BaseTopic):
2648 topic = "nsilcmops"
2649 topic_msg = "nsi"
2650 operation_schema = { # mapping between operation and jsonschema to validate
2651 "instantiate": nsi_instantiate,
2652 "terminate": None,
2653 }
2654
2655 def __init__(self, db, fs, msg, auth):
2656 BaseTopic.__init__(self, db, fs, msg, auth)
2657 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
2658
2659 def _check_nsi_operation(self, session, nsir, operation, indata):
2660 """
2661 Check that user has enter right parameters for the operation
2662 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2663 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2664 :param indata: descriptor with the parameters of the operation
2665 :return: None
2666 """
2667 nsds = {}
2668 nstd = nsir["network-slice-template"]
2669
2670 def check_valid_netslice_subnet_id(nstId):
2671 # TODO change to vnfR (??)
2672 for netslice_subnet in nstd["netslice-subnet"]:
2673 if nstId == netslice_subnet["id"]:
2674 nsd_id = netslice_subnet["nsd-ref"]
2675 if nsd_id not in nsds:
2676 _filter = self._get_project_filter(session)
2677 _filter["id"] = nsd_id
2678 nsds[nsd_id] = self.db.get_one("nsds", _filter)
2679 return nsds[nsd_id]
2680 else:
2681 raise EngineException(
2682 "Invalid parameter nstId='{}' is not one of the "
2683 "nst:netslice-subnet".format(nstId)
2684 )
2685
2686 if operation == "instantiate":
2687 # check the existance of netslice-subnet items
2688 for in_nst in get_iterable(indata.get("netslice-subnet")):
2689 check_valid_netslice_subnet_id(in_nst["id"])
2690
2691 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2692 now = time()
2693 _id = str(uuid4())
2694 nsilcmop = {
2695 "id": _id,
2696 "_id": _id,
2697 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2698 "statusEnteredTime": now,
2699 "netsliceInstanceId": netsliceInstanceId,
2700 "lcmOperationType": operation,
2701 "startTime": now,
2702 "isAutomaticInvocation": False,
2703 "operationParams": params,
2704 "isCancelPending": False,
2705 "links": {
2706 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
2707 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2708 + netsliceInstanceId,
2709 },
2710 }
2711 return nsilcmop
2712
2713 def add_shared_nsr_2vld(self, nsir, nsr_item):
2714 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2715 if nst_sb_item.get("is-shared-nss"):
2716 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2717 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2718 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
2719 for admin_vld_nss_cp_ref_item in admin_vld_item[
2720 "nss-connection-point-ref"
2721 ]:
2722 if (
2723 admin_subnet_item["nss-id"]
2724 == admin_vld_nss_cp_ref_item["nss-ref"]
2725 ):
2726 if (
2727 not nsr_item["nsrId"]
2728 in admin_vld_item["shared-nsrs-list"]
2729 ):
2730 admin_vld_item["shared-nsrs-list"].append(
2731 nsr_item["nsrId"]
2732 )
2733 break
2734 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
2735 self.db.set_one(
2736 "nsis",
2737 {"_id": nsir["_id"]},
2738 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2739 )
2740
2741 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
2742 """
2743 Performs a new operation over a ns
2744 :param rollback: list to append created items at database in case a rollback must to be done
2745 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2746 :param indata: descriptor with the parameters of the operation. It must contains among others
2747 netsliceInstanceId: _id of the nsir to perform the operation
2748 operation: it can be: instantiate, terminate, action, TODO: update, heal
2749 :param kwargs: used to override the indata descriptor
2750 :param headers: http request headers
2751 :return: id of the nslcmops
2752 """
2753 try:
2754 # Override descriptor with query string kwargs
2755 self._update_input_with_kwargs(indata, kwargs)
2756 operation = indata["lcmOperationType"]
2757 netsliceInstanceId = indata["netsliceInstanceId"]
2758 validate_input(indata, self.operation_schema[operation])
2759
2760 # get nsi from netsliceInstanceId
2761 _filter = self._get_project_filter(session)
2762 _filter["_id"] = netsliceInstanceId
2763 nsir = self.db.get_one("nsis", _filter)
2764 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
2765 del _filter["_id"]
2766
2767 # initial checking
2768 if (
2769 not nsir["_admin"].get("nsiState")
2770 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2771 ):
2772 if operation == "terminate" and indata.get("autoremove"):
2773 # NSIR must be deleted
2774 return (
2775 None,
2776 None,
2777 ) # a none in this case is used to indicate not instantiated. It can be removed
2778 if operation != "instantiate":
2779 raise EngineException(
2780 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2781 netsliceInstanceId, operation
2782 ),
2783 HTTPStatus.CONFLICT,
2784 )
2785 else:
2786 if operation == "instantiate" and not session["force"]:
2787 raise EngineException(
2788 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2789 netsliceInstanceId, operation
2790 ),
2791 HTTPStatus.CONFLICT,
2792 )
2793
2794 # Creating all the NS_operation (nslcmop)
2795 # Get service list from db
2796 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2797 nslcmops = []
2798 # nslcmops_item = None
2799 for index, nsr_item in enumerate(nsrs_list):
2800 nsr_id = nsr_item["nsrId"]
2801 if nsr_item.get("shared"):
2802 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2803 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2804 _filter[
2805 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2806 ] = None
2807 _filter["_id.ne"] = netsliceInstanceId
2808 nsi = self.db.get_one(
2809 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2810 )
2811 if operation == "terminate":
2812 _update = {
2813 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2814 index
2815 ): None
2816 }
2817 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2818 if (
2819 nsi
2820 ): # other nsi is using this nsr and it needs this nsr instantiated
2821 continue # do not create nsilcmop
2822 else: # instantiate
2823 # looks the first nsi fulfilling the conditions but not being the current NSIR
2824 if nsi:
2825 nsi_nsr_item = next(
2826 n
2827 for n in nsi["_admin"]["nsrs-detailed-list"]
2828 if n["nsrId"] == nsr_id
2829 and n["shared"]
2830 and n["nslcmop_instantiate"]
2831 )
2832 self.add_shared_nsr_2vld(nsir, nsr_item)
2833 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
2834 _update = {
2835 "_admin.nsrs-detailed-list.{}".format(
2836 index
2837 ): nsi_nsr_item
2838 }
2839 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2840 # continue to not create nslcmop since nsrs is shared and nsrs was created
2841 continue
2842 else:
2843 self.add_shared_nsr_2vld(nsir, nsr_item)
2844
2845 # create operation
2846 try:
2847 indata_ns = {
2848 "lcmOperationType": operation,
2849 "nsInstanceId": nsr_id,
2850 # Including netslice_id in the ns instantiate Operation
2851 "netsliceInstanceId": netsliceInstanceId,
2852 }
2853 if operation == "instantiate":
2854 service = self.db.get_one("nsrs", {"_id": nsr_id})
2855 indata_ns.update(service["instantiate_params"])
2856
2857 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
2858 # message via kafka bus
2859 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2860 rollback, session, indata_ns, None, headers, slice_object=True
2861 )
2862 nslcmops.append(nslcmop)
2863 if operation == "instantiate":
2864 _update = {
2865 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2866 index
2867 ): nslcmop
2868 }
2869 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2870 except (DbException, EngineException) as e:
2871 if e.http_code == HTTPStatus.NOT_FOUND:
2872 self.logger.info(
2873 logging_prefix
2874 + "skipping NS={} because not found".format(nsr_id)
2875 )
2876 pass
2877 else:
2878 raise
2879
2880 # Creates nsilcmop
2881 indata["nslcmops_ids"] = nslcmops
2882 self._check_nsi_operation(session, nsir, operation, indata)
2883
2884 nsilcmop_desc = self._create_nsilcmop(
2885 session, netsliceInstanceId, operation, indata
2886 )
2887 self.format_on_new(
2888 nsilcmop_desc, session["project_id"], make_public=session["public"]
2889 )
2890 _id = self.db.create("nsilcmops", nsilcmop_desc)
2891 rollback.append({"topic": "nsilcmops", "_id": _id})
2892 self.msg.write("nsi", operation, nsilcmop_desc)
2893 return _id, None
2894 except ValidationError as e:
2895 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2896
2897 def delete(self, session, _id, dry_run=False, not_send_msg=None):
2898 raise EngineException(
2899 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2900 )
2901
2902 def edit(self, session, _id, indata=None, kwargs=None, content=None):
2903 raise EngineException(
2904 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2905 )