Debian Codegraph @

ansible_collections/community/postgresql/plugins/modules/postgresql_tablespace.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2017, Flavien Chantelot (@Dorn-)
5 # Copyright: (c) 2018, Antoine Levy-Lambert (@antoinell)
6 # Copyright: (c) 2019, Andrew Klychkov (@Andersson007) <[email protected]>
7 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
8
9 from __future__ import absolute_import, division, print_function
10
11 __metaclass__ = type
12
13 DOCUMENTATION = r'''
14 ---
15 module: postgresql_tablespace
16 short_description: Add or remove PostgreSQL tablespaces from remote hosts
17 description:
18 - Adds or removes PostgreSQL tablespaces from remote hosts.
19 options:
20 tablespace:
21 description:
22 - Name of the tablespace to add or remove.
23 required: true
24 type: str
25 aliases:
26 - name
27 location:
28 description:
29 - Path to the tablespace directory in the file system.
30 - Ensure that the location exists and has right privileges.
31 type: path
32 aliases:
33 - path
34 state:
35 description:
36 - Tablespace state.
37 - I(state=present) implies the tablespace must be created if it doesn't exist.
38 - I(state=absent) implies the tablespace must be removed if present.
39 I(state=absent) is mutually exclusive with I(location), I(owner), i(set).
40 - See the Notes section for information about check mode restrictions.
41 type: str
42 default: present
43 choices: [ absent, present ]
44 owner:
45 description:
46 - Name of the role to set as an owner of the tablespace.
47 - If this option is not specified, the tablespace owner is a role that creates the tablespace.
48 type: str
49 set:
50 description:
51 - Dict of tablespace options to set. Supported from PostgreSQL 9.0.
52 - For more information see U(https://www.postgresql.org/docs/current/sql-createtablespace.html).
53 - When reset is passed as an option's value, if the option was set previously, it will be removed.
54 type: dict
55 rename_to:
56 description:
57 - DEPRECATED (see the L(discussion,https://github.com/ansible-collections/community.postgresql/issues/820)).
58 This option will be removed in version 5.0.0.
59 To rename a tablespace, use the M(community.postgresql.postgresql_query) module.
60 - New name of the tablespace.
61 - The new name cannot begin with pg_, as such names are reserved for system tablespaces.
62 type: str
63 session_role:
64 description:
65 - Switch to session_role after connecting. The specified session_role must
66 be a role that the current login_user is a member of.
67 - Permissions checking for SQL commands is carried out as though
68 the session_role were the one that had logged in originally.
69 type: str
70 login_db:
71 description:
72 - Name of database to connect to and run queries against.
73 - The V(db) alias is deprecated and will be removed in version 5.0.0.
74 type: str
75 aliases:
76 - db
77 trust_input:
78 description:
79 - If C(false), check whether values of parameters I(tablespace), I(location), I(owner),
80 I(rename_to), I(session_role), I(settings_list) are potentially dangerous.
81 - It makes sense to use C(false) only when SQL injections via the parameters are possible.
82 type: bool
83 default: true
84 version_added: '0.2.0'
85 comment:
86 description:
87 - Sets a comment on the tablespace.
88 - To reset the comment, pass an empty string.
89 type: str
90 version_added: '3.3.0'
91
92 attributes:
93 check_mode:
94 support: partial
95 details:
96 - I(state=absent) and I(state=present) (the second one if the tablespace doesn't exist) do not
97 support check mode because the corresponding PostgreSQL DROP and CREATE TABLESPACE commands
98 can not be run inside the transaction block.
99
100 seealso:
101 - name: PostgreSQL tablespaces
102 description: General information about PostgreSQL tablespaces.
103 link: https://www.postgresql.org/docs/current/manage-ag-tablespaces.html
104 - name: CREATE TABLESPACE reference
105 description: Complete reference of the CREATE TABLESPACE command documentation.
106 link: https://www.postgresql.org/docs/current/sql-createtablespace.html
107 - name: ALTER TABLESPACE reference
108 description: Complete reference of the ALTER TABLESPACE command documentation.
109 link: https://www.postgresql.org/docs/current/sql-altertablespace.html
110 - name: DROP TABLESPACE reference
111 description: Complete reference of the DROP TABLESPACE command documentation.
112 link: https://www.postgresql.org/docs/current/sql-droptablespace.html
113
114 author:
115 - Flavien Chantelot (@Dorn-)
116 - Antoine Levy-Lambert (@antoinell)
117 - Andrew Klychkov (@Andersson007)
118 - Daniele Giudice (@RealGreenDragon)
119
120 extends_documentation_fragment:
121 - community.postgresql.postgres
122 '''
123
124 EXAMPLES = r'''
125 - name: Create a new tablespace called acme and set bob as an its owner
126 community.postgresql.postgresql_tablespace:
127 name: acme
128 owner: bob
129 location: /data/foo
130 comment: "Bob's tablespace"
131
132 - name: Create a new tablespace called bar with tablespace options
133 community.postgresql.postgresql_tablespace:
134 name: bar
135 set:
136 random_page_cost: 1
137 seq_page_cost: 1
138
139 - name: Reset random_page_cost option
140 community.postgresql.postgresql_tablespace:
141 name: bar
142 set:
143 random_page_cost: reset
144
145 - name: Drop tablespace called bloat
146 community.postgresql.postgresql_tablespace:
147 name: bloat
148 state: absent
149 '''
150
151 RETURN = r'''
152 queries:
153 description: List of queries that was tried to be executed.
154 returned: success
155 type: str
156 sample: [ "CREATE TABLESPACE bar LOCATION '/incredible/ssd'" ]
157 tablespace:
158 description: Tablespace name.
159 returned: success
160 type: str
161 sample: 'ssd'
162 owner:
163 description: Tablespace owner.
164 returned: success
165 type: str
166 sample: 'Bob'
167 comment:
168 description: Tablespace comment.
169 returned: success
170 type: str
171 sample: 'Test tablespace'
172 options:
173 description: Tablespace options.
174 returned: success
175 type: dict
176 sample: { 'random_page_cost': 1, 'seq_page_cost': 1 }
177 location:
178 description: Path to the tablespace in the file system.
179 returned: success
180 type: str
181 sample: '/incredible/fast/ssd'
182 newname:
183 description: New tablespace name.
184 returned: if existent
185 type: str
186 sample: new_ssd
187 state:
188 description: Tablespace state at the end of execution.
189 returned: success
190 type: str
191 sample: 'present'
192 '''
193
194 from ansible.module_utils.basic import AnsibleModule
195 from ansible_collections.community.postgresql.plugins.module_utils.database import \
196 check_input
197 from ansible_collections.community.postgresql.plugins.module_utils.postgres import (
198 connect_to_db,
199 ensure_required_libs,
200 exec_sql,
201 get_conn_params,
202 pg_cursor_args,
203 postgres_common_argument_spec,
204 set_autocommit,
205 set_comment,
206 )
207
208
209 class PgTablespace(object):
210
211 """Class for working with PostgreSQL tablespaces.
212
213 Args:
214 module (AnsibleModule) -- object of AnsibleModule class
215 cursor (cursor) -- cursor object of psycopg library
216 name (str) -- name of the tablespace
217
218 Attrs:
219 module (AnsibleModule) -- object of AnsibleModule class
220 cursor (cursor) -- cursor object of psycopg library
221 name (str) -- name of the tablespace
222 exists (bool) -- flag the tablespace exists in the DB or not
223 owner (str) -- tablespace owner
224 location (str) -- path to the tablespace directory in the file system
225 executed_queries (list) -- list of executed queries
226 new_name (str) -- new name for the tablespace
227 opt_not_supported (bool) -- flag indicates a tablespace option is supported or not
228 """
229
230 def __init__(self, module, cursor, name):
231 self.module = module
232 self.cursor = cursor
233 self.name = name
234 self.exists = False
235 self.owner = ''
236 self.settings = {}
237 self.location = ''
238 self.executed_queries = []
239 self.new_name = ''
240 self.opt_not_supported = False
241 self.comment = None
242 # Collect info:
243 self.get_info()
244
245 def get_info(self):
246 """Get tablespace information."""
247 # Check that spcoptions exists:
248 opt = exec_sql(self, "SELECT 1 FROM information_schema.columns "
249 "WHERE table_name = 'pg_tablespace' "
250 "AND column_name = 'spcoptions'", add_to_executed=False)
251
252 # For 9.1 version and earlier:
253 location = exec_sql(self, "SELECT 1 FROM information_schema.columns "
254 "WHERE table_name = 'pg_tablespace' "
255 "AND column_name = 'spclocation'", add_to_executed=False)
256 if location:
257 location = 'spclocation'
258 else:
259 location = 'pg_tablespace_location(t.oid)'
260
261 if not opt:
262 self.opt_not_supported = True
263 query = ("SELECT shobj_description(t.oid, 'pg_tablespace') AS comment, "
264 "r.rolname, (SELECT Null) spcoptions, %s loc_string "
265 "FROM pg_catalog.pg_tablespace AS t "
266 "JOIN pg_catalog.pg_roles AS r "
267 "ON t.spcowner = r.oid " % location)
268 else:
269 query = ("SELECT shobj_description(t.oid, 'pg_tablespace') AS comment, "
270 "r.rolname, t.spcoptions, %s loc_string "
271 "FROM pg_catalog.pg_tablespace AS t "
272 "JOIN pg_catalog.pg_roles AS r "
273 "ON t.spcowner = r.oid " % location)
274
275 res = exec_sql(self, query + "WHERE t.spcname = %(name)s",
276 query_params={'name': self.name}, add_to_executed=False)
277
278 if not res:
279 self.exists = False
280 return False
281
282 if res[0]["rolname"]:
283 self.exists = True
284 self.owner = res[0]["rolname"]
285
286 if res[0]["spcoptions"]:
287 # Options exist:
288 for i in res[0]["spcoptions"]:
289 i = i.split('=')
290 self.settings[i[0]] = i[1]
291
292 if res[0]["loc_string"]:
293 # Location exists:
294 self.location = res[0]["loc_string"]
295
296 self.comment = res[0]["comment"] if res[0]["comment"] is not None else ''
297
298 def create(self, location):
299 """Create tablespace.
300
301 Return True if success, otherwise, return False.
302
303 args:
304 location (str) -- tablespace directory path in the FS
305 """
306 query = ('CREATE TABLESPACE "%s" LOCATION \'%s\'' % (self.name, location))
307 return exec_sql(self, query, return_bool=True)
308
309 def drop(self):
310 """Drop tablespace.
311
312 Return True if success, otherwise, return False.
313 """
314 return exec_sql(self, 'DROP TABLESPACE "%s"' % self.name, return_bool=True)
315
316 def set_owner(self, new_owner):
317 """Set tablespace owner.
318
319 Return True if success, otherwise, return False.
320
321 args:
322 new_owner (str) -- name of a new owner for the tablespace"
323 """
324 if new_owner == self.owner:
325 return False
326
327 query = 'ALTER TABLESPACE "%s" OWNER TO "%s"' % (self.name, new_owner)
328 return exec_sql(self, query, return_bool=True)
329
330 def set_comment(self, comment, check_mode):
331 """Set tablespace comment.
332
333 Return True if success, otherwise, return False.
334
335 args:
336 comment (str) -- comment to set for the tablespace"
337 """
338 if comment == self.comment:
339 return False
340
341 return set_comment(self.cursor, comment, 'tablespace', self.name,
342 check_mode, self.executed_queries)
343
344 def rename(self, newname):
345 """Rename tablespace.
346
347 Return True if success, otherwise, return False.
348
349 args:
350 newname (str) -- new name for the tablespace"
351 """
352 query = 'ALTER TABLESPACE "%s" RENAME TO "%s"' % (self.name, newname)
353 self.new_name = newname
354 return exec_sql(self, query, return_bool=True)
355
356 def set_settings(self, new_settings):
357 """Set tablespace settings (options).
358
359 If some setting has been changed, set changed = True.
360 After all settings list is handling, return changed.
361
362 args:
363 new_settings (list) -- list of new settings
364 """
365 # settings must be a dict {'key': 'value'}
366 if self.opt_not_supported:
367 return False
368
369 changed = False
370
371 # Apply new settings:
372 for i in new_settings:
373 if new_settings[i] == 'reset':
374 if i in self.settings:
375 changed = self.__reset_setting(i)
376 self.settings[i] = None
377
378 elif (i not in self.settings) or (str(new_settings[i]) != self.settings[i]):
379 changed = self.__set_setting("%s = '%s'" % (i, new_settings[i]))
380
381 return changed
382
383 def __reset_setting(self, setting):
384 """Reset tablespace setting.
385
386 Return True if success, otherwise, return False.
387
388 args:
389 setting (str) -- string in format "setting_name = 'setting_value'"
390 """
391 query = 'ALTER TABLESPACE "%s" RESET (%s)' % (self.name, setting)
392 return exec_sql(self, query, return_bool=True)
393
394 def __set_setting(self, setting):
395 """Set tablespace setting.
396
397 Return True if success, otherwise, return False.
398
399 args:
400 setting (str) -- string in format "setting_name = 'setting_value'"
401 """
402 query = 'ALTER TABLESPACE "%s" SET (%s)' % (self.name, setting)
403 return exec_sql(self, query, return_bool=True)
404
405
406 # ===========================================
407 # Module execution.
408 #
409
410
411 def main():
412 argument_spec = postgres_common_argument_spec()
413 argument_spec.update(
414 tablespace=dict(type='str', required=True, aliases=['name']),
415 state=dict(type='str', default="present", choices=["absent", "present"]),
416 location=dict(type='path', aliases=['path']),
417 owner=dict(type='str'),
418 set=dict(type='dict'),
419 login_db=dict(type='str', aliases=['db'], deprecated_aliases=[
420 {
421 'name': 'db',
422 'version': '5.0.0',
423 'collection_name': 'community.postgresql',
424 }],
425 ),
426 rename_to=dict(type='str', removed_in_version='5.0.0',
427 removed_from_collection='community.postgresql'),
428 session_role=dict(type='str'),
429 trust_input=dict(type='bool', default=True),
430 comment=dict(type='str', default=None),
431 )
432
433 module = AnsibleModule(
434 argument_spec=argument_spec,
435 supports_check_mode=True,
436 )
437
438 tablespace = module.params["tablespace"]
439 state = module.params["state"]
440 location = module.params["location"]
441 owner = module.params["owner"]
442 rename_to = module.params["rename_to"]
443 settings = module.params["set"]
444 session_role = module.params["session_role"]
445 trust_input = module.params["trust_input"]
446 comment = module.params["comment"]
447
448 if state == 'absent' and (location or owner or rename_to or settings):
449 module.fail_json(msg="state=absent is mutually exclusive location, "
450 "owner, rename_to, and set")
451
452 if not trust_input:
453 # Check input for potentially dangerous elements:
454 if not settings:
455 settings_list = None
456 else:
457 settings_list = ['%s = %s' % (k, v) for k, v in settings.items()]
458
459 check_input(module, tablespace, location, owner,
460 rename_to, session_role, settings_list, comment)
461
462 # Ensure psycopg libraries are available before connecting to DB:
463 ensure_required_libs(module)
464 conn_params = get_conn_params(module, module.params, warn_db_default=False)
465 db_connection, dummy = connect_to_db(module, conn_params, autocommit=False if module.check_mode else True)
466 cursor = db_connection.cursor(**pg_cursor_args)
467
468 # Set defaults:
469 autocommit = False
470 changed = False
471
472 ##############
473 # Create PgTablespace object and do main job:
474 tblspace = PgTablespace(module, cursor, tablespace)
475
476 # If tablespace exists with different location, exit:
477 if tblspace.exists and location and location != tblspace.location:
478 module.fail_json(msg="Tablespace '%s' exists with "
479 "different location '%s'" % (tblspace.name, tblspace.location))
480
481 # Create new tablespace:
482 if not tblspace.exists and state == 'present':
483 if rename_to:
484 module.fail_json(msg="Tablespace %s does not exist, nothing to rename" % tablespace)
485
486 if not location:
487 module.fail_json(msg="'location' parameter must be passed with "
488 "state=present if the tablespace doesn't exist")
489
490 # Because CREATE TABLESPACE can not be run inside the transaction block:
491 autocommit = True
492 set_autocommit(db_connection, True)
493
494 changed = tblspace.create(location)
495
496 # Drop existing tablespace:
497 elif tblspace.exists and state == 'absent':
498 # Because DROP TABLESPACE can not be run inside the transaction block:
499 autocommit = True
500 set_autocommit(db_connection, True)
501
502 changed = tblspace.drop()
503
504 # Rename tablespace:
505 elif tblspace.exists and rename_to:
506 if tblspace.name != rename_to:
507 changed = tblspace.rename(rename_to)
508
509 if state == 'present':
510 # Refresh information:
511 tblspace.get_info()
512
513 # Change owner, comment and settings:
514 if state == 'present' and tblspace.exists:
515 if owner:
516 changed = tblspace.set_owner(owner) or changed
517
518 if settings:
519 changed = tblspace.set_settings(settings) or changed
520
521 if comment is not None:
522 changed = tblspace.set_comment(comment, module.check_mode) or changed
523
524 # Update tablespace information in the class
525 tblspace.get_info()
526
527 # Rollback if it's possible and check_mode:
528 if not autocommit:
529 if module.check_mode:
530 db_connection.rollback()
531 else:
532 db_connection.commit()
533
534 cursor.close()
535 db_connection.close()
536
537 # Make return values:
538 kw = dict(
539 changed=changed,
540 state='present',
541 tablespace=tblspace.name,
542 owner=tblspace.owner,
543 queries=tblspace.executed_queries,
544 options=tblspace.settings,
545 location=tblspace.location,
546 comment=tblspace.comment,
547 )
548
549 if state == 'present':
550 kw['state'] = 'present'
551
552 if tblspace.new_name:
553 kw['newname'] = tblspace.new_name
554
555 elif state == 'absent':
556 kw['state'] = 'absent'
557
558 module.exit_json(**kw)
559
560
561 if __name__ == '__main__':
562 main()