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 http
import HTTPStatus
21 from random
import choice
as random_choice
22 from threading
import Lock
24 from traceback
import format_exc
as traceback_format_exc
25 from typing
import Any
, Dict
, Tuple
, Type
26 from uuid
import uuid4
28 from cryptography
.hazmat
.backends
import default_backend
as crypto_default_backend
29 from cryptography
.hazmat
.primitives
import serialization
as crypto_serialization
30 from cryptography
.hazmat
.primitives
.asymmetric
import rsa
38 from osm_common
import (
45 version
as common_version
,
47 from osm_common
.dbbase
import DbBase
, DbException
48 from osm_common
.fsbase
import FsBase
, FsException
49 from osm_common
.msgbase
import MsgException
50 from osm_ng_ro
.ns_thread
import deep_get
, NsWorker
, NsWorkerException
51 from osm_ng_ro
.validation
import deploy_schema
, validate_input
53 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
54 min_common_version
= "0.1.16"
57 class NsException(Exception):
58 def __init__(self
, message
, http_code
=HTTPStatus
.BAD_REQUEST
):
59 self
.http_code
= http_code
60 super(Exception, self
).__init
__(message
)
65 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
66 will provide a random one
69 # Try getting docker id. If fails, get pid
71 with
open("/proc/self/cgroup", "r") as f
:
72 text_id_
= f
.readline()
73 _
, _
, text_id
= text_id_
.rpartition("/")
74 text_id
= text_id
.replace("\n", "")[:12]
82 return "".join(random_choice("0123456789abcdef") for _
in range(12))
86 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
89 for point
in v
.split("."):
90 filled
.append(point
.zfill(8))
101 # self.operations = None
103 # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
104 # If done now it will not be linked to parent not getting its handler and level
106 self
.write_lock
= None
107 self
.vims_assigned
= {}
111 self
.process_params_function_map
= {
112 "net": Ns
._process
_net
_params
,
113 "image": Ns
._process
_image
_params
,
114 "flavor": Ns
._process
_flavor
_params
,
115 "vdu": Ns
._process
_vdu
_params
,
124 def init_db(self
, target_version
):
127 def start(self
, config
):
129 Connect to database, filesystem storage, and messaging
130 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
131 :param config: Configuration of db, storage, etc
135 self
.config
["process_id"] = get_process_id() # used for HA identity
136 self
.logger
= logging
.getLogger("ro.ns")
138 # check right version of common
139 if versiontuple(common_version
) < versiontuple(min_common_version
):
141 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
142 common_version
, min_common_version
148 if config
["database"]["driver"] == "mongo":
149 self
.db
= dbmongo
.DbMongo()
150 self
.db
.db_connect(config
["database"])
151 elif config
["database"]["driver"] == "memory":
152 self
.db
= dbmemory
.DbMemory()
153 self
.db
.db_connect(config
["database"])
156 "Invalid configuration param '{}' at '[database]':'driver'".format(
157 config
["database"]["driver"]
162 if config
["storage"]["driver"] == "local":
163 self
.fs
= fslocal
.FsLocal()
164 self
.fs
.fs_connect(config
["storage"])
165 elif config
["storage"]["driver"] == "mongo":
166 self
.fs
= fsmongo
.FsMongo()
167 self
.fs
.fs_connect(config
["storage"])
168 elif config
["storage"]["driver"] is None:
172 "Invalid configuration param '{}' at '[storage]':'driver'".format(
173 config
["storage"]["driver"]
178 if config
["message"]["driver"] == "local":
179 self
.msg
= msglocal
.MsgLocal()
180 self
.msg
.connect(config
["message"])
181 elif config
["message"]["driver"] == "kafka":
182 self
.msg
= msgkafka
.MsgKafka()
183 self
.msg
.connect(config
["message"])
186 "Invalid configuration param '{}' at '[message]':'driver'".format(
187 config
["message"]["driver"]
191 # TODO load workers to deal with exising database tasks
193 self
.write_lock
= Lock()
194 except (DbException
, FsException
, MsgException
) as e
:
195 raise NsException(str(e
), http_code
=e
.http_code
)
197 def get_assigned_vims(self
):
198 return list(self
.vims_assigned
.keys())
203 self
.db
.db_disconnect()
206 self
.fs
.fs_disconnect()
209 self
.msg
.disconnect()
211 self
.write_lock
= None
212 except (DbException
, FsException
, MsgException
) as e
:
213 raise NsException(str(e
), http_code
=e
.http_code
)
215 for worker
in self
.workers
:
216 worker
.insert_task(("terminate",))
218 def _create_worker(self
):
220 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
221 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
222 return the index of the assigned worker thread. Worker threads are storead at self.workers
224 # Look for a thread in idle status
228 for i
in range(len(self
.workers
))
229 if self
.workers
[i
] and self
.workers
[i
].idle
234 if worker_id
is not None:
235 # unset idle status to avoid race conditions
236 self
.workers
[worker_id
].idle
= False
238 worker_id
= len(self
.workers
)
240 if worker_id
< self
.config
["global"]["server.ns_threads"]:
241 # create a new worker
243 NsWorker(worker_id
, self
.config
, self
.plugins
, self
.db
)
245 self
.workers
[worker_id
].start()
247 # reached maximum number of threads, assign VIM to an existing one
248 worker_id
= self
.next_worker
249 self
.next_worker
= (self
.next_worker
+ 1) % self
.config
["global"][
255 def assign_vim(self
, target_id
):
256 with self
.write_lock
:
257 return self
._assign
_vim
(target_id
)
259 def _assign_vim(self
, target_id
):
260 if target_id
not in self
.vims_assigned
:
261 worker_id
= self
.vims_assigned
[target_id
] = self
._create
_worker
()
262 self
.workers
[worker_id
].insert_task(("load_vim", target_id
))
264 def reload_vim(self
, target_id
):
265 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
266 # this is because database VIM information is cached for threads working with SDN
267 with self
.write_lock
:
268 for worker
in self
.workers
:
269 if worker
and not worker
.idle
:
270 worker
.insert_task(("reload_vim", target_id
))
272 def unload_vim(self
, target_id
):
273 with self
.write_lock
:
274 return self
._unload
_vim
(target_id
)
276 def _unload_vim(self
, target_id
):
277 if target_id
in self
.vims_assigned
:
278 worker_id
= self
.vims_assigned
[target_id
]
279 self
.workers
[worker_id
].insert_task(("unload_vim", target_id
))
280 del self
.vims_assigned
[target_id
]
282 def check_vim(self
, target_id
):
283 with self
.write_lock
:
284 if target_id
in self
.vims_assigned
:
285 worker_id
= self
.vims_assigned
[target_id
]
287 worker_id
= self
._create
_worker
()
289 worker
= self
.workers
[worker_id
]
290 worker
.insert_task(("check_vim", target_id
))
292 def unload_unused_vims(self
):
293 with self
.write_lock
:
296 for target_id
in self
.vims_assigned
:
297 if not self
.db
.get_one(
300 "target_id": target_id
,
301 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
305 vims_to_unload
.append(target_id
)
307 for target_id
in vims_to_unload
:
308 self
._unload
_vim
(target_id
)
316 """This method reads cloud init from a file.
318 Note: Not used as cloud init content is provided in the http body.
321 db (Type[DbBase]): [description]
322 fs (Type[FsBase]): [description]
323 location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
326 NsException: [description]
327 NsException: [description]
332 vnfd_id
, _
, other
= location
.partition(":")
333 _type
, _
, name
= other
.partition(":")
334 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
337 base_folder
= vnfd
["_admin"]["storage"]
338 cloud_init_file
= "{}/{}/cloud_init/{}".format(
339 base_folder
["folder"], base_folder
["pkg-dir"], name
344 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
349 with fs
.file_open(cloud_init_file
, "r") as ci_file
:
350 cloud_init_content
= ci_file
.read()
352 cloud_init_content
= vnfd
["vdu"][int(name
)]["cloud-init"]
354 raise NsException("Mismatch descriptor for cloud init: {}".format(location
))
356 return cloud_init_content
360 cloud_init_content
: str,
361 params
: Dict
[str, Any
],
364 """Function that processes the cloud init to replace Jinja2 encoded parameters.
367 cloud_init_content (str): [description]
368 params (Dict[str, Any]): [description]
369 context (str): [description]
372 NsException: [description]
373 NsException: [description]
379 env
= Environment(undefined
=StrictUndefined
)
380 template
= env
.from_string(cloud_init_content
)
382 return template
.render(params
or {})
383 except UndefinedError
as e
:
385 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
386 "inside the 'additionalParamsForVnf' block".format(e
, context
)
388 except (TemplateError
, TemplateNotFound
) as e
:
390 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
395 def _create_db_ro_nsrs(self
, nsr_id
, now
):
397 key
= rsa
.generate_private_key(
398 backend
=crypto_default_backend(), public_exponent
=65537, key_size
=2048
400 private_key
= key
.private_bytes(
401 crypto_serialization
.Encoding
.PEM
,
402 crypto_serialization
.PrivateFormat
.PKCS8
,
403 crypto_serialization
.NoEncryption(),
405 public_key
= key
.public_key().public_bytes(
406 crypto_serialization
.Encoding
.OpenSSH
,
407 crypto_serialization
.PublicFormat
.OpenSSH
,
409 private_key
= private_key
.decode("utf8")
410 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
411 i
= private_key
.find("\n")
412 private_key
= "-----BEGIN RSA PRIVATE KEY-----" + private_key
[i
:]
413 public_key
= public_key
.decode("utf8")
414 except Exception as e
:
415 raise NsException("Cannot create ssh-keys: {}".format(e
))
417 schema_version
= "1.1"
418 private_key_encrypted
= self
.db
.encrypt(
419 private_key
, schema_version
=schema_version
, salt
=nsr_id
426 "schema_version": schema_version
,
428 "public_key": public_key
,
429 "private_key": private_key_encrypted
,
432 self
.db
.create("ro_nsrs", db_content
)
438 deployment_info
: Dict
[str, Any
],
443 target_record_id
: str,
444 extra_dict
: Dict
[str, Any
] = None,
446 """Function to create task dict from deployment information.
449 deployment_info (Dict[str, Any]): [description]
450 target_id (str): [description]
451 item (str): [description]
452 action (str): [description]
453 target_record (str): [description]
454 target_record_id (str): [description]
455 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
458 Dict[str, Any]: [description]
461 "target_id": target_id
, # it will be removed before pushing at database
462 "action_id": deployment_info
.get("action_id"),
463 "nsr_id": deployment_info
.get("nsr_id"),
464 "task_id": f
"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
465 "status": "SCHEDULED",
468 "target_record": target_record
,
469 "target_record_id": target_record_id
,
473 task
.update(extra_dict
) # params, find_params, depends_on
475 deployment_info
["task_index"] = deployment_info
.get("task_index", 0) + 1
482 task
: Dict
[str, Any
],
484 """Function to create an RO task from task information.
487 target_id (str): [description]
488 task (Dict[str, Any]): [description]
491 Dict[str, Any]: [description]
495 _id
= task
.get("task_id")
500 "target_id": target_id
,
503 "created_items": None,
519 def _process_image_params(
520 target_image
: Dict
[str, Any
],
521 indata
: Dict
[str, Any
],
522 vim_info
: Dict
[str, Any
],
523 target_record_id
: str,
524 **kwargs
: Dict
[str, Any
],
526 """Function to process VDU image parameters.
529 target_image (Dict[str, Any]): [description]
530 indata (Dict[str, Any]): [description]
531 vim_info (Dict[str, Any]): [description]
532 target_record_id (str): [description]
535 Dict[str, Any]: [description]
539 if target_image
.get("image"):
540 find_params
["filter_dict"] = {"name": target_image
.get("image")}
542 if target_image
.get("vim_image_id"):
543 find_params
["filter_dict"] = {"id": target_image
.get("vim_image_id")}
545 if target_image
.get("image_checksum"):
546 find_params
["filter_dict"] = {
547 "checksum": target_image
.get("image_checksum")
550 return {"find_params": find_params
}
553 def _get_resource_allocation_params(
554 quota_descriptor
: Dict
[str, Any
],
556 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
560 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
563 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
567 if quota_descriptor
.get("limit"):
568 quota
["limit"] = int(quota_descriptor
["limit"])
570 if quota_descriptor
.get("reserve"):
571 quota
["reserve"] = int(quota_descriptor
["reserve"])
573 if quota_descriptor
.get("shares"):
574 quota
["shares"] = int(quota_descriptor
["shares"])
579 def _process_guest_epa_quota_params(
580 guest_epa_quota
: Dict
[str, Any
],
583 """Function to extract the guest epa quota parameters.
586 guest_epa_quota (Dict[str, Any]): [description]
587 epa_vcpu_set (bool): [description]
590 Dict[str, Any]: [description]
594 if guest_epa_quota
.get("cpu-quota") and not epa_vcpu_set
:
595 cpuquota
= Ns
._get
_resource
_allocation
_params
(
596 guest_epa_quota
.get("cpu-quota")
600 result
["cpu-quota"] = cpuquota
602 if guest_epa_quota
.get("mem-quota"):
603 vduquota
= Ns
._get
_resource
_allocation
_params
(
604 guest_epa_quota
.get("mem-quota")
608 result
["mem-quota"] = vduquota
610 if guest_epa_quota
.get("disk-io-quota"):
611 diskioquota
= Ns
._get
_resource
_allocation
_params
(
612 guest_epa_quota
.get("disk-io-quota")
616 result
["disk-io-quota"] = diskioquota
618 if guest_epa_quota
.get("vif-quota"):
619 vifquota
= Ns
._get
_resource
_allocation
_params
(
620 guest_epa_quota
.get("vif-quota")
624 result
["vif-quota"] = vifquota
629 def _process_guest_epa_numa_params(
630 guest_epa_quota
: Dict
[str, Any
],
631 ) -> Tuple
[Dict
[str, Any
], bool]:
635 guest_epa_quota (Dict[str, Any]): [description]
638 Tuple[Dict[str, Any], bool]: [description]
643 if guest_epa_quota
.get("numa-node-policy"):
644 numa_node_policy
= guest_epa_quota
.get("numa-node-policy")
646 if numa_node_policy
.get("node"):
647 numa_node
= numa_node_policy
["node"][0]
649 if numa_node
.get("num-cores"):
650 numa
["cores"] = numa_node
["num-cores"]
653 paired_threads
= numa_node
.get("paired-threads", {})
654 if paired_threads
.get("num-paired-threads"):
655 numa
["paired-threads"] = int(
656 numa_node
["paired-threads"]["num-paired-threads"]
660 if paired_threads
.get("paired-thread-ids"):
661 numa
["paired-threads-id"] = []
663 for pair
in paired_threads
["paired-thread-ids"]:
664 numa
["paired-threads-id"].append(
666 str(pair
["thread-a"]),
667 str(pair
["thread-b"]),
671 if numa_node
.get("num-threads"):
672 numa
["threads"] = int(numa_node
["num-threads"])
675 if numa_node
.get("memory-mb"):
676 numa
["memory"] = max(int(int(numa_node
["memory-mb"]) / 1024), 1)
678 return numa
, epa_vcpu_set
681 def _process_guest_epa_cpu_pinning_params(
682 guest_epa_quota
: Dict
[str, Any
],
685 ) -> Tuple
[Dict
[str, Any
], bool]:
689 guest_epa_quota (Dict[str, Any]): [description]
690 vcpu_count (int): [description]
691 epa_vcpu_set (bool): [description]
694 Tuple[Dict[str, Any], bool]: [description]
697 local_epa_vcpu_set
= epa_vcpu_set
700 guest_epa_quota
.get("cpu-pinning-policy") == "DEDICATED"
705 if guest_epa_quota
.get("cpu-thread-pinning-policy") != "PREFER"
707 ] = max(vcpu_count
, 1)
708 local_epa_vcpu_set
= True
710 return numa
, local_epa_vcpu_set
713 def _process_epa_params(
714 target_flavor
: Dict
[str, Any
],
719 target_flavor (Dict[str, Any]): [description]
722 Dict[str, Any]: [description]
727 if target_flavor
.get("guest-epa"):
728 guest_epa
= target_flavor
["guest-epa"]
730 numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_numa
_params
(
731 guest_epa_quota
=guest_epa
734 if guest_epa
.get("mempage-size"):
735 extended
["mempage-size"] = guest_epa
.get("mempage-size")
737 tmp_numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_cpu
_pinning
_params
(
738 guest_epa_quota
=guest_epa
,
739 vcpu_count
=int(target_flavor
.get("vcpu-count", 1)),
740 epa_vcpu_set
=epa_vcpu_set
,
742 numa
.update(tmp_numa
)
745 Ns
._process
_guest
_epa
_quota
_params
(
746 guest_epa_quota
=guest_epa
,
747 epa_vcpu_set
=epa_vcpu_set
,
752 extended
["numas"] = [numa
]
757 def _process_flavor_params(
758 target_flavor
: Dict
[str, Any
],
759 indata
: Dict
[str, Any
],
760 vim_info
: Dict
[str, Any
],
761 target_record_id
: str,
762 **kwargs
: Dict
[str, Any
],
767 target_flavor (Dict[str, Any]): [description]
768 indata (Dict[str, Any]): [description]
769 vim_info (Dict[str, Any]): [description]
770 target_record_id (str): [description]
773 Dict[str, Any]: [description]
776 "disk": int(target_flavor
["storage-gb"]),
777 "ram": int(target_flavor
["memory-mb"]),
778 "vcpus": int(target_flavor
["vcpu-count"]),
782 for vnf
in indata
.get("vnf", []):
783 for vdur
in vnf
.get("vdur", []):
784 if vdur
.get("ns-flavor-id") == target_flavor
["id"]:
787 for storage
in target_vdur
.get("virtual-storages", []):
789 storage
.get("type-of-storage")
790 == "etsi-nfv-descriptors:ephemeral-storage"
792 flavor_data
["ephemeral"] = int(storage
.get("size-of-storage", 0))
793 elif storage
.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
794 flavor_data
["swap"] = int(storage
.get("size-of-storage", 0))
796 extended
= Ns
._process
_epa
_params
(target_flavor
)
798 flavor_data
["extended"] = extended
800 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
801 flavor_data_name
= flavor_data
.copy()
802 flavor_data_name
["name"] = target_flavor
["name"]
803 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
808 def _ip_profile_to_ro(
809 ip_profile
: Dict
[str, Any
],
814 ip_profile (Dict[str, Any]): [description]
817 Dict[str, Any]: [description]
824 if "v4" in ip_profile
.get("ip-version", "ipv4")
826 "subnet_address": ip_profile
.get("subnet-address"),
827 "gateway_address": ip_profile
.get("gateway-address"),
828 "dhcp_enabled": ip_profile
.get("dhcp-params", {}).get("enabled", False),
829 "dhcp_start_address": ip_profile
.get("dhcp-params", {}).get(
830 "start-address", None
832 "dhcp_count": ip_profile
.get("dhcp-params", {}).get("count", None),
835 if ip_profile
.get("dns-server"):
836 ro_ip_profile
["dns_address"] = ";".join(
837 [v
["address"] for v
in ip_profile
["dns-server"] if v
.get("address")]
840 if ip_profile
.get("security-group"):
841 ro_ip_profile
["security_group"] = ip_profile
["security-group"]
846 def _process_net_params(
847 target_vld
: Dict
[str, Any
],
848 indata
: Dict
[str, Any
],
849 vim_info
: Dict
[str, Any
],
850 target_record_id
: str,
851 **kwargs
: Dict
[str, Any
],
853 """Function to process network parameters.
856 target_vld (Dict[str, Any]): [description]
857 indata (Dict[str, Any]): [description]
858 vim_info (Dict[str, Any]): [description]
859 target_record_id (str): [description]
862 Dict[str, Any]: [description]
866 if vim_info
.get("sdn"):
867 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
868 # ns_preffix = "nsrs:{}".format(nsr_id)
869 # remove the ending ".sdn
870 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
871 extra_dict
["params"] = {
873 for k
in ("sdn-ports", "target_vim", "vlds", "type")
877 # TODO needed to add target_id in the dependency.
878 if vim_info
.get("target_vim"):
879 extra_dict
["depends_on"] = [
880 f
"{vim_info.get('target_vim')} {vld_target_record_id}"
885 if vim_info
.get("vim_network_name"):
886 extra_dict
["find_params"] = {
888 "name": vim_info
.get("vim_network_name"),
891 elif vim_info
.get("vim_network_id"):
892 extra_dict
["find_params"] = {
894 "id": vim_info
.get("vim_network_id"),
897 elif target_vld
.get("mgmt-network"):
898 extra_dict
["find_params"] = {
900 "name": target_vld
["id"],
904 extra_dict
["params"] = {
906 f
"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
908 "ip_profile": Ns
._ip
_profile
_to
_ro
(vim_info
.get("ip_profile")),
909 "provider_network_profile": vim_info
.get("provider_network"),
912 if not target_vld
.get("underlay"):
913 extra_dict
["params"]["net_type"] = "bridge"
915 extra_dict
["params"]["net_type"] = (
916 "ptp" if target_vld
.get("type") == "ELINE" else "data"
922 def _process_vdu_params(
923 target_vdu
: Dict
[str, Any
],
924 indata
: Dict
[str, Any
],
925 vim_info
: Dict
[str, Any
],
926 target_record_id
: str,
927 **kwargs
: Dict
[str, Any
],
929 """Function to process VDU parameters.
932 target_vdu (Dict[str, Any]): [description]
933 indata (Dict[str, Any]): [description]
934 vim_info (Dict[str, Any]): [description]
935 target_record_id (str): [description]
938 Dict[str, Any]: [description]
940 vnfr_id
= kwargs
.get("vnfr_id")
941 nsr_id
= kwargs
.get("nsr_id")
942 vnfr
= kwargs
.get("vnfr")
943 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
944 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
945 logger
= kwargs
.get("logger")
946 db
= kwargs
.get("db")
947 fs
= kwargs
.get("fs")
948 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
950 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
951 ns_preffix
= "nsrs:{}".format(nsr_id
)
952 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
953 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
954 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
957 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
958 if interface
.get("ns-vld-id"):
959 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
960 elif interface
.get("vnf-vld-id"):
961 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
964 "Interface {} from vdu {} not connected to any vld".format(
965 iface_index
, target_vdu
["vdu-name"]
969 continue # interface not connected to any vld
971 extra_dict
["depends_on"].append(net_text
)
973 if "port-security-enabled" in interface
:
974 interface
["port_security"] = interface
.pop("port-security-enabled")
976 if "port-security-disable-strategy" in interface
:
977 interface
["port_security_disable_strategy"] = interface
.pop(
978 "port-security-disable-strategy"
983 for x
, v
in interface
.items()
989 "port_security_disable_strategy",
993 net_item
["net_id"] = "TASK-" + net_text
994 net_item
["type"] = "virtual"
996 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
997 # TODO floating_ip: True/False (or it can be None)
998 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
999 # mark the net create task as type data
1001 tasks_by_target_record_id
,
1007 tasks_by_target_record_id
[net_text
]["extra_dict"]["params"][
1011 net_item
["use"] = "data"
1012 net_item
["model"] = interface
["type"]
1013 net_item
["type"] = interface
["type"]
1015 interface
.get("type") == "OM-MGMT"
1016 or interface
.get("mgmt-interface")
1017 or interface
.get("mgmt-vnf")
1019 net_item
["use"] = "mgmt"
1021 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1022 net_item
["use"] = "bridge"
1023 net_item
["model"] = interface
.get("type")
1025 if interface
.get("ip-address"):
1026 net_item
["ip_address"] = interface
["ip-address"]
1028 if interface
.get("mac-address"):
1029 net_item
["mac_address"] = interface
["mac-address"]
1031 net_list
.append(net_item
)
1033 if interface
.get("mgmt-vnf"):
1034 extra_dict
["mgmt_vnf_interface"] = iface_index
1035 elif interface
.get("mgmt-interface"):
1036 extra_dict
["mgmt_vdu_interface"] = iface_index
1041 if target_vdu
.get("cloud-init"):
1042 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1043 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1046 location
=target_vdu
["cloud-init"],
1049 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1050 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1051 cloud_init_content
=cloud_content_
,
1052 params
=target_vdu
.get("additionalParams"),
1053 context
=target_vdu
["cloud-init"],
1056 if target_vdu
.get("boot-data-drive"):
1057 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1061 if target_vdu
.get("ssh-keys"):
1062 ssh_keys
+= target_vdu
.get("ssh-keys")
1064 if target_vdu
.get("ssh-access-required"):
1065 ssh_keys
.append(ro_nsr_public_key
)
1068 cloud_config
["key-pairs"] = ssh_keys
1071 if target_vdu
.get("virtual-storages"):
1073 {"size": disk
["size-of-storage"]}
1074 for disk
in target_vdu
["virtual-storages"]
1075 if disk
.get("type-of-storage")
1076 == "persistent-storage:persistent-storage"
1079 extra_dict
["params"] = {
1080 "name": "{}-{}-{}-{}".format(
1081 indata
["name"][:16],
1082 vnfr
["member-vnf-index-ref"][:16],
1083 target_vdu
["vdu-name"][:32],
1084 target_vdu
.get("count-index") or 0,
1086 "description": target_vdu
["vdu-name"],
1088 "image_id": "TASK-" + image_text
,
1089 "flavor_id": "TASK-" + flavor_text
,
1090 "net_list": net_list
,
1091 "cloud_config": cloud_config
or None,
1092 "disk_list": disk_list
,
1093 "availability_zone_index": None, # TODO
1094 "availability_zone_list": None, # TODO
1099 def calculate_diff_items(
1106 tasks_by_target_record_id
,
1113 """Function that returns the incremental changes (creation, deletion)
1114 related to a specific item `item` to be done. This function should be
1115 called for NS instantiation, NS termination, NS update to add a new VNF
1116 or a new VLD, remove a VNF or VLD, etc.
1117 Item can be `net, `flavor`, `image` or `vdu`.
1118 It takes a list of target items from indata (which came from the REST API)
1119 and compares with the existing items from db_ro_nsr, identifying the
1120 incremental changes to be done. During the comparison, it calls the method
1121 `process_params` (which was passed as parameter, and is particular for each
1125 indata (Dict[str, Any]): deployment info
1126 db_nsr: NSR record from DB
1127 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1128 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1129 item (str): element to process (net, vdu...)
1130 tasks_by_target_record_id (Dict[str, Any]):
1131 [<target_record_id>, <task>]
1132 action_id (str): action id
1133 nsr_id (str): NSR id
1134 task_index (number): task index to add to task name
1135 vnfr_id (str): VNFR id
1136 vnfr (Dict[str, Any]): VNFR info
1139 List: list with the incremental changes (deletes, creates) for each item
1140 number: current task index
1148 process_params
= None
1149 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1150 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1152 # According to the type of item, the path, the target_list,
1153 # the existing_list and the method to process params are set
1154 db_path
= self
.db_path_map
[item
]
1155 process_params
= self
.process_params_function_map
[item
]
1156 if item
in ("net", "vdu"):
1158 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1159 target_list
= indata
.get("ns", []).get(db_path
, [])
1160 existing_list
= db_nsr
.get(db_path
, [])
1162 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
1164 (vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
),
1167 target_list
= target_vnf
.get(db_path
, []) if target_vnf
else []
1168 existing_list
= vnfr
.get(db_path
, [])
1169 elif item
in ("image", "flavor"):
1170 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1171 target_list
= indata
.get(item
, [])
1172 existing_list
= db_nsr
.get(item
, [])
1174 raise NsException("Item not supported: {}", item
)
1176 # ensure all the target_list elements has an "id". If not assign the index as id
1177 if target_list
is None:
1179 for target_index
, tl
in enumerate(target_list
):
1180 if tl
and not tl
.get("id"):
1181 tl
["id"] = str(target_index
)
1183 # step 1 items (networks,vdus,...) to be deleted/updated
1184 for item_index
, existing_item
in enumerate(existing_list
):
1186 (t
for t
in target_list
if t
["id"] == existing_item
["id"]),
1190 for target_vim
, existing_viminfo
in existing_item
.get(
1193 if existing_viminfo
is None:
1197 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
1199 target_viminfo
= None
1201 if target_viminfo
is None:
1203 self
._assign
_vim
(target_vim
)
1204 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
1207 if target_vim
.startswith("sdn"):
1208 # item must be sdn-net instead of net if target_vim is a sdn
1210 target_record_id
+= ".sdn"
1213 "action_id": action_id
,
1215 "task_index": task_index
,
1220 "deployment_info": deployment_info
,
1221 "target_id": target_vim
,
1224 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1225 "target_record_id": target_record_id
,
1230 # step 2 items (networks,vdus,...) to be created
1231 for target_item
in target_list
:
1234 for item_index
, existing_item
in enumerate(existing_list
):
1235 if existing_item
["id"] == target_item
["id"]:
1239 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1240 existing_list
.append(target_item
)
1241 existing_item
= None
1243 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
1244 existing_viminfo
= None
1247 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
1249 if existing_viminfo
is not None:
1252 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
1255 if target_vim
.startswith("sdn"):
1256 # item must be sdn-net instead of net if target_vim is a sdn
1258 target_record_id
+= ".sdn"
1261 if process_params
== Ns
._process
_vdu
_params
:
1267 "vdu2cloud_init": vdu2cloud_init
,
1268 "tasks_by_target_record_id": tasks_by_target_record_id
,
1269 "logger": self
.logger
,
1272 "ro_nsr_public_key": ro_nsr_public_key
,
1276 extra_dict
= process_params(
1283 self
._assign
_vim
(target_vim
)
1286 "action_id": action_id
,
1288 "task_index": task_index
,
1292 "deployment_info": deployment_info
,
1293 "target_id": target_vim
,
1296 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1297 "target_record_id": target_record_id
,
1298 "extra_dict": extra_dict
,
1299 "common_id": target_item
.get("common_id", None),
1301 diff_items
.append(new_item
)
1302 tasks_by_target_record_id
[target_record_id
] = new_item
1305 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1307 return diff_items
, task_index
1309 def calculate_all_differences_to_deploy(
1319 tasks_by_target_record_id
,
1321 """This method calculates the ordered list of items (`changes_list`)
1322 to be created and deleted.
1325 indata (Dict[str, Any]): deployment info
1326 nsr_id (str): NSR id
1327 db_nsr: NSR record from DB
1328 db_vnfrs: VNFRS record from DB
1329 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1330 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1331 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
1332 action_id (str): action id
1333 tasks_by_target_record_id (Dict[str, Any]):
1334 [<target_record_id>, <task>]
1337 List: ordered list of items to be created and deleted.
1341 # set list with diffs:
1344 # NS vld, image and flavor
1345 for item
in ["net", "image", "flavor"]:
1346 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
1347 diff_items
, task_index
= self
.calculate_diff_items(
1350 db_ro_nsr
=db_ro_nsr
,
1351 db_nsr_update
=db_nsr_update
,
1353 tasks_by_target_record_id
=tasks_by_target_record_id
,
1354 action_id
=action_id
,
1356 task_index
=task_index
,
1359 changes_list
+= diff_items
1362 for vnfr_id
, vnfr
in db_vnfrs
.items():
1363 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1364 for item
in ["net", "vdu"]:
1365 self
.logger
.debug("process VNF={} {}".format(vnfr_id
, item
))
1366 diff_items
, task_index
= self
.calculate_diff_items(
1369 db_ro_nsr
=db_ro_nsr
,
1370 db_nsr_update
=db_vnfrs_update
[vnfr
["_id"]],
1372 tasks_by_target_record_id
=tasks_by_target_record_id
,
1373 action_id
=action_id
,
1375 task_index
=task_index
,
1379 changes_list
+= diff_items
1383 def define_all_tasks(
1387 tasks_by_target_record_id
,
1389 """Function to create all the task structures obtanied from
1390 the method calculate_all_differences_to_deploy
1393 changes_list (List): ordered list of items to be created or deleted
1394 db_new_tasks (List): tasks list to be created
1395 action_id (str): action id
1396 tasks_by_target_record_id (Dict[str, Any]):
1397 [<target_record_id>, <task>]
1401 for change
in changes_list
:
1402 task
= Ns
._create
_task
(
1403 deployment_info
=change
["deployment_info"],
1404 target_id
=change
["target_id"],
1405 item
=change
["item"],
1406 action
=change
["action"],
1407 target_record
=change
["target_record"],
1408 target_record_id
=change
["target_record_id"],
1409 extra_dict
=change
.get("extra_dict", None),
1412 tasks_by_target_record_id
[change
["target_record_id"]] = task
1413 db_new_tasks
.append(task
)
1415 if change
.get("common_id"):
1416 task
["common_id"] = change
["common_id"]
1418 def upload_all_tasks(
1423 """Function to save all tasks in the common DB
1426 db_new_tasks (List): tasks list to be created
1427 now (time): current time
1431 nb_ro_tasks
= 0 # for logging
1433 for db_task
in db_new_tasks
:
1434 target_id
= db_task
.pop("target_id")
1435 common_id
= db_task
.get("common_id")
1441 "target_id": target_id
,
1442 "tasks.common_id": common_id
,
1444 update_dict
={"to_check_at": now
, "modified_at": now
},
1445 push
={"tasks": db_task
},
1446 fail_on_empty
=False,
1450 if not self
.db
.set_one(
1453 "target_id": target_id
,
1454 "tasks.target_record": db_task
["target_record"],
1456 update_dict
={"to_check_at": now
, "modified_at": now
},
1457 push
={"tasks": db_task
},
1458 fail_on_empty
=False,
1461 self
.logger
.debug("Updating database, Creating ro_tasks")
1462 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
1464 self
.db
.create("ro_tasks", db_ro_task
)
1467 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1468 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
1472 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
1473 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
1474 validate_input(indata
, deploy_schema
)
1475 action_id
= indata
.get("action_id", str(uuid4()))
1477 # get current deployment
1478 db_nsr_update
= {} # update operation on nsrs
1479 db_vnfrs_update
= {}
1480 db_vnfrs
= {} # vnf's info indexed by _id
1482 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
1483 self
.logger
.debug(logging_text
+ "Enter")
1486 step
= "Getting ns and vnfr record from db"
1487 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1489 tasks_by_target_record_id
= {}
1490 # read from db: vnf's of this ns
1491 step
= "Getting vnfrs from db"
1492 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1494 if not db_vnfrs_list
:
1495 raise NsException("Cannot obtain associated VNF for ns")
1497 for vnfr
in db_vnfrs_list
:
1498 db_vnfrs
[vnfr
["_id"]] = vnfr
1499 db_vnfrs_update
[vnfr
["_id"]] = {}
1502 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
1505 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
1507 # check that action_id is not in the list of actions. Suffixed with :index
1508 if action_id
in db_ro_nsr
["actions"]:
1512 new_action_id
= "{}:{}".format(action_id
, index
)
1514 if new_action_id
not in db_ro_nsr
["actions"]:
1515 action_id
= new_action_id
1518 + "Changing action_id in use to {}".format(action_id
)
1524 def _process_action(indata
):
1525 nonlocal db_new_tasks
1532 if indata
["action"]["action"] == "inject_ssh_key":
1533 key
= indata
["action"].get("key")
1534 user
= indata
["action"].get("user")
1535 password
= indata
["action"].get("password")
1537 for vnf
in indata
.get("vnf", ()):
1538 if vnf
["_id"] not in db_vnfrs
:
1539 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
1541 db_vnfr
= db_vnfrs
[vnf
["_id"]]
1543 for target_vdu
in vnf
.get("vdur", ()):
1544 vdu_index
, vdur
= next(
1547 for i_v
in enumerate(db_vnfr
["vdur"])
1548 if i_v
[1]["id"] == target_vdu
["id"]
1555 "Invalid vdu vnf={}.{}".format(
1556 vnf
["_id"], target_vdu
["id"]
1560 target_vim
, vim_info
= next(
1561 k_v
for k_v
in vdur
["vim_info"].items()
1563 self
._assign
_vim
(target_vim
)
1564 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
1565 vnf
["_id"], vdu_index
1569 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
1572 "ip_address": vdur
.get("ip-address"),
1575 "password": password
,
1576 "private_key": db_ro_nsr
["private_key"],
1577 "salt": db_ro_nsr
["_id"],
1578 "schema_version": db_ro_nsr
["_admin"][
1585 "action_id": action_id
,
1587 "task_index": task_index
,
1590 task
= Ns
._create
_task
(
1591 deployment_info
=deployment_info
,
1592 target_id
=target_vim
,
1595 target_record
=target_record
,
1596 target_record_id
=None,
1597 extra_dict
=extra_dict
,
1600 task_index
= deployment_info
.get("task_index")
1602 db_new_tasks
.append(task
)
1604 with self
.write_lock
:
1605 if indata
.get("action"):
1606 _process_action(indata
)
1608 # compute network differences
1610 step
= "process NS elements"
1611 changes_list
= self
.calculate_all_differences_to_deploy(
1616 db_ro_nsr
=db_ro_nsr
,
1617 db_nsr_update
=db_nsr_update
,
1618 db_vnfrs_update
=db_vnfrs_update
,
1619 action_id
=action_id
,
1620 tasks_by_target_record_id
=tasks_by_target_record_id
,
1622 self
.define_all_tasks(
1623 changes_list
=changes_list
,
1624 db_new_tasks
=db_new_tasks
,
1625 tasks_by_target_record_id
=tasks_by_target_record_id
,
1628 step
= "Updating database, Appending tasks to ro_tasks"
1629 self
.upload_all_tasks(
1630 db_new_tasks
=db_new_tasks
,
1634 step
= "Updating database, nsrs"
1636 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
1638 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
1640 step
= "Updating database, vnfrs={}".format(vnfr_id
)
1641 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
1644 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
1648 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
1652 except Exception as e
:
1653 if isinstance(e
, (DbException
, NsException
)):
1655 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
1658 e
= traceback_format_exc()
1659 self
.logger
.critical(
1660 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
1664 raise NsException(e
)
1666 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
1667 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
1668 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
1670 with self
.write_lock
:
1672 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
1673 except NsWorkerException
as e
:
1674 raise NsException(e
)
1676 return None, None, True
1678 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1679 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
1680 # .format(version, nsr_id, action_id, indata))
1684 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
1685 global_status
= "DONE"
1688 for ro_task
in ro_tasks
:
1689 for task
in ro_task
["tasks"]:
1690 if task
and task
["action_id"] == action_id
:
1691 task_list
.append(task
)
1694 if task
["status"] == "FAILED":
1695 global_status
= "FAILED"
1696 error_text
= "Error at {} {}: {}".format(
1697 task
["action"].lower(),
1699 ro_task
["vim_info"].get("vim_details") or "unknown",
1701 details
.append(error_text
)
1702 elif task
["status"] in ("SCHEDULED", "BUILD"):
1703 if global_status
!= "FAILED":
1704 global_status
= "BUILD"
1709 "status": global_status
,
1710 "details": ". ".join(details
)
1712 else "progress {}/{}".format(done
, total
),
1714 "action_id": action_id
,
1718 return return_data
, None, True
1720 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1722 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
1723 session
, indata
, version
, nsr_id
, action_id
1727 return None, None, True
1729 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1730 nsrs
= self
.db
.get_list("nsrs", {})
1734 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
1736 return return_data
, None, True
1738 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1739 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
1742 for ro_task
in ro_tasks
:
1743 for task
in ro_task
["tasks"]:
1744 if task
["action_id"] not in return_data
:
1745 return_data
.append(task
["action_id"])
1747 return return_data
, None, True