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.

104 lines
2.5 KiB

  1. # -*- mode: shell-script -*-
  2. include pretty
  3. export DB_NAME="$SERVICE_NAME" ## general type of database (ie: postgres/mysql...)
  4. export DB_DATADIR=/var/lib/mongodb
  5. export DATA_DIR=$SERVICE_DATASTORE$DB_DATADIR
  6. is_db_locked() {
  7. is_volume_used "$DATASTORE/${SERVICE_NAME}"
  8. }
  9. _set_server_db_params() {
  10. server_docker_opts+=("-v" "${SERVICE_CONFIGSTORE}/etc/mongod.conf:/etc/mongod.conf"
  11. "--add-host" "${SERVICE_NAME}:127.0.0.1")
  12. }
  13. _set_db_params() {
  14. local docker_ip="$1" docker_network="$2"
  15. ## XXXvlab: include this in compose-core
  16. if [ "${_db_params}" != "$docker_ip:$docker_network" ]; then
  17. db_docker_opts+=("--network" "$docker_network")
  18. db_cmd_opts+=("--host" "$docker_ip")
  19. check_command="db.serverStatus().ok"
  20. _db_params="$docker_ip:$docker_network"
  21. echo callers: "${FUNCNAME[@]}" >&2
  22. fi
  23. }
  24. ddb() { dcmd mongo --quiet "$@"; }
  25. djson() {
  26. local out err
  27. if ! out=$(ddb); then
  28. err "Mongo call failed"
  29. return 128
  30. fi
  31. if [ -z "$out" ]; then
  32. err "Mongo replied with empty output"
  33. return 64
  34. fi
  35. if [ "$(e "$out" | jq -r .ok)" != "1" ]; then
  36. if ! e "$out" | jq . >/dev/null 2>&1; then
  37. err "Mongo didn't output JSON, output follows:"
  38. e "$out" | prefix " | "
  39. return 32
  40. fi >&2
  41. errmsg=$(e "$out" | jq -r '.errmsg')
  42. code_name=$(e "$out" | jq -r '.codeName')
  43. err "Mongo failed with error message: $errmsg (code: ${code_name})"
  44. e "$out"
  45. return 32
  46. fi
  47. e "$out"
  48. return 0
  49. }
  50. mongo:db:ls() {
  51. local out
  52. if out=$(djson < <(echo "JSON.stringify(db.adminCommand( { listDatabases: 1 } ))")); then
  53. e "$out" | jq -r '.databases[] | .name'
  54. return 0
  55. else
  56. if [ "$(e "$out" | jq -r '.codeName')" == "NotMasterNoSlaveOk" ]; then
  57. ## equivalent to having no databases
  58. return 0
  59. fi
  60. err "Could not query list of databases."
  61. return 1
  62. fi
  63. }
  64. mongo:db:rename() {
  65. local src="$1" dst="$2" out
  66. if ! out=$(ddb <<EOF
  67. db.copyDatabase("$src","$dst");
  68. use $src;
  69. db.dropDatabase();
  70. EOF
  71. ); then
  72. err "Could not rename database '$src' to '$dst'."
  73. err "$out"
  74. return 1
  75. fi
  76. debug "$out"
  77. }
  78. mongo:db:version() {
  79. local out
  80. if out=$(ddb < <(echo "db.version()")); then
  81. e "$out"
  82. return 0
  83. else
  84. err "Could not query version of database."
  85. return 1
  86. fi
  87. }