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