From b4984ba781052bf3de99ae60d43abd89b5dec27e Mon Sep 17 00:00:00 2001 From: Benjamin Diaz Date: Tue, 26 Feb 2019 16:54:10 -0300 Subject: [PATCH] Modifies POL to create database if using mysql URI Change-Id: I718e703992eac66bae22cbc44ea8b78cbd776371 Signed-off-by: Benjamin Diaz --- docker/Dockerfile | 4 ++- docker/scripts/start.sh | 55 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 docker/scripts/start.sh diff --git a/docker/Dockerfile b/docker/Dockerfile index 3c00b7a..2ca3fc4 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -25,7 +25,7 @@ FROM ubuntu:16.04 LABEL authors="Benjamín Díaz" RUN apt-get --yes update \ - && apt-get --yes install python3 python3-pip libmysqlclient-dev git \ + && apt-get --yes install python3 python3-pip libmysqlclient-dev git mysql-client \ && pip3 install pip==9.0.3 COPY requirements.txt /policy_module/requirements.txt @@ -48,3 +48,5 @@ ENV OSMPOL_SQL_DATABASE_URI sqlite:///policy_module.db ENV OSMPOL_GLOBAL_LOGLEVEL INFO CMD osm-policy-agent + +CMD /bin/bash /policy_module/docker/scripts/start.sh \ No newline at end of file diff --git a/docker/scripts/start.sh b/docker/scripts/start.sh new file mode 100644 index 0000000..04d0d34 --- /dev/null +++ b/docker/scripts/start.sh @@ -0,0 +1,55 @@ +DB_EXISTS="" + +max_attempts=120 +function wait_db(){ + db_host=$1 + db_port=$2 + attempt=0 + echo "Wait until $max_attempts seconds for MySQL mano Server ${db_host}:${db_port} " + while ! mysqladmin ping -h"$db_host" -P"$db_port" --silent; do + #wait 120 sec + if [ $attempt -ge $max_attempts ]; then + echo + echo "Can not connect to database ${db_host}:${db_port} during $max_attempts sec" + return 1 + fi + attempt=$[$attempt+1] + echo -n "." + sleep 1 + done + return 0 +} + +function is_db_created() { + db_host=$1 + db_port=$2 + db_user=$3 + db_pswd=$4 + db_name=$5 + + if mysqlshow -h"$db_host" -P"$db_port" -u"$db_user" -p"$db_pswd" | grep -v Wildcard | grep -q $db_name; then + echo "DB $db_name exists" + return 0 + else + echo "DB $db_name does not exist" + return 1 + fi +} + +if [[ $OSMPOL_SQL_DATABASE_URI == *'mysql'* ]]; then + DB_HOST=$(echo $OSMPOL_SQL_DATABASE_URI | sed -r 's|^\w+://.+:.+@(.+):.*$|\1|') + DB_PORT=$(echo $OSMPOL_SQL_DATABASE_URI | sed -r 's|^\w+://.*:([0-9]+).*$|\1|') + DB_USER=$(echo $OSMPOL_SQL_DATABASE_URI | sed -r 's|^\w+://(.+):.+@.+$|\1|') + DB_PASSWORD=$(echo $OSMPOL_SQL_DATABASE_URI | sed -r 's|^.+://.+:(.+)@.*$|\1|') + DB_NAME=$(echo $OSMPOL_SQL_DATABASE_URI | sed -r 's|^\w+://.+:.+@.+:.*/(.+)$|\1|') + + wait_db "$DB_HOST" "$DB_PORT" || exit 1 + + is_db_created "$DB_HOST" "$DB_PORT" "$DB_USER" "$DB_PASSWORD" "$DB_NAME" && DB_EXISTS="Y" + + if [ -z $DB_EXISTS ]; then + mysql -h"$DB_HOST" -P"$DB_PORT" -u"$DB_USER" -p"$DB_PASSWORD" --default_character_set utf8 -e "CREATE DATABASE $DB_NAME" + fi +fi + +osm-policy-agent \ No newline at end of file -- 2.25.1