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