Debian Codegraph @

ansible_collections/community/proxysql/plugins/modules/proxysql_galera_hostgroups.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # Copyright: (c) 2017, Ansible Project
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7
8 __metaclass__ = type
9
10 DOCUMENTATION = '''
11 ---
12 module: proxysql_galera_hostgroups
13 author: "Tomas Palevičius (@tompal3)"
14 short_description: Manages galera hostgroups using the proxysql admin
15 interface
16 description:
17 - Unlike regular async replication, Galera hostgroup are NOT defined in mysql_replication_hostgroups table.
18 Instead there is a separate table that is specifically designed for Galera hostgroups.
19 The reason for this is that more advanced topology support is needed in order to accommodate
20 the deployment options available for Galera (e.g. controlled number of writers, cluster
21 level replication thresholds etc.)
22 options:
23 writer_hostgroup:
24 description:
25 - Id of the hostgroup that will contain all the Galera nodes that are active writers.
26 type: int
27 required: true
28 backup_writer_hostgroup:
29 description:
30 - Id of the hostgroup that will contain all the Galera nodes that are standby writers.
31 type: int
32 required: true
33 reader_hostgroup:
34 description:
35 - Id of the hostgroup that will contain all the Galera nodes that are readers.
36 type: int
37 required: true
38 offline_hostgroup:
39 description:
40 - Id of the hostgroup all failed nodes will be moved to.
41 type: int
42 required: true
43 active:
44 description:
45 - Enabled (1) or disabled (0) defined hostgroup configuration.
46 type: int
47 choices: [0 , 1]
48 default: 1
49 max_writers:
50 description:
51 - number of Read-Write instances populated in the writer hostgroup
52 type: int
53 default: 1
54 writer_is_also_reader:
55 description:
56 - writer_is_also_reader - 0 nodes with `read_only=0` will be placed either in the writer_hostgroup
57 and in the backup_writer_hostgroup after a topology change, these will be excluded from the reader_hostgroup
58 - writer_is_also_reader - 1 nodes with `read_only=0` will be placed in the writer_hostgroup or
59 backup_writer_hostgroup and are all also placed in reader_hostgroup after a topology change
60 - writer_is_also_reader - 2 Only the nodes with `read_only=0` which are placed in the in the
61 backup_writer_hostgroup are also placed in the reader_hostgroup after a topology change i.e.
62 the nodes with `read_only=0` exceeding the defined `max_writers`.
63 type: int
64 choices: [ 0, 1, 2 ]
65 default: 0
66 max_transactions_behind :
67 description:
68 - maximum number of writesets behind the cluster that ProxySQL should allow before shunning
69 the node to prevent stale reads
70 type: int
71 default: 0
72 comment:
73 description:
74 - Text field that can be used for any purposes defined by the user.
75 type: str
76 default: ""
77 state:
78 description:
79 - When C(present) - adds the galera hostgroup, when C(absent) -
80 removes the galera hostgroup.
81 type: str
82 choices: [ "present", "absent" ]
83 default: present
84 extends_documentation_fragment:
85 - community.proxysql.proxysql.managing_config
86 - community.proxysql.proxysql.connectivity
87 notes:
88 - Supports C(check_mode).
89 '''
90
91 EXAMPLES = '''
92 ---
93 # This example adds a new galera hostgroup, it saves the mysql server config
94 # to disk and loads it to a runtime and also enables the config which has
95 # maximum of 2 writers from the writers_hostgroup.
96
97 - name: Add a galera hostgroup
98 community.proxysql.proxysql_galera_hostgroups:
99 login_user: "admin"
100 login_password: "admin"
101 writer_hostgroup: 1
102 backup_writer_hostgroup: 2
103 reader_hostgroup: 3
104 offline_hostgroup: 4
105 active: 1
106 max_writers: 2
107 writer_is_also_reader: 0
108
109 # This example disables galera hostgroup by setting active to 0
110
111 - name: Disable a galera hostgroup
112 community.proxysql.proxysql_galera_hostgroups:
113 login_user: "admin"
114 login_password: "admin"
115 writer_hostgroup: 1
116 backup_writer_hostgroup: 2
117 reader_hostgroup: 3
118 offline_hostgroup: 4
119 active: 0
120
121 # This example removes a galera hostgroup from configuration,
122 # saves the mysql server config to disk, and loads the mysql
123 # server config to runtime. It uses credentials in a supplied
124 # config file to connect to the proxysql admin interface.
125
126 - name: Remove a galera hostgroup
127 community.proxysql.proxysql_galera_hostgroups:
128 config_file: '/tmp/proxysql.cnf'
129 writer_hostgroup: 0
130 backup_writer_hostgroup: 1
131 reader_hostgroup: 2
132 offline_hostgroup: 3
133 active: 0
134 state: absent
135 '''
136
137 RETURN = '''
138 stdout:
139 description: The galera hostgroup modified or removed from proxysql.
140 returned: On create/update will return the newly modified group, on delete
141 it will return the deleted record.
142 type: dict
143 "sample": {
144 "changed": true,
145 "galera_group": {
146 "active": "1",
147 "backup_writer_hostgroup": "1",
148 "comment": "test",
149 "max_transactions_behind": "0",
150 "max_writers": "3",
151 "offline_hostgroup": "3",
152 "reader_hostgroup": "2",
153 "writer_hostgroup": "0",
154 "writer_is_also_reader": "1"
155 },
156 "msg": "Updated galera hostgroups in check_mode",
157 "state": "present"
158 }
159 '''
160
161 from ansible.module_utils._text import to_native
162 from ansible.module_utils.basic import AnsibleModule
163 from ansible_collections.community.proxysql.plugins.module_utils.mysql import (
164 mysql_connect,
165 mysql_driver,
166 proxysql_common_argument_spec,
167 save_config_to_disk,
168 load_config_to_runtime,
169 )
170
171
172 def perform_checks(module):
173 """ Perform validation of
174 module.params variables
175
176 Args:
177 module (dict):
178 """
179 unique_hostgroups = {
180 "writer_hostgroup": module.params["writer_hostgroup"],
181 "backup_writer_hostgroup": module.params["backup_writer_hostgroup"],
182 "reader_hostgroup": module.params["reader_hostgroup"],
183 "offline_hostgroup": module.params["offline_hostgroup"]
184 }
185 positive_or_zero = {
186 "max_writers": module.params["max_writers"],
187 "max_transactions_behind": module.params["max_transactions_behind"]
188 }
189 positive_or_zero.update(unique_hostgroups)
190 status, hostgroup = check_if_unique(unique_hostgroups)
191 if not status:
192 module.fail_json(
193 msg="%s value is not unique. %s must have unique value" %
194 (hostgroup, list(unique_hostgroups.keys()))
195 )
196 status, hostgroup = check_positive_int(positive_or_zero)
197 if not status:
198 module.fail_json(
199 msg="%s must be an integer greater than or equal to 0" %
200 (hostgroup)
201 )
202
203
204 def check_if_unique(param_dict):
205 """check if dict have unique values
206
207 Args:
208 param_dict (dict): dict of unique values to check
209
210 Returns:
211 Boolean: True if unique
212 hostgroup (string): incorect hostgroup
213 """
214 unique_values = {}
215 for hostgroup, value in param_dict.items():
216 if value not in unique_values.values():
217 unique_values[hostgroup] = value
218 else:
219 return False, hostgroup
220 return True, None
221
222
223 def check_positive_int(param_dict):
224 """check if dict values are positive int or zero
225
226 Args:
227 param_dict (dict): dict of unique values to check
228
229 Returns:
230 Boolean: True if unique
231 hostgroup (string): incorect hostgroup
232 """
233 for hostgroup, value in param_dict.items():
234 if isinstance(value, int):
235 if not value < 0:
236 return True, None
237 return False, hostgroup
238
239
240 class ProxySQLGaleraHostgroup():
241 """proxysql galera hostgroup class"""
242
243 def __init__(self, module, version):
244 self.state = module.params["state"]
245 self.save_to_disk = module.params["save_to_disk"]
246 self.load_to_runtime = module.params["load_to_runtime"]
247
248 config_data_keys = [
249 "writer_hostgroup",
250 "backup_writer_hostgroup",
251 "reader_hostgroup",
252 "offline_hostgroup",
253 "active",
254 "max_writers",
255 "writer_is_also_reader",
256 "max_transactions_behind",
257 "comment"
258 ]
259
260 self.config_data = dict((k, module.params[k])
261 for k in config_data_keys)
262
263 self.galera_hostgroups_support = version.get("major") >= 2
264 self.check_mode = module.check_mode
265
266 def check_galera_group_config(self, cursor):
267 query_string = """SELECT count(*) AS `galera_groups`
268 FROM mysql_galera_hostgroups
269 WHERE writer_hostgroup = %s"""
270
271 query_data = [self.config_data['writer_hostgroup']]
272
273 cursor.execute(query_string, query_data)
274 check_count = cursor.fetchone()
275 return int(check_count["galera_groups"]) > 0
276
277 def get_galera_group_config(self, cursor):
278 query_string = """SELECT *
279 FROM mysql_galera_hostgroups
280 WHERE writer_hostgroup = %s"""
281
282 query_data = [self.config_data['writer_hostgroup']]
283
284 cursor.execute(query_string, query_data)
285 galera_group = cursor.fetchone()
286 return galera_group
287
288 def create_galera_group_config(self, cursor):
289 query_string = """INSERT INTO mysql_galera_hostgroups (
290 writer_hostgroup,
291 backup_writer_hostgroup,
292 reader_hostgroup,
293 offline_hostgroup,
294 active,
295 max_writers,
296 writer_is_also_reader,
297 max_transactions_behind,
298 comment)
299 VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"""
300
301 query_data = [
302 self.config_data['writer_hostgroup'],
303 self.config_data['backup_writer_hostgroup'],
304 self.config_data['reader_hostgroup'],
305 self.config_data['offline_hostgroup'],
306 self.config_data['active'],
307 self.config_data['max_writers'],
308 self.config_data['writer_is_also_reader'],
309 self.config_data['max_transactions_behind'],
310 self.config_data['comment']
311 ]
312
313 cursor.execute(query_string, query_data)
314
315 return True
316
317 def delete_galera_group_config(self, cursor):
318 query_string = """DELETE FROM mysql_galera_hostgroups
319 WHERE writer_hostgroup = %s"""
320
321 query_data = [self.config_data['writer_hostgroup']]
322
323 cursor.execute(query_string, query_data)
324 return True
325
326 def manage_config(self, cursor, state):
327 if state and not self.check_mode:
328 if self.save_to_disk:
329 save_config_to_disk(cursor, "SERVERS")
330 if self.load_to_runtime:
331 load_config_to_runtime(cursor, "SERVERS")
332
333 def create_galera_group(self, result, cursor):
334 if not self.check_mode:
335 result["changed"] = self.create_galera_group_config(cursor)
336 result["msg"] = "Galera group have been added to mysql_galera_hostgroups"
337 result["galera_group"] = self.get_galera_group_config(cursor)
338 self.manage_config(cursor, result["changed"])
339 else:
340 result["changed"] = True
341 result["msg"] = (
342 "Galera group would have been added to"
343 + " mysql_galera_hostgroups, however"
344 + " check_mode is enabled."
345 )
346
347 def update_galera_group(self, result, cursor):
348 current = self.get_galera_group_config(cursor)
349
350 for key, value in current.items():
351 if key != "comment":
352 value = int(value)
353 if self.config_data.get(key):
354 if value != self.config_data[key]:
355 result["changed"] = True
356 result["msg"] = "Updated galera hostgroups in check_mode"
357 if not self.check_mode:
358 result["changed"] = True
359 result["msg"] = "Updated galera hostgroups"
360 self.update_attr(cursor, key)
361
362 result["galera_group"] = self.get_galera_group_config(cursor)
363
364 self.manage_config(cursor, result["changed"])
365
366 def delete_galera_group(self, result, cursor):
367 if not self.check_mode:
368 result["galera_group"] = self.get_galera_group_config(cursor)
369 result["changed"] = self.delete_galera_group_config(cursor)
370 result["msg"] = "Deleted galera group from mysql_galera_hostgroup"
371 self.manage_config(cursor, result["changed"])
372 else:
373 result["changed"] = True
374 result["msg"] = (
375 "galera group would have been deleted from"
376 + " mysql_replication_hostgroups, however"
377 + " check_mode is enabled."
378 )
379
380 def update_attr(self, cursor, attr):
381 query_string = """UPDATE mysql_galera_hostgroups
382 SET %s = %s
383 WHERE writer_hostgroup = %s"""
384
385 query_data = [attr, self.config_data[attr],
386 self.config_data['writer_hostgroup']]
387
388 cursor.execute(query_string, query_data)
389
390
391 # ===========================================
392 # Module execution.
393 #
394
395
396 def main():
397 argument_spec = proxysql_common_argument_spec()
398 argument_spec.update(
399 writer_hostgroup=dict(required=True, type="int"),
400 backup_writer_hostgroup=dict(required=True, type='int'),
401 reader_hostgroup=dict(required=True, type="int"),
402 offline_hostgroup=dict(required=True, type="int"),
403 active=dict(type="int", default=1, choices=[0, 1]),
404 max_writers=dict(type="int", default=1),
405 writer_is_also_reader=dict(type="int", default=0, choices=[0, 1, 2]),
406 max_transactions_behind=dict(type="int", default=0),
407 comment=dict(type="str", default=""),
408 state=dict(default="present", choices=["present", "absent"]),
409 save_to_disk=dict(default=True, type="bool"),
410 load_to_runtime=dict(default=True, type="bool"),
411 )
412
413 module = AnsibleModule(supports_check_mode=True,
414 argument_spec=argument_spec)
415
416 perform_checks(module)
417
418 login_user = module.params["login_user"]
419 login_password = module.params["login_password"]
420 config_file = module.params["config_file"]
421
422 cursor = None
423 try:
424 cursor, db_conn, version = mysql_connect(
425 module, login_user, login_password, config_file, cursor_class="DictCursor"
426 )
427 except mysql_driver.Error as e:
428 module.fail_json(
429 msg="unable to connect to ProxySQL Admin Module.. %s" % (
430 to_native(e))
431 )
432
433 proxysql_galera_group = ProxySQLGaleraHostgroup(module, version)
434 result = {}
435
436 result["state"] = proxysql_galera_group.state
437 result["changed"] = False
438
439 if not proxysql_galera_group.galera_hostgroups_support:
440 result["msg"] = "mysql_galera_hostgroups is only supported with proxysql 2.0.0 and above"
441 module.exit_json(**result)
442
443 if proxysql_galera_group.state == "present":
444 try:
445 if not proxysql_galera_group.check_galera_group_config(cursor):
446 proxysql_galera_group.create_galera_group(result, cursor)
447 else:
448 proxysql_galera_group.update_galera_group(result, cursor)
449
450 result["galera_group"] = proxysql_galera_group.get_galera_group_config(
451 cursor)
452
453 except mysql_driver.Error as e:
454 module.fail_json(
455 msg="unable to modify galera hostgroup.. %s" % (to_native(e))
456 )
457
458 elif proxysql_galera_group.state == "absent":
459 try:
460 if proxysql_galera_group.check_galera_group_config(cursor):
461 proxysql_galera_group.delete_galera_group(result, cursor)
462 else:
463 result["changed"] = False
464 result["msg"] = (
465 "The galera group is already absent from the"
466 + " mysql_galera_hostgroups memory"
467 + " configuration"
468 )
469
470 except mysql_driver.Error as e:
471 module.fail_json(
472 msg="unable to delete galera hostgroup.. %s" % (to_native(e))
473 )
474
475 module.exit_json(**result)
476
477
478 if __name__ == "__main__":
479 main()