02572d0b99ccf4de03371c41a16ca575f487ec92
[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 ag_prefix_name = "{}-{}".format(nsr_descriptor["name"][:16], vnf_profile.get("id")[:16])
598
599 for vdu_profile in vdu_profiles:
600 ag_data = {}
601 for ag in vdu_profile.get("affinity-or-anti-affinity-group", ()):
602 ag_data = self._get_affinity_or_anti_affinity_group_data_from_vnfd(vnfd, ag["id"])
603 self._add_affinity_or_anti_affinity_group_to_nsr(nsr_descriptor, ag_data, ag_prefix_name)
604
605 for vld in nsr_vld:
606 vld["vnfd-connection-point-ref"] = all_vld_connection_point_data.get(
607 vld.get("id"), []
608 )
609 vld["name"] = vld["id"]
610 nsr_descriptor["vld"] = nsr_vld
611
612 return nsr_descriptor
613
614 def _get_affinity_or_anti_affinity_group_data_from_vnfd(self, vnfd, ag_id):
615 """
616 Gets affinity-or-anti-affinity-group info from df and returns the desired affinity group
617 """
618 affinity_or_anti_affinity_group = utils.find_in_list(
619 vnfd.get("df", [[]])[0].get("affinity-or-anti-affinity-group", ()), lambda ag: ag["id"] == ag_id
620 )
621 ag_data = {}
622 if affinity_or_anti_affinity_group and affinity_or_anti_affinity_group.get("id"):
623 ag_data["ag-id"] = affinity_or_anti_affinity_group["id"]
624 if affinity_or_anti_affinity_group and affinity_or_anti_affinity_group.get("type"):
625 ag_data["type"] = affinity_or_anti_affinity_group["type"]
626 if affinity_or_anti_affinity_group and affinity_or_anti_affinity_group.get("scope"):
627 ag_data["scope"] = affinity_or_anti_affinity_group["scope"]
628 return ag_data
629
630 def _add_affinity_or_anti_affinity_group_to_nsr(self, nsr_descriptor, ag_data, ag_prefix_name):
631 """
632 Adds affinity-or-anti-affinity-group to nsr checking first it is not already added
633 """
634 ag = next(
635 (
636 f
637 for f in nsr_descriptor["affinity-or-anti-affinity-group"]
638 if all(f.get(k) == ag_data[k] for k in ag_data)
639 ),
640 None,
641 )
642 if not ag:
643 ag_data["id"] = str(len(nsr_descriptor["affinity-or-anti-affinity-group"]))
644 ag_data["name"] = "{}-{}-{}".format(ag_prefix_name, ag_data["ag-id"][:32], ag_data.get("id") or 0)
645 nsr_descriptor["affinity-or-anti-affinity-group"].append(ag_data)
646
647 def _get_image_data_from_vnfd(self, vnfd, sw_image_id):
648 sw_image_desc = utils.find_in_list(
649 vnfd.get("sw-image-desc", ()), lambda sw: sw["id"] == sw_image_id
650 )
651 image_data = {}
652 if sw_image_desc.get("image"):
653 image_data["image"] = sw_image_desc["image"]
654 if sw_image_desc.get("checksum"):
655 image_data["image_checksum"] = sw_image_desc["checksum"]["hash"]
656 if sw_image_desc.get("vim-type"):
657 image_data["vim-type"] = sw_image_desc["vim-type"]
658 return image_data
659
660 def _add_image_to_nsr(self, nsr_descriptor, image_data):
661 """
662 Adds image to nsr checking first it is not already added
663 """
664 img = next(
665 (
666 f
667 for f in nsr_descriptor["image"]
668 if all(f.get(k) == image_data[k] for k in image_data)
669 ),
670 None,
671 )
672 if not img:
673 image_data["id"] = str(len(nsr_descriptor["image"]))
674 nsr_descriptor["image"].append(image_data)
675
676 def _create_vnfr_descriptor_from_vnfd(
677 self,
678 nsd,
679 vnfd,
680 vnfd_id,
681 vnf_index,
682 nsr_descriptor,
683 ns_request,
684 ns_k8s_namespace,
685 ):
686 vnfr_id = str(uuid4())
687 nsr_id = nsr_descriptor["id"]
688 now = time()
689 additional_params, vnf_params = self._format_additional_params(
690 ns_request, vnf_index, descriptor=vnfd
691 )
692
693 vnfr_descriptor = {
694 "id": vnfr_id,
695 "_id": vnfr_id,
696 "nsr-id-ref": nsr_id,
697 "member-vnf-index-ref": vnf_index,
698 "additionalParamsForVnf": additional_params,
699 "created-time": now,
700 # "vnfd": vnfd, # at OSM model.but removed to avoid data duplication TODO: revise
701 "vnfd-ref": vnfd_id,
702 "vnfd-id": vnfd["_id"], # not at OSM model, but useful
703 "vim-account-id": None,
704 "vca-id": None,
705 "vdur": [],
706 "connection-point": [],
707 "ip-address": None, # mgmt-interface filled by LCM
708 }
709 vnf_k8s_namespace = ns_k8s_namespace
710 if vnf_params:
711 if vnf_params.get("k8s-namespace"):
712 vnf_k8s_namespace = vnf_params["k8s-namespace"]
713 if vnf_params.get("config-units"):
714 vnfr_descriptor["config-units"] = vnf_params["config-units"]
715
716 # Create vld
717 if vnfd.get("int-virtual-link-desc"):
718 vnfr_descriptor["vld"] = []
719 for vnfd_vld in vnfd.get("int-virtual-link-desc"):
720 vnfr_descriptor["vld"].append({key: vnfd_vld[key] for key in vnfd_vld})
721
722 for cp in vnfd.get("ext-cpd", ()):
723 vnf_cp = {
724 "name": cp.get("id"),
725 "connection-point-id": cp.get("int-cpd", {}).get("cpd"),
726 "connection-point-vdu-id": cp.get("int-cpd", {}).get("vdu-id"),
727 "id": cp.get("id"),
728 # "ip-address", "mac-address" # filled by LCM
729 # vim-id # TODO it would be nice having a vim port id
730 }
731 vnfr_descriptor["connection-point"].append(vnf_cp)
732
733 # Create k8s-cluster information
734 # TODO: Validate if a k8s-cluster net can have more than one ext-cpd ?
735 if vnfd.get("k8s-cluster"):
736 vnfr_descriptor["k8s-cluster"] = vnfd["k8s-cluster"]
737 all_k8s_cluster_nets_cpds = {}
738 for cpd in get_iterable(vnfd.get("ext-cpd")):
739 if cpd.get("k8s-cluster-net"):
740 all_k8s_cluster_nets_cpds[cpd.get("k8s-cluster-net")] = cpd.get(
741 "id"
742 )
743 for net in get_iterable(vnfr_descriptor["k8s-cluster"].get("nets")):
744 if net.get("id") in all_k8s_cluster_nets_cpds:
745 net["external-connection-point-ref"] = all_k8s_cluster_nets_cpds[
746 net.get("id")
747 ]
748
749 # update kdus
750 for kdu in get_iterable(vnfd.get("kdu")):
751 additional_params, kdu_params = self._format_additional_params(
752 ns_request, vnf_index, kdu_name=kdu["name"], descriptor=vnfd
753 )
754 kdu_k8s_namespace = vnf_k8s_namespace
755 kdu_model = kdu_params.get("kdu_model") if kdu_params else None
756 if kdu_params and kdu_params.get("k8s-namespace"):
757 kdu_k8s_namespace = kdu_params["k8s-namespace"]
758 kdu_deployment_name = ""
759 if kdu_params and kdu_params.get("kdu-deployment-name"):
760 kdu_deployment_name = kdu_params.get("kdu-deployment-name")
761
762 kdur = {
763 "additionalParams": additional_params,
764 "k8s-namespace": kdu_k8s_namespace,
765 "kdu-deployment-name": kdu_deployment_name,
766 "kdu-name": kdu["name"],
767 # TODO "name": "" Name of the VDU in the VIM
768 "ip-address": None, # mgmt-interface filled by LCM
769 "k8s-cluster": {},
770 }
771 if kdu_params and kdu_params.get("config-units"):
772 kdur["config-units"] = kdu_params["config-units"]
773 if kdu.get("helm-version"):
774 kdur["helm-version"] = kdu["helm-version"]
775 for k8s_type in ("helm-chart", "juju-bundle"):
776 if kdu.get(k8s_type):
777 kdur[k8s_type] = kdu_model or kdu[k8s_type]
778 if not vnfr_descriptor.get("kdur"):
779 vnfr_descriptor["kdur"] = []
780 vnfr_descriptor["kdur"].append(kdur)
781
782 vnfd_mgmt_cp = vnfd.get("mgmt-cp")
783
784 for vdu in vnfd.get("vdu", ()):
785 vdu_mgmt_cp = []
786 try:
787 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
788 "operate-vnf-op-config"
789 ]["day1-2"]
790 vdu_config = utils.find_in_list(
791 configs, lambda config: config["id"] == vdu["id"]
792 )
793 except Exception:
794 vdu_config = None
795
796 try:
797 vdu_instantiation_level = utils.find_in_list(
798 vnfd.get("df")[0]["instantiation-level"][0]["vdu-level"],
799 lambda a_vdu_profile: a_vdu_profile["vdu-id"] == vdu["id"],
800 )
801 except Exception:
802 vdu_instantiation_level = None
803
804 if vdu_config:
805 external_connection_ee = utils.filter_in_list(
806 vdu_config.get("execution-environment-list", []),
807 lambda ee: "external-connection-point-ref" in ee,
808 )
809 for ee in external_connection_ee:
810 vdu_mgmt_cp.append(ee["external-connection-point-ref"])
811
812 additional_params, vdu_params = self._format_additional_params(
813 ns_request, vnf_index, vdu_id=vdu["id"], descriptor=vnfd
814 )
815
816 try:
817 vdu_virtual_storage_descriptors = utils.filter_in_list(
818 vnfd.get("virtual-storage-desc", []),
819 lambda stg_desc: stg_desc["id"] in vdu["virtual-storage-desc"]
820 )
821 except Exception:
822 vdu_virtual_storage_descriptors = []
823 vdur = {
824 "vdu-id-ref": vdu["id"],
825 # TODO "name": "" Name of the VDU in the VIM
826 "ip-address": None, # mgmt-interface filled by LCM
827 # "vim-id", "flavor-id", "image-id", "management-ip" # filled by LCM
828 "internal-connection-point": [],
829 "interfaces": [],
830 "additionalParams": additional_params,
831 "vdu-name": vdu["name"],
832 "virtual-storages": vdu_virtual_storage_descriptors
833 }
834 if vdu_params and vdu_params.get("config-units"):
835 vdur["config-units"] = vdu_params["config-units"]
836 if deep_get(vdu, ("supplemental-boot-data", "boot-data-drive")):
837 vdur["boot-data-drive"] = vdu["supplemental-boot-data"][
838 "boot-data-drive"
839 ]
840 if vdu.get("pdu-type"):
841 vdur["pdu-type"] = vdu["pdu-type"]
842 vdur["name"] = vdu["pdu-type"]
843 # TODO volumes: name, volume-id
844 for icp in vdu.get("int-cpd", ()):
845 vdu_icp = {
846 "id": icp["id"],
847 "connection-point-id": icp["id"],
848 "name": icp.get("id"),
849 }
850
851 vdur["internal-connection-point"].append(vdu_icp)
852
853 for iface in icp.get("virtual-network-interface-requirement", ()):
854 iface_fields = ("name", "mac-address")
855 vdu_iface = {
856 x: iface[x] for x in iface_fields if iface.get(x) is not None
857 }
858
859 vdu_iface["internal-connection-point-ref"] = vdu_icp["id"]
860 if "port-security-enabled" in icp:
861 vdu_iface["port-security-enabled"] = icp[
862 "port-security-enabled"
863 ]
864
865 if "port-security-disable-strategy" in icp:
866 vdu_iface["port-security-disable-strategy"] = icp[
867 "port-security-disable-strategy"
868 ]
869
870 for ext_cp in vnfd.get("ext-cpd", ()):
871 if not ext_cp.get("int-cpd"):
872 continue
873 if ext_cp["int-cpd"].get("vdu-id") != vdu["id"]:
874 continue
875 if icp["id"] == ext_cp["int-cpd"].get("cpd"):
876 vdu_iface["external-connection-point-ref"] = ext_cp.get(
877 "id"
878 )
879
880 if "port-security-enabled" in ext_cp:
881 vdu_iface["port-security-enabled"] = ext_cp[
882 "port-security-enabled"
883 ]
884
885 if "port-security-disable-strategy" in ext_cp:
886 vdu_iface["port-security-disable-strategy"] = ext_cp[
887 "port-security-disable-strategy"
888 ]
889
890 break
891
892 if (
893 vnfd_mgmt_cp
894 and vdu_iface.get("external-connection-point-ref")
895 == vnfd_mgmt_cp
896 ):
897 vdu_iface["mgmt-vnf"] = True
898 vdu_iface["mgmt-interface"] = True
899
900 for ecp in vdu_mgmt_cp:
901 if vdu_iface.get("external-connection-point-ref") == ecp:
902 vdu_iface["mgmt-interface"] = True
903
904 if iface.get("virtual-interface"):
905 vdu_iface.update(deepcopy(iface["virtual-interface"]))
906
907 # look for network where this interface is connected
908 iface_ext_cp = vdu_iface.get("external-connection-point-ref")
909 if iface_ext_cp:
910 # TODO: Change for multiple df support
911 for df in get_iterable(nsd.get("df")):
912 for vnf_profile in get_iterable(df.get("vnf-profile")):
913 for vlc_index, vlc in enumerate(
914 get_iterable(
915 vnf_profile.get("virtual-link-connectivity")
916 )
917 ):
918 for cpd in get_iterable(
919 vlc.get("constituent-cpd-id")
920 ):
921 if (
922 cpd.get("constituent-cpd-id")
923 == iface_ext_cp
924 ):
925 vdu_iface["ns-vld-id"] = vlc.get(
926 "virtual-link-profile-id"
927 )
928 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
929 if vdu_iface.get("type") in (
930 "SR-IOV",
931 "PCI-PASSTHROUGH",
932 ):
933 nsr_descriptor["vld"][vlc_index][
934 "pci-interfaces"
935 ] = True
936 break
937 elif vdu_iface.get("internal-connection-point-ref"):
938 vdu_iface["vnf-vld-id"] = icp.get("int-virtual-link-desc")
939 # TODO: store fixed IP address in the record (if it exists in the ICP)
940 # if iface type is SRIOV or PASSTHROUGH, set pci-interfaces flag to True
941 if vdu_iface.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
942 ivld_index = utils.find_index_in_list(
943 vnfd.get("int-virtual-link-desc", ()),
944 lambda ivld: ivld["id"]
945 == icp.get("int-virtual-link-desc"),
946 )
947 vnfr_descriptor["vld"][ivld_index]["pci-interfaces"] = True
948
949 vdur["interfaces"].append(vdu_iface)
950
951 if vdu.get("sw-image-desc"):
952 sw_image = utils.find_in_list(
953 vnfd.get("sw-image-desc", ()),
954 lambda image: image["id"] == vdu.get("sw-image-desc"),
955 )
956 nsr_sw_image_data = utils.find_in_list(
957 nsr_descriptor["image"],
958 lambda nsr_image: (nsr_image.get("image") == sw_image.get("image")),
959 )
960 vdur["ns-image-id"] = nsr_sw_image_data["id"]
961
962 if vdu.get("alternative-sw-image-desc"):
963 alt_image_ids = []
964 for alt_image_id in vdu.get("alternative-sw-image-desc", ()):
965 sw_image = utils.find_in_list(
966 vnfd.get("sw-image-desc", ()),
967 lambda image: image["id"] == alt_image_id,
968 )
969 nsr_sw_image_data = utils.find_in_list(
970 nsr_descriptor["image"],
971 lambda nsr_image: (
972 nsr_image.get("image") == sw_image.get("image")
973 ),
974 )
975 alt_image_ids.append(nsr_sw_image_data["id"])
976 vdur["alt-image-ids"] = alt_image_ids
977
978 flavor_data_name = vdu["id"][:56] + "-flv"
979 nsr_flavor_desc = utils.find_in_list(
980 nsr_descriptor["flavor"],
981 lambda flavor: flavor["name"] == flavor_data_name,
982 )
983
984 if nsr_flavor_desc:
985 vdur["ns-flavor-id"] = nsr_flavor_desc["id"]
986
987 # Adding Affinity groups information to vdur
988 try:
989 ags_vdu_profile = utils.find_in_list(
990 vnfd.get("df")[0]["vdu-profile"],
991 lambda a_vdu: a_vdu["id"] == vdu["id"],
992 )
993 except Exception:
994 ags_vdu_profile = None
995
996 if ags_vdu_profile:
997 ags_ids = []
998 for ag in ags_vdu_profile.get("affinity-or-anti-affinity-group", ()):
999 vdu_ag = utils.find_in_list(
1000 ags_vdu_profile.get("affinity-or-anti-affinity-group", ()),
1001 lambda ag_fp: ag_fp["id"] == ag["id"],
1002 )
1003 nsr_ags_data = utils.find_in_list(
1004 nsr_descriptor["affinity-or-anti-affinity-group"],
1005 lambda nsr_ag: (
1006 nsr_ag.get("ag-id") == vdu_ag.get("id")
1007 ),
1008 )
1009 ags_ids.append(nsr_ags_data["id"])
1010 vdur["affinity-or-anti-affinity-group-id"] = ags_ids
1011
1012 if vdu_instantiation_level:
1013 count = vdu_instantiation_level.get("number-of-instances")
1014 else:
1015 count = 1
1016
1017 for index in range(0, count):
1018 vdur = deepcopy(vdur)
1019 for iface in vdur["interfaces"]:
1020 if iface.get("ip-address") and index != 0:
1021 iface["ip-address"] = increment_ip_mac(iface["ip-address"])
1022 if iface.get("mac-address") and index != 0:
1023 iface["mac-address"] = increment_ip_mac(iface["mac-address"])
1024
1025 vdur["_id"] = str(uuid4())
1026 vdur["id"] = vdur["_id"]
1027 vdur["count-index"] = index
1028 vnfr_descriptor["vdur"].append(vdur)
1029
1030 return vnfr_descriptor
1031
1032 def vca_status_refresh(self, session, ns_instance_content, filter_q):
1033 """
1034 vcaStatus in ns_instance_content maybe stale, check if it is stale and create lcm op
1035 to refresh vca status by sending message to LCM when it is stale. Ignore otherwise.
1036 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1037 :param ns_instance_content: ns instance content
1038 :param filter_q: dict: query parameter containing vcaStatus-refresh as true or false
1039 :return: None
1040 """
1041 time_now, time_delta = time(), time() - ns_instance_content["_admin"]["modified"]
1042 force_refresh = isinstance(filter_q, dict) and filter_q.get('vcaStatusRefresh') == 'true'
1043 threshold_reached = time_delta > 120
1044 if force_refresh or threshold_reached:
1045 operation, _id = "vca_status_refresh", ns_instance_content["_id"]
1046 ns_instance_content["_admin"]["modified"] = time_now
1047 self.db.set_one(self.topic, {"_id": _id}, ns_instance_content)
1048 nslcmop_desc = NsLcmOpTopic._create_nslcmop(_id, operation, None)
1049 self.format_on_new(nslcmop_desc, session["project_id"], make_public=session["public"])
1050 nslcmop_desc["_admin"].pop("nsState")
1051 self.msg.write("ns", operation, nslcmop_desc)
1052 return
1053
1054 def show(self, session, _id, filter_q=None, api_req=False):
1055 """
1056 Get complete information on an ns instance.
1057 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1058 :param _id: string, ns instance id
1059 :param filter_q: dict: query parameter containing vcaStatusRefresh as true or false
1060 :param api_req: True if this call is serving an external API request. False if serving internal request.
1061 :return: dictionary, raise exception if not found.
1062 """
1063 ns_instance_content = super().show(session, _id, api_req)
1064 self.vca_status_refresh(session, ns_instance_content, filter_q)
1065 return ns_instance_content
1066
1067 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1068 raise EngineException(
1069 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1070 )
1071
1072
1073 class VnfrTopic(BaseTopic):
1074 topic = "vnfrs"
1075 topic_msg = None
1076
1077 def __init__(self, db, fs, msg, auth):
1078 BaseTopic.__init__(self, db, fs, msg, auth)
1079
1080 def delete(self, session, _id, dry_run=False, not_send_msg=None):
1081 raise EngineException(
1082 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1083 )
1084
1085 def edit(self, session, _id, indata=None, kwargs=None, content=None):
1086 raise EngineException(
1087 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1088 )
1089
1090 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
1091 # Not used because vnfrs are created and deleted by NsrTopic class directly
1092 raise EngineException(
1093 "Method new called directly", HTTPStatus.INTERNAL_SERVER_ERROR
1094 )
1095
1096
1097 class NsLcmOpTopic(BaseTopic):
1098 topic = "nslcmops"
1099 topic_msg = "ns"
1100 operation_schema = { # mapping between operation and jsonschema to validate
1101 "instantiate": ns_instantiate,
1102 "action": ns_action,
1103 "scale": ns_scale,
1104 "terminate": ns_terminate,
1105 }
1106
1107 def __init__(self, db, fs, msg, auth):
1108 BaseTopic.__init__(self, db, fs, msg, auth)
1109
1110 def _check_ns_operation(self, session, nsr, operation, indata):
1111 """
1112 Check that user has enter right parameters for the operation
1113 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1114 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
1115 :param indata: descriptor with the parameters of the operation
1116 :return: None
1117 """
1118 if operation == "action":
1119 self._check_action_ns_operation(indata, nsr)
1120 elif operation == "scale":
1121 self._check_scale_ns_operation(indata, nsr)
1122 elif operation == "instantiate":
1123 self._check_instantiate_ns_operation(indata, nsr, session)
1124
1125 def _check_action_ns_operation(self, indata, nsr):
1126 nsd = nsr["nsd"]
1127 # check vnf_member_index
1128 if indata.get("vnf_member_index"):
1129 indata["member_vnf_index"] = indata.pop(
1130 "vnf_member_index"
1131 ) # for backward compatibility
1132 if indata.get("member_vnf_index"):
1133 vnfd = self._get_vnfd_from_vnf_member_index(
1134 indata["member_vnf_index"], nsr["_id"]
1135 )
1136 try:
1137 configs = vnfd.get("df")[0]["lcm-operations-configuration"][
1138 "operate-vnf-op-config"
1139 ]["day1-2"]
1140 except Exception:
1141 configs = []
1142
1143 if indata.get("vdu_id"):
1144 self._check_valid_vdu(vnfd, indata["vdu_id"])
1145 descriptor_configuration = utils.find_in_list(
1146 configs, lambda config: config["id"] == indata["vdu_id"]
1147 )
1148 elif indata.get("kdu_name"):
1149 self._check_valid_kdu(vnfd, indata["kdu_name"])
1150 descriptor_configuration = utils.find_in_list(
1151 configs, lambda config: config["id"] == indata.get("kdu_name")
1152 )
1153 else:
1154 descriptor_configuration = utils.find_in_list(
1155 configs, lambda config: config["id"] == vnfd["id"]
1156 )
1157 if descriptor_configuration is not None:
1158 descriptor_configuration = descriptor_configuration.get(
1159 "config-primitive"
1160 )
1161 else: # use a NSD
1162 descriptor_configuration = nsd.get("ns-configuration", {}).get(
1163 "config-primitive"
1164 )
1165
1166 # For k8s allows default primitives without validating the parameters
1167 if indata.get("kdu_name") and indata["primitive"] in (
1168 "upgrade",
1169 "rollback",
1170 "status",
1171 "inspect",
1172 "readme",
1173 ):
1174 # TODO should be checked that rollback only can contains revsision_numbe????
1175 if not indata.get("member_vnf_index"):
1176 raise EngineException(
1177 "Missing action parameter 'member_vnf_index' for default KDU primitive '{}'".format(
1178 indata["primitive"]
1179 )
1180 )
1181 return
1182 # if not, check primitive
1183 for config_primitive in get_iterable(descriptor_configuration):
1184 if indata["primitive"] == config_primitive["name"]:
1185 # check needed primitive_params are provided
1186 if indata.get("primitive_params"):
1187 in_primitive_params_copy = copy(indata["primitive_params"])
1188 else:
1189 in_primitive_params_copy = {}
1190 for paramd in get_iterable(config_primitive.get("parameter")):
1191 if paramd["name"] in in_primitive_params_copy:
1192 del in_primitive_params_copy[paramd["name"]]
1193 elif not paramd.get("default-value"):
1194 raise EngineException(
1195 "Needed parameter {} not provided for primitive '{}'".format(
1196 paramd["name"], indata["primitive"]
1197 )
1198 )
1199 # check no extra primitive params are provided
1200 if in_primitive_params_copy:
1201 raise EngineException(
1202 "parameter/s '{}' not present at vnfd /nsd for primitive '{}'".format(
1203 list(in_primitive_params_copy.keys()), indata["primitive"]
1204 )
1205 )
1206 break
1207 else:
1208 raise EngineException(
1209 "Invalid primitive '{}' is not present at vnfd/nsd".format(
1210 indata["primitive"]
1211 )
1212 )
1213
1214 def _check_scale_ns_operation(self, indata, nsr):
1215 vnfd = self._get_vnfd_from_vnf_member_index(
1216 indata["scaleVnfData"]["scaleByStepData"]["member-vnf-index"], nsr["_id"]
1217 )
1218 for scaling_aspect in get_iterable(vnfd.get("df", ())[0]["scaling-aspect"]):
1219 if (
1220 indata["scaleVnfData"]["scaleByStepData"]["scaling-group-descriptor"]
1221 == scaling_aspect["id"]
1222 ):
1223 break
1224 else:
1225 raise EngineException(
1226 "Invalid scaleVnfData:scaleByStepData:scaling-group-descriptor '{}' is not "
1227 "present at vnfd:scaling-aspect".format(
1228 indata["scaleVnfData"]["scaleByStepData"][
1229 "scaling-group-descriptor"
1230 ]
1231 )
1232 )
1233
1234 def _check_instantiate_ns_operation(self, indata, nsr, session):
1235 vnf_member_index_to_vnfd = {} # map between vnf_member_index to vnf descriptor.
1236 vim_accounts = []
1237 wim_accounts = []
1238 nsd = nsr["nsd"]
1239 self._check_valid_vim_account(indata["vimAccountId"], vim_accounts, session)
1240 self._check_valid_wim_account(indata.get("wimAccountId"), wim_accounts, session)
1241 for in_vnf in get_iterable(indata.get("vnf")):
1242 member_vnf_index = in_vnf["member-vnf-index"]
1243 if vnf_member_index_to_vnfd.get(member_vnf_index):
1244 vnfd = vnf_member_index_to_vnfd[member_vnf_index]
1245 else:
1246 vnfd = self._get_vnfd_from_vnf_member_index(
1247 member_vnf_index, nsr["_id"]
1248 )
1249 vnf_member_index_to_vnfd[
1250 member_vnf_index
1251 ] = vnfd # add to cache, avoiding a later look for
1252 self._check_vnf_instantiation_params(in_vnf, vnfd)
1253 if in_vnf.get("vimAccountId"):
1254 self._check_valid_vim_account(
1255 in_vnf["vimAccountId"], vim_accounts, session
1256 )
1257
1258 for in_vld in get_iterable(indata.get("vld")):
1259 self._check_valid_wim_account(
1260 in_vld.get("wimAccountId"), wim_accounts, session
1261 )
1262 for vldd in get_iterable(nsd.get("virtual-link-desc")):
1263 if in_vld["name"] == vldd["id"]:
1264 break
1265 else:
1266 raise EngineException(
1267 "Invalid parameter vld:name='{}' is not present at nsd:vld".format(
1268 in_vld["name"]
1269 )
1270 )
1271
1272 def _get_vnfd_from_vnf_member_index(self, member_vnf_index, nsr_id):
1273 # Obtain vnf descriptor. The vnfr is used to get the vnfd._id used for this member_vnf_index
1274 vnfr = self.db.get_one(
1275 "vnfrs",
1276 {"nsr-id-ref": nsr_id, "member-vnf-index-ref": member_vnf_index},
1277 fail_on_empty=False,
1278 )
1279 if not vnfr:
1280 raise EngineException(
1281 "Invalid parameter member_vnf_index='{}' is not one of the "
1282 "nsd:constituent-vnfd".format(member_vnf_index)
1283 )
1284 vnfd = self.db.get_one("vnfds", {"_id": vnfr["vnfd-id"]}, fail_on_empty=False)
1285 if not vnfd:
1286 raise EngineException(
1287 "vnfd id={} has been deleted!. Operation cannot be performed".format(
1288 vnfr["vnfd-id"]
1289 )
1290 )
1291 return vnfd
1292
1293 def _check_valid_vdu(self, vnfd, vdu_id):
1294 for vdud in get_iterable(vnfd.get("vdu")):
1295 if vdud["id"] == vdu_id:
1296 return vdud
1297 else:
1298 raise EngineException(
1299 "Invalid parameter vdu_id='{}' not present at vnfd:vdu:id".format(
1300 vdu_id
1301 )
1302 )
1303
1304 def _check_valid_kdu(self, vnfd, kdu_name):
1305 for kdud in get_iterable(vnfd.get("kdu")):
1306 if kdud["name"] == kdu_name:
1307 return kdud
1308 else:
1309 raise EngineException(
1310 "Invalid parameter kdu_name='{}' not present at vnfd:kdu:name".format(
1311 kdu_name
1312 )
1313 )
1314
1315 def _check_vnf_instantiation_params(self, in_vnf, vnfd):
1316 for in_vdu in get_iterable(in_vnf.get("vdu")):
1317 for vdu in get_iterable(vnfd.get("vdu")):
1318 if in_vdu["id"] == vdu["id"]:
1319 for volume in get_iterable(in_vdu.get("volume")):
1320 for volumed in get_iterable(vdu.get("virtual-storage-desc")):
1321 if volumed["id"] == volume["name"]:
1322 break
1323 else:
1324 raise EngineException(
1325 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1326 "volume:name='{}' is not present at "
1327 "vnfd:vdu:virtual-storage-desc list".format(
1328 in_vnf["member-vnf-index"],
1329 in_vdu["id"],
1330 volume["id"],
1331 )
1332 )
1333
1334 vdu_if_names = set()
1335 for cpd in get_iterable(vdu.get("int-cpd")):
1336 for iface in get_iterable(
1337 cpd.get("virtual-network-interface-requirement")
1338 ):
1339 vdu_if_names.add(iface.get("name"))
1340
1341 for in_iface in get_iterable(in_vdu["interface"]):
1342 if in_iface["name"] in vdu_if_names:
1343 break
1344 else:
1345 raise EngineException(
1346 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}']:"
1347 "int-cpd[id='{}'] is not present at vnfd:vdu:int-cpd".format(
1348 in_vnf["member-vnf-index"],
1349 in_vdu["id"],
1350 in_iface["name"],
1351 )
1352 )
1353 break
1354
1355 else:
1356 raise EngineException(
1357 "Invalid parameter vnf[member-vnf-index='{}']:vdu[id='{}'] is not present "
1358 "at vnfd:vdu".format(in_vnf["member-vnf-index"], in_vdu["id"])
1359 )
1360
1361 vnfd_ivlds_cpds = {
1362 ivld.get("id"): set()
1363 for ivld in get_iterable(vnfd.get("int-virtual-link-desc"))
1364 }
1365 for vdu in get_iterable(vnfd.get("vdu")):
1366 for cpd in get_iterable(vnfd.get("int-cpd")):
1367 if cpd.get("int-virtual-link-desc"):
1368 vnfd_ivlds_cpds[cpd.get("int-virtual-link-desc")] = cpd.get("id")
1369
1370 for in_ivld in get_iterable(in_vnf.get("internal-vld")):
1371 if in_ivld.get("name") in vnfd_ivlds_cpds:
1372 for in_icp in get_iterable(in_ivld.get("internal-connection-point")):
1373 if in_icp["id-ref"] in vnfd_ivlds_cpds[in_ivld.get("name")]:
1374 break
1375 else:
1376 raise EngineException(
1377 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld[name"
1378 "='{}']:internal-connection-point[id-ref:'{}'] is not present at "
1379 "vnfd:internal-vld:name/id:internal-connection-point".format(
1380 in_vnf["member-vnf-index"],
1381 in_ivld["name"],
1382 in_icp["id-ref"],
1383 )
1384 )
1385 else:
1386 raise EngineException(
1387 "Invalid parameter vnf[member-vnf-index='{}']:internal-vld:name='{}'"
1388 " is not present at vnfd '{}'".format(
1389 in_vnf["member-vnf-index"], in_ivld["name"], vnfd["id"]
1390 )
1391 )
1392
1393 def _check_valid_vim_account(self, vim_account, vim_accounts, session):
1394 if vim_account in vim_accounts:
1395 return
1396 try:
1397 db_filter = self._get_project_filter(session)
1398 db_filter["_id"] = vim_account
1399 self.db.get_one("vim_accounts", db_filter)
1400 except Exception:
1401 raise EngineException(
1402 "Invalid vimAccountId='{}' not present for the project".format(
1403 vim_account
1404 )
1405 )
1406 vim_accounts.append(vim_account)
1407
1408 def _get_vim_account(self, vim_id: str, session):
1409 try:
1410 db_filter = self._get_project_filter(session)
1411 db_filter["_id"] = vim_id
1412 return self.db.get_one("vim_accounts", db_filter)
1413 except Exception:
1414 raise EngineException(
1415 "Invalid vimAccountId='{}' not present for the project".format(
1416 vim_id
1417 )
1418 )
1419
1420 def _check_valid_wim_account(self, wim_account, wim_accounts, session):
1421 if not isinstance(wim_account, str):
1422 return
1423 if wim_account in wim_accounts:
1424 return
1425 try:
1426 db_filter = self._get_project_filter(session)
1427 db_filter["_id"] = wim_account
1428 self.db.get_one("wim_accounts", db_filter)
1429 except Exception:
1430 raise EngineException(
1431 "Invalid wimAccountId='{}' not present for the project".format(
1432 wim_account
1433 )
1434 )
1435 wim_accounts.append(wim_account)
1436
1437 def _look_for_pdu(
1438 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1439 ):
1440 """
1441 Look for a free PDU in the catalog matching vdur type and interfaces. Fills vnfr.vdur with the interface
1442 (ip_address, ...) information.
1443 Modifies PDU _admin.usageState to 'IN_USE'
1444 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1445 :param rollback: list with the database modifications to rollback if needed
1446 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1447 :param vim_account: vim_account where this vnfr should be deployed
1448 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1449 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1450 of the changed vnfr is needed
1451
1452 :return: List of PDU interfaces that are connected to an existing VIM network. Each item contains:
1453 "vim-network-name": used at VIM
1454 "name": interface name
1455 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1456 "ns-vld-id": NSD vld where this interface is connected.
1457 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1458 """
1459
1460 ifaces_forcing_vim_network = []
1461 for vdur_index, vdur in enumerate(get_iterable(vnfr.get("vdur"))):
1462 if not vdur.get("pdu-type"):
1463 continue
1464 pdu_type = vdur.get("pdu-type")
1465 pdu_filter = self._get_project_filter(session)
1466 pdu_filter["vim_accounts"] = vim_account
1467 pdu_filter["type"] = pdu_type
1468 pdu_filter["_admin.operationalState"] = "ENABLED"
1469 pdu_filter["_admin.usageState"] = "NOT_IN_USE"
1470 # TODO feature 1417: "shared": True,
1471
1472 available_pdus = self.db.get_list("pdus", pdu_filter)
1473 for pdu in available_pdus:
1474 # step 1 check if this pdu contains needed interfaces:
1475 match_interfaces = True
1476 for vdur_interface in vdur["interfaces"]:
1477 for pdu_interface in pdu["interfaces"]:
1478 if pdu_interface["name"] == vdur_interface["name"]:
1479 # TODO feature 1417: match per mgmt type
1480 break
1481 else: # no interface found for name
1482 match_interfaces = False
1483 break
1484 if match_interfaces:
1485 break
1486 else:
1487 raise EngineException(
1488 "No PDU of type={} at vim_account={} found for member_vnf_index={}, vdu={} matching interface "
1489 "names".format(
1490 pdu_type,
1491 vim_account,
1492 vnfr["member-vnf-index-ref"],
1493 vdur["vdu-id-ref"],
1494 )
1495 )
1496
1497 # step 2. Update pdu
1498 rollback_pdu = {
1499 "_admin.usageState": pdu["_admin"]["usageState"],
1500 "_admin.usage.vnfr_id": None,
1501 "_admin.usage.nsr_id": None,
1502 "_admin.usage.vdur": None,
1503 }
1504 self.db.set_one(
1505 "pdus",
1506 {"_id": pdu["_id"]},
1507 {
1508 "_admin.usageState": "IN_USE",
1509 "_admin.usage": {
1510 "vnfr_id": vnfr["_id"],
1511 "nsr_id": vnfr["nsr-id-ref"],
1512 "vdur": vdur["vdu-id-ref"],
1513 },
1514 },
1515 )
1516 rollback.append(
1517 {
1518 "topic": "pdus",
1519 "_id": pdu["_id"],
1520 "operation": "set",
1521 "content": rollback_pdu,
1522 }
1523 )
1524
1525 # step 3. Fill vnfr info by filling vdur
1526 vdu_text = "vdur.{}".format(vdur_index)
1527 vnfr_update_rollback[vdu_text + ".pdu-id"] = None
1528 vnfr_update[vdu_text + ".pdu-id"] = pdu["_id"]
1529 for iface_index, vdur_interface in enumerate(vdur["interfaces"]):
1530 for pdu_interface in pdu["interfaces"]:
1531 if pdu_interface["name"] == vdur_interface["name"]:
1532 iface_text = vdu_text + ".interfaces.{}".format(iface_index)
1533 for k, v in pdu_interface.items():
1534 if k in (
1535 "ip-address",
1536 "mac-address",
1537 ): # TODO: switch-xxxxx must be inserted
1538 vnfr_update[iface_text + ".{}".format(k)] = v
1539 vnfr_update_rollback[
1540 iface_text + ".{}".format(k)
1541 ] = vdur_interface.get(v)
1542 if pdu_interface.get("ip-address"):
1543 if vdur_interface.get(
1544 "mgmt-interface"
1545 ) or vdur_interface.get("mgmt-vnf"):
1546 vnfr_update_rollback[
1547 vdu_text + ".ip-address"
1548 ] = vdur.get("ip-address")
1549 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1550 "ip-address"
1551 ]
1552 if vdur_interface.get("mgmt-vnf"):
1553 vnfr_update_rollback["ip-address"] = vnfr.get(
1554 "ip-address"
1555 )
1556 vnfr_update["ip-address"] = pdu_interface["ip-address"]
1557 vnfr_update[vdu_text + ".ip-address"] = pdu_interface[
1558 "ip-address"
1559 ]
1560 if pdu_interface.get("vim-network-name") or pdu_interface.get(
1561 "vim-network-id"
1562 ):
1563 ifaces_forcing_vim_network.append(
1564 {
1565 "name": vdur_interface.get("vnf-vld-id")
1566 or vdur_interface.get("ns-vld-id"),
1567 "vnf-vld-id": vdur_interface.get("vnf-vld-id"),
1568 "ns-vld-id": vdur_interface.get("ns-vld-id"),
1569 }
1570 )
1571 if pdu_interface.get("vim-network-id"):
1572 ifaces_forcing_vim_network[-1][
1573 "vim-network-id"
1574 ] = pdu_interface["vim-network-id"]
1575 if pdu_interface.get("vim-network-name"):
1576 ifaces_forcing_vim_network[-1][
1577 "vim-network-name"
1578 ] = pdu_interface["vim-network-name"]
1579 break
1580
1581 return ifaces_forcing_vim_network
1582
1583 def _look_for_k8scluster(
1584 self, session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1585 ):
1586 """
1587 Look for an available k8scluster for all the kuds in the vnfd matching version and cni requirements.
1588 Fills vnfr.kdur with the selected k8scluster
1589
1590 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1591 :param rollback: list with the database modifications to rollback if needed
1592 :param vnfr: vnfr to be updated. It is modified with pdu interface info if pdu is found
1593 :param vim_account: vim_account where this vnfr should be deployed
1594 :param vnfr_update: dictionary filled by this method with changes to be done at database vnfr
1595 :param vnfr_update_rollback: dictionary filled by this method with original content of vnfr in case a rollback
1596 of the changed vnfr is needed
1597
1598 :return: List of KDU interfaces that are connected to an existing VIM network. Each item contains:
1599 "vim-network-name": used at VIM
1600 "name": interface name
1601 "vnf-vld-id": internal VNFD vld where this interface is connected, or
1602 "ns-vld-id": NSD vld where this interface is connected.
1603 NOTE: One, and only one between 'vnf-vld-id' and 'ns-vld-id' contains a value. The other will be None
1604 """
1605
1606 ifaces_forcing_vim_network = []
1607 if not vnfr.get("kdur"):
1608 return ifaces_forcing_vim_network
1609
1610 kdu_filter = self._get_project_filter(session)
1611 kdu_filter["vim_account"] = vim_account
1612 # TODO kdu_filter["_admin.operationalState"] = "ENABLED"
1613 available_k8sclusters = self.db.get_list("k8sclusters", kdu_filter)
1614
1615 k8s_requirements = {} # just for logging
1616 for k8scluster in available_k8sclusters:
1617 if not vnfr.get("k8s-cluster"):
1618 break
1619 # restrict by cni
1620 if vnfr["k8s-cluster"].get("cni"):
1621 k8s_requirements["cni"] = vnfr["k8s-cluster"]["cni"]
1622 if not set(vnfr["k8s-cluster"]["cni"]).intersection(
1623 k8scluster.get("cni", ())
1624 ):
1625 continue
1626 # restrict by version
1627 if vnfr["k8s-cluster"].get("version"):
1628 k8s_requirements["version"] = vnfr["k8s-cluster"]["version"]
1629 if k8scluster.get("k8s_version") not in vnfr["k8s-cluster"]["version"]:
1630 continue
1631 # restrict by number of networks
1632 if vnfr["k8s-cluster"].get("nets"):
1633 k8s_requirements["networks"] = len(vnfr["k8s-cluster"]["nets"])
1634 if not k8scluster.get("nets") or len(k8scluster["nets"]) < len(
1635 vnfr["k8s-cluster"]["nets"]
1636 ):
1637 continue
1638 break
1639 else:
1640 raise EngineException(
1641 "No k8scluster with requirements='{}' at vim_account={} found for member_vnf_index={}".format(
1642 k8s_requirements, vim_account, vnfr["member-vnf-index-ref"]
1643 )
1644 )
1645
1646 for kdur_index, kdur in enumerate(get_iterable(vnfr.get("kdur"))):
1647 # step 3. Fill vnfr info by filling kdur
1648 kdu_text = "kdur.{}.".format(kdur_index)
1649 vnfr_update_rollback[kdu_text + "k8s-cluster.id"] = None
1650 vnfr_update[kdu_text + "k8s-cluster.id"] = k8scluster["_id"]
1651
1652 # step 4. Check VIM networks that forces the selected k8s_cluster
1653 if vnfr.get("k8s-cluster") and vnfr["k8s-cluster"].get("nets"):
1654 k8scluster_net_list = list(k8scluster.get("nets").keys())
1655 for net_index, kdur_net in enumerate(vnfr["k8s-cluster"]["nets"]):
1656 # get a network from k8s_cluster nets. If name matches use this, if not use other
1657 if kdur_net["id"] in k8scluster_net_list: # name matches
1658 vim_net = k8scluster["nets"][kdur_net["id"]]
1659 k8scluster_net_list.remove(kdur_net["id"])
1660 else:
1661 vim_net = k8scluster["nets"][k8scluster_net_list[0]]
1662 k8scluster_net_list.pop(0)
1663 vnfr_update_rollback[
1664 "k8s-cluster.nets.{}.vim_net".format(net_index)
1665 ] = None
1666 vnfr_update["k8s-cluster.nets.{}.vim_net".format(net_index)] = vim_net
1667 if vim_net and (
1668 kdur_net.get("vnf-vld-id") or kdur_net.get("ns-vld-id")
1669 ):
1670 ifaces_forcing_vim_network.append(
1671 {
1672 "name": kdur_net.get("vnf-vld-id")
1673 or kdur_net.get("ns-vld-id"),
1674 "vnf-vld-id": kdur_net.get("vnf-vld-id"),
1675 "ns-vld-id": kdur_net.get("ns-vld-id"),
1676 "vim-network-name": vim_net, # TODO can it be vim-network-id ???
1677 }
1678 )
1679 # TODO check that this forcing is not incompatible with other forcing
1680 return ifaces_forcing_vim_network
1681
1682 def _update_vnfrs_from_nsd(self, nsr):
1683 try:
1684 nsr_id = nsr["_id"]
1685 nsd = nsr["nsd"]
1686
1687 step = "Getting vnf_profiles from nsd"
1688 vnf_profiles = nsd.get("df", [{}])[0].get("vnf-profile", ())
1689 vld_fixed_ip_connection_point_data = {}
1690
1691 step = "Getting ip-address info from vnf_profile if it exists"
1692 for vnfp in vnf_profiles:
1693 # Checking ip-address info from nsd.vnf_profile and storing
1694 for vlc in vnfp.get("virtual-link-connectivity", ()):
1695 for cpd in vlc.get("constituent-cpd-id", ()):
1696 if cpd.get("ip-address"):
1697 step = "Storing ip-address info"
1698 vld_fixed_ip_connection_point_data.update({vlc.get("virtual-link-profile-id") + '.' + cpd.get("constituent-base-element-id"): {
1699 "vnfd-connection-point-ref": cpd.get(
1700 "constituent-cpd-id"),
1701 "ip-address": cpd.get(
1702 "ip-address")}})
1703
1704 # Inserting ip address to vnfr
1705 if len(vld_fixed_ip_connection_point_data) > 0:
1706 step = "Getting vnfrs"
1707 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1708 for item in vld_fixed_ip_connection_point_data.keys():
1709 step = "Filtering vnfrs"
1710 vnfr = next(filter(lambda vnfr: vnfr["member-vnf-index-ref"] == item.split('.')[1], vnfrs), None)
1711 if vnfr:
1712 vnfr_update = {}
1713 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1714 for iface_index, iface in enumerate(vdur["interfaces"]):
1715 step = "Looking for matched interface"
1716 if (
1717 iface.get("external-connection-point-ref")
1718 == vld_fixed_ip_connection_point_data[item].get("vnfd-connection-point-ref") and
1719 iface.get("ns-vld-id") == item.split('.')[0]
1720
1721 ):
1722 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1723 vdur_index, iface_index
1724 )
1725 step = "Storing info in order to update vnfr"
1726 vnfr_update[
1727 vnfr_update_text + ".ip-address"
1728 ] = increment_ip_mac(
1729 vld_fixed_ip_connection_point_data[item].get("ip-address"),
1730 vdur.get("count-index", 0), )
1731 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1732
1733 step = "updating vnfr at database"
1734 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1735 except (
1736 ValidationError,
1737 EngineException,
1738 DbException,
1739 MsgException,
1740 FsException,
1741 ) as e:
1742 raise type(e)("{} while '{}'".format(e, step), http_code=e.http_code)
1743
1744 def _update_vnfrs(self, session, rollback, nsr, indata):
1745 # get vnfr
1746 nsr_id = nsr["_id"]
1747 vnfrs = self.db.get_list("vnfrs", {"nsr-id-ref": nsr_id})
1748
1749 for vnfr in vnfrs:
1750 vnfr_update = {}
1751 vnfr_update_rollback = {}
1752 member_vnf_index = vnfr["member-vnf-index-ref"]
1753 # update vim-account-id
1754
1755 vim_account = indata["vimAccountId"]
1756 vca_id = self._get_vim_account(vim_account, session).get("vca")
1757 # check instantiate parameters
1758 for vnf_inst_params in get_iterable(indata.get("vnf")):
1759 if vnf_inst_params["member-vnf-index"] != member_vnf_index:
1760 continue
1761 if vnf_inst_params.get("vimAccountId"):
1762 vim_account = vnf_inst_params.get("vimAccountId")
1763 vca_id = self._get_vim_account(vim_account, session).get("vca")
1764
1765 # get vnf.vdu.interface instantiation params to update vnfr.vdur.interfaces ip, mac
1766 for vdu_inst_param in get_iterable(vnf_inst_params.get("vdu")):
1767 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1768 if vdu_inst_param["id"] != vdur["vdu-id-ref"]:
1769 continue
1770 for iface_inst_param in get_iterable(
1771 vdu_inst_param.get("interface")
1772 ):
1773 iface_index, _ = next(
1774 i
1775 for i in enumerate(vdur["interfaces"])
1776 if i[1]["name"] == iface_inst_param["name"]
1777 )
1778 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1779 vdur_index, iface_index
1780 )
1781 if iface_inst_param.get("ip-address"):
1782 vnfr_update[
1783 vnfr_update_text + ".ip-address"
1784 ] = increment_ip_mac(
1785 iface_inst_param.get("ip-address"),
1786 vdur.get("count-index", 0),
1787 )
1788 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1789 if iface_inst_param.get("mac-address"):
1790 vnfr_update[
1791 vnfr_update_text + ".mac-address"
1792 ] = increment_ip_mac(
1793 iface_inst_param.get("mac-address"),
1794 vdur.get("count-index", 0),
1795 )
1796 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
1797 if iface_inst_param.get("floating-ip-required"):
1798 vnfr_update[
1799 vnfr_update_text + ".floating-ip-required"
1800 ] = True
1801 # get vnf.internal-vld.internal-conection-point instantiation params to update vnfr.vdur.interfaces
1802 # TODO update vld with the ip-profile
1803 for ivld_inst_param in get_iterable(
1804 vnf_inst_params.get("internal-vld")
1805 ):
1806 for icp_inst_param in get_iterable(
1807 ivld_inst_param.get("internal-connection-point")
1808 ):
1809 # look for iface
1810 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1811 for iface_index, iface in enumerate(vdur["interfaces"]):
1812 if (
1813 iface.get("internal-connection-point-ref")
1814 == icp_inst_param["id-ref"]
1815 ):
1816 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1817 vdur_index, iface_index
1818 )
1819 if icp_inst_param.get("ip-address"):
1820 vnfr_update[
1821 vnfr_update_text + ".ip-address"
1822 ] = increment_ip_mac(
1823 icp_inst_param.get("ip-address"),
1824 vdur.get("count-index", 0),
1825 )
1826 vnfr_update[
1827 vnfr_update_text + ".fixed-ip"
1828 ] = True
1829 if icp_inst_param.get("mac-address"):
1830 vnfr_update[
1831 vnfr_update_text + ".mac-address"
1832 ] = increment_ip_mac(
1833 icp_inst_param.get("mac-address"),
1834 vdur.get("count-index", 0),
1835 )
1836 vnfr_update[
1837 vnfr_update_text + ".fixed-mac"
1838 ] = True
1839 break
1840 # get ip address from instantiation parameters.vld.vnfd-connection-point-ref
1841 for vld_inst_param in get_iterable(indata.get("vld")):
1842 for vnfcp_inst_param in get_iterable(
1843 vld_inst_param.get("vnfd-connection-point-ref")
1844 ):
1845 if vnfcp_inst_param["member-vnf-index-ref"] != member_vnf_index:
1846 continue
1847 # look for iface
1848 for vdur_index, vdur in enumerate(vnfr["vdur"]):
1849 for iface_index, iface in enumerate(vdur["interfaces"]):
1850 if (
1851 iface.get("external-connection-point-ref")
1852 == vnfcp_inst_param["vnfd-connection-point-ref"]
1853 ):
1854 vnfr_update_text = "vdur.{}.interfaces.{}".format(
1855 vdur_index, iface_index
1856 )
1857 if vnfcp_inst_param.get("ip-address"):
1858 vnfr_update[
1859 vnfr_update_text + ".ip-address"
1860 ] = increment_ip_mac(
1861 vnfcp_inst_param.get("ip-address"),
1862 vdur.get("count-index", 0),
1863 )
1864 vnfr_update[vnfr_update_text + ".fixed-ip"] = True
1865 if vnfcp_inst_param.get("mac-address"):
1866 vnfr_update[
1867 vnfr_update_text + ".mac-address"
1868 ] = increment_ip_mac(
1869 vnfcp_inst_param.get("mac-address"),
1870 vdur.get("count-index", 0),
1871 )
1872 vnfr_update[vnfr_update_text + ".fixed-mac"] = True
1873 break
1874
1875 vnfr_update["vim-account-id"] = vim_account
1876 vnfr_update_rollback["vim-account-id"] = vnfr.get("vim-account-id")
1877
1878 if vca_id:
1879 vnfr_update["vca-id"] = vca_id
1880 vnfr_update_rollback["vca-id"] = vnfr.get("vca-id")
1881
1882 # get pdu
1883 ifaces_forcing_vim_network = self._look_for_pdu(
1884 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1885 )
1886
1887 # get kdus
1888 ifaces_forcing_vim_network += self._look_for_k8scluster(
1889 session, rollback, vnfr, vim_account, vnfr_update, vnfr_update_rollback
1890 )
1891 # update database vnfr
1892 self.db.set_one("vnfrs", {"_id": vnfr["_id"]}, vnfr_update)
1893 rollback.append(
1894 {
1895 "topic": "vnfrs",
1896 "_id": vnfr["_id"],
1897 "operation": "set",
1898 "content": vnfr_update_rollback,
1899 }
1900 )
1901
1902 # Update indada in case pdu forces to use a concrete vim-network-name
1903 # TODO check if user has already insert a vim-network-name and raises an error
1904 if not ifaces_forcing_vim_network:
1905 continue
1906 for iface_info in ifaces_forcing_vim_network:
1907 if iface_info.get("ns-vld-id"):
1908 if "vld" not in indata:
1909 indata["vld"] = []
1910 indata["vld"].append(
1911 {
1912 key: iface_info[key]
1913 for key in ("name", "vim-network-name", "vim-network-id")
1914 if iface_info.get(key)
1915 }
1916 )
1917
1918 elif iface_info.get("vnf-vld-id"):
1919 if "vnf" not in indata:
1920 indata["vnf"] = []
1921 indata["vnf"].append(
1922 {
1923 "member-vnf-index": member_vnf_index,
1924 "internal-vld": [
1925 {
1926 key: iface_info[key]
1927 for key in (
1928 "name",
1929 "vim-network-name",
1930 "vim-network-id",
1931 )
1932 if iface_info.get(key)
1933 }
1934 ],
1935 }
1936 )
1937
1938 @staticmethod
1939 def _create_nslcmop(nsr_id, operation, params):
1940 """
1941 Creates a ns-lcm-opp content to be stored at database.
1942 :param nsr_id: internal id of the instance
1943 :param operation: instantiate, terminate, scale, action, ...
1944 :param params: user parameters for the operation
1945 :return: dictionary following SOL005 format
1946 """
1947 now = time()
1948 _id = str(uuid4())
1949 nslcmop = {
1950 "id": _id,
1951 "_id": _id,
1952 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
1953 "queuePosition": None,
1954 "stage": None,
1955 "errorMessage": None,
1956 "detailedStatus": None,
1957 "statusEnteredTime": now,
1958 "nsInstanceId": nsr_id,
1959 "lcmOperationType": operation,
1960 "startTime": now,
1961 "isAutomaticInvocation": False,
1962 "operationParams": params,
1963 "isCancelPending": False,
1964 "links": {
1965 "self": "/osm/nslcm/v1/ns_lcm_op_occs/" + _id,
1966 "nsInstance": "/osm/nslcm/v1/ns_instances/" + nsr_id,
1967 },
1968 }
1969 return nslcmop
1970
1971 def _get_enabled_vims(self, session):
1972 """
1973 Retrieve and return VIM accounts that are accessible by current user and has state ENABLE
1974 :param session: current session with user information
1975 """
1976 db_filter = self._get_project_filter(session)
1977 db_filter["_admin.operationalState"] = "ENABLED"
1978 vims = self.db.get_list("vim_accounts", db_filter)
1979 vimAccounts = []
1980 for vim in vims:
1981 vimAccounts.append(vim["_id"])
1982 return vimAccounts
1983
1984 def new(
1985 self,
1986 rollback,
1987 session,
1988 indata=None,
1989 kwargs=None,
1990 headers=None,
1991 slice_object=False,
1992 ):
1993 """
1994 Performs a new operation over a ns
1995 :param rollback: list to append created items at database in case a rollback must to be done
1996 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
1997 :param indata: descriptor with the parameters of the operation. It must contains among others
1998 nsInstanceId: _id of the nsr to perform the operation
1999 operation: it can be: instantiate, terminate, action, TODO: update, heal
2000 :param kwargs: used to override the indata descriptor
2001 :param headers: http request headers
2002 :return: id of the nslcmops
2003 """
2004
2005 def check_if_nsr_is_not_slice_member(session, nsr_id):
2006 nsis = None
2007 db_filter = self._get_project_filter(session)
2008 db_filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2009 nsis = self.db.get_one(
2010 "nsis", db_filter, fail_on_empty=False, fail_on_more=False
2011 )
2012 if nsis:
2013 raise EngineException(
2014 "The NS instance {} cannot be terminated because is used by the slice {}".format(
2015 nsr_id, nsis["_id"]
2016 ),
2017 http_code=HTTPStatus.CONFLICT,
2018 )
2019
2020 try:
2021 # Override descriptor with query string kwargs
2022 self._update_input_with_kwargs(indata, kwargs, yaml_format=True)
2023 operation = indata["lcmOperationType"]
2024 nsInstanceId = indata["nsInstanceId"]
2025
2026 validate_input(indata, self.operation_schema[operation])
2027 # get ns from nsr_id
2028 _filter = BaseTopic._get_project_filter(session)
2029 _filter["_id"] = nsInstanceId
2030 nsr = self.db.get_one("nsrs", _filter)
2031
2032 # initial checking
2033 if operation == "terminate" and slice_object is False:
2034 check_if_nsr_is_not_slice_member(session, nsr["_id"])
2035 if (
2036 not nsr["_admin"].get("nsState")
2037 or nsr["_admin"]["nsState"] == "NOT_INSTANTIATED"
2038 ):
2039 if operation == "terminate" and indata.get("autoremove"):
2040 # NSR must be deleted
2041 return (
2042 None,
2043 None,
2044 ) # a none in this case is used to indicate not instantiated. It can be removed
2045 if operation != "instantiate":
2046 raise EngineException(
2047 "ns_instance '{}' cannot be '{}' because it is not instantiated".format(
2048 nsInstanceId, operation
2049 ),
2050 HTTPStatus.CONFLICT,
2051 )
2052 else:
2053 if operation == "instantiate" and not session["force"]:
2054 raise EngineException(
2055 "ns_instance '{}' cannot be '{}' because it is already instantiated".format(
2056 nsInstanceId, operation
2057 ),
2058 HTTPStatus.CONFLICT,
2059 )
2060 self._check_ns_operation(session, nsr, operation, indata)
2061 if (indata.get("primitive_params")):
2062 indata["primitive_params"] = json.dumps(indata["primitive_params"])
2063 elif (indata.get("additionalParamsForVnf")):
2064 indata["additionalParamsForVnf"] = json.dumps(indata["additionalParamsForVnf"])
2065
2066 if operation == "instantiate":
2067 self._update_vnfrs_from_nsd(nsr)
2068 self._update_vnfrs(session, rollback, nsr, indata)
2069
2070 nslcmop_desc = self._create_nslcmop(nsInstanceId, operation, indata)
2071 _id = nslcmop_desc["_id"]
2072 self.format_on_new(
2073 nslcmop_desc, session["project_id"], make_public=session["public"]
2074 )
2075 if indata.get("placement-engine"):
2076 # Save valid vim accounts in lcm operation descriptor
2077 nslcmop_desc["operationParams"][
2078 "validVimAccounts"
2079 ] = self._get_enabled_vims(session)
2080 self.db.create("nslcmops", nslcmop_desc)
2081 rollback.append({"topic": "nslcmops", "_id": _id})
2082 if not slice_object:
2083 self.msg.write("ns", operation, nslcmop_desc)
2084 return _id, None
2085 except ValidationError as e: # TODO remove try Except, it is captured at nbi.py
2086 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2087 # except DbException as e:
2088 # raise EngineException("Cannot get ns_instance '{}': {}".format(e), HTTPStatus.NOT_FOUND)
2089
2090 def delete(self, session, _id, dry_run=False, not_send_msg=None):
2091 raise EngineException(
2092 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2093 )
2094
2095 def edit(self, session, _id, indata=None, kwargs=None, content=None):
2096 raise EngineException(
2097 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2098 )
2099
2100
2101 class NsiTopic(BaseTopic):
2102 topic = "nsis"
2103 topic_msg = "nsi"
2104 quota_name = "slice_instances"
2105
2106 def __init__(self, db, fs, msg, auth):
2107 BaseTopic.__init__(self, db, fs, msg, auth)
2108 self.nsrTopic = NsrTopic(db, fs, msg, auth)
2109
2110 @staticmethod
2111 def _format_ns_request(ns_request):
2112 formated_request = copy(ns_request)
2113 # TODO: Add request params
2114 return formated_request
2115
2116 @staticmethod
2117 def _format_addional_params(slice_request):
2118 """
2119 Get and format user additional params for NS or VNF
2120 :param slice_request: User instantiation additional parameters
2121 :return: a formatted copy of additional params or None if not supplied
2122 """
2123 additional_params = copy(slice_request.get("additionalParamsForNsi"))
2124 if additional_params:
2125 for k, v in additional_params.items():
2126 if not isinstance(k, str):
2127 raise EngineException(
2128 "Invalid param at additionalParamsForNsi:{}. Only string keys are allowed".format(
2129 k
2130 )
2131 )
2132 if "." in k or "$" in k:
2133 raise EngineException(
2134 "Invalid param at additionalParamsForNsi:{}. Keys must not contain dots or $".format(
2135 k
2136 )
2137 )
2138 if isinstance(v, (dict, tuple, list)):
2139 additional_params[k] = "!!yaml " + safe_dump(v)
2140 return additional_params
2141
2142 def _check_descriptor_dependencies(self, session, descriptor):
2143 """
2144 Check that the dependent descriptors exist on a new descriptor or edition
2145 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2146 :param descriptor: descriptor to be inserted or edit
2147 :return: None or raises exception
2148 """
2149 if not descriptor.get("nst-ref"):
2150 return
2151 nstd_id = descriptor["nst-ref"]
2152 if not self.get_item_list(session, "nsts", {"id": nstd_id}):
2153 raise EngineException(
2154 "Descriptor error at nst-ref='{}' references a non exist nstd".format(
2155 nstd_id
2156 ),
2157 http_code=HTTPStatus.CONFLICT,
2158 )
2159
2160 def check_conflict_on_del(self, session, _id, db_content):
2161 """
2162 Check that NSI is not instantiated
2163 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2164 :param _id: nsi internal id
2165 :param db_content: The database content of the _id
2166 :return: None or raises EngineException with the conflict
2167 """
2168 if session["force"]:
2169 return
2170 nsi = db_content
2171 if nsi["_admin"].get("nsiState") == "INSTANTIATED":
2172 raise EngineException(
2173 "nsi '{}' cannot be deleted because it is in 'INSTANTIATED' state. "
2174 "Launch 'terminate' operation first; or force deletion".format(_id),
2175 http_code=HTTPStatus.CONFLICT,
2176 )
2177
2178 def delete_extra(self, session, _id, db_content, not_send_msg=None):
2179 """
2180 Deletes associated nsilcmops from database. Deletes associated filesystem.
2181 Set usageState of nst
2182 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2183 :param _id: server internal id
2184 :param db_content: The database content of the descriptor
2185 :param not_send_msg: To not send message (False) or store content (list) instead
2186 :return: None if ok or raises EngineException with the problem
2187 """
2188
2189 # Deleting the nsrs belonging to nsir
2190 nsir = db_content
2191 for nsrs_detailed_item in nsir["_admin"]["nsrs-detailed-list"]:
2192 nsr_id = nsrs_detailed_item["nsrId"]
2193 if nsrs_detailed_item.get("shared"):
2194 _filter = {
2195 "_admin.nsrs-detailed-list.ANYINDEX.shared": True,
2196 "_admin.nsrs-detailed-list.ANYINDEX.nsrId": nsr_id,
2197 "_id.ne": nsir["_id"],
2198 }
2199 nsi = self.db.get_one(
2200 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2201 )
2202 if nsi: # last one using nsr
2203 continue
2204 try:
2205 self.nsrTopic.delete(
2206 session, nsr_id, dry_run=False, not_send_msg=not_send_msg
2207 )
2208 except (DbException, EngineException) as e:
2209 if e.http_code == HTTPStatus.NOT_FOUND:
2210 pass
2211 else:
2212 raise
2213
2214 # delete related nsilcmops database entries
2215 self.db.del_list("nsilcmops", {"netsliceInstanceId": _id})
2216
2217 # Check and set used NST usage state
2218 nsir_admin = nsir.get("_admin")
2219 if nsir_admin and nsir_admin.get("nst-id"):
2220 # check if used by another NSI
2221 nsis_list = self.db.get_one(
2222 "nsis",
2223 {"nst-id": nsir_admin["nst-id"]},
2224 fail_on_empty=False,
2225 fail_on_more=False,
2226 )
2227 if not nsis_list:
2228 self.db.set_one(
2229 "nsts",
2230 {"_id": nsir_admin["nst-id"]},
2231 {"_admin.usageState": "NOT_IN_USE"},
2232 )
2233
2234 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
2235 """
2236 Creates a new netslice instance record into database. It also creates needed nsrs and vnfrs
2237 :param rollback: list to append the created items at database in case a rollback must be done
2238 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2239 :param indata: params to be used for the nsir
2240 :param kwargs: used to override the indata descriptor
2241 :param headers: http request headers
2242 :return: the _id of nsi descriptor created at database
2243 """
2244
2245 try:
2246 step = "checking quotas"
2247 self.check_quota(session)
2248
2249 step = ""
2250 slice_request = self._remove_envelop(indata)
2251 # Override descriptor with query string kwargs
2252 self._update_input_with_kwargs(slice_request, kwargs)
2253 slice_request = self._validate_input_new(slice_request, session["force"])
2254
2255 # look for nstd
2256 step = "getting nstd id='{}' from database".format(
2257 slice_request.get("nstId")
2258 )
2259 _filter = self._get_project_filter(session)
2260 _filter["_id"] = slice_request["nstId"]
2261 nstd = self.db.get_one("nsts", _filter)
2262 # check NST is not disabled
2263 step = "checking NST operationalState"
2264 if nstd["_admin"]["operationalState"] == "DISABLED":
2265 raise EngineException(
2266 "nst with id '{}' is DISABLED, and thus cannot be used to create a netslice "
2267 "instance".format(slice_request["nstId"]),
2268 http_code=HTTPStatus.CONFLICT,
2269 )
2270 del _filter["_id"]
2271
2272 # check NSD is not disabled
2273 step = "checking operationalState"
2274 if nstd["_admin"]["operationalState"] == "DISABLED":
2275 raise EngineException(
2276 "nst with id '{}' is DISABLED, and thus cannot be used to create "
2277 "a network slice".format(slice_request["nstId"]),
2278 http_code=HTTPStatus.CONFLICT,
2279 )
2280
2281 nstd.pop("_admin", None)
2282 nstd_id = nstd.pop("_id", None)
2283 nsi_id = str(uuid4())
2284 step = "filling nsi_descriptor with input data"
2285
2286 # Creating the NSIR
2287 nsi_descriptor = {
2288 "id": nsi_id,
2289 "name": slice_request["nsiName"],
2290 "description": slice_request.get("nsiDescription", ""),
2291 "datacenter": slice_request["vimAccountId"],
2292 "nst-ref": nstd["id"],
2293 "instantiation_parameters": slice_request,
2294 "network-slice-template": nstd,
2295 "nsr-ref-list": [],
2296 "vlr-list": [],
2297 "_id": nsi_id,
2298 "additionalParamsForNsi": self._format_addional_params(slice_request),
2299 }
2300
2301 step = "creating nsi at database"
2302 self.format_on_new(
2303 nsi_descriptor, session["project_id"], make_public=session["public"]
2304 )
2305 nsi_descriptor["_admin"]["nsiState"] = "NOT_INSTANTIATED"
2306 nsi_descriptor["_admin"]["netslice-subnet"] = None
2307 nsi_descriptor["_admin"]["deployed"] = {}
2308 nsi_descriptor["_admin"]["deployed"]["RO"] = []
2309 nsi_descriptor["_admin"]["nst-id"] = nstd_id
2310
2311 # Creating netslice-vld for the RO.
2312 step = "creating netslice-vld at database"
2313
2314 # Building the vlds list to be deployed
2315 # From netslice descriptors, creating the initial list
2316 nsi_vlds = []
2317
2318 for netslice_vlds in get_iterable(nstd.get("netslice-vld")):
2319 # Getting template Instantiation parameters from NST
2320 nsi_vld = deepcopy(netslice_vlds)
2321 nsi_vld["shared-nsrs-list"] = []
2322 nsi_vld["vimAccountId"] = slice_request["vimAccountId"]
2323 nsi_vlds.append(nsi_vld)
2324
2325 nsi_descriptor["_admin"]["netslice-vld"] = nsi_vlds
2326 # Creating netslice-subnet_record.
2327 needed_nsds = {}
2328 services = []
2329
2330 # Updating the nstd with the nsd["_id"] associated to the nss -> services list
2331 for member_ns in nstd["netslice-subnet"]:
2332 nsd_id = member_ns["nsd-ref"]
2333 step = "getting nstd id='{}' constituent-nsd='{}' from database".format(
2334 member_ns["nsd-ref"], member_ns["id"]
2335 )
2336 if nsd_id not in needed_nsds:
2337 # Obtain nsd
2338 _filter["id"] = nsd_id
2339 nsd = self.db.get_one(
2340 "nsds", _filter, fail_on_empty=True, fail_on_more=True
2341 )
2342 del _filter["id"]
2343 nsd.pop("_admin")
2344 needed_nsds[nsd_id] = nsd
2345 else:
2346 nsd = needed_nsds[nsd_id]
2347 member_ns["_id"] = needed_nsds[nsd_id].get("_id")
2348 services.append(member_ns)
2349
2350 step = "filling nsir nsd-id='{}' constituent-nsd='{}' from database".format(
2351 member_ns["nsd-ref"], member_ns["id"]
2352 )
2353
2354 # creates Network Services records (NSRs)
2355 step = "creating nsrs at database using NsrTopic.new()"
2356 ns_params = slice_request.get("netslice-subnet")
2357 nsrs_list = []
2358 nsi_netslice_subnet = []
2359 for service in services:
2360 # Check if the netslice-subnet is shared and if it is share if the nss exists
2361 _id_nsr = None
2362 indata_ns = {}
2363 # Is the nss shared and instantiated?
2364 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2365 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsd-id"] = service[
2366 "nsd-ref"
2367 ]
2368 _filter["_admin.nsrs-detailed-list.ANYINDEX.nss-id"] = service["id"]
2369 nsi = self.db.get_one(
2370 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2371 )
2372 if nsi and service.get("is-shared-nss"):
2373 nsrs_detailed_list = nsi["_admin"]["nsrs-detailed-list"]
2374 for nsrs_detailed_item in nsrs_detailed_list:
2375 if nsrs_detailed_item["nsd-id"] == service["nsd-ref"]:
2376 if nsrs_detailed_item["nss-id"] == service["id"]:
2377 _id_nsr = nsrs_detailed_item["nsrId"]
2378 break
2379 for netslice_subnet in nsi["_admin"]["netslice-subnet"]:
2380 if netslice_subnet["nss-id"] == service["id"]:
2381 indata_ns = netslice_subnet
2382 break
2383 else:
2384 indata_ns = {}
2385 if service.get("instantiation-parameters"):
2386 indata_ns = deepcopy(service["instantiation-parameters"])
2387 # del service["instantiation-parameters"]
2388
2389 indata_ns["nsdId"] = service["_id"]
2390 indata_ns["nsName"] = (
2391 slice_request.get("nsiName") + "." + service["id"]
2392 )
2393 indata_ns["vimAccountId"] = slice_request.get("vimAccountId")
2394 indata_ns["nsDescription"] = service["description"]
2395 if slice_request.get("ssh_keys"):
2396 indata_ns["ssh_keys"] = slice_request.get("ssh_keys")
2397
2398 if ns_params:
2399 for ns_param in ns_params:
2400 if ns_param.get("id") == service["id"]:
2401 copy_ns_param = deepcopy(ns_param)
2402 del copy_ns_param["id"]
2403 indata_ns.update(copy_ns_param)
2404 break
2405
2406 # Creates Nsr objects
2407 _id_nsr, _ = self.nsrTopic.new(
2408 rollback, session, indata_ns, kwargs, headers
2409 )
2410 nsrs_item = {
2411 "nsrId": _id_nsr,
2412 "shared": service.get("is-shared-nss"),
2413 "nsd-id": service["nsd-ref"],
2414 "nss-id": service["id"],
2415 "nslcmop_instantiate": None,
2416 }
2417 indata_ns["nss-id"] = service["id"]
2418 nsrs_list.append(nsrs_item)
2419 nsi_netslice_subnet.append(indata_ns)
2420 nsr_ref = {"nsr-ref": _id_nsr}
2421 nsi_descriptor["nsr-ref-list"].append(nsr_ref)
2422
2423 # Adding the nsrs list to the nsi
2424 nsi_descriptor["_admin"]["nsrs-detailed-list"] = nsrs_list
2425 nsi_descriptor["_admin"]["netslice-subnet"] = nsi_netslice_subnet
2426 self.db.set_one(
2427 "nsts", {"_id": slice_request["nstId"]}, {"_admin.usageState": "IN_USE"}
2428 )
2429
2430 # Creating the entry in the database
2431 self.db.create("nsis", nsi_descriptor)
2432 rollback.append({"topic": "nsis", "_id": nsi_id})
2433 return nsi_id, None
2434 except Exception as e: # TODO remove try Except, it is captured at nbi.py
2435 self.logger.exception(
2436 "Exception {} at NsiTopic.new()".format(e), exc_info=True
2437 )
2438 raise EngineException("Error {}: {}".format(step, e))
2439 except ValidationError as e:
2440 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2441
2442 def edit(self, session, _id, indata=None, kwargs=None, content=None):
2443 raise EngineException(
2444 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2445 )
2446
2447
2448 class NsiLcmOpTopic(BaseTopic):
2449 topic = "nsilcmops"
2450 topic_msg = "nsi"
2451 operation_schema = { # mapping between operation and jsonschema to validate
2452 "instantiate": nsi_instantiate,
2453 "terminate": None,
2454 }
2455
2456 def __init__(self, db, fs, msg, auth):
2457 BaseTopic.__init__(self, db, fs, msg, auth)
2458 self.nsi_NsLcmOpTopic = NsLcmOpTopic(self.db, self.fs, self.msg, self.auth)
2459
2460 def _check_nsi_operation(self, session, nsir, operation, indata):
2461 """
2462 Check that user has enter right parameters for the operation
2463 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2464 :param operation: it can be: instantiate, terminate, action, TODO: update, heal
2465 :param indata: descriptor with the parameters of the operation
2466 :return: None
2467 """
2468 nsds = {}
2469 nstd = nsir["network-slice-template"]
2470
2471 def check_valid_netslice_subnet_id(nstId):
2472 # TODO change to vnfR (??)
2473 for netslice_subnet in nstd["netslice-subnet"]:
2474 if nstId == netslice_subnet["id"]:
2475 nsd_id = netslice_subnet["nsd-ref"]
2476 if nsd_id not in nsds:
2477 _filter = self._get_project_filter(session)
2478 _filter["id"] = nsd_id
2479 nsds[nsd_id] = self.db.get_one("nsds", _filter)
2480 return nsds[nsd_id]
2481 else:
2482 raise EngineException(
2483 "Invalid parameter nstId='{}' is not one of the "
2484 "nst:netslice-subnet".format(nstId)
2485 )
2486
2487 if operation == "instantiate":
2488 # check the existance of netslice-subnet items
2489 for in_nst in get_iterable(indata.get("netslice-subnet")):
2490 check_valid_netslice_subnet_id(in_nst["id"])
2491
2492 def _create_nsilcmop(self, session, netsliceInstanceId, operation, params):
2493 now = time()
2494 _id = str(uuid4())
2495 nsilcmop = {
2496 "id": _id,
2497 "_id": _id,
2498 "operationState": "PROCESSING", # COMPLETED,PARTIALLY_COMPLETED,FAILED_TEMP,FAILED,ROLLING_BACK,ROLLED_BACK
2499 "statusEnteredTime": now,
2500 "netsliceInstanceId": netsliceInstanceId,
2501 "lcmOperationType": operation,
2502 "startTime": now,
2503 "isAutomaticInvocation": False,
2504 "operationParams": params,
2505 "isCancelPending": False,
2506 "links": {
2507 "self": "/osm/nsilcm/v1/nsi_lcm_op_occs/" + _id,
2508 "netsliceInstanceId": "/osm/nsilcm/v1/netslice_instances/"
2509 + netsliceInstanceId,
2510 },
2511 }
2512 return nsilcmop
2513
2514 def add_shared_nsr_2vld(self, nsir, nsr_item):
2515 for nst_sb_item in nsir["network-slice-template"].get("netslice-subnet"):
2516 if nst_sb_item.get("is-shared-nss"):
2517 for admin_subnet_item in nsir["_admin"].get("netslice-subnet"):
2518 if admin_subnet_item["nss-id"] == nst_sb_item["id"]:
2519 for admin_vld_item in nsir["_admin"].get("netslice-vld"):
2520 for admin_vld_nss_cp_ref_item in admin_vld_item[
2521 "nss-connection-point-ref"
2522 ]:
2523 if (
2524 admin_subnet_item["nss-id"]
2525 == admin_vld_nss_cp_ref_item["nss-ref"]
2526 ):
2527 if (
2528 not nsr_item["nsrId"]
2529 in admin_vld_item["shared-nsrs-list"]
2530 ):
2531 admin_vld_item["shared-nsrs-list"].append(
2532 nsr_item["nsrId"]
2533 )
2534 break
2535 # self.db.set_one("nsis", {"_id": nsir["_id"]}, nsir)
2536 self.db.set_one(
2537 "nsis",
2538 {"_id": nsir["_id"]},
2539 {"_admin.netslice-vld": nsir["_admin"].get("netslice-vld")},
2540 )
2541
2542 def new(self, rollback, session, indata=None, kwargs=None, headers=None):
2543 """
2544 Performs a new operation over a ns
2545 :param rollback: list to append created items at database in case a rollback must to be done
2546 :param session: contains "username", "admin", "force", "public", "project_id", "set_project"
2547 :param indata: descriptor with the parameters of the operation. It must contains among others
2548 netsliceInstanceId: _id of the nsir to perform the operation
2549 operation: it can be: instantiate, terminate, action, TODO: update, heal
2550 :param kwargs: used to override the indata descriptor
2551 :param headers: http request headers
2552 :return: id of the nslcmops
2553 """
2554 try:
2555 # Override descriptor with query string kwargs
2556 self._update_input_with_kwargs(indata, kwargs)
2557 operation = indata["lcmOperationType"]
2558 netsliceInstanceId = indata["netsliceInstanceId"]
2559 validate_input(indata, self.operation_schema[operation])
2560
2561 # get nsi from netsliceInstanceId
2562 _filter = self._get_project_filter(session)
2563 _filter["_id"] = netsliceInstanceId
2564 nsir = self.db.get_one("nsis", _filter)
2565 logging_prefix = "nsi={} {} ".format(netsliceInstanceId, operation)
2566 del _filter["_id"]
2567
2568 # initial checking
2569 if (
2570 not nsir["_admin"].get("nsiState")
2571 or nsir["_admin"]["nsiState"] == "NOT_INSTANTIATED"
2572 ):
2573 if operation == "terminate" and indata.get("autoremove"):
2574 # NSIR must be deleted
2575 return (
2576 None,
2577 None,
2578 ) # a none in this case is used to indicate not instantiated. It can be removed
2579 if operation != "instantiate":
2580 raise EngineException(
2581 "netslice_instance '{}' cannot be '{}' because it is not instantiated".format(
2582 netsliceInstanceId, operation
2583 ),
2584 HTTPStatus.CONFLICT,
2585 )
2586 else:
2587 if operation == "instantiate" and not session["force"]:
2588 raise EngineException(
2589 "netslice_instance '{}' cannot be '{}' because it is already instantiated".format(
2590 netsliceInstanceId, operation
2591 ),
2592 HTTPStatus.CONFLICT,
2593 )
2594
2595 # Creating all the NS_operation (nslcmop)
2596 # Get service list from db
2597 nsrs_list = nsir["_admin"]["nsrs-detailed-list"]
2598 nslcmops = []
2599 # nslcmops_item = None
2600 for index, nsr_item in enumerate(nsrs_list):
2601 nsr_id = nsr_item["nsrId"]
2602 if nsr_item.get("shared"):
2603 _filter["_admin.nsrs-detailed-list.ANYINDEX.shared"] = True
2604 _filter["_admin.nsrs-detailed-list.ANYINDEX.nsrId"] = nsr_id
2605 _filter[
2606 "_admin.nsrs-detailed-list.ANYINDEX.nslcmop_instantiate.ne"
2607 ] = None
2608 _filter["_id.ne"] = netsliceInstanceId
2609 nsi = self.db.get_one(
2610 "nsis", _filter, fail_on_empty=False, fail_on_more=False
2611 )
2612 if operation == "terminate":
2613 _update = {
2614 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2615 index
2616 ): None
2617 }
2618 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2619 if (
2620 nsi
2621 ): # other nsi is using this nsr and it needs this nsr instantiated
2622 continue # do not create nsilcmop
2623 else: # instantiate
2624 # looks the first nsi fulfilling the conditions but not being the current NSIR
2625 if nsi:
2626 nsi_nsr_item = next(
2627 n
2628 for n in nsi["_admin"]["nsrs-detailed-list"]
2629 if n["nsrId"] == nsr_id
2630 and n["shared"]
2631 and n["nslcmop_instantiate"]
2632 )
2633 self.add_shared_nsr_2vld(nsir, nsr_item)
2634 nslcmops.append(nsi_nsr_item["nslcmop_instantiate"])
2635 _update = {
2636 "_admin.nsrs-detailed-list.{}".format(
2637 index
2638 ): nsi_nsr_item
2639 }
2640 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2641 # continue to not create nslcmop since nsrs is shared and nsrs was created
2642 continue
2643 else:
2644 self.add_shared_nsr_2vld(nsir, nsr_item)
2645
2646 # create operation
2647 try:
2648 indata_ns = {
2649 "lcmOperationType": operation,
2650 "nsInstanceId": nsr_id,
2651 # Including netslice_id in the ns instantiate Operation
2652 "netsliceInstanceId": netsliceInstanceId,
2653 }
2654 if operation == "instantiate":
2655 service = self.db.get_one("nsrs", {"_id": nsr_id})
2656 indata_ns.update(service["instantiate_params"])
2657
2658 # Creating NS_LCM_OP with the flag slice_object=True to not trigger the service instantiation
2659 # message via kafka bus
2660 nslcmop, _ = self.nsi_NsLcmOpTopic.new(
2661 rollback, session, indata_ns, None, headers, slice_object=True
2662 )
2663 nslcmops.append(nslcmop)
2664 if operation == "instantiate":
2665 _update = {
2666 "_admin.nsrs-detailed-list.{}.nslcmop_instantiate".format(
2667 index
2668 ): nslcmop
2669 }
2670 self.db.set_one("nsis", {"_id": nsir["_id"]}, _update)
2671 except (DbException, EngineException) as e:
2672 if e.http_code == HTTPStatus.NOT_FOUND:
2673 self.logger.info(
2674 logging_prefix
2675 + "skipping NS={} because not found".format(nsr_id)
2676 )
2677 pass
2678 else:
2679 raise
2680
2681 # Creates nsilcmop
2682 indata["nslcmops_ids"] = nslcmops
2683 self._check_nsi_operation(session, nsir, operation, indata)
2684
2685 nsilcmop_desc = self._create_nsilcmop(
2686 session, netsliceInstanceId, operation, indata
2687 )
2688 self.format_on_new(
2689 nsilcmop_desc, session["project_id"], make_public=session["public"]
2690 )
2691 _id = self.db.create("nsilcmops", nsilcmop_desc)
2692 rollback.append({"topic": "nsilcmops", "_id": _id})
2693 self.msg.write("nsi", operation, nsilcmop_desc)
2694 return _id, None
2695 except ValidationError as e:
2696 raise EngineException(e, HTTPStatus.UNPROCESSABLE_ENTITY)
2697
2698 def delete(self, session, _id, dry_run=False, not_send_msg=None):
2699 raise EngineException(
2700 "Method delete called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2701 )
2702
2703 def edit(self, session, _id, indata=None, kwargs=None, content=None):
2704 raise EngineException(
2705 "Method edit called directly", HTTPStatus.INTERNAL_SERVER_ERROR
2706 )