deploy-remote.sh 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. #!/usr/bin/env bash
  2. set -euo pipefail
  3. remote="${MAILHUB_DEPLOY_REMOTE:-}"
  4. remote_dir="${MAILHUB_DEPLOY_DIR:-}"
  5. branch="${MAILHUB_DEPLOY_BRANCH:-$(git branch --show-current)}"
  6. git_url="${MAILHUB_DEPLOY_GIT_URL:-$(git remote get-url origin)}"
  7. stash_remote="${MAILHUB_DEPLOY_STASH_REMOTE:-0}"
  8. if [[ -z "${remote}" || -z "${remote_dir}" ]]; then
  9. echo "Set MAILHUB_DEPLOY_REMOTE and MAILHUB_DEPLOY_DIR before deploying." >&2
  10. echo "Example: MAILHUB_DEPLOY_REMOTE=deploy@example.com MAILHUB_DEPLOY_DIR=/opt/mailhub npm run deploy:remote" >&2
  11. exit 1
  12. fi
  13. if [[ -z "${branch}" ]]; then
  14. echo "Unable to detect current git branch." >&2
  15. exit 1
  16. fi
  17. git fetch origin "${branch}"
  18. local_head="$(git rev-parse HEAD)"
  19. remote_head="$(git rev-parse "origin/${branch}")"
  20. if [[ "${local_head}" != "${remote_head}" ]]; then
  21. echo "Local HEAD is not pushed to origin/${branch}." >&2
  22. echo "Commit and push first, then run this deploy script." >&2
  23. exit 1
  24. fi
  25. ssh -o ServerAliveInterval=15 -o ServerAliveCountMax=4 "${remote}" \
  26. 'bash -s' -- "${remote_dir}" "${branch}" "${git_url}" "${stash_remote}" <<'REMOTE'
  27. set -euo pipefail
  28. remote_dir="$1"
  29. branch="$2"
  30. git_url="$3"
  31. stash_remote="$4"
  32. cd "${remote_dir}"
  33. wait_for_compose_health() {
  34. local timeout="${MAILHUB_DEPLOY_HEALTH_TIMEOUT:-180}"
  35. local deadline=$((SECONDS + timeout))
  36. local service container_id snapshot state health all_ready
  37. while (( SECONDS < deadline )); do
  38. all_ready=1
  39. for service in "$@"; do
  40. container_id="$(docker compose ps --all --quiet "${service}" </dev/null 2>/dev/null | tail -n 1 || true)"
  41. if [[ -z "${container_id}" ]]; then
  42. all_ready=0
  43. continue
  44. fi
  45. snapshot="$(docker inspect \
  46. --format '{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{else}}missing{{end}}' \
  47. "${container_id}" </dev/null 2>/dev/null || true)"
  48. state="${snapshot%% *}"
  49. health="${snapshot#* }"
  50. if [[ "${state}" == "exited" || "${state}" == "dead" ]]; then
  51. docker compose logs --tail=100 "${service}" </dev/null >&2 || true
  52. return 1
  53. fi
  54. [[ "${state}" == "running" && "${health}" == "healthy" ]] || all_ready=0
  55. done
  56. [[ "${all_ready}" == "1" ]] && return 0
  57. sleep 2
  58. done
  59. docker compose ps </dev/null >&2 || true
  60. docker compose logs --tail=100 "$@" </dev/null >&2 || true
  61. return 1
  62. }
  63. verify_mail_runtime() {
  64. local dovecot_probe_name=".mailhub-dovecot-runtime-probe"
  65. docker compose exec -T app </dev/null node -e '
  66. const fs = require("node:fs");
  67. const dovecotProbe = `/data/maildir/${process.argv[1]}`;
  68. try {
  69. fs.unlinkSync(dovecotProbe);
  70. } catch (error) {
  71. if (error.code !== "ENOENT") throw error;
  72. }
  73. const secret = fs.readFileSync("/run/secrets/dovecot_auth_secret", "utf8").trim();
  74. fs.accessSync("/data/maildir", fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK);
  75. const probe = `/data/maildir/.mailhub-app-health-${process.pid}`;
  76. try {
  77. fs.writeFileSync(probe, "", { mode: 0o600, flag: "wx" });
  78. } finally {
  79. try { fs.unlinkSync(probe); } catch {}
  80. }
  81. fetch("http://app:3001/internal/dovecot/auth", {
  82. method: "POST",
  83. headers: {
  84. authorization: `Bearer ${secret}`,
  85. "content-type": "application/json"
  86. },
  87. body: JSON.stringify({
  88. username: "mailhub-healthcheck@invalid.invalid",
  89. password: "mailhub-healthcheck-invalid-password",
  90. service: "imap",
  91. remoteIp: "127.0.0.1"
  92. }),
  93. signal: AbortSignal.timeout(5000)
  94. }).then(async (response) => {
  95. const payload = await response.json();
  96. if (response.status !== 200 || payload.authenticated !== false) process.exit(1);
  97. }).catch(() => process.exit(1));
  98. ' "${dovecot_probe_name}" >/dev/null 2>&1 || {
  99. echo "MailHub authentication bridge or app Maildir access check failed." >&2
  100. return 1
  101. }
  102. if ! docker compose exec -T --user 1000:1000 dovecot </dev/null sh -ec '
  103. test -r /run/secrets/dovecot_auth_secret
  104. test -s /run/secrets/dovecot_auth_secret
  105. probe="/srv/vmail/$1"
  106. test ! -e "$probe"
  107. umask 077
  108. : >"$probe"
  109. test -f "$probe"
  110. ' -- "${dovecot_probe_name}" >/dev/null 2>&1; then
  111. docker compose exec -T app </dev/null node -e '
  112. const fs = require("node:fs");
  113. try { fs.unlinkSync(`/data/maildir/${process.argv[1]}`); } catch {}
  114. ' "${dovecot_probe_name}" >/dev/null 2>&1 || true
  115. echo "Dovecot secret or Maildir write access check failed." >&2
  116. return 1
  117. fi
  118. docker compose exec -T app </dev/null node -e '
  119. const fs = require("node:fs");
  120. const probe = `/data/maildir/${process.argv[1]}`;
  121. try {
  122. if (!fs.statSync(probe).isFile()) process.exitCode = 1;
  123. } finally {
  124. try { fs.unlinkSync(probe); } catch {}
  125. }
  126. ' "${dovecot_probe_name}" >/dev/null 2>&1 || {
  127. echo "Dovecot Maildir write probe was not visible to the MailHub app." >&2
  128. return 1
  129. }
  130. }
  131. if ! git remote get-url origin </dev/null >/dev/null 2>&1; then
  132. git remote add origin "${git_url}" </dev/null
  133. fi
  134. if [[ -n "$(git status --porcelain </dev/null)" ]]; then
  135. if [[ "${stash_remote}" == "1" ]]; then
  136. git stash push -u -m "pre-deploy-$(date -u +%Y%m%d-%H%M%S)" </dev/null
  137. else
  138. echo "Remote working tree is dirty. Set MAILHUB_DEPLOY_STASH_REMOTE=1 to stash it before pulling." >&2
  139. git status --short </dev/null >&2
  140. exit 1
  141. fi
  142. fi
  143. previous_revision="$(git rev-parse HEAD </dev/null)"
  144. stopped_app_container=""
  145. stopped_dovecot_container=""
  146. mail_services_stopped_for_migration=0
  147. maildir_cutover_committed=0
  148. on_deploy_exit() {
  149. local status=$?
  150. trap - EXIT
  151. if [[ "${status}" != "0" ]]; then
  152. echo "Deployment failed. Previous revision was ${previous_revision}; inspect the running containers before recovery." >&2
  153. if [[ "${mail_services_stopped_for_migration}" == "1" ]]; then
  154. echo "Restarting the pre-migration MailHub mail services." >&2
  155. if [[ -n "${stopped_app_container}" ]]; then
  156. docker start "${stopped_app_container}" </dev/null >/dev/null 2>&1 || \
  157. echo "Unable to restart the pre-migration app container ${stopped_app_container}." >&2
  158. fi
  159. if [[ -n "${stopped_dovecot_container}" ]]; then
  160. docker start "${stopped_dovecot_container}" </dev/null >/dev/null 2>&1 || \
  161. echo "Unable to restart the pre-migration Dovecot container ${stopped_dovecot_container}." >&2
  162. fi
  163. elif [[ "${maildir_cutover_committed}" == "1" ]]; then
  164. docker compose stop app dovecot </dev/null >/dev/null 2>&1 || \
  165. echo "Unable to stop the post-cutover mail services; inspect their port exposure immediately." >&2
  166. echo "Maildir cutover is already committed; legacy mail services will not be restarted because that would create two conflicting sources of truth." >&2
  167. echo "The maintenance window remains active; recover the current Compose services or perform an explicit revision rollback before reopening mail traffic." >&2
  168. fi
  169. docker compose ps </dev/null >&2 || true
  170. fi
  171. exit "${status}"
  172. }
  173. trap on_deploy_exit EXIT
  174. git fetch origin "${branch}" </dev/null
  175. git checkout "${branch}" </dev/null
  176. git pull --ff-only origin "${branch}" </dev/null
  177. ./scripts/prepare-dovecot.sh </dev/null
  178. if [[ "$(id -u)" == "0" ]]; then
  179. MAILHUB_CERT_READER_GID=1000 MAILHUB_CERT_RESTART=0 ./scripts/sync-tls-certificate.sh </dev/null
  180. else
  181. MAILHUB_CERT_RESTART=0 ./scripts/sync-tls-certificate.sh </dev/null
  182. fi
  183. docker compose build app postfix </dev/null
  184. docker compose pull dovecot </dev/null
  185. stopped_app_container="$(docker compose ps --all --quiet app </dev/null 2>/dev/null | tail -n 1 || true)"
  186. stopped_dovecot_container="$(docker compose ps --all --quiet dovecot </dev/null 2>/dev/null | tail -n 1 || true)"
  187. mail_services_stopped_for_migration=1
  188. docker compose stop app dovecot </dev/null
  189. docker compose run --rm --no-deps -T app </dev/null node scripts/migrate-sqlite-maildir.js
  190. maildir_cutover_committed=1
  191. mail_services_stopped_for_migration=0
  192. docker compose up -d </dev/null
  193. wait_for_compose_health app postfix dovecot
  194. verify_mail_runtime
  195. MAILHUB_CERT_RESTART=1 ./scripts/sync-tls-certificate.sh </dev/null
  196. wait_for_compose_health app postfix dovecot
  197. verify_mail_runtime
  198. docker compose ps </dev/null
  199. trap - EXIT
  200. REMOTE