Debian Codegraph @

ansible_collections/community/postgresql/plugins/module_utils/postgres.py

raw
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # Copyright (c), Ted Timmons <[email protected]>, 2017.
8 # Most of this was originally added by other creators in the postgresql_user module.
9 #
10 # Simplified BSD License (see simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
11
12 from __future__ import absolute_import, division, print_function
13
14 __metaclass__ = type
15
16 from datetime import timedelta, datetime
17 from decimal import Decimal
18 from os import environ
19
20 from ansible.module_utils.common.text.converters import to_native
21 from ansible.module_utils.basic import missing_required_lib
22 from ansible_collections.community.postgresql.plugins.module_utils.version import \
23 LooseVersion
24
25 psycopg = None # This line is needed for unit tests
26 psycopg2 = None # This line is needed for unit tests
27 pg_cursor_args = None # This line is needed for unit tests
28 PSYCOPG_VERSION = LooseVersion("0.0") # This line is needed for unit tests
29
30 try:
31 import psycopg
32 from psycopg import ClientCursor
33 from psycopg.rows import dict_row
34
35 from psycopg.types.datetime import TimestamptzLoader
36
37 # We need Psycopg 3 to be at least 3.1.0 because we need Client-side-binding cursors
38 # When a Linux distribution provides both Psycopg2 and Psycopg 3.0 we will use Psycopg2
39 PSYCOPG_VERSION = LooseVersion(psycopg.__version__)
40 if PSYCOPG_VERSION < LooseVersion("3.1"):
41 raise ImportError
42 HAS_PSYCOPG = True
43 pg_cursor_args = {"row_factory": psycopg.rows.dict_row}
44 except ImportError:
45 try:
46 import psycopg2
47 psycopg = psycopg2
48 from psycopg2.extras import DictCursor
49 PSYCOPG_VERSION = LooseVersion(psycopg2.__version__)
50 HAS_PSYCOPG = True
51 pg_cursor_args = {"cursor_factory": DictCursor}
52 except ImportError:
53 HAS_PSYCOPG = False
54
55 TYPES_NEED_TO_CONVERT = (Decimal, timedelta)
56
57
58 if PSYCOPG_VERSION >= LooseVersion("3"):
59 class InfTimestamptzLoader(TimestamptzLoader):
60 def load(self, data):
61 if data == b"infinity":
62 return datetime.max
63 elif data == b"-infinity":
64 return datetime.min
65 else:
66 return super().load(data)
67
68 psycopg.adapters.register_loader("timestamptz", InfTimestamptzLoader)
69
70
71 def postgres_common_argument_spec():
72 """
73 Return a dictionary with connection options.
74
75 The options are commonly used by most of PostgreSQL modules.
76 """
77 # Getting a dictionary of environment variables
78 env_vars = environ
79
80 return dict(
81 login_user=dict(
82 default='postgres' if not env_vars.get("PGUSER") else env_vars.get("PGUSER"),
83 aliases=['login'], deprecated_aliases=[
84 {
85 'name': 'login',
86 'version': '5.0.0',
87 'collection_name': 'community.postgresql',
88 }
89 ],
90 ),
91 login_password=dict(default='', no_log=True),
92 login_host=dict(default='', aliases=['host'], deprecated_aliases=[
93 {
94 'name': 'host',
95 'version': '5.0.0',
96 'collection_name': 'community.postgresql',
97 }],
98 ),
99 login_unix_socket=dict(default='', aliases=['unix_socket'], deprecated_aliases=[
100 {
101 'name': 'unix_socket',
102 'version': '5.0.0',
103 'collection_name': 'community.postgresql',
104 }],
105 ),
106 login_port=dict(
107 type='int',
108 default=int(env_vars.get("PGPORT", 5432)),
109 aliases=['port'], deprecated_aliases=[
110 {
111 'name': 'port',
112 'version': '5.0.0',
113 'collection_name': 'community.postgresql',
114 }
115 ],
116 ),
117 ssl_mode=dict(
118 default='prefer',
119 choices=[
120 'allow',
121 'disable',
122 'prefer',
123 'require',
124 'verify-ca',
125 'verify-full'
126 ]
127 ),
128 ca_cert=dict(aliases=['ssl_rootcert']),
129 ssl_cert=dict(type='path'),
130 ssl_key=dict(type='path'),
131 connect_params=dict(default={}, type='dict'),
132 )
133
134
135 def ensure_required_libs(module):
136 """Check required libraries."""
137 if not HAS_PSYCOPG:
138 # TODO: Should we raise it as psycopg? That will be a breaking change
139 module.fail_json(msg=missing_required_lib('psycopg2'))
140
141 elif PSYCOPG_VERSION < LooseVersion("2.5.1"):
142 module.warn("psycopg should be at least 2.5.1 to support all modules functionality")
143
144 if module.params.get('ca_cert') and PSYCOPG_VERSION < LooseVersion('2.4.3'):
145 module.fail_json(msg='psycopg2 must be at least 2.4.3 in order to use the ca_cert parameter')
146
147
148 def connect_to_db(module, conn_params, autocommit=False, fail_on_conn=True):
149 """Connect to a PostgreSQL database.
150
151 Return a tuple containing a psycopg connection object and error message / None.
152
153 Args:
154 module (AnsibleModule) -- object of ansible.module_utils.basic.AnsibleModule class
155 conn_params (dict) -- dictionary with connection parameters
156
157 Kwargs:
158 autocommit (bool) -- commit automatically (default False)
159 fail_on_conn (bool) -- fail if connection failed or just warn and return None (default True)
160 """
161
162 db_connection = None
163 conn_err = None
164 try:
165 if PSYCOPG_VERSION >= LooseVersion("3.0"):
166 conn_params["autocommit"] = autocommit
167 conn_params["cursor_factory"] = ClientCursor
168 conn_params["row_factory"] = dict_row
169 db_connection = psycopg.connect(**conn_params)
170 else:
171 db_connection = psycopg2.connect(**conn_params)
172 if autocommit:
173 if PSYCOPG_VERSION >= LooseVersion("2.4.2"):
174 db_connection.set_session(autocommit=True)
175 else:
176 db_connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
177
178 # Switch role, if specified:
179 if module.params.get('session_role'):
180 if PSYCOPG_VERSION >= LooseVersion("3.0"):
181 cursor = db_connection.cursor(row_factory=psycopg.rows.dict_row)
182 else:
183 cursor = db_connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
184
185 try:
186 cursor.execute('SET ROLE "%s"' % module.params['session_role'])
187 except Exception as e:
188 module.fail_json(msg="Could not switch role: %s" % to_native(e))
189 finally:
190 cursor.close()
191
192 # Ensure proper datestyle, only supported in psycopg 3
193 if PSYCOPG_VERSION >= LooseVersion("3.0"):
194 cursor = db_connection.cursor(row_factory=psycopg.rows.dict_row)
195 try:
196 cursor.execute('SET datestyle TO iso')
197 except Exception as e:
198 module.fail_json(msg="Could not set date style: %s" % to_native(e))
199 finally:
200 cursor.close()
201
202 except TypeError as e:
203 if 'sslrootcert' in e.args[0]:
204 module.fail_json(msg='Postgresql server must be at least '
205 'version 8.4 to support sslrootcert')
206
207 conn_err = to_native(e)
208
209 except Exception as e:
210 conn_err = to_native(e)
211
212 if conn_err is not None:
213 if fail_on_conn:
214 module.fail_json(msg="unable to connect to database: %s" % conn_err)
215 else:
216 module.warn("PostgreSQL server is unavailable: %s" % conn_err)
217 db_connection = None
218
219 return db_connection, conn_err
220
221
222 def exec_sql(obj, query, query_params=None, return_bool=False, add_to_executed=True, dont_exec=False):
223 """Execute SQL.
224
225 Auxiliary function for PostgreSQL user classes.
226
227 Returns a query result if possible or a boolean value.
228
229 Args:
230 obj (obj) -- must be an object of a user class.
231 The object must have module (AnsibleModule class object) and
232 cursor (psycopg cursor object) attributes
233 query (str) -- SQL query to execute
234
235 Kwargs:
236 query_params (dict or tuple) -- Query parameters to prevent SQL injections,
237 could be a dict or tuple
238 return_bool (bool) -- return True instead of rows if a query was successfully executed.
239 It's necessary for statements that don't return any result like DDL queries (default False).
240 add_to_executed (bool) -- append the query to obj.executed_queries attribute
241 dont_exec (bool) -- used with add_to_executed=True to generate a query, add it
242 to obj.executed_queries list and return True (default False)
243 """
244
245 if dont_exec:
246 # This is usually needed to return queries in check_mode
247 # without execution
248 query = obj.cursor.mogrify(query, query_params)
249 if add_to_executed:
250 obj.executed_queries.append(query)
251
252 return True
253
254 try:
255 if query_params is not None:
256 obj.cursor.execute(query, query_params)
257 else:
258 obj.cursor.execute(query)
259
260 if add_to_executed:
261 if query_params is not None:
262 obj.executed_queries.append(obj.cursor.mogrify(query, query_params))
263 else:
264 obj.executed_queries.append(query)
265
266 if not return_bool:
267 res = obj.cursor.fetchall()
268 return res
269 return True
270 except Exception as e:
271 obj.module.fail_json(msg="Cannot execute SQL '%s': %s" % (query, to_native(e)))
272 return False
273
274
275 def get_conn_params(module, params_dict, warn_db_default=True):
276 """Get connection parameters from the passed dictionary.
277
278 Return a dictionary with parameters to connect to PostgreSQL server.
279
280 Args:
281 module (AnsibleModule) -- object of ansible.module_utils.basic.AnsibleModule class
282 params_dict (dict) -- dictionary with variables
283
284 Kwargs:
285 warn_db_default (bool) -- warn that the default DB is used (default True)
286 """
287
288 # To use defaults values, keyword arguments must be absent, so
289 # check which values are empty and don't include in the return dictionary
290 params_map = {
291 "login_host": "host",
292 "login_user": "user",
293 "login_password": "password",
294 "login_port": "port",
295 "ssl_mode": "sslmode",
296 "ca_cert": "sslrootcert",
297 "ssl_cert": "sslcert",
298 "ssl_key": "sslkey",
299 }
300
301 # Might be different in the modules:
302 if PSYCOPG_VERSION >= LooseVersion("2.7.0"):
303 if params_dict.get('db'):
304 params_map['db'] = 'dbname'
305 elif params_dict.get('database'):
306 params_map['database'] = 'dbname'
307 elif params_dict.get('login_db'):
308 params_map['login_db'] = 'dbname'
309 else:
310 if warn_db_default:
311 module.warn('Database name has not been passed, '
312 'used default database to connect to.')
313 else:
314 if params_dict.get('db'):
315 params_map['db'] = 'database'
316 elif params_dict.get('database'):
317 params_map['database'] = 'database'
318 elif params_dict.get('login_db'):
319 params_map['login_db'] = 'database'
320 else:
321 if warn_db_default:
322 module.warn('Database name has not been passed, '
323 'used default database to connect to.')
324
325 kw = dict((params_map[k], v) for (k, v) in params_dict.items()
326 if k in params_map and v != '' and v is not None)
327
328 # If a login_unix_socket is specified, incorporate it here.
329 is_localhost = False
330 if 'host' not in kw or kw['host'] in [None, 'localhost']:
331 is_localhost = True
332
333 if is_localhost and params_dict["login_unix_socket"] != "":
334 kw["host"] = params_dict["login_unix_socket"]
335
336 # If connect_params is specified, merge it together
337 if params_dict.get("connect_params"):
338 kw.update(params_dict["connect_params"])
339
340 return kw
341
342
343 class PgRole():
344 def __init__(self, module, cursor, name):
345 self.module = module
346 self.cursor = cursor
347 self.name = name
348 self.memberof = self.__fetch_members()
349
350 def __fetch_members(self):
351 query = ("SELECT ARRAY(SELECT b.rolname FROM "
352 "pg_catalog.pg_auth_members m "
353 "JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid) "
354 "WHERE m.member = r.oid) "
355 "FROM pg_catalog.pg_roles r "
356 "WHERE r.rolname = %(dst_role)s")
357
358 res = exec_sql(self, query, query_params={'dst_role': self.name},
359 add_to_executed=False)
360 if res:
361 return res[0]["array"]
362 else:
363 return []
364
365
366 class PgMembership(object):
367 def __init__(self, module, cursor, groups, target_roles, fail_on_role=True):
368 self.module = module
369 self.cursor = cursor
370 self.target_roles = [r.strip() for r in target_roles]
371 self.groups = [r.strip() for r in groups]
372 self.executed_queries = []
373 self.granted = {}
374 self.revoked = {}
375 self.fail_on_role = fail_on_role
376 self.non_existent_roles = []
377 self.changed = False
378 self.__check_roles_exist()
379
380 def grant(self):
381 for group in self.groups:
382 self.granted[group] = []
383
384 for role in self.target_roles:
385 role_obj = PgRole(self.module, self.cursor, role)
386 # If role is in a group now, pass:
387 if group in role_obj.memberof:
388 continue
389
390 query = 'GRANT "%s" TO "%s"' % (group, role)
391 self.changed = exec_sql(self, query, return_bool=True)
392
393 if self.changed:
394 self.granted[group].append(role)
395
396 return self.changed
397
398 def revoke(self):
399 for group in self.groups:
400 self.revoked[group] = []
401
402 for role in self.target_roles:
403 role_obj = PgRole(self.module, self.cursor, role)
404 # If role is not in a group now, pass:
405 if group not in role_obj.memberof:
406 continue
407
408 query = 'REVOKE "%s" FROM "%s"' % (group, role)
409 self.changed = exec_sql(self, query, return_bool=True)
410
411 if self.changed:
412 self.revoked[group].append(role)
413
414 return self.changed
415
416 def match(self):
417 for role in self.target_roles:
418 role_obj = PgRole(self.module, self.cursor, role)
419
420 desired_groups = set(self.groups)
421 current_groups = set(role_obj.memberof)
422 # 1. Get groups that the role is member of but not in self.groups and revoke them
423 groups_to_revoke = current_groups - desired_groups
424 for group in groups_to_revoke:
425 query = 'REVOKE "%s" FROM "%s"' % (group, role)
426 self.changed = exec_sql(self, query, return_bool=True)
427 if group in self.revoked:
428 self.revoked[group].append(role)
429 else:
430 self.revoked[group] = [role]
431
432 # 2. Filter out groups that in self.groups and
433 # the role is already member of and grant the rest
434 groups_to_grant = desired_groups - current_groups
435 for group in groups_to_grant:
436 query = 'GRANT "%s" TO "%s"' % (group, role)
437 self.changed = exec_sql(self, query, return_bool=True)
438 if group in self.granted:
439 self.granted[group].append(role)
440 else:
441 self.granted[group] = [role]
442
443 return self.changed
444
445 def __check_roles_exist(self):
446 if self.groups:
447 existent_groups = self.__roles_exist(self.groups)
448
449 for group in self.groups:
450 if group not in existent_groups:
451 if self.fail_on_role:
452 self.module.fail_json(msg="Role %s does not exist" % group)
453 else:
454 self.module.warn("Role %s does not exist, pass" % group)
455 self.non_existent_roles.append(group)
456
457 existent_roles = self.__roles_exist(self.target_roles)
458 for role in self.target_roles:
459 if role not in existent_roles:
460 if self.fail_on_role:
461 self.module.fail_json(msg="Role %s does not exist" % role)
462 else:
463 self.module.warn("Role %s does not exist, pass" % role)
464
465 if role not in self.groups:
466 self.non_existent_roles.append(role)
467
468 else:
469 if self.fail_on_role:
470 self.module.exit_json(msg="Role role '%s' is a member of role '%s'" % (role, role))
471 else:
472 self.module.warn("Role role '%s' is a member of role '%s', pass" % (role, role))
473
474 # Update role lists, excluding non existent roles:
475 if self.groups:
476 self.groups = [g for g in self.groups if g not in self.non_existent_roles]
477
478 self.target_roles = [r for r in self.target_roles if r not in self.non_existent_roles]
479
480 def __roles_exist(self, roles):
481 tmp = ["'" + x + "'" for x in roles]
482 query = "SELECT rolname FROM pg_roles WHERE rolname IN (%s)" % ','.join(tmp)
483 return [x["rolname"] for x in exec_sql(self, query, add_to_executed=False)]
484
485
486 def set_search_path(cursor, search_path):
487 """Set session's search_path.
488
489 Args:
490 cursor (Psycopg cursor): Database cursor object.
491 search_path (str): String containing comma-separated schema names.
492 """
493 cursor.execute('SET search_path TO %s' % search_path)
494
495
496 def convert_elements_to_pg_arrays(obj):
497 """Convert list elements of the passed object
498 to PostgreSQL arrays represented as strings.
499
500 Args:
501 obj (dict or list): Object whose elements need to be converted.
502
503 Returns:
504 obj (dict or list): Object with converted elements.
505 """
506 if isinstance(obj, dict):
507 for (key, elem) in obj.items():
508 if isinstance(elem, list):
509 obj[key] = list_to_pg_array(elem)
510
511 elif isinstance(obj, list):
512 for i, elem in enumerate(obj):
513 if isinstance(elem, list):
514 obj[i] = list_to_pg_array(elem)
515
516 return obj
517
518
519 def list_to_pg_array(elem):
520 """Convert the passed list to PostgreSQL array
521 represented as a string.
522
523 Args:
524 elem (list): List that needs to be converted.
525
526 Returns:
527 elem (str): String representation of PostgreSQL array.
528 """
529 elem = str(elem).strip('[]')
530 elem = '{' + elem + '}'
531 return elem
532
533
534 def convert_to_supported(val):
535 """Convert unsupported type to appropriate.
536 Args:
537 val (any) -- Any value fetched from database.
538 Returns value of appropriate type.
539 """
540 if isinstance(val, Decimal):
541 return float(val)
542
543 elif isinstance(val, timedelta):
544 return str(val)
545
546 return val # By default returns the same value
547
548
549 def get_server_version(conn):
550 """Get server version.
551
552 Args:
553 conn (psycopg.Connection) -- Psycopg connection object.
554
555 Returns server version (int).
556 """
557 if PSYCOPG_VERSION >= LooseVersion("3.0.0"):
558 return conn.info.server_version
559 else:
560 return conn.server_version
561
562
563 def set_autocommit(conn, autocommit):
564 """Set autocommit.
565
566 Args:
567 conn (psycopg.Connection) -- Psycopg connection object.
568 autocommit -- bool.
569 """
570 if PSYCOPG_VERSION >= LooseVersion("2.4.2"):
571 conn.autocommit = autocommit
572 else:
573 if autocommit:
574 conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
575 else:
576 conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED)
577
578
579 def get_comment(cursor, obj_type, obj_name):
580 """Get DB object's comment.
581
582 Args:
583 cursor (Psycopg cursor) -- Database cursor object.
584 obj_name (str) -- DB object name to get comment from.
585 obj_type (str) -- Object type.
586
587 Returns object's comment (str) if present or None.
588 """
589 query = ''
590 if obj_type == 'role':
591 query = ("SELECT pg_catalog.shobj_description(r.oid, 'pg_authid') AS comment "
592 "FROM pg_catalog.pg_roles AS r "
593 "WHERE r.rolname = %(obj_name)s")
594 elif obj_type == 'extension':
595 query = ("SELECT pg_catalog.obj_description(e.oid, 'pg_extension') AS comment "
596 "FROM pg_catalog.pg_extension AS e "
597 "WHERE e.extname = %(obj_name)s")
598
599 cursor.execute(query, {'obj_name': obj_name})
600 return cursor.fetchone()['comment']
601
602
603 def set_comment(cursor, comment, obj_type, obj_name, check_mode=True, executed_queries=None):
604 """Get DB object's comment.
605
606 Args:
607 cursor (Psycopg cursor) -- Database cursor object.
608 comment(str) -- Comment to set on object.
609 obj_name (str) -- DB object name to set comment on.
610 obj_type (str) -- Object type.
611 executed_statements (list) -- List of executed state-modifying statements.
612 """
613 query = 'COMMENT ON %s "%s" IS ' % (obj_type.upper(), obj_name)
614
615 if not check_mode:
616 cursor.execute(query + '%(comment)s', {'comment': comment})
617
618 if executed_queries is not None:
619 executed_queries.append(cursor.mogrify(query + '%(comment)s', {'comment': comment}))
620
621 return True