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