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