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
= {}
112 def init_db(self
, target_version
):
115 def start(self
, config
):
117 Connect to database, filesystem storage, and messaging
118 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
119 :param config: Configuration of db, storage, etc
123 self
.config
["process_id"] = get_process_id() # used for HA identity
124 self
.logger
= logging
.getLogger("ro.ns")
126 # check right version of common
127 if versiontuple(common_version
) < versiontuple(min_common_version
):
129 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
130 common_version
, min_common_version
136 if config
["database"]["driver"] == "mongo":
137 self
.db
= dbmongo
.DbMongo()
138 self
.db
.db_connect(config
["database"])
139 elif config
["database"]["driver"] == "memory":
140 self
.db
= dbmemory
.DbMemory()
141 self
.db
.db_connect(config
["database"])
144 "Invalid configuration param '{}' at '[database]':'driver'".format(
145 config
["database"]["driver"]
150 if config
["storage"]["driver"] == "local":
151 self
.fs
= fslocal
.FsLocal()
152 self
.fs
.fs_connect(config
["storage"])
153 elif config
["storage"]["driver"] == "mongo":
154 self
.fs
= fsmongo
.FsMongo()
155 self
.fs
.fs_connect(config
["storage"])
156 elif config
["storage"]["driver"] is None:
160 "Invalid configuration param '{}' at '[storage]':'driver'".format(
161 config
["storage"]["driver"]
166 if config
["message"]["driver"] == "local":
167 self
.msg
= msglocal
.MsgLocal()
168 self
.msg
.connect(config
["message"])
169 elif config
["message"]["driver"] == "kafka":
170 self
.msg
= msgkafka
.MsgKafka()
171 self
.msg
.connect(config
["message"])
174 "Invalid configuration param '{}' at '[message]':'driver'".format(
175 config
["message"]["driver"]
179 # TODO load workers to deal with exising database tasks
181 self
.write_lock
= Lock()
182 except (DbException
, FsException
, MsgException
) as e
:
183 raise NsException(str(e
), http_code
=e
.http_code
)
185 def get_assigned_vims(self
):
186 return list(self
.vims_assigned
.keys())
191 self
.db
.db_disconnect()
194 self
.fs
.fs_disconnect()
197 self
.msg
.disconnect()
199 self
.write_lock
= None
200 except (DbException
, FsException
, MsgException
) as e
:
201 raise NsException(str(e
), http_code
=e
.http_code
)
203 for worker
in self
.workers
:
204 worker
.insert_task(("terminate",))
206 def _create_worker(self
):
208 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
209 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
210 return the index of the assigned worker thread. Worker threads are storead at self.workers
212 # Look for a thread in idle status
216 for i
in range(len(self
.workers
))
217 if self
.workers
[i
] and self
.workers
[i
].idle
222 if worker_id
is not None:
223 # unset idle status to avoid race conditions
224 self
.workers
[worker_id
].idle
= False
226 worker_id
= len(self
.workers
)
228 if worker_id
< self
.config
["global"]["server.ns_threads"]:
229 # create a new worker
231 NsWorker(worker_id
, self
.config
, self
.plugins
, self
.db
)
233 self
.workers
[worker_id
].start()
235 # reached maximum number of threads, assign VIM to an existing one
236 worker_id
= self
.next_worker
237 self
.next_worker
= (self
.next_worker
+ 1) % self
.config
["global"][
243 def assign_vim(self
, target_id
):
244 with self
.write_lock
:
245 return self
._assign
_vim
(target_id
)
247 def _assign_vim(self
, target_id
):
248 if target_id
not in self
.vims_assigned
:
249 worker_id
= self
.vims_assigned
[target_id
] = self
._create
_worker
()
250 self
.workers
[worker_id
].insert_task(("load_vim", target_id
))
252 def reload_vim(self
, target_id
):
253 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
254 # this is because database VIM information is cached for threads working with SDN
255 with self
.write_lock
:
256 for worker
in self
.workers
:
257 if worker
and not worker
.idle
:
258 worker
.insert_task(("reload_vim", target_id
))
260 def unload_vim(self
, target_id
):
261 with self
.write_lock
:
262 return self
._unload
_vim
(target_id
)
264 def _unload_vim(self
, target_id
):
265 if target_id
in self
.vims_assigned
:
266 worker_id
= self
.vims_assigned
[target_id
]
267 self
.workers
[worker_id
].insert_task(("unload_vim", target_id
))
268 del self
.vims_assigned
[target_id
]
270 def check_vim(self
, target_id
):
271 with self
.write_lock
:
272 if target_id
in self
.vims_assigned
:
273 worker_id
= self
.vims_assigned
[target_id
]
275 worker_id
= self
._create
_worker
()
277 worker
= self
.workers
[worker_id
]
278 worker
.insert_task(("check_vim", target_id
))
280 def unload_unused_vims(self
):
281 with self
.write_lock
:
284 for target_id
in self
.vims_assigned
:
285 if not self
.db
.get_one(
288 "target_id": target_id
,
289 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
293 vims_to_unload
.append(target_id
)
295 for target_id
in vims_to_unload
:
296 self
._unload
_vim
(target_id
)
304 """This method reads cloud init from a file.
306 Note: Not used as cloud init content is provided in the http body.
309 db (Type[DbBase]): [description]
310 fs (Type[FsBase]): [description]
311 location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
314 NsException: [description]
315 NsException: [description]
320 vnfd_id
, _
, other
= location
.partition(":")
321 _type
, _
, name
= other
.partition(":")
322 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
325 base_folder
= vnfd
["_admin"]["storage"]
326 cloud_init_file
= "{}/{}/cloud_init/{}".format(
327 base_folder
["folder"], base_folder
["pkg-dir"], name
332 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
337 with fs
.file_open(cloud_init_file
, "r") as ci_file
:
338 cloud_init_content
= ci_file
.read()
340 cloud_init_content
= vnfd
["vdu"][int(name
)]["cloud-init"]
342 raise NsException("Mismatch descriptor for cloud init: {}".format(location
))
344 return cloud_init_content
348 cloud_init_content
: str,
349 params
: Dict
[str, Any
],
352 """Function that processes the cloud init to replace Jinja2 encoded parameters.
355 cloud_init_content (str): [description]
356 params (Dict[str, Any]): [description]
357 context (str): [description]
360 NsException: [description]
361 NsException: [description]
367 env
= Environment(undefined
=StrictUndefined
)
368 template
= env
.from_string(cloud_init_content
)
370 return template
.render(params
or {})
371 except UndefinedError
as e
:
373 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
374 "inside the 'additionalParamsForVnf' block".format(e
, context
)
376 except (TemplateError
, TemplateNotFound
) as e
:
378 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
383 def _create_db_ro_nsrs(self
, nsr_id
, now
):
385 key
= rsa
.generate_private_key(
386 backend
=crypto_default_backend(), public_exponent
=65537, key_size
=2048
388 private_key
= key
.private_bytes(
389 crypto_serialization
.Encoding
.PEM
,
390 crypto_serialization
.PrivateFormat
.PKCS8
,
391 crypto_serialization
.NoEncryption(),
393 public_key
= key
.public_key().public_bytes(
394 crypto_serialization
.Encoding
.OpenSSH
,
395 crypto_serialization
.PublicFormat
.OpenSSH
,
397 private_key
= private_key
.decode("utf8")
398 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
399 i
= private_key
.find("\n")
400 private_key
= "-----BEGIN RSA PRIVATE KEY-----" + private_key
[i
:]
401 public_key
= public_key
.decode("utf8")
402 except Exception as e
:
403 raise NsException("Cannot create ssh-keys: {}".format(e
))
405 schema_version
= "1.1"
406 private_key_encrypted
= self
.db
.encrypt(
407 private_key
, schema_version
=schema_version
, salt
=nsr_id
414 "schema_version": schema_version
,
416 "public_key": public_key
,
417 "private_key": private_key_encrypted
,
420 self
.db
.create("ro_nsrs", db_content
)
426 deployment_info
: Dict
[str, Any
],
431 target_record_id
: str,
432 extra_dict
: Dict
[str, Any
] = None,
434 """Function to create task dict from deployment information.
437 deployment_info (Dict[str, Any]): [description]
438 target_id (str): [description]
439 item (str): [description]
440 action (str): [description]
441 target_record (str): [description]
442 target_record_id (str): [description]
443 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
446 Dict[str, Any]: [description]
449 "target_id": target_id
, # it will be removed before pushing at database
450 "action_id": deployment_info
.get("action_id"),
451 "nsr_id": deployment_info
.get("nsr_id"),
452 "task_id": f
"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
453 "status": "SCHEDULED",
456 "target_record": target_record
,
457 "target_record_id": target_record_id
,
461 task
.update(extra_dict
) # params, find_params, depends_on
463 deployment_info
["task_index"] = deployment_info
.get("task_index", 0) + 1
470 task
: Dict
[str, Any
],
472 """Function to create an RO task from task information.
475 target_id (str): [description]
476 task (Dict[str, Any]): [description]
479 Dict[str, Any]: [description]
483 _id
= task
.get("task_id")
488 "target_id": target_id
,
491 "created_items": None,
507 def _process_image_params(
508 target_image
: Dict
[str, Any
],
509 indata
: Dict
[str, Any
],
510 vim_info
: Dict
[str, Any
],
511 target_record_id
: str,
512 **kwargs
: Dict
[str, Any
],
514 """Function to process VDU image parameters.
517 target_image (Dict[str, Any]): [description]
518 indata (Dict[str, Any]): [description]
519 vim_info (Dict[str, Any]): [description]
520 target_record_id (str): [description]
523 Dict[str, Any]: [description]
527 if target_image
.get("image"):
528 find_params
["filter_dict"] = {"name": target_image
.get("image")}
530 if target_image
.get("vim_image_id"):
531 find_params
["filter_dict"] = {"id": target_image
.get("vim_image_id")}
533 if target_image
.get("image_checksum"):
534 find_params
["filter_dict"] = {
535 "checksum": target_image
.get("image_checksum")
538 return {"find_params": find_params
}
541 def _get_resource_allocation_params(
542 quota_descriptor
: Dict
[str, Any
],
544 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
548 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
551 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
555 if quota_descriptor
.get("limit"):
556 quota
["limit"] = int(quota_descriptor
["limit"])
558 if quota_descriptor
.get("reserve"):
559 quota
["reserve"] = int(quota_descriptor
["reserve"])
561 if quota_descriptor
.get("shares"):
562 quota
["shares"] = int(quota_descriptor
["shares"])
567 def _process_guest_epa_quota_params(
568 guest_epa_quota
: Dict
[str, Any
],
571 """Function to extract the guest epa quota parameters.
574 guest_epa_quota (Dict[str, Any]): [description]
575 epa_vcpu_set (bool): [description]
578 Dict[str, Any]: [description]
582 if guest_epa_quota
.get("cpu-quota") and not epa_vcpu_set
:
583 cpuquota
= Ns
._get
_resource
_allocation
_params
(
584 guest_epa_quota
.get("cpu-quota")
588 result
["cpu-quota"] = cpuquota
590 if guest_epa_quota
.get("mem-quota"):
591 vduquota
= Ns
._get
_resource
_allocation
_params
(
592 guest_epa_quota
.get("mem-quota")
596 result
["mem-quota"] = vduquota
598 if guest_epa_quota
.get("disk-io-quota"):
599 diskioquota
= Ns
._get
_resource
_allocation
_params
(
600 guest_epa_quota
.get("disk-io-quota")
604 result
["disk-io-quota"] = diskioquota
606 if guest_epa_quota
.get("vif-quota"):
607 vifquota
= Ns
._get
_resource
_allocation
_params
(
608 guest_epa_quota
.get("vif-quota")
612 result
["vif-quota"] = vifquota
617 def _process_guest_epa_numa_params(
618 guest_epa_quota
: Dict
[str, Any
],
619 ) -> Tuple
[Dict
[str, Any
], bool]:
623 guest_epa_quota (Dict[str, Any]): [description]
626 Tuple[Dict[str, Any], bool]: [description]
631 if guest_epa_quota
.get("numa-node-policy"):
632 numa_node_policy
= guest_epa_quota
.get("numa-node-policy")
634 if numa_node_policy
.get("node"):
635 numa_node
= numa_node_policy
["node"][0]
637 if numa_node
.get("num-cores"):
638 numa
["cores"] = numa_node
["num-cores"]
641 paired_threads
= numa_node
.get("paired-threads", {})
642 if paired_threads
.get("num-paired-threads"):
643 numa
["paired-threads"] = int(
644 numa_node
["paired-threads"]["num-paired-threads"]
648 if paired_threads
.get("paired-thread-ids"):
649 numa
["paired-threads-id"] = []
651 for pair
in paired_threads
["paired-thread-ids"]:
652 numa
["paired-threads-id"].append(
654 str(pair
["thread-a"]),
655 str(pair
["thread-b"]),
659 if numa_node
.get("num-threads"):
660 numa
["threads"] = int(numa_node
["num-threads"])
663 if numa_node
.get("memory-mb"):
664 numa
["memory"] = max(int(int(numa_node
["memory-mb"]) / 1024), 1)
666 return numa
, epa_vcpu_set
669 def _process_guest_epa_cpu_pinning_params(
670 guest_epa_quota
: Dict
[str, Any
],
673 ) -> Tuple
[Dict
[str, Any
], bool]:
677 guest_epa_quota (Dict[str, Any]): [description]
678 vcpu_count (int): [description]
679 epa_vcpu_set (bool): [description]
682 Tuple[Dict[str, Any], bool]: [description]
685 local_epa_vcpu_set
= epa_vcpu_set
688 guest_epa_quota
.get("cpu-pinning-policy") == "DEDICATED"
693 if guest_epa_quota
.get("cpu-thread-pinning-policy") != "PREFER"
695 ] = max(vcpu_count
, 1)
696 local_epa_vcpu_set
= True
698 return numa
, local_epa_vcpu_set
701 def _process_epa_params(
702 target_flavor
: Dict
[str, Any
],
707 target_flavor (Dict[str, Any]): [description]
710 Dict[str, Any]: [description]
715 if target_flavor
.get("guest-epa"):
716 guest_epa
= target_flavor
["guest-epa"]
718 numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_numa
_params
(
719 guest_epa_quota
=guest_epa
722 if guest_epa
.get("mempage-size"):
723 extended
["mempage-size"] = guest_epa
.get("mempage-size")
725 tmp_numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_cpu
_pinning
_params
(
726 guest_epa_quota
=guest_epa
,
727 vcpu_count
=int(target_flavor
.get("vcpu-count", 1)),
728 epa_vcpu_set
=epa_vcpu_set
,
730 numa
.update(tmp_numa
)
733 Ns
._process
_guest
_epa
_quota
_params
(
734 guest_epa_quota
=guest_epa
,
735 epa_vcpu_set
=epa_vcpu_set
,
740 extended
["numas"] = [numa
]
745 def _process_flavor_params(
746 target_flavor
: Dict
[str, Any
],
747 indata
: Dict
[str, Any
],
748 vim_info
: Dict
[str, Any
],
749 target_record_id
: str,
750 **kwargs
: Dict
[str, Any
],
755 target_flavor (Dict[str, Any]): [description]
756 indata (Dict[str, Any]): [description]
757 vim_info (Dict[str, Any]): [description]
758 target_record_id (str): [description]
761 Dict[str, Any]: [description]
764 "disk": int(target_flavor
["storage-gb"]),
765 "ram": int(target_flavor
["memory-mb"]),
766 "vcpus": int(target_flavor
["vcpu-count"]),
770 for vnf
in indata
.get("vnf", []):
771 for vdur
in vnf
.get("vdur", []):
772 if vdur
.get("ns-flavor-id") == target_flavor
["id"]:
775 for storage
in target_vdur
.get("virtual-storages", []):
777 storage
.get("type-of-storage")
778 == "etsi-nfv-descriptors:ephemeral-storage"
780 flavor_data
["ephemeral"] = int(storage
.get("size-of-storage", 0))
781 elif storage
.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
782 flavor_data
["swap"] = int(storage
.get("size-of-storage", 0))
784 extended
= Ns
._process
_epa
_params
(target_flavor
)
786 flavor_data
["extended"] = extended
788 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
789 flavor_data_name
= flavor_data
.copy()
790 flavor_data_name
["name"] = target_flavor
["name"]
791 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
796 def _ip_profile_to_ro(
797 ip_profile
: Dict
[str, Any
],
802 ip_profile (Dict[str, Any]): [description]
805 Dict[str, Any]: [description]
812 if "v4" in ip_profile
.get("ip-version", "ipv4")
814 "subnet_address": ip_profile
.get("subnet-address"),
815 "gateway_address": ip_profile
.get("gateway-address"),
816 "dhcp_enabled": ip_profile
.get("dhcp-params", {}).get("enabled", False),
817 "dhcp_start_address": ip_profile
.get("dhcp-params", {}).get(
818 "start-address", None
820 "dhcp_count": ip_profile
.get("dhcp-params", {}).get("count", None),
823 if ip_profile
.get("dns-server"):
824 ro_ip_profile
["dns_address"] = ";".join(
825 [v
["address"] for v
in ip_profile
["dns-server"] if v
.get("address")]
828 if ip_profile
.get("security-group"):
829 ro_ip_profile
["security_group"] = ip_profile
["security-group"]
834 def _process_net_params(
835 target_vld
: Dict
[str, Any
],
836 indata
: Dict
[str, Any
],
837 vim_info
: Dict
[str, Any
],
838 target_record_id
: str,
839 **kwargs
: Dict
[str, Any
],
841 """Function to process network parameters.
844 target_vld (Dict[str, Any]): [description]
845 indata (Dict[str, Any]): [description]
846 vim_info (Dict[str, Any]): [description]
847 target_record_id (str): [description]
850 Dict[str, Any]: [description]
854 if vim_info
.get("sdn"):
855 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
856 # ns_preffix = "nsrs:{}".format(nsr_id)
857 # remove the ending ".sdn
858 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
859 extra_dict
["params"] = {
861 for k
in ("sdn-ports", "target_vim", "vlds", "type")
865 # TODO needed to add target_id in the dependency.
866 if vim_info
.get("target_vim"):
867 extra_dict
["depends_on"] = [
868 f
"{vim_info.get('target_vim')} {vld_target_record_id}"
873 if vim_info
.get("vim_network_name"):
874 extra_dict
["find_params"] = {
876 "name": vim_info
.get("vim_network_name"),
879 elif vim_info
.get("vim_network_id"):
880 extra_dict
["find_params"] = {
882 "id": vim_info
.get("vim_network_id"),
885 elif target_vld
.get("mgmt-network"):
886 extra_dict
["find_params"] = {
888 "name": target_vld
["id"],
892 extra_dict
["params"] = {
894 f
"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
896 "ip_profile": Ns
._ip
_profile
_to
_ro
(vim_info
.get("ip_profile")),
897 "provider_network_profile": vim_info
.get("provider_network"),
900 if not target_vld
.get("underlay"):
901 extra_dict
["params"]["net_type"] = "bridge"
903 extra_dict
["params"]["net_type"] = (
904 "ptp" if target_vld
.get("type") == "ELINE" else "data"
910 def _process_vdu_params(
911 target_vdu
: Dict
[str, Any
],
912 indata
: Dict
[str, Any
],
913 vim_info
: Dict
[str, Any
],
914 target_record_id
: str,
915 **kwargs
: Dict
[str, Any
],
917 """Function to process VDU parameters.
920 target_vdu (Dict[str, Any]): [description]
921 indata (Dict[str, Any]): [description]
922 vim_info (Dict[str, Any]): [description]
923 target_record_id (str): [description]
926 Dict[str, Any]: [description]
928 vnfr_id
= kwargs
.get("vnfr_id")
929 nsr_id
= kwargs
.get("nsr_id")
930 vnfr
= kwargs
.get("vnfr")
931 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
932 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
933 logger
= kwargs
.get("logger")
934 db
= kwargs
.get("db")
935 fs
= kwargs
.get("fs")
936 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
938 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
939 ns_preffix
= "nsrs:{}".format(nsr_id
)
940 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
941 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
942 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
945 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
946 if interface
.get("ns-vld-id"):
947 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
948 elif interface
.get("vnf-vld-id"):
949 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
952 "Interface {} from vdu {} not connected to any vld".format(
953 iface_index
, target_vdu
["vdu-name"]
957 continue # interface not connected to any vld
959 extra_dict
["depends_on"].append(net_text
)
961 if "port-security-enabled" in interface
:
962 interface
["port_security"] = interface
.pop("port-security-enabled")
964 if "port-security-disable-strategy" in interface
:
965 interface
["port_security_disable_strategy"] = interface
.pop(
966 "port-security-disable-strategy"
971 for x
, v
in interface
.items()
977 "port_security_disable_strategy",
981 net_item
["net_id"] = "TASK-" + net_text
982 net_item
["type"] = "virtual"
984 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
985 # TODO floating_ip: True/False (or it can be None)
986 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
987 # mark the net create task as type data
989 tasks_by_target_record_id
,
994 tasks_by_target_record_id
[net_text
]["params"]["net_type"] = "data"
996 net_item
["use"] = "data"
997 net_item
["model"] = interface
["type"]
998 net_item
["type"] = interface
["type"]
1000 interface
.get("type") == "OM-MGMT"
1001 or interface
.get("mgmt-interface")
1002 or interface
.get("mgmt-vnf")
1004 net_item
["use"] = "mgmt"
1006 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1007 net_item
["use"] = "bridge"
1008 net_item
["model"] = interface
.get("type")
1010 if interface
.get("ip-address"):
1011 net_item
["ip_address"] = interface
["ip-address"]
1013 if interface
.get("mac-address"):
1014 net_item
["mac_address"] = interface
["mac-address"]
1016 net_list
.append(net_item
)
1018 if interface
.get("mgmt-vnf"):
1019 extra_dict
["mgmt_vnf_interface"] = iface_index
1020 elif interface
.get("mgmt-interface"):
1021 extra_dict
["mgmt_vdu_interface"] = iface_index
1026 if target_vdu
.get("cloud-init"):
1027 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1028 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1031 location
=target_vdu
["cloud-init"],
1034 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1035 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1036 cloud_init_content
=cloud_content_
,
1037 params
=target_vdu
.get("additionalParams"),
1038 context
=target_vdu
["cloud-init"],
1041 if target_vdu
.get("boot-data-drive"):
1042 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1046 if target_vdu
.get("ssh-keys"):
1047 ssh_keys
+= target_vdu
.get("ssh-keys")
1049 if target_vdu
.get("ssh-access-required"):
1050 ssh_keys
.append(ro_nsr_public_key
)
1053 cloud_config
["key-pairs"] = ssh_keys
1056 if target_vdu
.get("virtual-storages"):
1058 {"size": disk
["size-of-storage"]}
1059 for disk
in target_vdu
["virtual-storages"]
1060 if disk
.get("type-of-storage")
1061 == "persistent-storage:persistent-storage"
1064 extra_dict
["params"] = {
1065 "name": "{}-{}-{}-{}".format(
1066 indata
["name"][:16],
1067 vnfr
["member-vnf-index-ref"][:16],
1068 target_vdu
["vdu-name"][:32],
1069 target_vdu
.get("count-index") or 0,
1071 "description": target_vdu
["vdu-name"],
1073 "image_id": "TASK-" + image_text
,
1074 "flavor_id": "TASK-" + flavor_text
,
1075 "net_list": net_list
,
1076 "cloud_config": cloud_config
or None,
1077 "disk_list": disk_list
,
1078 "availability_zone_index": None, # TODO
1079 "availability_zone_list": None, # TODO
1084 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
1085 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
1086 validate_input(indata
, deploy_schema
)
1087 action_id
= indata
.get("action_id", str(uuid4()))
1089 # get current deployment
1090 db_nsr_update
= {} # update operation on nsrs
1091 db_vnfrs_update
= {}
1092 db_vnfrs
= {} # vnf's info indexed by _id
1093 nb_ro_tasks
= 0 # for logging
1094 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1096 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
1097 self
.logger
.debug(logging_text
+ "Enter")
1100 step
= "Getting ns and vnfr record from db"
1101 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1103 tasks_by_target_record_id
= {}
1104 # read from db: vnf's of this ns
1105 step
= "Getting vnfrs from db"
1106 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1108 if not db_vnfrs_list
:
1109 raise NsException("Cannot obtain associated VNF for ns")
1111 for vnfr
in db_vnfrs_list
:
1112 db_vnfrs
[vnfr
["_id"]] = vnfr
1113 db_vnfrs_update
[vnfr
["_id"]] = {}
1116 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
1119 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
1121 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1123 # check that action_id is not in the list of actions. Suffixed with :index
1124 if action_id
in db_ro_nsr
["actions"]:
1128 new_action_id
= "{}:{}".format(action_id
, index
)
1130 if new_action_id
not in db_ro_nsr
["actions"]:
1131 action_id
= new_action_id
1134 + "Changing action_id in use to {}".format(action_id
)
1149 nonlocal db_new_tasks
1150 nonlocal tasks_by_target_record_id
1156 # ensure all the target_list elements has an "id". If not assign the index as id
1157 for target_index
, tl
in enumerate(target_list
):
1158 if tl
and not tl
.get("id"):
1159 tl
["id"] = str(target_index
)
1161 # step 1 items (networks,vdus,...) to be deleted/updated
1162 for item_index
, existing_item
in enumerate(existing_list
):
1164 (t
for t
in target_list
if t
["id"] == existing_item
["id"]), None
1167 for target_vim
, existing_viminfo
in existing_item
.get(
1170 if existing_viminfo
is None:
1174 target_viminfo
= target_item
.get("vim_info", {}).get(
1178 target_viminfo
= None
1180 if target_viminfo
is None:
1182 self
._assign
_vim
(target_vim
)
1183 target_record_id
= "{}.{}".format(
1184 db_record
, existing_item
["id"]
1188 if target_vim
.startswith("sdn"):
1189 # item must be sdn-net instead of net if target_vim is a sdn
1191 target_record_id
+= ".sdn"
1194 "action_id": action_id
,
1196 "task_index": task_index
,
1199 task
= Ns
._create
_task
(
1200 deployment_info
=deployment_info
,
1201 target_id
=target_vim
,
1204 target_record
=f
"{db_record}.{item_index}.vim_info.{target_vim}",
1205 target_record_id
=target_record_id
,
1208 task_index
= deployment_info
.get("task_index")
1210 tasks_by_target_record_id
[target_record_id
] = task
1211 db_new_tasks
.append(task
)
1213 # TODO check one by one the vims to be created/deleted
1215 # step 2 items (networks,vdus,...) to be created
1216 for target_item
in target_list
:
1219 for item_index
, existing_item
in enumerate(existing_list
):
1220 if existing_item
["id"] == target_item
["id"]:
1224 db_update
[db_path
+ ".{}".format(item_index
)] = target_item
1225 existing_list
.append(target_item
)
1226 existing_item
= None
1228 for target_vim
, target_viminfo
in target_item
.get(
1231 existing_viminfo
= None
1234 existing_viminfo
= existing_item
.get("vim_info", {}).get(
1238 # TODO check if different. Delete and create???
1239 # TODO delete if not exist
1240 if existing_viminfo
is not None:
1243 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
1246 if target_vim
.startswith("sdn"):
1247 # item must be sdn-net instead of net if target_vim is a sdn
1249 target_record_id
+= ".sdn"
1252 if process_params
== Ns
._process
_vdu
_params
:
1258 "vdu2cloud_init": vdu2cloud_init
,
1259 "tasks_by_target_record_id": tasks_by_target_record_id
,
1260 "logger": self
.logger
,
1263 "ro_nsr_public_key": ro_nsr_public_key
,
1267 extra_dict
= process_params(
1274 self
._assign
_vim
(target_vim
)
1277 "action_id": action_id
,
1279 "task_index": task_index
,
1282 task
= Ns
._create
_task
(
1283 deployment_info
=deployment_info
,
1284 target_id
=target_vim
,
1287 target_record
=f
"{db_record}.{item_index}.vim_info.{target_vim}",
1288 target_record_id
=target_record_id
,
1289 extra_dict
=extra_dict
,
1292 task_index
= deployment_info
.get("task_index")
1294 tasks_by_target_record_id
[target_record_id
] = task
1295 db_new_tasks
.append(task
)
1297 if target_item
.get("common_id"):
1298 task
["common_id"] = target_item
["common_id"]
1300 db_update
[db_path
+ ".{}".format(item_index
)] = target_item
1302 def _process_action(indata
):
1303 nonlocal db_new_tasks
1310 if indata
["action"]["action"] == "inject_ssh_key":
1311 key
= indata
["action"].get("key")
1312 user
= indata
["action"].get("user")
1313 password
= indata
["action"].get("password")
1315 for vnf
in indata
.get("vnf", ()):
1316 if vnf
["_id"] not in db_vnfrs
:
1317 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
1319 db_vnfr
= db_vnfrs
[vnf
["_id"]]
1321 for target_vdu
in vnf
.get("vdur", ()):
1322 vdu_index
, vdur
= next(
1325 for i_v
in enumerate(db_vnfr
["vdur"])
1326 if i_v
[1]["id"] == target_vdu
["id"]
1333 "Invalid vdu vnf={}.{}".format(
1334 vnf
["_id"], target_vdu
["id"]
1338 target_vim
, vim_info
= next(
1339 k_v
for k_v
in vdur
["vim_info"].items()
1341 self
._assign
_vim
(target_vim
)
1342 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
1343 vnf
["_id"], vdu_index
1347 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
1350 "ip_address": vdur
.get("ip-address"),
1353 "password": password
,
1354 "private_key": db_ro_nsr
["private_key"],
1355 "salt": db_ro_nsr
["_id"],
1356 "schema_version": db_ro_nsr
["_admin"][
1363 "action_id": action_id
,
1365 "task_index": task_index
,
1368 task
= Ns
._create
_task
(
1369 deployment_info
=deployment_info
,
1370 target_id
=target_vim
,
1373 target_record
=target_record
,
1374 target_record_id
=None,
1375 extra_dict
=extra_dict
,
1378 task_index
= deployment_info
.get("task_index")
1380 db_new_tasks
.append(task
)
1382 with self
.write_lock
:
1383 if indata
.get("action"):
1384 _process_action(indata
)
1386 # compute network differences
1388 step
= "process NS VLDs"
1390 target_list
=indata
["ns"]["vld"] or [],
1391 existing_list
=db_nsr
.get("vld") or [],
1392 db_record
="nsrs:{}:vld".format(nsr_id
),
1393 db_update
=db_nsr_update
,
1396 process_params
=Ns
._process
_net
_params
,
1399 step
= "process NS images"
1401 target_list
=indata
.get("image") or [],
1402 existing_list
=db_nsr
.get("image") or [],
1403 db_record
="nsrs:{}:image".format(nsr_id
),
1404 db_update
=db_nsr_update
,
1407 process_params
=Ns
._process
_image
_params
,
1410 step
= "process NS flavors"
1412 target_list
=indata
.get("flavor") or [],
1413 existing_list
=db_nsr
.get("flavor") or [],
1414 db_record
="nsrs:{}:flavor".format(nsr_id
),
1415 db_update
=db_nsr_update
,
1418 process_params
=Ns
._process
_flavor
_params
,
1422 for vnfr_id
, vnfr
in db_vnfrs
.items():
1423 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1424 step
= "process VNF={} VLDs".format(vnfr_id
)
1428 for vnf
in indata
.get("vnf", ())
1429 if vnf
["_id"] == vnfr_id
1433 target_list
= target_vnf
.get("vld") if target_vnf
else None
1435 target_list
=target_list
or [],
1436 existing_list
=vnfr
.get("vld") or [],
1437 db_record
="vnfrs:{}:vld".format(vnfr_id
),
1438 db_update
=db_vnfrs_update
[vnfr
["_id"]],
1441 process_params
=Ns
._process
_net
_params
,
1444 target_list
= target_vnf
.get("vdur") if target_vnf
else None
1445 step
= "process VNF={} VDUs".format(vnfr_id
)
1447 target_list
=target_list
or [],
1448 existing_list
=vnfr
.get("vdur") or [],
1449 db_record
="vnfrs:{}:vdur".format(vnfr_id
),
1450 db_update
=db_vnfrs_update
[vnfr
["_id"]],
1453 process_params
=Ns
._process
_vdu
_params
,
1456 for db_task
in db_new_tasks
:
1457 step
= "Updating database, Appending tasks to ro_tasks"
1458 target_id
= db_task
.pop("target_id")
1459 common_id
= db_task
.get("common_id")
1465 "target_id": target_id
,
1466 "tasks.common_id": common_id
,
1468 update_dict
={"to_check_at": now
, "modified_at": now
},
1469 push
={"tasks": db_task
},
1470 fail_on_empty
=False,
1474 if not self
.db
.set_one(
1477 "target_id": target_id
,
1478 "tasks.target_record": db_task
["target_record"],
1480 update_dict
={"to_check_at": now
, "modified_at": now
},
1481 push
={"tasks": db_task
},
1482 fail_on_empty
=False,
1485 step
= "Updating database, Creating ro_tasks"
1486 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
1488 self
.db
.create("ro_tasks", db_ro_task
)
1490 step
= "Updating database, nsrs"
1492 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
1494 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
1496 step
= "Updating database, vnfrs={}".format(vnfr_id
)
1497 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
1501 + "Exit. Created {} ro_tasks; {} tasks".format(
1502 nb_ro_tasks
, len(db_new_tasks
)
1507 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
1511 except Exception as e
:
1512 if isinstance(e
, (DbException
, NsException
)):
1514 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
1517 e
= traceback_format_exc()
1518 self
.logger
.critical(
1519 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
1523 raise NsException(e
)
1525 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
1526 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
1527 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
1529 with self
.write_lock
:
1531 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
1532 except NsWorkerException
as e
:
1533 raise NsException(e
)
1535 return None, None, True
1537 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1538 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
1539 # .format(version, nsr_id, action_id, indata))
1543 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
1544 global_status
= "DONE"
1547 for ro_task
in ro_tasks
:
1548 for task
in ro_task
["tasks"]:
1549 if task
and task
["action_id"] == action_id
:
1550 task_list
.append(task
)
1553 if task
["status"] == "FAILED":
1554 global_status
= "FAILED"
1555 error_text
= "Error at {} {}: {}".format(
1556 task
["action"].lower(),
1558 ro_task
["vim_info"].get("vim_details") or "unknown",
1560 details
.append(error_text
)
1561 elif task
["status"] in ("SCHEDULED", "BUILD"):
1562 if global_status
!= "FAILED":
1563 global_status
= "BUILD"
1568 "status": global_status
,
1569 "details": ". ".join(details
)
1571 else "progress {}/{}".format(done
, total
),
1573 "action_id": action_id
,
1577 return return_data
, None, True
1579 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1581 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
1582 session
, indata
, version
, nsr_id
, action_id
1586 return None, None, True
1588 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1589 nsrs
= self
.db
.get_list("nsrs", {})
1593 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
1595 return return_data
, None, True
1597 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1598 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
1601 for ro_task
in ro_tasks
:
1602 for task
in ro_task
["tasks"]:
1603 if task
["action_id"] not in return_data
:
1604 return_data
.append(task
["action_id"])
1606 return return_data
, None, True