| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2019, Andrew Klychkov (@Andersson007) <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
|
| 9 |
__metaclass__ = type |
| 10 |
|
| 11 |
DOCUMENTATION = r''' |
| 12 |
--- |
| 13 |
module: postgresql_info |
| 14 |
short_description: Gather information about PostgreSQL servers |
| 15 |
description: |
| 16 |
- Gathers information about PostgreSQL servers. |
| 17 |
options: |
| 18 |
filter: |
| 19 |
description: |
| 20 |
- Limit the collected information by comma separated string or YAML list. |
| 21 |
- Allowable values are C(version), |
| 22 |
C(databases), C(in_recovery), C(settings), C(tablespaces), C(roles), |
| 23 |
C(replications), C(repl_slots). |
| 24 |
- By default, collects all subsets. |
| 25 |
- You can use shell-style (fnmatch) wildcard to pass groups of values (see Examples). |
| 26 |
- You can use '!' before value (for example, C(!settings)) to exclude it from the information. |
| 27 |
- If you pass including and excluding values to the filter, for example, I(filter=!settings,ver), |
| 28 |
the excluding values will be ignored. |
| 29 |
type: list |
| 30 |
elements: str |
| 31 |
login_db: |
| 32 |
description: |
| 33 |
- Name of database to connect. |
| 34 |
type: str |
| 35 |
session_role: |
| 36 |
description: |
| 37 |
- Switch to session_role after connecting. The specified session_role must |
| 38 |
be a role that the current login_user is a member of. |
| 39 |
- Permissions checking for SQL commands is carried out as though |
| 40 |
the session_role were the one that had logged in originally. |
| 41 |
type: str |
| 42 |
trust_input: |
| 43 |
description: |
| 44 |
- If C(false), check whether a value of I(session_role) is potentially dangerous. |
| 45 |
- It makes sense to use C(false) only when SQL injections via I(session_role) are possible. |
| 46 |
type: bool |
| 47 |
default: true |
| 48 |
version_added: '0.2.0' |
| 49 |
|
| 50 |
attributes: |
| 51 |
check_mode: |
| 52 |
support: full |
| 53 |
|
| 54 |
seealso: |
| 55 |
- module: community.postgresql.postgresql_ping |
| 56 |
|
| 57 |
author: |
| 58 |
- Andrew Klychkov (@Andersson007) |
| 59 |
|
| 60 |
extends_documentation_fragment: |
| 61 |
- community.postgresql.postgres |
| 62 |
''' |
| 63 |
|
| 64 |
EXAMPLES = r''' |
| 65 |
# Display info from postgres hosts. |
| 66 |
# ansible postgres -m postgresql_info |
| 67 |
|
| 68 |
# Display only databases and roles info from all hosts using shell-style wildcards: |
| 69 |
# ansible all -m postgresql_info -a 'filter=dat*,rol*' |
| 70 |
|
| 71 |
# Display only replications and repl_slots info from standby hosts using shell-style wildcards: |
| 72 |
# ansible standby -m postgresql_info -a 'filter=repl*' |
| 73 |
|
| 74 |
# Display all info from databases hosts except settings: |
| 75 |
# ansible databases -m postgresql_info -a 'filter=!settings' |
| 76 |
|
| 77 |
- name: Collect PostgreSQL version and extensions |
| 78 |
become: true |
| 79 |
become_user: postgres |
| 80 |
community.postgresql.postgresql_info: |
| 81 |
filter: ver*,ext* |
| 82 |
|
| 83 |
- name: Collect all info except settings and roles |
| 84 |
become: true |
| 85 |
become_user: postgres |
| 86 |
community.postgresql.postgresql_info: |
| 87 |
filter: "!settings,!roles" |
| 88 |
|
| 89 |
# On FreeBSD with PostgreSQL 9.5 version and lower use pgsql user to become |
| 90 |
# and pass "postgres" as a database to connect to |
| 91 |
- name: Collect tablespaces and repl_slots info |
| 92 |
become: true |
| 93 |
become_user: pgsql |
| 94 |
community.postgresql.postgresql_info: |
| 95 |
login_db: postgres |
| 96 |
filter: |
| 97 |
- tablesp* |
| 98 |
- repl_sl* |
| 99 |
|
| 100 |
- name: Collect all info except databases |
| 101 |
become: true |
| 102 |
become_user: postgres |
| 103 |
community.postgresql.postgresql_info: |
| 104 |
filter: |
| 105 |
- "!databases" |
| 106 |
''' |
| 107 |
|
| 108 |
RETURN = r''' |
| 109 |
version: |
| 110 |
description: Database server version. |
| 111 |
returned: success |
| 112 |
type: dict |
| 113 |
in_recovery: |
| 114 |
description: Indicates if the service is in recovery mode or not. |
| 115 |
returned: success |
| 116 |
type: bool |
| 117 |
sample: false |
| 118 |
databases: |
| 119 |
description: Information about databases. |
| 120 |
returned: success |
| 121 |
type: dict |
| 122 |
repl_slots: |
| 123 |
description: |
| 124 |
- Replication slots (available in 9.4 and later). |
| 125 |
returned: if existent |
| 126 |
type: dict |
| 127 |
replications: |
| 128 |
description: |
| 129 |
- Information about the current replications by process PIDs. |
| 130 |
returned: if pg_stat_replication view existent |
| 131 |
type: dict |
| 132 |
tablespaces: |
| 133 |
description: |
| 134 |
- Information about tablespaces. |
| 135 |
returned: success |
| 136 |
type: dict |
| 137 |
roles: |
| 138 |
description: |
| 139 |
- Information about roles. |
| 140 |
returned: success |
| 141 |
type: dict |
| 142 |
pending_restart_settings: |
| 143 |
description: |
| 144 |
- List of changed settings that will take effect upon restart . |
| 145 |
returned: success |
| 146 |
type: list |
| 147 |
settings: |
| 148 |
description: |
| 149 |
- Information about run-time server parameters. |
| 150 |
returned: success |
| 151 |
type: dict |
| 152 |
''' |
| 153 |
|
| 154 |
import re |
| 155 |
from fnmatch import fnmatch |
| 156 |
|
| 157 |
from ansible.module_utils.common.text.converters import to_native |
| 158 |
from ansible.module_utils.basic import AnsibleModule |
| 159 |
from ansible_collections.community.postgresql.plugins.module_utils.database import \ |
| 160 |
check_input |
| 161 |
from ansible_collections.community.postgresql.plugins.module_utils.postgres import ( |
| 162 |
connect_to_db, |
| 163 |
ensure_required_libs, |
| 164 |
get_conn_params, |
| 165 |
get_server_version, |
| 166 |
pg_cursor_args, |
| 167 |
postgres_common_argument_spec, |
| 168 |
) |
| 169 |
|
| 170 |
# =========================================== |
| 171 |
# PostgreSQL module specific support methods. |
| 172 |
# |
| 173 |
|
| 174 |
|
| 175 |
class PgDbConn(object): |
| 176 |
"""Auxiliary class for working with PostgreSQL connection objects. |
| 177 |
|
| 178 |
Arguments: |
| 179 |
module (AnsibleModule): Object of AnsibleModule class that |
| 180 |
contains connection parameters. |
| 181 |
""" |
| 182 |
|
| 183 |
def __init__(self, module): |
| 184 |
self.module = module |
| 185 |
self.db_conn = None |
| 186 |
self.cursor = None |
| 187 |
|
| 188 |
def connect(self, fail_on_conn=True): |
| 189 |
"""Connect to a PostgreSQL database and return a cursor object. |
| 190 |
|
| 191 |
Note: connection parameters are passed by self.module object. |
| 192 |
""" |
| 193 |
# Ensure psycopg libraries are available before connecting to DB: |
| 194 |
ensure_required_libs(self.module) |
| 195 |
conn_params = get_conn_params(self.module, self.module.params, warn_db_default=False) |
| 196 |
self.db_conn, dummy = connect_to_db(self.module, conn_params, fail_on_conn=fail_on_conn) |
| 197 |
if self.db_conn is None: |
| 198 |
# only happens if fail_on_conn is False and there actually was an issue connecting to the DB |
| 199 |
return None |
| 200 |
return self.db_conn.cursor(**pg_cursor_args) |
| 201 |
|
| 202 |
def reconnect(self, dbname): |
| 203 |
"""Reconnect to another database and return a PostgreSQL cursor object. |
| 204 |
|
| 205 |
Arguments: |
| 206 |
dbname (string): Database name to connect to. |
| 207 |
""" |
| 208 |
if self.db_conn is not None: |
| 209 |
self.db_conn.close() |
| 210 |
|
| 211 |
# the lines below seem redundant but they are actually needed for connect to work as expected |
| 212 |
self.module.params['db'] = dbname |
| 213 |
self.module.params['database'] = dbname |
| 214 |
self.module.params['login_db'] = dbname |
| 215 |
return self.connect(fail_on_conn=False) |
| 216 |
|
| 217 |
|
| 218 |
class PgClusterInfo(object): |
| 219 |
"""Class for collection information about a PostgreSQL instance. |
| 220 |
|
| 221 |
Arguments: |
| 222 |
module (AnsibleModule): Object of AnsibleModule class. |
| 223 |
db_conn_obj (psycopg.connect): PostgreSQL connection object. |
| 224 |
""" |
| 225 |
|
| 226 |
def __init__(self, module, db_conn_obj): |
| 227 |
self.module = module |
| 228 |
self.db_obj = db_conn_obj |
| 229 |
self.cursor = db_conn_obj.connect() |
| 230 |
self.default_db = self.__get_current_db() |
| 231 |
self.pg_info = { |
| 232 |
"version": {}, |
| 233 |
"in_recovery": None, |
| 234 |
"tablespaces": {}, |
| 235 |
"databases": {}, |
| 236 |
"replications": {}, |
| 237 |
"repl_slots": {}, |
| 238 |
"settings": {}, |
| 239 |
"roles": {}, |
| 240 |
"pending_restart_settings": [], |
| 241 |
} |
| 242 |
|
| 243 |
def collect(self, val_list=False): |
| 244 |
"""Collect information based on 'filter' option.""" |
| 245 |
subset_map = { |
| 246 |
"version": self.get_pg_version, |
| 247 |
"in_recovery": self.get_recovery_state, |
| 248 |
"tablespaces": self.get_tablespaces, |
| 249 |
"databases": self.get_db_info, |
| 250 |
"replications": self.get_repl_info, |
| 251 |
"repl_slots": self.get_rslot_info, |
| 252 |
"settings": self.get_settings, |
| 253 |
"roles": self.get_role_info, |
| 254 |
} |
| 255 |
|
| 256 |
incl_list = [] |
| 257 |
excl_list = [] |
| 258 |
# Notice: incl_list and excl_list |
| 259 |
# don't make sense together, therefore, |
| 260 |
# if incl_list is not empty, we collect |
| 261 |
# only values from it: |
| 262 |
if val_list: |
| 263 |
for i in val_list: |
| 264 |
if i[0] != '!': |
| 265 |
incl_list.append(i) |
| 266 |
else: |
| 267 |
excl_list.append(i.lstrip('!')) |
| 268 |
|
| 269 |
if incl_list: |
| 270 |
for s in subset_map: |
| 271 |
for i in incl_list: |
| 272 |
if fnmatch(s, i): |
| 273 |
subset_map[s]() |
| 274 |
break |
| 275 |
elif excl_list: |
| 276 |
found = False |
| 277 |
# Collect info: |
| 278 |
for s in subset_map: |
| 279 |
for e in excl_list: |
| 280 |
if fnmatch(s, e): |
| 281 |
found = True |
| 282 |
|
| 283 |
if not found: |
| 284 |
subset_map[s]() |
| 285 |
else: |
| 286 |
found = False |
| 287 |
|
| 288 |
# Default behaviour, if include or exclude is not passed: |
| 289 |
else: |
| 290 |
# Just collect info for each item: |
| 291 |
for s in subset_map: |
| 292 |
subset_map[s]() |
| 293 |
|
| 294 |
self.cursor.close() |
| 295 |
self.db_obj.db_conn.close() |
| 296 |
|
| 297 |
return self.pg_info |
| 298 |
|
| 299 |
def get_pub_info(self): |
| 300 |
"""Get publication statistics.""" |
| 301 |
query = ("SELECT p.*, r.rolname AS ownername " |
| 302 |
"FROM pg_catalog.pg_publication AS p " |
| 303 |
"JOIN pg_catalog.pg_roles AS r " |
| 304 |
"ON p.pubowner = r.oid") |
| 305 |
|
| 306 |
result = self.__exec_sql(query) |
| 307 |
|
| 308 |
if result: |
| 309 |
result = [dict(row) for row in result] |
| 310 |
else: |
| 311 |
return {} |
| 312 |
|
| 313 |
publications = {} |
| 314 |
|
| 315 |
for elem in result: |
| 316 |
if not publications.get(elem['pubname']): |
| 317 |
publications[elem['pubname']] = {} |
| 318 |
|
| 319 |
for key, val in elem.items(): |
| 320 |
if key != 'pubname': |
| 321 |
publications[elem['pubname']][key] = val |
| 322 |
|
| 323 |
return publications |
| 324 |
|
| 325 |
def get_subscr_info(self): |
| 326 |
"""Get subscription statistics.""" |
| 327 |
columns_sub_table = ("SELECT column_name " |
| 328 |
"FROM information_schema.columns " |
| 329 |
"WHERE table_schema = 'pg_catalog' " |
| 330 |
"AND table_name = 'pg_subscription'") |
| 331 |
columns_result = self.__exec_sql(columns_sub_table) |
| 332 |
columns = ", ".join(["s.%s" % column["column_name"] for column in columns_result]) |
| 333 |
|
| 334 |
query = ("SELECT %s, r.rolname AS ownername, d.datname AS dbname " |
| 335 |
"FROM pg_catalog.pg_subscription s " |
| 336 |
"JOIN pg_catalog.pg_database d " |
| 337 |
"ON s.subdbid = d.oid " |
| 338 |
"JOIN pg_catalog.pg_roles AS r " |
| 339 |
"ON s.subowner = r.oid" % columns) |
| 340 |
|
| 341 |
result = self.__exec_sql(query) |
| 342 |
|
| 343 |
if result: |
| 344 |
result = [dict(row) for row in result] |
| 345 |
else: |
| 346 |
return {} |
| 347 |
|
| 348 |
subscr_info = {} |
| 349 |
|
| 350 |
for elem in result: |
| 351 |
if not subscr_info.get(elem['dbname']): |
| 352 |
subscr_info[elem['dbname']] = {} |
| 353 |
|
| 354 |
if not subscr_info[elem['dbname']].get(elem['subname']): |
| 355 |
subscr_info[elem['dbname']][elem['subname']] = {} |
| 356 |
|
| 357 |
for key, val in elem.items(): |
| 358 |
if key not in ('subname', 'dbname'): |
| 359 |
subscr_info[elem['dbname']][elem['subname']][key] = val |
| 360 |
|
| 361 |
return subscr_info |
| 362 |
|
| 363 |
def get_tablespaces(self): |
| 364 |
"""Get information about tablespaces.""" |
| 365 |
# Check spcoption exists: |
| 366 |
opt = self.__exec_sql("SELECT column_name " |
| 367 |
"FROM information_schema.columns " |
| 368 |
"WHERE table_name = 'pg_tablespace' " |
| 369 |
"AND column_name = 'spcoptions'") |
| 370 |
|
| 371 |
if not opt: |
| 372 |
query = ("SELECT s.spcname, pg_catalog.pg_get_userbyid(s.spcowner) as rolname, s.spcacl::text " |
| 373 |
"FROM pg_tablespace AS s ") |
| 374 |
else: |
| 375 |
query = ("SELECT s.spcname, pg_catalog.pg_get_userbyid(s.spcowner) as rolname, s.spcacl::text, s.spcoptions " |
| 376 |
"FROM pg_tablespace AS s ") |
| 377 |
|
| 378 |
res = self.__exec_sql(query) |
| 379 |
ts_dict = {} |
| 380 |
for i in res: |
| 381 |
ts_name = i["spcname"] |
| 382 |
ts_info = dict( |
| 383 |
spcowner=i["rolname"], |
| 384 |
spcacl=i["spcacl"] if i["spcacl"] else '', |
| 385 |
) |
| 386 |
if opt: |
| 387 |
ts_info["spcoptions"] = i["spcoptions"] if i["spcoptions"] else [] |
| 388 |
|
| 389 |
ts_dict[ts_name] = ts_info |
| 390 |
|
| 391 |
self.pg_info["tablespaces"] = ts_dict |
| 392 |
|
| 393 |
def get_ext_info(self): |
| 394 |
"""Get information about existing extensions.""" |
| 395 |
# Check that pg_extension exists: |
| 396 |
res = self.__exec_sql("SELECT EXISTS (SELECT 1 FROM " |
| 397 |
"information_schema.tables " |
| 398 |
"WHERE table_name = 'pg_extension')") |
| 399 |
if not res[0]["exists"]: |
| 400 |
return True |
| 401 |
|
| 402 |
query = ("SELECT e.extname, e.extversion, n.nspname, c.description " |
| 403 |
"FROM pg_catalog.pg_extension AS e " |
| 404 |
"LEFT JOIN pg_catalog.pg_namespace AS n " |
| 405 |
"ON n.oid = e.extnamespace " |
| 406 |
"LEFT JOIN pg_catalog.pg_description AS c " |
| 407 |
"ON c.objoid = e.oid " |
| 408 |
"AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass") |
| 409 |
res = self.__exec_sql(query) |
| 410 |
ext_dict = {} |
| 411 |
for i in res: |
| 412 |
ext_ver_raw = i["extversion"] |
| 413 |
|
| 414 |
if re.search(r'^([0-9]+([\-]*[0-9]+)?\.)*[0-9]+([\-]*[0-9]+)?$', i["extversion"]) is None: |
| 415 |
ext_ver = [None, None] |
| 416 |
else: |
| 417 |
ext_ver = i["extversion"].split('.') |
| 418 |
if re.search(r'-', ext_ver[0]) is not None: |
| 419 |
ext_ver = ext_ver[0].split('-') |
| 420 |
else: |
| 421 |
try: |
| 422 |
if re.search(r'-', ext_ver[1]) is not None: |
| 423 |
ext_ver[1] = ext_ver[1].split('-')[0] |
| 424 |
except IndexError: |
| 425 |
ext_ver.append(None) |
| 426 |
|
| 427 |
ext_dict[i["extname"]] = dict( |
| 428 |
extversion=dict( |
| 429 |
major=int(ext_ver[0]) if ext_ver[0] else None, |
| 430 |
minor=int(ext_ver[1]) if ext_ver[1] else None, |
| 431 |
raw=ext_ver_raw, |
| 432 |
), |
| 433 |
nspname=i["nspname"], |
| 434 |
description=i["description"], |
| 435 |
) |
| 436 |
|
| 437 |
return ext_dict |
| 438 |
|
| 439 |
def get_role_info(self): |
| 440 |
"""Get information about roles (in PgSQL groups and users are roles).""" |
| 441 |
query = ("SELECT r.rolname, r.rolsuper, r.rolcanlogin, " |
| 442 |
"r.rolvaliduntil, " |
| 443 |
"ARRAY(SELECT b.rolname " |
| 444 |
"FROM pg_catalog.pg_auth_members AS m " |
| 445 |
"JOIN pg_catalog.pg_roles AS b ON (m.roleid = b.oid) " |
| 446 |
"WHERE m.member = r.oid) AS memberof " |
| 447 |
"FROM pg_catalog.pg_roles AS r " |
| 448 |
"WHERE r.rolname !~ '^pg_'") |
| 449 |
|
| 450 |
res = self.__exec_sql(query) |
| 451 |
rol_dict = {} |
| 452 |
for i in res: |
| 453 |
rol_dict[i["rolname"]] = dict( |
| 454 |
superuser=i["rolsuper"], |
| 455 |
canlogin=i["rolcanlogin"], |
| 456 |
valid_until=i["rolvaliduntil"] if i["rolvaliduntil"] else '', |
| 457 |
member_of=i["memberof"] if i["memberof"] else [], |
| 458 |
) |
| 459 |
|
| 460 |
self.pg_info["roles"] = rol_dict |
| 461 |
|
| 462 |
def get_rslot_info(self): |
| 463 |
"""Get information about replication slots if exist.""" |
| 464 |
# Check that pg_replication_slots exists: |
| 465 |
res = self.__exec_sql("SELECT EXISTS (SELECT 1 FROM " |
| 466 |
"information_schema.tables " |
| 467 |
"WHERE table_name = 'pg_replication_slots')") |
| 468 |
if not res[0]["exists"]: |
| 469 |
return True |
| 470 |
|
| 471 |
query = ("SELECT slot_name, plugin, slot_type, database, " |
| 472 |
"active FROM pg_replication_slots") |
| 473 |
res = self.__exec_sql(query) |
| 474 |
|
| 475 |
# If there is no replication: |
| 476 |
if not res: |
| 477 |
return True |
| 478 |
|
| 479 |
rslot_dict = {} |
| 480 |
for i in res: |
| 481 |
rslot_dict[i["slot_name"]] = dict( |
| 482 |
plugin=i["plugin"], |
| 483 |
slot_type=i["slot_type"], |
| 484 |
database=i["database"], |
| 485 |
active=i["active"], |
| 486 |
) |
| 487 |
|
| 488 |
self.pg_info["repl_slots"] = rslot_dict |
| 489 |
|
| 490 |
def get_settings(self): |
| 491 |
"""Get server settings.""" |
| 492 |
# Check pending restart column exists: |
| 493 |
pend_rest_col_exists = self.__exec_sql("SELECT 1 FROM information_schema.columns " |
| 494 |
"WHERE table_name = 'pg_settings' " |
| 495 |
"AND column_name = 'pending_restart'") |
| 496 |
if not pend_rest_col_exists: |
| 497 |
query = ("SELECT name, setting, unit, context, vartype, " |
| 498 |
"boot_val, min_val, max_val, sourcefile " |
| 499 |
"FROM pg_settings") |
| 500 |
else: |
| 501 |
query = ("SELECT name, setting, unit, context, vartype, " |
| 502 |
"boot_val, min_val, max_val, sourcefile, pending_restart " |
| 503 |
"FROM pg_settings") |
| 504 |
|
| 505 |
res = self.__exec_sql(query) |
| 506 |
|
| 507 |
set_dict = {} |
| 508 |
for i in res: |
| 509 |
val_in_bytes = None |
| 510 |
setting = i["setting"] |
| 511 |
if i["unit"]: |
| 512 |
unit = i["unit"] |
| 513 |
else: |
| 514 |
unit = '' |
| 515 |
|
| 516 |
if unit == 'kB': |
| 517 |
val_in_bytes = int(setting) * 1024 |
| 518 |
|
| 519 |
elif unit == '8kB': |
| 520 |
val_in_bytes = int(setting) * 1024 * 8 |
| 521 |
|
| 522 |
elif unit == 'MB': |
| 523 |
val_in_bytes = int(setting) * 1024 * 1024 |
| 524 |
|
| 525 |
if val_in_bytes is not None and val_in_bytes < 0: |
| 526 |
val_in_bytes = 0 |
| 527 |
|
| 528 |
setting_name = i["name"] |
| 529 |
pretty_val = self.__get_pretty_val(setting_name) |
| 530 |
|
| 531 |
pending_restart = None |
| 532 |
if pend_rest_col_exists: |
| 533 |
pending_restart = i["pending_restart"] |
| 534 |
|
| 535 |
set_dict[setting_name] = dict( |
| 536 |
setting=setting, |
| 537 |
unit=unit, |
| 538 |
context=i["context"], |
| 539 |
vartype=i["vartype"], |
| 540 |
boot_val=i["boot_val"] if i["boot_val"] else '', |
| 541 |
min_val=i["min_val"] if i["min_val"] else '', |
| 542 |
max_val=i["max_val"] if i["max_val"] else '', |
| 543 |
sourcefile=i["sourcefile"] if i["sourcefile"] else '', |
| 544 |
pretty_val=pretty_val, |
| 545 |
) |
| 546 |
if val_in_bytes is not None: |
| 547 |
set_dict[setting_name]['val_in_bytes'] = val_in_bytes |
| 548 |
|
| 549 |
if pending_restart is not None: |
| 550 |
set_dict[setting_name]['pending_restart'] = pending_restart |
| 551 |
if pending_restart: |
| 552 |
self.pg_info["pending_restart_settings"].append(setting_name) |
| 553 |
|
| 554 |
self.pg_info["settings"] = set_dict |
| 555 |
|
| 556 |
def get_repl_info(self): |
| 557 |
"""Get information about replication if the server is a primary.""" |
| 558 |
# Check that pg_replication_slots exists: |
| 559 |
res = self.__exec_sql("SELECT EXISTS (SELECT 1 FROM " |
| 560 |
"information_schema.tables " |
| 561 |
"WHERE table_name = 'pg_stat_replication')") |
| 562 |
if not res[0]["exists"]: |
| 563 |
return True |
| 564 |
|
| 565 |
query = ("SELECT r.pid, pg_catalog.pg_get_userbyid(r.usesysid) AS rolname, r.application_name, r.client_addr::text, " |
| 566 |
"r.client_hostname, r.backend_start::text, r.state " |
| 567 |
"FROM pg_stat_replication AS r ") |
| 568 |
res = self.__exec_sql(query) |
| 569 |
|
| 570 |
# If there is no replication: |
| 571 |
if not res: |
| 572 |
return True |
| 573 |
|
| 574 |
repl_dict = {} |
| 575 |
for i in res: |
| 576 |
repl_dict[str(i["pid"])] = dict( |
| 577 |
usename=i["rolname"], |
| 578 |
app_name=i["application_name"] if i["application_name"] else '', |
| 579 |
client_addr=i["client_addr"], |
| 580 |
client_hostname=i["client_hostname"] if i["client_hostname"] else '', |
| 581 |
backend_start=i["backend_start"], |
| 582 |
state=i["state"], |
| 583 |
) |
| 584 |
|
| 585 |
self.pg_info["replications"] = repl_dict |
| 586 |
|
| 587 |
def get_lang_info(self): |
| 588 |
"""Get information about current supported languages.""" |
| 589 |
query = ("SELECT l.lanname, pg_catalog.pg_get_userbyid(l.lanowner) AS rolname, l.lanacl::text " |
| 590 |
"FROM pg_language AS l ") |
| 591 |
res = self.__exec_sql(query) |
| 592 |
lang_dict = {} |
| 593 |
for i in res: |
| 594 |
lang_dict[i["lanname"]] = dict( |
| 595 |
lanowner=i["rolname"], |
| 596 |
lanacl=i["lanacl"] if i["lanacl"] else '', |
| 597 |
) |
| 598 |
|
| 599 |
return lang_dict |
| 600 |
|
| 601 |
def get_namespaces(self): |
| 602 |
"""Get information about namespaces.""" |
| 603 |
query = ("SELECT n.nspname, pg_catalog.pg_get_userbyid(n.nspowner) AS rolname, n.nspacl::text " |
| 604 |
"FROM pg_catalog.pg_namespace AS n ") |
| 605 |
res = self.__exec_sql(query) |
| 606 |
|
| 607 |
nsp_dict = {} |
| 608 |
for i in res: |
| 609 |
nsp_dict[i["nspname"]] = dict( |
| 610 |
nspowner=i["rolname"], |
| 611 |
nspacl=i["nspacl"] if i["nspacl"] else '', |
| 612 |
) |
| 613 |
|
| 614 |
return nsp_dict |
| 615 |
|
| 616 |
def get_pg_version(self): |
| 617 |
"""Get major and minor PostgreSQL server version.""" |
| 618 |
query = "SELECT current_setting('server_version_num')" |
| 619 |
srv_ver = self.__exec_sql(query)[0]["current_setting"] |
| 620 |
query = "SELECT version()" |
| 621 |
raw = self.__exec_sql(query)[0]["version"] |
| 622 |
|
| 623 |
major = int(srv_ver[0:2]) |
| 624 |
minor = int(srv_ver[2:4]) |
| 625 |
patch = int(srv_ver[4:6]) |
| 626 |
|
| 627 |
if minor == 0: |
| 628 |
# PG 10+ |
| 629 |
full = '.'.join([str(major), str(patch)]) |
| 630 |
else: |
| 631 |
# PG < 10 |
| 632 |
full = '.'.join([str(major), str(minor), str(patch)]) |
| 633 |
|
| 634 |
self.pg_info["version"] = dict( |
| 635 |
major=major, |
| 636 |
minor=minor, |
| 637 |
patch=patch, |
| 638 |
full=full, |
| 639 |
raw=raw, |
| 640 |
) |
| 641 |
|
| 642 |
if minor == 0: |
| 643 |
self.pg_info["version"]["minor"] = patch |
| 644 |
self.pg_info["version"]["patch"] = None |
| 645 |
|
| 646 |
def get_recovery_state(self): |
| 647 |
"""Get if the service is in recovery mode.""" |
| 648 |
self.pg_info["in_recovery"] = self.__exec_sql("SELECT pg_is_in_recovery()")[0]["pg_is_in_recovery"] |
| 649 |
|
| 650 |
def get_db_info(self): |
| 651 |
"""Get information about the current database.""" |
| 652 |
# Following query returns: |
| 653 |
# Name, Owner, Encoding, Collate, Ctype, Access Priv, Size |
| 654 |
query = ("SELECT d.datname, " |
| 655 |
"pg_catalog.pg_get_userbyid(d.datdba) AS username, " |
| 656 |
"pg_catalog.pg_encoding_to_char(d.encoding) AS encoding, " |
| 657 |
"d.datcollate, " |
| 658 |
"d.datctype, " |
| 659 |
"pg_catalog.array_to_string(d.datacl, E'\n') aclstring, " |
| 660 |
"CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT') " |
| 661 |
"THEN pg_catalog.pg_database_size(d.datname)::text " |
| 662 |
"ELSE 'No Access' END as dbsize, " |
| 663 |
"t.spcname " |
| 664 |
"FROM pg_catalog.pg_database AS d " |
| 665 |
"JOIN pg_catalog.pg_tablespace t ON d.dattablespace = t.oid " |
| 666 |
"WHERE d.datname != 'template0'") |
| 667 |
|
| 668 |
res = self.__exec_sql(query) |
| 669 |
|
| 670 |
db_dict = {} |
| 671 |
for i in res: |
| 672 |
db_dict[i["datname"]] = dict( |
| 673 |
owner=i["username"], |
| 674 |
encoding=i["encoding"], |
| 675 |
collate=i["datcollate"], |
| 676 |
ctype=i["datctype"], |
| 677 |
access_priv=i["aclstring"] if i["aclstring"] else '', |
| 678 |
size=i["dbsize"], |
| 679 |
) |
| 680 |
|
| 681 |
if get_server_version(self.cursor.connection) >= 100000: |
| 682 |
subscr_info = self.get_subscr_info() |
| 683 |
|
| 684 |
for datname in db_dict: |
| 685 |
self.cursor = self.db_obj.reconnect(datname) |
| 686 |
if self.cursor is None: |
| 687 |
# that means we don't have permission to access these database |
| 688 |
db_dict[datname]['namespaces'] = {} |
| 689 |
db_dict[datname]['extensions'] = {} |
| 690 |
db_dict[datname]['languages'] = {} |
| 691 |
db_dict[datname]['error'] = "Could not connect to the database." |
| 692 |
continue |
| 693 |
db_dict[datname]['namespaces'] = self.get_namespaces() |
| 694 |
db_dict[datname]['extensions'] = self.get_ext_info() |
| 695 |
db_dict[datname]['languages'] = self.get_lang_info() |
| 696 |
if get_server_version(self.cursor.connection) >= 100000: |
| 697 |
db_dict[datname]['publications'] = self.get_pub_info() |
| 698 |
db_dict[datname]['subscriptions'] = subscr_info.get(datname, {}) |
| 699 |
|
| 700 |
self.pg_info["databases"] = db_dict |
| 701 |
# Reconnect to the default DB after gathering info in other DBs |
| 702 |
self.cursor = self.db_obj.reconnect(self.default_db) |
| 703 |
|
| 704 |
def __get_pretty_val(self, setting): |
| 705 |
"""Get setting's value represented by SHOW command.""" |
| 706 |
return self.__exec_sql('SHOW "%s"' % setting)[0][setting] |
| 707 |
|
| 708 |
def __exec_sql(self, query): |
| 709 |
"""Execute SQL and return the result.""" |
| 710 |
try: |
| 711 |
self.cursor.execute(query) |
| 712 |
res = self.cursor.fetchall() |
| 713 |
if res: |
| 714 |
return res |
| 715 |
except Exception as e: |
| 716 |
self.module.fail_json(msg="Cannot execute SQL '%s': %s" % (query, to_native(e))) |
| 717 |
self.cursor.close() |
| 718 |
return False |
| 719 |
|
| 720 |
def __get_current_db(self): |
| 721 |
"""Get current DB""" |
| 722 |
# The context is to get the user's default database. |
| 723 |
# Should be executed right after logging in |
| 724 |
# https://github.com/ansible-collections/community.postgresql/issues/794 |
| 725 |
return self.__exec_sql('SELECT current_database() AS db')[0]['db'] |
| 726 |
|
| 727 |
# =========================================== |
| 728 |
# Module execution. |
| 729 |
# |
| 730 |
|
| 731 |
|
| 732 |
def main(): |
| 733 |
argument_spec = postgres_common_argument_spec() |
| 734 |
argument_spec.update( |
| 735 |
login_db=dict(type='str'), |
| 736 |
filter=dict(type='list', elements='str'), |
| 737 |
session_role=dict(type='str'), |
| 738 |
trust_input=dict(type='bool', default=True), |
| 739 |
) |
| 740 |
module = AnsibleModule( |
| 741 |
argument_spec=argument_spec, |
| 742 |
supports_check_mode=True, |
| 743 |
) |
| 744 |
|
| 745 |
filter_ = module.params['filter'] |
| 746 |
|
| 747 |
if not module.params['trust_input']: |
| 748 |
# Check input for potentially dangerous elements: |
| 749 |
check_input(module, module.params['session_role']) |
| 750 |
|
| 751 |
db_conn_obj = PgDbConn(module) |
| 752 |
|
| 753 |
# Do job: |
| 754 |
pg_info = PgClusterInfo(module, db_conn_obj) |
| 755 |
|
| 756 |
module.exit_json(**pg_info.collect(filter_)) |
| 757 |
|
| 758 |
|
| 759 |
if __name__ == '__main__': |
| 760 |
main() |