From 5d49f15475a7361163743e47667b54c122ca49a5 Mon Sep 17 00:00:00 2001 From: Valentin Lab Date: Mon, 16 Mar 2020 18:13:45 +0100 Subject: [PATCH] fix: dev: [rocketchat,mongo] do not use ``$PROJECT_NAME`` in mongo database url. Indeed, when changing project name, ``rocketchat`` would create a new database and would not be able to use previous database. ``mongo`` side is here to ensure proper update of existing installation that would use previous naming scheme. Signed-off-by: Valentin Lab --- mongo/hooks/mongo_database-relation-joined | 27 ++++++++++++++++++ mongo/lib/common | 28 ++++++++++++++++++- .../hooks/mongo_database-relation-joined | 2 +- 3 files changed, 55 insertions(+), 2 deletions(-) diff --git a/mongo/hooks/mongo_database-relation-joined b/mongo/hooks/mongo_database-relation-joined index 99520b3..b93b7ed 100755 --- a/mongo/hooks/mongo_database-relation-joined +++ b/mongo/hooks/mongo_database-relation-joined @@ -10,6 +10,33 @@ DBNAME=$(relation-get dbname) || { } +dbs=$(mongo:db:ls) || exit 1 +if matching_db=$(e "$dbs" | egrep "[a-zA-Z0-9.-_]*_${DBNAME}"); then + if e "$dbs" | grep "^${DBNAME}$"; then + err "Error: unexpected database '$matching_db'" \ + "found along with database named '${DBNAME}'." + exit 1 + fi + ## Let's take for granted that only current source service is + ## concerned by the database. We need to restart source service + ## container only if already running. + container_ids=($(get_running_containers_for_service "$MASTER_BASE_SERVICE_NAME")) + for container_id in "${container_ids[@]}"; do + mongo_url=$(docker:container:env_get "$container_id" MONGO_URL) || return 1 + if [[ "$mongo_url" == */"${matching_db}"* ]]; then + info "Attempting to stop current containers of service $MASTER_BASE_SERVICE_NAME" + docker stop -t 5 "$container_id" + fi + done + + mongo:db:rename "$matching_db" "${DBNAME}" + + ## we DO NOT want to start the stopped container again as they are not + ## properly configured +fi + +## ReplicaSet initialization + cmd="rs.initiate({ _id: 'rs01', members: [ { _id: 0, host: '$TARGET_SERVICE_NAME:27017' } ]})" debug "${WHITE}running:$NORMAL $cmd" diff --git a/mongo/lib/common b/mongo/lib/common index ca426a0..7ed3237 100644 --- a/mongo/lib/common +++ b/mongo/lib/common @@ -27,4 +27,30 @@ _set_db_params() { check_command="db.serverStatus().ok" } -ddb () { dcmd mongo "$@"; } +ddb() { dcmd mongo --quiet "$@"; } + + +mongo:db:ls() { + local out + if ! out=$(ddb < <(echo "JSON.stringify(db.adminCommand( { listDatabases: 1 } ))")); then + err "Could not query list of databases." + return 1 + fi + e "$out" | jq -r '.databases[] | .name' +} + + +mongo:db:rename() { + local src="$1" dst="$2" out + if ! out=$(ddb <