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