From 225c26d4d939bd326d8c648ad280e0f9b29b6d7f Mon Sep 17 00:00:00 2001
From: Einar Forselv <eforselv@gmail.com>
Date: Tue, 3 Dec 2019 03:00:17 +0100
Subject: [PATCH] ping postgres with pg_isready

---
 restic_volume_backup/commands.py      | 14 ++++++++++----
 restic_volume_backup/containers_db.py |  9 +++++++--
 2 files changed, 17 insertions(+), 6 deletions(-)

diff --git a/restic_volume_backup/commands.py b/restic_volume_backup/commands.py
index f9f575e..3d97cd3 100644
--- a/restic_volume_backup/commands.py
+++ b/restic_volume_backup/commands.py
@@ -10,7 +10,7 @@ def test():
 
 
 def ping_mysql(host, port, username, password) -> int:
-    """Check if the database is up and can be reached"""
+    """Check if the mysql is up and can be reached"""
     return run([
         'mysqladmin',
         'ping',
@@ -25,7 +25,7 @@ def ping_mysql(host, port, username, password) -> int:
 
 
 def ping_mariadb(host, port, username, password) -> int:
-    """Check if the database is up and can be reached"""
+    """Check if the mariadb is up and can be reached"""
     return run([
         'mysqladmin',
         'ping',
@@ -39,8 +39,14 @@ def ping_mariadb(host, port, username, password) -> int:
     ])
 
 
-def ping_postgres(self) -> int:
-    return -1
+def ping_postgres(host, port, username, password) -> int:
+    """Check if postgres can be reached"""
+    return run([
+        "pg_isready",
+        f"--host={host}",
+        f"--port={port}",
+        f"--username={username}", 
+    ])
 
 
 def run(cmd: List[str]) -> int:
diff --git a/restic_volume_backup/containers_db.py b/restic_volume_backup/containers_db.py
index 2fe3399..be458cc 100644
--- a/restic_volume_backup/containers_db.py
+++ b/restic_volume_backup/containers_db.py
@@ -70,8 +70,13 @@ class PostgresContainer(Container):
 
     def ping(self) -> bool:
         """Check the availability of the service"""
-        # raise NotImplementedError("Base container class don't implement this")
-        print("Implement postgres ping!")
+        creds = self.get_credentials()
+        return commands.ping_postgres(
+            creds['host'],
+            creds['port'],
+            creds['username'],
+            creds['password'],
+        )
 
     def dump_command(self) -> list:
         """list: create a dump command restic and use to send data through stdin"""