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