Debian Codegraph @

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