| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) Andrei 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_alter_system |
| 14 |
short_description: Change a PostgreSQL server configuration parameter |
| 15 |
description: |
| 16 |
- Supports C(PostgreSQL 14) or later. |
| 17 |
- Allows to change a PostgreSQL server configuration parameter. |
| 18 |
- The module uses ALTER SYSTEM command and applies changes by reload server configuration. |
| 19 |
- Some parameters require PostgreSQL to restart. See the RV(restart_required) return value. |
| 20 |
|
| 21 |
version_added: '3.13.0' |
| 22 |
|
| 23 |
options: |
| 24 |
param: |
| 25 |
description: |
| 26 |
- Name of PostgreSQL server parameter. |
| 27 |
type: str |
| 28 |
required: true |
| 29 |
|
| 30 |
value: |
| 31 |
description: |
| 32 |
- Parameter value to set. |
| 33 |
- Specify the value in appropriate units! |
| 34 |
- For memory-related parameters of type integer, it is C(kB), C(MB), C(GB), and C(TB). |
| 35 |
- Use V(_RESET) to run the C(ALTER SYSTEM RESET param) which will remove |
| 36 |
a corresponding entry from C(postgresql.auto.conf). Always returns C(changed=True). |
| 37 |
- For boolean parameters, pass the V("on") or V("off") string. |
| 38 |
type: str |
| 39 |
required: true |
| 40 |
|
| 41 |
session_role: |
| 42 |
description: |
| 43 |
- Switch to session_role after connecting. The specified session_role must |
| 44 |
be a role that the current login_user is a member of. |
| 45 |
- Permissions checking for SQL commands is carried out as though |
| 46 |
the O(session_role) were the one that had logged in originally. |
| 47 |
type: str |
| 48 |
|
| 49 |
login_db: |
| 50 |
description: |
| 51 |
- Name of database to connect. |
| 52 |
type: str |
| 53 |
|
| 54 |
trust_input: |
| 55 |
description: |
| 56 |
- If V(false), check whether values of parameters are potentially dangerous. |
| 57 |
- It makes sense to use V(false) only when SQL injections are possible. |
| 58 |
type: bool |
| 59 |
default: true |
| 60 |
|
| 61 |
notes: |
| 62 |
- For some parameters restart of PostgreSQL server is required. |
| 63 |
See official documentation U(https://www.postgresql.org/docs/current/view-pg-settings.html). |
| 64 |
|
| 65 |
attributes: |
| 66 |
check_mode: |
| 67 |
support: full |
| 68 |
|
| 69 |
seealso: |
| 70 |
- module: community.postgresql.postgresql_info |
| 71 |
- name: PostgreSQL server configuration |
| 72 |
description: General information about PostgreSQL server configuration. |
| 73 |
link: https://www.postgresql.org/docs/current/runtime-config.html |
| 74 |
- name: PostgreSQL view pg_catalog.pg_settings reference |
| 75 |
description: Complete reference of the pg_catalog.pg_settings view documentation. |
| 76 |
link: https://www.postgresql.org/docs/current/view-pg-settings.html |
| 77 |
- name: PostgreSQL ALTER SYSTEM command reference |
| 78 |
description: Complete reference of the ALTER SYSTEM command documentation. |
| 79 |
link: https://www.postgresql.org/docs/current/sql-altersystem.html |
| 80 |
|
| 81 |
author: |
| 82 |
- Andrew Klychkov (@Andersson007) |
| 83 |
|
| 84 |
extends_documentation_fragment: |
| 85 |
- community.postgresql.postgres |
| 86 |
''' |
| 87 |
|
| 88 |
EXAMPLES = r''' |
| 89 |
- name: Set work_mem |
| 90 |
community.postgresql.postgresql_alter_system: |
| 91 |
param: work_mem |
| 92 |
value: 1024 |
| 93 |
|
| 94 |
- name: Reset work_mem |
| 95 |
community.postgresql.postgresql_alter_system: |
| 96 |
param: work_mem |
| 97 |
value: _RESET |
| 98 |
|
| 99 |
- name: Set TimeZone parameter (careful, case sensitive) |
| 100 |
community.postgresql.postgresql_alter_system: |
| 101 |
param: TimeZone |
| 102 |
value: 'Europe/Paris' |
| 103 |
''' |
| 104 |
|
| 105 |
RETURN = r''' |
| 106 |
attrs: |
| 107 |
description: |
| 108 |
- Parameter attributes from C(pg_catalog.pg_settings) |
| 109 |
that do not change. |
| 110 |
returned: success |
| 111 |
type: dict |
| 112 |
sample: { |
| 113 |
'unit': 'kB', |
| 114 |
'context': 'user', |
| 115 |
'vartype': 'integer', |
| 116 |
'min_val': 64, |
| 117 |
'max_val': 2147483647, |
| 118 |
'boot_val': 4096, |
| 119 |
} |
| 120 |
diff: |
| 121 |
description: |
| 122 |
- A dictionary the C(before) and C(after) keys. |
| 123 |
- Each key contains a dictionary of key-value pairs |
| 124 |
representing changeable columns and values for the parameter |
| 125 |
obtained from the pg_catalog.pg_settings relation. |
| 126 |
returned: success |
| 127 |
type: dict |
| 128 |
sample: { |
| 129 |
'before': { |
| 130 |
'setting': 4096, |
| 131 |
'pending_restart': false |
| 132 |
}, |
| 133 |
'after': { |
| 134 |
'setting': 8192, |
| 135 |
'pending_restart': false, |
| 136 |
} |
| 137 |
} |
| 138 |
|
| 139 |
executed_queries: |
| 140 |
description: |
| 141 |
- List of executed queries except SELECTs. |
| 142 |
- In the check mode, returns a query that |
| 143 |
would be supposed to get executed in the real mode. |
| 144 |
returned: success |
| 145 |
type: list |
| 146 |
elements: str |
| 147 |
sample: ["ALTER SYSTEM SET shared_preload_libraries = ''"] |
| 148 |
|
| 149 |
restart_required: |
| 150 |
description: |
| 151 |
- Indicates if restart of PostgreSQL is required or not. |
| 152 |
- Added here for convenience. Can be also determined from |
| 153 |
the diff["after"]["pending_restart"] return value. |
| 154 |
returned: success |
| 155 |
type: bool |
| 156 |
sample: true |
| 157 |
''' |
| 158 |
|
| 159 |
from ansible.module_utils.basic import AnsibleModule |
| 160 |
from ansible.module_utils.common.text.converters import to_native |
| 161 |
from ansible_collections.community.postgresql.plugins.module_utils.database import \ |
| 162 |
check_input |
| 163 |
from ansible_collections.community.postgresql.plugins.module_utils.postgres import ( |
| 164 |
connect_to_db, |
| 165 |
ensure_required_libs, |
| 166 |
get_conn_params, |
| 167 |
get_server_version, |
| 168 |
pg_cursor_args, |
| 169 |
postgres_common_argument_spec, |
| 170 |
) |
| 171 |
|
| 172 |
executed_queries = [] |
| 173 |
|
| 174 |
PG_SUPPORTED_VER = 140000 |
| 175 |
|
| 176 |
# It was copied here from postgresql_set. |
| 177 |
# GUC_LIST_QUOTE parameters list for each version where they changed (from PG_REQ_VER). |
| 178 |
# It is a tuple of tuples as we need to iterate it in order. |
| 179 |
PARAMETERS_GUC_LIST_QUOTE = ( |
| 180 |
(140000, ( |
| 181 |
'local_preload_libraries', |
| 182 |
'search_path', |
| 183 |
'session_preload_libraries', |
| 184 |
'shared_preload_libraries', |
| 185 |
'temp_tablespaces', |
| 186 |
'unix_socket_directories' |
| 187 |
)), |
| 188 |
(90400, ( |
| 189 |
'local_preload_libraries', |
| 190 |
'search_path', |
| 191 |
'session_preload_libraries', |
| 192 |
'shared_preload_libraries', |
| 193 |
'temp_tablespaces' |
| 194 |
)), |
| 195 |
) |
| 196 |
|
| 197 |
|
| 198 |
# It was copied here from postgresql_set. |
| 199 |
def param_is_guc_list_quote(server_version, name): |
| 200 |
for guc_list_quote_ver, guc_list_quote_params in PARAMETERS_GUC_LIST_QUOTE: |
| 201 |
if server_version >= guc_list_quote_ver: |
| 202 |
return name in guc_list_quote_params |
| 203 |
return False |
| 204 |
|
| 205 |
|
| 206 |
# It was copied here from postgresql_set. |
| 207 |
def param_guc_list_unquote(value): |
| 208 |
# Unquote GUC_LIST_QUOTE parameter (each element can be quoted or not) |
| 209 |
# Assume the parameter is GUC_LIST_QUOTE (check in param_is_guc_list_quote function) |
| 210 |
return ', '.join([v.strip('" ') for v in value.split(',')]) |
| 211 |
|
| 212 |
|
| 213 |
def check_pg_version(module, pg_ver): |
| 214 |
if pg_ver < PG_SUPPORTED_VER: |
| 215 |
msg = ("PostgreSQL version %s is supported, but %s is used. " |
| 216 |
"Before filing a bug report, please run your task " |
| 217 |
"on a supported version of PostgreSQL." % (PG_SUPPORTED_VER, pg_ver)) |
| 218 |
module.warn(msg) |
| 219 |
|
| 220 |
|
| 221 |
def check_problematic_params(module, param, value): |
| 222 |
# Due to a bug in PostgreSQL |
| 223 |
if param == 'shared_preload_libraries' and value == '': |
| 224 |
msg = ("Due to a PostgreSQL bug in resetting shared_preload_libraries " |
| 225 |
"with ALTER SYSTEM SET, setting it as an empty string " |
| 226 |
"is not supported by the module to avoid crashes. " |
| 227 |
"Use `value: _RESET` instead. " |
| 228 |
"If you think the bug has been fixed, please let us know.") |
| 229 |
module.fail_json(msg=msg) |
| 230 |
|
| 231 |
# Andersson007 originally used ABC, but it turned out that |
| 232 |
# Python 2.7 does not support it. As of 2025-03-27 it's still |
| 233 |
# supported by Ansible on target hosts until ~mid May, 2025, |
| 234 |
# so we, as a certified collection must support it as well. |
| 235 |
# TODO revisit this after May, 2025 to uncomment and use |
| 236 |
# as a parent class in all the Value* classes. |
| 237 |
# class Value(ABC): |
| 238 |
# This abstract class is a blueprint for "real" classes |
| 239 |
# that represent values of certain types. |
| 240 |
# This makes practical sense as we want the classes |
| 241 |
# have same set of parameters to instantiate them |
| 242 |
# in the same manner. |
| 243 |
# If you need to handle parameters of a new type |
| 244 |
# or if you need to handle some combination of vartype |
| 245 |
# and unit differently (like we do it with ValueMem or ValueTime), |
| 246 |
# create another class using this class as parent. |
| 247 |
|
| 248 |
# To understand why we use this, take a look at how |
| 249 |
# the child classes are instantiated in a similar manner |
| 250 |
# @abstractmethod |
| 251 |
# def __init__(self, module, param_name, value, default_unit, pg_ver): |
| 252 |
# pass |
| 253 |
|
| 254 |
|
| 255 |
class ValueBool(): |
| 256 |
"""Represents a parameter of type bool.""" |
| 257 |
# SELECT * FROM pg_catalog.pg_settings WHERE vartype = 'bool' |
| 258 |
|
| 259 |
def __init__(self, module, param_name, value, default_unit, pg_ver=None): |
| 260 |
# We do not use all the parameters in every class |
| 261 |
# like default_unit, etc., but we need them to instantiate |
| 262 |
# classes in a standard manner |
| 263 |
self.normalized = self.__normalize(value) |
| 264 |
|
| 265 |
def __normalize(self, value): |
| 266 |
return normalize_bool_val(value) |
| 267 |
|
| 268 |
|
| 269 |
class ValueInt(): |
| 270 |
"""Represents a parameter of type integer. |
| 271 |
Memory- and time-related parameters are handled by dedicated classes. |
| 272 |
""" |
| 273 |
# SELECT * FROM pg_catalog.pg_settings WHERE vartype = 'integer' and unit IS NULL |
| 274 |
|
| 275 |
def __init__(self, module, param_name, value, default_unit, pg_ver=None): |
| 276 |
# We do not use all the parameters in every class |
| 277 |
# like default_unit, etc., but we need them to instantiate |
| 278 |
# classes in a standard manner |
| 279 |
self.normalized = to_int(module, value) |
| 280 |
|
| 281 |
|
| 282 |
class ValueString(): |
| 283 |
"""Represents a parameter of type string.""" |
| 284 |
# SELECT * FROM pg_catalog.pg_settings WHERE vartype = 'string' |
| 285 |
|
| 286 |
def __init__(self, module, param_name, value, default_unit, pg_ver): |
| 287 |
# We do not use all the parameters in every class |
| 288 |
# like default_unit, etc., but we need them to instantiate |
| 289 |
# classes in a standard manner. |
| 290 |
|
| 291 |
# It typically doesn't need normalization, |
| 292 |
# so accept it as is |
| 293 |
self.normalized = self.__normalize(pg_ver, param_name, value) |
| 294 |
|
| 295 |
def __normalize(self, pg_ver, param_name, value): |
| 296 |
# Check parameter is GUC_LIST_QUOTE (done once as depend only on server version). |
| 297 |
# These functions were copied here from the postgresql_set module |
| 298 |
is_guc_list_quote = param_is_guc_list_quote(pg_ver, param_name) |
| 299 |
if is_guc_list_quote: |
| 300 |
return param_guc_list_unquote(value) |
| 301 |
|
| 302 |
return value |
| 303 |
|
| 304 |
|
| 305 |
class ValueEnum(): |
| 306 |
"""Represents a parameter of type enum.""" |
| 307 |
# SELECT * FROM pg_catalog.pg_settings WHERE vartype = 'enum' |
| 308 |
|
| 309 |
def __init__(self, module, param_name, value, default_unit, pg_ver=None): |
| 310 |
# We do not use all the parameters in every class |
| 311 |
# like default_unit, etc., but we need them to instantiate |
| 312 |
# classes in a standard manner. |
| 313 |
|
| 314 |
# It typically doesn't need normalization, |
| 315 |
# so accept it as is |
| 316 |
self.normalized = self.__normalize(value) |
| 317 |
|
| 318 |
def __normalize(self, value): |
| 319 |
return normalize_bool_val(value) |
| 320 |
|
| 321 |
|
| 322 |
def normalize_bool_val(value): |
| 323 |
# No idea why Ansible converts on/off passed as string |
| 324 |
# to "True" and "False". However, there are represented |
| 325 |
# as "on" and "off" in pg_catalog.pg_settings. |
| 326 |
if value == "True": |
| 327 |
return "on" |
| 328 |
elif value == "False": |
| 329 |
return "off" |
| 330 |
else: |
| 331 |
return value |
| 332 |
|
| 333 |
|
| 334 |
class ValueReal(): |
| 335 |
"""Represents a parameter of type real.""" |
| 336 |
# SELECT * FROM pg_catalog.pg_settings WHERE vartype = 'real' |
| 337 |
|
| 338 |
def __init__(self, module, param_name, value, default_unit, pg_ver=None): |
| 339 |
# We do not use all the parameters in every class |
| 340 |
# like default_unit, etc., but we need them to instantiate |
| 341 |
# classes in a standard manner |
| 342 |
self.module = module |
| 343 |
self.normalized = self.__normalize(value) |
| 344 |
|
| 345 |
def __normalize(self, value): |
| 346 |
# Drop the unit part as there's only "ms" or nothing |
| 347 |
if len(value) > 2 and value[-2:].isalpha(): |
| 348 |
value = value[:-2] |
| 349 |
|
| 350 |
return float(value) if str_contains_float(value) else to_int(self.module, value) |
| 351 |
|
| 352 |
|
| 353 |
class ValueTime(): |
| 354 |
"""Represents a time-related parameter.""" |
| 355 |
|
| 356 |
VALID_UNITS = {"us", "ms", "s", "min", "h", "d"} |
| 357 |
|
| 358 |
def __init__(self, module, param_name, value, default_unit, pg_ver=None): |
| 359 |
# We do not use all the parameters in every class |
| 360 |
# like default_unit, etc., but we need them to instantiate |
| 361 |
# classes in a standard manner |
| 362 |
self.module = module |
| 363 |
self.default_unit = default_unit |
| 364 |
self.num_value, self.passed_unit = self.__set(param_name, value) |
| 365 |
self.normalized = self.__normalize(self.num_value, self.passed_unit) |
| 366 |
|
| 367 |
def __normalize(self, num_value, passed_unit): |
| 368 |
value_in_microsecs = None |
| 369 |
# Let's convert num_value to the smallest unit, |
| 370 |
# i.e. to "us" which means microseconds |
| 371 |
if num_value == -1: |
| 372 |
# When disabled, some params have -1 as value |
| 373 |
value_in_microsecs = num_value |
| 374 |
elif passed_unit == "us": |
| 375 |
value_in_microsecs = num_value |
| 376 |
elif passed_unit == "ms": |
| 377 |
value_in_microsecs = num_value * 1000 |
| 378 |
elif passed_unit == "s": |
| 379 |
value_in_microsecs = num_value * 1000000 |
| 380 |
elif passed_unit == "min": |
| 381 |
value_in_microsecs = num_value * 60 * 1000000 |
| 382 |
elif passed_unit == "h": |
| 383 |
value_in_microsecs = num_value * 60 * 60 * 1000000 |
| 384 |
elif passed_unit == "d": |
| 385 |
value_in_microsecs = num_value * 24 * 60 * 60 * 1000000 |
| 386 |
|
| 387 |
return value_in_microsecs |
| 388 |
|
| 389 |
def __set(self, param_name, value): |
| 390 |
return self.__validate(param_name, value) |
| 391 |
|
| 392 |
def __validate(self, param_name, value): |
| 393 |
int_part = None |
| 394 |
unit_part = None |
| 395 |
|
| 396 |
# When the value is like 1min |
| 397 |
if len(value) > 3 and value[-3:].isalpha(): |
| 398 |
int_part = to_int(self.module, value[:-3]) |
| 399 |
unit_part = value[-3:] |
| 400 |
|
| 401 |
# When the value is like 1ms |
| 402 |
elif len(value) > 2 and value[-2:].isalpha(): |
| 403 |
int_part = to_int(self.module, value[:-2]) |
| 404 |
unit_part = value[-2:] |
| 405 |
|
| 406 |
# When the value is like 1s |
| 407 |
elif len(value) > 1 and value[-1].isalpha(): |
| 408 |
int_part = to_int(self.module, value[:-1]) |
| 409 |
unit_part = value[-1] |
| 410 |
|
| 411 |
# When it doesn't contain a unit part |
| 412 |
# we set it as the unit defined for this |
| 413 |
# parameter in pg_catalog.pg_settings |
| 414 |
else: |
| 415 |
int_part = to_int(self.module, value) |
| 416 |
unit_part = self.default_unit |
| 417 |
|
| 418 |
if unit_part not in ValueTime.VALID_UNITS: |
| 419 |
val_err_msg = ('invalid value for parameter "%s": "%s", ' |
| 420 |
'Valid units for this parameter ' |
| 421 |
'are %s' % (param_name, value, ', '.join(ValueTime.VALID_UNITS))) |
| 422 |
self.module.fail_json(msg=val_err_msg) |
| 423 |
|
| 424 |
return (int_part, unit_part) |
| 425 |
|
| 426 |
|
| 427 |
class ValueMem(): |
| 428 |
"""Represents a memory-related parameter.""" |
| 429 |
# If you pass anything else for memory-related param, |
| 430 |
# Postgres will show that only the following |
| 431 |
# units are acceptable |
| 432 |
VALID_UNITS = {"B", "kB", "MB", "GB", "TB"} |
| 433 |
|
| 434 |
# Bytes = MB << 20, etc. |
| 435 |
# This looks a bit better and maybe |
| 436 |
# even works more efficiently than |
| 437 |
# say Bytes = MB * 1024 * 1024 |
| 438 |
UNIT_TO_BYTES_BITWISE_SHIFT = { |
| 439 |
"B": 0, |
| 440 |
"kB": 10, |
| 441 |
"MB": 20, |
| 442 |
"GB": 30, |
| 443 |
"TB": 40, |
| 444 |
} |
| 445 |
|
| 446 |
def __init__(self, module, param_name, value, default_unit, pg_ver=None): |
| 447 |
self.module = module |
| 448 |
self.default_unit = default_unit |
| 449 |
self.num_value, self.passed_unit = self.__set(param_name, value) |
| 450 |
if self.passed_unit == "8kB": |
| 451 |
# This is a special case when the unit in pg_catalog.pg_settings is "8kB". |
| 452 |
# Users can still pass such values as "10MB", etc. |
| 453 |
# The only issue seems to appear when users don't specify values |
| 454 |
# of 8kB default value explicitly, i.e., when they pass just "100". |
| 455 |
# In this case the self.__validate method will assign its default unit of 8kB |
| 456 |
self.normalized = (self.num_value << ValueMem.UNIT_TO_BYTES_BITWISE_SHIFT["kB"]) * 8 |
| 457 |
else: |
| 458 |
self.normalized = self.num_value << ValueMem.UNIT_TO_BYTES_BITWISE_SHIFT[self.passed_unit] |
| 459 |
|
| 460 |
def __set(self, param_name, value): |
| 461 |
return self.__validate(param_name, value) |
| 462 |
|
| 463 |
def __validate(self, param_name, value): |
| 464 |
int_part = None |
| 465 |
unit_part = None |
| 466 |
|
| 467 |
# When the value is like 1024MB |
| 468 |
if len(value) > 2 and value[-2:].isalpha(): |
| 469 |
int_part = to_int(self.module, value[:-2]) |
| 470 |
unit_part = value[-2:] |
| 471 |
|
| 472 |
# When the value is like 1024B |
| 473 |
elif len(value) > 1 and value[-1].isalpha(): |
| 474 |
int_part = to_int(self.module, value[:-1]) |
| 475 |
unit_part = value[-1] |
| 476 |
|
| 477 |
# When it doesn't contain a unit part |
| 478 |
# we set it as the unit defined for this |
| 479 |
# parameter in pg_catalog.pg_settings |
| 480 |
else: |
| 481 |
int_part = to_int(self.module, value) |
| 482 |
unit_part = self.default_unit |
| 483 |
|
| 484 |
if unit_part not in ValueMem.VALID_UNITS and unit_part != "8kB": |
| 485 |
val_err_msg = ('invalid value for parameter "%s": "%s", ' |
| 486 |
'Valid units for this parameter ' |
| 487 |
'are %s' % (param_name, value, ', '.join(ValueMem.VALID_UNITS))) |
| 488 |
self.module.fail_json(msg=val_err_msg) |
| 489 |
|
| 490 |
return (int_part, unit_part) |
| 491 |
|
| 492 |
|
| 493 |
def to_int(module, value): |
| 494 |
"""Tries to convert the value to int and |
| 495 |
fail gracefully when no success. |
| 496 |
""" |
| 497 |
try: |
| 498 |
return int(value) |
| 499 |
except Exception: |
| 500 |
val_err_msg = "Value %s cannot be converted to int" % value |
| 501 |
module.fail_json(msg=val_err_msg) |
| 502 |
|
| 503 |
|
| 504 |
# Run "SELECT DISTINCT unit FROM pg_catalog.pg_settings;" |
| 505 |
# and extract memory-related ones |
| 506 |
MEM_PARAM_UNITS = {"B", "kB", "8kB", "MB"} |
| 507 |
|
| 508 |
|
| 509 |
# Run "SELECT DISTINCT unit FROM pg_catalog.pg_settings;" |
| 510 |
# and extract time-related ones |
| 511 |
TIME_PARAM_UNITS = {"min", "s", "ms"} |
| 512 |
|
| 513 |
|
| 514 |
def build_value_class(module, param_name, value, unit, vartype, pg_ver): |
| 515 |
""" Choose a proper Value class based on vartype and/or unit, |
| 516 |
instantiate it and return the object. |
| 517 |
""" |
| 518 |
if value == "-1": |
| 519 |
# In this case, it means that the setting is disabled |
| 520 |
# and we don't need to do any sophisticated normalization |
| 521 |
return ValueInt(module, param_name, value, unit) |
| 522 |
|
| 523 |
elif unit in TIME_PARAM_UNITS: |
| 524 |
# It can be of type integer or real, that's why |
| 525 |
# we don't have them under vartype == "integer" |
| 526 |
return ValueTime(module, param_name, value, unit) |
| 527 |
|
| 528 |
elif vartype == "integer": |
| 529 |
if unit in MEM_PARAM_UNITS: |
| 530 |
return ValueMem(module, param_name, value, unit) |
| 531 |
|
| 532 |
else: |
| 533 |
return ValueInt(module, param_name, value, unit) |
| 534 |
|
| 535 |
elif vartype == "bool": |
| 536 |
return ValueBool(module, param_name, value, unit) |
| 537 |
|
| 538 |
elif vartype == "real": |
| 539 |
return ValueReal(module, param_name, value, unit) |
| 540 |
|
| 541 |
elif vartype == "string": |
| 542 |
return ValueString(module, param_name, value, unit, pg_ver) |
| 543 |
|
| 544 |
elif vartype == "enum": |
| 545 |
return ValueEnum(module, param_name, value, unit) |
| 546 |
|
| 547 |
|
| 548 |
def str_contains_float(s): |
| 549 |
"""Check if the string s contains float.""" |
| 550 |
try: |
| 551 |
# Attempt to convert the string to a float |
| 552 |
num = float(s) |
| 553 |
|
| 554 |
# Check if the number is not an integer (has a decimal part) |
| 555 |
# We don't expect s to be anything but a string |
| 556 |
return '.' in s and num != int(num) |
| 557 |
|
| 558 |
except ValueError: |
| 559 |
# If it cannot be converted to a float, it's not a valid float |
| 560 |
return False |
| 561 |
|
| 562 |
|
| 563 |
def convert_ret_vals(attrs): |
| 564 |
"""Converts some ret values to numeric types.""" |
| 565 |
if attrs["vartype"] not in ("integer", "real"): |
| 566 |
return attrs |
| 567 |
|
| 568 |
# The issue here is that a value can look like |
| 569 |
# integer in one column, but like float in another, |
| 570 |
# so let's check them all separately |
| 571 |
for elem in ("setting", "boot_val", "min_val", "max_val"): |
| 572 |
if str_contains_float(attrs[elem]): |
| 573 |
attrs[elem] = float(attrs[elem]) |
| 574 |
else: |
| 575 |
try: |
| 576 |
attrs[elem] = int(attrs[elem]) |
| 577 |
except ValueError: |
| 578 |
# Leave the attrs[elem] as-is, i.e. a string |
| 579 |
# This can happen when max_value of type real |
| 580 |
# is huge and written in scientific notation |
| 581 |
# e.g., 1.79769e+308 (as of 2025-05-14, this is the only one) |
| 582 |
# and it doesn't make sense to convert it as it'll be really huge |
| 583 |
# https://github.com/ansible-collections/community.postgresql/issues/853 |
| 584 |
pass |
| 585 |
|
| 586 |
return attrs |
| 587 |
|
| 588 |
|
| 589 |
class PgParam(): |
| 590 |
"""Represents a postgresql parameter. |
| 591 |
|
| 592 |
Provides attributes and method for operating |
| 593 |
on a corresponding parameter in the database |
| 594 |
like setting or resetting its value. |
| 595 |
|
| 596 |
If you're interested in adding other operations, |
| 597 |
add them in this class as methods. |
| 598 |
|
| 599 |
To represent values of particular types we use |
| 600 |
corresponding classes. For example for booleans |
| 601 |
we use ValueBool and for strings ValueString. |
| 602 |
The build_value_class function returns a proper |
| 603 |
class object based on the vartype column value |
| 604 |
for a particular parameter. |
| 605 |
To get types, run in your PG client |
| 606 |
SELECT DISTINCT vartype FROM pg_catalog.pg_settings; |
| 607 |
|
| 608 |
We can't predict what our users pass, so we need |
| 609 |
some kind of normalization of the values that we |
| 610 |
do in the value classes (not for every kind of parameter). |
| 611 |
""" |
| 612 |
def __init__(self, module, cursor, name, pg_ver): |
| 613 |
self.module = module |
| 614 |
self.cursor = cursor |
| 615 |
self.name = name |
| 616 |
self.pg_ver = pg_ver |
| 617 |
|
| 618 |
self.attrs = self.get_attrs() |
| 619 |
# For some type of context it's impossible |
| 620 |
# to change settings with ALTER SYSTEM and |
| 621 |
# for some service restart is required |
| 622 |
self.__check_param_context(self.attrs["context"]) |
| 623 |
|
| 624 |
# Return a proper value class based on vartype and unit |
| 625 |
# from a pg_catalog.pg_settings entry for a specific parameter |
| 626 |
self.init_value = build_value_class(self.module, self.name, |
| 627 |
self.attrs["setting"], |
| 628 |
self.attrs["unit"], |
| 629 |
self.attrs["vartype"], |
| 630 |
self.pg_ver) |
| 631 |
# Same object will be instantiated to compare |
| 632 |
# the desired and the current values |
| 633 |
self.desired_value = None |
| 634 |
|
| 635 |
def set(self, value): |
| 636 |
self.desired_value = build_value_class(self.module, self.name, |
| 637 |
value, |
| 638 |
self.attrs["unit"], |
| 639 |
self.attrs["vartype"], |
| 640 |
self.pg_ver) |
| 641 |
|
| 642 |
# Compare normalized values of the desired and the current |
| 643 |
# values to decide whether we need to do any real job |
| 644 |
if self.desired_value.normalized != self.init_value.normalized: |
| 645 |
query = self.__construct_alter_system_query(value) |
| 646 |
self.__exec_set_sql(query) |
| 647 |
return True |
| 648 |
|
| 649 |
return False |
| 650 |
|
| 651 |
def reset(self): |
| 652 |
# As the value is "_RESET", i.e. a string, and |
| 653 |
# the module always return changed=true, we just instantiate |
| 654 |
# the desired value as if it would be a value of string type |
| 655 |
self.desired_value = ValueString(self.module, self.name, |
| 656 |
"_RESET", |
| 657 |
self.attrs["unit"], |
| 658 |
self.pg_ver) |
| 659 |
# Because the result of running "ALTER SYSTEM RESET param;" |
| 660 |
# is always a removal of the line from postgresql.auto.conf |
| 661 |
# this will always run the command to ensure the removal |
| 662 |
# and report changed=true |
| 663 |
query = "ALTER SYSTEM RESET %s" % self.name |
| 664 |
self.__exec_set_sql(query) |
| 665 |
return True |
| 666 |
|
| 667 |
def get_attrs(self): |
| 668 |
query = ("SELECT setting, unit, context, vartype, enumvals, " |
| 669 |
"boot_val, min_val, max_val, pending_restart " |
| 670 |
"FROM pg_catalog.pg_settings where name = %s") |
| 671 |
res = self.__exec_sql(query, (self.name,)) |
| 672 |
# You can uncomment the line below while debugging |
| 673 |
# to see what DB actually returns for the parameter |
| 674 |
# executed_queries.append(res[0]) |
| 675 |
if not res: |
| 676 |
self.module.fail_json(msg="Parameter %s does not exist" % self.name) |
| 677 |
|
| 678 |
return res[0] |
| 679 |
|
| 680 |
def __construct_alter_system_query(self, value): |
| 681 |
if isinstance(value, str) and ',' in value and \ |
| 682 |
not self.name.endswith(('_command', '_prefix')) and \ |
| 683 |
not (self.pg_ver < 140000 and self.name == 'unix_socket_directories'): |
| 684 |
# Issue https://github.com/ansible-collections/community.postgresql/issues/78 |
| 685 |
# Change value from 'one, two, three' -> "'one','two','three'" |
| 686 |
# PR https://github.com/ansible-collections/community.postgresql/pull/400 |
| 687 |
# Parameter names ends with '_command' or '_prefix' |
| 688 |
# can contains commas but they are not lists |
| 689 |
# PR https://github.com/ansible-collections/community.postgresql/pull/521 |
| 690 |
# unix_socket_directories up to PostgreSQL 13 lacks GUC_LIST_INPUT and |
| 691 |
# GUC_LIST_QUOTE options so it is a single value parameter |
| 692 |
tmp = [] |
| 693 |
for elem in value.split(','): |
| 694 |
if elem.strip()[0] == '"': |
| 695 |
# In case like search_path value "$user" |
| 696 |
# just append it w/o any modifications |
| 697 |
tmp.append(elem.strip()) |
| 698 |
else: |
| 699 |
tmp.append("'" + elem.strip() + "'") |
| 700 |
|
| 701 |
query = "ALTER SYSTEM SET %s = %s" % (self.name, ','.join(tmp)) |
| 702 |
|
| 703 |
elif self.pg_ver >= 140000: |
| 704 |
query = "ALTER SYSTEM SET %s = '%s'" % (self.name, value) |
| 705 |
|
| 706 |
else: |
| 707 |
query = "ALTER SYSTEM SET %s = %s" % (self.name, value) |
| 708 |
|
| 709 |
return query |
| 710 |
|
| 711 |
def __check_param_context(self, context): |
| 712 |
if context == "internal": |
| 713 |
msg = ("%s cannot be changed (internal context). " |
| 714 |
"See https://www.postgresql.org/docs/current/" |
| 715 |
"runtime-config-preset.html" % self.name) |
| 716 |
self.module.fail_json(msg=msg) |
| 717 |
|
| 718 |
def __exec_sql(self, query, params=()): |
| 719 |
"""Execute a query that is supposed to return something.""" |
| 720 |
try: |
| 721 |
self.cursor.execute(query, params) |
| 722 |
res = self.cursor.fetchall() |
| 723 |
if res: |
| 724 |
return res |
| 725 |
except Exception as e: |
| 726 |
msg = "Cannot execute SQL '%s': %s" % (query, to_native(e)) |
| 727 |
self.module.fail_json(msg=msg) |
| 728 |
self.cursor.close() |
| 729 |
return None |
| 730 |
|
| 731 |
def __exec_set_sql(self, query): |
| 732 |
"""Execute ALTER SYSTEM kind of queries.""" |
| 733 |
try: |
| 734 |
executed_queries.append(query) |
| 735 |
if not self.module.check_mode: |
| 736 |
self.cursor.execute(query) |
| 737 |
except Exception as e: |
| 738 |
self.module.fail_json(msg="Cannot set %s: %s" % (self.name, to_native(e))) |
| 739 |
|
| 740 |
try: |
| 741 |
query = "SELECT pg_reload_conf()" |
| 742 |
executed_queries.append(query) |
| 743 |
if not self.module.check_mode: |
| 744 |
self.cursor.execute(query) |
| 745 |
except Exception as e: |
| 746 |
self.module.fail_json(msg="Cannot run 'SELECT pg_reload_conf()': %s" % to_native(e)) |
| 747 |
|
| 748 |
|
| 749 |
def build_ret_attrs(param_attrs): |
| 750 |
"""Extracts and returns immutable attributes |
| 751 |
that we return to users as the attrs return value. |
| 752 |
""" |
| 753 |
return { |
| 754 |
"context": param_attrs["context"], |
| 755 |
"boot_val": param_attrs["boot_val"], |
| 756 |
"enumvals": param_attrs["enumvals"], |
| 757 |
"unit": param_attrs["unit"], |
| 758 |
"vartype": param_attrs["vartype"], |
| 759 |
"min_val": param_attrs["min_val"], |
| 760 |
"max_val": param_attrs["max_val"], |
| 761 |
} |
| 762 |
|
| 763 |
|
| 764 |
def build_ret_diff(param_attrs_before, param_attrs_after): |
| 765 |
"""Extracts and returns mutable attributes |
| 766 |
that we return to users as the diff return value. |
| 767 |
""" |
| 768 |
return { |
| 769 |
"before": { |
| 770 |
"setting": param_attrs_before["setting"], |
| 771 |
"pending_restart": param_attrs_before["pending_restart"], |
| 772 |
}, |
| 773 |
"after": { |
| 774 |
"setting": param_attrs_after["setting"], |
| 775 |
"pending_restart": param_attrs_after["pending_restart"], |
| 776 |
} |
| 777 |
} |
| 778 |
|
| 779 |
# =========================================== |
| 780 |
# Module execution. |
| 781 |
# |
| 782 |
|
| 783 |
|
| 784 |
def main(): |
| 785 |
argument_spec = postgres_common_argument_spec() |
| 786 |
argument_spec.update( |
| 787 |
param=dict(type='str', required=True), |
| 788 |
login_db=dict(type='str'), |
| 789 |
value=dict(type='str', required=True), |
| 790 |
session_role=dict(type='str'), |
| 791 |
trust_input=dict(type='bool', default=True), |
| 792 |
) |
| 793 |
module = AnsibleModule( |
| 794 |
argument_spec=argument_spec, |
| 795 |
supports_check_mode=True, |
| 796 |
) |
| 797 |
|
| 798 |
param = module.params['param'] |
| 799 |
value = module.params['value'] |
| 800 |
session_role = module.params['session_role'] |
| 801 |
trust_input = module.params['trust_input'] |
| 802 |
|
| 803 |
# There's at least one param that doesn't |
| 804 |
# work well with ALTER SYSTEM SET. |
| 805 |
# Add more to this function if you see any |
| 806 |
check_problematic_params(module, param, value) |
| 807 |
|
| 808 |
if not trust_input: |
| 809 |
# Check input for potentially dangerous elements |
| 810 |
check_input(module, param, value, session_role) |
| 811 |
|
| 812 |
# Ensure psycopg libraries are available before connecting to DB |
| 813 |
ensure_required_libs(module) |
| 814 |
conn_params = get_conn_params(module, module.params, warn_db_default=False) |
| 815 |
db_connection, dummy = connect_to_db(module, conn_params, autocommit=True) |
| 816 |
cursor = db_connection.cursor(**pg_cursor_args) |
| 817 |
|
| 818 |
# Get and check server version |
| 819 |
pg_ver = get_server_version(db_connection) |
| 820 |
check_pg_version(module, pg_ver) |
| 821 |
|
| 822 |
# We assume nothing has changed by default |
| 823 |
changed = False |
| 824 |
|
| 825 |
# Instantiate the object |
| 826 |
pg_param = PgParam(module, cursor, param, pg_ver) |
| 827 |
|
| 828 |
# When we need to reset the value by running |
| 829 |
# "ALTER SYSTEM RESET param;". |
| 830 |
# setting up a regular value first |
| 831 |
if value == "_RESET": |
| 832 |
changed = pg_param.reset() |
| 833 |
|
| 834 |
# This is the default case when we need to run |
| 835 |
# "ALTER SYSTEM SET param = 'value';", |
| 836 |
# i.e., it's not the above cases |
| 837 |
else: |
| 838 |
changed = pg_param.set(value) |
| 839 |
|
| 840 |
# Fetch info again to get diff. |
| 841 |
# It doesn't see the changes w/o reconnect |
| 842 |
cursor.close() |
| 843 |
db_connection.close() |
| 844 |
db_connection, dummy = connect_to_db(module, conn_params, autocommit=True) |
| 845 |
cursor = db_connection.cursor(**pg_cursor_args) |
| 846 |
# Instantiate another object to get the latest attrs |
| 847 |
pg_param_after = PgParam(module, cursor, param, pg_ver) |
| 848 |
|
| 849 |
# Make sure if there any difference between |
| 850 |
# the attrs in the diff, report changed |
| 851 |
changed = pg_param.attrs != pg_param_after.attrs or changed |
| 852 |
|
| 853 |
# Disconnect |
| 854 |
cursor.close() |
| 855 |
db_connection.close() |
| 856 |
|
| 857 |
# Convert ret values, then populate attrs and diff |
| 858 |
pg_param.attrs = convert_ret_vals(pg_param.attrs) |
| 859 |
pg_param_after.attrs = convert_ret_vals(pg_param_after.attrs) |
| 860 |
# Attributes are immutable (in the context of this module at least), |
| 861 |
# so we put them separately, not as a part of diff |
| 862 |
immut_attrs = build_ret_attrs(pg_param.attrs) |
| 863 |
diff = build_ret_diff(pg_param.attrs, pg_param_after.attrs) |
| 864 |
|
| 865 |
module.exit_json( |
| 866 |
attrs=immut_attrs, |
| 867 |
changed=changed, |
| 868 |
executed_queries=executed_queries, |
| 869 |
diff=diff, |
| 870 |
restart_required=diff["after"]["pending_restart"], |
| 871 |
# FOR DEBUGGING you can return the information below if needed. |
| 872 |
# If yes, create an empty dict called debug first |
| 873 |
# debug["value_class_value"]=pg_param.init_value.num_value, |
| 874 |
# debug["value_class_unit"]=pg_param.init_value.passed_unit, |
| 875 |
# debug["value_class_normalized"]=pg_param.init_value.normalized, |
| 876 |
# debug["desir_class_value"]=pg_param.desired_value.num_value, |
| 877 |
# debug["desir_class_unit"]=pg_param.desired_value.passed_unit, |
| 878 |
# debug["desir_class_normalized"]=pg_param.desired_value.normalized, |
| 879 |
) |
| 880 |
|
| 881 |
|
| 882 |
if __name__ == '__main__': |
| 883 |
main() |