Debian Codegraph @

ansible_collections/community/proxysql/plugins/modules/proxysql_pgsql_servers.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_servers
12 author: "Janos Ruszo (@jruszo)"
13 short_description: Adds or removes pgsql hosts from proxysql admin interface
14 description:
15 - The M(community.proxysql.proxysql_pgsql_servers) module adds or removes
16 pgsql hosts using the proxysql admin interface.
17 version_added: '1.8.0'
18 options:
19 hostgroup_id:
20 description:
21 - The hostgroup in which this PostgreSQL instance is included. An instance
22 can be part of one or more hostgroups.
23 type: int
24 default: 0
25 hostname:
26 description:
27 - The hostname or ip address at which the PostgreSQL instance can be contacted.
28 type: str
29 required: true
30 port:
31 description:
32 - The port at which the PostgreSQL instance can be contacted.
33 type: int
34 default: 5432
35 status:
36 description:
37 - ONLINE - Backend server is fully operational.
38 SHUNNED - The server is temporarily taken out of use because either too
39 many connection errors happened in a short time, or
40 replication lag exceeded the allowed threshold.
41 OFFLINE_SOFT - When a server is put into C(OFFLINE_SOFT) mode,
42 connections are kept in use until the current
43 transaction is completed. This allows to gracefully
44 detach a backend.
45 OFFLINE_HARD - When a server is put into C(OFFLINE_HARD) mode, the
46 existing connections are dropped, while new incoming
47 connections aren't accepted either.
48
49 If omitted the proxysql database default for I(status) is C(ONLINE).
50 type: str
51 choices: [ "ONLINE", "SHUNNED", "OFFLINE_SOFT", "OFFLINE_HARD"]
52 weight:
53 description:
54 - The bigger the weight of a server relative to other weights, the higher
55 the probability of the server being chosen from the hostgroup. If
56 omitted the proxysql database default for I(weight) is 1.
57 type: int
58 compression:
59 description:
60 - If I(compression) is set to C(1), new connections to that server will
61 use compression. If omitted the proxysql database default for
62 I(compression) is 0.
63 type: int
64 max_connections:
65 description:
66 - The maximum number of connections ProxySQL will open to this backend
67 server. If omitted the proxysql database default for I(max_connections)
68 is 1000.
69 type: int
70 max_replication_lag:
71 description:
72 - If greater than 0, ProxySQL will regularly monitor replication lag. If
73 replication lag goes above I(max_replication_lag), proxysql will
74 temporarily shun the server until replication catches up. If omitted
75 the proxysql database default for I(max_replication_lag) is 0.
76 type: int
77 use_ssl:
78 description:
79 - If I(use_ssl) is set to C(True), connections to this server will be
80 made using SSL connections. If omitted the proxysql database default
81 for I(use_ssl) is C(False).
82 type: bool
83 max_latency_ms:
84 description:
85 - Ping time is monitored regularly. If a host has a ping time greater
86 than I(max_latency_ms) it is excluded from the connection pool
87 (although the server stays ONLINE). If omitted the proxysql database
88 default for I(max_latency_ms) is 0.
89 type: int
90 comment:
91 description:
92 - Text field that can be used for any purposes defined by the user.
93 Could be a description of what the host stores, a reminder of when the
94 host was added or disabled, or a JSON processed by some checker script.
95 type: str
96 default: ''
97 state:
98 description:
99 - When C(present) - adds the host, when C(absent) - removes the host.
100 type: str
101 choices: [ "present", "absent" ]
102 default: present
103 extends_documentation_fragment:
104 - community.proxysql.proxysql.managing_config
105 - community.proxysql.proxysql.connectivity
106 attributes:
107 check_mode:
108 description: Do not make any changes to memory, disk, or runtime.
109 support: full
110 '''
111
112 EXAMPLES = '''
113 ---
114 # This example adds a server, it saves the pgsql server config to disk, but
115 # avoids loading the pgsql server config to runtime (this might be because
116 # several servers are being added and the user wants to push the config to
117 # runtime in a single batch using the community.proxysql.proxysql_manage_config
118 # module). It uses supplied credentials to connect to the proxysql admin
119 # interface.
120
121 - name: Add a server
122 community.proxysql.proxysql_pgsql_servers:
123 login_user: 'admin'
124 login_password: 'admin'
125 hostname: 'pgsql01'
126 state: present
127 load_to_runtime: false
128
129 # This example removes a server, saves the pgsql server config to disk, and
130 # dynamically loads the pgsql server config to runtime. It uses credentials
131 # in a supplied config file to connect to the proxysql admin interface.
132
133 - name: Remove a server
134 community.proxysql.proxysql_pgsql_servers:
135 config_file: '~/proxysql.cnf'
136 hostname: 'pgsql02'
137 state: absent
138 '''
139
140 RETURN = '''
141 stdout:
142 description: The pgsql host modified or removed from proxysql
143 returned: On create/update will return the newly modified host, on delete
144 it will return the deleted record.
145 type: dict
146 "sample": {
147 "changed": true,
148 "hostname": "192.168.52.1",
149 "msg": "Added server to pgsql_servers",
150 "server": {
151 "comment": "",
152 "compression": "0",
153 "hostgroup_id": "1",
154 "hostname": "192.168.52.1",
155 "max_connections": "1000",
156 "max_latency_ms": "0",
157 "max_replication_lag": "0",
158 "port": "5432",
159 "status": "ONLINE",
160 "use_ssl": "0",
161 "weight": "1"
162 },
163 "state": "present"
164 }
165 '''
166
167 from ansible.module_utils.basic import AnsibleModule
168 from ansible_collections.community.proxysql.plugins.module_utils.mysql import (
169 mysql_connect,
170 mysql_driver,
171 proxysql_common_argument_spec,
172 save_config_to_disk,
173 load_config_to_runtime,
174 )
175 from ansible.module_utils._text import to_native
176
177 # ===========================================
178 # proxysql module specific support methods.
179 #
180
181
182 def perform_checks(module):
183 if module.params["port"] < 0 \
184 or module.params["port"] > 65535:
185 module.fail_json(
186 msg="port must be a valid unix port number (0-65535)"
187 )
188
189 if module.params["compression"]:
190 if module.params["compression"] < 0 \
191 or module.params["compression"] > 1:
192 module.fail_json(
193 msg="compression must be set between 0 and 1"
194 )
195
196 if module.params["max_replication_lag"]:
197 if module.params["max_replication_lag"] < 0 \
198 or module.params["max_replication_lag"] > 126144000:
199 module.fail_json(
200 msg="max_replication_lag must be set between 0 and 126144000"
201 )
202
203
204 class ProxySQLPgSQLServer(object):
205
206 def __init__(self, module):
207 self.state = module.params["state"]
208 self.save_to_disk = module.params["save_to_disk"]
209 self.load_to_runtime = module.params["load_to_runtime"]
210
211 self.hostgroup_id = module.params["hostgroup_id"]
212 self.hostname = module.params["hostname"]
213 self.port = module.params["port"]
214
215 config_data_keys = ["status",
216 "weight",
217 "compression",
218 "max_connections",
219 "max_replication_lag",
220 "use_ssl",
221 "max_latency_ms",
222 "comment"]
223
224 self.config_data = dict((k, module.params[k])
225 for k in config_data_keys)
226
227 def check_server_config_exists(self, cursor):
228 query_string = ("SELECT count(*) AS `host_count`"
229 " FROM pgsql_servers"
230 " WHERE hostgroup_id = %s"
231 " AND hostname = %s"
232 " AND port = %s")
233
234 query_data = \
235 [self.hostgroup_id,
236 self.hostname,
237 self.port]
238
239 cursor.execute(query_string, query_data)
240 check_count = cursor.fetchone()
241 return (int(check_count['host_count']) > 0)
242
243 def check_server_config(self, cursor):
244 query_string = ("SELECT count(*) AS `host_count`"
245 " FROM pgsql_servers"
246 " WHERE hostgroup_id = %s"
247 " AND hostname = %s"
248 " AND port = %s")
249
250 query_data = \
251 [self.hostgroup_id,
252 self.hostname,
253 self.port]
254
255 for col, val in self.config_data.items():
256 if val is not None:
257 query_data.append(val)
258 query_string += "\n AND " + col + " = %s"
259
260 cursor.execute(query_string, query_data)
261 check_count = cursor.fetchone()
262
263 if isinstance(check_count, tuple):
264 return int(check_count[0]) > 0
265
266 return (int(check_count['host_count']) > 0)
267
268 def get_server_config(self, cursor):
269 query_string = ("SELECT * FROM pgsql_servers"
270 " WHERE hostgroup_id = %s"
271 " AND hostname = %s"
272 " AND port = %s")
273
274 query_data = \
275 [self.hostgroup_id,
276 self.hostname,
277 self.port]
278
279 cursor.execute(query_string, query_data)
280 server = cursor.fetchone()
281 return server
282
283 def create_server_config(self, cursor):
284 query_string = \
285 """INSERT INTO pgsql_servers (
286 hostgroup_id,
287 hostname,
288 port"""
289
290 cols = 3
291 query_data = \
292 [self.hostgroup_id,
293 self.hostname,
294 self.port]
295
296 for col, val in self.config_data.items():
297 if val is not None:
298 cols += 1
299 query_data.append(val)
300 query_string += ",\n" + col
301
302 query_string += \
303 (")\n" +
304 "VALUES (" +
305 "%s ," * cols)
306
307 query_string = query_string[:-2]
308 query_string += ")"
309
310 cursor.execute(query_string, query_data)
311 return True
312
313 def update_server_config(self, cursor):
314 query_string = "UPDATE pgsql_servers"
315
316 cols = 0
317 query_data = []
318
319 for col, val in self.config_data.items():
320 if val is not None:
321 cols += 1
322 query_data.append(val)
323 if cols == 1:
324 query_string += "\nSET " + col + "= %s,"
325 else:
326 query_string += "\n " + col + " = %s,"
327
328 query_string = query_string[:-1]
329 query_string += ("\nWHERE hostgroup_id = %s\n AND hostname = %s" +
330 "\n AND port = %s")
331
332 query_data.append(self.hostgroup_id)
333 query_data.append(self.hostname)
334 query_data.append(self.port)
335
336 cursor.execute(query_string, query_data)
337 return True
338
339 def delete_server_config(self, cursor):
340 query_string = ("DELETE FROM pgsql_servers"
341 " WHERE hostgroup_id = %s"
342 " AND hostname = %s"
343 " AND port = %s")
344
345 query_data = \
346 [self.hostgroup_id,
347 self.hostname,
348 self.port]
349
350 cursor.execute(query_string, query_data)
351 return True
352
353 def manage_config(self, cursor, state):
354 if state:
355 if self.save_to_disk:
356 save_config_to_disk(cursor, "SERVERS",
357 variable="pgsql")
358 if self.load_to_runtime:
359 load_config_to_runtime(cursor, "SERVERS",
360 variable="pgsql")
361
362 def create_server(self, check_mode, result, cursor):
363 if not check_mode:
364 result['changed'] = \
365 self.create_server_config(cursor)
366 result['msg'] = "Added server to pgsql_servers"
367 result['server'] = \
368 self.get_server_config(cursor)
369 self.manage_config(cursor,
370 result['changed'])
371 else:
372 result['changed'] = True
373 result['msg'] = ("Server would have been added to" +
374 " pgsql_servers, however check_mode" +
375 " is enabled.")
376
377 def update_server(self, check_mode, result, cursor):
378 if not check_mode:
379 result['changed'] = \
380 self.update_server_config(cursor)
381 result['msg'] = "Updated server in pgsql_servers"
382 result['server'] = \
383 self.get_server_config(cursor)
384 self.manage_config(cursor,
385 result['changed'])
386 else:
387 result['changed'] = True
388 result['msg'] = ("Server would have been updated in" +
389 " pgsql_servers, however check_mode" +
390 " is enabled.")
391
392 def delete_server(self, check_mode, result, cursor):
393 if not check_mode:
394 result['server'] = \
395 self.get_server_config(cursor)
396 result['changed'] = \
397 self.delete_server_config(cursor)
398 result['msg'] = "Deleted server from pgsql_servers"
399 self.manage_config(cursor,
400 result['changed'])
401 else:
402 result['changed'] = True
403 result['msg'] = ("Server would have been deleted from" +
404 " pgsql_servers, however check_mode is" +
405 " enabled.")
406
407 # ===========================================
408 # Module execution.
409 #
410
411
412 def main():
413 argument_spec = proxysql_common_argument_spec()
414 argument_spec.update(
415 hostgroup_id=dict(default=0, type='int'),
416 hostname=dict(required=True, type='str'),
417 port=dict(default=5432, type='int'),
418 status=dict(choices=['ONLINE',
419 'SHUNNED',
420 'OFFLINE_SOFT',
421 'OFFLINE_HARD']),
422 weight=dict(type='int'),
423 compression=dict(type='int'),
424 max_connections=dict(type='int'),
425 max_replication_lag=dict(type='int'),
426 use_ssl=dict(type='bool'),
427 max_latency_ms=dict(type='int'),
428 comment=dict(default='', type='str'),
429 state=dict(default='present', choices=['present',
430 'absent']),
431 save_to_disk=dict(default=True, type='bool'),
432 load_to_runtime=dict(default=True, type='bool')
433 )
434
435 module = AnsibleModule(
436 supports_check_mode=True,
437 argument_spec=argument_spec
438 )
439
440 perform_checks(module)
441
442 login_user = module.params["login_user"]
443 login_password = module.params["login_password"]
444 config_file = module.params["config_file"]
445
446 cursor = None
447 try:
448 cursor, db_conn, version = mysql_connect(module,
449 login_user,
450 login_password,
451 config_file,
452 cursor_class='DictCursor')
453 except mysql_driver.Error as e:
454 module.fail_json(
455 msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e)
456 )
457
458 proxysql_server = ProxySQLPgSQLServer(module)
459 result = {}
460
461 result['state'] = proxysql_server.state
462 if proxysql_server.hostname:
463 result['hostname'] = proxysql_server.hostname
464
465 if proxysql_server.state == "present":
466 try:
467 if not proxysql_server.check_server_config(cursor):
468 if not proxysql_server.check_server_config_exists(cursor):
469 proxysql_server.create_server(module.check_mode,
470 result,
471 cursor)
472 else:
473 proxysql_server.update_server(module.check_mode,
474 result,
475 cursor)
476 else:
477 result['changed'] = False
478 result['msg'] = ("The server already exists in pgsql_servers" +
479 " and doesn't need to be updated.")
480 result['server'] = \
481 proxysql_server.get_server_config(cursor)
482 except mysql_driver.Error as e:
483 module.fail_json(
484 msg="unable to modify server.. %s" % to_native(e)
485 )
486
487 elif proxysql_server.state == "absent":
488 try:
489 if proxysql_server.check_server_config_exists(cursor):
490 proxysql_server.delete_server(module.check_mode,
491 result,
492 cursor)
493 else:
494 result['changed'] = False
495 result['msg'] = ("The server is already absent from the" +
496 " pgsql_servers memory configuration")
497 except mysql_driver.Error as e:
498 module.fail_json(
499 msg="unable to remove server.. %s" % to_native(e)
500 )
501
502 module.exit_json(**result)
503
504
505 if __name__ == '__main__':
506 main()