1 # -*- coding: utf-8 -*-
4 # Copyright 2020 Telefonica Investigacion y Desarrollo, S.A.U.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
19 from http
import HTTPStatus
21 from random
import choice
as random_choice
22 from threading
import Lock
24 from traceback
import format_exc
as traceback_format_exc
25 from typing
import Any
, Dict
, Tuple
, Type
26 from uuid
import uuid4
28 from cryptography
.hazmat
.backends
import default_backend
as crypto_default_backend
29 from cryptography
.hazmat
.primitives
import serialization
as crypto_serialization
30 from cryptography
.hazmat
.primitives
.asymmetric
import rsa
38 from osm_common
import (
45 version
as common_version
,
47 from osm_common
.dbbase
import DbBase
, DbException
48 from osm_common
.fsbase
import FsBase
, FsException
49 from osm_common
.msgbase
import MsgException
50 from osm_ng_ro
.ns_thread
import deep_get
, NsWorker
, NsWorkerException
51 from osm_ng_ro
.validation
import deploy_schema
, validate_input
53 __author__
= "Alfonso Tierno <alfonso.tiernosepulveda@telefonica.com>"
54 min_common_version
= "0.1.16"
57 class NsException(Exception):
58 def __init__(self
, message
, http_code
=HTTPStatus
.BAD_REQUEST
):
59 self
.http_code
= http_code
60 super(Exception, self
).__init
__(message
)
65 Obtain a unique ID for this process. If running from inside docker, it will get docker ID. If not it
66 will provide a random one
69 # Try getting docker id. If fails, get pid
71 with
open("/proc/self/cgroup", "r") as f
:
72 text_id_
= f
.readline()
73 _
, _
, text_id
= text_id_
.rpartition("/")
74 text_id
= text_id
.replace("\n", "")[:12]
82 return "".join(random_choice("0123456789abcdef") for _
in range(12))
86 """utility for compare dot separate versions. Fills with zeros to proper number comparison"""
89 for point
in v
.split("."):
90 filled
.append(point
.zfill(8))
101 # self.operations = None
103 # ^ Getting logger inside method self.start because parent logger (ro) is not available yet.
104 # If done now it will not be linked to parent not getting its handler and level
106 self
.write_lock
= None
107 self
.vims_assigned
= {}
111 self
.process_params_function_map
= {
112 "net": Ns
._process
_net
_params
,
113 "image": Ns
._process
_image
_params
,
114 "flavor": Ns
._process
_flavor
_params
,
115 "vdu": Ns
._process
_vdu
_params
,
116 "affinity-or-anti-affinity-group": Ns
._process
_affinity
_group
_params
,
123 "affinity-or-anti-affinity-group": "affinity-or-anti-affinity-group",
126 def init_db(self
, target_version
):
129 def start(self
, config
):
131 Connect to database, filesystem storage, and messaging
132 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
133 :param config: Configuration of db, storage, etc
137 self
.config
["process_id"] = get_process_id() # used for HA identity
138 self
.logger
= logging
.getLogger("ro.ns")
140 # check right version of common
141 if versiontuple(common_version
) < versiontuple(min_common_version
):
143 "Not compatible osm/common version '{}'. Needed '{}' or higher".format(
144 common_version
, min_common_version
150 if config
["database"]["driver"] == "mongo":
151 self
.db
= dbmongo
.DbMongo()
152 self
.db
.db_connect(config
["database"])
153 elif config
["database"]["driver"] == "memory":
154 self
.db
= dbmemory
.DbMemory()
155 self
.db
.db_connect(config
["database"])
158 "Invalid configuration param '{}' at '[database]':'driver'".format(
159 config
["database"]["driver"]
164 if config
["storage"]["driver"] == "local":
165 self
.fs
= fslocal
.FsLocal()
166 self
.fs
.fs_connect(config
["storage"])
167 elif config
["storage"]["driver"] == "mongo":
168 self
.fs
= fsmongo
.FsMongo()
169 self
.fs
.fs_connect(config
["storage"])
170 elif config
["storage"]["driver"] is None:
174 "Invalid configuration param '{}' at '[storage]':'driver'".format(
175 config
["storage"]["driver"]
180 if config
["message"]["driver"] == "local":
181 self
.msg
= msglocal
.MsgLocal()
182 self
.msg
.connect(config
["message"])
183 elif config
["message"]["driver"] == "kafka":
184 self
.msg
= msgkafka
.MsgKafka()
185 self
.msg
.connect(config
["message"])
188 "Invalid configuration param '{}' at '[message]':'driver'".format(
189 config
["message"]["driver"]
193 # TODO load workers to deal with exising database tasks
195 self
.write_lock
= Lock()
196 except (DbException
, FsException
, MsgException
) as e
:
197 raise NsException(str(e
), http_code
=e
.http_code
)
199 def get_assigned_vims(self
):
200 return list(self
.vims_assigned
.keys())
205 self
.db
.db_disconnect()
208 self
.fs
.fs_disconnect()
211 self
.msg
.disconnect()
213 self
.write_lock
= None
214 except (DbException
, FsException
, MsgException
) as e
:
215 raise NsException(str(e
), http_code
=e
.http_code
)
217 for worker
in self
.workers
:
218 worker
.insert_task(("terminate",))
220 def _create_worker(self
):
222 Look for a worker thread in idle status. If not found it creates one unless the number of threads reach the
223 limit of 'server.ns_threads' configuration. If reached, it just assigns one existing thread
224 return the index of the assigned worker thread. Worker threads are storead at self.workers
226 # Look for a thread in idle status
230 for i
in range(len(self
.workers
))
231 if self
.workers
[i
] and self
.workers
[i
].idle
236 if worker_id
is not None:
237 # unset idle status to avoid race conditions
238 self
.workers
[worker_id
].idle
= False
240 worker_id
= len(self
.workers
)
242 if worker_id
< self
.config
["global"]["server.ns_threads"]:
243 # create a new worker
245 NsWorker(worker_id
, self
.config
, self
.plugins
, self
.db
)
247 self
.workers
[worker_id
].start()
249 # reached maximum number of threads, assign VIM to an existing one
250 worker_id
= self
.next_worker
251 self
.next_worker
= (self
.next_worker
+ 1) % self
.config
["global"][
257 def assign_vim(self
, target_id
):
258 with self
.write_lock
:
259 return self
._assign
_vim
(target_id
)
261 def _assign_vim(self
, target_id
):
262 if target_id
not in self
.vims_assigned
:
263 worker_id
= self
.vims_assigned
[target_id
] = self
._create
_worker
()
264 self
.workers
[worker_id
].insert_task(("load_vim", target_id
))
266 def reload_vim(self
, target_id
):
267 # send reload_vim to the thread working with this VIM and inform all that a VIM has been changed,
268 # this is because database VIM information is cached for threads working with SDN
269 with self
.write_lock
:
270 for worker
in self
.workers
:
271 if worker
and not worker
.idle
:
272 worker
.insert_task(("reload_vim", target_id
))
274 def unload_vim(self
, target_id
):
275 with self
.write_lock
:
276 return self
._unload
_vim
(target_id
)
278 def _unload_vim(self
, target_id
):
279 if target_id
in self
.vims_assigned
:
280 worker_id
= self
.vims_assigned
[target_id
]
281 self
.workers
[worker_id
].insert_task(("unload_vim", target_id
))
282 del self
.vims_assigned
[target_id
]
284 def check_vim(self
, target_id
):
285 with self
.write_lock
:
286 if target_id
in self
.vims_assigned
:
287 worker_id
= self
.vims_assigned
[target_id
]
289 worker_id
= self
._create
_worker
()
291 worker
= self
.workers
[worker_id
]
292 worker
.insert_task(("check_vim", target_id
))
294 def unload_unused_vims(self
):
295 with self
.write_lock
:
298 for target_id
in self
.vims_assigned
:
299 if not self
.db
.get_one(
302 "target_id": target_id
,
303 "tasks.status": ["SCHEDULED", "BUILD", "DONE", "FAILED"],
307 vims_to_unload
.append(target_id
)
309 for target_id
in vims_to_unload
:
310 self
._unload
_vim
(target_id
)
318 """This method reads cloud init from a file.
320 Note: Not used as cloud init content is provided in the http body.
323 db (Type[DbBase]): [description]
324 fs (Type[FsBase]): [description]
325 location (str): can be 'vnfr_id:file:file_name' or 'vnfr_id:vdu:vdu_idex'
328 NsException: [description]
329 NsException: [description]
334 vnfd_id
, _
, other
= location
.partition(":")
335 _type
, _
, name
= other
.partition(":")
336 vnfd
= db
.get_one("vnfds", {"_id": vnfd_id
})
339 base_folder
= vnfd
["_admin"]["storage"]
340 cloud_init_file
= "{}/{}/cloud_init/{}".format(
341 base_folder
["folder"], base_folder
["pkg-dir"], name
346 "Cannot read file '{}'. Filesystem not loaded, change configuration at storage.driver".format(
351 with fs
.file_open(cloud_init_file
, "r") as ci_file
:
352 cloud_init_content
= ci_file
.read()
354 cloud_init_content
= vnfd
["vdu"][int(name
)]["cloud-init"]
356 raise NsException("Mismatch descriptor for cloud init: {}".format(location
))
358 return cloud_init_content
362 cloud_init_content
: str,
363 params
: Dict
[str, Any
],
366 """Function that processes the cloud init to replace Jinja2 encoded parameters.
369 cloud_init_content (str): [description]
370 params (Dict[str, Any]): [description]
371 context (str): [description]
374 NsException: [description]
375 NsException: [description]
381 env
= Environment(undefined
=StrictUndefined
)
382 template
= env
.from_string(cloud_init_content
)
384 return template
.render(params
or {})
385 except UndefinedError
as e
:
387 "Variable '{}' defined at vnfd='{}' must be provided in the instantiation parameters"
388 "inside the 'additionalParamsForVnf' block".format(e
, context
)
390 except (TemplateError
, TemplateNotFound
) as e
:
392 "Error parsing Jinja2 to cloud-init content at vnfd='{}': {}".format(
397 def _create_db_ro_nsrs(self
, nsr_id
, now
):
399 key
= rsa
.generate_private_key(
400 backend
=crypto_default_backend(), public_exponent
=65537, key_size
=2048
402 private_key
= key
.private_bytes(
403 crypto_serialization
.Encoding
.PEM
,
404 crypto_serialization
.PrivateFormat
.PKCS8
,
405 crypto_serialization
.NoEncryption(),
407 public_key
= key
.public_key().public_bytes(
408 crypto_serialization
.Encoding
.OpenSSH
,
409 crypto_serialization
.PublicFormat
.OpenSSH
,
411 private_key
= private_key
.decode("utf8")
412 # Change first line because Paramiko needs a explicit start with 'BEGIN RSA PRIVATE KEY'
413 i
= private_key
.find("\n")
414 private_key
= "-----BEGIN RSA PRIVATE KEY-----" + private_key
[i
:]
415 public_key
= public_key
.decode("utf8")
416 except Exception as e
:
417 raise NsException("Cannot create ssh-keys: {}".format(e
))
419 schema_version
= "1.1"
420 private_key_encrypted
= self
.db
.encrypt(
421 private_key
, schema_version
=schema_version
, salt
=nsr_id
428 "schema_version": schema_version
,
430 "public_key": public_key
,
431 "private_key": private_key_encrypted
,
434 self
.db
.create("ro_nsrs", db_content
)
440 deployment_info
: Dict
[str, Any
],
445 target_record_id
: str,
446 extra_dict
: Dict
[str, Any
] = None,
448 """Function to create task dict from deployment information.
451 deployment_info (Dict[str, Any]): [description]
452 target_id (str): [description]
453 item (str): [description]
454 action (str): [description]
455 target_record (str): [description]
456 target_record_id (str): [description]
457 extra_dict (Dict[str, Any], optional): [description]. Defaults to None.
460 Dict[str, Any]: [description]
463 "target_id": target_id
, # it will be removed before pushing at database
464 "action_id": deployment_info
.get("action_id"),
465 "nsr_id": deployment_info
.get("nsr_id"),
466 "task_id": f
"{deployment_info.get('action_id')}:{deployment_info.get('task_index')}",
467 "status": "SCHEDULED",
470 "target_record": target_record
,
471 "target_record_id": target_record_id
,
475 task
.update(extra_dict
) # params, find_params, depends_on
477 deployment_info
["task_index"] = deployment_info
.get("task_index", 0) + 1
484 task
: Dict
[str, Any
],
486 """Function to create an RO task from task information.
489 target_id (str): [description]
490 task (Dict[str, Any]): [description]
493 Dict[str, Any]: [description]
497 _id
= task
.get("task_id")
502 "target_id": target_id
,
505 "created_items": None,
521 def _process_image_params(
522 target_image
: Dict
[str, Any
],
523 indata
: Dict
[str, Any
],
524 vim_info
: Dict
[str, Any
],
525 target_record_id
: str,
526 **kwargs
: Dict
[str, Any
],
528 """Function to process VDU image parameters.
531 target_image (Dict[str, Any]): [description]
532 indata (Dict[str, Any]): [description]
533 vim_info (Dict[str, Any]): [description]
534 target_record_id (str): [description]
537 Dict[str, Any]: [description]
541 if target_image
.get("image"):
542 find_params
["filter_dict"] = {"name": target_image
.get("image")}
544 if target_image
.get("vim_image_id"):
545 find_params
["filter_dict"] = {"id": target_image
.get("vim_image_id")}
547 if target_image
.get("image_checksum"):
548 find_params
["filter_dict"] = {
549 "checksum": target_image
.get("image_checksum")
552 return {"find_params": find_params
}
555 def _get_resource_allocation_params(
556 quota_descriptor
: Dict
[str, Any
],
558 """Read the quota_descriptor from vnfd and fetch the resource allocation properties from the
562 quota_descriptor (Dict[str, Any]): cpu/mem/vif/disk-io quota descriptor
565 Dict[str, Any]: quota params for limit, reserve, shares from the descriptor object
569 if quota_descriptor
.get("limit"):
570 quota
["limit"] = int(quota_descriptor
["limit"])
572 if quota_descriptor
.get("reserve"):
573 quota
["reserve"] = int(quota_descriptor
["reserve"])
575 if quota_descriptor
.get("shares"):
576 quota
["shares"] = int(quota_descriptor
["shares"])
581 def _process_guest_epa_quota_params(
582 guest_epa_quota
: Dict
[str, Any
],
585 """Function to extract the guest epa quota parameters.
588 guest_epa_quota (Dict[str, Any]): [description]
589 epa_vcpu_set (bool): [description]
592 Dict[str, Any]: [description]
596 if guest_epa_quota
.get("cpu-quota") and not epa_vcpu_set
:
597 cpuquota
= Ns
._get
_resource
_allocation
_params
(
598 guest_epa_quota
.get("cpu-quota")
602 result
["cpu-quota"] = cpuquota
604 if guest_epa_quota
.get("mem-quota"):
605 vduquota
= Ns
._get
_resource
_allocation
_params
(
606 guest_epa_quota
.get("mem-quota")
610 result
["mem-quota"] = vduquota
612 if guest_epa_quota
.get("disk-io-quota"):
613 diskioquota
= Ns
._get
_resource
_allocation
_params
(
614 guest_epa_quota
.get("disk-io-quota")
618 result
["disk-io-quota"] = diskioquota
620 if guest_epa_quota
.get("vif-quota"):
621 vifquota
= Ns
._get
_resource
_allocation
_params
(
622 guest_epa_quota
.get("vif-quota")
626 result
["vif-quota"] = vifquota
631 def _process_guest_epa_numa_params(
632 guest_epa_quota
: Dict
[str, Any
],
633 ) -> Tuple
[Dict
[str, Any
], bool]:
637 guest_epa_quota (Dict[str, Any]): [description]
640 Tuple[Dict[str, Any], bool]: [description]
645 if guest_epa_quota
.get("numa-node-policy"):
646 numa_node_policy
= guest_epa_quota
.get("numa-node-policy")
648 if numa_node_policy
.get("node"):
649 numa_node
= numa_node_policy
["node"][0]
651 if numa_node
.get("num-cores"):
652 numa
["cores"] = numa_node
["num-cores"]
655 paired_threads
= numa_node
.get("paired-threads", {})
656 if paired_threads
.get("num-paired-threads"):
657 numa
["paired-threads"] = int(
658 numa_node
["paired-threads"]["num-paired-threads"]
662 if paired_threads
.get("paired-thread-ids"):
663 numa
["paired-threads-id"] = []
665 for pair
in paired_threads
["paired-thread-ids"]:
666 numa
["paired-threads-id"].append(
668 str(pair
["thread-a"]),
669 str(pair
["thread-b"]),
673 if numa_node
.get("num-threads"):
674 numa
["threads"] = int(numa_node
["num-threads"])
677 if numa_node
.get("memory-mb"):
678 numa
["memory"] = max(int(int(numa_node
["memory-mb"]) / 1024), 1)
680 return numa
, epa_vcpu_set
683 def _process_guest_epa_cpu_pinning_params(
684 guest_epa_quota
: Dict
[str, Any
],
687 ) -> Tuple
[Dict
[str, Any
], bool]:
691 guest_epa_quota (Dict[str, Any]): [description]
692 vcpu_count (int): [description]
693 epa_vcpu_set (bool): [description]
696 Tuple[Dict[str, Any], bool]: [description]
699 local_epa_vcpu_set
= epa_vcpu_set
702 guest_epa_quota
.get("cpu-pinning-policy") == "DEDICATED"
707 if guest_epa_quota
.get("cpu-thread-pinning-policy") != "PREFER"
709 ] = max(vcpu_count
, 1)
710 local_epa_vcpu_set
= True
712 return numa
, local_epa_vcpu_set
715 def _process_epa_params(
716 target_flavor
: Dict
[str, Any
],
721 target_flavor (Dict[str, Any]): [description]
724 Dict[str, Any]: [description]
729 if target_flavor
.get("guest-epa"):
730 guest_epa
= target_flavor
["guest-epa"]
732 numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_numa
_params
(
733 guest_epa_quota
=guest_epa
736 if guest_epa
.get("mempage-size"):
737 extended
["mempage-size"] = guest_epa
.get("mempage-size")
739 tmp_numa
, epa_vcpu_set
= Ns
._process
_guest
_epa
_cpu
_pinning
_params
(
740 guest_epa_quota
=guest_epa
,
741 vcpu_count
=int(target_flavor
.get("vcpu-count", 1)),
742 epa_vcpu_set
=epa_vcpu_set
,
744 numa
.update(tmp_numa
)
747 Ns
._process
_guest
_epa
_quota
_params
(
748 guest_epa_quota
=guest_epa
,
749 epa_vcpu_set
=epa_vcpu_set
,
754 extended
["numas"] = [numa
]
759 def _process_flavor_params(
760 target_flavor
: Dict
[str, Any
],
761 indata
: Dict
[str, Any
],
762 vim_info
: Dict
[str, Any
],
763 target_record_id
: str,
764 **kwargs
: Dict
[str, Any
],
769 target_flavor (Dict[str, Any]): [description]
770 indata (Dict[str, Any]): [description]
771 vim_info (Dict[str, Any]): [description]
772 target_record_id (str): [description]
775 Dict[str, Any]: [description]
778 "disk": int(target_flavor
["storage-gb"]),
779 "ram": int(target_flavor
["memory-mb"]),
780 "vcpus": int(target_flavor
["vcpu-count"]),
784 for vnf
in indata
.get("vnf", []):
785 for vdur
in vnf
.get("vdur", []):
786 if vdur
.get("ns-flavor-id") == target_flavor
["id"]:
789 for storage
in target_vdur
.get("virtual-storages", []):
791 storage
.get("type-of-storage")
792 == "etsi-nfv-descriptors:ephemeral-storage"
794 flavor_data
["ephemeral"] = int(storage
.get("size-of-storage", 0))
795 elif storage
.get("type-of-storage") == "etsi-nfv-descriptors:swap-storage":
796 flavor_data
["swap"] = int(storage
.get("size-of-storage", 0))
798 extended
= Ns
._process
_epa
_params
(target_flavor
)
800 flavor_data
["extended"] = extended
802 extra_dict
= {"find_params": {"flavor_data": flavor_data
}}
803 flavor_data_name
= flavor_data
.copy()
804 flavor_data_name
["name"] = target_flavor
["name"]
805 extra_dict
["params"] = {"flavor_data": flavor_data_name
}
810 def _ip_profile_to_ro(
811 ip_profile
: Dict
[str, Any
],
816 ip_profile (Dict[str, Any]): [description]
819 Dict[str, Any]: [description]
826 if "v4" in ip_profile
.get("ip-version", "ipv4")
828 "subnet_address": ip_profile
.get("subnet-address"),
829 "gateway_address": ip_profile
.get("gateway-address"),
830 "dhcp_enabled": ip_profile
.get("dhcp-params", {}).get("enabled", False),
831 "dhcp_start_address": ip_profile
.get("dhcp-params", {}).get(
832 "start-address", None
834 "dhcp_count": ip_profile
.get("dhcp-params", {}).get("count", None),
837 if ip_profile
.get("dns-server"):
838 ro_ip_profile
["dns_address"] = ";".join(
839 [v
["address"] for v
in ip_profile
["dns-server"] if v
.get("address")]
842 if ip_profile
.get("security-group"):
843 ro_ip_profile
["security_group"] = ip_profile
["security-group"]
848 def _process_net_params(
849 target_vld
: Dict
[str, Any
],
850 indata
: Dict
[str, Any
],
851 vim_info
: Dict
[str, Any
],
852 target_record_id
: str,
853 **kwargs
: Dict
[str, Any
],
855 """Function to process network parameters.
858 target_vld (Dict[str, Any]): [description]
859 indata (Dict[str, Any]): [description]
860 vim_info (Dict[str, Any]): [description]
861 target_record_id (str): [description]
864 Dict[str, Any]: [description]
868 if vim_info
.get("sdn"):
869 # vnf_preffix = "vnfrs:{}".format(vnfr_id)
870 # ns_preffix = "nsrs:{}".format(nsr_id)
871 # remove the ending ".sdn
872 vld_target_record_id
, _
, _
= target_record_id
.rpartition(".")
873 extra_dict
["params"] = {
875 for k
in ("sdn-ports", "target_vim", "vlds", "type")
879 # TODO needed to add target_id in the dependency.
880 if vim_info
.get("target_vim"):
881 extra_dict
["depends_on"] = [
882 f
"{vim_info.get('target_vim')} {vld_target_record_id}"
887 if vim_info
.get("vim_network_name"):
888 extra_dict
["find_params"] = {
890 "name": vim_info
.get("vim_network_name"),
893 elif vim_info
.get("vim_network_id"):
894 extra_dict
["find_params"] = {
896 "id": vim_info
.get("vim_network_id"),
899 elif target_vld
.get("mgmt-network"):
900 extra_dict
["find_params"] = {
902 "name": target_vld
["id"],
906 extra_dict
["params"] = {
908 f
"{indata.get('name')[:16]}-{target_vld.get('name', target_vld.get('id'))[:16]}"
910 "ip_profile": Ns
._ip
_profile
_to
_ro
(vim_info
.get("ip_profile")),
911 "provider_network_profile": vim_info
.get("provider_network"),
914 if not target_vld
.get("underlay"):
915 extra_dict
["params"]["net_type"] = "bridge"
917 extra_dict
["params"]["net_type"] = (
918 "ptp" if target_vld
.get("type") == "ELINE" else "data"
924 def _process_vdu_params(
925 target_vdu
: Dict
[str, Any
],
926 indata
: Dict
[str, Any
],
927 vim_info
: Dict
[str, Any
],
928 target_record_id
: str,
929 **kwargs
: Dict
[str, Any
],
931 """Function to process VDU parameters.
934 target_vdu (Dict[str, Any]): [description]
935 indata (Dict[str, Any]): [description]
936 vim_info (Dict[str, Any]): [description]
937 target_record_id (str): [description]
940 Dict[str, Any]: [description]
942 vnfr_id
= kwargs
.get("vnfr_id")
943 nsr_id
= kwargs
.get("nsr_id")
944 vnfr
= kwargs
.get("vnfr")
945 vdu2cloud_init
= kwargs
.get("vdu2cloud_init")
946 tasks_by_target_record_id
= kwargs
.get("tasks_by_target_record_id")
947 logger
= kwargs
.get("logger")
948 db
= kwargs
.get("db")
949 fs
= kwargs
.get("fs")
950 ro_nsr_public_key
= kwargs
.get("ro_nsr_public_key")
952 vnf_preffix
= "vnfrs:{}".format(vnfr_id
)
953 ns_preffix
= "nsrs:{}".format(nsr_id
)
954 image_text
= ns_preffix
+ ":image." + target_vdu
["ns-image-id"]
955 flavor_text
= ns_preffix
+ ":flavor." + target_vdu
["ns-flavor-id"]
956 extra_dict
= {"depends_on": [image_text
, flavor_text
]}
959 for iface_index
, interface
in enumerate(target_vdu
["interfaces"]):
960 if interface
.get("ns-vld-id"):
961 net_text
= ns_preffix
+ ":vld." + interface
["ns-vld-id"]
962 elif interface
.get("vnf-vld-id"):
963 net_text
= vnf_preffix
+ ":vld." + interface
["vnf-vld-id"]
966 "Interface {} from vdu {} not connected to any vld".format(
967 iface_index
, target_vdu
["vdu-name"]
971 continue # interface not connected to any vld
973 extra_dict
["depends_on"].append(net_text
)
975 if "port-security-enabled" in interface
:
976 interface
["port_security"] = interface
.pop("port-security-enabled")
978 if "port-security-disable-strategy" in interface
:
979 interface
["port_security_disable_strategy"] = interface
.pop(
980 "port-security-disable-strategy"
985 for x
, v
in interface
.items()
991 "port_security_disable_strategy",
995 net_item
["net_id"] = "TASK-" + net_text
996 net_item
["type"] = "virtual"
998 # TODO mac_address: used for SR-IOV ifaces #TODO for other types
999 # TODO floating_ip: True/False (or it can be None)
1000 if interface
.get("type") in ("SR-IOV", "PCI-PASSTHROUGH"):
1001 # mark the net create task as type data
1003 tasks_by_target_record_id
,
1009 tasks_by_target_record_id
[net_text
]["extra_dict"]["params"][
1013 net_item
["use"] = "data"
1014 net_item
["model"] = interface
["type"]
1015 net_item
["type"] = interface
["type"]
1017 interface
.get("type") == "OM-MGMT"
1018 or interface
.get("mgmt-interface")
1019 or interface
.get("mgmt-vnf")
1021 net_item
["use"] = "mgmt"
1023 # if interface.get("type") in ("VIRTIO", "E1000", "PARAVIRT"):
1024 net_item
["use"] = "bridge"
1025 net_item
["model"] = interface
.get("type")
1027 if interface
.get("ip-address"):
1028 net_item
["ip_address"] = interface
["ip-address"]
1030 if interface
.get("mac-address"):
1031 net_item
["mac_address"] = interface
["mac-address"]
1033 net_list
.append(net_item
)
1035 if interface
.get("mgmt-vnf"):
1036 extra_dict
["mgmt_vnf_interface"] = iface_index
1037 elif interface
.get("mgmt-interface"):
1038 extra_dict
["mgmt_vdu_interface"] = iface_index
1043 if target_vdu
.get("cloud-init"):
1044 if target_vdu
["cloud-init"] not in vdu2cloud_init
:
1045 vdu2cloud_init
[target_vdu
["cloud-init"]] = Ns
._get
_cloud
_init
(
1048 location
=target_vdu
["cloud-init"],
1051 cloud_content_
= vdu2cloud_init
[target_vdu
["cloud-init"]]
1052 cloud_config
["user-data"] = Ns
._parse
_jinja
2(
1053 cloud_init_content
=cloud_content_
,
1054 params
=target_vdu
.get("additionalParams"),
1055 context
=target_vdu
["cloud-init"],
1058 if target_vdu
.get("boot-data-drive"):
1059 cloud_config
["boot-data-drive"] = target_vdu
.get("boot-data-drive")
1063 if target_vdu
.get("ssh-keys"):
1064 ssh_keys
+= target_vdu
.get("ssh-keys")
1066 if target_vdu
.get("ssh-access-required"):
1067 ssh_keys
.append(ro_nsr_public_key
)
1070 cloud_config
["key-pairs"] = ssh_keys
1073 if target_vdu
.get("virtual-storages"):
1075 {"size": disk
["size-of-storage"]}
1076 for disk
in target_vdu
["virtual-storages"]
1077 if disk
.get("type-of-storage")
1078 == "persistent-storage:persistent-storage"
1081 affinity_group_list
= []
1083 if target_vdu
.get("affinity-or-anti-affinity-group-id"):
1085 for affinity_group_id
in target_vdu
["affinity-or-anti-affinity-group-id"]:
1086 affinity_group_text
= (
1087 ns_preffix
+ ":affinity-or-anti-affinity-group." + affinity_group_id
1090 extra_dict
["depends_on"].append(affinity_group_text
)
1091 affinity_group
["affinity_group_id"] = "TASK-" + affinity_group_text
1092 affinity_group_list
.append(affinity_group
)
1094 extra_dict
["params"] = {
1095 "name": "{}-{}-{}-{}".format(
1096 indata
["name"][:16],
1097 vnfr
["member-vnf-index-ref"][:16],
1098 target_vdu
["vdu-name"][:32],
1099 target_vdu
.get("count-index") or 0,
1101 "description": target_vdu
["vdu-name"],
1103 "image_id": "TASK-" + image_text
,
1104 "flavor_id": "TASK-" + flavor_text
,
1105 "affinity_group_list": affinity_group_list
,
1106 "net_list": net_list
,
1107 "cloud_config": cloud_config
or None,
1108 "disk_list": disk_list
,
1109 "availability_zone_index": None, # TODO
1110 "availability_zone_list": None, # TODO
1116 def _process_affinity_group_params(
1117 target_affinity_group
: Dict
[str, Any
],
1118 indata
: Dict
[str, Any
],
1119 vim_info
: Dict
[str, Any
],
1120 target_record_id
: str,
1121 **kwargs
: Dict
[str, Any
],
1122 ) -> Dict
[str, Any
]:
1123 """Get affinity or anti-affinity group parameters.
1126 target_affinity_group (Dict[str, Any]): [description]
1127 indata (Dict[str, Any]): [description]
1128 vim_info (Dict[str, Any]): [description]
1129 target_record_id (str): [description]
1132 Dict[str, Any]: [description]
1136 affinity_group_data
= {
1137 "name": target_affinity_group
["name"],
1138 "type": target_affinity_group
["type"],
1139 "scope": target_affinity_group
["scope"],
1142 extra_dict
["params"] = {
1143 "affinity_group_data": affinity_group_data
,
1148 def calculate_diff_items(
1155 tasks_by_target_record_id
,
1162 """Function that returns the incremental changes (creation, deletion)
1163 related to a specific item `item` to be done. This function should be
1164 called for NS instantiation, NS termination, NS update to add a new VNF
1165 or a new VLD, remove a VNF or VLD, etc.
1166 Item can be `net, `flavor`, `image` or `vdu`.
1167 It takes a list of target items from indata (which came from the REST API)
1168 and compares with the existing items from db_ro_nsr, identifying the
1169 incremental changes to be done. During the comparison, it calls the method
1170 `process_params` (which was passed as parameter, and is particular for each
1174 indata (Dict[str, Any]): deployment info
1175 db_nsr: NSR record from DB
1176 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1177 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1178 item (str): element to process (net, vdu...)
1179 tasks_by_target_record_id (Dict[str, Any]):
1180 [<target_record_id>, <task>]
1181 action_id (str): action id
1182 nsr_id (str): NSR id
1183 task_index (number): task index to add to task name
1184 vnfr_id (str): VNFR id
1185 vnfr (Dict[str, Any]): VNFR info
1188 List: list with the incremental changes (deletes, creates) for each item
1189 number: current task index
1197 process_params
= None
1198 vdu2cloud_init
= indata
.get("cloud_init_content") or {}
1199 ro_nsr_public_key
= db_ro_nsr
["public_key"]
1201 # According to the type of item, the path, the target_list,
1202 # the existing_list and the method to process params are set
1203 db_path
= self
.db_path_map
[item
]
1204 process_params
= self
.process_params_function_map
[item
]
1205 if item
in ("net", "vdu"):
1207 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1208 target_list
= indata
.get("ns", []).get(db_path
, [])
1209 existing_list
= db_nsr
.get(db_path
, [])
1211 db_record
= "vnfrs:{}:{}".format(vnfr_id
, db_path
)
1213 (vnf
for vnf
in indata
.get("vnf", ()) if vnf
["_id"] == vnfr_id
),
1216 target_list
= target_vnf
.get(db_path
, []) if target_vnf
else []
1217 existing_list
= vnfr
.get(db_path
, [])
1218 elif item
in ("image", "flavor", "affinity-or-anti-affinity-group"):
1219 db_record
= "nsrs:{}:{}".format(nsr_id
, db_path
)
1220 target_list
= indata
.get(item
, [])
1221 existing_list
= db_nsr
.get(item
, [])
1223 raise NsException("Item not supported: {}", item
)
1225 # ensure all the target_list elements has an "id". If not assign the index as id
1226 if target_list
is None:
1228 for target_index
, tl
in enumerate(target_list
):
1229 if tl
and not tl
.get("id"):
1230 tl
["id"] = str(target_index
)
1232 # step 1 items (networks,vdus,...) to be deleted/updated
1233 for item_index
, existing_item
in enumerate(existing_list
):
1235 (t
for t
in target_list
if t
["id"] == existing_item
["id"]),
1239 for target_vim
, existing_viminfo
in existing_item
.get(
1242 if existing_viminfo
is None:
1246 target_viminfo
= target_item
.get("vim_info", {}).get(target_vim
)
1248 target_viminfo
= None
1250 if target_viminfo
is None:
1252 self
._assign
_vim
(target_vim
)
1253 target_record_id
= "{}.{}".format(db_record
, existing_item
["id"])
1256 if target_vim
.startswith("sdn"):
1257 # item must be sdn-net instead of net if target_vim is a sdn
1259 target_record_id
+= ".sdn"
1262 "action_id": action_id
,
1264 "task_index": task_index
,
1269 "deployment_info": deployment_info
,
1270 "target_id": target_vim
,
1273 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1274 "target_record_id": target_record_id
,
1279 # step 2 items (networks,vdus,...) to be created
1280 for target_item
in target_list
:
1283 for item_index
, existing_item
in enumerate(existing_list
):
1284 if existing_item
["id"] == target_item
["id"]:
1288 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1289 existing_list
.append(target_item
)
1290 existing_item
= None
1292 for target_vim
, target_viminfo
in target_item
.get("vim_info", {}).items():
1293 existing_viminfo
= None
1296 existing_viminfo
= existing_item
.get("vim_info", {}).get(target_vim
)
1298 if existing_viminfo
is not None:
1301 target_record_id
= "{}.{}".format(db_record
, target_item
["id"])
1304 if target_vim
.startswith("sdn"):
1305 # item must be sdn-net instead of net if target_vim is a sdn
1307 target_record_id
+= ".sdn"
1310 if process_params
== Ns
._process
_vdu
_params
:
1316 "vdu2cloud_init": vdu2cloud_init
,
1317 "tasks_by_target_record_id": tasks_by_target_record_id
,
1318 "logger": self
.logger
,
1321 "ro_nsr_public_key": ro_nsr_public_key
,
1325 extra_dict
= process_params(
1332 self
._assign
_vim
(target_vim
)
1335 "action_id": action_id
,
1337 "task_index": task_index
,
1341 "deployment_info": deployment_info
,
1342 "target_id": target_vim
,
1345 "target_record": f
"{db_record}.{item_index}.vim_info.{target_vim}",
1346 "target_record_id": target_record_id
,
1347 "extra_dict": extra_dict
,
1348 "common_id": target_item
.get("common_id", None),
1350 diff_items
.append(new_item
)
1351 tasks_by_target_record_id
[target_record_id
] = new_item
1354 db_nsr_update
[db_path
+ ".{}".format(item_index
)] = target_item
1356 return diff_items
, task_index
1358 def calculate_all_differences_to_deploy(
1368 tasks_by_target_record_id
,
1370 """This method calculates the ordered list of items (`changes_list`)
1371 to be created and deleted.
1374 indata (Dict[str, Any]): deployment info
1375 nsr_id (str): NSR id
1376 db_nsr: NSR record from DB
1377 db_vnfrs: VNFRS record from DB
1378 db_ro_nsr (Dict[str, Any]): record from "ro_nsrs"
1379 db_nsr_update (Dict[str, Any]): NSR info to update in DB
1380 db_vnfrs_update (Dict[str, Any]): VNFRS info to update in DB
1381 action_id (str): action id
1382 tasks_by_target_record_id (Dict[str, Any]):
1383 [<target_record_id>, <task>]
1386 List: ordered list of items to be created and deleted.
1390 # set list with diffs:
1393 # NS vld, image and flavor
1394 for item
in ["net", "image", "flavor", "affinity-or-anti-affinity-group"]:
1395 self
.logger
.debug("process NS={} {}".format(nsr_id
, item
))
1396 diff_items
, task_index
= self
.calculate_diff_items(
1399 db_ro_nsr
=db_ro_nsr
,
1400 db_nsr_update
=db_nsr_update
,
1402 tasks_by_target_record_id
=tasks_by_target_record_id
,
1403 action_id
=action_id
,
1405 task_index
=task_index
,
1408 changes_list
+= diff_items
1411 for vnfr_id
, vnfr
in db_vnfrs
.items():
1412 # vnfr_id need to be set as global variable for among others nested method _process_vdu_params
1413 for item
in ["net", "vdu"]:
1414 self
.logger
.debug("process VNF={} {}".format(vnfr_id
, item
))
1415 diff_items
, task_index
= self
.calculate_diff_items(
1418 db_ro_nsr
=db_ro_nsr
,
1419 db_nsr_update
=db_vnfrs_update
[vnfr
["_id"]],
1421 tasks_by_target_record_id
=tasks_by_target_record_id
,
1422 action_id
=action_id
,
1424 task_index
=task_index
,
1428 changes_list
+= diff_items
1432 def define_all_tasks(
1436 tasks_by_target_record_id
,
1438 """Function to create all the task structures obtanied from
1439 the method calculate_all_differences_to_deploy
1442 changes_list (List): ordered list of items to be created or deleted
1443 db_new_tasks (List): tasks list to be created
1444 action_id (str): action id
1445 tasks_by_target_record_id (Dict[str, Any]):
1446 [<target_record_id>, <task>]
1450 for change
in changes_list
:
1451 task
= Ns
._create
_task
(
1452 deployment_info
=change
["deployment_info"],
1453 target_id
=change
["target_id"],
1454 item
=change
["item"],
1455 action
=change
["action"],
1456 target_record
=change
["target_record"],
1457 target_record_id
=change
["target_record_id"],
1458 extra_dict
=change
.get("extra_dict", None),
1461 tasks_by_target_record_id
[change
["target_record_id"]] = task
1462 db_new_tasks
.append(task
)
1464 if change
.get("common_id"):
1465 task
["common_id"] = change
["common_id"]
1467 def upload_all_tasks(
1472 """Function to save all tasks in the common DB
1475 db_new_tasks (List): tasks list to be created
1476 now (time): current time
1480 nb_ro_tasks
= 0 # for logging
1482 for db_task
in db_new_tasks
:
1483 target_id
= db_task
.pop("target_id")
1484 common_id
= db_task
.get("common_id")
1490 "target_id": target_id
,
1491 "tasks.common_id": common_id
,
1493 update_dict
={"to_check_at": now
, "modified_at": now
},
1494 push
={"tasks": db_task
},
1495 fail_on_empty
=False,
1499 if not self
.db
.set_one(
1502 "target_id": target_id
,
1503 "tasks.target_record": db_task
["target_record"],
1505 update_dict
={"to_check_at": now
, "modified_at": now
},
1506 push
={"tasks": db_task
},
1507 fail_on_empty
=False,
1510 self
.logger
.debug("Updating database, Creating ro_tasks")
1511 db_ro_task
= Ns
._create
_ro
_task
(target_id
, db_task
)
1513 self
.db
.create("ro_tasks", db_ro_task
)
1516 "Created {} ro_tasks; {} tasks - db_new_tasks={}".format(
1517 nb_ro_tasks
, len(db_new_tasks
), db_new_tasks
1521 def deploy(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
1522 self
.logger
.debug("ns.deploy nsr_id={} indata={}".format(nsr_id
, indata
))
1523 validate_input(indata
, deploy_schema
)
1524 action_id
= indata
.get("action_id", str(uuid4()))
1526 # get current deployment
1527 db_nsr_update
= {} # update operation on nsrs
1528 db_vnfrs_update
= {}
1529 db_vnfrs
= {} # vnf's info indexed by _id
1531 logging_text
= "Task deploy nsr_id={} action_id={} ".format(nsr_id
, action_id
)
1532 self
.logger
.debug(logging_text
+ "Enter")
1535 step
= "Getting ns and vnfr record from db"
1536 db_nsr
= self
.db
.get_one("nsrs", {"_id": nsr_id
})
1538 tasks_by_target_record_id
= {}
1539 # read from db: vnf's of this ns
1540 step
= "Getting vnfrs from db"
1541 db_vnfrs_list
= self
.db
.get_list("vnfrs", {"nsr-id-ref": nsr_id
})
1543 if not db_vnfrs_list
:
1544 raise NsException("Cannot obtain associated VNF for ns")
1546 for vnfr
in db_vnfrs_list
:
1547 db_vnfrs
[vnfr
["_id"]] = vnfr
1548 db_vnfrs_update
[vnfr
["_id"]] = {}
1551 db_ro_nsr
= self
.db
.get_one("ro_nsrs", {"_id": nsr_id
}, fail_on_empty
=False)
1554 db_ro_nsr
= self
._create
_db
_ro
_nsrs
(nsr_id
, now
)
1556 # check that action_id is not in the list of actions. Suffixed with :index
1557 if action_id
in db_ro_nsr
["actions"]:
1561 new_action_id
= "{}:{}".format(action_id
, index
)
1563 if new_action_id
not in db_ro_nsr
["actions"]:
1564 action_id
= new_action_id
1567 + "Changing action_id in use to {}".format(action_id
)
1573 def _process_action(indata
):
1574 nonlocal db_new_tasks
1581 if indata
["action"]["action"] == "inject_ssh_key":
1582 key
= indata
["action"].get("key")
1583 user
= indata
["action"].get("user")
1584 password
= indata
["action"].get("password")
1586 for vnf
in indata
.get("vnf", ()):
1587 if vnf
["_id"] not in db_vnfrs
:
1588 raise NsException("Invalid vnf={}".format(vnf
["_id"]))
1590 db_vnfr
= db_vnfrs
[vnf
["_id"]]
1592 for target_vdu
in vnf
.get("vdur", ()):
1593 vdu_index
, vdur
= next(
1596 for i_v
in enumerate(db_vnfr
["vdur"])
1597 if i_v
[1]["id"] == target_vdu
["id"]
1604 "Invalid vdu vnf={}.{}".format(
1605 vnf
["_id"], target_vdu
["id"]
1609 target_vim
, vim_info
= next(
1610 k_v
for k_v
in vdur
["vim_info"].items()
1612 self
._assign
_vim
(target_vim
)
1613 target_record
= "vnfrs:{}:vdur.{}.ssh_keys".format(
1614 vnf
["_id"], vdu_index
1618 "vnfrs:{}:vdur.{}".format(vnf
["_id"], vdur
["id"])
1621 "ip_address": vdur
.get("ip-address"),
1624 "password": password
,
1625 "private_key": db_ro_nsr
["private_key"],
1626 "salt": db_ro_nsr
["_id"],
1627 "schema_version": db_ro_nsr
["_admin"][
1634 "action_id": action_id
,
1636 "task_index": task_index
,
1639 task
= Ns
._create
_task
(
1640 deployment_info
=deployment_info
,
1641 target_id
=target_vim
,
1644 target_record
=target_record
,
1645 target_record_id
=None,
1646 extra_dict
=extra_dict
,
1649 task_index
= deployment_info
.get("task_index")
1651 db_new_tasks
.append(task
)
1653 with self
.write_lock
:
1654 if indata
.get("action"):
1655 _process_action(indata
)
1657 # compute network differences
1659 step
= "process NS elements"
1660 changes_list
= self
.calculate_all_differences_to_deploy(
1665 db_ro_nsr
=db_ro_nsr
,
1666 db_nsr_update
=db_nsr_update
,
1667 db_vnfrs_update
=db_vnfrs_update
,
1668 action_id
=action_id
,
1669 tasks_by_target_record_id
=tasks_by_target_record_id
,
1671 self
.define_all_tasks(
1672 changes_list
=changes_list
,
1673 db_new_tasks
=db_new_tasks
,
1674 tasks_by_target_record_id
=tasks_by_target_record_id
,
1677 step
= "Updating database, Appending tasks to ro_tasks"
1678 self
.upload_all_tasks(
1679 db_new_tasks
=db_new_tasks
,
1683 step
= "Updating database, nsrs"
1685 self
.db
.set_one("nsrs", {"_id": nsr_id
}, db_nsr_update
)
1687 for vnfr_id
, db_vnfr_update
in db_vnfrs_update
.items():
1689 step
= "Updating database, vnfrs={}".format(vnfr_id
)
1690 self
.db
.set_one("vnfrs", {"_id": vnfr_id
}, db_vnfr_update
)
1693 logging_text
+ "Exit. Created {} tasks".format(len(db_new_tasks
))
1697 {"status": "ok", "nsr_id": nsr_id
, "action_id": action_id
},
1701 except Exception as e
:
1702 if isinstance(e
, (DbException
, NsException
)):
1704 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
)
1707 e
= traceback_format_exc()
1708 self
.logger
.critical(
1709 logging_text
+ "Exit Exception while '{}': {}".format(step
, e
),
1713 raise NsException(e
)
1715 def delete(self
, session
, indata
, version
, nsr_id
, *args
, **kwargs
):
1716 self
.logger
.debug("ns.delete version={} nsr_id={}".format(version
, nsr_id
))
1717 # self.db.del_list({"_id": ro_task["_id"], "tasks.nsr_id.ne": nsr_id})
1719 with self
.write_lock
:
1721 NsWorker
.delete_db_tasks(self
.db
, nsr_id
, None)
1722 except NsWorkerException
as e
:
1723 raise NsException(e
)
1725 return None, None, True
1727 def status(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1728 # self.logger.debug("ns.status version={} nsr_id={}, action_id={} indata={}"
1729 # .format(version, nsr_id, action_id, indata))
1733 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.action_id": action_id
})
1734 global_status
= "DONE"
1737 for ro_task
in ro_tasks
:
1738 for task
in ro_task
["tasks"]:
1739 if task
and task
["action_id"] == action_id
:
1740 task_list
.append(task
)
1743 if task
["status"] == "FAILED":
1744 global_status
= "FAILED"
1745 error_text
= "Error at {} {}: {}".format(
1746 task
["action"].lower(),
1748 ro_task
["vim_info"].get("vim_details") or "unknown",
1750 details
.append(error_text
)
1751 elif task
["status"] in ("SCHEDULED", "BUILD"):
1752 if global_status
!= "FAILED":
1753 global_status
= "BUILD"
1758 "status": global_status
,
1759 "details": ". ".join(details
)
1761 else "progress {}/{}".format(done
, total
),
1763 "action_id": action_id
,
1767 return return_data
, None, True
1769 def cancel(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1771 "ns.cancel session={} indata={} version={} nsr_id={}, action_id={}".format(
1772 session
, indata
, version
, nsr_id
, action_id
1776 return None, None, True
1778 def get_deploy(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1779 nsrs
= self
.db
.get_list("nsrs", {})
1783 return_data
.append({"_id": ns
["_id"], "name": ns
["name"]})
1785 return return_data
, None, True
1787 def get_actions(self
, session
, indata
, version
, nsr_id
, action_id
, *args
, **kwargs
):
1788 ro_tasks
= self
.db
.get_list("ro_tasks", {"tasks.nsr_id": nsr_id
})
1791 for ro_task
in ro_tasks
:
1792 for task
in ro_task
["tasks"]:
1793 if task
["action_id"] not in return_data
:
1794 return_data
.append(task
["action_id"])
1796 return return_data
, None, True