Debian Codegraph @

ansible_collections/community/proxysql/plugins/modules/proxysql_pgsql_users.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_users
12 author: "Janos Ruszo (@jruszo)"
13 short_description: Adds or removes postgresql users from proxysql admin interface
14 description:
15 - The M(community.proxysql.proxysql_pgsql_users) module adds or removes postgresql users using the
16 proxysql admin interface.
17 version_added: '1.8.0'
18 options:
19 username:
20 description:
21 - Name of the user connecting to the postgresql or ProxySQL instance.
22 type: str
23 required: true
24 password:
25 description:
26 - Password of the user connecting to the postgresql or ProxySQL instance.
27 type: str
28 active:
29 description:
30 - A user with I(active) set to C(False) will be tracked in the database,
31 but will be never loaded in the in-memory data structures. If omitted
32 the proxysql database default for I(active) is C(True).
33 type: bool
34 use_ssl:
35 description:
36 - If I(use_ssl) is set to C(True), connections by this user will be made
37 using SSL connections. If omitted the proxysql database default for
38 I(use_ssl) is C(False).
39 type: bool
40 default_hostgroup:
41 description:
42 - If there is no matching rule for the queries sent by this user, the
43 traffic it generates is sent to the specified hostgroup.
44 If omitted the proxysql database default for I(default_hostgroup) is 0.
45 type: int
46 transaction_persistent:
47 description:
48 - If this is set for the user with which the PostgreSQL client is connecting
49 to ProxySQL (thus a "frontend" user), transactions started within a
50 hostgroup will remain within that hostgroup regardless of any other
51 rules.
52 If omitted the proxysql database default for I(transaction_persistent)
53 is C(True).
54 type: bool
55 fast_forward:
56 description:
57 - If I(fast_forward) is set to C(True), I(fast_forward) will bypass the
58 query processing layer (rewriting, caching) and pass through the query
59 directly as is to the backend server. If omitted the proxysql database
60 default for I(fast_forward) is C(False).
61 type: bool
62 backend:
63 description:
64 - If I(backend) is set to C(True), this (username, password) pair is
65 used for authenticating to the ProxySQL instance.
66 default: true
67 type: bool
68 frontend:
69 description:
70 - If I(frontend) is set to C(True), this (username, password) pair is
71 used for authenticating to the PostgreSQL servers against any hostgroup.
72 default: true
73 type: bool
74 max_connections:
75 description:
76 - The maximum number of connections ProxySQL will open to the backend for
77 this user. If omitted the proxysql database default for
78 I(max_connections) is 10000.
79 type: int
80 state:
81 description:
82 - When C(present) - adds the user, when C(absent) - removes the user.
83 type: str
84 choices: [ "present", "absent" ]
85 default: present
86 extends_documentation_fragment:
87 - community.proxysql.proxysql.managing_config
88 - community.proxysql.proxysql.connectivity
89 attributes:
90 check_mode:
91 description: Do not make any changes to memory, disk, or runtime.
92 support: full
93 '''
94
95 EXAMPLES = '''
96 ---
97 # This example adds a user, it saves the postgresql user config to disk, but
98 # avoids loading the postgresql user config to runtime (this might be because
99 # several users are being added and the user wants to push the config to
100 # runtime in a single batch using the community.general.proxysql_manage_config
101 # module). It uses supplied credentials to connect to the proxysql admin
102 # interface.
103
104 - name: Add a user
105 community.proxysql.proxysql_pgsql_users:
106 login_user: 'admin'
107 login_password: 'admin'
108 username: 'productiondba'
109 state: present
110 load_to_runtime: false
111
112 # This example removes a user, saves the postgresql user config to disk, and
113 # dynamically loads the postgresql user config to runtime. It uses credentials
114 # in a supplied config file to connect to the proxysql admin interface.
115
116 - name: Remove a user
117 community.proxysql.proxysql_pgsql_users:
118 config_file: '~/proxysql.cnf'
119 username: 'postgresboy'
120 state: absent
121 '''
122
123 RETURN = '''
124 stdout:
125 description: The postgresql user modified or removed from proxysql.
126 returned: On create/update will return the newly modified user, on delete
127 it will return the deleted record.
128 type: dict
129 sample:
130 changed: true
131 msg: Added user to pgsql_users
132 state: present
133 user:
134 active: 1
135 backend: 1
136 default_hostgroup: 1
137 fast_forward: 0
138 frontend: 1
139 max_connections: 10000
140 password: VALUE_SPECIFIED_IN_NO_LOG_PARAMETER
141 transaction_persistent: 0
142 use_ssl: 0
143 username: guest_ro
144 username: guest_ro
145 '''
146
147 from ansible.module_utils.basic import AnsibleModule
148 from ansible_collections.community.proxysql.plugins.module_utils.mysql import (
149 mysql_connect,
150 mysql_driver,
151 proxysql_common_argument_spec,
152 save_config_to_disk,
153 load_config_to_runtime
154 )
155 from ansible.module_utils._text import to_native
156
157 # ===========================================
158 # proxysql module specific support methods.
159 #
160
161
162 class ProxySQLPgSQLUser(object):
163
164 def __init__(self, module):
165 self.state = module.params["state"]
166 self.save_to_disk = module.params["save_to_disk"]
167 self.load_to_runtime = module.params["load_to_runtime"]
168
169 self.username = module.params["username"]
170 self.backend = module.params["backend"]
171 self.frontend = module.params["frontend"]
172
173 config_data_keys = ["password",
174 "active",
175 "use_ssl",
176 "default_hostgroup",
177 "transaction_persistent",
178 "fast_forward",
179 "max_connections"
180 ]
181
182 self.config_data = dict((k, module.params[k])
183 for k in config_data_keys)
184
185 def check_user_config_exists(self, cursor):
186 query_string = ("SELECT count(*) AS `user_count`"
187 " FROM pgsql_users"
188 " WHERE username = %s"
189 " AND backend = %s"
190 " AND frontend = %s")
191
192 query_data = \
193 [self.username,
194 self.backend,
195 self.frontend]
196
197 cursor.execute(query_string, query_data)
198 check_count = cursor.fetchone()
199 return (int(check_count['user_count']) > 0)
200
201 def check_user_privs(self, cursor):
202 query_string = ("SELECT count(*) AS `user_count`"
203 " FROM pgsql_users"
204 " WHERE username = %s"
205 " AND backend = %s"
206 " AND frontend = %s")
207
208 query_data = \
209 [self.username,
210 self.backend,
211 self.frontend]
212
213 for col, val in self.config_data.items():
214 if val is not None:
215 query_data.append(val)
216 query_string += "\n AND " + col + " = %s"
217
218 cursor.execute(query_string, query_data)
219 check_count = cursor.fetchone()
220 return (int(check_count['user_count']) > 0)
221
222 def get_user_config(self, cursor):
223 query_string = ("SELECT *"
224 " FROM pgsql_users"
225 " WHERE username = %s"
226 " AND backend = %s"
227 " AND frontend = %s")
228
229 query_data = \
230 [self.username,
231 self.backend,
232 self.frontend]
233
234 cursor.execute(query_string, query_data)
235 user = cursor.fetchone()
236 return user
237
238 def create_user_config(self, cursor):
239 query_string = ("INSERT INTO pgsql_users ("
240 "username,"
241 " backend,"
242 " frontend")
243
244 cols = 3
245 query_data = \
246 [self.username,
247 self.backend,
248 self.frontend]
249
250 for col, val in self.config_data.items():
251 if val is not None:
252 cols += 1
253 query_data.append(val)
254 query_string += ",\n" + col
255
256 query_string += \
257 (")\n" +
258 "VALUES (" +
259 "%s ," * cols)
260
261 query_string = query_string[:-2]
262 query_string += ")"
263
264 cursor.execute(query_string, query_data)
265 return True
266
267 def update_user_config(self, cursor):
268 query_string = ("UPDATE pgsql_users")
269
270 cols = 0
271 query_data = []
272
273 for col, val in self.config_data.items():
274 if val is not None:
275 cols += 1
276 query_data.append(val)
277 if cols == 1:
278 query_string += "\nSET " + col + "= %s,"
279 else:
280 query_string += "\n " + col + " = %s,"
281
282 query_string = query_string[:-1]
283 query_string += ("\nWHERE username = %s\n AND backend = %s" +
284 "\n AND frontend = %s")
285
286 query_data.append(self.username)
287 query_data.append(self.backend)
288 query_data.append(self.frontend)
289
290 cursor.execute(query_string, query_data)
291 return True
292
293 def delete_user_config(self, cursor):
294 query_string = ("DELETE FROM pgsql_users"
295 " WHERE username = %s"
296 " AND backend = %s"
297 " AND frontend = %s")
298
299 query_data = \
300 [self.username,
301 self.backend,
302 self.frontend]
303
304 cursor.execute(query_string, query_data)
305 return True
306
307 def manage_config(self, cursor, state):
308 if state:
309 if self.save_to_disk:
310 save_config_to_disk(cursor, "USERS", "pgsql")
311 if self.load_to_runtime:
312 load_config_to_runtime(cursor, "USERS", "pgsql")
313
314 def create_user(self, check_mode, result, cursor):
315 if not check_mode:
316 result['changed'] = \
317 self.create_user_config(cursor)
318 result['msg'] = "Added user to pgsql_users"
319 result['user'] = \
320 self.get_user_config(cursor)
321 self.manage_config(cursor,
322 result['changed'])
323 else:
324 result['changed'] = True
325 result['msg'] = ("User would have been added to" +
326 " pgsql_users, however check_mode" +
327 " is enabled.")
328
329 def update_user(self, check_mode, result, cursor):
330 if not check_mode:
331 result['changed'] = \
332 self.update_user_config(cursor)
333 result['msg'] = "Updated user in pgsql_users"
334 result['user'] = \
335 self.get_user_config(cursor)
336 self.manage_config(cursor,
337 result['changed'])
338 else:
339 result['changed'] = True
340 result['msg'] = ("User would have been updated in" +
341 " pgsql_users, however check_mode" +
342 " is enabled.")
343
344 def delete_user(self, check_mode, result, cursor):
345 if not check_mode:
346 result['user'] = \
347 self.get_user_config(cursor)
348 result['changed'] = \
349 self.delete_user_config(cursor)
350 result['msg'] = "Deleted user from pgsql_users"
351 self.manage_config(cursor,
352 result['changed'])
353 else:
354 result['changed'] = True
355 result['msg'] = ("User would have been deleted from" +
356 " pgsql_users, however check_mode is" +
357 " enabled.")
358
359 # ===========================================
360 # Module execution.
361 #
362
363
364 def main():
365 argument_spec = proxysql_common_argument_spec()
366 argument_spec.update(
367 username=dict(required=True, type='str'),
368 password=dict(no_log=True, type='str'),
369 active=dict(type='bool'),
370 use_ssl=dict(type='bool'),
371 default_hostgroup=dict(type='int'),
372 transaction_persistent=dict(type='bool'),
373 fast_forward=dict(type='bool'),
374 backend=dict(default=True, type='bool'),
375 frontend=dict(default=True, type='bool'),
376 max_connections=dict(type='int'),
377 state=dict(default='present', choices=['present',
378 'absent']),
379 save_to_disk=dict(default=True, type='bool'),
380 load_to_runtime=dict(default=True, type='bool')
381 )
382
383 module = AnsibleModule(
384 supports_check_mode=True,
385 argument_spec=argument_spec
386 )
387
388 login_user = module.params["login_user"]
389 login_password = module.params["login_password"]
390 config_file = module.params["config_file"]
391
392 cursor = None
393 try:
394 cursor, db_conn, version = mysql_connect(module,
395 login_user,
396 login_password,
397 config_file,
398 cursor_class='DictCursor')
399 except mysql_driver.Error as e:
400 module.fail_json(
401 msg="unable to connect to ProxySQL Admin Module.. %s" % to_native(e)
402 )
403
404 proxysql_user = ProxySQLPgSQLUser(module)
405 result = {}
406
407 result['state'] = proxysql_user.state
408 if proxysql_user.username:
409 result['username'] = proxysql_user.username
410
411 if proxysql_user.state == "present":
412 try:
413 if not proxysql_user.check_user_privs(cursor):
414 if not proxysql_user.check_user_config_exists(cursor):
415 proxysql_user.create_user(module.check_mode,
416 result,
417 cursor)
418 else:
419 proxysql_user.update_user(module.check_mode,
420 result,
421 cursor)
422 else:
423 result['changed'] = False
424 result['msg'] = ("The user already exists in pgsql_users" +
425 " and doesn't need to be updated.")
426 result['user'] = \
427 proxysql_user.get_user_config(cursor)
428 except mysql_driver.Error as e:
429 module.fail_json(
430 msg="unable to modify user.. %s" % to_native(e)
431 )
432
433 elif proxysql_user.state == "absent":
434 try:
435 if proxysql_user.check_user_config_exists(cursor):
436 proxysql_user.delete_user(module.check_mode,
437 result,
438 cursor)
439 else:
440 result['changed'] = False
441 result['msg'] = ("The user is already absent from the" +
442 " pgsql_users memory configuration")
443 except mysql_driver.Error as e:
444 module.fail_json(
445 msg="unable to remove user.. %s" % to_native(e)
446 )
447
448 module.exit_json(**result)
449
450
451 if __name__ == '__main__':
452 main()