fork 0k-charms
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.8 KiB

  1. #!/bin/bash
  2. . lib/common
  3. set -e
  4. DBNAME=$(relation-get dbname) || {
  5. DBNAME="${BASE_SERVICE_NAME//\./_}"
  6. relation-set dbname "$DBNAME"
  7. }
  8. ensure_db_docker_running
  9. if dbs=$(mongo:db:ls); then
  10. if matching_db=$(e "$dbs" | egrep "[a-zA-Z0-9.-_]*_${DBNAME}"); then
  11. if e "$dbs" | grep "^${DBNAME}$"; then
  12. err "Error: unexpected database '$matching_db'" \
  13. "found along with database named '${DBNAME}'."
  14. exit 1
  15. fi
  16. ## Let's take for granted that only current source service is
  17. ## concerned by the database. We need to restart source service
  18. ## container only if already running.
  19. container_ids=($(get_running_containers_for_service "$MASTER_BASE_SERVICE_NAME"))
  20. for container_id in "${container_ids[@]}"; do
  21. mongo_url=$(docker:container:env_get "$container_id" MONGO_URL) || return 1
  22. if [[ "$mongo_url" == */"${matching_db}"* ]]; then
  23. info "Attempting to stop current containers of service $MASTER_BASE_SERVICE_NAME"
  24. docker stop -t 5 "$container_id"
  25. fi
  26. done
  27. mongo:db:rename "$matching_db" "${DBNAME}"
  28. ## we DO NOT want to start the stopped container again as they are not
  29. ## properly configured
  30. fi
  31. else
  32. err "Failed to query for database list"
  33. exit 14
  34. fi
  35. ## ReplicaSet initialization
  36. cmd="rs.initiate({ _id: 'rs01', members: [ { _id: 0, host: '$TARGET_SERVICE_NAME:27017' } ]})"
  37. debug "${WHITE}running:$NORMAL $cmd"
  38. out=$(ddb < <(echo "use $DBNAME";
  39. echo "$cmd"))
  40. if [[ "$out" == *"\"codeName\" : \"AlreadyInitialized\""* ]]; then
  41. info "ReplicaSet already initialized."
  42. elif [[ "$out" == *"\"ok\" : 1"* ]]; then
  43. info "ReplicaSet initialized. "
  44. else
  45. err "ReplicaSet initialisation failed:"
  46. echo "$out" >&2
  47. exit 13
  48. fi