Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018-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_ping
14 short_description: Check remote PostgreSQL server availability
15 description:
16 - Simple module to check remote PostgreSQL server availability.
17 options:
18 login_db:
19 description:
20 - Name of a database to connect to.
21 - The V(db) alias is deprecated and will be removed in version 5.0.0.
22 type: str
23 aliases:
24 - db
25 session_role:
26 description:
27 - Switch to session_role after connecting. The specified session_role must
28 be a role that the current login_user is a member of.
29 - Permissions checking for SQL commands is carried out as though
30 the session_role were the one that had logged in originally.
31 type: str
32 version_added: '0.2.0'
33 trust_input:
34 description:
35 - If C(false), check whether a value of I(session_role) is potentially dangerous.
36 - It makes sense to use C(false) only when SQL injections via I(session_role) are possible.
37 type: bool
38 default: true
39 version_added: '0.2.0'
40 seealso:
41 - module: community.postgresql.postgresql_info
42 attributes:
43 check_mode:
44 support: full
45 author:
46 - Andrew Klychkov (@Andersson007)
47 extends_documentation_fragment:
48 - community.postgresql.postgres
49 '''
50
51 EXAMPLES = r'''
52 # PostgreSQL ping dbsrv server from the shell:
53 # ansible dbsrv -m postgresql_ping
54
55 # In the example below you need to generate certificates previously.
56 # See https://www.postgresql.org/docs/current/libpq-ssl.html for more information.
57 - name: >
58 Ping PostgreSQL server using non-default credentials and SSL
59 registering the return values into the result variable for future use
60 community.postgresql.postgresql_ping:
61 login_db: protected_db
62 login_host: dbsrv
63 login_user: secret
64 login_password: secret_pass
65 ca_cert: /root/root.crt
66 ssl_mode: verify-full
67 register: result
68 # If you need to fail when the server is not available,
69 # uncomment the following line:
70 # failed_when: not result.is_available
71
72 # You can use the registered result with another task
73 - name: This task should be executed only if the server is available
74 # ...
75 when: result.is_available == true
76 '''
77
78 RETURN = r'''
79 is_available:
80 description: PostgreSQL server availability.
81 returned: success
82 type: bool
83 sample: true
84 server_version:
85 description: PostgreSQL server version.
86 returned: success
87 type: dict
88 sample: { major: 13, minor: 2, full: '13.2', raw: 'PostgreSQL 13.2 on x86_64-pc-linux-gnu' }
89 conn_err_msg:
90 description: Connection error message.
91 returned: success
92 type: str
93 sample: ''
94 version_added: 1.7.0
95 '''
96
97 import re
98
99 from ansible.module_utils.basic import AnsibleModule
100 from ansible_collections.community.postgresql.plugins.module_utils.database import \
101 check_input
102 from ansible_collections.community.postgresql.plugins.module_utils.postgres import (
103 connect_to_db,
104 ensure_required_libs,
105 exec_sql,
106 get_conn_params,
107 pg_cursor_args,
108 postgres_common_argument_spec,
109 )
110
111 # ===========================================
112 # PostgreSQL module specific support methods.
113 #
114
115
116 class PgPing(object):
117 def __init__(self, module, cursor):
118 self.module = module
119 self.cursor = cursor
120 self.is_available = False
121 self.version = {}
122
123 def do(self):
124 self.get_pg_version()
125 return (self.is_available, self.version)
126
127 def get_pg_version(self):
128 query = "SELECT version()"
129 raw = exec_sql(self, query, add_to_executed=False)[0]["version"]
130
131 if not raw:
132 return
133
134 self.is_available = True
135
136 full = raw.split()[1]
137 m = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", full)
138
139 major = int(m.group(1))
140 minor = int(m.group(2))
141 patch = None
142 if m.group(3) is not None:
143 patch = int(m.group(3))
144
145 self.version = dict(
146 major=major,
147 minor=minor,
148 full=full,
149 raw=raw,
150 )
151
152 if patch is not None:
153 self.version['patch'] = patch
154
155
156 # ===========================================
157 # Module execution.
158 #
159
160
161 def main():
162 argument_spec = postgres_common_argument_spec()
163 argument_spec.update(
164 login_db=dict(type='str', aliases=['db'], deprecated_aliases=[
165 {
166 'name': 'db',
167 'version': '5.0.0',
168 'collection_name': 'community.postgresql',
169 }],
170 ),
171 session_role=dict(type='str'),
172 trust_input=dict(type='bool', default=True),
173 )
174 module = AnsibleModule(
175 argument_spec=argument_spec,
176 supports_check_mode=True,
177 )
178
179 if not module.params['trust_input']:
180 # Check input for potentially dangerous elements:
181 check_input(module, module.params['session_role'])
182
183 # Set some default values:
184 cursor = False
185 db_connection = False
186 result = dict(
187 changed=False,
188 is_available=False,
189 server_version=dict(),
190 conn_err_msg='',
191 )
192
193 # Ensure psycopg libraries are available before connecting to DB:
194 ensure_required_libs(module)
195 conn_params = get_conn_params(module, module.params, warn_db_default=False)
196 db_connection, err = connect_to_db(module, conn_params, fail_on_conn=False)
197 if err:
198 result['conn_err_msg'] = err
199
200 if db_connection is not None:
201 cursor = db_connection.cursor(**pg_cursor_args)
202
203 # Do job:
204 pg_ping = PgPing(module, cursor)
205 if cursor:
206 # If connection established:
207 result["is_available"], result["server_version"] = pg_ping.do()
208 cursor.close()
209 db_connection.close()
210
211 module.exit_json(**result)
212
213
214 if __name__ == '__main__':
215 main()