Debian Codegraph @

ansible_collections/community/proxysql/plugins/modules/proxysql_pgsql_hostgroup_attributes.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_hostgroup_attributes
12 author: "Janos Ruszo (@jruszo)"
13 short_description: Manages PostgreSQL hostgroup attributes using the ProxySQL admin
14 interface
15 description:
16 - Each row in pgsql_hostgroup_attributes provides a per-hostgroup override
17 of a specific hostgroup. This extension table allows for
18 hostgroup-specific configurations, like `max_num_online_servers`, which
19 change the behaviour of the given hostgroup in ways that are not otherwise
20 possible.
21 version_added: '1.8.0'
22 options:
23 hostgroup_id:
24 description:
25 - ID of the hostgroup.
26 type: int
27 required: true
28
29 state:
30 description:
31 - When C(present) - adds the hostgroup attributes, when C(absent) -
32 removes the hostgroup attributes.
33 type: str
34 choices: [ "present", "absent" ]
35 default: present
36
37 max_num_online_servers:
38 description:
39 - Prevents new connections when the number of ONLINE servers in the
40 hostgroup exceeds this number.
41 type: int
42 default: 1000000
43
44 autocommit:
45 description:
46 - Not yet implemented (as per ProxySQL documentation).
47 type: int
48 default: -1
49
50 free_connections_pct:
51 description:
52 - The percentage of open idle connections for each server in a hostgroup.
53 type: int
54 default: 10
55
56 init_connect:
57 description:
58 - Semicolon-delimited string of SQL statements to be executed for each
59 back-end connection when initialized.
60 type: str
61 default: ""
62
63 multiplex:
64 description:
65 - Enables or disables multiplexing for the specific hostgroup.
66 type: int
67 default: 1
68
69 connection_warming:
70 description:
71 - Whether ProxySQL will be opening new connections until the expected number
72 of warm connections is reached.
73 type: int
74 default: 0
75
76 throttle_connections_per_sec:
77 description:
78 - Maximum number of new connections that can be opened per second.
79 type: int
80 default: 1000000
81
82 ignore_session_variables:
83 description:
84 - Not yet implemented (as per ProxySQL documentation).
85 type: str
86 default: ""
87
88 hostgroup_settings:
89 description:
90 - Override certain global configurations.
91 type: str
92 default: ""
93
94 servers_defaults:
95 description:
96 - Provide default values for discovered servers.
97 type: str
98 default: ""
99
100 comment:
101 description:
102 - Text field that can be used for any purposes defined by the user.
103 type: str
104 default: ""
105
106 extends_documentation_fragment:
107 - community.proxysql.proxysql.managing_config
108 - community.proxysql.proxysql.connectivity
109
110 attributes:
111 check_mode:
112 description: Do not make any changes to memory, disk, or runtime.
113 support: full
114 '''
115
116 EXAMPLES = '''
117 # This example uses supplied credentials to add a hostgroup override for the
118 # hostgroup with ID, `1`. The override sets the maximum number of ONLINE
119 # servers to `1` and provides a short comment. The configuration will be saved
120 # to disk and memory, but not loaded into runtime.
121
122 - name: Add hostgroup overrides to limit servers
123 community.proxysql.proxysql_pgsql_hostgroup_attributes:
124 login_user: admin
125 login_password: admin
126 hostgroup_id: 1
127 state: present
128 load_to_runtime: false
129 max_num_online_servers: 1
130 comment: >-
131 Limit connections to the writer hostgroup to prevent split-brains.
132
133 # This example uses stored configuration to manage a hostgroup override for the
134 # hostgroup with ID, `2`. The override limits the number of new connections
135 # that can be opened to 100/sec. The configuration will be saved to memory and
136 # runtime but not persisted to disk.
137
138 - name: Throttle connections on reader hostgroup
139 community.proxysql.proxysql_pgsql_hostgroup_attributes:
140 config_file: /etc/proxysql/admin.cnf
141 hostgroup_id: 2
142 state: present
143 load_to_runtime: true
144 save_to_disk: false
145 throttle_connections_per_sec: 100
146
147 # This example uses supplied credentials to add a hostgroup override for the
148 # hostgroup with ID, `2`. The override enables multiplexing and sets the number
149 # of cached connections to 100%. The configuration will be saved to memory but
150 # not disk or runtime.
151
152 - name: Aggressively reuse and cache connections
153 community.proxysql.proxysql_pgsql_hostgroup_attributes:
154 login_user: admin
155 login_password: admin
156 hostgroup_id: 2
157 load_to_runtime: false
158 save_to_disk: false
159 multiplex: 1
160 free_connections_pct: 100
161
162 # This example uses stored configuration to manage a hostgroup override for the
163 # hostgroup with ID, `42`. The override changes the hostgroup to handle
164 # warnings and each server added into the hostgroup to have 1000 connections.
165
166 - name: Override globals for hostgroup 42
167 community.proxysql.proxysql_pgsql_hostgroup_attributes:
168 config_file: /etc/proxysql/admin.cnf
169 hostgroup_id: 42
170 hostgroup_settings:
171 handle_warnings: 1
172 servers_defaults:
173 max_connections: 1000
174
175 # This example removes a hostgroup override using the credentials supplied in
176 # a configuration file.
177
178 - name: Remove hostgroup overrides
179 community.proxysql.proxysql_pgsql_hostgroup_attributes:
180 config_file: '~/proxysql.cnf'
181 hostgroup_id: 3
182 state: absent
183 '''
184
185 RETURN = '''
186 stdout:
187 description: The pgsql_hostgroup_override modified or removed from
188 ProxySQL.
189 returned: On create/update will return the newly modified group, on delete
190 it will return the deleted record.
191 type: dict
192 "sample": {
193 "changed": true,
194 "msg": "Added entry to pgsql_hostgroup_overrides",
195 "pgsql_hostgroup_attributes": {
196 "autocommit": "-1",
197 "comment": "",
198 "connection_warming": "0",
199 "free_connections_pct": "10",
200 "hostgroup_id": "21",
201 "hostgroup_settings": "",
202 "ignore_session_variables": "",
203 "init_connect": "",
204 "max_num_online_servers": "1000000",
205 "multiplex": "1",
206 "servers_defaults": "",
207 "throttle_connections_per_sec": "1000000"
208 },
209 "state": "present"
210 }
211 '''
212
213 from ansible.module_utils.basic import AnsibleModule
214 from ansible_collections.community.proxysql.plugins.module_utils.mysql import (
215 mysql_connect,
216 mysql_driver,
217 proxysql_common_argument_spec,
218 save_config_to_disk,
219 load_config_to_runtime,
220 )
221 from ansible.module_utils._text import to_native
222
223
224 def validate_args(module):
225 if not module.params["hostgroup_id"] >= 0:
226 module.fail_json(
227 msg="hostgroup_id must be a integer greater than or equal to 0"
228 )
229
230
231 class ProxySQLPgSQLHostgroupAttributes(object):
232 """
233 See https://www.proxysql.com/documentation/main-runtime/postgresql-tables#pgsql_hostgroup_attributes.
234
235 CREATE TABLE pgsql_hostgroup_attributes (
236 hostgroup_id INT NOT NULL PRIMARY KEY,
237 max_num_online_servers INT CHECK (max_num_online_servers>=0 AND max_num_online_servers <= 1000000) NOT NULL DEFAULT 1000000,
238 autocommit INT CHECK (autocommit IN (-1, 0, 1)) NOT NULL DEFAULT -1,
239 free_connections_pct INT CHECK (free_connections_pct >= 0 AND free_connections_pct <= 100) NOT NULL DEFAULT 10,
240 init_connect VARCHAR NOT NULL DEFAULT '',
241 multiplex INT CHECK (multiplex IN (0, 1)) NOT NULL DEFAULT 1,
242 connection_warming INT CHECK (connection_warming IN (0, 1)) NOT NULL DEFAULT 0,
243 throttle_connections_per_sec INT CHECK (throttle_connections_per_sec >= 1 AND throttle_connections_per_sec <= 1000000) NOT NULL DEFAULT 1000000,
244 ignore_session_variables VARCHAR CHECK (JSON_VALID(ignore_session_variables) OR ignore_session_variables = '') NOT NULL DEFAULT '',
245 hostgroup_settings VARCHAR CHECK (JSON_VALID(hostgroup_settings) OR hostgroup_settings = '') NOT NULL DEFAULT '',
246 servers_defaults VARCHAR CHECK (JSON_VALID(servers_defaults) OR servers_defaults = '') NOT NULL DEFAULT '',
247 comment VARCHAR NOT NULL DEFAULT ''
248 )
249 """ # noqa: E501
250
251 def __init__(self, module, version):
252 self.state = module.params["state"]
253 self.save_to_disk = module.params["save_to_disk"]
254 self.load_to_runtime = module.params["load_to_runtime"]
255 self.check_mode = module.check_mode
256
257 self.hostgroup_id = module.params["hostgroup_id"]
258 self.max_num_online_servers = module.params["max_num_online_servers"]
259 self.autocommit = module.params["autocommit"]
260 self.free_connections_pct = module.params["free_connections_pct"]
261 self.init_connect = module.params["init_connect"]
262 self.multiplex = module.params["multiplex"]
263 self.connection_warming = module.params["connection_warming"]
264 self.throttle_connections_per_sec = \
265 module.params["throttle_connections_per_sec"]
266 self.ignore_session_variables = \
267 module.params["ignore_session_variables"]
268 self.hostgroup_settings = module.params["hostgroup_settings"]
269 self.servers_defaults = module.params["servers_defaults"]
270 self.comment = module.params["comment"]
271
272 def check_exists(self, cursor, keys):
273 query_string = ("SELECT count(*) AS `attributes`"
274 " FROM pgsql_hostgroup_attributes"
275 " WHERE hostgroup_id = %s")
276
277 cursor.execute(query_string, [self.hostgroup_id])
278 check_count = cursor.fetchone()
279 return (int(check_count['attributes']) > 0)
280
281 def select(self, cursor):
282 query_string = ("SELECT * FROM pgsql_hostgroup_attributes"
283 " WHERE hostgroup_id = %s")
284
285 query_data = [self.hostgroup_id]
286
287 cursor.execute(query_string, query_data)
288 repl_group = cursor.fetchone()
289 return repl_group
290
291 def create(self, result, cursor):
292 if not self.check_mode:
293 result['changed'] = self._insert(cursor)
294 result['msg'] = "Added entry to pgsql_hostgroup_attributes"
295 result['pgsql_hostgroup_attributes'] = self.select(cursor)
296 self.manage_config(cursor, result['changed'])
297 else:
298 result['changed'] = True
299 result['msg'] = ("Hostgroup attributes would have been added to" +
300 " pgsql_hostgroup_attributes, however" +
301 " check_mode is enabled.")
302
303 def delete(self, result, cursor):
304 if not self.check_mode:
305 result['pgsql_hostgroup_attributes'] = self.select(cursor)
306 result['changed'] = self._delete(cursor)
307 result['msg'] = "Deleted entry from pgsql_hostgroup_attributes"
308 self.manage_config(cursor, result['changed'])
309 else:
310 result['changed'] = True
311 result['msg'] = ("Hostgroup attributes would have been deleted" +
312 " from pgsql_hostgroup_attributes, however" +
313 " check_mode is enabled.")
314
315 def update(self, result, cursor):
316 if not self.check_mode:
317 result['changed'] = self._update(cursor)
318 result['msg'] = "Updated entry in pgsql_hostgroup_attributes"
319 result['pgsql_hostgroup_attributes'] = self.select(cursor)
320 self.manage_config(cursor, result['changed'])
321 else:
322 result['changed'] = True
323 result['msg'] = ("Hostgroup attributes would have been updated" +
324 " from pgsql_hostgroup_attributes, however" +
325 " check_mode is enabled.")
326
327 def _insert(self, cursor):
328 fields = self._as_fields()
329
330 query_string = \
331 "INSERT INTO pgsql_hostgroup_attributes (" \
332 + ", ".join(list(fields.keys())) \
333 + ") VALUES (" + ", ".join(["%s" for f in fields.values()]) + ")"
334
335 query_data = list(fields.values())
336
337 cursor.execute(query_string, query_data)
338
339 return True
340
341 def _delete(self, cursor):
342 query_string = ("DELETE FROM pgsql_hostgroup_attributes WHERE hostgroup_id = %s")
343
344 cursor.execute(query_string, [self.hostgroup_id])
345
346 return True
347
348 def _update(self, cursor):
349 current = self.select(cursor)
350 new = self._as_fields()
351
352 to_update = {
353 k: v for k, v in new.items()
354 # Use get with default for table changes.
355 if str(current.get(k, '')) != str(v)
356 }
357
358 if len(to_update) == 0:
359 return False
360
361 query = \
362 "UPDATE pgsql_hostgroup_attributes SET " \
363 + ", ".join([f"{k} = %s" for k in to_update.keys()]) \
364 + " WHERE hostgroup_id = %s"
365 args = [*list(to_update.values()), self.hostgroup_id]
366 cursor.execute(query, args)
367 return True
368
369 def manage_config(self, cursor, state):
370 if state and not self.check_mode:
371 if self.save_to_disk:
372 save_config_to_disk(cursor, "SERVERS", "pgsql")
373
374 if self.load_to_runtime:
375 load_config_to_runtime(cursor, "SERVERS", "pgsql")
376
377 def _as_fields(self):
378 return {
379 'hostgroup_id': self.hostgroup_id,
380 'max_num_online_servers': self.max_num_online_servers,
381 'autocommit': self.autocommit,
382 'free_connections_pct': self.free_connections_pct,
383 'init_connect': self.init_connect,
384 'multiplex': self.multiplex,
385 'connection_warming': self.connection_warming,
386 'throttle_connections_per_sec': self.throttle_connections_per_sec,
387 'ignore_session_variables': self.ignore_session_variables,
388 'hostgroup_settings': self.hostgroup_settings,
389 'servers_defaults': self.servers_defaults,
390 'comment': self.comment,
391 }
392
393
394 # ===========================================
395 # Module execution.
396 #
397 def main():
398 argument_spec = proxysql_common_argument_spec()
399 argument_spec.update(
400 state=dict(default='present', choices=['present',
401 'absent']),
402 save_to_disk=dict(default=True, type='bool'),
403 load_to_runtime=dict(default=True, type='bool'),
404
405 hostgroup_id=dict(required=True, type='int'),
406 max_num_online_servers=dict(type='int', default=1000000),
407 autocommit=dict(type='int', default=-1),
408 free_connections_pct=dict(type='int', default=10),
409 init_connect=dict(type='str', default=''),
410 multiplex=dict(type='int', default=1),
411 connection_warming=dict(type='int', default=0),
412 throttle_connections_per_sec=dict(type='int', default=1000000),
413 ignore_session_variables=dict(type='str', default=''),
414 hostgroup_settings=dict(type='str', default=''),
415 servers_defaults=dict(type='str', default=''),
416 comment=dict(type='str', default=''),
417 )
418
419 module = AnsibleModule(
420 supports_check_mode=True,
421 argument_spec=argument_spec
422 )
423
424 validate_args(module)
425
426 login_user = module.params["login_user"]
427 login_password = module.params["login_password"]
428 config_file = module.params["config_file"]
429
430 cursor = None
431 try:
432 cursor, db_conn, version = mysql_connect(module,
433 login_user,
434 login_password,
435 config_file,
436 cursor_class='DictCursor')
437 except mysql_driver.Error as e:
438 module.fail_json(
439 msg=f"Unable to connect to ProxySQL Admin Module.. {to_native(e)}"
440 )
441
442 hostgroup_attributes = ProxySQLPgSQLHostgroupAttributes(module, version)
443 result = {}
444
445 result['state'] = hostgroup_attributes.state
446 result['changed'] = False
447
448 if hostgroup_attributes.state == "present":
449 try:
450 if not hostgroup_attributes.check_exists(cursor, keys=True):
451 hostgroup_attributes.create(result, cursor)
452 else:
453 hostgroup_attributes.update(result, cursor)
454
455 except mysql_driver.Error as e:
456 module.fail_json(
457 msg="unable to modify hostgroup attributes.. %s" % to_native(e)
458 )
459
460 elif hostgroup_attributes.state == "absent":
461 try:
462 if hostgroup_attributes.check_exists(cursor, keys=True):
463 hostgroup_attributes.delete(result, cursor)
464 else:
465 result['changed'] = False
466 result['msg'] = ("The pgsql_hostgroup_attributes is absent" +
467 " from pgsql_hostgroup_attributes memory" +
468 " configuration")
469
470 except mysql_driver.Error as e:
471 module.fail_json(
472 msg="Unable to delete hostgroup attributes.. %s" % to_native(e)
473 )
474
475 module.exit_json(**result)
476
477
478 if __name__ == '__main__':
479 main()