Repository: ansible/ansible
Pull request: Handle LibraryError exception in postgresql_db
Signed-off-by: Satyajit Bulage <sbulage@redhat.com>

##### SUMMARY
<!--- Describe the change below, including rationale and design decisions -->
Removed `exception` class for `LibraryError` which fixes #65223.
<!--- HINT: Include "Fixes #nnn" if you are fixing an existing issue -->

##### ISSUE TYPE
<!--- Pick one below and delete the rest -->
- Bugfix Pull Request

##### COMPONENT NAME
<!--- Write the short name of the module, plugin, task or feature below -->
postgresql



Problem statement:
LibraryError doesn't exist in the module ansible.module_utils.postgres
<!--- Verify first that your issue is not already reported on GitHub -->
<!--- Also test if the latest release and devel branch are affected too -->
<!--- Complete *all* sections as described, this form is processed automatically -->

##### SUMMARY
Line 556 in the current file `ansible/modules/database/postgresql/postgresql_db.py` references an exception LibraryError, that doesn't exist. This leads to the code to stop at that point instead of showing the actual error. The error message is `AttributeError: 'module' object has no attribute 'LibraryError`. This line seems to be new since 2.9 version. It is still existent in the current master code.

##### ISSUE TYPE
- Bug Report

##### COMPONENT NAME
postgresql

##### ANSIBLE VERSION
<!--- Paste verbatim output from "ansible --version" between quotes -->
```paste below
ansible 2.9.1
  config file = /home/gerhard/projects/localserver/ansible.cfg
  configured module search path = ['/home/gerhard/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/gerhard/projects/localserver/ansible/lib/python3.7/site-packages/ansible
  executable location = ansible/bin/ansible
  python version = 3.7.5 (default, Oct 27 2019, 15:43:29) [GCC 9.2.1 20191022]
```
 but the line is also in the current HEAD.

##### CONFIGURATION
<!--- Paste verbatim output from "ansible-config dump --only-changed" between quotes -->
```paste below
ALLOW_WORLD_READABLE_TMPFILES(/home/gerhard/projects/localserver/ansible.cfg) = True
DEFAULT_BECOME(/home/gerhard/projects/localserver/ansible.cfg) = True
DEFAULT_BECOME_ASK_PASS(/home/gerhard/projects/localserver/ansible.cfg) = False
DEFAULT_BECOME_USER(/home/gerhard/projects/localserver/ansible.cfg) = root
DEFAULT_REMOTE_USER(/home/gerhard/projects/localserver/ansible.cfg) = gerhard
DEFAULT_ROLES_PATH(/home/gerhard/projects/localserver/ansible.cfg) = ['/home/gerhard/projects/localserver/external/roles']
```

##### OS / ENVIRONMENT
<!--- Provide all relevant information below, e.g. target OS versions, network device firmware, etc. -->
Linux


##### STEPS TO REPRODUCE
<!--- Describe exactly how to reproduce the problem, using a minimal test-case -->

<!--- Paste example playbooks or commands between quotes below -->
```yaml
- name: Create database
  postgresql_db:
    name: testdatabase
    state: present
```

<!--- HINT: You can paste gist.github.com links for larger files -->

##### EXPECTED RESULTS
<!--- Describe what you expected to happen when running the steps above -->
The database should be created. For some reasons there seems to be a configuration error though, so access to the database doesn't seem to work. I would now expect an error message regarding authentication to the database.


##### ACTUAL RESULTS
<!--- Describe what actually happened. If possible run with extra verbosity (-vvvv) -->

<!--- Paste verbatim command output between quotes -->
```paste below
failed: [planet.jerri.home] (item=mayanedms) => {
    "ansible_loop_var": "item",
    "changed": false,
    "item": "mayanedms",
    "module_stderr": "Shared connection to planet.jerri.home closed.\r\n",
    "module_stdout": "\r\nTraceback (most recent call last):\r\n  File \"/home/gerhard/.ansible/tmp/ansible-tmp-1574545223.9061017-167794219070878/AnsiballZ_postgresql_db.py\", line 102, in <module>\r\n    _ansiballz_main()\r\n  File \"/home/gerhard/.ansible/tmp/ansible-tmp-1574545223.9061017-167794219070878/AnsiballZ_postgresql_db.py\", line 94, in _ansiballz_main\r\n    invoke_module(zipped_mod, temp_path, ANSIBALLZ_PARAMS)\r\n  File \"/home/gerhard/.ansible/tmp/ansible-tmp-1574545223.9061017-167794219070878/AnsiballZ_postgresql_db.py\", line 40, in invoke_module\r\n    runpy.run_module(mod_name='ansible.modules.database.postgresql.postgresql_db', init_globals=None, run_name='__main__', alter_sys=True)\r\n  File \"/usr/lib/python2.7/runpy.py\", line 188, in run_module\r\n    fname, loader, pkg_name)\r\n  File \"/usr/lib/python2.7/runpy.py\", line 82, in _run_module_code\r\n    mod_name, mod_fname, mod_loader, pkg_name)\r\n  File \"/usr/lib/python2.7/runpy.py\", line 72, in _run_code\r\n    exec code in run_globals\r\n  File \"/tmp/ansible_postgresql_db_payload_7L6Qx4/ansible_postgresql_db_payload.zip/ansible/modules/database/postgresql/postgresql_db.py\", line 611, in <module>\r\n  File \"/tmp/ansible_postgresql_db_payload_7L6Qx4/ansible_postgresql_db_payload.zip/ansible/modules/database/postgresql/postgresql_db.py\", line 550, in main\r\nAttributeError: 'module' object has no attribute 'LibraryError'\r\n",
    "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error",
    "rc": 1
}
```

Hints from issue discussion:
Files identified in the description:
* [`lib/ansible/plugins/doc_fragments/postgres.py`](https://github.com/ansible/ansible/blob/devel/lib/ansible/plugins/doc_fragments/postgres.py)

If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->
cc @Andersson007 @Dorn- @amenonsen @andytom @jbscalia @kostiantyn-nemchenko @matburt @nerzhul @sebasmannem @tcraxs
[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: notify --->
`LibraryError` removed via 86354ff1fb559a943442805b046f3a8b06b2e91e

As a quick workaround, you can do - 

```
diff --git a/lib/ansible/modules/database/postgresql/postgresql_db.py b/lib/ansible/modules/database/postgresql/postgresql_db.py
index cdbb8443b6..2fdfe7bb1a 100644
--- a/lib/ansible/modules/database/postgresql/postgresql_db.py
+++ b/lib/ansible/modules/database/postgresql/postgresql_db.py
@@ -553,9 +553,6 @@ def main():
                 db_connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
             cursor = db_connection.cursor(cursor_factory=psycopg2.extras.DictCursor)

-        except pgutils.LibraryError as e:
-            module.fail_json(msg="unable to connect to database: {0}".format(to_native(e)), exception=traceback.format_exc())
-
         except TypeError as e:
             if 'sslrootcert' in e.args[0]:
                 module.fail_json(msg='Postgresql server must be at least version 8.4 to support sslrootcert. Exception: {0}'.format(to_native(e)),c
```
!component =lib/ansible/module_utils/postgres.py
Files identified in the description:
* [`lib/ansible/module_utils/postgres.py`](https://github.com/ansible/ansible/blob/devel/lib/ansible/module_utils/postgres.py)

If these files are inaccurate, please update the `component name` section of the description or use the `!component` bot command.

[click here for bot help](https://github.com/ansible/ansibullbot/blob/master/ISSUE_HELP.md)
<!--- boilerplate: components_banner --->

Commit message: Fixed LibraryError for issue 65223

Signed-off-by: Satyajit Bulage <sbulage@redhat.com>

Patch to review:
diff --git a/lib/ansible/modules/database/postgresql/postgresql_db.py b/lib/ansible/modules/database/postgresql/postgresql_db.py
index cdbb8443b65f19..b51800a8d5bf3e 100644
--- a/lib/ansible/modules/database/postgresql/postgresql_db.py
+++ b/lib/ansible/modules/database/postgresql/postgresql_db.py
@@ -201,6 +201,11 @@
 class NotSupportedError(Exception):
     pass
 
+
+class LibraryError(Exception):
+    pass
+
+
 # ===========================================
 # PostgreSQL module specific support methods.
 #
@@ -553,7 +558,7 @@ def main():
                 db_connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
             cursor = db_connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
 
-        except pgutils.LibraryError as e:
+        except LibraryError as e:
             module.fail_json(msg="unable to connect to database: {0}".format(to_native(e)), exception=traceback.format_exc())
 
         except TypeError as e:


Code review comments:
diff_hunk: @@ -201,6 +201,11 @@
 class NotSupportedError(Exception):
     pass
 
+
+class LibraryError(Exception):
path: lib/ansible/modules/database/postgresql/postgresql_db.py
text: @user2:
@user1 Are you OK with this exception ? @author Could you please add a change log entry [here](https://github.com/ansible/ansible/tree/devel/changelogs/fragments) ?

@author:
@user2 Added change log entry. Thanks for quick review.

@user1:
@user2 , thanks for mentioning!
i left a comment, it's not needed, we can just remove the problem lines from postgresql_db, see the comment below

diff_hunk: @@ -0,0 +1,2 @@
+bugfixes:
+  - postgresql_db - Added exception for 'LibraryError'
path: changelogs/fragments/65223-postgresql_db-exception-added.yml
text: @user1:
```suggestion
  - postgresql_db - Added exception for 'LibraryError' (https://github.com/ansible/ansible/issues/65223).
```