1 # -*- coding: utf-8 -*-
4 # Copyright 2020 Telefonica Investigacion y Desarrollo, S.A.U.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
19 from copy
import deepcopy
20 from http
import HTTPStatus
21 from itertools
import product
23 from random
import choice
as random_choice
24 from threading
import Lock
26 from traceback
import format_exc
as traceback_format_exc
27 from typing
import Any
, Dict
, List
, Optional
, Tuple
, Type
28 from uuid
import uuid4
30 from cryptography
.hazmat
.backends
import default_backend
as crypto_default_backend
31 from cryptography
.hazmat
.primitives
import serialization
as crypto_serialization
32 from cryptography
.hazmat
.primitives
.asymmetric
import rsa
41 from osm_common
import (
48 version
as common_version
,
50 from osm_common
.dbbase
import DbBase
, DbException
51 from osm_common
.fsbase
import FsBase
, FsException
52 from osm_common
.msgbase
import MsgException
53 from osm_ng_ro
.ns_thread
import deep_get
, NsWorker
, NsWorkerException
54 from osm_ng_ro
.validation
import deploy_schema
, validate_input
57 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
58 min_common_version
= "0.1.16"
61 class NsException(Exception):
62 def __init__(self
, message
, http_code
=HTTPStatus
.BAD_REQUEST
):
63 self
.http_code
= http_code
64 super(Exception, self
).__init
__(message
)
69 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
70 will provide a random one
73 # Try getting docker id. If fails, get pid
75 with
open("/proc/self/cgroup", "r") as f
:
76 text_id_
= f
.readline()
77 _
, _
, text_id
= text_id_
.rpartition("/")
78 text_id
= text_id
.replace("\n", "")[:12]
82 except Exception as error
:
83 logging
.exception(f
"{error} occured while getting process id")
86 return "".join(random_choice("0123456789abcdef") for _
in range(12))
90 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
93 for point
in v
.split("."):
94 filled
.append(point
.zfill(8))
105 # self.operations = None
107 # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
108 # If done now it will not be linked to parent not getting its handler and level
110 self
.write_lock
= None
111 self
.vims_assigned
= {}
115 self
.process_params_function_map
= {
116 "net": Ns
._process
_net
_params
,
117 "image": Ns
._process
_image
_params
,
118 "flavor": Ns
._process
_flavor
_params
,
119 "vdu": Ns
._process
_vdu
_params
,
120 "classification": Ns
._process
_classification
_params
,
121 "sfi": Ns
._process
_sfi
_params
,
122 "sf": Ns
._process
_sf
_params
,
123 "sfp": Ns
._process
_sfp
_params
,
124 "affinity-or-anti-affinity-group": Ns
._process
_affinity
_group
_params
,
125 "shared-volumes": Ns
._process
_shared
_volumes
_params
,
132 "classification": "classification",
136 "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group",
137 "shared-volumes": "shared-volumes",
140 def init_db(self
, target_version
):
143 def start(self
, config
):
145 Connect to database, filesystem storage, and messaging
146 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
147 :param config: Configuration of db, storage, etc
151 self
.config
["process_id"] = get_process_id() # used for HA identity
152 self
.logger
= logging
.getLogger("ro.ns")
154 # check right version of common
155 if versiontuple(common_version
) < versiontuple(min_common_version
):
157 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
158 common_version
, min_common_version
164 if config
["database"]["driver"] == "mongo":
165 self
.db
= dbmongo
.DbMongo()
166 self
.db
.db_connect(config
["database"])
167 elif config
["database"]["driver"] == "memory":
168 self
.db
= dbmemory
.DbMemory()
169 self
.db
.db_connect(config
["database"])
172 "Invalid configuration param '{}' at '[database]':'driver'".format(
173 config
["database"]["driver"]
178 if config
["storage"]["driver"] == "local":
179 self
.fs
= fslocal
.FsLocal()
180 self
.fs
.fs_connect(config
["storage"])
181 elif config
["storage"]["driver"] == "mongo":
182 self
.fs
= fsmongo
.FsMongo()
183 self
.fs
.fs_connect(config
["storage"])
184 elif config
["storage"]["driver"] is None:
188 "Invalid configuration param '{}' at '[storage]':'driver'".format(
189 config
["storage"]["driver"]
194 if config
["message"]["driver"] == "local":
195 self
.msg
= msglocal
.MsgLocal()
196 self
.msg
.connect(config
["message"])
197 elif config
["message"]["driver"] == "kafka":
198 self
.msg
= msgkafka
.MsgKafka()
199 self
.msg
.connect(config
["message"])
202 "Invalid configuration param '{}' at '[message]':'driver'".format(
203 config
["message"]["driver"]
207 # TODO load workers to deal with exising database tasks
209 self
.write_lock
= Lock()
210 except (DbException
, FsException
, MsgException
) as e
:
211 raise NsException(str(e
), http_code
=e
.http_code
)
213 def get_assigned_vims(self
):
214 return list(self
.vims_assigned
.keys())
219 self
.db
.db_disconnect()
222 self
.fs
.fs_disconnect()
225 self
.msg
.disconnect()
227 self
.write_lock
= None
228 except (DbException
, FsException
, MsgException
) as e
:
229 raise NsException(str(e
), http_code
=e
.http_code
)
231 for worker
in self
.workers
:
232 worker
.insert_task(("terminate",))
234 def _create_worker(self
):
236 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
237 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
238 return the index of the assigned worker thread. Worker threads are storead at self.workers
240 # Look for a thread in idle status
244 for i
in range(len(self
.workers
))
245 if self
.workers
[i
] and self
.workers
[i
].idle
250 if worker_id
is not None:
251 # unset idle status to avoid race conditions
252 self
.workers
[worker_id
].idle
= False
254 worker_id
= len(self
.workers
)
256 if worker_id
< self
.config
["global"]["server.ns_threads"]:
257 # create a new worker
259 NsWorker(worker_id
, self
.config
, self
.plugins
, self
.db
)
261 self
.workers
[worker_id
].start()
263 # reached maximum number of threads, assign VIM to an existing one
264 worker_id
= self
.next_worker
265 self
.next_worker
= (self
.next_worker
+ 1) % self
.config
["global"][
271 def assign_vim(self
, target_id
):
272 with self
.write_lock
:
273 return self
._assign
_vim
(target_id
)
275 def _assign_vim(self
, target_id
):
276 if target_id
not in self
.vims_assigned
:
277 worker_id
= self
.vims_assigned
[target_id
] = self
._create
_worker
()
278 self
.workers
[worker_id
].insert_task(("load_vim", target_id
))
280 def reload_vim(self
, target_id
):
281 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
282 # this is because database VIM information is cached for threads working with SDN
283 with self
.write_lock
:
284 for worker
in self
.workers
:
285 if worker
and not worker
.idle
:
286 worker
.insert_task(("reload_vim", target_id
))
288 def unload_vim(self
, target_id
):
289 with self
.write_lock
:
290 return self
._unload
_vim
(target_id
)
292 def _unload_vim(self
, target_id
):
293 if target_id
in self
.vims_assigned
:
294 worker_id
= self
.vims_assigned
[target_id
]
295 self
.workers
[worker_id
].insert_task(("unload_vim", target_id
))
296 del self
.vims_assigned
[target_id
]
298 def check_vim(self
, target_id
):
299 with self
.write_lock
:
300 if target_id
in self
.vims_assigned
:
301 worker_id
= self
.vims_assigned
[target_id
]
303 worker_id
= self
._create
_worker
()
305 worker
= self
.workers
[worker_id
]
306 worker
.insert_task(("check_vim", target_id
))
308 def unload_unused_vims(self
):
309 with self
.write_lock
:
312 for target_id
in self
.vims_assigned
:
313 if not self
.db
.get_one(
316 "target_id": target_id
,
317 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
321 vims_to_unload
.append(target_id
)
323 for target_id
in vims_to_unload
:
324 self
._unload
_vim
(target_id
)
332 """This method reads cloud init from a file.
334 Note: Not used as cloud init content is provided in the http body.
337 db (Type[DbBase]): [description]
338 fs (Type[FsBase]): [description]
339 location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
342 NsException: [description]
343 NsException: [description]
348 vnfd_id
, _
, other
= location
.partition(":")
349 _type
, _
, name
= other
.partition(":")
350 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
353 base_folder
= vnfd
["_admin"]["storage"]
354 cloud_init_file
= "{}/{}/cloud_init/{}".format(
355 base_folder
["folder"], base_folder
["pkg-dir"], name
360 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
365 with fs
.file_open(cloud_init_file
, "r") as ci_file
:
366 cloud_init_content
= ci_file
.read()
368 cloud_init_content
= vnfd
["vdu"][int(name
)]["cloud-init"]
370 raise NsException("Mismatch descriptor for cloud init: {}".format(location
))
372 return cloud_init_content
376 cloud_init_content
: str,
377 params
: Dict
[str, Any
],
380 """Function that processes the cloud init to replace Jinja2 encoded parameters.
383 cloud_init_content (str): [description]
384 params (Dict[str, Any]): [description]
385 context (str): [description]
388 NsException: [description]
389 NsException: [description]
396 undefined
=StrictUndefined
,
397 autoescape
=select_autoescape(default_for_string
=True, default
=True),
399 template
= env
.from_string(cloud_init_content
)
401 return template
.render(params
or {})
402 except UndefinedError
as e
:
404 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
405 "inside the 'additionalParamsForVnf' block".format(e
, context
)
407 except (TemplateError
, TemplateNotFound
) as e
:
409 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
414 def _create_db_ro_nsrs(self
, nsr_id
, now
):
416 key
= rsa
.generate_private_key(
417 backend
=crypto_default_backend(), public_exponent
=65537, key_size
=2048
419 private_key
= key
.private_bytes(
420 crypto_serialization
.Encoding
.PEM
,
421 crypto_serialization
.PrivateFormat
.PKCS8
,
422 crypto_serialization
.NoEncryption(),
424 public_key
= key
.public_key().public_bytes(
425 crypto_serialization
.Encoding
.OpenSSH
,
426 crypto_serialization
.PublicFormat
.OpenSSH
,
428 private_key
= private_key
.decode("utf8")
429 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
430 i
= private_key
.find("\n")
431 private_key
= "-----BEGIN RSA PRIVATE KEY-----" + private_key
[i
:]
432 public_key
= public_key
.decode("utf8")
433 except Exception as e
:
434 raise NsException("Cannot create ssh-keys: {}".format(e
))
436 schema_version
= "1.1"
437 private_key_encrypted
= self
.db
.encrypt(
438 private_key
, schema_version
=schema_version
, salt
=nsr_id
445 "schema_version": schema_version
,
447 "public_key": public_key
,
448 "private_key": private_key_encrypted
,
451 self
.db
.create("ro_nsrs", db_content
)
457 deployment_info
: Dict
[str, Any
],
462 target_record_id
: str,
463 extra_dict
: Dict
[str, Any
] = None,
465 """Function to create task dict from deployment information.
468 deployment_info (Dict[str, Any]): [description]
469 target_id (str): [description]
470 item (str): [description]
471 action (str): [description]
472 target_record (str): [description]
473 target_record_id (str): [description]
474 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
477 Dict[str, Any]: [description]
480 "target_id": target_id
, # it will be removed before pushing at database
481 "action_id": deployment_info
.get("action_id"),
482 "nsr_id": deployment_info
.get("nsr_id"),
483 "task_id": f
"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
484 "status": "SCHEDULED",
487 "target_record": target_record
,
488 "target_record_id": target_record_id
,
492 task
.update(extra_dict
) # params, find_params, depends_on
494 deployment_info
["task_index"] = deployment_info
.get("task_index", 0) + 1
501 task
: Dict
[str, Any
],
503 """Function to create an RO task from task information.
506 target_id (str): [description]
507 task (Dict[str, Any]): [description]
510 Dict[str, Any]: [description]
514 _id
= task
.get("task_id")
519 "target_id": target_id
,
522 "created_items": None,
539 def _process_image_params(
540 target_image
: Dict
[str, Any
],
541 indata
: Dict
[str, Any
],
542 vim_info
: Dict
[str, Any
],
543 target_record_id
: str,
544 **kwargs
: Dict
[str, Any
],
546 """Function to process VDU image parameters.
549 target_image (Dict[str, Any]): [description]
550 indata (Dict[str, Any]): [description]
551 vim_info (Dict[str, Any]): [description]
552 target_record_id (str): [description]
555 Dict[str, Any]: [description]
559 if target_image
.get("image"):
560 find_params
["filter_dict"] = {"name": target_image
.get("image")}
562 if target_image
.get("vim_image_id"):
563 find_params
["filter_dict"] = {"id": target_image
.get("vim_image_id")}
565 if target_image
.get("image_checksum"):
566 find_params
["filter_dict"] = {
567 "checksum": target_image
.get("image_checksum")
570 return {"find_params": find_params
}
573 def _get_resource_allocation_params(
574 quota_descriptor
: Dict
[str, Any
],
576 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
580 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
583 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
587 if quota_descriptor
.get("limit"):
588 quota
["limit"] = int(quota_descriptor
["limit"])
590 if quota_descriptor
.get("reserve"):
591 quota
["reserve"] = int(quota_descriptor
["reserve"])
593 if quota_descriptor
.get("shares"):
594 quota
["shares"] = int(quota_descriptor
["shares"])
599 def _process_guest_epa_quota_params(
600 guest_epa_quota
: Dict
[str, Any
],
603 """Function to extract the guest epa quota parameters.
606 guest_epa_quota (Dict[str, Any]): [description]
607 epa_vcpu_set (bool): [description]
610 Dict[str, Any]: [description]
614 if guest_epa_quota
.get("cpu-quota") and not epa_vcpu_set
:
615 cpuquota
= Ns
._get
_resource
_allocation
_params
(
616 guest_epa_quota
.get("cpu-quota")
620 result
["cpu-quota"] = cpuquota
622 if guest_epa_quota
.get("mem-quota"):
623 vduquota
= Ns
._get
_resource
_allocation
_params
(
624 guest_epa_quota
.get("mem-quota")
628 result
["mem-quota"] = vduquota
630 if guest_epa_quota
.get("disk-io-quota"):
631 diskioquota
= Ns
._get
_resource
_allocation
_params
(
632 guest_epa_quota
.get("disk-io-quota")
636 result
["disk-io-quota"] = diskioquota
638 if guest_epa_quota
.get("vif-quota"):
639 vifquota
= Ns
._get
_resource
_allocation
_params
(
640 guest_epa_quota
.get("vif-quota")
644 result
["vif-quota"] = vifquota
649 def _process_guest_epa_numa_params(
650 guest_epa_quota
: Dict
[str, Any
],
651 ) -> Tuple
[Dict
[str, Any
], bool]:
655 guest_epa_quota (Dict[str, Any]): [description]
658 Tuple[Dict[str, Any], bool]: [description]
664 if guest_epa_quota
.get("numa-node-policy"):
665 numa_node_policy
= guest_epa_quota
.get("numa-node-policy")
667 if numa_node_policy
.get("node"):
668 for numa_node
in numa_node_policy
["node"]:
670 if numa_node
.get("id"):
671 numa
["id"] = int(numa_node
["id"])
673 if numa_node
.get("vcpu"):
674 for vcpu
in numa_node
.get("vcpu"):
675 vcpu_id
= int(vcpu
.get("id"))
676 vcpu_list
.append(vcpu_id
)
677 numa
["vcpu"] = vcpu_list
679 if numa_node
.get("num-cores"):
680 numa
["cores"] = numa_node
["num-cores"]
683 paired_threads
= numa_node
.get("paired-threads", {})
684 if paired_threads
.get("num-paired-threads"):
685 numa
["paired_threads"] = int(
686 numa_node
["paired-threads"]["num-paired-threads"]
690 if paired_threads
.get("paired-thread-ids"):
691 numa
["paired-threads-id"] = []
693 for pair
in paired_threads
["paired-thread-ids"]:
694 numa
["paired-threads-id"].append(
696 str(pair
["thread-a"]),
697 str(pair
["thread-b"]),
701 if numa_node
.get("num-threads"):
702 numa
["threads"] = int(numa_node
["num-threads"])
705 if numa_node
.get("memory-mb"):
706 numa
["memory"] = max(int(int(numa_node
["memory-mb"]) / 1024), 1)
708 numa_list
.append(numa
)
711 return numa_list
, epa_vcpu_set
714 def _process_guest_epa_cpu_pinning_params(
715 guest_epa_quota
: Dict
[str, Any
],
718 ) -> Tuple
[Dict
[str, Any
], bool]:
722 guest_epa_quota (Dict[str, Any]): [description]
723 vcpu_count (int): [description]
724 epa_vcpu_set (bool): [description]
727 Tuple[Dict[str, Any], bool]: [description]
730 local_epa_vcpu_set
= epa_vcpu_set
733 guest_epa_quota
.get("cpu-pinning-policy") == "DEDICATED"
736 # Pinning policy "REQUIRE" uses threads as host should support SMT architecture
737 # Pinning policy "ISOLATE" uses cores as host should not support SMT architecture
738 # Pinning policy "PREFER" uses threads in case host supports SMT architecture
742 if guest_epa_quota
.get("cpu-thread-pinning-policy") == "ISOLATE"
745 ] = max(vcpu_count
, 1)
746 local_epa_vcpu_set
= True
748 return numa
, local_epa_vcpu_set
751 def _process_epa_params(
752 target_flavor
: Dict
[str, Any
],
757 target_flavor (Dict[str, Any]): [description]
760 Dict[str, Any]: [description]
766 if target_flavor
.get("guest-epa"):
767 guest_epa
= target_flavor
["guest-epa"]
769 numa_list
, epa_vcpu_set
= Ns
._process
_guest
_epa
_numa
_params
(
770 guest_epa_quota
=guest_epa
773 if guest_epa
.get("mempage-size"):
774 extended
["mempage-size"] = guest_epa
.get("mempage-size")
776 if guest_epa
.get("cpu-pinning-policy"):
777 extended
["cpu-pinning-policy"] = guest_epa
.get("cpu-pinning-policy")
779 if guest_epa
.get("cpu-thread-pinning-policy"):
780 extended
["cpu-thread-pinning-policy"] = guest_epa
.get(
781 "cpu-thread-pinning-policy"
784 if guest_epa
.get("numa-node-policy"):
785 if guest_epa
.get("numa-node-policy").get("mem-policy"):
786 extended
["mem-policy"] = guest_epa
.get("numa-node-policy").get(
790 tmp_numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_cpu
_pinning
_params
(
791 guest_epa_quota
=guest_epa
,
792 vcpu_count
=int(target_flavor
.get("vcpu-count", 1)),
793 epa_vcpu_set
=epa_vcpu_set
,
795 for numa
in numa_list
:
796 numa
.update(tmp_numa
)
799 Ns
._process
_guest
_epa
_quota
_params
(
800 guest_epa_quota
=guest_epa
,
801 epa_vcpu_set
=epa_vcpu_set
,
806 extended
["numas"] = numa_list
811 def _process_flavor_params(
812 target_flavor
: Dict
[str, Any
],
813 indata
: Dict
[str, Any
],
814 vim_info
: Dict
[str, Any
],
815 target_record_id
: str,
816 **kwargs
: Dict
[str, Any
],
821 target_flavor (Dict[str, Any]): [description]
822 indata (Dict[str, Any]): [description]
823 vim_info (Dict[str, Any]): [description]
824 target_record_id (str): [description]
827 Dict[str, Any]: [description]
829 db
= kwargs
.get("db")
832 for vnf
in indata
.get("vnf", []):
833 for vdur
in vnf
.get("vdur", []):
834 if vdur
.get("ns-flavor-id") == target_flavor
.get("id"):
838 target_vdur
.get("additionalParams", {}).get("OSM", {}).get("vim_flavor_id")
840 if vim_flavor_id
: # vim-flavor-id was passed so flavor won't be created
841 return {"find_params": {"vim_flavor_id": vim_flavor_id
}}
844 "disk": int(target_flavor
["storage-gb"]),
845 "ram": int(target_flavor
["memory-mb"]),
846 "vcpus": int(target_flavor
["vcpu-count"]),
849 if db
and isinstance(indata
.get("vnf"), list):
850 vnfd_id
= indata
.get("vnf")[0].get("vnfd-id")
851 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
852 # check if there is persistent root disk
853 for vdu
in vnfd
.get("vdu", ()):
854 if vdu
["name"] == target_vdur
.get("vdu-name"):
855 for vsd
in vnfd
.get("virtual-storage-desc", ()):
856 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
859 root_disk
.get("type-of-storage")
860 == "persistent-storage:persistent-storage"
862 flavor_data
["disk"] = 0
864 for storage
in target_vdur
.get("virtual-storages", []):
866 storage
.get("type-of-storage")
867 == "etsi-nfv-descriptors:ephemeral-storage"
869 flavor_data
["ephemeral"] = int(storage
.get("size-of-storage", 0))
870 elif storage
.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
871 flavor_data
["swap"] = int(storage
.get("size-of-storage", 0))
873 extended
= Ns
._process
_epa
_params
(target_flavor
)
875 flavor_data
["extended"] = extended
877 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
878 flavor_data_name
= flavor_data
.copy()
879 flavor_data_name
["name"] = target_flavor
["name"]
880 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
884 def _prefix_ip_address(ip_address
):
885 if "/" not in ip_address
:
890 def _process_ip_proto(ip_proto
):
901 def _process_classification_params(
902 target_classification
: Dict
[str, Any
],
903 indata
: Dict
[str, Any
],
904 vim_info
: Dict
[str, Any
],
905 target_record_id
: str,
906 **kwargs
: Dict
[str, Any
],
911 target_classification (Dict[str, Any]): Classification dictionary parameters that needs to be processed to create resource on VIM
912 indata (Dict[str, Any]): Deployment info
913 vim_info (Dict[str, Any]):To add items created by OSM on the VIM.
914 target_record_id (str): Task record ID.
915 **kwargs (Dict[str, Any]): Used to send additional information to the task.
918 Dict[str, Any]: Return parameters required to create classification and Items on which classification is dependent.
920 vnfr_id
= target_classification
["vnfr_id"]
921 vdur_id
= target_classification
["vdur_id"]
922 port_index
= target_classification
["ingress_port_index"]
925 classification_data
= {
926 "name": target_classification
["id"],
927 "source_port_range_min": target_classification
["source-port"],
928 "source_port_range_max": target_classification
["source-port"],
929 "destination_port_range_min": target_classification
["destination-port"],
930 "destination_port_range_max": target_classification
["destination-port"],
933 classification_data
["source_ip_prefix"] = Ns
._prefix
_ip
_address
(
934 target_classification
["source-ip-address"]
937 classification_data
["destination_ip_prefix"] = Ns
._prefix
_ip
_address
(
938 target_classification
["destination-ip-address"]
941 classification_data
["protocol"] = Ns
._process
_ip
_proto
(
942 int(target_classification
["ip-proto"])
945 db
= kwargs
.get("db")
946 vdu_text
= Ns
._get
_vnfr
_vdur
_text
(db
, vnfr_id
, vdur_id
)
948 extra_dict
= {"depends_on": [vdu_text
]}
950 extra_dict
= {"depends_on": [vdu_text
]}
951 classification_data
["logical_source_port"] = "TASK-" + vdu_text
952 classification_data
["logical_source_port_index"] = port_index
954 extra_dict
["params"] = classification_data
959 def _process_sfi_params(
960 target_sfi
: Dict
[str, Any
],
961 indata
: Dict
[str, Any
],
962 vim_info
: Dict
[str, Any
],
963 target_record_id
: str,
964 **kwargs
: Dict
[str, Any
],
969 target_sfi (Dict[str, Any]): SFI dictionary parameters that needs to be processed to create resource on VIM
970 indata (Dict[str, Any]): deployment info
971 vim_info (Dict[str, Any]): To add items created by OSM on the VIM.
972 target_record_id (str): Task record ID.
973 **kwargs (Dict[str, Any]): Used to send additional information to the task.
976 Dict[str, Any]: Return parameters required to create SFI and Items on which SFI is dependent.
979 vnfr_id
= target_sfi
["vnfr_id"]
980 vdur_id
= target_sfi
["vdur_id"]
983 "name": target_sfi
["id"],
984 "ingress_port_index": target_sfi
["ingress_port_index"],
985 "egress_port_index": target_sfi
["egress_port_index"],
988 db
= kwargs
.get("db")
989 vdu_text
= Ns
._get
_vnfr
_vdur
_text
(db
, vnfr_id
, vdur_id
)
991 extra_dict
= {"depends_on": [vdu_text
]}
992 sfi_data
["ingress_port"] = "TASK-" + vdu_text
993 sfi_data
["egress_port"] = "TASK-" + vdu_text
995 extra_dict
["params"] = sfi_data
1000 def _get_vnfr_vdur_text(db
, vnfr_id
, vdur_id
):
1001 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
1002 db_vnfr
= db
.get_one("vnfrs", {"_id": vnfr_id
})
1008 vdur
["id"] for vdur
in db_vnfr
["vdur"] if vdur
["vdu-id-ref"] == vdur_id
1012 vdu_text
= vnf_preffix
+ ":vdur." + vdur_list
[0]
1017 def _process_sf_params(
1018 target_sf
: Dict
[str, Any
],
1019 indata
: Dict
[str, Any
],
1020 vim_info
: Dict
[str, Any
],
1021 target_record_id
: str,
1022 **kwargs
: Dict
[str, Any
],
1023 ) -> Dict
[str, Any
]:
1027 target_sf (Dict[str, Any]): SF dictionary parameters that needs to be processed to create resource on VIM
1028 indata (Dict[str, Any]): Deployment info.
1029 vim_info (Dict[str, Any]):To add items created by OSM on the VIM.
1030 target_record_id (str): Task record ID.
1031 **kwargs (Dict[str, Any]): Used to send additional information to the task.
1034 Dict[str, Any]: Return parameters required to create SF and Items on which SF is dependent.
1037 nsr_id
= kwargs
.get("nsr_id", "")
1038 sfis
= target_sf
["sfis"]
1039 ns_preffix
= "nsrs:{}".format(nsr_id
)
1040 extra_dict
= {"depends_on": [], "params": []}
1041 sf_data
= {"name": target_sf
["id"], "sfis": sfis
}
1043 for count
, sfi
in enumerate(sfis
):
1044 sfi_text
= ns_preffix
+ ":sfi." + sfi
1045 sfis
[count
] = "TASK-" + sfi_text
1046 extra_dict
["depends_on"].append(sfi_text
)
1048 extra_dict
["params"] = sf_data
1053 def _process_sfp_params(
1054 target_sfp
: Dict
[str, Any
],
1055 indata
: Dict
[str, Any
],
1056 vim_info
: Dict
[str, Any
],
1057 target_record_id
: str,
1058 **kwargs
: Dict
[str, Any
],
1059 ) -> Dict
[str, Any
]:
1063 target_sfp (Dict[str, Any]): SFP dictionary parameters that needs to be processed to create resource on VIM.
1064 indata (Dict[str, Any]): Deployment info
1065 vim_info (Dict[str, Any]):To add items created by OSM on the VIM.
1066 target_record_id (str): Task record ID.
1067 **kwargs (Dict[str, Any]): Used to send additional information to the task.
1070 Dict[str, Any]: Return parameters required to create SFP and Items on which SFP is dependent.
1073 nsr_id
= kwargs
.get("nsr_id")
1074 sfs
= target_sfp
["sfs"]
1075 classifications
= target_sfp
["classifications"]
1076 ns_preffix
= "nsrs:{}".format(nsr_id
)
1077 extra_dict
= {"depends_on": [], "params": []}
1079 "name": target_sfp
["id"],
1081 "classifications": classifications
,
1084 for count
, sf
in enumerate(sfs
):
1085 sf_text
= ns_preffix
+ ":sf." + sf
1086 sfs
[count
] = "TASK-" + sf_text
1087 extra_dict
["depends_on"].append(sf_text
)
1089 for count
, classi
in enumerate(classifications
):
1090 classi_text
= ns_preffix
+ ":classification." + classi
1091 classifications
[count
] = "TASK-" + classi_text
1092 extra_dict
["depends_on"].append(classi_text
)
1094 extra_dict
["params"] = sfp_data
1099 def _process_net_params(
1100 target_vld
: Dict
[str, Any
],
1101 indata
: Dict
[str, Any
],
1102 vim_info
: Dict
[str, Any
],
1103 target_record_id
: str,
1104 **kwargs
: Dict
[str, Any
],
1105 ) -> Dict
[str, Any
]:
1106 """Function to process network parameters.
1109 target_vld (Dict[str, Any]): [description]
1110 indata (Dict[str, Any]): [description]
1111 vim_info (Dict[str, Any]): [description]
1112 target_record_id (str): [description]
1115 Dict[str, Any]: [description]
1119 if vim_info
.get("sdn"):
1120 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
1121 # ns_preffix = "nsrs:{}".format(nsr_id)
1122 # remove the ending ".sdn
1123 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
1124 extra_dict
["params"] = {
1126 for k
in ("sdn-ports", "target_vim", "vlds", "type")
1130 # TODO needed to add target_id in the dependency.
1131 if vim_info
.get("target_vim"):
1132 extra_dict
["depends_on"] = [
1133 f
"{vim_info.get('target_vim')} {vld_target_record_id}"
1138 if vim_info
.get("vim_network_name"):
1139 extra_dict
["find_params"] = {
1141 "name": vim_info
.get("vim_network_name"),
1144 elif vim_info
.get("vim_network_id"):
1145 extra_dict
["find_params"] = {
1147 "id": vim_info
.get("vim_network_id"),
1150 elif target_vld
.get("mgmt-network") and not vim_info
.get("provider_network"):
1151 extra_dict
["find_params"] = {
1153 "name": target_vld
["id"],
1157 extra_dict
["params"] = {
1159 f
"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
1161 "ip_profile": vim_info
.get("ip_profile"),
1162 "provider_network_profile": vim_info
.get("provider_network"),
1165 if not target_vld
.get("underlay"):
1166 extra_dict
["params"]["net_type"] = "bridge"
1168 extra_dict
["params"]["net_type"] = (
1169 "ptp" if target_vld
.get("type") == "ELINE" else "data"
1175 def find_persistent_root_volumes(
1178 vdu_instantiation_volumes_list
: list,
1180 ) -> Dict
[str, any
]:
1181 """Find the persistent root volumes and add them to the disk_list
1182 by parsing the instantiation parameters.
1185 vnfd (dict): VNF descriptor
1186 target_vdu (dict): processed VDU
1187 vdu_instantiation_volumes_list (list): instantiation parameters for the each VDU as a list
1188 disk_list (list): to be filled up
1191 persistent_root_disk (dict): Details of persistent root disk
1194 persistent_root_disk
= {}
1195 # There can be only one root disk, when we find it, it will return the result
1197 for vdu
, vsd
in product(
1198 vnfd
.get("vdu", ()), vnfd
.get("virtual-storage-desc", ())
1201 vdu
["name"] == target_vdu
["vdu-name"]
1202 and vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]
1206 root_disk
.get("type-of-storage")
1207 == "persistent-storage:persistent-storage"
1209 for vdu_volume
in vdu_instantiation_volumes_list
:
1211 vdu_volume
["vim-volume-id"]
1212 and root_disk
["id"] == vdu_volume
["name"]
1214 persistent_root_disk
[vsd
["id"]] = {
1215 "vim_volume_id": vdu_volume
["vim-volume-id"],
1216 "image_id": vdu
.get("sw-image-desc"),
1219 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1221 return persistent_root_disk
1224 if root_disk
.get("size-of-storage"):
1225 persistent_root_disk
[vsd
["id"]] = {
1226 "image_id": vdu
.get("sw-image-desc"),
1227 "size": root_disk
.get("size-of-storage"),
1228 "keep": Ns
.is_volume_keeping_required(root_disk
),
1231 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1233 return persistent_root_disk
1234 return persistent_root_disk
1237 def find_persistent_volumes(
1238 persistent_root_disk
: dict,
1240 vdu_instantiation_volumes_list
: list,
1243 """Find the ordinary persistent volumes and add them to the disk_list
1244 by parsing the instantiation parameters.
1247 persistent_root_disk: persistent root disk dictionary
1248 target_vdu: processed VDU
1249 vdu_instantiation_volumes_list: instantiation parameters for the each VDU as a list
1250 disk_list: to be filled up
1253 # Find the ordinary volumes which are not added to the persistent_root_disk
1254 persistent_disk
= {}
1255 for disk
in target_vdu
.get("virtual-storages", {}):
1257 disk
.get("type-of-storage") == "persistent-storage:persistent-storage"
1258 and disk
["id"] not in persistent_root_disk
.keys()
1260 for vdu_volume
in vdu_instantiation_volumes_list
:
1261 if vdu_volume
["vim-volume-id"] and disk
["id"] == vdu_volume
["name"]:
1262 persistent_disk
[disk
["id"]] = {
1263 "vim_volume_id": vdu_volume
["vim-volume-id"],
1265 disk_list
.append(persistent_disk
[disk
["id"]])
1268 if disk
["id"] not in persistent_disk
.keys():
1269 persistent_disk
[disk
["id"]] = {
1270 "size": disk
.get("size-of-storage"),
1271 "keep": Ns
.is_volume_keeping_required(disk
),
1273 disk_list
.append(persistent_disk
[disk
["id"]])
1276 def is_volume_keeping_required(virtual_storage_desc
: Dict
[str, Any
]) -> bool:
1277 """Function to decide keeping persistent volume
1281 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1287 if not virtual_storage_desc
.get("vdu-storage-requirements"):
1289 for item
in virtual_storage_desc
.get("vdu-storage-requirements", {}):
1290 if item
.get("key") == "keep-volume" and item
.get("value").lower() == "true":
1295 def is_shared_volume(
1296 virtual_storage_desc
: Dict
[str, Any
], vnfd_id
: str
1298 """Function to decide if the volume type is multi attached or not .
1301 virtual_storage_desc (Dict[str, Any]): virtual storage description dictionary
1302 vnfd_id (str): vnfd id
1306 name (str) New name if it is a multiattach disk
1309 if vdu_storage_requirements
:= virtual_storage_desc
.get(
1310 "vdu-storage-requirements", {}
1312 for item
in vdu_storage_requirements
:
1314 item
.get("key") == "multiattach"
1315 and item
.get("value").lower() == "true"
1317 name
= f
"shared-{virtual_storage_desc['id']}-{vnfd_id}"
1319 return virtual_storage_desc
["id"], False
1322 def _sort_vdu_interfaces(target_vdu
: dict) -> None:
1323 """Sort the interfaces according to position number.
1326 target_vdu (dict): Details of VDU to be created
1329 # If the position info is provided for all the interfaces, it will be sorted
1330 # according to position number ascendingly.
1331 sorted_interfaces
= sorted(
1332 target_vdu
["interfaces"],
1333 key
=lambda x
: (x
.get("position") is None, x
.get("position")),
1335 target_vdu
["interfaces"] = sorted_interfaces
1338 def _partially_locate_vdu_interfaces(target_vdu
: dict) -> None:
1339 """Only place the interfaces which has specific position.
1342 target_vdu (dict): Details of VDU to be created
1345 # If the position info is provided for some interfaces but not all of them, the interfaces
1346 # which has specific position numbers will be placed and others' positions will not be taken care.
1348 i
.get("position") + 1
1349 for i
in target_vdu
["interfaces"]
1350 if i
.get("position") is not None
1352 n
= len(target_vdu
["interfaces"])
1353 sorted_interfaces
= [-1] * n
1357 if target_vdu
["interfaces"][k
].get("position") is not None:
1358 if any(i
.get("position") == 0 for i
in target_vdu
["interfaces"]):
1359 idx
= target_vdu
["interfaces"][k
]["position"] + 1
1361 idx
= target_vdu
["interfaces"][k
]["position"]
1362 sorted_interfaces
[idx
- 1] = target_vdu
["interfaces"][k
]
1366 if target_vdu
["interfaces"][m
].get("position") is None:
1367 idy
= sorted_interfaces
.index(-1)
1368 sorted_interfaces
[idy
] = target_vdu
["interfaces"][m
]
1371 target_vdu
["interfaces"] = sorted_interfaces
1374 def _prepare_vdu_cloud_init(
1375 target_vdu
: dict, vdu2cloud_init
: dict, db
: object, fs
: object
1377 """Fill cloud_config dict with cloud init details.
1380 target_vdu (dict): Details of VDU to be created
1381 vdu2cloud_init (dict): Cloud init dict
1382 db (object): DB object
1383 fs (object): FS object
1386 cloud_config (dict): Cloud config details of VDU
1392 if target_vdu
.get("cloud-init"):
1393 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1394 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1397 location
=target_vdu
["cloud-init"],
1400 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1401 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1402 cloud_init_content
=cloud_content_
,
1403 params
=target_vdu
.get("additionalParams"),
1404 context
=target_vdu
["cloud-init"],
1407 if target_vdu
.get("boot-data-drive"):
1408 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1413 def _check_vld_information_of_interfaces(
1414 interface
: dict, ns_preffix
: str, vnf_preffix
: str
1416 """Prepare the net_text by the virtual link information for vnf and ns level.
1418 interface (dict): Interface details
1419 ns_preffix (str): Prefix of NS
1420 vnf_preffix (str): Prefix of VNF
1423 net_text (str): information of net
1427 if interface
.get("ns-vld-id"):
1428 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
1429 elif interface
.get("vnf-vld-id"):
1430 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
1435 def _prepare_interface_port_security(interface
: dict) -> None:
1439 interface (dict): Interface details
1442 if "port-security-enabled" in interface
:
1443 interface
["port_security"] = interface
.pop("port-security-enabled")
1445 if "port-security-disable-strategy" in interface
:
1446 interface
["port_security_disable_strategy"] = interface
.pop(
1447 "port-security-disable-strategy"
1451 def _create_net_item_of_interface(interface
: dict, net_text
: str) -> dict:
1452 """Prepare net item including name, port security, floating ip etc.
1455 interface (dict): Interface details
1456 net_text (str): information of net
1459 net_item (dict): Dict including net details
1465 for x
, v
in interface
.items()
1471 "port_security_disable_strategy",
1475 net_item
["net_id"] = "TASK-" + net_text
1476 net_item
["type"] = "virtual"
1481 def _prepare_type_of_interface(
1482 interface
: dict, tasks_by_target_record_id
: dict, net_text
: str, net_item
: dict
1484 """Fill the net item type by interface type such as SR-IOV, OM-MGMT, bridge etc.
1487 interface (dict): Interface details
1488 tasks_by_target_record_id (dict): Task details
1489 net_text (str): information of net
1490 net_item (dict): Dict including net details
1493 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1494 # TODO floating_ip: True/False (or it can be None)
1496 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1497 # Mark the net create task as type data
1499 tasks_by_target_record_id
,
1505 tasks_by_target_record_id
[net_text
]["extra_dict"]["params"][
1509 net_item
["use"] = "data"
1510 net_item
["model"] = interface
["type"]
1511 net_item
["type"] = interface
["type"]
1514 interface
.get("type") == "OM-MGMT"
1515 or interface
.get("mgmt-interface")
1516 or interface
.get("mgmt-vnf")
1518 net_item
["use"] = "mgmt"
1521 # If interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1522 net_item
["use"] = "bridge"
1523 net_item
["model"] = interface
.get("type")
1526 def _prepare_vdu_interfaces(
1532 tasks_by_target_record_id
: dict,
1535 """Prepare the net_item and add net_list, add mgmt interface to extra_dict.
1538 target_vdu (dict): VDU to be created
1539 extra_dict (dict): Dictionary to be filled
1540 ns_preffix (str): NS prefix as string
1541 vnf_preffix (str): VNF prefix as string
1542 logger (object): Logger Object
1543 tasks_by_target_record_id (dict): Task details
1544 net_list (list): Net list of VDU
1546 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
1547 net_text
= Ns
._check
_vld
_information
_of
_interfaces
(
1548 interface
, ns_preffix
, vnf_preffix
1551 # Interface not connected to any vld
1553 "Interface {} from vdu {} not connected to any vld".format(
1554 iface_index
, target_vdu
["vdu-name"]
1559 extra_dict
["depends_on"].append(net_text
)
1561 Ns
._prepare
_interface
_port
_security
(interface
)
1563 net_item
= Ns
._create
_net
_item
_of
_interface
(interface
, net_text
)
1565 Ns
._prepare
_type
_of
_interface
(
1566 interface
, tasks_by_target_record_id
, net_text
, net_item
1569 if interface
.get("ip-address"):
1570 net_item
["ip_address"] = interface
["ip-address"]
1572 if interface
.get("mac-address"):
1573 net_item
["mac_address"] = interface
["mac-address"]
1575 net_list
.append(net_item
)
1577 if interface
.get("mgmt-vnf"):
1578 extra_dict
["mgmt_vnf_interface"] = iface_index
1579 elif interface
.get("mgmt-interface"):
1580 extra_dict
["mgmt_vdu_interface"] = iface_index
1583 def _prepare_vdu_ssh_keys(
1584 target_vdu
: dict, ro_nsr_public_key
: dict, cloud_config
: dict
1586 """Add ssh keys to cloud config.
1589 target_vdu (dict): Details of VDU to be created
1590 ro_nsr_public_key (dict): RO NSR public Key
1591 cloud_config (dict): Cloud config details
1596 if target_vdu
.get("ssh-keys"):
1597 ssh_keys
+= target_vdu
.get("ssh-keys")
1599 if target_vdu
.get("ssh-access-required"):
1600 ssh_keys
.append(ro_nsr_public_key
)
1603 cloud_config
["key-pairs"] = ssh_keys
1606 def _select_persistent_root_disk(vsd
: dict, vdu
: dict) -> dict:
1607 """Selects the persistent root disk if exists.
1609 vsd (dict): Virtual storage descriptors in VNFD
1610 vdu (dict): VNF descriptor
1613 root_disk (dict): Selected persistent root disk
1615 if vsd
.get("id") == vdu
.get("virtual-storage-desc", [[]])[0]:
1619 ) == "persistent-storage:persistent-storage" and root_disk
.get(
1625 def _add_persistent_root_disk_to_disk_list(
1626 vnfd
: dict, target_vdu
: dict, persistent_root_disk
: dict, disk_list
: list
1628 """Find the persistent root disk and add to disk list.
1631 vnfd (dict): VNF descriptor
1632 target_vdu (dict): Details of VDU to be created
1633 persistent_root_disk (dict): Details of persistent root disk
1634 disk_list (list): Disks of VDU
1637 for vdu
in vnfd
.get("vdu", ()):
1638 if vdu
["name"] == target_vdu
["vdu-name"]:
1639 for vsd
in vnfd
.get("virtual-storage-desc", ()):
1640 root_disk
= Ns
._select
_persistent
_root
_disk
(vsd
, vdu
)
1644 persistent_root_disk
[vsd
["id"]] = {
1645 "image_id": vdu
.get("sw-image-desc"),
1646 "size": root_disk
["size-of-storage"],
1647 "keep": Ns
.is_volume_keeping_required(root_disk
),
1649 disk_list
.append(persistent_root_disk
[vsd
["id"]])
1653 def _add_persistent_ordinary_disks_to_disk_list(
1655 persistent_root_disk
: dict,
1656 persistent_ordinary_disk
: dict,
1662 """Fill the disk list by adding persistent ordinary disks.
1665 target_vdu (dict): Details of VDU to be created
1666 persistent_root_disk (dict): Details of persistent root disk
1667 persistent_ordinary_disk (dict): Details of persistent ordinary disk
1668 disk_list (list): Disks of VDU
1671 if target_vdu
.get("virtual-storages"):
1672 for disk
in target_vdu
["virtual-storages"]:
1674 disk
.get("type-of-storage")
1675 == "persistent-storage:persistent-storage"
1676 and disk
["id"] not in persistent_root_disk
.keys()
1678 name
, multiattach
= Ns
.is_shared_volume(disk
, vnf_id
)
1679 persistent_ordinary_disk
[disk
["id"]] = {
1681 "size": disk
["size-of-storage"],
1682 "keep": Ns
.is_volume_keeping_required(disk
),
1683 "multiattach": multiattach
,
1685 disk_list
.append(persistent_ordinary_disk
[disk
["id"]])
1686 if multiattach
: # VDU creation has to wait for shared volumes
1687 extra_dict
["depends_on"].append(
1688 f
"nsrs:{nsr_id}:shared-volumes.{name}"
1692 def _prepare_vdu_affinity_group_list(
1693 target_vdu
: dict, extra_dict
: dict, ns_preffix
: str
1694 ) -> List
[Dict
[str, any
]]:
1695 """Process affinity group details to prepare affinity group list.
1698 target_vdu (dict): Details of VDU to be created
1699 extra_dict (dict): Dictionary to be filled
1700 ns_preffix (str): Prefix as string
1704 affinity_group_list (list): Affinity group details
1707 affinity_group_list
= []
1709 if target_vdu
.get("affinity-or-anti-affinity-group-id"):
1710 for affinity_group_id
in target_vdu
["affinity-or-anti-affinity-group-id"]:
1712 affinity_group_text
= (
1713 ns_preffix
+ ":affinity-or-anti-affinity-group." + affinity_group_id
1716 if not isinstance(extra_dict
.get("depends_on"), list):
1717 raise NsException("Invalid extra_dict format.")
1719 extra_dict
["depends_on"].append(affinity_group_text
)
1720 affinity_group
["affinity_group_id"] = "TASK-" + affinity_group_text
1721 affinity_group_list
.append(affinity_group
)
1723 return affinity_group_list
1726 def _process_vdu_params(
1727 target_vdu
: Dict
[str, Any
],
1728 indata
: Dict
[str, Any
],
1729 vim_info
: Dict
[str, Any
],
1730 target_record_id
: str,
1731 **kwargs
: Dict
[str, Any
],
1732 ) -> Dict
[str, Any
]:
1733 """Function to process VDU parameters.
1736 target_vdu (Dict[str, Any]): [description]
1737 indata (Dict[str, Any]): [description]
1738 vim_info (Dict[str, Any]): [description]
1739 target_record_id (str): [description]
1742 Dict[str, Any]: [description]
1744 vnfr_id
= kwargs
.get("vnfr_id")
1745 nsr_id
= kwargs
.get("nsr_id")
1746 vnfr
= kwargs
.get("vnfr")
1747 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1748 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
1749 logger
= kwargs
.get("logger")
1750 db
= kwargs
.get("db")
1751 fs
= kwargs
.get("fs")
1752 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1754 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
1755 ns_preffix
= "nsrs:{}".format(nsr_id
)
1756 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
1757 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
1758 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
1760 persistent_root_disk
= {}
1761 persistent_ordinary_disk
= {}
1762 vdu_instantiation_volumes_list
= []
1764 vnfd_id
= vnfr
["vnfd-id"]
1765 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
1766 # If the position info is provided for all the interfaces, it will be sorted
1767 # according to position number ascendingly.
1769 True if i
.get("position") is not None else False
1770 for i
in target_vdu
["interfaces"]
1772 Ns
._sort
_vdu
_interfaces
(target_vdu
)
1774 # If the position info is provided for some interfaces but not all of them, the interfaces
1775 # which has specific position numbers will be placed and others' positions will not be taken care.
1777 Ns
._partially
_locate
_vdu
_interfaces
(target_vdu
)
1779 # If the position info is not provided for the interfaces, interfaces will be attached
1780 # according to the order in the VNFD.
1781 Ns
._prepare
_vdu
_interfaces
(
1787 tasks_by_target_record_id
,
1792 cloud_config
= Ns
._prepare
_vdu
_cloud
_init
(target_vdu
, vdu2cloud_init
, db
, fs
)
1794 # Prepare VDU ssh keys
1795 Ns
._prepare
_vdu
_ssh
_keys
(target_vdu
, ro_nsr_public_key
, cloud_config
)
1797 if target_vdu
.get("additionalParams"):
1798 vdu_instantiation_volumes_list
= (
1799 target_vdu
.get("additionalParams").get("OSM", {}).get("vdu_volumes")
1802 if vdu_instantiation_volumes_list
:
1803 # Find the root volumes and add to the disk_list
1804 persistent_root_disk
= Ns
.find_persistent_root_volumes(
1805 vnfd
, target_vdu
, vdu_instantiation_volumes_list
, disk_list
1808 # Find the ordinary volumes which are not added to the persistent_root_disk
1809 # and put them to the disk list
1810 Ns
.find_persistent_volumes(
1811 persistent_root_disk
,
1813 vdu_instantiation_volumes_list
,
1818 # Vdu_instantiation_volumes_list is empty
1819 # First get add the persistent root disks to disk_list
1820 Ns
._add
_persistent
_root
_disk
_to
_disk
_list
(
1821 vnfd
, target_vdu
, persistent_root_disk
, disk_list
1823 # Add the persistent non-root disks to disk_list
1824 Ns
._add
_persistent
_ordinary
_disks
_to
_disk
_list
(
1826 persistent_root_disk
,
1827 persistent_ordinary_disk
,
1834 affinity_group_list
= Ns
._prepare
_vdu
_affinity
_group
_list
(
1835 target_vdu
, extra_dict
, ns_preffix
1838 extra_dict
["params"] = {
1839 "name": "{}-{}-{}-{}".format(
1840 indata
["name"][:16],
1841 vnfr
["member-vnf-index-ref"][:16],
1842 target_vdu
["vdu-name"][:32],
1843 target_vdu
.get("count-index") or 0,
1845 "description": target_vdu
["vdu-name"],
1847 "image_id": "TASK-" + image_text
,
1848 "flavor_id": "TASK-" + flavor_text
,
1849 "affinity_group_list": affinity_group_list
,
1850 "net_list": net_list
,
1851 "cloud_config": cloud_config
or None,
1852 "disk_list": disk_list
,
1853 "availability_zone_index": None, # TODO
1854 "availability_zone_list": None, # TODO
1859 def _process_shared_volumes_params(
1860 target_shared_volume
: Dict
[str, Any
],
1861 indata
: Dict
[str, Any
],
1862 vim_info
: Dict
[str, Any
],
1863 target_record_id
: str,
1864 **kwargs
: Dict
[str, Any
],
1865 ) -> Dict
[str, Any
]:
1867 shared_volume_data
= {
1868 "size": target_shared_volume
["size-of-storage"],
1869 "name": target_shared_volume
["id"],
1870 "type": target_shared_volume
["type-of-storage"],
1871 "keep": Ns
.is_volume_keeping_required(target_shared_volume
),
1873 extra_dict
["params"] = shared_volume_data
1877 def _process_affinity_group_params(
1878 target_affinity_group
: Dict
[str, Any
],
1879 indata
: Dict
[str, Any
],
1880 vim_info
: Dict
[str, Any
],
1881 target_record_id
: str,
1882 **kwargs
: Dict
[str, Any
],
1883 ) -> Dict
[str, Any
]:
1884 """Get affinity or anti-affinity group parameters.
1887 target_affinity_group (Dict[str, Any]): [description]
1888 indata (Dict[str, Any]): [description]
1889 vim_info (Dict[str, Any]): [description]
1890 target_record_id (str): [description]
1893 Dict[str, Any]: [description]
1897 affinity_group_data
= {
1898 "name": target_affinity_group
["name"],
1899 "type": target_affinity_group
["type"],
1900 "scope": target_affinity_group
["scope"],
1903 if target_affinity_group
.get("vim-affinity-group-id"):
1904 affinity_group_data
["vim-affinity-group-id"] = target_affinity_group
[
1905 "vim-affinity-group-id"
1908 extra_dict
["params"] = {
1909 "affinity_group_data": affinity_group_data
,
1914 def _process_recreate_vdu_params(
1915 existing_vdu
: Dict
[str, Any
],
1916 db_nsr
: Dict
[str, Any
],
1917 vim_info
: Dict
[str, Any
],
1918 target_record_id
: str,
1920 **kwargs
: Dict
[str, Any
],
1921 ) -> Dict
[str, Any
]:
1922 """Function to process VDU parameters to recreate.
1925 existing_vdu (Dict[str, Any]): [description]
1926 db_nsr (Dict[str, Any]): [description]
1927 vim_info (Dict[str, Any]): [description]
1928 target_record_id (str): [description]
1929 target_id (str): [description]
1932 Dict[str, Any]: [description]
1934 vnfr
= kwargs
.get("vnfr")
1935 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
1936 # logger = kwargs.get("logger")
1937 db
= kwargs
.get("db")
1938 fs
= kwargs
.get("fs")
1939 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
1945 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
1947 if vim_details_text
:
1948 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
1950 for iface_index
, interface
in enumerate(existing_vdu
["interfaces"]):
1951 if "port-security-enabled" in interface
:
1952 interface
["port_security"] = interface
.pop("port-security-enabled")
1954 if "port-security-disable-strategy" in interface
:
1955 interface
["port_security_disable_strategy"] = interface
.pop(
1956 "port-security-disable-strategy"
1961 for x
, v
in interface
.items()
1967 "port_security_disable_strategy",
1971 existing_ifaces
= existing_vdu
["vim_info"][target_id
].get(
1972 "interfaces_backup", []
1977 for i
in existing_ifaces
1978 if i
["ip_address"] == interface
["ip-address"]
1983 net_item
["net_id"] = net_id
1984 net_item
["type"] = "virtual"
1986 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
1987 # TODO floating_ip: True/False (or it can be None)
1988 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1989 net_item
["use"] = "data"
1990 net_item
["model"] = interface
["type"]
1991 net_item
["type"] = interface
["type"]
1993 interface
.get("type") == "OM-MGMT"
1994 or interface
.get("mgmt-interface")
1995 or interface
.get("mgmt-vnf")
1997 net_item
["use"] = "mgmt"
1999 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
2000 net_item
["use"] = "bridge"
2001 net_item
["model"] = interface
.get("type")
2003 if interface
.get("ip-address"):
2004 net_item
["ip_address"] = interface
["ip-address"]
2006 if interface
.get("mac-address"):
2007 net_item
["mac_address"] = interface
["mac-address"]
2009 net_list
.append(net_item
)
2011 if interface
.get("mgmt-vnf"):
2012 extra_dict
["mgmt_vnf_interface"] = iface_index
2013 elif interface
.get("mgmt-interface"):
2014 extra_dict
["mgmt_vdu_interface"] = iface_index
2019 if existing_vdu
.get("cloud-init"):
2020 if existing_vdu
["cloud-init"] not in vdu2cloud_init
:
2021 vdu2cloud_init
[existing_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
2024 location
=existing_vdu
["cloud-init"],
2027 cloud_content_
= vdu2cloud_init
[existing_vdu
["cloud-init"]]
2028 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
2029 cloud_init_content
=cloud_content_
,
2030 params
=existing_vdu
.get("additionalParams"),
2031 context
=existing_vdu
["cloud-init"],
2034 if existing_vdu
.get("boot-data-drive"):
2035 cloud_config
["boot-data-drive"] = existing_vdu
.get("boot-data-drive")
2039 if existing_vdu
.get("ssh-keys"):
2040 ssh_keys
+= existing_vdu
.get("ssh-keys")
2042 if existing_vdu
.get("ssh-access-required"):
2043 ssh_keys
.append(ro_nsr_public_key
)
2046 cloud_config
["key-pairs"] = ssh_keys
2049 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
2050 disk_list
.append({"vim_id": vol_id
["id"]})
2052 affinity_group_list
= []
2054 if existing_vdu
.get("affinity-or-anti-affinity-group-id"):
2056 for affinity_group_id
in existing_vdu
["affinity-or-anti-affinity-group-id"]:
2057 for group
in db_nsr
.get("affinity-or-anti-affinity-group"):
2059 group
["id"] == affinity_group_id
2060 and group
["vim_info"][target_id
].get("vim_id", None) is not None
2062 affinity_group
["affinity_group_id"] = group
["vim_info"][
2064 ].get("vim_id", None)
2065 affinity_group_list
.append(affinity_group
)
2067 extra_dict
["params"] = {
2068 "name": "{}-{}-{}-{}".format(
2069 db_nsr
["name"][:16],
2070 vnfr
["member-vnf-index-ref"][:16],
2071 existing_vdu
["vdu-name"][:32],
2072 existing_vdu
.get("count-index") or 0,
2074 "description": existing_vdu
["vdu-name"],
2076 "image_id": vim_details
["image"]["id"],
2077 "flavor_id": vim_details
["flavor"]["id"],
2078 "affinity_group_list": affinity_group_list
,
2079 "net_list": net_list
,
2080 "cloud_config": cloud_config
or None,
2081 "disk_list": disk_list
,
2082 "availability_zone_index": None, # TODO
2083 "availability_zone_list": None, # TODO
2088 def calculate_diff_items(
2095 tasks_by_target_record_id
,
2102 """Function that returns the incremental changes (creation, deletion)
2103 related to a specific item `item` to be done. This function should be
2104 called for NS instantiation, NS termination, NS update to add a new VNF
2105 or a new VLD, remove a VNF or VLD, etc.
2106 Item can be `net`, `flavor`, `image` or `vdu`.
2107 It takes a list of target items from indata (which came from the REST API)
2108 and compares with the existing items from db_ro_nsr, identifying the
2109 incremental changes to be done. During the comparison, it calls the method
2110 `process_params` (which was passed as parameter, and is particular for each
2114 indata (Dict[str, Any]): deployment info
2115 db_nsr: NSR record from DB
2116 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2117 db_nsr_update (Dict[str, Any]): NSR info to update in DB
2118 item (str): element to process (net, vdu...)
2119 tasks_by_target_record_id (Dict[str, Any]):
2120 [<target_record_id>, <task>]
2121 action_id (str): action id
2122 nsr_id (str): NSR id
2123 task_index (number): task index to add to task name
2124 vnfr_id (str): VNFR id
2125 vnfr (Dict[str, Any]): VNFR info
2128 List: list with the incremental changes (deletes, creates) for each item
2129 number: current task index
2137 process_params
= None
2138 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
2139 ro_nsr_public_key
= db_ro_nsr
["public_key"]
2140 # According to the type of item, the path, the target_list,
2141 # the existing_list and the method to process params are set
2142 db_path
= self
.db_path_map
[item
]
2143 process_params
= self
.process_params_function_map
[item
]
2145 if item
in ("sfp", "classification", "sf", "sfi"):
2146 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
2147 target_vnffg
= indata
.get("vnffg", [])[0]
2148 target_list
= target_vnffg
[item
]
2149 existing_list
= db_nsr
.get(item
, [])
2150 elif item
in ("net", "vdu"):
2151 # This case is specific for the NS VLD (not applied to VDU)
2153 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
2154 target_list
= indata
.get("ns", []).get(db_path
, [])
2155 existing_list
= db_nsr
.get(db_path
, [])
2156 # This case is common for VNF VLDs and VNF VDUs
2158 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
2160 (vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
),
2163 target_list
= target_vnf
.get(db_path
, []) if target_vnf
else []
2164 existing_list
= vnfr
.get(db_path
, [])
2168 "affinity-or-anti-affinity-group",
2171 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
2172 target_list
= indata
.get(item
, [])
2173 existing_list
= db_nsr
.get(item
, [])
2175 raise NsException("Item not supported: {}", item
)
2176 # ensure all the target_list elements has an "id". If not assign the index as id
2177 if target_list
is None:
2179 for target_index
, tl
in enumerate(target_list
):
2180 if tl
and not tl
.get("id"):
2181 tl
["id"] = str(target_index
)
2182 # step 1 items (networks,vdus,...) to be deleted/updated
2183 for item_index
, existing_item
in enumerate(existing_list
):
2185 (t
for t
in target_list
if t
["id"] == existing_item
["id"]),
2188 for target_vim
, existing_viminfo
in existing_item
.get(
2191 if existing_viminfo
is None:
2195 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
2197 target_viminfo
= None
2199 if target_viminfo
is None:
2201 self
._assign
_vim
(target_vim
)
2202 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
2205 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
2206 # item must be sdn-net instead of net if target_vim is a sdn
2208 target_record_id
+= ".sdn"
2211 "action_id": action_id
,
2213 "task_index": task_index
,
2218 "deployment_info": deployment_info
,
2219 "target_id": target_vim
,
2222 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
2223 "target_record_id": target_record_id
,
2228 # step 2 items (networks,vdus,...) to be created
2229 for target_item
in target_list
:
2231 for item_index
, existing_item
in enumerate(existing_list
):
2232 if existing_item
["id"] == target_item
["id"]:
2236 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
2237 existing_list
.append(target_item
)
2238 existing_item
= None
2240 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
2241 existing_viminfo
= None
2244 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
2246 if existing_viminfo
is not None:
2249 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
2252 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
2253 # item must be sdn-net instead of net if target_vim is a sdn
2255 target_record_id
+= ".sdn"
2259 "ns.calculate_diff_items target_item={}".format(target_item
)
2261 if process_params
== Ns
._process
_flavor
_params
:
2268 "calculate_diff_items for flavor kwargs={}".format(kwargs
)
2271 if process_params
== Ns
._process
_vdu
_params
:
2272 self
.logger
.debug("calculate_diff_items self.fs={}".format(self
.fs
))
2278 "vdu2cloud_init": vdu2cloud_init
,
2279 "tasks_by_target_record_id": tasks_by_target_record_id
,
2280 "logger": self
.logger
,
2283 "ro_nsr_public_key": ro_nsr_public_key
,
2286 self
.logger
.debug("calculate_diff_items kwargs={}".format(kwargs
))
2288 process_params
== Ns
._process
_sfi
_params
2289 or Ns
._process
_sf
_params
2290 or Ns
._process
_classification
_params
2291 or Ns
._process
_sfp
_params
2293 kwargs
.update({"nsr_id": nsr_id
, "db": self
.db
})
2295 self
.logger
.debug("calculate_diff_items kwargs={}".format(kwargs
))
2297 extra_dict
= process_params(
2304 self
._assign
_vim
(target_vim
)
2307 "action_id": action_id
,
2309 "task_index": task_index
,
2313 "deployment_info": deployment_info
,
2314 "target_id": target_vim
,
2317 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
2318 "target_record_id": target_record_id
,
2319 "extra_dict": extra_dict
,
2320 "common_id": target_item
.get("common_id", None),
2322 diff_items
.append(new_item
)
2323 tasks_by_target_record_id
[target_record_id
] = new_item
2326 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
2328 return diff_items
, task_index
2330 def _process_vnfgd_sfp(self
, sfp
):
2332 # getting sfp name, sfs and classifications in sfp to store it in processed_sfp
2333 processed_sfp
["id"] = sfp
["id"]
2335 sf
["id"] for sf
in sfp
.get("position-desc-id", [])[0].get("cp-profile-id")
2337 classifications_in_sfp
= [
2339 for classi
in sfp
.get("position-desc-id", [])[0].get("match-attributes")
2342 # creating a list of sfp with sfs and classifications
2343 processed_sfp
["sfs"] = sfs_in_sfp
2344 processed_sfp
["classifications"] = classifications_in_sfp
2346 return processed_sfp
2348 def _process_vnfgd_sf(self
, sf
):
2350 # getting name of sf
2351 processed_sf
["id"] = sf
["id"]
2352 # getting sfis in sf
2353 sfis_in_sf
= sf
.get("constituent-profile-elements")
2354 sorted_sfis
= sorted(sfis_in_sf
, key
=lambda i
: i
["order"])
2355 # getting sfis names
2356 processed_sf
["sfis"] = [sfi
["id"] for sfi
in sorted_sfis
]
2360 def _process_vnfgd_sfi(self
, sfi
, db_vnfrs
):
2362 # getting name of sfi
2363 processed_sfi
["id"] = sfi
["id"]
2365 # getting ports in sfi
2366 ingress_port
= sfi
["ingress-constituent-cpd-id"]
2367 egress_port
= sfi
["egress-constituent-cpd-id"]
2368 sfi_vnf_member_index
= sfi
["constituent-base-element-id"]
2370 processed_sfi
["ingress_port"] = ingress_port
2371 processed_sfi
["egress_port"] = egress_port
2373 all_vnfrs
= db_vnfrs
.values()
2377 for element
in all_vnfrs
2378 if element
["member-vnf-index-ref"] == sfi_vnf_member_index
2380 processed_sfi
["vnfr_id"] = sfi_vnfr
[0]["id"]
2382 sfi_vnfr_cp
= sfi_vnfr
[0]["connection-point"]
2384 ingress_port_index
= [
2385 c
for c
, element
in enumerate(sfi_vnfr_cp
) if element
["id"] == ingress_port
2387 ingress_port_index
= ingress_port_index
[0]
2389 processed_sfi
["vdur_id"] = sfi_vnfr_cp
[ingress_port_index
][
2390 "connection-point-vdu-id"
2392 processed_sfi
["ingress_port_index"] = ingress_port_index
2393 processed_sfi
["egress_port_index"] = ingress_port_index
2395 if egress_port
!= ingress_port
:
2396 egress_port_index
= [
2398 for c
, element
in enumerate(sfi_vnfr_cp
)
2399 if element
["id"] == egress_port
2401 processed_sfi
["egress_port_index"] = egress_port_index
2403 return processed_sfi
2405 def _process_vnfgd_classification(self
, classification
, db_vnfrs
):
2406 processed_classification
= {}
2408 processed_classification
= deepcopy(classification
)
2409 classi_vnf_member_index
= processed_classification
[
2410 "constituent-base-element-id"
2412 logical_source_port
= processed_classification
["constituent-cpd-id"]
2414 all_vnfrs
= db_vnfrs
.values()
2418 for element
in all_vnfrs
2419 if element
["member-vnf-index-ref"] == classi_vnf_member_index
2421 processed_classification
["vnfr_id"] = classi_vnfr
[0]["id"]
2423 classi_vnfr_cp
= classi_vnfr
[0]["connection-point"]
2425 ingress_port_index
= [
2427 for c
, element
in enumerate(classi_vnfr_cp
)
2428 if element
["id"] == logical_source_port
2430 ingress_port_index
= ingress_port_index
[0]
2432 processed_classification
["ingress_port_index"] = ingress_port_index
2433 processed_classification
["vdur_id"] = classi_vnfr_cp
[ingress_port_index
][
2434 "connection-point-vdu-id"
2437 return processed_classification
2439 def _update_db_nsr_with_vnffg(self
, processed_vnffg
, vim_info
, nsr_id
):
2440 """This method used to add viminfo dict to sfi, sf sfp and classification in indata and count info in db_nsr.
2443 processed_vnffg (Dict[str, Any]): deployment info
2444 vim_info (Dict): dictionary to store VIM resource information
2445 nsr_id (str): NSR id
2453 nsr_classification
= {}
2454 db_nsr_vnffg
= deepcopy(processed_vnffg
)
2456 for count
, sfi
in enumerate(processed_vnffg
["sfi"]):
2457 sfi
["vim_info"] = vim_info
2458 sfi_count
= "sfi.{}".format(count
)
2459 nsr_sfi
[sfi_count
] = db_nsr_vnffg
["sfi"][count
]
2461 self
.db
.set_list("nsrs", {"_id": nsr_id
}, nsr_sfi
)
2463 for count
, sf
in enumerate(processed_vnffg
["sf"]):
2464 sf
["vim_info"] = vim_info
2465 sf_count
= "sf.{}".format(count
)
2466 nsr_sf
[sf_count
] = db_nsr_vnffg
["sf"][count
]
2468 self
.db
.set_list("nsrs", {"_id": nsr_id
}, nsr_sf
)
2470 for count
, sfp
in enumerate(processed_vnffg
["sfp"]):
2471 sfp
["vim_info"] = vim_info
2472 sfp_count
= "sfp.{}".format(count
)
2473 nsr_sfp
[sfp_count
] = db_nsr_vnffg
["sfp"][count
]
2475 self
.db
.set_list("nsrs", {"_id": nsr_id
}, nsr_sfp
)
2477 for count
, classi
in enumerate(processed_vnffg
["classification"]):
2478 classi
["vim_info"] = vim_info
2479 classification_count
= "classification.{}".format(count
)
2480 nsr_classification
[classification_count
] = db_nsr_vnffg
["classification"][
2484 self
.db
.set_list("nsrs", {"_id": nsr_id
}, nsr_classification
)
2486 def process_vnffgd_descriptor(
2493 """This method used to process vnffgd parameters from descriptor.
2496 indata (Dict[str, Any]): deployment info
2497 nsr_id (str): NSR id
2498 db_nsr: NSR record from DB
2499 db_vnfrs: VNFRS record from DB
2502 Dict: Processed vnffg parameters.
2505 processed_vnffg
= {}
2506 vnffgd
= db_nsr
.get("nsd", {}).get("vnffgd")
2507 vnf_list
= indata
.get("vnf", [])
2511 vim_text
= "vim:" + vnf_list
[0].get("vim-account-id", "")
2514 vim_info
[vim_text
] = {}
2516 processed_classifications
= []
2520 # setting up intial empty entries for vnffg items in mongodb.
2528 "classification": [],
2534 sfps
= vnffg
.get("nfpd")
2536 processed_sfp
= self
._process
_vnfgd
_sfp
(sfp
)
2537 # appending the list of processed sfps
2538 processed_sfps
.append(processed_sfp
)
2540 # getting sfs in sfp
2541 sfs
= sfp
.get("position-desc-id")[0].get("cp-profile-id")
2543 processed_sf
= self
._process
_vnfgd
_sf
(sf
)
2545 # appending the list of processed sfs
2546 processed_sfs
.append(processed_sf
)
2548 # getting sfis in sf
2549 sfis_in_sf
= sf
.get("constituent-profile-elements")
2550 sorted_sfis
= sorted(sfis_in_sf
, key
=lambda i
: i
["order"])
2552 for sfi
in sorted_sfis
:
2553 processed_sfi
= self
._process
_vnfgd
_sfi
(sfi
, db_vnfrs
)
2555 processed_sfis
.append(processed_sfi
)
2557 classifications
= sfp
.get("position-desc-id")[0].get("match-attributes")
2558 # getting classifications from sfp
2559 for classification
in classifications
:
2560 processed_classification
= self
._process
_vnfgd
_classification
(
2561 classification
, db_vnfrs
2564 processed_classifications
.append(processed_classification
)
2566 processed_vnffg
["sfi"] = processed_sfis
2567 processed_vnffg
["sf"] = processed_sfs
2568 processed_vnffg
["classification"] = processed_classifications
2569 processed_vnffg
["sfp"] = processed_sfps
2571 # adding viminfo dict to sfi, sf sfp and classification
2572 self
._update
_db
_nsr
_with
_vnffg
(processed_vnffg
, vim_info
, nsr_id
)
2574 # updating indata with vnffg porcessed parameters
2575 indata
["vnffg"].append(processed_vnffg
)
2577 def calculate_all_differences_to_deploy(
2587 tasks_by_target_record_id
,
2589 """This method calculates the ordered list of items (`changes_list`)
2590 to be created and deleted.
2593 indata (Dict[str, Any]): deployment info
2594 nsr_id (str): NSR id
2595 db_nsr: NSR record from DB
2596 db_vnfrs: VNFRS record from DB
2597 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
2598 db_nsr_update (Dict[str, Any]): NSR info to update in DB
2599 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
2600 action_id (str): action id
2601 tasks_by_target_record_id (Dict[str, Any]):
2602 [<target_record_id>, <task>]
2605 List: ordered list of items to be created and deleted.
2609 # set list with diffs:
2612 # processing vnffg from descriptor parameter
2613 vnffgd
= db_nsr
.get("nsd").get("vnffgd")
2614 if vnffgd
is not None:
2615 indata
["vnffg"] = []
2616 vnf_list
= indata
["vnf"]
2617 processed_vnffg
= {}
2619 # in case of ns-delete
2621 processed_vnffg
["sfi"] = []
2622 processed_vnffg
["sf"] = []
2623 processed_vnffg
["classification"] = []
2624 processed_vnffg
["sfp"] = []
2626 indata
["vnffg"].append(processed_vnffg
)
2629 self
.process_vnffgd_descriptor(
2636 # getting updated db_nsr having vnffg parameters
2637 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
2640 "After processing vnffd parameters indata={} nsr={}".format(
2645 for item
in ["sfp", "classification", "sf", "sfi"]:
2646 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
2647 diff_items
, task_index
= self
.calculate_diff_items(
2650 db_ro_nsr
=db_ro_nsr
,
2651 db_nsr_update
=db_nsr_update
,
2653 tasks_by_target_record_id
=tasks_by_target_record_id
,
2654 action_id
=action_id
,
2656 task_index
=task_index
,
2659 changes_list
+= diff_items
2661 # NS vld, image and flavor
2666 "affinity-or-anti-affinity-group",
2668 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
2669 diff_items
, task_index
= self
.calculate_diff_items(
2672 db_ro_nsr
=db_ro_nsr
,
2673 db_nsr_update
=db_nsr_update
,
2675 tasks_by_target_record_id
=tasks_by_target_record_id
,
2676 action_id
=action_id
,
2678 task_index
=task_index
,
2681 changes_list
+= diff_items
2684 for vnfr_id
, vnfr
in db_vnfrs
.items():
2685 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
2686 for item
in ["net", "vdu", "shared-volumes"]:
2687 self
.logger
.debug("process VNF={} {}".format(vnfr_id
, item
))
2688 diff_items
, task_index
= self
.calculate_diff_items(
2691 db_ro_nsr
=db_ro_nsr
,
2692 db_nsr_update
=db_vnfrs_update
[vnfr
["_id"]],
2694 tasks_by_target_record_id
=tasks_by_target_record_id
,
2695 action_id
=action_id
,
2697 task_index
=task_index
,
2701 changes_list
+= diff_items
2705 def define_all_tasks(
2709 tasks_by_target_record_id
,
2711 """Function to create all the task structures obtanied from
2712 the method calculate_all_differences_to_deploy
2715 changes_list (List): ordered list of items to be created or deleted
2716 db_new_tasks (List): tasks list to be created
2717 action_id (str): action id
2718 tasks_by_target_record_id (Dict[str, Any]):
2719 [<target_record_id>, <task>]
2723 for change
in changes_list
:
2724 task
= Ns
._create
_task
(
2725 deployment_info
=change
["deployment_info"],
2726 target_id
=change
["target_id"],
2727 item
=change
["item"],
2728 action
=change
["action"],
2729 target_record
=change
["target_record"],
2730 target_record_id
=change
["target_record_id"],
2731 extra_dict
=change
.get("extra_dict", None),
2734 self
.logger
.debug("ns.define_all_tasks task={}".format(task
))
2735 tasks_by_target_record_id
[change
["target_record_id"]] = task
2736 db_new_tasks
.append(task
)
2738 if change
.get("common_id"):
2739 task
["common_id"] = change
["common_id"]
2741 def upload_all_tasks(
2746 """Function to save all tasks in the common DB
2749 db_new_tasks (List): tasks list to be created
2750 now (time): current time
2754 nb_ro_tasks
= 0 # for logging
2756 for db_task
in db_new_tasks
:
2757 target_id
= db_task
.pop("target_id")
2758 common_id
= db_task
.get("common_id")
2760 # Do not chek tasks with vim_status DELETED
2761 # because in manual heealing there are two tasks for the same vdur:
2762 # one with vim_status deleted and the other one with the actual VM status.
2768 "target_id": target_id
,
2769 "tasks.common_id": common_id
,
2770 "vim_info.vim_status.ne": "DELETED",
2772 update_dict
={"to_check_at": now
, "modified_at": now
},
2773 push
={"tasks": db_task
},
2774 fail_on_empty
=False,
2778 if not self
.db
.set_one(
2781 "target_id": target_id
,
2782 "tasks.target_record": db_task
["target_record"],
2783 "vim_info.vim_status.ne": "DELETED",
2785 update_dict
={"to_check_at": now
, "modified_at": now
},
2786 push
={"tasks": db_task
},
2787 fail_on_empty
=False,
2790 self
.logger
.debug("Updating database, Creating ro_tasks")
2791 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2793 self
.db
.create("ro_tasks", db_ro_task
)
2796 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2797 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2801 def upload_recreate_tasks(
2806 """Function to save recreate tasks in the common DB
2809 db_new_tasks (List): tasks list to be created
2810 now (time): current time
2814 nb_ro_tasks
= 0 # for logging
2816 for db_task
in db_new_tasks
:
2817 target_id
= db_task
.pop("target_id")
2818 self
.logger
.debug("target_id={} db_task={}".format(target_id
, db_task
))
2820 action
= db_task
.get("action", None)
2823 self
.logger
.debug("Updating database, Creating ro_tasks")
2824 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
2826 # If DELETE task: the associated created items should be removed
2827 # (except persistent volumes):
2828 if action
== "DELETE":
2829 db_ro_task
["vim_info"]["created"] = True
2830 db_ro_task
["vim_info"]["created_items"] = db_task
.get(
2833 db_ro_task
["vim_info"]["volumes_to_hold"] = db_task
.get(
2834 "volumes_to_hold", []
2836 db_ro_task
["vim_info"]["vim_id"] = db_task
.get("vim_id", None)
2839 self
.logger
.debug("upload_all_tasks db_ro_task={}".format(db_ro_task
))
2840 self
.db
.create("ro_tasks", db_ro_task
)
2843 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
2844 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
2848 def _prepare_created_items_for_healing(
2854 # Get created_items from ro_task
2855 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
2856 for ro_task
in ro_tasks
:
2857 for task
in ro_task
["tasks"]:
2859 task
["target_record"] == target_record
2860 and task
["action"] == "CREATE"
2861 and ro_task
["vim_info"]["created_items"]
2863 created_items
= ro_task
["vim_info"]["created_items"]
2866 return created_items
2868 def _prepare_persistent_volumes_for_healing(
2873 # The associated volumes of the VM shouldn't be removed
2876 vim_details_text
= existing_vdu
["vim_info"][target_id
].get("vim_details", None)
2877 if vim_details_text
:
2878 vim_details
= yaml
.safe_load(f
"{vim_details_text}")
2880 for vol_id
in vim_details
.get("os-extended-volumes:volumes_attached", []):
2881 volumes_list
.append(vol_id
["id"])
2885 def prepare_changes_to_recreate(
2893 tasks_by_target_record_id
,
2895 """This method will obtain an ordered list of items (`changes_list`)
2896 to be created and deleted to meet the recreate request.
2900 "ns.prepare_changes_to_recreate nsr_id={} indata={}".format(nsr_id
, indata
)
2904 # set list with diffs:
2906 db_path
= self
.db_path_map
["vdu"]
2907 target_list
= indata
.get("healVnfData", {})
2908 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
2909 ro_nsr_public_key
= db_ro_nsr
["public_key"]
2911 # Check each VNF of the target
2912 for target_vnf
in target_list
:
2913 # Find this VNF in the list from DB, raise exception if vnfInstanceId is not found
2914 vnfr_id
= target_vnf
["vnfInstanceId"]
2915 existing_vnf
= db_vnfrs
.get(vnfr_id
, {})
2916 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
2917 # vim_account_id = existing_vnf.get("vim-account-id", "")
2919 target_vdus
= target_vnf
.get("additionalParams", {}).get("vdu", [])
2920 # Check each VDU of this VNF
2922 # Create target_vdu_list from DB, if VDUs are not specified
2924 for existing_vdu
in existing_vnf
.get("vdur"):
2925 vdu_name
= existing_vdu
.get("vdu-name", None)
2926 vdu_index
= existing_vdu
.get("count-index", 0)
2927 vdu_to_be_healed
= {"vdu-id": vdu_name
, "count-index": vdu_index
}
2928 target_vdus
.append(vdu_to_be_healed
)
2929 for target_vdu
in target_vdus
:
2930 vdu_name
= target_vdu
.get("vdu-id", None)
2931 # For multi instance VDU count-index is mandatory
2932 # For single session VDU count-indes is 0
2933 count_index
= target_vdu
.get("count-index", 0)
2935 existing_instance
= {}
2937 for instance
in existing_vnf
.get("vdur", {}):
2939 instance
["vdu-name"] == vdu_name
2940 and instance
["count-index"] == count_index
2942 existing_instance
= instance
2947 target_record_id
= "{}.{}".format(db_record
, existing_instance
["id"])
2949 # The target VIM is the one already existing in DB to recreate
2950 for target_vim
, target_viminfo
in existing_instance
.get(
2953 # step 1 vdu to be deleted
2954 self
._assign
_vim
(target_vim
)
2956 "action_id": action_id
,
2958 "task_index": task_index
,
2961 target_record
= f
"{db_record}.{item_index}.vim_info.{target_vim}"
2962 created_items
= self
._prepare
_created
_items
_for
_healing
(
2963 nsr_id
, target_record
2966 volumes_to_hold
= self
._prepare
_persistent
_volumes
_for
_healing
(
2967 target_vim
, existing_instance
2970 # Specific extra params for recreate tasks:
2972 "created_items": created_items
,
2973 "vim_id": existing_instance
["vim-id"],
2974 "volumes_to_hold": volumes_to_hold
,
2977 changes_list
.append(
2979 "deployment_info": deployment_info
,
2980 "target_id": target_vim
,
2983 "target_record": target_record
,
2984 "target_record_id": target_record_id
,
2985 "extra_dict": extra_dict
,
2988 delete_task_id
= f
"{action_id}:{task_index}"
2991 # step 2 vdu to be created
2997 "vnfr": existing_vnf
,
2998 "vdu2cloud_init": vdu2cloud_init
,
2999 "tasks_by_target_record_id": tasks_by_target_record_id
,
3000 "logger": self
.logger
,
3003 "ro_nsr_public_key": ro_nsr_public_key
,
3007 extra_dict
= self
._process
_recreate
_vdu
_params
(
3016 # The CREATE task depens on the DELETE task
3017 extra_dict
["depends_on"] = [delete_task_id
]
3019 # Add volumes created from created_items if any
3020 # Ports should be deleted with delete task and automatically created with create task
3022 for k
, v
in created_items
.items():
3024 k_item
, _
, k_id
= k
.partition(":")
3025 if k_item
== "volume":
3027 except Exception as e
:
3029 "Error evaluating created item {}: {}".format(k
, e
)
3031 extra_dict
["previous_created_volumes"] = volumes
3034 "action_id": action_id
,
3036 "task_index": task_index
,
3038 self
._assign
_vim
(target_vim
)
3041 "deployment_info": deployment_info
,
3042 "target_id": target_vim
,
3045 "target_record": target_record
,
3046 "target_record_id": target_record_id
,
3047 "extra_dict": extra_dict
,
3049 changes_list
.append(new_item
)
3050 tasks_by_target_record_id
[target_record_id
] = new_item
3055 def recreate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3056 self
.logger
.debug("ns.recreate nsr_id={} indata={}".format(nsr_id
, indata
))
3057 # TODO: validate_input(indata, recreate_schema)
3058 action_id
= indata
.get("action_id", str(uuid4()))
3059 # get current deployment
3060 db_vnfrs
= {} # vnf's info indexed by _id
3062 logging_text
= "Recreate nsr_id={} action_id={} indata={}".format(
3063 nsr_id
, action_id
, indata
3065 self
.logger
.debug(logging_text
+ "Enter")
3068 step
= "Getting ns and vnfr record from db"
3069 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
3071 tasks_by_target_record_id
= {}
3072 # read from db: vnf's of this ns
3073 step
= "Getting vnfrs from db"
3074 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
3075 self
.logger
.debug("ns.recreate: db_vnfrs_list={}".format(db_vnfrs_list
))
3077 if not db_vnfrs_list
:
3078 raise NsException("Cannot obtain associated VNF for ns")
3080 for vnfr
in db_vnfrs_list
:
3081 db_vnfrs
[vnfr
["_id"]] = vnfr
3084 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
3085 self
.logger
.debug("ns.recreate: db_ro_nsr={}".format(db_ro_nsr
))
3088 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
3090 with self
.write_lock
:
3092 step
= "process NS elements"
3093 changes_list
= self
.prepare_changes_to_recreate(
3098 db_ro_nsr
=db_ro_nsr
,
3099 action_id
=action_id
,
3100 tasks_by_target_record_id
=tasks_by_target_record_id
,
3103 self
.define_all_tasks(
3104 changes_list
=changes_list
,
3105 db_new_tasks
=db_new_tasks
,
3106 tasks_by_target_record_id
=tasks_by_target_record_id
,
3109 # Delete all ro_tasks registered for the targets vdurs (target_record)
3110 # If task of type CREATE exist then vim will try to get info form deleted VMs.
3111 # So remove all task related to target record.
3112 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
3113 for change
in changes_list
:
3114 for ro_task
in ro_tasks
:
3115 for task
in ro_task
["tasks"]:
3116 if task
["target_record"] == change
["target_record"]:
3120 "_id": ro_task
["_id"],
3121 "modified_at": ro_task
["modified_at"],
3123 fail_on_empty
=False,
3126 step
= "Updating database, Appending tasks to ro_tasks"
3127 self
.upload_recreate_tasks(
3128 db_new_tasks
=db_new_tasks
,
3133 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3137 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3141 except Exception as e
:
3142 if isinstance(e
, (DbException
, NsException
)):
3144 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3147 e
= traceback_format_exc()
3148 self
.logger
.critical(
3149 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3153 raise NsException(e
)
3155 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3156 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
3157 validate_input(indata
, deploy_schema
)
3158 action_id
= indata
.get("action_id", str(uuid4()))
3160 # get current deployment
3161 db_nsr_update
= {} # update operation on nsrs
3162 db_vnfrs_update
= {}
3163 db_vnfrs
= {} # vnf's info indexed by _id
3165 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
3166 self
.logger
.debug(logging_text
+ "Enter")
3169 step
= "Getting ns and vnfr record from db"
3170 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
3171 self
.logger
.debug("ns.deploy: db_nsr={}".format(db_nsr
))
3173 tasks_by_target_record_id
= {}
3174 # read from db: vnf's of this ns
3175 step
= "Getting vnfrs from db"
3176 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
3178 if not db_vnfrs_list
:
3179 raise NsException("Cannot obtain associated VNF for ns")
3181 for vnfr
in db_vnfrs_list
:
3182 db_vnfrs
[vnfr
["_id"]] = vnfr
3183 db_vnfrs_update
[vnfr
["_id"]] = {}
3184 self
.logger
.debug("ns.deploy db_vnfrs={}".format(db_vnfrs
))
3187 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
3190 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
3192 # check that action_id is not in the list of actions. Suffixed with :index
3193 if action_id
in db_ro_nsr
["actions"]:
3197 new_action_id
= "{}:{}".format(action_id
, index
)
3199 if new_action_id
not in db_ro_nsr
["actions"]:
3200 action_id
= new_action_id
3203 + "Changing action_id in use to {}".format(action_id
)
3209 def _process_action(indata
):
3210 nonlocal db_new_tasks
3217 if indata
["action"]["action"] == "inject_ssh_key":
3218 key
= indata
["action"].get("key")
3219 user
= indata
["action"].get("user")
3220 password
= indata
["action"].get("password")
3222 for vnf
in indata
.get("vnf", ()):
3223 if vnf
["_id"] not in db_vnfrs
:
3224 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
3226 db_vnfr
= db_vnfrs
[vnf
["_id"]]
3228 for target_vdu
in vnf
.get("vdur", ()):
3229 vdu_index
, vdur
= next(
3232 for i_v
in enumerate(db_vnfr
["vdur"])
3233 if i_v
[1]["id"] == target_vdu
["id"]
3240 "Invalid vdu vnf={}.{}".format(
3241 vnf
["_id"], target_vdu
["id"]
3245 target_vim
, vim_info
= next(
3246 k_v
for k_v
in vdur
["vim_info"].items()
3248 self
._assign
_vim
(target_vim
)
3249 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
3250 vnf
["_id"], vdu_index
3254 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
3257 "ip_address": vdur
.get("ip-address"),
3260 "password": password
,
3261 "private_key": db_ro_nsr
["private_key"],
3262 "salt": db_ro_nsr
["_id"],
3263 "schema_version": db_ro_nsr
["_admin"][
3270 "action_id": action_id
,
3272 "task_index": task_index
,
3275 task
= Ns
._create
_task
(
3276 deployment_info
=deployment_info
,
3277 target_id
=target_vim
,
3280 target_record
=target_record
,
3281 target_record_id
=None,
3282 extra_dict
=extra_dict
,
3285 task_index
= deployment_info
.get("task_index")
3287 db_new_tasks
.append(task
)
3289 with self
.write_lock
:
3290 if indata
.get("action"):
3291 _process_action(indata
)
3293 # compute network differences
3295 step
= "process NS elements"
3296 changes_list
= self
.calculate_all_differences_to_deploy(
3301 db_ro_nsr
=db_ro_nsr
,
3302 db_nsr_update
=db_nsr_update
,
3303 db_vnfrs_update
=db_vnfrs_update
,
3304 action_id
=action_id
,
3305 tasks_by_target_record_id
=tasks_by_target_record_id
,
3307 self
.define_all_tasks(
3308 changes_list
=changes_list
,
3309 db_new_tasks
=db_new_tasks
,
3310 tasks_by_target_record_id
=tasks_by_target_record_id
,
3313 step
= "Updating database, Appending tasks to ro_tasks"
3314 self
.upload_all_tasks(
3315 db_new_tasks
=db_new_tasks
,
3319 step
= "Updating database, nsrs"
3321 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
3323 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
3325 step
= "Updating database, vnfrs={}".format(vnfr_id
)
3326 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
3329 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3333 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3337 except Exception as e
:
3338 if isinstance(e
, (DbException
, NsException
)):
3340 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3343 e
= traceback_format_exc()
3344 self
.logger
.critical(
3345 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3349 raise NsException(e
)
3351 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3352 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
3353 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
3355 with self
.write_lock
:
3357 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
3358 except NsWorkerException
as e
:
3359 raise NsException(e
)
3361 return None, None, True
3363 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
3365 "ns.status version={} nsr_id={}, action_id={} indata={}".format(
3366 version
, nsr_id
, action_id
, indata
3372 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
3373 global_status
= "DONE"
3376 for ro_task
in ro_tasks
:
3377 for task
in ro_task
["tasks"]:
3378 if task
and task
["action_id"] == action_id
:
3379 task_list
.append(task
)
3382 if task
["status"] == "FAILED":
3383 global_status
= "FAILED"
3384 error_text
= "Error at {} {}: {}".format(
3385 task
["action"].lower(),
3387 ro_task
["vim_info"].get("vim_message") or "unknown",
3389 details
.append(error_text
)
3390 elif task
["status"] in ("SCHEDULED", "BUILD"):
3391 if global_status
!= "FAILED":
3392 global_status
= "BUILD"
3397 "status": global_status
,
3399 ". ".join(details
) if details
else "progress {}/{}".format(done
, total
)
3402 "action_id": action_id
,
3406 return return_data
, None, True
3408 def recreate_status(
3409 self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
3411 return self
.status(session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
)
3413 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
3415 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
3416 session
, indata
, version
, nsr_id
, action_id
3420 return None, None, True
3422 def rebuild_start_stop_task(
3433 self
._assign
_vim
(target_vim
)
3434 target_record
= "vnfrs:{}:vdur.{}.vim_info.{}".format(
3435 vnf_id
, vdu_index
, target_vim
3437 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf_id
, vdu_id
)
3439 "action_id": action_id
,
3441 "task_index": task_index
,
3444 task
= Ns
._create
_task
(
3445 deployment_info
=deployment_info
,
3446 target_id
=target_vim
,
3449 target_record
=target_record
,
3450 target_record_id
=target_record_id
,
3451 extra_dict
=extra_dict
,
3455 def rebuild_start_stop(
3456 self
, session
, action_dict
, version
, nsr_id
, *args
, **kwargs
3461 action_id
= action_dict
.get("action_id", str(uuid4()))
3463 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
3464 self
.logger
.debug(logging_text
+ "Enter")
3466 action
= list(action_dict
.keys())[0]
3467 task_dict
= action_dict
.get(action
)
3468 vim_vm_id
= action_dict
.get(action
).get("vim_vm_id")
3470 if action_dict
.get("stop"):
3474 step
= "lock the operation & do task creation"
3475 with self
.write_lock
:
3476 extra_dict
["params"] = {
3477 "vim_vm_id": vim_vm_id
,
3480 task
= self
.rebuild_start_stop_task(
3481 task_dict
["vdu_id"],
3482 task_dict
["vnf_id"],
3483 task_dict
["vdu_index"],
3487 task_dict
["target_vim"],
3490 db_new_tasks
.append(task
)
3491 step
= "upload Task to db"
3492 self
.upload_all_tasks(
3493 db_new_tasks
=db_new_tasks
,
3497 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3500 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3504 except Exception as e
:
3505 if isinstance(e
, (DbException
, NsException
)):
3507 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3510 e
= traceback_format_exc()
3511 self
.logger
.critical(
3512 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3515 raise NsException(e
)
3517 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
3518 nsrs
= self
.db
.get_list("nsrs", {})
3522 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
3524 return return_data
, None, True
3526 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
3527 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
3530 for ro_task
in ro_tasks
:
3531 for task
in ro_task
["tasks"]:
3532 if task
["action_id"] not in return_data
:
3533 return_data
.append(task
["action_id"])
3535 return return_data
, None, True
3538 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
3540 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
3541 self
._assign
_vim
(target_vim
)
3542 target_record
= "vnfrs:{}:vdur.{}.vim_info.{}".format(
3543 vnf
["_id"], vdu_index
, target_vim
3545 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
3547 "action_id": action_id
,
3549 "task_index": task_index
,
3552 task
= Ns
._create
_task
(
3553 deployment_info
=deployment_info
,
3554 target_id
=target_vim
,
3557 target_record
=target_record
,
3558 target_record_id
=target_record_id
,
3559 extra_dict
=extra_dict
,
3564 def migrate(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3568 action_id
= indata
.get("action_id", str(uuid4()))
3570 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
3571 self
.logger
.debug(logging_text
+ "Enter")
3573 vnf_instance_id
= indata
["vnfInstanceId"]
3574 step
= "Getting vnfrs from db"
3575 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
3576 vdu
= indata
.get("vdu")
3577 migrateToHost
= indata
.get("migrateToHost")
3580 with self
.write_lock
:
3582 vdu_id
= indata
["vdu"]["vduId"]
3583 vdu_count_index
= indata
["vdu"].get("vduCountIndex", 0)
3584 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3586 vdu
["vdu-id-ref"] == vdu_id
3587 and vdu
["count-index"] == vdu_count_index
3589 extra_dict
["params"] = {
3590 "vim_vm_id": vdu
["vim-id"],
3591 "migrate_host": migrateToHost
,
3592 "vdu_vim_info": vdu
["vim_info"],
3594 step
= "Creating migration task for vdu:{}".format(vdu
)
3595 task
= self
.migrate_task(
3604 db_new_tasks
.append(task
)
3608 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3609 extra_dict
["params"] = {
3610 "vim_vm_id": vdu
["vim-id"],
3611 "migrate_host": migrateToHost
,
3612 "vdu_vim_info": vdu
["vim_info"],
3614 step
= "Creating migration task for vdu:{}".format(vdu
)
3615 task
= self
.migrate_task(
3624 db_new_tasks
.append(task
)
3627 self
.upload_all_tasks(
3628 db_new_tasks
=db_new_tasks
,
3633 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3636 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3640 except Exception as e
:
3641 if isinstance(e
, (DbException
, NsException
)):
3643 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3646 e
= traceback_format_exc()
3647 self
.logger
.critical(
3648 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3651 raise NsException(e
)
3653 def verticalscale_task(
3654 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
3656 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
3657 self
._assign
_vim
(target_vim
)
3658 ns_preffix
= "nsrs:{}".format(nsr_id
)
3659 flavor_text
= ns_preffix
+ ":flavor." + vdu
["ns-flavor-id"]
3660 extra_dict
["depends_on"] = [flavor_text
]
3661 extra_dict
["params"].update({"flavor_id": "TASK-" + flavor_text
})
3662 target_record
= "vnfrs:{}:vdur.{}.vim_info.{}".format(
3663 vnf
["_id"], vdu_index
, target_vim
3665 target_record_id
= "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdu
["id"])
3667 "action_id": action_id
,
3669 "task_index": task_index
,
3672 task
= Ns
._create
_task
(
3673 deployment_info
=deployment_info
,
3674 target_id
=target_vim
,
3675 item
="verticalscale",
3677 target_record
=target_record
,
3678 target_record_id
=target_record_id
,
3679 extra_dict
=extra_dict
,
3683 def verticalscale_flavor_task(
3684 self
, vdu
, vnf
, vdu_index
, action_id
, nsr_id
, task_index
, extra_dict
3686 target_vim
, vim_info
= next(k_v
for k_v
in vdu
["vim_info"].items())
3687 self
._assign
_vim
(target_vim
)
3688 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
3689 target_record
= "nsrs:{}:flavor.{}.vim_info.{}".format(
3690 nsr_id
, len(db_nsr
["flavor"]) - 1, target_vim
3692 target_record_id
= "nsrs:{}:flavor.{}".format(nsr_id
, len(db_nsr
["flavor"]) - 1)
3694 "action_id": action_id
,
3696 "task_index": task_index
,
3698 task
= Ns
._create
_task
(
3699 deployment_info
=deployment_info
,
3700 target_id
=target_vim
,
3703 target_record
=target_record
,
3704 target_record_id
=target_record_id
,
3705 extra_dict
=extra_dict
,
3709 def verticalscale(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
3712 flavor_extra_dict
= {}
3714 action_id
= indata
.get("action_id", str(uuid4()))
3716 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
3717 self
.logger
.debug(logging_text
+ "Enter")
3719 VnfFlavorData
= indata
.get("changeVnfFlavorData")
3720 vnf_instance_id
= VnfFlavorData
["vnfInstanceId"]
3721 step
= "Getting vnfrs from db"
3722 db_vnfr
= self
.db
.get_one("vnfrs", {"_id": vnf_instance_id
})
3723 vduid
= VnfFlavorData
["additionalParams"]["vduid"]
3724 vduCountIndex
= VnfFlavorData
["additionalParams"]["vduCountIndex"]
3725 virtualMemory
= VnfFlavorData
["additionalParams"]["virtualMemory"]
3726 numVirtualCpu
= VnfFlavorData
["additionalParams"]["numVirtualCpu"]
3727 sizeOfStorage
= VnfFlavorData
["additionalParams"]["sizeOfStorage"]
3729 "name": vduid
+ "-flv",
3730 "ram": virtualMemory
,
3731 "vcpus": numVirtualCpu
,
3732 "disk": sizeOfStorage
,
3735 "ram": virtualMemory
,
3736 "vcpus": numVirtualCpu
,
3737 "disk": sizeOfStorage
,
3739 flavor_extra_dict
["find_params"] = {"flavor_data": flavor_data
}
3740 flavor_extra_dict
["params"] = {"flavor_data": flavor_dict
}
3742 step
= "Creating Tasks for vertical scaling"
3743 with self
.write_lock
:
3744 for vdu_index
, vdu
in enumerate(db_vnfr
["vdur"]):
3746 vdu
["vdu-id-ref"] == vduid
3747 and vdu
["count-index"] == vduCountIndex
3749 extra_dict
["params"] = {
3750 "vim_vm_id": vdu
["vim-id"],
3751 "flavor_dict": flavor_dict
,
3752 "vdu-id-ref": vdu
["vdu-id-ref"],
3753 "count-index": vdu
["count-index"],
3754 "vnf_instance_id": vnf_instance_id
,
3756 task
= self
.verticalscale_flavor_task(
3765 db_new_tasks
.append(task
)
3767 task
= self
.verticalscale_task(
3776 db_new_tasks
.append(task
)
3779 self
.upload_all_tasks(
3780 db_new_tasks
=db_new_tasks
,
3784 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
3787 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
3791 except Exception as e
:
3792 if isinstance(e
, (DbException
, NsException
)):
3794 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
3797 e
= traceback_format_exc()
3798 self
.logger
.critical(
3799 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
3802 raise NsException(e
)