Repository navigation
Expand file tree
/
Copy pathcensus-deploy.sh
More file actions
executable file
·232 lines (196 loc) · 7.55 KB
/
Copy pathcensus-deploy.sh
File metadata and controls
executable file
·232 lines (196 loc) · 7.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#!/usr/bin/bash
#
# Census Scheduler auto-deploy script
# Polls CensusScheduler (deploy/test-bundle branch) and OnPlayaData (main) for updates.
# On change: rebuilds Docker, refreshes DB (max once/day).
#
# Usage: Run via cron or systemd timer.
# */15 * * * * /home/mew/Census/CensusScheduler/census-deploy.sh >> /home/mew/Census/CensusScheduler/deploy.log 2>&1
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CENSUS_DIR="$SCRIPT_DIR"
ONPLAYA_DIR="$(dirname "$SCRIPT_DIR")/OnPlayaData"
LOCKFILE="/tmp/census-deploy.lock"
DB_REFRESH_MARKER="/tmp/census-db-last-refresh"
DB_PASSWORD_FILE="$CENSUS_DIR/.env"
LOG_PREFIX="[census-deploy]"
LOCK_MAX_AGE_SECONDS=1800 # Kill stuck deploys after 30 minutes
log() {
echo "$LOG_PREFIX $(date '+%Y-%m-%d %H:%M:%S') $*"
}
# Prevent concurrent runs (with age-based failsafe for hung processes)
if [ -f "$LOCKFILE" ]; then
LOCK_PID=$(cat "$LOCKFILE" 2>/dev/null || true)
if [ -n "$LOCK_PID" ] && kill -0 "$LOCK_PID" 2>/dev/null; then
LOCK_AGE=$(( $(date +%s) - $(stat -c %Y "$LOCKFILE") ))
if [ "$LOCK_AGE" -gt "$LOCK_MAX_AGE_SECONDS" ]; then
log "Lock held by PID $LOCK_PID for ${LOCK_AGE}s (>${LOCK_MAX_AGE_SECONDS}s). Killing hung deploy."
kill -9 "$LOCK_PID" 2>/dev/null || true
rm -f "$LOCKFILE"
else
log "Another instance is running (PID $LOCK_PID, age ${LOCK_AGE}s). Exiting."
exit 0
fi
else
log "Stale lock file found. Removing."
rm -f "$LOCKFILE"
fi
fi
echo $$ > "$LOCKFILE"
trap 'rm -f "$LOCKFILE"' EXIT
# Generate a new random DB password and write to .env for docker-compose
generate_db_password() {
local password
password=$(openssl rand -base64 24 | tr -d '/+=' | head -c 24)
echo "MYSQL_ROOT_PASSWORD=$password" > "$DB_PASSWORD_FILE"
chmod 600 "$DB_PASSWORD_FILE"
log "Generated new DB password."
}
# Read the current DB password from .env
get_db_password() {
if [ -f "$DB_PASSWORD_FILE" ]; then
grep -oP 'MYSQL_ROOT_PASSWORD=\K.*' "$DB_PASSWORD_FILE"
else
echo ""
fi
}
# Calculate the event year (3 months ahead, matching get_year.sh)
YEAR=$(date -d "3 month" +%Y)
# Pull a repo and return 0 if there were new commits.
# Optional second arg = branch to track (default "main").
pull_repo() {
local repo_dir="$1"
local branch="${2:-main}"
local repo_name="$(basename "$repo_dir")"
if [ ! -d "$repo_dir/.git" ]; then
log "WARNING: $repo_dir is not a git repo. Skipping."
return 1
fi
cd "$repo_dir"
git fetch origin "$branch" 2>/dev/null
LOCAL=$(git rev-parse HEAD)
REMOTE=$(git rev-parse "origin/$branch")
# If tracking a non-main branch, warn when origin/main has commits the
# tracked branch doesn't — heads-up that a manual merge is needed to keep
# the deploy current with main.
if [ "$branch" != "main" ]; then
git fetch origin main 2>/dev/null || true
local main_ahead
main_ahead=$(git rev-list --count "$REMOTE..origin/main" 2>/dev/null || echo 0)
if [ "$main_ahead" -gt 0 ]; then
log "$repo_name: NOTE — origin/main has $main_ahead commit(s) not in $branch. Manual merge required to pick them up."
fi
fi
if [ "$LOCAL" = "$REMOTE" ]; then
log "$repo_name: up to date on $branch ($LOCAL)"
return 1
fi
log "$repo_name: new commits on $branch ($LOCAL -> $REMOTE)"
git checkout "$branch" 2>/dev/null
git pull origin "$branch"
return 0
}
# Check if DB was already refreshed today
db_refreshed_today() {
if [ -f "$DB_REFRESH_MARKER" ]; then
LAST_REFRESH=$(cat "$DB_REFRESH_MARKER")
TODAY=$(date +%Y-%m-%d)
if [ "$LAST_REFRESH" = "$TODAY" ]; then
return 0
fi
fi
return 1
}
# Refresh database from OnPlayaData SQL dump
refresh_database() {
local sql_file="$ONPLAYA_DIR/server/${YEAR}_on_playa_server_data.sql"
if [ ! -f "$sql_file" ]; then
log "DB refresh: SQL file not found: $sql_file"
return 1
fi
log "DB refresh: loading $sql_file into census-database container..."
# Get the running database container
local db_container
db_container=$(sudo docker ps --filter "name=census-database" --format '{{.Names}}' | head -1)
if [ -z "$db_container" ]; then
log "DB refresh: census-database container not running. Skipping."
return 1
fi
# Wait for MySQL to be ready (important after fresh container start)
local db_pass
db_pass=$(get_db_password)
local retries=0
while ! sudo docker exec "$db_container" mariadb-admin ping -uroot -p"$db_pass" --silent 2>/dev/null; do
retries=$((retries + 1))
if [ "$retries" -ge 30 ]; then
log "DB refresh: MySQL not ready after 30 attempts. Skipping."
return 1
fi
log "DB refresh: waiting for MySQL to be ready... ($retries/30)"
sleep 2
done
# On-playa DB is MariaDB 11 (matches prod) — the dump loads natively, no
# collation translation needed. Still drop op_email_queue data (real-email
# PII) on the test server before importing.
awk '/^INSERT INTO `op_email_queue` VALUES/{skip=1} skip{if(/;[[:space:]]*$/)skip=0; next} {print}' "$sql_file" \
| sudo docker exec -i "$db_container" mariadb -uroot -p"$db_pass" census
# Blank PII - test server should not contain real names, emails, phones
log "DB refresh: blanking PII..."
sudo docker exec -i "$db_container" mariadb -uroot -p"$db_pass" census < "$CENSUS_DIR/blank_pii.sql"
log "DB refresh: PII blanked."
date +%Y-%m-%d > "$DB_REFRESH_MARKER"
log "DB refresh: complete."
}
# Ensure DB password exists (generated once, persists with the volume)
ensure_db_password() {
if [ ! -f "$DB_PASSWORD_FILE" ]; then
generate_db_password
fi
}
# Rebuild and restart Docker services
# Build FIRST, then stop old containers — keeps the site up during builds.
# If the build fails/times out, old containers keep running.
rebuild_docker() {
log "Docker: rebuilding and restarting..."
cd "$CENSUS_DIR"
# Prune old build cache to prevent disk bloat on this small droplet
sudo docker buildx prune -af 2>/dev/null || true
sudo docker system prune -f
# Build new images while old containers are still serving traffic
if ! timeout --kill-after=30 600 sudo docker compose --file docker-compose.yaml build; then
log "Docker: BUILD FAILED or timed out. Old containers left running."
return 1
fi
# Build succeeded — now swap: stop old, start new
# Password persists with the DB volume — only generate if missing
ensure_db_password
sudo docker compose --file docker-compose.yaml down
timeout --kill-after=10 120 sudo docker compose --file docker-compose.yaml up -d
log "Docker: rebuild complete."
}
# --- Main ---
log "=== Starting deploy check ==="
SCHEDULER_UPDATED=false
ONPLAYA_UPDATED=false
if pull_repo "$CENSUS_DIR" "deploy/test-bundle"; then
SCHEDULER_UPDATED=true
fi
if pull_repo "$ONPLAYA_DIR"; then
ONPLAYA_UPDATED=true
fi
if [ "$SCHEDULER_UPDATED" = true ]; then
log "Code changes detected. Rebuilding Docker..."
rebuild_docker
# Always refresh DB after a rebuild — the container may have reinitialized
log "DB refresh: forced after container rebuild."
refresh_database
elif [ "$ONPLAYA_UPDATED" = true ]; then
if ! db_refreshed_today; then
refresh_database
else
log "DB refresh: already refreshed today. Skipping."
fi
else
log "No changes detected."
fi
log "=== Deploy check complete ==="