| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2020, 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_user_obj_stat_info |
| 14 |
short_description: Gather statistics about PostgreSQL user objects |
| 15 |
description: |
| 16 |
- Gathers statistics about PostgreSQL user objects. |
| 17 |
version_added: '0.2.0' |
| 18 |
options: |
| 19 |
filter: |
| 20 |
description: |
| 21 |
- Limit the collected information by comma separated string or YAML list. |
| 22 |
- Allowable values are C(functions), C(indexes), C(tables). |
| 23 |
- By default, collects all subsets. |
| 24 |
- Unsupported values are ignored. |
| 25 |
type: list |
| 26 |
elements: str |
| 27 |
schema: |
| 28 |
description: |
| 29 |
- Restrict the output by certain schema. |
| 30 |
type: str |
| 31 |
login_db: |
| 32 |
description: |
| 33 |
- Name of database to connect. |
| 34 |
- The V(db) alias is deprecated and will be removed in version 5.0.0. |
| 35 |
type: str |
| 36 |
aliases: |
| 37 |
- db |
| 38 |
session_role: |
| 39 |
description: |
| 40 |
- Switch to session_role after connecting. The specified session_role must |
| 41 |
be a role that the current login_user is a member of. |
| 42 |
- Permissions checking for SQL commands is carried out as though |
| 43 |
the session_role were the one that had logged in originally. |
| 44 |
type: str |
| 45 |
trust_input: |
| 46 |
description: |
| 47 |
- If C(false), check the value of I(session_role) is potentially dangerous. |
| 48 |
- It makes sense to use C(false) only when SQL injections via I(session_role) are possible. |
| 49 |
type: bool |
| 50 |
default: true |
| 51 |
version_added: '0.2.0' |
| 52 |
|
| 53 |
notes: |
| 54 |
- C(size) and C(total_size) returned values are presented in bytes. |
| 55 |
- For tracking function statistics the PostgreSQL C(track_functions) parameter must be enabled. |
| 56 |
See U(https://www.postgresql.org/docs/current/runtime-config-statistics.html) for more information. |
| 57 |
|
| 58 |
attributes: |
| 59 |
check_mode: |
| 60 |
support: full |
| 61 |
|
| 62 |
seealso: |
| 63 |
- module: community.postgresql.postgresql_info |
| 64 |
- module: community.postgresql.postgresql_ping |
| 65 |
- name: PostgreSQL statistics collector reference |
| 66 |
description: Complete reference of the PostgreSQL statistics collector documentation. |
| 67 |
link: https://www.postgresql.org/docs/current/monitoring-stats.html |
| 68 |
author: |
| 69 |
- Andrew Klychkov (@Andersson007) |
| 70 |
- Thomas O'Donnell (@andytom) |
| 71 |
extends_documentation_fragment: |
| 72 |
- community.postgresql.postgres |
| 73 |
''' |
| 74 |
|
| 75 |
EXAMPLES = r''' |
| 76 |
- name: Collect information about all supported user objects of the acme database |
| 77 |
community.postgresql.postgresql_user_obj_stat_info: |
| 78 |
login_db: acme |
| 79 |
|
| 80 |
- name: Collect information about all supported user objects in the custom schema of the acme database |
| 81 |
community.postgresql.postgresql_user_obj_stat_info: |
| 82 |
login_db: acme |
| 83 |
schema: custom |
| 84 |
|
| 85 |
- name: Collect information about user tables and indexes in the acme database |
| 86 |
community.postgresql.postgresql_user_obj_stat_info: |
| 87 |
login_db: acme |
| 88 |
filter: tables, indexes |
| 89 |
''' |
| 90 |
|
| 91 |
RETURN = r''' |
| 92 |
indexes: |
| 93 |
description: User index statistics. |
| 94 |
returned: success |
| 95 |
type: dict |
| 96 |
sample: {"public": {"test_id_idx": {"idx_scan": 0, "idx_tup_fetch": 0, "idx_tup_read": 0, "relname": "test", "size": 8192, ...}}} |
| 97 |
tables: |
| 98 |
description: User table statistics. |
| 99 |
returned: success |
| 100 |
type: dict |
| 101 |
sample: {"public": {"test": {"analyze_count": 3, "n_dead_tup": 0, "n_live_tup": 0, "seq_scan": 2, "size": 0, "total_size": 8192, ...}}} |
| 102 |
functions: |
| 103 |
description: User function statistics. |
| 104 |
returned: success |
| 105 |
type: dict |
| 106 |
sample: {"public": {"inc": {"calls": 1, "funcid": 26722, "self_time": 0.23, "total_time": 0.23}}} |
| 107 |
''' |
| 108 |
|
| 109 |
from ansible.module_utils.basic import AnsibleModule |
| 110 |
from ansible_collections.community.postgresql.plugins.module_utils.database import \ |
| 111 |
check_input |
| 112 |
from ansible_collections.community.postgresql.plugins.module_utils.postgres import ( |
| 113 |
connect_to_db, |
| 114 |
ensure_required_libs, |
| 115 |
exec_sql, |
| 116 |
get_conn_params, |
| 117 |
pg_cursor_args, |
| 118 |
postgres_common_argument_spec, |
| 119 |
) |
| 120 |
|
| 121 |
# =========================================== |
| 122 |
# PostgreSQL module specific support methods. |
| 123 |
# |
| 124 |
|
| 125 |
|
| 126 |
class PgUserObjStatInfo(): |
| 127 |
"""Class to collect information about PostgreSQL user objects. |
| 128 |
|
| 129 |
Args: |
| 130 |
module (AnsibleModule): Object of AnsibleModule class. |
| 131 |
cursor (cursor): Cursor object of psycopg library to work with PostgreSQL. |
| 132 |
|
| 133 |
Attributes: |
| 134 |
module (AnsibleModule): Object of AnsibleModule class. |
| 135 |
cursor (cursor): Cursor object of psycopg library to work with PostgreSQL. |
| 136 |
executed_queries (list): List of executed queries. |
| 137 |
info (dict): Statistics dictionary. |
| 138 |
obj_func_mapping (dict): Mapping of object types to corresponding functions. |
| 139 |
schema (str): Name of a schema to restrict stat collecting. |
| 140 |
""" |
| 141 |
|
| 142 |
def __init__(self, module, cursor): |
| 143 |
self.module = module |
| 144 |
self.cursor = cursor |
| 145 |
self.info = { |
| 146 |
'functions': {}, |
| 147 |
'indexes': {}, |
| 148 |
'tables': {}, |
| 149 |
} |
| 150 |
self.obj_func_mapping = { |
| 151 |
'functions': self.get_func_stat, |
| 152 |
'indexes': self.get_idx_stat, |
| 153 |
'tables': self.get_tbl_stat, |
| 154 |
} |
| 155 |
self.schema = None |
| 156 |
|
| 157 |
def collect(self, filter_=None, schema=None): |
| 158 |
"""Collect statistics information of user objects. |
| 159 |
|
| 160 |
Kwargs: |
| 161 |
filter_ (list): List of subsets which need to be collected. |
| 162 |
schema (str): Restrict stat collecting by certain schema. |
| 163 |
|
| 164 |
Returns: |
| 165 |
``self.info``. |
| 166 |
""" |
| 167 |
if schema: |
| 168 |
self.set_schema(schema) |
| 169 |
|
| 170 |
if filter_: |
| 171 |
for obj_type in filter_: |
| 172 |
obj_type = obj_type.strip() |
| 173 |
obj_func = self.obj_func_mapping.get(obj_type) |
| 174 |
|
| 175 |
if obj_func is not None: |
| 176 |
obj_func() |
| 177 |
else: |
| 178 |
self.module.warn("Unknown filter option '%s'" % obj_type) |
| 179 |
|
| 180 |
else: |
| 181 |
for obj_func in self.obj_func_mapping.values(): |
| 182 |
obj_func() |
| 183 |
|
| 184 |
return self.info |
| 185 |
|
| 186 |
def get_func_stat(self): |
| 187 |
"""Get function statistics and fill out self.info dictionary.""" |
| 188 |
query = "SELECT * FROM pg_stat_user_functions" |
| 189 |
qp = None |
| 190 |
if self.schema: |
| 191 |
query = "SELECT * FROM pg_stat_user_functions WHERE schemaname = %s" |
| 192 |
qp = (self.schema,) |
| 193 |
|
| 194 |
result = exec_sql(self, query, query_params=qp, add_to_executed=False) |
| 195 |
|
| 196 |
if not result: |
| 197 |
return |
| 198 |
|
| 199 |
self.__fill_out_info(result, |
| 200 |
info_key='functions', |
| 201 |
schema_key='schemaname', |
| 202 |
name_key='funcname') |
| 203 |
|
| 204 |
def get_idx_stat(self): |
| 205 |
"""Get index statistics and fill out self.info dictionary.""" |
| 206 |
query = "SELECT * FROM pg_stat_user_indexes" |
| 207 |
qp = None |
| 208 |
if self.schema: |
| 209 |
query = "SELECT * FROM pg_stat_user_indexes WHERE schemaname = %s" |
| 210 |
qp = (self.schema,) |
| 211 |
|
| 212 |
result = exec_sql(self, query, query_params=qp, add_to_executed=False) |
| 213 |
|
| 214 |
if not result: |
| 215 |
return |
| 216 |
|
| 217 |
self.__fill_out_info(result, |
| 218 |
info_key='indexes', |
| 219 |
schema_key='schemaname', |
| 220 |
name_key='indexrelname') |
| 221 |
|
| 222 |
def get_tbl_stat(self): |
| 223 |
"""Get table statistics and fill out self.info dictionary.""" |
| 224 |
query = "SELECT * FROM pg_stat_user_tables" |
| 225 |
qp = None |
| 226 |
if self.schema: |
| 227 |
query = "SELECT * FROM pg_stat_user_tables WHERE schemaname = %s" |
| 228 |
qp = (self.schema,) |
| 229 |
|
| 230 |
result = exec_sql(self, query, query_params=qp, add_to_executed=False) |
| 231 |
|
| 232 |
if not result: |
| 233 |
return |
| 234 |
|
| 235 |
self.__fill_out_info(result, |
| 236 |
info_key='tables', |
| 237 |
schema_key='schemaname', |
| 238 |
name_key='relname') |
| 239 |
|
| 240 |
def __fill_out_info(self, result, info_key=None, schema_key=None, name_key=None): |
| 241 |
# Convert result to list of dicts to handle it easier: |
| 242 |
result = [dict(row) for row in result] |
| 243 |
|
| 244 |
for elem in result: |
| 245 |
# Add schema name as a key if not presented: |
| 246 |
if not self.info[info_key].get(elem[schema_key]): |
| 247 |
self.info[info_key][elem[schema_key]] = {} |
| 248 |
|
| 249 |
# Add object name key as a subkey |
| 250 |
# (they must be uniq over a schema, so no need additional checks): |
| 251 |
self.info[info_key][elem[schema_key]][elem[name_key]] = {} |
| 252 |
|
| 253 |
# Add other other attributes to a certain index: |
| 254 |
for key, val in elem.items(): |
| 255 |
if key not in (schema_key, name_key): |
| 256 |
self.info[info_key][elem[schema_key]][elem[name_key]][key] = val |
| 257 |
|
| 258 |
if info_key in ('tables', 'indexes'): |
| 259 |
schemaname = elem[schema_key] |
| 260 |
if self.schema: |
| 261 |
schemaname = self.schema |
| 262 |
|
| 263 |
relname = '%s.%s' % (schemaname, elem[name_key]) |
| 264 |
|
| 265 |
result = exec_sql(self, "SELECT pg_relation_size (%s)", |
| 266 |
query_params=(relname,), |
| 267 |
add_to_executed=False) |
| 268 |
|
| 269 |
self.info[info_key][elem[schema_key]][elem[name_key]]['size'] = result[0]["pg_relation_size"] |
| 270 |
|
| 271 |
if info_key == 'tables': |
| 272 |
result = exec_sql(self, "SELECT pg_total_relation_size (%s)", |
| 273 |
query_params=(relname,), |
| 274 |
add_to_executed=False) |
| 275 |
|
| 276 |
self.info[info_key][elem[schema_key]][elem[name_key]]['total_size'] = result[0]["pg_total_relation_size"] |
| 277 |
|
| 278 |
def set_schema(self, schema): |
| 279 |
"""If schema exists, sets self.schema, otherwise fails.""" |
| 280 |
query = ("SELECT 1 as schema_exists FROM information_schema.schemata " |
| 281 |
"WHERE schema_name = %s") |
| 282 |
result = exec_sql(self, query, query_params=(schema,), |
| 283 |
add_to_executed=False) |
| 284 |
|
| 285 |
if result and result[0]["schema_exists"]: |
| 286 |
self.schema = schema |
| 287 |
else: |
| 288 |
self.module.fail_json(msg="Schema '%s' does not exist" % (schema)) |
| 289 |
|
| 290 |
|
| 291 |
# =========================================== |
| 292 |
# Module execution. |
| 293 |
# |
| 294 |
|
| 295 |
def main(): |
| 296 |
argument_spec = postgres_common_argument_spec() |
| 297 |
argument_spec.update( |
| 298 |
login_db=dict(type='str', aliases=['db'], deprecated_aliases=[ |
| 299 |
{ |
| 300 |
'name': 'db', |
| 301 |
'version': '5.0.0', |
| 302 |
'collection_name': 'community.postgresql', |
| 303 |
}], |
| 304 |
), |
| 305 |
filter=dict(type='list', elements='str'), |
| 306 |
session_role=dict(type='str'), |
| 307 |
schema=dict(type='str'), |
| 308 |
trust_input=dict(type="bool", default=True), |
| 309 |
) |
| 310 |
module = AnsibleModule( |
| 311 |
argument_spec=argument_spec, |
| 312 |
supports_check_mode=True, |
| 313 |
) |
| 314 |
|
| 315 |
filter_ = module.params["filter"] |
| 316 |
schema = module.params["schema"] |
| 317 |
|
| 318 |
if not module.params["trust_input"]: |
| 319 |
check_input(module, module.params['session_role']) |
| 320 |
|
| 321 |
# Ensure psycopg libraries are available before connecting to DB: |
| 322 |
ensure_required_libs(module) |
| 323 |
# Connect to DB and make cursor object: |
| 324 |
pg_conn_params = get_conn_params(module, module.params) |
| 325 |
# We don't need to commit anything, so, set it to False: |
| 326 |
db_connection, dummy = connect_to_db(module, pg_conn_params, autocommit=False) |
| 327 |
cursor = db_connection.cursor(**pg_cursor_args) |
| 328 |
|
| 329 |
############################ |
| 330 |
# Create object and do work: |
| 331 |
pg_obj_info = PgUserObjStatInfo(module, cursor) |
| 332 |
|
| 333 |
info_dict = pg_obj_info.collect(filter_, schema) |
| 334 |
|
| 335 |
# Clean up: |
| 336 |
cursor.close() |
| 337 |
db_connection.close() |
| 338 |
|
| 339 |
# Return information: |
| 340 |
module.exit_json(**info_dict) |
| 341 |
|
| 342 |
|
| 343 |
if __name__ == '__main__': |
| 344 |
main() |