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