Debian Codegraph @

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