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