Debian Codegraph @

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