| 1 |
#!/usr/bin/python |
| 2 |
"""short_description: Check or wait for migrations between nodes""" |
| 3 |
|
| 4 |
# Copyright (c) 2018, Albert Autin |
| 5 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: aerospike_migrations |
| 11 |
short_description: Check or wait for migrations between nodes |
| 12 |
description: |
| 13 |
- This can be used to check for migrations in a cluster. This makes it easy to do a rolling upgrade/update on Aerospike |
| 14 |
nodes. |
| 15 |
- If waiting for migrations is not desired, simply just poll until port 3000 if available or C(asinfo -v status) returns |
| 16 |
ok. |
| 17 |
author: "Albert Autin (@Alb0t)" |
| 18 |
extends_documentation_fragment: |
| 19 |
- community.general._attributes |
| 20 |
attributes: |
| 21 |
check_mode: |
| 22 |
support: full |
| 23 |
diff_mode: |
| 24 |
support: none |
| 25 |
options: |
| 26 |
host: |
| 27 |
description: |
| 28 |
- Which host do we use as seed for info connection. |
| 29 |
type: str |
| 30 |
default: localhost |
| 31 |
port: |
| 32 |
description: |
| 33 |
- Which port to connect to Aerospike on (service port). |
| 34 |
type: int |
| 35 |
default: 3000 |
| 36 |
connect_timeout: |
| 37 |
description: |
| 38 |
- How long to try to connect before giving up (milliseconds). |
| 39 |
type: int |
| 40 |
default: 1000 |
| 41 |
consecutive_good_checks: |
| 42 |
description: |
| 43 |
- How many times should the cluster report "no migrations" consecutively before returning OK back to ansible? |
| 44 |
type: int |
| 45 |
default: 3 |
| 46 |
sleep_between_checks: |
| 47 |
description: |
| 48 |
- How long to sleep between each check (seconds). |
| 49 |
type: int |
| 50 |
default: 60 |
| 51 |
tries_limit: |
| 52 |
description: |
| 53 |
- How many times do we poll before giving up and failing? |
| 54 |
default: 300 |
| 55 |
type: int |
| 56 |
local_only: |
| 57 |
description: |
| 58 |
- Do you wish to only check for migrations on the local node before returning, or do you want all nodes in the cluster |
| 59 |
to finish before returning? |
| 60 |
required: true |
| 61 |
type: bool |
| 62 |
min_cluster_size: |
| 63 |
description: |
| 64 |
- Check fails until cluster size is met or until tries is exhausted. |
| 65 |
type: int |
| 66 |
default: 1 |
| 67 |
fail_on_cluster_change: |
| 68 |
description: |
| 69 |
- Fail if the cluster key changes if something else is changing the cluster, we may want to fail. |
| 70 |
type: bool |
| 71 |
default: true |
| 72 |
migrate_tx_key: |
| 73 |
description: |
| 74 |
- The metric key used to determine if we have tx migrations remaining. Changeable due to backwards compatibility. |
| 75 |
type: str |
| 76 |
default: migrate_tx_partitions_remaining |
| 77 |
migrate_rx_key: |
| 78 |
description: |
| 79 |
- The metric key used to determine if we have rx migrations remaining. Changeable due to backwards compatibility. |
| 80 |
type: str |
| 81 |
default: migrate_rx_partitions_remaining |
| 82 |
target_cluster_size: |
| 83 |
description: |
| 84 |
- When all aerospike builds in the cluster are greater than version 4.3, then the C(cluster-stable) info command is |
| 85 |
used. Inside this command, you can optionally specify what the target cluster size is - but it is not necessary. |
| 86 |
You can still rely on O(min_cluster_size) if you do not want to use this option. |
| 87 |
- If this option is specified on a cluster that has at least one host <4.3 then it is ignored until the min version |
| 88 |
reaches 4.3. |
| 89 |
type: int |
| 90 |
""" |
| 91 |
|
| 92 |
EXAMPLES = r""" |
| 93 |
# check for migrations on local node |
| 94 |
- name: Wait for migrations on local node before proceeding |
| 95 |
community.general.aerospike_migrations: |
| 96 |
host: "localhost" |
| 97 |
connect_timeout: 2000 |
| 98 |
consecutive_good_checks: 5 |
| 99 |
sleep_between_checks: 15 |
| 100 |
tries_limit: 600 |
| 101 |
local_only: false |
| 102 |
|
| 103 |
# example playbook: |
| 104 |
- name: Upgrade aerospike |
| 105 |
hosts: all |
| 106 |
become: true |
| 107 |
serial: 1 |
| 108 |
tasks: |
| 109 |
- name: Install dependencies |
| 110 |
ansible.builtin.apt: |
| 111 |
name: |
| 112 |
- python |
| 113 |
- python-pip |
| 114 |
- python-setuptools |
| 115 |
state: latest |
| 116 |
- name: Setup aerospike |
| 117 |
ansible.builtin.pip: |
| 118 |
name: aerospike |
| 119 |
# check for migrations every (sleep_between_checks) |
| 120 |
# If at least (consecutive_good_checks) checks come back OK in a row, then return OK. |
| 121 |
# Will exit if any exception, which can be caused by bad nodes, |
| 122 |
# nodes not returning data, or other reasons. |
| 123 |
# Maximum runtime before giving up in this case will be: |
| 124 |
# Tries Limit * Sleep Between Checks * delay * retries |
| 125 |
- name: Wait for aerospike migrations |
| 126 |
community.general.aerospike_migrations: |
| 127 |
local_only: true |
| 128 |
sleep_between_checks: 1 |
| 129 |
tries_limit: 5 |
| 130 |
consecutive_good_checks: 3 |
| 131 |
fail_on_cluster_change: true |
| 132 |
min_cluster_size: 3 |
| 133 |
target_cluster_size: 4 |
| 134 |
register: migrations_check |
| 135 |
until: migrations_check is succeeded |
| 136 |
changed_when: false |
| 137 |
delay: 60 |
| 138 |
retries: 120 |
| 139 |
- name: Another thing |
| 140 |
ansible.builtin.shell: | |
| 141 |
echo foo |
| 142 |
- name: Reboot |
| 143 |
ansible.builtin.reboot: |
| 144 |
""" |
| 145 |
|
| 146 |
RETURN = r""" |
| 147 |
# Returns only a success/failure result. Changed is always false. |
| 148 |
""" |
| 149 |
|
| 150 |
import traceback |
| 151 |
|
| 152 |
from ansible.module_utils.basic import AnsibleModule, missing_required_lib |
| 153 |
|
| 154 |
LIB_FOUND_ERR = None |
| 155 |
try: |
| 156 |
import re |
| 157 |
from time import sleep |
| 158 |
|
| 159 |
import aerospike |
| 160 |
except ImportError: |
| 161 |
LIB_FOUND = False |
| 162 |
LIB_FOUND_ERR = traceback.format_exc() |
| 163 |
else: |
| 164 |
LIB_FOUND = True |
| 165 |
|
| 166 |
|
| 167 |
def run_module(): |
| 168 |
"""run ansible module""" |
| 169 |
module_args = dict( |
| 170 |
host=dict(type="str", default="localhost"), |
| 171 |
port=dict(type="int", default=3000), |
| 172 |
connect_timeout=dict(type="int", default=1000), |
| 173 |
consecutive_good_checks=dict(type="int", default=3), |
| 174 |
sleep_between_checks=dict(type="int", default=60), |
| 175 |
tries_limit=dict(type="int", default=300), |
| 176 |
local_only=dict(type="bool", required=True), |
| 177 |
min_cluster_size=dict(type="int", default=1), |
| 178 |
target_cluster_size=dict(type="int"), |
| 179 |
fail_on_cluster_change=dict(type="bool", default=True), |
| 180 |
migrate_tx_key=dict(type="str", no_log=False, default="migrate_tx_partitions_remaining"), |
| 181 |
migrate_rx_key=dict(type="str", no_log=False, default="migrate_rx_partitions_remaining"), |
| 182 |
) |
| 183 |
|
| 184 |
result = dict( |
| 185 |
changed=False, |
| 186 |
) |
| 187 |
|
| 188 |
module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) |
| 189 |
if not LIB_FOUND: |
| 190 |
module.fail_json(msg=missing_required_lib("aerospike"), exception=LIB_FOUND_ERR) |
| 191 |
|
| 192 |
try: |
| 193 |
if module.check_mode: |
| 194 |
has_migrations, skip_reason = False, None |
| 195 |
else: |
| 196 |
migrations = Migrations(module) |
| 197 |
has_migrations, skip_reason = migrations.has_migs(module.params["local_only"]) |
| 198 |
|
| 199 |
if has_migrations: |
| 200 |
module.fail_json(msg="Failed.", skip_reason=skip_reason) |
| 201 |
except Exception as e: |
| 202 |
module.fail_json(msg=f"Error: {e}") |
| 203 |
|
| 204 |
module.exit_json(**result) |
| 205 |
|
| 206 |
|
| 207 |
class Migrations: |
| 208 |
"""Check or wait for migrations between nodes""" |
| 209 |
|
| 210 |
def __init__(self, module): |
| 211 |
self.module = module |
| 212 |
self._client = self._create_client().connect() |
| 213 |
self._nodes = {} |
| 214 |
self._update_nodes_list() |
| 215 |
self._cluster_statistics = {} |
| 216 |
self._update_cluster_statistics() |
| 217 |
self._namespaces = set() |
| 218 |
self._update_cluster_namespace_list() |
| 219 |
self._build_list = set() |
| 220 |
self._update_build_list() |
| 221 |
self._start_cluster_key = self._cluster_statistics[self._nodes[0]]["cluster_key"] |
| 222 |
|
| 223 |
def _create_client(self): |
| 224 |
"""TODO: add support for auth, tls, and other special features |
| 225 |
I won't use those features, so I'll wait until somebody complains |
| 226 |
or does it for me (Cross fingers) |
| 227 |
create the client object""" |
| 228 |
config = { |
| 229 |
"hosts": [(self.module.params["host"], self.module.params["port"])], |
| 230 |
"policies": {"timeout": self.module.params["connect_timeout"]}, |
| 231 |
} |
| 232 |
return aerospike.client(config) |
| 233 |
|
| 234 |
def _info_cmd_helper(self, cmd, node=None, delimiter=";"): |
| 235 |
"""delimiter is for separate stats that come back, NOT for kv |
| 236 |
separation which is =""" |
| 237 |
if node is None: # If no node passed, use the first one (local) |
| 238 |
node = self._nodes[0] |
| 239 |
data = self._client.info_node(cmd, node) |
| 240 |
data = data.split("\t") |
| 241 |
if len(data) != 1 and len(data) != 2: |
| 242 |
self.module.fail_json(msg=f"Unexpected number of values returned in info command: {len(data)}") |
| 243 |
# data will be in format 'command\touput' |
| 244 |
data = data[-1] |
| 245 |
data = data.rstrip("\n\r") |
| 246 |
data_arr = data.split(delimiter) |
| 247 |
|
| 248 |
# some commands don't return in kv format |
| 249 |
# so we dont want a dict from those. |
| 250 |
if "=" in data: |
| 251 |
retval = dict(metric.split("=", 1) for metric in data_arr) |
| 252 |
else: |
| 253 |
# if only 1 element found, and not kv, return just the value. |
| 254 |
if len(data_arr) == 1: |
| 255 |
retval = data_arr[0] |
| 256 |
else: |
| 257 |
retval = data_arr |
| 258 |
return retval |
| 259 |
|
| 260 |
def _update_build_list(self): |
| 261 |
"""creates self._build_list which is a unique list |
| 262 |
of build versions.""" |
| 263 |
self._build_list = set() |
| 264 |
for node in self._nodes: |
| 265 |
build = self._info_cmd_helper("build", node) |
| 266 |
self._build_list.add(build) |
| 267 |
|
| 268 |
# just checks to see if the version is 4.3 or greater |
| 269 |
def _can_use_cluster_stable(self): |
| 270 |
# if version <4.3 we can't use cluster-stable info cmd |
| 271 |
# regex hack to check for versions beginning with 0-3 or |
| 272 |
# beginning with 4.0,4.1,4.2 |
| 273 |
return not re.search(R"^([0-3]\.|4\.[0-2])", min(self._build_list)) |
| 274 |
|
| 275 |
def _update_cluster_namespace_list(self): |
| 276 |
"""make a unique list of namespaces |
| 277 |
TODO: does this work on a rolling namespace add/deletion? |
| 278 |
thankfully if it doesn't, we dont need this on builds >=4.3""" |
| 279 |
self._namespaces = set() |
| 280 |
for node in self._nodes: |
| 281 |
namespaces = self._info_cmd_helper("namespaces", node) |
| 282 |
for namespace in namespaces: |
| 283 |
self._namespaces.add(namespace) |
| 284 |
|
| 285 |
def _update_cluster_statistics(self): |
| 286 |
"""create a dict of nodes with their related stats""" |
| 287 |
self._cluster_statistics = {} |
| 288 |
for node in self._nodes: |
| 289 |
self._cluster_statistics[node] = self._info_cmd_helper("statistics", node) |
| 290 |
|
| 291 |
def _update_nodes_list(self): |
| 292 |
"""get a fresh list of all the nodes""" |
| 293 |
self._nodes = self._client.get_nodes() |
| 294 |
if not self._nodes: |
| 295 |
self.module.fail_json("Failed to retrieve at least 1 node.") |
| 296 |
|
| 297 |
def _namespace_has_migs(self, namespace, node=None): |
| 298 |
"""returns a True or False. |
| 299 |
Does the namespace have migrations for the node passed? |
| 300 |
If no node passed, uses the local node or the first one in the list""" |
| 301 |
namespace_stats = self._info_cmd_helper(f"namespace/{namespace}", node) |
| 302 |
try: |
| 303 |
namespace_tx = int(namespace_stats[self.module.params["migrate_tx_key"]]) |
| 304 |
namespace_rx = int(namespace_stats[self.module.params["migrate_rx_key"]]) |
| 305 |
except KeyError: |
| 306 |
self.module.fail_json( |
| 307 |
msg=( |
| 308 |
f"Did not find partition remaining key:{self.module.params['migrate_tx_key']} " |
| 309 |
f"or key:{self.module.params['migrate_rx_key']} in 'namespace/{namespace}' output." |
| 310 |
) |
| 311 |
) |
| 312 |
except TypeError: |
| 313 |
self.module.fail_json(msg="namespace stat returned was not numerical") |
| 314 |
return namespace_tx != 0 or namespace_rx != 0 |
| 315 |
|
| 316 |
def _node_has_migs(self, node=None): |
| 317 |
"""just calls namespace_has_migs and |
| 318 |
if any namespace has migs returns true""" |
| 319 |
migs = 0 |
| 320 |
self._update_cluster_namespace_list() |
| 321 |
for namespace in self._namespaces: |
| 322 |
if self._namespace_has_migs(namespace, node): |
| 323 |
migs += 1 |
| 324 |
return migs != 0 |
| 325 |
|
| 326 |
def _cluster_key_consistent(self): |
| 327 |
"""create a dictionary to store what each node |
| 328 |
returns the cluster key as. we should end up with only 1 dict key, |
| 329 |
with the key being the cluster key.""" |
| 330 |
cluster_keys = {} |
| 331 |
for node in self._nodes: |
| 332 |
cluster_key = self._cluster_statistics[node]["cluster_key"] |
| 333 |
if cluster_key not in cluster_keys: |
| 334 |
cluster_keys[cluster_key] = 1 |
| 335 |
else: |
| 336 |
cluster_keys[cluster_key] += 1 |
| 337 |
return bool(len(cluster_keys.keys()) == 1 and self._start_cluster_key in cluster_keys) |
| 338 |
|
| 339 |
def _cluster_migrates_allowed(self): |
| 340 |
"""ensure all nodes have 'migrate_allowed' in their stats output""" |
| 341 |
for node in self._nodes: |
| 342 |
node_stats = self._info_cmd_helper("statistics", node) |
| 343 |
allowed = node_stats["migrate_allowed"] |
| 344 |
if allowed == "false": |
| 345 |
return False |
| 346 |
return True |
| 347 |
|
| 348 |
def _cluster_has_migs(self): |
| 349 |
"""calls node_has_migs for each node""" |
| 350 |
migs = 0 |
| 351 |
for node in self._nodes: |
| 352 |
if self._node_has_migs(node): |
| 353 |
migs += 1 |
| 354 |
return migs != 0 |
| 355 |
|
| 356 |
def _has_migs(self, local): |
| 357 |
if local: |
| 358 |
return self._local_node_has_migs() |
| 359 |
return self._cluster_has_migs() |
| 360 |
|
| 361 |
def _local_node_has_migs(self): |
| 362 |
return self._node_has_migs(None) |
| 363 |
|
| 364 |
def _is_min_cluster_size(self): |
| 365 |
"""checks that all nodes in the cluster are returning the |
| 366 |
minimum cluster size specified in their statistics output""" |
| 367 |
sizes = set() |
| 368 |
for node in self._cluster_statistics: |
| 369 |
sizes.add(int(self._cluster_statistics[node]["cluster_size"])) |
| 370 |
|
| 371 |
if (len(sizes)) > 1: # if we are getting more than 1 size, lets say no |
| 372 |
return False |
| 373 |
return min(sizes) >= self.module.params["min_cluster_size"] |
| 374 |
|
| 375 |
def _cluster_stable(self): |
| 376 |
"""Added 4.3: |
| 377 |
cluster-stable:size=<target-cluster-size>;ignore-migrations=<yes/no>;namespace=<namespace-name> |
| 378 |
Returns the current 'cluster_key' when the following are satisfied: |
| 379 |
|
| 380 |
If 'size' is specified then the target node's 'cluster-size' |
| 381 |
must match size. |
| 382 |
If 'ignore-migrations' is either unspecified or 'false' then |
| 383 |
the target node's migrations counts must be zero for the provided |
| 384 |
'namespace' or all namespaces if 'namespace' is not provided.""" |
| 385 |
cluster_key = set() |
| 386 |
cluster_key.add(self._info_cmd_helper("statistics")["cluster_key"]) |
| 387 |
cmd = "cluster-stable:" |
| 388 |
target_cluster_size = self.module.params["target_cluster_size"] |
| 389 |
if target_cluster_size is not None: |
| 390 |
cmd = f"{cmd}size={target_cluster_size};" |
| 391 |
for node in self._nodes: |
| 392 |
try: |
| 393 |
cluster_key.add(self._info_cmd_helper(cmd, node)) |
| 394 |
except aerospike.exception.ServerError as e: # unstable-cluster is returned in form of Exception |
| 395 |
if "unstable-cluster" in e.msg: |
| 396 |
return False |
| 397 |
raise e |
| 398 |
return len(cluster_key) == 1 |
| 399 |
|
| 400 |
def _cluster_good_state(self): |
| 401 |
"""checks a few things to make sure we're OK to say the cluster |
| 402 |
has no migs. It could be in a unhealthy condition that does not allow |
| 403 |
migs, or a split brain""" |
| 404 |
if self._cluster_key_consistent() is not True: |
| 405 |
return False, "Cluster key inconsistent." |
| 406 |
if self._is_min_cluster_size() is not True: |
| 407 |
return False, "Cluster min size not reached." |
| 408 |
if self._cluster_migrates_allowed() is not True: |
| 409 |
return False, "migrate_allowed is false somewhere." |
| 410 |
return True, "OK." |
| 411 |
|
| 412 |
def has_migs(self, local=True): |
| 413 |
"""returns a boolean, False if no migrations otherwise True""" |
| 414 |
consecutive_good = 0 |
| 415 |
try_num = 0 |
| 416 |
skip_reason = list() |
| 417 |
while try_num < int(self.module.params["tries_limit"]) and consecutive_good < int( |
| 418 |
self.module.params["consecutive_good_checks"] |
| 419 |
): |
| 420 |
self._update_nodes_list() |
| 421 |
self._update_cluster_statistics() |
| 422 |
|
| 423 |
# These checks are outside of the while loop because |
| 424 |
# we probably want to skip & sleep instead of failing entirely |
| 425 |
stable, reason = self._cluster_good_state() |
| 426 |
if stable is not True: |
| 427 |
skip_reason.append(f"Skipping on try#{try_num} for reason:{reason}") |
| 428 |
else: |
| 429 |
if self._can_use_cluster_stable(): |
| 430 |
if self._cluster_stable(): |
| 431 |
consecutive_good += 1 |
| 432 |
else: |
| 433 |
consecutive_good = 0 |
| 434 |
skip_reason.append(f"Skipping on try#{try_num} for reason: cluster_stable") |
| 435 |
elif self._has_migs(local): |
| 436 |
# print("_has_migs") |
| 437 |
skip_reason.append(f"Skipping on try#{try_num} for reason: migrations") |
| 438 |
consecutive_good = 0 |
| 439 |
else: |
| 440 |
consecutive_good += 1 |
| 441 |
if consecutive_good == self.module.params["consecutive_good_checks"]: |
| 442 |
break |
| 443 |
try_num += 1 |
| 444 |
sleep(self.module.params["sleep_between_checks"]) |
| 445 |
# print(skip_reason) |
| 446 |
if consecutive_good == self.module.params["consecutive_good_checks"]: |
| 447 |
return False, None |
| 448 |
return True, skip_reason |
| 449 |
|
| 450 |
|
| 451 |
def main(): |
| 452 |
"""main method for ansible module""" |
| 453 |
run_module() |
| 454 |
|
| 455 |
|
| 456 |
if __name__ == "__main__": |
| 457 |
main() |