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.

92 lines
2.4 KiB

  1. #!/bin/bash
  2. ## When writing relation script, remember:
  3. ## - they should be idempotents
  4. ## - they can be launched while the dockers is already up
  5. ## - they are launched from the host
  6. ## - the target of the link is launched first, and get a chance to ``relation-set``
  7. ## - both side of the scripts get to use ``relation-get``.
  8. DBNAME=$(relation-get dbname) || {
  9. DBNAME="$BASE_SERVICE_NAME"
  10. relation-set dbname "$DBNAME"
  11. }
  12. USER=$(relation-get user) || {
  13. USER="$BASE_SERVICE_NAME"
  14. relation-set user "$USER"
  15. }
  16. . lib/common
  17. set -e
  18. ## YYY: check that password was not already generated/set for the same user
  19. ## use session state storage.
  20. ## is there a previous password set for user $USER ?
  21. NO_PREVIOUS_PASS=
  22. PREVIOUS_PASSWORD_PATH="$state_tmpdir/$SERVICE_NAME/pwd/$USER"
  23. PREVIOUS_PASSWORD=$(cat "$PREVIOUS_PASSWORD_PATH" 2>/dev/null) || NO_PREVIOUS_PASS=true
  24. if PASSWORD="$(relation-get password 2>/dev/null)"; then
  25. if [ -z "$NO_PREVIOUS_PASS" -a "$PREVIOUS_PASSWORD" != "$PASSWORD" ]; then
  26. die "Inconsistent password specification for user '$USER' on ${DARKYELLOW}$TARGET_SERVICE_NAME$NORMAL."
  27. fi
  28. else
  29. if [ "$PREVIOUS_PASSWORD" ]; then
  30. PASSWORD="${PREVIOUS_PASSWORD}"
  31. else
  32. PASSWORD="$(gen_password)"
  33. info "Generated a new password for user '$USER'."
  34. fi
  35. fi
  36. array_read-0 extensions < <(relation-get extensions 2>/dev/null | shyaml get-values-0)
  37. ensure_db_docker_running
  38. ## XXXvlab: should send all these into only one docker...
  39. if ! db_has_database "$DBNAME"; then
  40. db_create "$DBNAME" || exit 1
  41. fi
  42. if [ "${#extensions[@]}" -gt 0 ]; then
  43. db_install_extensions "$DBNAME" "${extensions[@]}" || exit 1
  44. fi
  45. if ! db_has_user "$USER"; then
  46. info "Creating a new user $USER."
  47. db_create_user "$USER" "$PASSWORD" || exit 1
  48. else
  49. info "Updating password of user $USER."
  50. db_change_password "$USER" "$PASSWORD" || exit 1
  51. fi
  52. db_grant_rights "$DBNAME" "$USER"
  53. info "Granted rights on database '$DBNAME' to user '$USER'."
  54. ##
  55. ## PGPASS
  56. ##
  57. pgpass_line="*:*:*:$USER:$PASSWORD"
  58. pgpass_file="$CONFIGSTORE/$BASE_SERVICE_NAME/root/.pgpass"
  59. if [ -e "$pgpass_file" ]; then
  60. sed -ri "/^.+:.+:.+:$USER:.*$/d" "$pgpass_file"
  61. fi
  62. mkdir -p "$(dirname "$pgpass_file")"
  63. echo "$pgpass_line" >> "$pgpass_file"
  64. chmod 600 "$pgpass_file"
  65. ##
  66. ## Saving password
  67. ##
  68. relation-set password "$PASSWORD"
  69. mkdir -p "$(dirname "$PREVIOUS_PASSWORD_PATH")"
  70. echo "$PASSWORD" > "$PREVIOUS_PASSWORD_PATH"