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