Debian Codegraph @

ansible_collections/community/proxysql/plugins/modules/proxysql_replication_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 __metaclass__ = type
8
9 DOCUMENTATION = '''
10 ---
11 module: proxysql_replication_hostgroups
12 author: "Ben Mildren (@bmildren)"
13 short_description: Manages replication hostgroups using the proxysql admin
14 interface
15 description:
16 - Each row in mysql_replication_hostgroups represent a pair of
17 writer_hostgroup and reader_hostgroup. ProxySQL will monitor the value of
18 read_only for all the servers in specified hostgroups, and based on the
19 value of read_only will assign the server to the writer or reader
20 hostgroups.
21 options:
22 writer_hostgroup:
23 description:
24 - Id of the writer hostgroup.
25 type: int
26 required: true
27 reader_hostgroup:
28 description:
29 - Id of the reader hostgroup.
30 type: int
31 required: true
32 comment:
33 description:
34 - Text field that can be used for any purposes defined by the user.
35 type: str
36 default: ""
37 state:
38 description:
39 - When C(present) - adds the replication hostgroup, when C(absent) -
40 removes the replication hostgroup.
41 type: str
42 choices: [ "present", "absent" ]
43 default: present
44 check_type:
45 description:
46 - Which check type to use when detecting that the node is a standby.
47 - Requires proxysql >= 2.0.1. Otherwise it has no effect.
48 - C(read_only|innodb_read_only) and C(read_only&innodb_read_only) requires proxysql >= 2.0.8.
49 type: str
50 choices: [ "read_only", "innodb_read_only", "super_read_only", "read_only|innodb_read_only", "read_only&innodb_read_only" ]
51 default: read_only
52 version_added: 1.3.0
53 extends_documentation_fragment:
54 - community.proxysql.proxysql.managing_config
55 - community.proxysql.proxysql.connectivity
56 notes:
57 - Supports C(check_mode).
58 '''
59
60 EXAMPLES = '''
61 ---
62 # This example adds a replication hostgroup, it saves the mysql server config
63 # to disk, but avoids loading the mysql server config to runtime (this might be
64 # because several replication hostgroup are being added and the user wants to
65 # push the config to runtime in a single batch using the
66 # community.general.proxysql_manage_config module). It uses supplied credentials
67 # to connect to the proxysql admin interface.
68
69 - name: Add a replication hostgroup
70 community.proxysql.proxysql_replication_hostgroups:
71 login_user: 'admin'
72 login_password: 'admin'
73 writer_hostgroup: 1
74 reader_hostgroup: 2
75 state: present
76 load_to_runtime: false
77
78 - name: Change check_type
79 community.proxysql.proxysql_replication_hostgroups:
80 login_user: 'admin'
81 login_password: 'admin'
82 writer_hostgroup: 1
83 reader_hostgroup: 2
84 check_type: innodb_read_only
85 state: present
86 load_to_runtime: false
87
88 # This example removes a replication hostgroup, saves the mysql server config
89 # to disk, and dynamically loads the mysql server config to runtime. It uses
90 # credentials in a supplied config file to connect to the proxysql admin
91 # interface.
92
93 - name: Remove a replication hostgroup
94 community.proxysql.proxysql_replication_hostgroups:
95 config_file: '~/proxysql.cnf'
96 writer_hostgroup: 3
97 reader_hostgroup: 4
98 state: absent
99 '''
100
101 RETURN = '''
102 stdout:
103 description: The replication hostgroup modified or removed from proxysql.
104 returned: On create/update will return the newly modified group, on delete
105 it will return the deleted record.
106 type: dict
107 "sample": {
108 "changed": true,
109 "msg": "Added server to mysql_hosts",
110 "repl_group": {
111 "comment": "",
112 "reader_hostgroup": "1",
113 "writer_hostgroup": "2",
114 "check_type": "read_only"
115 },
116 "state": "present"
117 }
118 '''
119
120 from ansible.module_utils.basic import AnsibleModule
121 from ansible_collections.community.proxysql.plugins.module_utils.mysql import (
122 mysql_connect,
123 mysql_driver,
124 proxysql_common_argument_spec,
125 save_config_to_disk,
126 load_config_to_runtime,
127 )
128 from ansible.module_utils._text import to_native
129
130 # ===========================================
131 # proxysql module specific support methods.
132 #
133
134
135 def perform_checks(module):
136 if not module.params["writer_hostgroup"] >= 0:
137 module.fail_json(
138 msg="writer_hostgroup must be a integer greater than or equal to 0"
139 )
140
141 if module.params["reader_hostgroup"] < 0:
142 module.fail_json(
143 msg="reader_hostgroup must be an integer greater than or equal to 0"
144 )
145
146 if module.params["reader_hostgroup"] == module.params["writer_hostgroup"]:
147 module.fail_json(
148 msg="reader_hostgroup and writer_hostgroup must be different integer values")
149
150
151 class ProxySQLReplicationHostgroup(object):
152
153 def __init__(self, module, version):
154 self.state = module.params["state"]
155 self.save_to_disk = module.params["save_to_disk"]
156 self.load_to_runtime = module.params["load_to_runtime"]
157 self.writer_hostgroup = module.params["writer_hostgroup"]
158 self.reader_hostgroup = module.params["reader_hostgroup"]
159 self.comment = module.params["comment"]
160 self.check_type = module.params["check_type"]
161 self.check_type_support = version.get('major') >= 2
162 self.check_mode = module.check_mode
163
164 def check_repl_group_config(self, cursor, keys):
165 query_string = \
166 """SELECT count(*) AS `repl_groups`
167 FROM mysql_replication_hostgroups
168 WHERE writer_hostgroup = %s"""
169
170 query_data = \
171 [self.writer_hostgroup]
172
173 cursor.execute(query_string, query_data)
174 check_count = cursor.fetchone()
175 return (int(check_count['repl_groups']) > 0)
176
177 def get_repl_group_config(self, cursor):
178 query_string = \
179 """SELECT *
180 FROM mysql_replication_hostgroups
181 WHERE writer_hostgroup = %s"""
182
183 query_data = \
184 [self.writer_hostgroup]
185
186 cursor.execute(query_string, query_data)
187 repl_group = cursor.fetchone()
188 return repl_group
189
190 def create_repl_group_config(self, cursor):
191 query_string = \
192 """INSERT INTO mysql_replication_hostgroups (
193 writer_hostgroup,
194 reader_hostgroup,
195 comment)
196 VALUES (%s, %s, %s)"""
197
198 query_data = \
199 [self.writer_hostgroup,
200 self.reader_hostgroup,
201 self.comment or '']
202
203 cursor.execute(query_string, query_data)
204
205 if self.check_type_support:
206 self.update_check_type(cursor)
207
208 return True
209
210 def delete_repl_group_config(self, cursor):
211 query_string = \
212 """DELETE FROM mysql_replication_hostgroups
213 WHERE writer_hostgroup = %s"""
214
215 query_data = \
216 [self.writer_hostgroup]
217
218 cursor.execute(query_string, query_data)
219 return True
220
221 def manage_config(self, cursor, state):
222 if state and not self.check_mode:
223 if self.save_to_disk:
224 save_config_to_disk(cursor, "SERVERS")
225 if self.load_to_runtime:
226 load_config_to_runtime(cursor, "SERVERS")
227
228 def create_repl_group(self, result, cursor):
229 if not self.check_mode:
230 result['changed'] = \
231 self.create_repl_group_config(cursor)
232 result['msg'] = "Added server to mysql_hosts"
233 result['repl_group'] = \
234 self.get_repl_group_config(cursor)
235 self.manage_config(cursor,
236 result['changed'])
237 else:
238 result['changed'] = True
239 result['msg'] = ("Repl group would have been added to" +
240 " mysql_replication_hostgroups, however" +
241 " check_mode is enabled.")
242
243 def update_repl_group(self, result, cursor):
244 current = self.get_repl_group_config(cursor)
245
246 if self.check_type_support and current.get('check_type') != self.check_type:
247 result['changed'] = True
248 if not self.check_mode:
249 result['msg'] = "Updated replication hostgroups"
250 self.update_check_type(cursor)
251 else:
252 result['msg'] = "Updated replication hostgroups in check_mode"
253
254 if current.get('comment') != self.comment:
255 result['changed'] = True
256 result['msg'] = "Updated replication hostgroups in check_mode"
257 if not self.check_mode:
258 result['msg'] = "Updated replication hostgroups"
259 self.update_comment(cursor)
260
261 if int(current.get('reader_hostgroup')) != self.reader_hostgroup:
262 result['changed'] = True
263 result['msg'] = "Updated replication hostgroups in check_mode"
264 if not self.check_mode:
265 result['msg'] = "Updated replication hostgroups"
266 self.update_reader_hostgroup(cursor)
267
268 result['repl_group'] = self.get_repl_group_config(cursor)
269
270 self.manage_config(cursor,
271 result['changed'])
272
273 def delete_repl_group(self, result, cursor):
274 if not self.check_mode:
275 result['repl_group'] = \
276 self.get_repl_group_config(cursor)
277 result['changed'] = \
278 self.delete_repl_group_config(cursor)
279 result['msg'] = "Deleted server from mysql_hosts"
280 self.manage_config(cursor,
281 result['changed'])
282 else:
283 result['changed'] = True
284 result['msg'] = ("Repl group would have been deleted from" +
285 " mysql_replication_hostgroups, however" +
286 " check_mode is enabled.")
287
288 def update_check_type(self, cursor):
289 try:
290 query_string = ("UPDATE mysql_replication_hostgroups "
291 "SET check_type = %s "
292 "WHERE writer_hostgroup = %s")
293
294 cursor.execute(query_string, (self.check_type, self.writer_hostgroup))
295 except Exception as e:
296 pass
297
298 def update_reader_hostgroup(self, cursor):
299 query_string = ("UPDATE mysql_replication_hostgroups "
300 "SET reader_hostgroup = %s "
301 "WHERE writer_hostgroup = %s")
302
303 cursor.execute(query_string, (self.reader_hostgroup, self.writer_hostgroup))
304
305 def update_comment(self, cursor):
306 query_string = ("UPDATE mysql_replication_hostgroups "
307 "SET comment = %s "
308 "WHERE writer_hostgroup = %s ")
309
310 cursor.execute(query_string, (self.comment, self.writer_hostgroup))
311
312
313 # ===========================================
314 # Module execution.
315 #
316 def main():
317 argument_spec = proxysql_common_argument_spec()
318 argument_spec.update(
319 writer_hostgroup=dict(required=True, type='int'),
320 reader_hostgroup=dict(required=True, type='int'),
321 check_type=dict(type='str', default='read_only', choices=['read_only',
322 'innodb_read_only',
323 'super_read_only',
324 'read_only|innodb_read_only',
325 'read_only&innodb_read_only']),
326 comment=dict(type='str', default=''),
327 state=dict(default='present', choices=['present',
328 'absent']),
329 save_to_disk=dict(default=True, type='bool'),
330 load_to_runtime=dict(default=True, type='bool')
331 )
332
333 module = AnsibleModule(
334 supports_check_mode=True,
335 argument_spec=argument_spec
336 )
337
338 perform_checks(module)
339
340 login_user = module.params["login_user"]
341 login_password = module.params["login_password"]
342 config_file = module.params["config_file"]
343
344 cursor = None
345 try:
346 cursor, db_conn, version = mysql_connect(module,
347 login_user,
348 login_password,
349 config_file,
350 cursor_class='DictCursor')
351 except mysql_driver.Error as e:
352 module.fail_json(
353 msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e)
354 )
355
356 proxysql_repl_group = ProxySQLReplicationHostgroup(module, version)
357 result = {}
358
359 result['state'] = proxysql_repl_group.state
360 result['changed'] = False
361
362 if proxysql_repl_group.state == "present":
363 try:
364 if not proxysql_repl_group.check_repl_group_config(cursor,
365 keys=True):
366 proxysql_repl_group.create_repl_group(result,
367 cursor)
368 else:
369 proxysql_repl_group.update_repl_group(result, cursor)
370
371 result['repl_group'] = proxysql_repl_group.get_repl_group_config(cursor)
372
373 except mysql_driver.Error as e:
374 module.fail_json(
375 msg="unable to modify replication hostgroup.. %s" % to_native(e)
376 )
377
378 elif proxysql_repl_group.state == "absent":
379 try:
380 if proxysql_repl_group.check_repl_group_config(cursor,
381 keys=True):
382 proxysql_repl_group.delete_repl_group(result, cursor)
383 else:
384 result['changed'] = False
385 result['msg'] = ("The repl group is already absent from the" +
386 " mysql_replication_hostgroups memory" +
387 " configuration")
388
389 except mysql_driver.Error as e:
390 module.fail_json(
391 msg="unable to delete replication hostgroup.. %s" % to_native(e)
392 )
393
394 module.exit_json(**result)
395
396
397 if __name__ == '__main__':
398 main()