CORD-2818 Wait for database before running migrations

Change-Id: I9edb10e6b3f1d3ec9d572fd3fda6f29b73ebc13e
diff --git a/xos/coreapi/Makefile b/xos/coreapi/Makefile
index 2482d1c..bf99f99 100644
--- a/xos/coreapi/Makefile
+++ b/xos/coreapi/Makefile
@@ -31,7 +31,7 @@
 start:
 	bash -c "source env.sh && python ./core_main.py $(START_OPTIONS)"
 
-prep: unload_unwanted app_lists rebuild_protos compile_protos try_models makemigrations migrate
+prep: unload_unwanted app_lists rebuild_protos compile_protos try_models wait_for_db makemigrations migrate
 
 unload_unwanted:
 	python unload_unwanted_apps.py
@@ -53,3 +53,6 @@
 
 try_models:
 	python ./try_models.py
+
+wait_for_db:
+	python ./wait_for_db.py
diff --git a/xos/coreapi/wait_for_db.py b/xos/coreapi/wait_for_db.py
new file mode 100644
index 0000000..939d4ed
--- /dev/null
+++ b/xos/coreapi/wait_for_db.py
@@ -0,0 +1,48 @@
+
+# Copyright 2017-present Open Networking Foundation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import psycopg2
+import sys
+import time
+import traceback
+
+from xosconfig import Config
+
+Config.init()
+
+def wait_for_database():
+    while True:
+        db_name = Config.get("database.name")
+        db_user = Config.get("database.username")
+        db_password = Config.get("database.password")
+        db_host = "xos-db"  # TODO: this should be configurable
+        db_port = 5432      # TODO: this should be configurable
+
+        try:
+            myConnection = psycopg2.connect(host = db_host, port = db_port,
+                                            user = db_user, password = db_password)
+
+
+
+            myConnection.close()
+
+            # Exit on successful connection
+            print "Database is available"
+            return
+        except:
+            traceback.print_exc("Exception while connecting to db")
+            time.sleep(1)
+
+wait_for_database()