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