Debian Codegraph @

ansible_collections/community/proxysql/plugins/modules/proxysql_pgsql_query_rules_fast_routing.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_query_rules_fast_routing
12 author: "Janos Ruszo (@jruszo)"
13 short_description: Modifies query rules for fast routing policies using the proxysql admin interface
14 description:
15 - The M(community.proxysql.proxysql_pgsql_query_rules_fast_routing) module modifies query rules for fast
16 routing policies and attributes using the proxysql admin interface.
17 version_added: '1.8.0'
18 options:
19 username:
20 description:
21 - Filtering criteria matching username, a query will match only if the connection is made with
22 the correct username.
23 type: str
24 required: true
25 database:
26 description:
27 - Filtering criteria matching database, a query will match only if the connection uses
28 database as its default database.
29 type: str
30 required: true
31 flagIN:
32 description:
33 - Evaluated in the same way as I(flagIN) is in B(pgsql_query_rules) and correlates to the
34 I(flagOUT/apply) specified in the B(pgsql_query_rules) table.
35 (see M(community.proxysql.proxysql_pgsql_query_rules)).
36 type: int
37 default: 0
38 destination_hostgroup:
39 description:
40 - Route matched queries to this hostgroup. This happens unless there is a
41 started transaction and the logged in user has
42 I(transaction_persistent) set to C(True) (refer to M(community.proxysql.proxysql_pgsql_users)).
43 type: int
44 required: true
45 comment:
46 description:
47 - Free form text field, usable for a descriptive comment of the query rule.
48 type: str
49 default: ''
50 state:
51 description:
52 - When C(present), adds the rule. When C(absent), removes the rule.
53 type: str
54 choices: [ "present", "absent" ]
55 default: present
56 force_delete:
57 description:
58 - By default, we avoid deleting more than one query rule in a single batch;
59 however, if you need this behaviour and you are not concerned about the
60 query rules deleted, you can set I(force_delete) to C(True).
61 type: bool
62 default: false
63 extends_documentation_fragment:
64 - community.proxysql.proxysql.managing_config
65 - community.proxysql.proxysql.connectivity
66 attributes:
67 check_mode:
68 description: Do not make any changes to memory, disk, or runtime.
69 support: full
70 '''
71
72 EXAMPLES = '''
73 ---
74 # This example adds a rule for fast routing
75 - name: Add a rule
76 community.proxysql.proxysql_pgsql_query_rules_fast_routing:
77 login_user: admin
78 login_password: admin
79 username: 'user_ro'
80 database: 'default'
81 destination_hostgroup: 1
82 comment: 'fast route user_ro to default database to hostgroup 1'
83 state: present
84 save_to_disk: true
85 load_to_runtime: true
86 '''
87
88 RETURN = '''
89 stdout:
90 description: The pgsql user modified or removed from proxysql.
91 returned: On create/update will return the newly modified rule, in all
92 other cases will return a list of rules that match the supplied
93 criteria.
94 type: dict
95 "sample": {
96 "changed": true,
97 "msg": "Added rule to pgsql_query_rules_fast_routing",
98 "rules": [
99 {
100 "username": "user_ro",
101 "database": "default",
102 "destination_hostgroup": 1,
103 "flagIN": "0",
104 "comment": ""
105 }
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 class ProxySQLPgSQLQueryRuleFastRouting(object):
127
128 def __init__(self, module):
129 self.state = module.params["state"]
130 self.force_delete = module.params["force_delete"]
131 self.save_to_disk = module.params["save_to_disk"]
132 self.load_to_runtime = module.params["load_to_runtime"]
133
134 config_data_keys = [
135 "username",
136 "database",
137 "flagIN",
138 "destination_hostgroup",
139 "comment"
140 ]
141
142 self.config_data = dict(
143 (k, module.params[k])
144 for k in config_data_keys
145 )
146
147 def check_rule_pk_exists(self, cursor):
148 query_string = (
149 "SELECT count(*) AS `rule_count` "
150 "FROM pgsql_query_rules_fast_routing "
151 "WHERE username = %s "
152 "AND database = %s "
153 "AND flagIN = %s"
154 )
155
156 query_data = [
157 self.config_data["username"],
158 self.config_data["database"],
159 self.config_data["flagIN"],
160 ]
161
162 cursor.execute(query_string, query_data)
163 check_count = cursor.fetchone()
164 return (int(check_count['rule_count']) > 0)
165
166 def check_rule_cfg_exists(self, cursor):
167 query_string = "SELECT count(*) AS `rule_count` FROM pgsql_query_rules_fast_routing"
168
169 cols = 0
170 query_data = []
171
172 for col, val in self.config_data.items():
173 if val is not None:
174 cols += 1
175 query_data.append(val)
176 if cols == 1:
177 query_string += " WHERE " + col + " = %s"
178 else:
179 query_string += " AND " + col + " = %s"
180
181 if cols > 0:
182 cursor.execute(query_string, query_data)
183 else:
184 cursor.execute(query_string)
185 check_count = cursor.fetchone()
186 return int(check_count['rule_count'])
187
188 def get_rule_config(self, cursor):
189 query_string = (
190 "SELECT * "
191 "FROM pgsql_query_rules_fast_routing "
192 "WHERE username = %s "
193 "AND database = %s "
194 "AND flagIN = %s"
195 )
196
197 query_data = [
198 self.config_data["username"],
199 self.config_data["database"],
200 self.config_data["flagIN"]
201 ]
202
203 for col, val in self.config_data.items():
204 if val is not None:
205 query_data.append(val)
206 query_string += " AND " + col + " = %s"
207
208 cursor.execute(query_string, query_data)
209 rule = cursor.fetchall()
210 return rule
211
212 def create_rule_config(self, cursor):
213 query_string = "INSERT INTO pgsql_query_rules_fast_routing ("
214
215 cols = 0
216 query_data = []
217
218 for col, val in self.config_data.items():
219 if val is not None:
220 cols += 1
221 query_data.append(val)
222 query_string += col + ","
223
224 query_string = query_string[:-1]
225 query_string += ") VALUES (" + "%s, " * cols
226 query_string = query_string[:-2]
227 query_string += ")"
228
229 cursor.execute(query_string, query_data)
230 return True
231
232 def update_rule_config(self, cursor):
233 query_string = "UPDATE pgsql_query_rules_fast_routing"
234
235 cols = 0
236 query_data = [
237 self.config_data["username"],
238 self.config_data["database"],
239 self.config_data["flagIN"]
240 ]
241
242 for col, val in self.config_data.items():
243 if val is not None and col not in ("username", "database", "flagIN"):
244 query_data.insert(cols, val)
245 cols += 1
246 if cols == 1:
247 query_string += " SET " + col + "= %s,"
248 else:
249 query_string += " " + col + " = %s,"
250
251 query_string = query_string[:-1]
252 query_string += (
253 "WHERE username = %s "
254 "AND database = %s "
255 "AND flagIN = %s"
256 )
257
258 cursor.execute(query_string, query_data)
259 return True
260
261 def delete_rule_config(self, cursor):
262 query_string = "DELETE FROM pgsql_query_rules_fast_routing"
263
264 cols = 0
265 query_data = []
266
267 for col, val in self.config_data.items():
268 if val is not None:
269 cols += 1
270 query_data.append(val)
271 if cols == 1:
272 query_string += " WHERE " + col + " = %s"
273 else:
274 query_string += " AND " + col + " = %s"
275
276 if cols > 0:
277 cursor.execute(query_string, query_data)
278 else:
279 cursor.execute(query_string)
280 check_count = cursor.rowcount
281 return True, int(check_count)
282
283 def manage_config(self, cursor, changed):
284 if not changed:
285 return
286
287 if self.save_to_disk:
288 save_config_to_disk(cursor, "QUERY RULES", "pgsql")
289 if self.load_to_runtime:
290 load_config_to_runtime(cursor, "QUERY RULES", "pgsql")
291
292 def create_rule(self, check_mode, result, cursor):
293 if not check_mode:
294 result['changed'] = self.create_rule_config(cursor)
295 result['msg'] = "Added rule to pgsql_query_rules_fast_routing."
296 self.manage_config(cursor, result['changed'])
297 result['rules'] = self.get_rule_config(cursor)
298 else:
299 result['changed'] = True
300 result['msg'] = (
301 "Rule would have been added to "
302 "pgsql_query_rules_fast_routing, "
303 "however check_mode is enabled."
304 )
305
306 def update_rule(self, check_mode, result, cursor):
307 if not check_mode:
308 result['changed'] = self.update_rule_config(cursor)
309 result['msg'] = "Updated rule in pgsql_query_rules_fast_routing."
310 self.manage_config(cursor, result['changed'])
311 result['rules'] = self.get_rule_config(cursor)
312 else:
313 result['changed'] = True
314 result['msg'] = (
315 "Rule would have been updated in "
316 "pgsql_query_rules_fast_routing, "
317 "however check_mode is enabled."
318 )
319
320 def delete_rule(self, check_mode, result, cursor):
321 if not check_mode:
322 result['rules'] = self.get_rule_config(cursor)
323 result['changed'], result['rows_affected'] = self.delete_rule_config(cursor)
324 result['msg'] = "Deleted rule from pgsql_query_rules_fast_routing."
325 self.manage_config(cursor, result['changed'])
326 else:
327 result['changed'] = True
328 result['msg'] = (
329 "Rule would have been deleted from "
330 "pgsql_query_rules_fast_routing, "
331 "however check_mode is enabled."
332 )
333
334 # ===========================================
335 # Module execution.
336 #
337
338
339 def main():
340 argument_spec = proxysql_common_argument_spec()
341 argument_spec.update(
342 username=dict(required=True, type='str'),
343 database=dict(required=True, type='str'),
344 destination_hostgroup=dict(required=True, type='int'),
345 flagIN=dict(default=0, type='int'),
346 comment=dict(default='', type='str'),
347 state=dict(default='present', choices=['present', 'absent']),
348 force_delete=dict(default=False, type='bool'),
349 save_to_disk=dict(default=True, type='bool'),
350 load_to_runtime=dict(default=True, type='bool')
351 )
352
353 module = AnsibleModule(
354 supports_check_mode=True,
355 argument_spec=argument_spec
356 )
357
358 login_user = module.params["login_user"]
359 login_password = module.params["login_password"]
360 config_file = module.params["config_file"]
361
362 cursor = None
363 try:
364 cursor, db_conn, version = mysql_connect(
365 module,
366 login_user,
367 login_password,
368 config_file,
369 cursor_class='DictCursor'
370 )
371 except mysql_driver.Error as e:
372 module.fail_json(msg="unable to connect to ProxySQL Admin Module: %s" % to_native(e))
373
374 query_rule = ProxySQLPgSQLQueryRuleFastRouting(module)
375 result = {}
376
377 result['state'] = query_rule.state
378
379 if query_rule.state == "present":
380 try:
381 if not query_rule.check_rule_cfg_exists(cursor):
382 if query_rule.config_data["username"] and query_rule.config_data["database"] and \
383 query_rule.check_rule_pk_exists(cursor):
384 query_rule.update_rule(module.check_mode, result, cursor)
385 else:
386 query_rule.create_rule(module.check_mode, result, cursor)
387 else:
388 result['changed'] = False
389 result['msg'] = (
390 "The rule already exists in "
391 "pgsql_query_rules_fast_routing "
392 "and doesn't need to be updated."
393 )
394 result['rules'] = query_rule.get_rule_config(cursor)
395
396 except mysql_driver.Error as e:
397 module.fail_json(msg="unable to modify rule: %s" % to_native(e))
398
399 elif query_rule.state == "absent":
400 try:
401 existing_rules = query_rule.check_rule_cfg_exists(cursor)
402 if existing_rules > 0:
403 if existing_rules == 1 or query_rule.force_delete:
404 query_rule.delete_rule(module.check_mode, result, cursor)
405 else:
406 module.fail_json(msg=("Operation would delete multiple rules use force_delete to override this."))
407 else:
408 result['changed'] = False
409 result['msg'] = (
410 "The rule is already absent from the "
411 "pgsql_query_rules_fast_routing memory "
412 "configuration"
413 )
414 except mysql_driver.Error as e:
415 module.fail_json(msg="unable to remove rule: %s" % to_native(e))
416
417 module.exit_json(**result)
418
419
420 if __name__ == '__main__':
421 main()