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 uuid
import uuid4
27 from cryptography
.hazmat
.backends
import default_backend
as crypto_default_backend
28 from cryptography
.hazmat
.primitives
import serialization
as crypto_serialization
29 from cryptography
.hazmat
.primitives
.asymmetric
import rsa
38 from osm_common
import (
45 version
as common_version
,
47 from osm_common
.dbbase
import DbException
48 from osm_common
.fsbase
import 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]
78 except Exception as error
:
79 logging
.exception(f
"{error} occured while getting process id")
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
):
333 undefined
=StrictUndefined
,
334 autoescape
=select_autoescape(default_for_string
=True, default
=True),
336 template
= env
.from_string(cloud_init_content
)
338 return template
.render(params
or {})
339 except UndefinedError
as e
:
341 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
342 "inside the 'additionalParamsForVnf' block".format(e
, context
)
344 except (TemplateError
, TemplateNotFound
) as e
:
346 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
351 def _create_db_ro_nsrs(self
, nsr_id
, now
):
353 key
= rsa
.generate_private_key(
354 backend
=crypto_default_backend(), public_exponent
=65537, key_size
=2048
356 private_key
= key
.private_bytes(
357 crypto_serialization
.Encoding
.PEM
,
358 crypto_serialization
.PrivateFormat
.PKCS8
,
359 crypto_serialization
.NoEncryption(),
361 public_key
= key
.public_key().public_bytes(
362 crypto_serialization
.Encoding
.OpenSSH
,
363 crypto_serialization
.PublicFormat
.OpenSSH
,
365 private_key
= private_key
.decode("utf8")
366 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
367 i
= private_key
.find("\n")
368 private_key
= "-----BEGIN RSA PRIVATE KEY-----" + private_key
[i
:]
369 public_key
= public_key
.decode("utf8")
370 except Exception as e
:
371 raise NsException("Cannot create ssh-keys: {}".format(e
))
373 schema_version
= "1.1"
374 private_key_encrypted
= self
.db
.encrypt(
375 private_key
, schema_version
=schema_version
, salt
=nsr_id
382 "schema_version": schema_version
,
384 "public_key": public_key
,
385 "private_key": private_key_encrypted
,
388 self
.db
.create("ro_nsrs", db_content
)
392 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
393 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
394 validate_input(indata
, deploy_schema
)
395 action_id
= indata
.get("action_id", str(uuid4()))
397 # get current deployment
398 db_nsr_update
= {} # update operation on nsrs
400 db_vnfrs
= {} # vnf's info indexed by _id
401 nb_ro_tasks
= 0 # for logging
402 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
404 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
405 self
.logger
.debug(logging_text
+ "Enter")
408 step
= "Getting ns and vnfr record from db"
409 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
411 tasks_by_target_record_id
= {}
412 # read from db: vnf's of this ns
413 step
= "Getting vnfrs from db"
414 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
416 if not db_vnfrs_list
:
417 raise NsException("Cannot obtain associated VNF for ns")
419 for vnfr
in db_vnfrs_list
:
420 db_vnfrs
[vnfr
["_id"]] = vnfr
421 db_vnfrs_update
[vnfr
["_id"]] = {}
424 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
427 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
429 ro_nsr_public_key
= db_ro_nsr
["public_key"]
431 # check that action_id is not in the list of actions. Suffixed with :index
432 if action_id
in db_ro_nsr
["actions"]:
436 new_action_id
= "{}:{}".format(action_id
, index
)
438 if new_action_id
not in db_ro_nsr
["actions"]:
439 action_id
= new_action_id
442 + "Changing action_id in use to {}".format(action_id
)
461 "target_id": target_id
, # it will be removed before pushing at database
462 "action_id": action_id
,
464 "task_id": "{}:{}".format(action_id
, 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
479 def _create_ro_task(target_id
, task
):
484 _id
= task
["task_id"]
489 "target_id": target_id
,
492 "created_items": None,
507 def _process_image_params(target_image
, vim_info
, target_record_id
):
510 if target_image
.get("image"):
511 find_params
["filter_dict"] = {"name": target_image
.get("image")}
513 if target_image
.get("vim_image_id"):
514 find_params
["filter_dict"] = {
515 "id": target_image
.get("vim_image_id")
518 if target_image
.get("image_checksum"):
519 find_params
["filter_dict"] = {
520 "checksum": target_image
.get("image_checksum")
523 return {"find_params": find_params
}
525 def _process_flavor_params(target_flavor
, vim_info
, target_record_id
):
526 def _get_resource_allocation_params(quota_descriptor
):
528 read the quota_descriptor from vnfd and fetch the resource allocation properties from the
530 :param quota_descriptor: cpu/mem/vif/disk-io quota descriptor
531 :return: quota params for limit, reserve, shares from the descriptor object
535 if quota_descriptor
.get("limit"):
536 quota
["limit"] = int(quota_descriptor
["limit"])
538 if quota_descriptor
.get("reserve"):
539 quota
["reserve"] = int(quota_descriptor
["reserve"])
541 if quota_descriptor
.get("shares"):
542 quota
["shares"] = int(quota_descriptor
["shares"])
549 "disk": int(target_flavor
["storage-gb"]),
550 "ram": int(target_flavor
["memory-mb"]),
551 "vcpus": int(target_flavor
["vcpu-count"]),
557 for vnf
in indata
.get("vnf", []):
558 for vdur
in vnf
.get("vdur", []):
559 if vdur
.get("ns-flavor-id") == target_flavor
["id"]:
562 for storage
in target_vdur
.get("virtual-storages", []):
564 storage
.get("type-of-storage")
565 == "etsi-nfv-descriptors:ephemeral-storage"
567 flavor_data
["ephemeral"] = int(
568 storage
.get("size-of-storage", 0)
571 storage
.get("type-of-storage")
572 == "etsi-nfv-descriptors:swap-storage"
574 flavor_data
["swap"] = int(storage
.get("size-of-storage", 0))
576 if target_flavor
.get("guest-epa"):
580 if target_flavor
["guest-epa"].get("numa-node-policy"):
581 numa_node_policy
= target_flavor
["guest-epa"].get(
585 if numa_node_policy
.get("node"):
586 numa_node
= numa_node_policy
["node"][0]
588 if numa_node
.get("num-cores"):
589 numa
["cores"] = numa_node
["num-cores"]
592 if numa_node
.get("paired-threads"):
593 if numa_node
["paired-threads"].get(
596 numa
["paired-threads"] = int(
597 numa_node
["paired-threads"][
604 numa_node
["paired-threads"].get("paired-thread-ids")
606 numa
["paired-threads-id"] = []
608 for pair
in numa_node
["paired-threads"][
611 numa
["paired-threads-id"].append(
613 str(pair
["thread-a"]),
614 str(pair
["thread-b"]),
618 if numa_node
.get("num-threads"):
619 numa
["threads"] = int(numa_node
["num-threads"])
622 if numa_node
.get("memory-mb"):
623 numa
["memory"] = max(
624 int(numa_node
["memory-mb"] / 1024), 1
627 if target_flavor
["guest-epa"].get("mempage-size"):
628 extended
["mempage-size"] = target_flavor
["guest-epa"].get(
633 target_flavor
["guest-epa"].get("cpu-pinning-policy")
637 target_flavor
["guest-epa"]["cpu-pinning-policy"]
641 target_flavor
["guest-epa"].get(
642 "cpu-thread-pinning-policy"
644 and target_flavor
["guest-epa"][
645 "cpu-thread-pinning-policy"
649 numa
["cores"] = max(flavor_data
["vcpus"], 1)
651 numa
["threads"] = max(flavor_data
["vcpus"], 1)
655 if target_flavor
["guest-epa"].get("cpu-quota") and not epa_vcpu_set
:
656 cpuquota
= _get_resource_allocation_params(
657 target_flavor
["guest-epa"].get("cpu-quota")
661 extended
["cpu-quota"] = cpuquota
663 if target_flavor
["guest-epa"].get("mem-quota"):
664 vduquota
= _get_resource_allocation_params(
665 target_flavor
["guest-epa"].get("mem-quota")
669 extended
["mem-quota"] = vduquota
671 if target_flavor
["guest-epa"].get("disk-io-quota"):
672 diskioquota
= _get_resource_allocation_params(
673 target_flavor
["guest-epa"].get("disk-io-quota")
677 extended
["disk-io-quota"] = diskioquota
679 if target_flavor
["guest-epa"].get("vif-quota"):
680 vifquota
= _get_resource_allocation_params(
681 target_flavor
["guest-epa"].get("vif-quota")
685 extended
["vif-quota"] = vifquota
688 extended
["numas"] = [numa
]
691 flavor_data
["extended"] = extended
693 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
694 flavor_data_name
= flavor_data
.copy()
695 flavor_data_name
["name"] = target_flavor
["name"]
696 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
700 def _process_affinity_group_params(
701 target_affinity_group
, vim_info
, target_record_id
705 affinity_group_data
= {
706 "name": target_affinity_group
["name"],
707 "type": target_affinity_group
["type"],
708 "scope": target_affinity_group
["scope"],
711 if target_affinity_group
.get("vim-affinity-group-id"):
713 "vim-affinity-group-id"
714 ] = target_affinity_group
["vim-affinity-group-id"]
716 extra_dict
["params"] = {
717 "affinity_group_data": affinity_group_data
,
722 def _ip_profile_2_ro(ip_profile
):
728 if "v4" in ip_profile
.get("ip-version", "ipv4")
730 "subnet_address": ip_profile
.get("subnet-address"),
731 "gateway_address": ip_profile
.get("gateway-address"),
732 "dhcp_enabled": ip_profile
.get("dhcp-params", {}).get(
735 "dhcp_start_address": ip_profile
.get("dhcp-params", {}).get(
736 "start-address", None
738 "dhcp_count": ip_profile
.get("dhcp-params", {}).get("count", None),
741 if ip_profile
.get("dns-server"):
742 ro_ip_profile
["dns_address"] = ";".join(
743 [v
["address"] for v
in ip_profile
["dns-server"]]
746 if ip_profile
.get("security-group"):
747 ro_ip_profile
["security_group"] = ip_profile
["security-group"]
751 def _process_net_params(target_vld
, vim_info
, target_record_id
):
755 if vim_info
.get("sdn"):
756 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
757 # ns_preffix = "nsrs:{}".format(nsr_id)
758 # remove the ending ".sdn
759 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
760 extra_dict
["params"] = {
762 for k
in ("sdn-ports", "target_vim", "vlds", "type")
766 # TODO needed to add target_id in the dependency.
767 if vim_info
.get("target_vim"):
768 extra_dict
["depends_on"] = [
769 vim_info
.get("target_vim") + " " + vld_target_record_id
774 if vim_info
.get("vim_network_name"):
775 extra_dict
["find_params"] = {
776 "filter_dict": {"name": vim_info
.get("vim_network_name")}
778 elif vim_info
.get("vim_network_id"):
779 extra_dict
["find_params"] = {
780 "filter_dict": {"id": vim_info
.get("vim_network_id")}
782 elif target_vld
.get("mgmt-network"):
783 extra_dict
["find_params"] = {"mgmt": True, "name": target_vld
["id"]}
786 extra_dict
["params"] = {
787 "net_name": "{}-{}".format(
789 target_vld
.get("name", target_vld
["id"])[:16],
791 "ip_profile": _ip_profile_2_ro(vim_info
.get("ip_profile")),
792 "provider_network_profile": vim_info
.get("provider_network"),
795 if not target_vld
.get("underlay"):
796 extra_dict
["params"]["net_type"] = "bridge"
798 extra_dict
["params"]["net_type"] = (
799 "ptp" if target_vld
.get("type") == "ELINE" else "data"
804 def _process_vdu_params(target_vdu
, vim_info
, target_record_id
):
809 nonlocal vdu2cloud_init
810 nonlocal tasks_by_target_record_id
812 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
813 ns_preffix
= "nsrs:{}".format(nsr_id
)
814 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
815 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
816 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
819 # If the position info is provided for all the interfaces, it will be sorted
820 # according to position number ascendingly.
822 i
.get("position") + 1
823 for i
in target_vdu
["interfaces"]
824 if i
.get("position") is not None
826 sorted_interfaces
= sorted(
827 target_vdu
["interfaces"],
828 key
=lambda x
: (x
.get("position") is None, x
.get("position")),
830 target_vdu
["interfaces"] = sorted_interfaces
832 # If the position info is provided for some interfaces but not all of them, the interfaces
833 # which has specific position numbers will be placed and others' positions will not be taken care.
836 i
.get("position") + 1
837 for i
in target_vdu
["interfaces"]
838 if i
.get("position") is not None
840 n
= len(target_vdu
["interfaces"])
841 sorted_interfaces
= [-1] * n
844 if target_vdu
["interfaces"][k
].get("position"):
845 idx
= target_vdu
["interfaces"][k
]["position"]
846 sorted_interfaces
[idx
- 1] = target_vdu
["interfaces"][k
]
849 if not target_vdu
["interfaces"][m
].get("position"):
850 idy
= sorted_interfaces
.index(-1)
851 sorted_interfaces
[idy
] = target_vdu
["interfaces"][m
]
854 target_vdu
["interfaces"] = sorted_interfaces
856 # If the position info is not provided for the interfaces, interfaces will be attached
857 # according to the order in the VNFD.
858 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
859 if interface
.get("ns-vld-id"):
860 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
861 elif interface
.get("vnf-vld-id"):
862 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
865 "Interface {} from vdu {} not connected to any vld".format(
866 iface_index
, target_vdu
["vdu-name"]
870 continue # interface not connected to any vld
872 extra_dict
["depends_on"].append(net_text
)
874 if "port-security-enabled" in interface
:
875 interface
["port_security"] = interface
.pop(
876 "port-security-enabled"
879 if "port-security-disable-strategy" in interface
:
880 interface
["port_security_disable_strategy"] = interface
.pop(
881 "port-security-disable-strategy"
886 for x
, v
in interface
.items()
892 "port_security_disable_strategy",
896 net_item
["net_id"] = "TASK-" + net_text
897 net_item
["type"] = "virtual"
899 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
900 # TODO floating_ip: True/False (or it can be None)
901 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
902 # mark the net create task as type data
904 tasks_by_target_record_id
, net_text
, "params", "net_type"
906 tasks_by_target_record_id
[net_text
]["params"][
910 net_item
["use"] = "data"
911 net_item
["model"] = interface
["type"]
912 net_item
["type"] = interface
["type"]
914 interface
.get("type") == "OM-MGMT"
915 or interface
.get("mgmt-interface")
916 or interface
.get("mgmt-vnf")
918 net_item
["use"] = "mgmt"
920 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
921 net_item
["use"] = "bridge"
922 net_item
["model"] = interface
.get("type")
924 if interface
.get("ip-address"):
925 net_item
["ip_address"] = interface
["ip-address"]
927 if interface
.get("mac-address"):
928 net_item
["mac_address"] = interface
["mac-address"]
930 net_list
.append(net_item
)
932 if interface
.get("mgmt-vnf"):
933 extra_dict
["mgmt_vnf_interface"] = iface_index
934 elif interface
.get("mgmt-interface"):
935 extra_dict
["mgmt_vdu_interface"] = iface_index
940 if target_vdu
.get("cloud-init"):
941 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
942 vdu2cloud_init
[target_vdu
["cloud-init"]] = self
._get
_cloud
_init
(
943 target_vdu
["cloud-init"]
946 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
947 cloud_config
["user-data"] = self
._parse
_jinja
2(
949 target_vdu
.get("additionalParams"),
950 target_vdu
["cloud-init"],
953 if target_vdu
.get("boot-data-drive"):
954 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
958 if target_vdu
.get("ssh-keys"):
959 ssh_keys
+= target_vdu
.get("ssh-keys")
961 if target_vdu
.get("ssh-access-required"):
962 ssh_keys
.append(ro_nsr_public_key
)
965 cloud_config
["key-pairs"] = ssh_keys
967 persistent_root_disk
= {}
969 vnfd_id
= vnfr
["vnfd-id"]
970 vnfd
= self
.db
.get_one("vnfds", {"_id": vnfd_id
})
971 for vdu
in vnfd
.get("vdu", ()):
972 if vdu
["name"] == target_vdu
["vdu-name"]:
973 for vsd
in vnfd
.get("virtual-storage-desc", ()):
976 == vdu
.get("virtual-storage-desc", [[]])[0]
981 ) == "persistent-storage:persistent-storage" and root_disk
.get(
984 persistent_root_disk
[vsd
["id"]] = {
985 "image_id": vdu
.get("sw-image-desc"),
986 "size": root_disk
["size-of-storage"],
988 disk_list
.append(persistent_root_disk
[vsd
["id"]])
990 if target_vdu
.get("virtual-storages"):
991 for disk
in target_vdu
["virtual-storages"]:
993 disk
.get("type-of-storage")
994 == "persistent-storage:persistent-storage"
995 and disk
["id"] not in persistent_root_disk
.keys()
997 disk_list
.append({"size": disk
["size-of-storage"]})
999 affinity_group_list
= []
1001 if target_vdu
.get("affinity-or-anti-affinity-group-id"):
1003 for affinity_group_id
in target_vdu
[
1004 "affinity-or-anti-affinity-group-id"
1006 affinity_group_text
= (
1008 + ":affinity-or-anti-affinity-group."
1012 extra_dict
["depends_on"].append(affinity_group_text
)
1013 affinity_group
["affinity_group_id"] = (
1014 "TASK-" + affinity_group_text
1016 affinity_group_list
.append(affinity_group
)
1018 extra_dict
["params"] = {
1019 "name": "{}-{}-{}-{}".format(
1020 indata
["name"][:16],
1021 vnfr
["member-vnf-index-ref"][:16],
1022 target_vdu
["vdu-name"][:32],
1023 target_vdu
.get("count-index") or 0,
1025 "description": target_vdu
["vdu-name"],
1027 "image_id": "TASK-" + image_text
,
1028 "flavor_id": "TASK-" + flavor_text
,
1029 "affinity_group_list": affinity_group_list
,
1030 "net_list": net_list
,
1031 "cloud_config": cloud_config
or None,
1032 "disk_list": disk_list
,
1033 "availability_zone_index": None, # TODO
1034 "availability_zone_list": None, # TODO
1048 nonlocal db_new_tasks
1049 nonlocal tasks_by_target_record_id
1052 # ensure all the target_list elements has an "id". If not assign the index as id
1053 for target_index
, tl
in enumerate(target_list
):
1054 if tl
and not tl
.get("id"):
1055 tl
["id"] = str(target_index
)
1057 # step 1 items (networks,vdus,...) to be deleted/updated
1058 for item_index
, existing_item
in enumerate(existing_list
):
1060 (t
for t
in target_list
if t
["id"] == existing_item
["id"]), None
1063 for target_vim
, existing_viminfo
in existing_item
.get(
1066 if existing_viminfo
is None:
1070 target_viminfo
= target_item
.get("vim_info", {}).get(
1074 target_viminfo
= None
1076 if target_viminfo
is None:
1078 self
._assign
_vim
(target_vim
)
1079 target_record_id
= "{}.{}".format(
1080 db_record
, existing_item
["id"]
1084 if target_vim
.startswith("sdn") or target_vim
.startswith(
1087 # item must be sdn-net instead of net if target_vim is a sdn
1089 target_record_id
+= ".sdn"
1091 task
= _create_task(
1095 target_record
="{}.{}.vim_info.{}".format(
1096 db_record
, item_index
, target_vim
1098 target_record_id
=target_record_id
,
1100 tasks_by_target_record_id
[target_record_id
] = task
1101 db_new_tasks
.append(task
)
1103 # TODO check one by one the vims to be created/deleted
1105 # step 2 items (networks,vdus,...) to be created
1106 for target_item
in target_list
:
1109 for item_index
, existing_item
in enumerate(existing_list
):
1110 if existing_item
["id"] == target_item
["id"]:
1114 db_update
[db_path
+ ".{}".format(item_index
)] = target_item
1115 existing_list
.append(target_item
)
1116 existing_item
= None
1118 for target_vim
, target_viminfo
in target_item
.get(
1121 existing_viminfo
= None
1124 existing_viminfo
= existing_item
.get("vim_info", {}).get(
1128 # TODO check if different. Delete and create???
1129 # TODO delete if not exist
1130 if existing_viminfo
is not None:
1133 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
1136 if target_vim
.startswith("sdn") or target_vim
.startswith("wim"):
1137 # item must be sdn-net instead of net if target_vim is a sdn
1139 target_record_id
+= ".sdn"
1141 extra_dict
= process_params(
1142 target_item
, target_viminfo
, target_record_id
1144 self
._assign
_vim
(target_vim
)
1145 task
= _create_task(
1149 target_record
="{}.{}.vim_info.{}".format(
1150 db_record
, item_index
, target_vim
1152 target_record_id
=target_record_id
,
1153 extra_dict
=extra_dict
,
1155 tasks_by_target_record_id
[target_record_id
] = task
1156 db_new_tasks
.append(task
)
1158 if target_item
.get("common_id"):
1159 task
["common_id"] = target_item
["common_id"]
1161 db_update
[db_path
+ ".{}".format(item_index
)] = target_item
1163 def _process_action(indata
):
1164 nonlocal db_new_tasks
1169 if indata
["action"]["action"] == "inject_ssh_key":
1170 key
= indata
["action"].get("key")
1171 user
= indata
["action"].get("user")
1172 password
= indata
["action"].get("password")
1174 for vnf
in indata
.get("vnf", ()):
1175 if vnf
["_id"] not in db_vnfrs
:
1176 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
1178 db_vnfr
= db_vnfrs
[vnf
["_id"]]
1180 for target_vdu
in vnf
.get("vdur", ()):
1181 vdu_index
, vdur
= next(
1184 for i_v
in enumerate(db_vnfr
["vdur"])
1185 if i_v
[1]["id"] == target_vdu
["id"]
1192 "Invalid vdu vnf={}.{}".format(
1193 vnf
["_id"], target_vdu
["id"]
1197 target_vim
, vim_info
= next(
1198 k_v
for k_v
in vdur
["vim_info"].items()
1200 self
._assign
_vim
(target_vim
)
1201 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
1202 vnf
["_id"], vdu_index
1206 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
1209 "ip_address": vdur
.get("ip-address"),
1212 "password": password
,
1213 "private_key": db_ro_nsr
["private_key"],
1214 "salt": db_ro_nsr
["_id"],
1215 "schema_version": db_ro_nsr
["_admin"][
1220 task
= _create_task(
1224 target_record
=target_record
,
1225 target_record_id
=None,
1226 extra_dict
=extra_dict
,
1228 db_new_tasks
.append(task
)
1230 with self
.write_lock
:
1231 if indata
.get("action"):
1232 _process_action(indata
)
1234 # compute network differences
1236 step
= "process NS VLDs"
1238 target_list
=indata
["ns"]["vld"] or [],
1239 existing_list
=db_nsr
.get("vld") or [],
1240 db_record
="nsrs:{}:vld".format(nsr_id
),
1241 db_update
=db_nsr_update
,
1244 process_params
=_process_net_params
,
1247 step
= "process NS images"
1249 target_list
=indata
.get("image") or [],
1250 existing_list
=db_nsr
.get("image") or [],
1251 db_record
="nsrs:{}:image".format(nsr_id
),
1252 db_update
=db_nsr_update
,
1255 process_params
=_process_image_params
,
1258 step
= "process NS flavors"
1260 target_list
=indata
.get("flavor") or [],
1261 existing_list
=db_nsr
.get("flavor") or [],
1262 db_record
="nsrs:{}:flavor".format(nsr_id
),
1263 db_update
=db_nsr_update
,
1266 process_params
=_process_flavor_params
,
1269 step
= "process NS Affinity Groups"
1271 target_list
=indata
.get("affinity-or-anti-affinity-group") or [],
1272 existing_list
=db_nsr
.get("affinity-or-anti-affinity-group")
1274 db_record
="nsrs:{}:affinity-or-anti-affinity-group".format(
1277 db_update
=db_nsr_update
,
1278 db_path
="affinity-or-anti-affinity-group",
1279 item
="affinity-or-anti-affinity-group",
1280 process_params
=_process_affinity_group_params
,
1284 for vnfr_id
, vnfr
in db_vnfrs
.items():
1285 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1286 step
= "process VNF={} VLDs".format(vnfr_id
)
1290 for vnf
in indata
.get("vnf", ())
1291 if vnf
["_id"] == vnfr_id
1295 target_list
= target_vnf
.get("vld") if target_vnf
else None
1297 target_list
=target_list
or [],
1298 existing_list
=vnfr
.get("vld") or [],
1299 db_record
="vnfrs:{}:vld".format(vnfr_id
),
1300 db_update
=db_vnfrs_update
[vnfr
["_id"]],
1303 process_params
=_process_net_params
,
1306 target_list
= target_vnf
.get("vdur") if target_vnf
else None
1307 step
= "process VNF={} VDUs".format(vnfr_id
)
1309 target_list
=target_list
or [],
1310 existing_list
=vnfr
.get("vdur") or [],
1311 db_record
="vnfrs:{}:vdur".format(vnfr_id
),
1312 db_update
=db_vnfrs_update
[vnfr
["_id"]],
1315 process_params
=_process_vdu_params
,
1318 for db_task
in db_new_tasks
:
1319 step
= "Updating database, Appending tasks to ro_tasks"
1320 target_id
= db_task
.pop("target_id")
1321 common_id
= db_task
.get("common_id")
1327 "target_id": target_id
,
1328 "tasks.common_id": common_id
,
1330 update_dict
={"to_check_at": now
, "modified_at": now
},
1331 push
={"tasks": db_task
},
1332 fail_on_empty
=False,
1336 if not self
.db
.set_one(
1339 "target_id": target_id
,
1340 "tasks.target_record": db_task
["target_record"],
1342 update_dict
={"to_check_at": now
, "modified_at": now
},
1343 push
={"tasks": db_task
},
1344 fail_on_empty
=False,
1347 step
= "Updating database, Creating ro_tasks"
1348 db_ro_task
= _create_ro_task(target_id
, db_task
)
1350 self
.db
.create("ro_tasks", db_ro_task
)
1352 step
= "Updating database, nsrs"
1354 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
1356 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
1358 step
= "Updating database, vnfrs={}".format(vnfr_id
)
1359 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
1363 + "Exit. Created {} ro_tasks; {} tasks".format(
1364 nb_ro_tasks
, len(db_new_tasks
)
1369 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
1373 except Exception as e
:
1374 if isinstance(e
, (DbException
, NsException
)):
1376 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
1379 e
= traceback_format_exc()
1380 self
.logger
.critical(
1381 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
1385 raise NsException(e
)
1387 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
1388 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
1389 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
1391 with self
.write_lock
:
1393 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
1394 except NsWorkerException
as e
:
1395 raise NsException(e
)
1397 return None, None, True
1399 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1400 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
1401 # .format(version, nsr_id, action_id, indata))
1405 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
1406 global_status
= "DONE"
1409 for ro_task
in ro_tasks
:
1410 for task
in ro_task
["tasks"]:
1411 if task
and task
["action_id"] == action_id
:
1412 task_list
.append(task
)
1415 if task
["status"] == "FAILED":
1416 global_status
= "FAILED"
1417 error_text
= "Error at {} {}: {}".format(
1418 task
["action"].lower(),
1420 ro_task
["vim_info"].get("vim_details") or "unknown",
1422 details
.append(error_text
)
1423 elif task
["status"] in ("SCHEDULED", "BUILD"):
1424 if global_status
!= "FAILED":
1425 global_status
= "BUILD"
1430 "status": global_status
,
1431 "details": ". ".join(details
)
1433 else "progress {}/{}".format(done
, total
),
1435 "action_id": action_id
,
1439 return return_data
, None, True
1441 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1443 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
1444 session
, indata
, version
, nsr_id
, action_id
1448 return None, None, True
1450 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1451 nsrs
= self
.db
.get_list("nsrs", {})
1455 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
1457 return return_data
, None, True
1459 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1460 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
1463 for ro_task
in ro_tasks
:
1464 for task
in ro_task
["tasks"]:
1465 if task
["action_id"] not in return_data
:
1466 return_data
.append(task
["action_id"])
1468 return return_data
, None, True