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.
21 from typing
import Any
, Dict
22 from traceback
import format_exc
as traceback_format_exc
23 from osm_ng_ro
.ns_thread
import NsWorker
, NsWorkerException
, deep_get
24 from osm_ng_ro
.validation
import validate_input
, deploy_schema
25 from osm_common
import (
32 version
as common_version
,
34 from osm_common
.dbbase
import DbException
35 from osm_common
.fsbase
import FsException
36 from osm_common
.msgbase
import MsgException
37 from http
import HTTPStatus
38 from uuid
import uuid4
39 from threading
import Lock
40 from random
import choice
as random_choice
49 from cryptography
.hazmat
.primitives
import serialization
as crypto_serialization
50 from cryptography
.hazmat
.primitives
.asymmetric
import rsa
51 from cryptography
.hazmat
.backends
import default_backend
as crypto_default_backend
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
)
298 def _get_cloud_init(self
, where
):
300 Not used as cloud init content is provided in the http body. This method reads cloud init from a file
301 :param where: can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
304 vnfd_id
, _
, other
= where
.partition(":")
305 _type
, _
, name
= other
.partition(":")
306 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
309 base_folder
= vnfd
["_admin"]["storage"]
310 cloud_init_file
= "{}/{}/cloud_init/{}".format(
311 base_folder
["folder"], base_folder
["pkg-dir"], name
316 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
321 with self
.fs
.file_open(cloud_init_file
, "r") as ci_file
:
322 cloud_init_content
= ci_file
.read()
324 cloud_init_content
= vnfd
["vdu"][int(name
)]["cloud-init"]
326 raise NsException("Mismatch descriptor for cloud init: {}".format(where
))
328 return cloud_init_content
330 def _parse_jinja2(self
, cloud_init_content
, params
, context
):
332 env
= Environment(undefined
=StrictUndefined
)
333 template
= env
.from_string(cloud_init_content
)
335 return template
.render(params
or {})
336 except UndefinedError
as e
:
338 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
339 "inside the 'additionalParamsForVnf' block".format(e
, context
)
341 except (TemplateError
, TemplateNotFound
) as e
:
343 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
348 def _create_db_ro_nsrs(self
, nsr_id
, now
):
350 key
= rsa
.generate_private_key(
351 backend
=crypto_default_backend(), public_exponent
=65537, key_size
=2048
353 private_key
= key
.private_bytes(
354 crypto_serialization
.Encoding
.PEM
,
355 crypto_serialization
.PrivateFormat
.PKCS8
,
356 crypto_serialization
.NoEncryption(),
358 public_key
= key
.public_key().public_bytes(
359 crypto_serialization
.Encoding
.OpenSSH
,
360 crypto_serialization
.PublicFormat
.OpenSSH
,
362 private_key
= private_key
.decode("utf8")
363 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
364 i
= private_key
.find("\n")
365 private_key
= "-----BEGIN RSA PRIVATE KEY-----" + private_key
[i
:]
366 public_key
= public_key
.decode("utf8")
367 except Exception as e
:
368 raise NsException("Cannot create ssh-keys: {}".format(e
))
370 schema_version
= "1.1"
371 private_key_encrypted
= self
.db
.encrypt(
372 private_key
, schema_version
=schema_version
, salt
=nsr_id
379 "schema_version": schema_version
,
381 "public_key": public_key
,
382 "private_key": private_key_encrypted
,
385 self
.db
.create("ro_nsrs", db_content
)
391 deployment_info
: Dict
[str, Any
],
396 target_record_id
: str,
397 extra_dict
: Dict
[str, Any
] = None,
399 """Function to create task dict from deployment information.
402 deployment_info (Dict[str, Any]): [description]
403 target_id (str): [description]
404 item (str): [description]
405 action (str): [description]
406 target_record (str): [description]
407 target_record_id (str): [description]
408 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
411 Dict[str, Any]: [description]
414 "target_id": target_id
, # it will be removed before pushing at database
415 "action_id": deployment_info
.get("action_id"),
416 "nsr_id": deployment_info
.get("nsr_id"),
417 "task_id": f
"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
418 "status": "SCHEDULED",
421 "target_record": target_record
,
422 "target_record_id": target_record_id
,
426 task
.update(extra_dict
) # params, find_params, depends_on
428 deployment_info
["task_index"] = deployment_info
.get("task_index", 0) + 1
435 task
: Dict
[str, Any
],
437 """Function to create an RO task from task information.
440 target_id (str): [description]
441 task (Dict[str, Any]): [description]
444 Dict[str, Any]: [description]
448 _id
= task
.get("task_id")
453 "target_id": target_id
,
456 "created_items": None,
472 def _process_image_params(
473 target_image
: Dict
[str, Any
],
474 vim_info
: Dict
[str, Any
],
475 target_record_id
: str,
477 """Function to process VDU image parameters.
480 target_image (Dict[str, Any]): [description]
481 vim_info (Dict[str, Any]): [description]
482 target_record_id (str): [description]
485 Dict[str, Any]: [description]
489 if target_image
.get("image"):
490 find_params
["filter_dict"] = {"name": target_image
.get("image")}
492 if target_image
.get("vim_image_id"):
493 find_params
["filter_dict"] = {"id": target_image
.get("vim_image_id")}
495 if target_image
.get("image_checksum"):
496 find_params
["filter_dict"] = {
497 "checksum": target_image
.get("image_checksum")
500 return {"find_params": find_params
}
502 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
503 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
504 validate_input(indata
, deploy_schema
)
505 action_id
= indata
.get("action_id", str(uuid4()))
507 # get current deployment
508 db_nsr_update
= {} # update operation on nsrs
510 db_vnfrs
= {} # vnf's info indexed by _id
511 nb_ro_tasks
= 0 # for logging
512 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
514 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
515 self
.logger
.debug(logging_text
+ "Enter")
518 step
= "Getting ns and vnfr record from db"
519 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
521 tasks_by_target_record_id
= {}
522 # read from db: vnf's of this ns
523 step
= "Getting vnfrs from db"
524 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
526 if not db_vnfrs_list
:
527 raise NsException("Cannot obtain associated VNF for ns")
529 for vnfr
in db_vnfrs_list
:
530 db_vnfrs
[vnfr
["_id"]] = vnfr
531 db_vnfrs_update
[vnfr
["_id"]] = {}
534 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
537 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
539 ro_nsr_public_key
= db_ro_nsr
["public_key"]
541 # check that action_id is not in the list of actions. Suffixed with :index
542 if action_id
in db_ro_nsr
["actions"]:
546 new_action_id
= "{}:{}".format(action_id
, index
)
548 if new_action_id
not in db_ro_nsr
["actions"]:
549 action_id
= new_action_id
552 + "Changing action_id in use to {}".format(action_id
)
558 def _process_flavor_params(target_flavor
, vim_info
, target_record_id
):
559 def _get_resource_allocation_params(quota_descriptor
):
561 read the quota_descriptor from vnfd and fetch the resource allocation properties from the
563 :param quota_descriptor: cpu/mem/vif/disk-io quota descriptor
564 :return: quota params for limit, reserve, shares from the descriptor object
568 if quota_descriptor
.get("limit"):
569 quota
["limit"] = int(quota_descriptor
["limit"])
571 if quota_descriptor
.get("reserve"):
572 quota
["reserve"] = int(quota_descriptor
["reserve"])
574 if quota_descriptor
.get("shares"):
575 quota
["shares"] = int(quota_descriptor
["shares"])
582 "disk": int(target_flavor
["storage-gb"]),
583 "ram": int(target_flavor
["memory-mb"]),
584 "vcpus": int(target_flavor
["vcpu-count"]),
590 for vnf
in indata
.get("vnf", []):
591 for vdur
in vnf
.get("vdur", []):
592 if vdur
.get("ns-flavor-id") == target_flavor
["id"]:
595 for storage
in target_vdur
.get("virtual-storages", []):
597 storage
.get("type-of-storage")
598 == "etsi-nfv-descriptors:ephemeral-storage"
600 flavor_data
["ephemeral"] = int(
601 storage
.get("size-of-storage", 0)
604 if target_flavor
.get("guest-epa"):
608 if target_flavor
["guest-epa"].get("numa-node-policy"):
609 numa_node_policy
= target_flavor
["guest-epa"].get(
613 if numa_node_policy
.get("node"):
614 numa_node
= numa_node_policy
["node"][0]
616 if numa_node
.get("num-cores"):
617 numa
["cores"] = numa_node
["num-cores"]
620 if numa_node
.get("paired-threads"):
621 if numa_node
["paired-threads"].get(
624 numa
["paired-threads"] = int(
625 numa_node
["paired-threads"][
632 numa_node
["paired-threads"].get("paired-thread-ids")
634 numa
["paired-threads-id"] = []
636 for pair
in numa_node
["paired-threads"][
639 numa
["paired-threads-id"].append(
641 str(pair
["thread-a"]),
642 str(pair
["thread-b"]),
646 if numa_node
.get("num-threads"):
647 numa
["threads"] = int(numa_node
["num-threads"])
650 if numa_node
.get("memory-mb"):
651 numa
["memory"] = max(
652 int(numa_node
["memory-mb"] / 1024), 1
655 if target_flavor
["guest-epa"].get("mempage-size"):
656 extended
["mempage-size"] = target_flavor
["guest-epa"].get(
661 target_flavor
["guest-epa"].get("cpu-pinning-policy")
665 target_flavor
["guest-epa"]["cpu-pinning-policy"]
669 target_flavor
["guest-epa"].get(
670 "cpu-thread-pinning-policy"
672 and target_flavor
["guest-epa"][
673 "cpu-thread-pinning-policy"
677 numa
["cores"] = max(flavor_data
["vcpus"], 1)
679 numa
["threads"] = max(flavor_data
["vcpus"], 1)
683 if target_flavor
["guest-epa"].get("cpu-quota") and not epa_vcpu_set
:
684 cpuquota
= _get_resource_allocation_params(
685 target_flavor
["guest-epa"].get("cpu-quota")
689 extended
["cpu-quota"] = cpuquota
691 if target_flavor
["guest-epa"].get("mem-quota"):
692 vduquota
= _get_resource_allocation_params(
693 target_flavor
["guest-epa"].get("mem-quota")
697 extended
["mem-quota"] = vduquota
699 if target_flavor
["guest-epa"].get("disk-io-quota"):
700 diskioquota
= _get_resource_allocation_params(
701 target_flavor
["guest-epa"].get("disk-io-quota")
705 extended
["disk-io-quota"] = diskioquota
707 if target_flavor
["guest-epa"].get("vif-quota"):
708 vifquota
= _get_resource_allocation_params(
709 target_flavor
["guest-epa"].get("vif-quota")
713 extended
["vif-quota"] = vifquota
716 extended
["numas"] = [numa
]
719 flavor_data
["extended"] = extended
721 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
722 flavor_data_name
= flavor_data
.copy()
723 flavor_data_name
["name"] = target_flavor
["name"]
724 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
728 def _ip_profile_2_ro(ip_profile
):
734 if "v4" in ip_profile
.get("ip-version", "ipv4")
736 "subnet_address": ip_profile
.get("subnet-address"),
737 "gateway_address": ip_profile
.get("gateway-address"),
738 "dhcp_enabled": ip_profile
.get("dhcp-params", {}).get(
741 "dhcp_start_address": ip_profile
.get("dhcp-params", {}).get(
742 "start-address", None
744 "dhcp_count": ip_profile
.get("dhcp-params", {}).get("count", None),
747 if ip_profile
.get("dns-server"):
748 ro_ip_profile
["dns_address"] = ";".join(
749 [v
["address"] for v
in ip_profile
["dns-server"]]
752 if ip_profile
.get("security-group"):
753 ro_ip_profile
["security_group"] = ip_profile
["security-group"]
757 def _process_net_params(target_vld
, vim_info
, target_record_id
):
761 if vim_info
.get("sdn"):
762 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
763 # ns_preffix = "nsrs:{}".format(nsr_id)
764 # remove the ending ".sdn
765 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
766 extra_dict
["params"] = {
768 for k
in ("sdn-ports", "target_vim", "vlds", "type")
772 # TODO needed to add target_id in the dependency.
773 if vim_info
.get("target_vim"):
774 extra_dict
["depends_on"] = [
775 vim_info
.get("target_vim") + " " + vld_target_record_id
780 if vim_info
.get("vim_network_name"):
781 extra_dict
["find_params"] = {
782 "filter_dict": {"name": vim_info
.get("vim_network_name")}
784 elif vim_info
.get("vim_network_id"):
785 extra_dict
["find_params"] = {
786 "filter_dict": {"id": vim_info
.get("vim_network_id")}
788 elif target_vld
.get("mgmt-network"):
789 extra_dict
["find_params"] = {"mgmt": True, "name": target_vld
["id"]}
792 extra_dict
["params"] = {
793 "net_name": "{}-{}".format(
795 target_vld
.get("name", target_vld
["id"])[:16],
797 "ip_profile": _ip_profile_2_ro(vim_info
.get("ip_profile")),
798 "provider_network_profile": vim_info
.get("provider_network"),
801 if not target_vld
.get("underlay"):
802 extra_dict
["params"]["net_type"] = "bridge"
804 extra_dict
["params"]["net_type"] = (
805 "ptp" if target_vld
.get("type") == "ELINE" else "data"
810 def _process_vdu_params(target_vdu
, vim_info
, target_record_id
):
815 nonlocal vdu2cloud_init
816 nonlocal tasks_by_target_record_id
818 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
819 ns_preffix
= "nsrs:{}".format(nsr_id
)
820 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
821 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
822 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
825 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
826 if interface
.get("ns-vld-id"):
827 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
828 elif interface
.get("vnf-vld-id"):
829 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
832 "Interface {} from vdu {} not connected to any vld".format(
833 iface_index
, target_vdu
["vdu-name"]
837 continue # interface not connected to any vld
839 extra_dict
["depends_on"].append(net_text
)
841 if "port-security-enabled" in interface
:
842 interface
["port_security"] = interface
.pop(
843 "port-security-enabled"
846 if "port-security-disable-strategy" in interface
:
847 interface
["port_security_disable_strategy"] = interface
.pop(
848 "port-security-disable-strategy"
853 for x
, v
in interface
.items()
859 "port_security_disable_strategy",
863 net_item
["net_id"] = "TASK-" + net_text
864 net_item
["type"] = "virtual"
866 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
867 # TODO floating_ip: True/False (or it can be None)
868 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
869 # mark the net create task as type data
871 tasks_by_target_record_id
, net_text
, "params", "net_type"
873 tasks_by_target_record_id
[net_text
]["params"][
877 net_item
["use"] = "data"
878 net_item
["model"] = interface
["type"]
879 net_item
["type"] = interface
["type"]
881 interface
.get("type") == "OM-MGMT"
882 or interface
.get("mgmt-interface")
883 or interface
.get("mgmt-vnf")
885 net_item
["use"] = "mgmt"
887 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
888 net_item
["use"] = "bridge"
889 net_item
["model"] = interface
.get("type")
891 if interface
.get("ip-address"):
892 net_item
["ip_address"] = interface
["ip-address"]
894 if interface
.get("mac-address"):
895 net_item
["mac_address"] = interface
["mac-address"]
897 net_list
.append(net_item
)
899 if interface
.get("mgmt-vnf"):
900 extra_dict
["mgmt_vnf_interface"] = iface_index
901 elif interface
.get("mgmt-interface"):
902 extra_dict
["mgmt_vdu_interface"] = iface_index
907 if target_vdu
.get("cloud-init"):
908 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
909 vdu2cloud_init
[target_vdu
["cloud-init"]] = self
._get
_cloud
_init
(
910 target_vdu
["cloud-init"]
913 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
914 cloud_config
["user-data"] = self
._parse
_jinja
2(
916 target_vdu
.get("additionalParams"),
917 target_vdu
["cloud-init"],
920 if target_vdu
.get("boot-data-drive"):
921 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
925 if target_vdu
.get("ssh-keys"):
926 ssh_keys
+= target_vdu
.get("ssh-keys")
928 if target_vdu
.get("ssh-access-required"):
929 ssh_keys
.append(ro_nsr_public_key
)
932 cloud_config
["key-pairs"] = ssh_keys
935 if target_vdu
.get("virtual-storages"):
937 {"size": disk
["size-of-storage"]}
938 for disk
in target_vdu
["virtual-storages"]
939 if disk
.get("type-of-storage")
940 == "persistent-storage:persistent-storage"
943 extra_dict
["params"] = {
944 "name": "{}-{}-{}-{}".format(
946 vnfr
["member-vnf-index-ref"][:16],
947 target_vdu
["vdu-name"][:32],
948 target_vdu
.get("count-index") or 0,
950 "description": target_vdu
["vdu-name"],
952 "image_id": "TASK-" + image_text
,
953 "flavor_id": "TASK-" + flavor_text
,
954 "net_list": net_list
,
955 "cloud_config": cloud_config
or None,
956 "disk_list": disk_list
,
957 "availability_zone_index": None, # TODO
958 "availability_zone_list": None, # TODO
972 nonlocal db_new_tasks
973 nonlocal tasks_by_target_record_id
978 # ensure all the target_list elements has an "id". If not assign the index as id
979 for target_index
, tl
in enumerate(target_list
):
980 if tl
and not tl
.get("id"):
981 tl
["id"] = str(target_index
)
983 # step 1 items (networks,vdus,...) to be deleted/updated
984 for item_index
, existing_item
in enumerate(existing_list
):
986 (t
for t
in target_list
if t
["id"] == existing_item
["id"]), None
989 for target_vim
, existing_viminfo
in existing_item
.get(
992 if existing_viminfo
is None:
996 target_viminfo
= target_item
.get("vim_info", {}).get(
1000 target_viminfo
= None
1002 if target_viminfo
is None:
1004 self
._assign
_vim
(target_vim
)
1005 target_record_id
= "{}.{}".format(
1006 db_record
, existing_item
["id"]
1010 if target_vim
.startswith("sdn"):
1011 # item must be sdn-net instead of net if target_vim is a sdn
1013 target_record_id
+= ".sdn"
1016 "action_id": action_id
,
1018 "task_index": task_index
,
1021 task
= Ns
._create
_task
(
1022 deployment_info
=deployment_info
,
1023 target_id
=target_vim
,
1026 target_record
=f
"{db_record}.{item_index}.vim_info.{target_vim}",
1027 target_record_id
=target_record_id
,
1030 task_index
= deployment_info
.get("task_index")
1032 tasks_by_target_record_id
[target_record_id
] = task
1033 db_new_tasks
.append(task
)
1035 # TODO check one by one the vims to be created/deleted
1037 # step 2 items (networks,vdus,...) to be created
1038 for target_item
in target_list
:
1041 for item_index
, existing_item
in enumerate(existing_list
):
1042 if existing_item
["id"] == target_item
["id"]:
1046 db_update
[db_path
+ ".{}".format(item_index
)] = target_item
1047 existing_list
.append(target_item
)
1048 existing_item
= None
1050 for target_vim
, target_viminfo
in target_item
.get(
1053 existing_viminfo
= None
1056 existing_viminfo
= existing_item
.get("vim_info", {}).get(
1060 # TODO check if different. Delete and create???
1061 # TODO delete if not exist
1062 if existing_viminfo
is not None:
1065 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
1068 if target_vim
.startswith("sdn"):
1069 # item must be sdn-net instead of net if target_vim is a sdn
1071 target_record_id
+= ".sdn"
1073 extra_dict
= process_params(
1074 target_item
, target_viminfo
, target_record_id
1076 self
._assign
_vim
(target_vim
)
1079 "action_id": action_id
,
1081 "task_index": task_index
,
1084 task
= Ns
._create
_task
(
1085 deployment_info
=deployment_info
,
1086 target_id
=target_vim
,
1089 target_record
=f
"{db_record}.{item_index}.vim_info.{target_vim}",
1090 target_record_id
=target_record_id
,
1091 extra_dict
=extra_dict
,
1094 task_index
= deployment_info
.get("task_index")
1096 tasks_by_target_record_id
[target_record_id
] = task
1097 db_new_tasks
.append(task
)
1099 if target_item
.get("common_id"):
1100 task
["common_id"] = target_item
["common_id"]
1102 db_update
[db_path
+ ".{}".format(item_index
)] = target_item
1104 def _process_action(indata
):
1105 nonlocal db_new_tasks
1112 if indata
["action"]["action"] == "inject_ssh_key":
1113 key
= indata
["action"].get("key")
1114 user
= indata
["action"].get("user")
1115 password
= indata
["action"].get("password")
1117 for vnf
in indata
.get("vnf", ()):
1118 if vnf
["_id"] not in db_vnfrs
:
1119 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
1121 db_vnfr
= db_vnfrs
[vnf
["_id"]]
1123 for target_vdu
in vnf
.get("vdur", ()):
1124 vdu_index
, vdur
= next(
1127 for i_v
in enumerate(db_vnfr
["vdur"])
1128 if i_v
[1]["id"] == target_vdu
["id"]
1135 "Invalid vdu vnf={}.{}".format(
1136 vnf
["_id"], target_vdu
["id"]
1140 target_vim
, vim_info
= next(
1141 k_v
for k_v
in vdur
["vim_info"].items()
1143 self
._assign
_vim
(target_vim
)
1144 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
1145 vnf
["_id"], vdu_index
1149 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
1152 "ip_address": vdur
.get("ip-address"),
1155 "password": password
,
1156 "private_key": db_ro_nsr
["private_key"],
1157 "salt": db_ro_nsr
["_id"],
1158 "schema_version": db_ro_nsr
["_admin"][
1165 "action_id": action_id
,
1167 "task_index": task_index
,
1170 task
= Ns
._create
_task
(
1171 deployment_info
=deployment_info
,
1172 target_id
=target_vim
,
1175 target_record
=target_record
,
1176 target_record_id
=None,
1177 extra_dict
=extra_dict
,
1180 task_index
= deployment_info
.get("task_index")
1182 db_new_tasks
.append(task
)
1184 with self
.write_lock
:
1185 if indata
.get("action"):
1186 _process_action(indata
)
1188 # compute network differences
1190 step
= "process NS VLDs"
1192 target_list
=indata
["ns"]["vld"] or [],
1193 existing_list
=db_nsr
.get("vld") or [],
1194 db_record
="nsrs:{}:vld".format(nsr_id
),
1195 db_update
=db_nsr_update
,
1198 process_params
=_process_net_params
,
1201 step
= "process NS images"
1203 target_list
=indata
.get("image") or [],
1204 existing_list
=db_nsr
.get("image") or [],
1205 db_record
="nsrs:{}:image".format(nsr_id
),
1206 db_update
=db_nsr_update
,
1209 process_params
=Ns
._process
_image
_params
,
1212 step
= "process NS flavors"
1214 target_list
=indata
.get("flavor") or [],
1215 existing_list
=db_nsr
.get("flavor") or [],
1216 db_record
="nsrs:{}:flavor".format(nsr_id
),
1217 db_update
=db_nsr_update
,
1220 process_params
=_process_flavor_params
,
1224 for vnfr_id
, vnfr
in db_vnfrs
.items():
1225 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1226 step
= "process VNF={} VLDs".format(vnfr_id
)
1230 for vnf
in indata
.get("vnf", ())
1231 if vnf
["_id"] == vnfr_id
1235 target_list
= target_vnf
.get("vld") if target_vnf
else None
1237 target_list
=target_list
or [],
1238 existing_list
=vnfr
.get("vld") or [],
1239 db_record
="vnfrs:{}:vld".format(vnfr_id
),
1240 db_update
=db_vnfrs_update
[vnfr
["_id"]],
1243 process_params
=_process_net_params
,
1246 target_list
= target_vnf
.get("vdur") if target_vnf
else None
1247 step
= "process VNF={} VDUs".format(vnfr_id
)
1249 target_list
=target_list
or [],
1250 existing_list
=vnfr
.get("vdur") or [],
1251 db_record
="vnfrs:{}:vdur".format(vnfr_id
),
1252 db_update
=db_vnfrs_update
[vnfr
["_id"]],
1255 process_params
=_process_vdu_params
,
1258 for db_task
in db_new_tasks
:
1259 step
= "Updating database, Appending tasks to ro_tasks"
1260 target_id
= db_task
.pop("target_id")
1261 common_id
= db_task
.get("common_id")
1267 "target_id": target_id
,
1268 "tasks.common_id": common_id
,
1270 update_dict
={"to_check_at": now
, "modified_at": now
},
1271 push
={"tasks": db_task
},
1272 fail_on_empty
=False,
1276 if not self
.db
.set_one(
1279 "target_id": target_id
,
1280 "tasks.target_record": db_task
["target_record"],
1282 update_dict
={"to_check_at": now
, "modified_at": now
},
1283 push
={"tasks": db_task
},
1284 fail_on_empty
=False,
1287 step
= "Updating database, Creating ro_tasks"
1288 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
1290 self
.db
.create("ro_tasks", db_ro_task
)
1292 step
= "Updating database, nsrs"
1294 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
1296 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
1298 step
= "Updating database, vnfrs={}".format(vnfr_id
)
1299 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
1303 + "Exit. Created {} ro_tasks; {} tasks".format(
1304 nb_ro_tasks
, len(db_new_tasks
)
1309 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
1313 except Exception as e
:
1314 if isinstance(e
, (DbException
, NsException
)):
1316 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
1319 e
= traceback_format_exc()
1320 self
.logger
.critical(
1321 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
1325 raise NsException(e
)
1327 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
1328 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
1329 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
1331 with self
.write_lock
:
1333 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
1334 except NsWorkerException
as e
:
1335 raise NsException(e
)
1337 return None, None, True
1339 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1340 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
1341 # .format(version, nsr_id, action_id, indata))
1345 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
1346 global_status
= "DONE"
1349 for ro_task
in ro_tasks
:
1350 for task
in ro_task
["tasks"]:
1351 if task
and task
["action_id"] == action_id
:
1352 task_list
.append(task
)
1355 if task
["status"] == "FAILED":
1356 global_status
= "FAILED"
1357 error_text
= "Error at {} {}: {}".format(
1358 task
["action"].lower(),
1360 ro_task
["vim_info"].get("vim_details") or "unknown",
1362 details
.append(error_text
)
1363 elif task
["status"] in ("SCHEDULED", "BUILD"):
1364 if global_status
!= "FAILED":
1365 global_status
= "BUILD"
1370 "status": global_status
,
1371 "details": ". ".join(details
)
1373 else "progress {}/{}".format(done
, total
),
1375 "action_id": action_id
,
1379 return return_data
, None, True
1381 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1383 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
1384 session
, indata
, version
, nsr_id
, action_id
1388 return None, None, True
1390 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1391 nsrs
= self
.db
.get_list("nsrs", {})
1395 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
1397 return return_data
, None, True
1399 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1400 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
1403 for ro_task
in ro_tasks
:
1404 for task
in ro_task
["tasks"]:
1405 if task
["action_id"] not in return_data
:
1406 return_data
.append(task
["action_id"])
1408 return return_data
, None, True