Debian Codegraph @

ansible_collections/community/aws/plugins/module_utils/opensearch.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: Contributors to the Ansible project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 import datetime
7 import functools
8 import time
9 from copy import deepcopy
10
11 try:
12 import botocore
13 except ImportError:
14 pass # caught by AnsibleAWSModule
15
16 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
17
18 from ansible_collections.amazon.aws.plugins.module_utils.botocore import is_boto3_error_code
19 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
20 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
21 from ansible_collections.amazon.aws.plugins.module_utils.tagging import compare_aws_tags
22
23
24 def get_domain_status(client, module, domain_name):
25 """
26 Get the status of an existing OpenSearch cluster.
27 """
28 try:
29 response = client.describe_domain(DomainName=domain_name)
30 except is_boto3_error_code("ResourceNotFoundException"):
31 return None
32 except (
33 botocore.exceptions.BotoCoreError,
34 botocore.exceptions.ClientError,
35 ) as e: # pylint: disable=duplicate-except
36 module.fail_json_aws(e, msg=f"Couldn't get domain {domain_name}")
37 return response["DomainStatus"]
38
39
40 def get_domain_config(client, module, domain_name):
41 """
42 Get the configuration of an existing OpenSearch cluster, convert the data
43 such that it can be used as input parameter to client.update_domain().
44 The status info is removed.
45 The returned config includes the 'EngineVersion' property, it needs to be removed
46 from the dict before invoking client.update_domain().
47
48 Return (domain_config, domain_arn) or (None, None) if the domain does not exist.
49 """
50 try:
51 response = client.describe_domain_config(DomainName=domain_name)
52 except is_boto3_error_code("ResourceNotFoundException"):
53 return (None, None)
54 except (
55 botocore.exceptions.BotoCoreError,
56 botocore.exceptions.ClientError,
57 ) as e: # pylint: disable=duplicate-except
58 module.fail_json_aws(e, msg=f"Couldn't get domain {domain_name}")
59 domain_config = {}
60 arn = None
61 if response is not None:
62 for k in response["DomainConfig"]:
63 if "Options" in response["DomainConfig"][k]:
64 domain_config[k] = response["DomainConfig"][k]["Options"]
65 domain_config["DomainName"] = domain_name
66 # If ES cluster is attached to the Internet, the "VPCOptions" property is not present.
67 if "VPCOptions" in domain_config:
68 # The "VPCOptions" returned by the describe_domain_config API has
69 # additional attributes that would cause an error if sent in the HTTP POST body.
70 dc = {}
71 if "SubnetIds" in domain_config["VPCOptions"]:
72 dc["SubnetIds"] = deepcopy(domain_config["VPCOptions"]["SubnetIds"])
73 if "SecurityGroupIds" in domain_config["VPCOptions"]:
74 dc["SecurityGroupIds"] = deepcopy(domain_config["VPCOptions"]["SecurityGroupIds"])
75 domain_config["VPCOptions"] = dc
76 # The "StartAt" property is converted to datetime, but when doing comparisons it should
77 # be in the string format "YYYY-MM-DD".
78 for s in domain_config["AutoTuneOptions"]["MaintenanceSchedules"]:
79 if isinstance(s["StartAt"], datetime.datetime):
80 s["StartAt"] = s["StartAt"].strftime("%Y-%m-%d")
81 # Provisioning of "AdvancedOptions" is not supported by this module yet.
82 domain_config.pop("AdvancedOptions", None)
83
84 # Get the ARN of the OpenSearch cluster.
85 domain = get_domain_status(client, module, domain_name)
86 if domain is not None:
87 arn = domain["ARN"]
88 return (domain_config, arn)
89
90
91 def normalize_opensearch(client, module, domain):
92 """
93 Merge the input domain object with tags associated with the domain,
94 convert the attributes from camel case to snake case, and return the object.
95 """
96 try:
97 domain["Tags"] = boto3_tag_list_to_ansible_dict(client.list_tags(ARN=domain["ARN"], aws_retry=True)["TagList"])
98 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
99 module.fail_json_aws(e, f"Couldn't get tags for domain {domain['domain_name']}")
100 except KeyError:
101 module.fail_json(msg=str(domain))
102
103 return camel_dict_to_snake_dict(domain, ignore_list=["Tags"])
104
105
106 def wait_for_domain_status(client, module, domain_name, waiter_name):
107 if not module.params["wait"]:
108 return
109 timeout = module.params["wait_timeout"]
110 deadline = time.time() + timeout
111 status_msg = ""
112 while time.time() < deadline:
113 status = get_domain_status(client, module, domain_name)
114 if status is None:
115 status_msg = "Not Found"
116 if waiter_name == "domain_deleted":
117 return
118 else:
119 status_msg = "Created: {0}. Processing: {1}. UpgradeProcessing: {2}".format(
120 status["Created"],
121 status["Processing"],
122 status["UpgradeProcessing"],
123 )
124 if (
125 waiter_name == "domain_available"
126 and status["Created"]
127 and not status["Processing"]
128 and not status["UpgradeProcessing"]
129 ):
130 return
131 time.sleep(15)
132 # Timeout occured.
133 module.fail_json(msg=f"Timeout waiting for wait state '{waiter_name}'. {status_msg}")
134
135
136 def parse_version(engine_version):
137 """
138 Parse the engine version, which should be Elasticsearch_X.Y or OpenSearch_X.Y
139 Return dict { 'engine_type': engine_type, 'major': major, 'minor': minor }
140 """
141 version = engine_version.split("_")
142 if len(version) != 2:
143 return None
144 semver = version[1].split(".")
145 if len(semver) != 2:
146 return None
147 engine_type = version[0]
148 if engine_type not in ["Elasticsearch", "OpenSearch"]:
149 return None
150 if not (semver[0].isdigit() and semver[1].isdigit()):
151 return None
152 major = int(semver[0])
153 minor = int(semver[1])
154 return {"engine_type": engine_type, "major": major, "minor": minor}
155
156
157 def compare_domain_versions(version1, version2):
158 supported_engines = {
159 "Elasticsearch": 1,
160 "OpenSearch": 2,
161 }
162 if isinstance(version1, str):
163 version1 = parse_version(version1)
164 if isinstance(version2, str):
165 version2 = parse_version(version2)
166 if version1 is None and version2 is not None:
167 return -1
168 elif version1 is not None and version2 is None:
169 return 1
170 elif version1 is None and version2 is None:
171 return 0
172 e1 = supported_engines.get(version1.get("engine_type"))
173 e2 = supported_engines.get(version2.get("engine_type"))
174 if e1 < e2:
175 return -1
176 elif e1 > e2:
177 return 1
178 else:
179 if version1.get("major") < version2.get("major"):
180 return -1
181 elif version1.get("major") > version2.get("major"):
182 return 1
183 else:
184 if version1.get("minor") < version2.get("minor"):
185 return -1
186 elif version1.get("minor") > version2.get("minor"):
187 return 1
188 else:
189 return 0
190
191
192 def get_target_increment_version(client, module, domain_name, target_version):
193 """
194 Returns the highest compatible version which is less than or equal to target_version.
195 When upgrading a domain from version V1 to V2, it may not be possible to upgrade
196 directly from V1 to V2. The domain may have to be upgraded through intermediate versions.
197 Return None if there is no such version.
198 For example, it's not possible to upgrade directly from Elasticsearch 5.5 to 7.10.
199 """
200 api_compatible_versions = None
201 try:
202 api_compatible_versions = client.get_compatible_versions(DomainName=domain_name)
203 except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
204 module.fail_json_aws(
205 e,
206 msg=f"Couldn't get compatible versions for domain {domain_name}",
207 )
208 compat = api_compatible_versions.get("CompatibleVersions")
209 if compat is None:
210 module.fail_json("Unable to determine list of compatible versions", compatible_versions=api_compatible_versions)
211 if len(compat) == 0:
212 module.fail_json("Unable to determine list of compatible versions", compatible_versions=api_compatible_versions)
213 if compat[0].get("TargetVersions") is None:
214 module.fail_json("No compatible versions found", compatible_versions=api_compatible_versions)
215 compatible_versions = []
216 for v in compat[0].get("TargetVersions"):
217 if target_version == v:
218 # It's possible to upgrade directly to the target version.
219 return target_version
220 semver = parse_version(v)
221 if semver is not None:
222 compatible_versions.append(semver)
223 # No direct upgrade is possible. Upgrade to the highest version available.
224 compatible_versions = sorted(compatible_versions, key=functools.cmp_to_key(compare_domain_versions))
225 # Return the highest compatible version which is lower than target_version
226 for v in reversed(compatible_versions):
227 if compare_domain_versions(v, target_version) <= 0:
228 return v
229 return None
230
231
232 def ensure_tags(client, module, resource_arn, existing_tags, tags, purge_tags):
233 if tags is None:
234 return False
235 tags_to_add, tags_to_remove = compare_aws_tags(existing_tags, tags, purge_tags)
236 changed = bool(tags_to_add or tags_to_remove)
237 if tags_to_add:
238 if module.check_mode:
239 module.exit_json(changed=True, msg="Would have added tags to domain if not in check mode")
240 try:
241 client.add_tags(
242 ARN=resource_arn,
243 TagList=ansible_dict_to_boto3_tag_list(tags_to_add),
244 )
245 except (
246 botocore.exceptions.ClientError,
247 botocore.exceptions.BotoCoreError,
248 ) as e:
249 module.fail_json_aws(e, f"Couldn't add tags to domain {resource_arn}")
250 if tags_to_remove:
251 if module.check_mode:
252 module.exit_json(changed=True, msg="Would have removed tags if not in check mode")
253 try:
254 client.remove_tags(ARN=resource_arn, TagKeys=tags_to_remove)
255 except (
256 botocore.exceptions.ClientError,
257 botocore.exceptions.BotoCoreError,
258 ) as e:
259 module.fail_json_aws(e, f"Couldn't remove tags from domain {resource_arn}")
260 return changed