-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.sh
More file actions
executable file
·578 lines (506 loc) · 25.1 KB
/
start.sh
File metadata and controls
executable file
·578 lines (506 loc) · 25.1 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
#!/bin/bash
set -eu
echo "==> Ensure directories"
mkdir -p /app/data/config /app/data/content /app/data/uploads /app/data/releases /app/data/cache /app/data/images
# Clean up data corruption from previous buggy deployments
echo "==> Cleaning up any corrupted data from backups"
# Remove circular symlink that causes ELOOP errors (content/content/content/...)
rm -f /app/data/content/content 2>/dev/null || true
# Remove old buggy eleventy directory (node_modules should never be in /app/data)
rm -rf /app/data/eleventy 2>/dev/null || true
# Merge migrated legacy content (copy new files without overwriting existing)
if [[ -d /app/pkg/migrated-content ]]; then
echo "==> Merging migrated legacy content"
for dir in /app/pkg/migrated-content/*/; do
dirname=$(basename "$dir")
mkdir -p "/app/data/content/$dirname"
# Use cp -n (no clobber) to not overwrite existing files
cp -rn "$dir"* "/app/data/content/$dirname/" 2>/dev/null || true
done
echo "==> Migration merge complete"
fi
# Update config from bundled version (supports personal overrides via .rmendes pattern)
# Always update to ensure config changes are applied on deploy
if [[ -f /app/pkg/indiekit.config.js ]]; then
echo "==> Updating Indiekit config from bundled version"
cp /app/pkg/indiekit.config.js /app/data/config/indiekit.config.js
elif [[ ! -f /app/data/config/indiekit.config.js ]]; then
echo "==> Creating default config from template (first run)"
cp /app/pkg/indiekit.config.js.template /app/data/config/indiekit.config.js
fi
# Create user env file for secrets on first run
if [[ ! -f /app/data/config/env.sh ]]; then
echo "==> Creating env.sh for syndicator tokens"
cat > /app/data/config/env.sh <<'ENVEOF'
# Add your tokens here and restart the app
# PASSWORD_SECRET - REQUIRED after first run
# 1. Visit your Indiekit URL /admin, you'll see a "New password" page
# 2. Create a password
# 3. Copy the PASSWORD_SECRET hash and paste it below IN SINGLE QUOTES
# 4. Restart the app (cloudron restart)
# IMPORTANT: Use single quotes because the hash contains $ characters!
export PASSWORD_SECRET='paste-your-hash-here'
# GitHub token (optional, for /github endpoint)
export GITHUB_TOKEN=""
# Bluesky app password (get from Settings > App Passwords)
export BLUESKY_PASSWORD=""
# Mastodon access token (get from Settings > Development > Applications)
export MASTODON_ACCESS_TOKEN=""
# LinkedIn syndication (for posting to LinkedIn)
# Option 1: Use OAuth flow at /linkedin (recommended)
# Option 2: Set access token manually
export LINKEDIN_ACCESS_TOKEN=""
export LINKEDIN_AUTHOR_NAME=""
export LINKEDIN_PROFILE_URL=""
# LinkedIn OAuth app credentials (get from LinkedIn Developer Portal)
export LINKEDIN_CLIENT_ID=""
export LINKEDIN_CLIENT_SECRET=""
# Webmention.io token (get from https://webmention.io/settings)
export WEBMENTION_IO_TOKEN=""
# Funkwhale configuration (for /funkwhale endpoint)
# Get token from your Funkwhale Settings > Applications
export FUNKWHALE_INSTANCE="https://buzzworkers.com"
export FUNKWHALE_TOKEN=""
export FUNKWHALE_USERNAME="buzz"
# YouTube configuration (for /youtube endpoint)
# Get API key from Google Cloud Console > APIs & Services > Credentials
export YOUTUBE_API_KEY=""
# Comma-separated channel handles (e.g., "@channel1,@channel2")
export YOUTUBE_CHANNELS=""
# Last.fm configuration (for /listening endpoint)
# Get API key from https://www.last.fm/api/account/create
export LASTFM_API_KEY=""
export LASTFM_USERNAME=""
# Site customization (optional)
export SITE_NAME="My IndieWeb Blog"
export SITE_DESCRIPTION="An IndieWeb blog powered by Indiekit"
export AUTHOR_NAME="Your Name"
export AUTHOR_TITLE=""
export AUTHOR_BIO="Welcome to my IndieWeb blog."
export AUTHOR_AVATAR=""
export AUTHOR_LOCATION=""
export AUTHOR_LOCALITY=""
export AUTHOR_COUNTRY=""
export AUTHOR_ORG=""
export AUTHOR_PRONOUN=""
export AUTHOR_EMAIL=""
export AUTHOR_KEY_URL=""
export AUTHOR_CATEGORIES=""
# Social profile handles (used for feed widgets AND h-card rel="me" links)
export GITHUB_USERNAME=""
export BLUESKY_HANDLE=""
export MASTODON_INSTANCE=""
export MASTODON_USER=""
export LINKEDIN_USERNAME=""
export ACTIVITYPUB_HANDLE="" # Fediverse handle (e.g., "rick") — adds rel="me" link to h-card
# Or set all social links manually (overrides auto-generation from handles above)
# Format: "Name|URL|icon,Name|URL|icon"
# Example: "GitHub|https://github.com/user|github,Mastodon|https://mastodon.social/@user|mastodon"
export SITE_SOCIAL=""
# Markdown for Agents — serve clean Markdown to AI agents
# Set to "false" to disable Markdown generation entirely
export MARKDOWN_AGENTS_ENABLED="true"
# Content-signal policy — controls what AI agents are allowed to do with your content
# Values: "yes" or "no" for each signal
export MARKDOWN_AGENTS_AI_TRAIN="yes" # Allow AI model training
export MARKDOWN_AGENTS_SEARCH="yes" # Allow search indexing
export MARKDOWN_AGENTS_AI_INPUT="yes" # Allow agentic use (RAG, summarization)
ENVEOF
fi
# Source user secrets
source /app/data/config/env.sh
# Migrate: add ACTIVITYPUB_HANDLE to env.sh if missing (added in v2.0.21)
if ! grep -q 'ACTIVITYPUB_HANDLE' /app/data/config/env.sh 2>/dev/null; then
echo '' >> /app/data/config/env.sh
echo '# ActivityPub handle for fediverse rel="me" verification in h-card' >> /app/data/config/env.sh
echo 'export ACTIVITYPUB_HANDLE=""' >> /app/data/config/env.sh
fi
# Migrate: add MARKDOWN_AGENTS vars to env.sh if missing
if ! grep -q 'MARKDOWN_AGENTS_ENABLED' /app/data/config/env.sh 2>/dev/null; then
cat >> /app/data/config/env.sh <<'MDEOF'
# Markdown for Agents — serve clean Markdown to AI agents
# Set to "false" to disable Markdown generation entirely
export MARKDOWN_AGENTS_ENABLED="true"
# Content-signal policy — controls what AI agents are allowed to do with your content
# Values: "yes" or "no" for each signal
export MARKDOWN_AGENTS_AI_TRAIN="yes"
export MARKDOWN_AGENTS_SEARCH="yes"
export MARKDOWN_AGENTS_AI_INPUT="yes"
MDEOF
fi
# Bridge ActivityPub handle to Eleventy theme for rel="me" link in h-card
# Priority: explicit ACTIVITYPUB_HANDLE > AP_ACTOR_HANDLE > extracted from indiekit config
if [[ -z "${ACTIVITYPUB_HANDLE:-}" && -z "${AP_ACTOR_HANDLE:-}" ]]; then
# Extract handle from the activitypub plugin section of indiekit config
AP_HANDLE_FROM_CONFIG=$(sed -n '/indiekit-endpoint-activitypub/,/^[[:space:]]*}/{ s/.*handle:[[:space:]]*"\([^"]*\)".*/\1/p; }' /app/data/config/indiekit.config.js 2>/dev/null | head -1)
export ACTIVITYPUB_HANDLE="${AP_HANDLE_FROM_CONFIG}"
else
export ACTIVITYPUB_HANDLE="${ACTIVITYPUB_HANDLE:-${AP_ACTOR_HANDLE:-}}"
fi
# Indiekit core configuration
export MONGODB_URL="${CLOUDRON_MONGODB_URL}"
export PORT=8080 # Indiekit runs on internal port, nginx proxies
# Generate and persist SECRET if not exists (used for JWT signing)
if [[ ! -f /app/data/config/.secret ]]; then
openssl rand -hex 32 > /app/data/config/.secret
fi
export SECRET="$(cat /app/data/config/.secret)"
# App URL from Cloudron
export CLOUDRON_APP_URL="${CLOUDRON_APP_ORIGIN}"
export SITE_URL="${CLOUDRON_APP_ORIGIN}"
export SITE_ME="${CLOUDRON_APP_ORIGIN}"
echo "==> Setting permissions"
chown -R cloudron:cloudron /app/data
# Setup nginx first (needed for health checks)
cp /app/pkg/nginx.conf /run/nginx.conf
mkdir -p /run/nginx-client-body /run/nginx-proxy /run/nginx-fastcgi /run/nginx-uwsgi /run/nginx-scgi /run/nginx-ap-cache
echo "==> Starting nginx on port 3000"
nginx -c /run/nginx.conf &
# Start Indiekit in background first (so API is available for Eleventy build)
# Heap: 1024MB for Indiekit + plugins. If crashing at startup, check /tmp for heap snapshots.
# --heapsnapshot-near-heap-limit=1: auto-snapshot before OOM (writes to --diagnostic-dir)
# --heapsnapshot-signal=SIGUSR2: manual snapshot via kill -USR2 <pid>
# --abort-on-uncaught-exception: core dump on unhandled errors
# Remove readiness signal BEFORE Indiekit starts — plugins check on init
rm -f /app/data/.indiekit-ready
echo "==> Starting Indiekit on port ${PORT} (heap: 1536MB, diagnostic snapshots enabled)"
# CWD must be writable — V8 --heap-snapshot-on-oom writes to CWD.
# /app/code is read-only at runtime on Cloudron.
mkdir -p /tmp/indiekit-diag
cd /tmp/indiekit-diag
gosu cloudron:cloudron env NODE_OPTIONS="--max-old-space-size=1536 --heapsnapshot-signal=SIGUSR2 --diagnostic-dir=/tmp/indiekit-diag" node --heap-snapshot-on-oom /app/code/node_modules/@indiekit/indiekit/bin/cli.js serve --config /app/data/config/indiekit.config.js &
INDIEKIT_PID=$!
# Monitor Indiekit process for crashes (background)
(
wait $INDIEKIT_PID 2>/dev/null
EXIT_CODE=$?
echo "[INDIEKIT CRASH] Process exited with code ${EXIT_CODE} at $(date '+%Y-%m-%d %H:%M:%S')"
# Check for heap snapshots (V8 writes to CWD, Node writes to --diagnostic-dir)
SNAPSHOTS=$(ls /tmp/indiekit-diag/*.heapsnapshot 2>/dev/null)
if [ -n "$SNAPSHOTS" ]; then
echo "[INDIEKIT CRASH] Heap snapshot(s) written:"
ls -lh /tmp/indiekit-diag/*.heapsnapshot 2>/dev/null
# Copy to persistent storage for analysis
cp /tmp/indiekit-diag/*.heapsnapshot /app/data/config/ 2>/dev/null
echo "[INDIEKIT CRASH] Snapshot(s) copied to /app/data/config/ for retrieval"
else
echo "[INDIEKIT CRASH] No heap snapshots found in /tmp/indiekit-diag/"
fi
echo "[INDIEKIT CRASH] RSS at exit: $(cat /proc/$INDIEKIT_PID/status 2>/dev/null | grep VmRSS || echo 'process gone')"
) &
# Wait for Indiekit to be ready (max 30 seconds)
echo "==> Waiting for Indiekit to be ready..."
for i in {1..30}; do
if curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/ | grep -q "200\|302"; then
echo "==> Indiekit is ready"
break
fi
sleep 1
done
# Wait extra time for API endpoints to initialize (plugins need to register routes)
echo "==> Waiting for API endpoints to initialize..."
sleep 3
# Verify Funkwhale API is available (if configured)
if [ -n "${FUNKWHALE_TOKEN:-}" ]; then
for i in {1..10}; do
if curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/funkwhaleapi/api/now-playing 2>/dev/null | grep -q "200"; then
echo "==> Funkwhale API is ready"
break
fi
sleep 1
done
fi
# Verify Last.fm API is available (if configured)
if [ -n "${LASTFM_API_KEY:-}" ]; then
for i in {1..10}; do
if curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/lastfmapi/api/now-playing 2>/dev/null | grep -q "200"; then
echo "==> Last.fm API is ready"
break
fi
sleep 1
done
fi
# Verify GitHub starred API is available (if configured)
if [ -n "${GITHUB_TOKEN:-}" ]; then
for i in {1..10}; do
if curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/githubapi/api/starred/all 2>/dev/null | grep -q "200"; then
echo "==> GitHub starred API is ready"
break
fi
sleep 1
done
fi
# ─── Start background pollers early (they only need Indiekit, not Eleventy) ───
# Start syndication background process
# Polls the syndicate endpoint every 2 minutes to process pending syndications
echo "==> Starting syndication background process"
(
echo "[syndication] Starting auto-syndication polling"
while true; do
# Safety net: verify the site is serving before attempting syndication.
# During initial Eleventy build (~9 min after restart), pages don't exist yet.
SITE_STATUS=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "${CLOUDRON_APP_ORIGIN}/" 2>/dev/null)
if [ "$SITE_STATUS" != "200" ]; then
echo "[syndication] $(date '+%Y-%m-%d %H:%M:%S') - Site not ready (HTTP $SITE_STATUS), skipping cycle"
sleep 120
continue
fi
# Read SECRET from file (env var not available in subshell)
SYNDICATION_SECRET=$(cat /app/data/config/.secret 2>/dev/null)
SYNDICATION_ORIGIN="${CLOUDRON_APP_ORIGIN}"
if [ -n "$SYNDICATION_SECRET" ]; then
# Generate a short-lived JWT token with update scope
# Uses env vars instead of shell interpolation to prevent injection
SYNDICATION_TOKEN=$(cd /app/code && JWT_ORIGIN="$SYNDICATION_ORIGIN" JWT_SECRET="$SYNDICATION_SECRET" node -e "
const jwt = require('jsonwebtoken');
const token = jwt.sign(
{ me: process.env.JWT_ORIGIN, scope: 'update' },
process.env.JWT_SECRET,
{ expiresIn: '5m' }
);
console.log(token);
" 2>/dev/null)
if [ -n "$SYNDICATION_TOKEN" ]; then
# Call syndicate endpoint - this processes posts with mp-syndicate-to
RESULT=$(curl -s -X POST "http://localhost:8080/syndicate?token=${SYNDICATION_TOKEN}" \
-H "Content-Type: application/json" 2>&1)
echo "[syndication] $(date '+%Y-%m-%d %H:%M:%S') - $RESULT"
fi
fi
# Wait 2 minutes before next check
sleep 120
done
) &
# Start webmention sender background process
# Polls the webmention-sender endpoint every 5 minutes to send pending webmentions
echo "==> Starting webmention sender background process"
(
echo "[webmention] Starting auto-send polling"
# Wait 3 minutes before first run (let Eleventy build complete first)
sleep 180
while true; do
# Safety net: verify the site is serving before attempting to send webmentions.
# The real per-post URL check is in the controller, but this avoids unnecessary
# JWT generation and HTTP calls when the site is completely down.
SITE_STATUS=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "${CLOUDRON_APP_ORIGIN}/" 2>/dev/null)
if [ "$SITE_STATUS" != "200" ]; then
echo "[webmention] $(date '+%Y-%m-%d %H:%M:%S') - Site not ready (HTTP $SITE_STATUS), skipping cycle"
sleep 300
continue
fi
# Read SECRET from file (env var not available in subshell)
WEBMENTION_SECRET=$(cat /app/data/config/.secret 2>/dev/null)
WEBMENTION_ORIGIN="${CLOUDRON_APP_ORIGIN}"
if [ -n "$WEBMENTION_SECRET" ]; then
# Generate a short-lived JWT token with update scope
# Uses env vars instead of shell interpolation to prevent injection
WEBMENTION_TOKEN=$(cd /app/code && JWT_ORIGIN="$WEBMENTION_ORIGIN" JWT_SECRET="$WEBMENTION_SECRET" node -e "
const jwt = require('jsonwebtoken');
const token = jwt.sign(
{ me: process.env.JWT_ORIGIN, scope: 'update' },
process.env.JWT_SECRET,
{ expiresIn: '5m' }
);
console.log(token);
" 2>/dev/null)
if [ -n "$WEBMENTION_TOKEN" ]; then
# Call webmention-sender endpoint - this sends webmentions for posts
RESULT=$(curl -s -X POST "http://localhost:8080/webmention-sender?token=${WEBMENTION_TOKEN}" \
-H "Content-Type: application/json" 2>&1)
echo "[webmention] $(date '+%Y-%m-%d %H:%M:%S') - $RESULT"
fi
fi
# Wait 5 minutes before next check
sleep 300
done
) &
# ─── Zero-downtime Eleventy build with atomic release swap ───
# Old site continues serving while new build runs. Swap is atomic (single syscall).
# Ensure /app/data/site is a symlink to a release directory
# Migration: if /app/data/site is a real directory (pre-atomic-swap), convert it
if [ -d /app/data/site ] && [ ! -L /app/data/site ]; then
echo "==> Migrating /app/data/site from directory to release symlink"
MIGRATION_TS=$(date +%s)
mv /app/data/site "/app/data/releases/${MIGRATION_TS}"
ln -s "/app/data/releases/${MIGRATION_TS}" /app/data/site
chown -h cloudron:cloudron /app/data/site
echo "==> Migration complete: site -> releases/${MIGRATION_TS}"
fi
# First-ever run: no symlink and no directory exist yet
if [ ! -L /app/data/site ] && [ ! -d /app/data/site ]; then
echo "==> First run: creating placeholder release"
mkdir -p /app/data/releases/placeholder
echo '<html><head><meta http-equiv="refresh" content="5"></head><body><p>Building site...</p></body></html>' > /app/data/releases/placeholder/index.html
chown -R cloudron:cloudron /app/data/releases/placeholder
ln -s /app/data/releases/placeholder /app/data/site
chown -h cloudron:cloudron /app/data/site
fi
# At this point /app/data/site is a symlink → previous release → nginx serves old site
CURRENT_RELEASE=$(readlink -f /app/data/site)
echo "==> Current release: ${CURRENT_RELEASE}"
echo "==> Old site continues serving while new build runs"
# Eleventy-fetch cache is NOT wiped on deploy. Each entry has its own TTL
# (duration: "1d" for build, "30d" for watch) and expires naturally.
# Wiping forces ALL _data files to re-fetch from APIs simultaneously,
# which causes OOM during the initial build (2,352 posts + fresh API data
# exceeds the 2048MB heap within the 3072MB cgroup limit).
# If you need to force a fresh fetch, delete specific cache files manually.
# Initial build DISABLED — consistently OOMs because Eleventy (3.9GB peak RSS from
# V8 heap + Sharp buffers + OG WASM) + Indiekit (~370MB) exceeds the 4GB cgroup.
# The watcher always succeeds because it starts after the initial build process exits,
# freeing all memory. The old release serves during the watcher's ~5 min full build.
# To re-enable: uncomment the block below and comment the INITIAL_BUILD_OK=false line.
INITIAL_BUILD_OK=false
cd /app/pkg/eleventy-site
export DEBUG="Eleventy:Benchmark*"
# # Build new release to a timestamped directory
# RELEASE_TS=$(date +%s)
# NEW_RELEASE="/app/data/releases/${RELEASE_TS}"
# mkdir -p "${NEW_RELEASE}"
# chown cloudron:cloudron "${NEW_RELEASE}"
#
# echo "==> Building Eleventy site to ${NEW_RELEASE}"
# export NODE_OPTIONS="--max-old-space-size=2560"
# INITIAL_BUILD_OK=false
# # Pagefind runs inside Eleventy's eleventy.after hook (non-incremental builds only)
# gosu cloudron:cloudron node --heap-snapshot-on-oom ./node_modules/.bin/eleventy --output="${NEW_RELEASE}" && INITIAL_BUILD_OK=true || {
# echo "==> Eleventy build failed (likely OOM-killed)"
# SNAP=$(ls -t /tmp/*.heapsnapshot 2>/dev/null | head -1)
# if [ -n "$SNAP" ]; then
# SNAP_SIZE=$(du -h "$SNAP" | cut -f1)
# echo "==> Heap snapshot captured: $SNAP ($SNAP_SIZE)"
# fi
# }
# Only swap if build succeeded — keep serving the old release on failure
if [ "$INITIAL_BUILD_OK" = true ]; then
# Sync OG images from persistent cache to new release.
# eleventy.before generates OG images to .cache/og/ (→ /app/data/cache/og/),
# but passthrough copy may miss them when --output differs from _site symlink.
if [ -d /app/data/cache/og ]; then
echo "==> Syncing OG images from cache to new release"
mkdir -p "${NEW_RELEASE}/og"
cp -f /app/data/cache/og/*.png "${NEW_RELEASE}/og/" 2>/dev/null || true
OG_COUNT=$(ls -1 "${NEW_RELEASE}/og/"*.png 2>/dev/null | wc -l)
echo "==> Synced ${OG_COUNT} OG images"
fi
echo "==> Setting permissions on new release"
chown -R cloudron:cloudron "${NEW_RELEASE}"
# Atomic swap: create temp symlink, then rename over current (rename(2) is atomic)
echo "==> Atomic swap: site -> releases/${RELEASE_TS}"
ln -s "${NEW_RELEASE}" /app/data/site_tmp
chown -h cloudron:cloudron /app/data/site_tmp
mv -T /app/data/site_tmp /app/data/site
# Reload nginx to resolve the new symlink target
nginx -s reload
echo "==> nginx reloaded, new release is live"
# Signal readiness — plugins can now start background tasks
touch /app/data/.indiekit-ready
chown cloudron:cloudron /app/data/.indiekit-ready
echo "==> Readiness signal created, plugins starting deferred tasks"
# Cleanup: keep only 2 most recent releases for rollback capability
echo "==> Cleaning up old releases (keeping 2)"
cd /app/data/releases && ls -1t | tail -n +3 | xargs -r rm -rf
else
echo "==> Initial build skipped/failed, keeping previous release: ${CURRENT_RELEASE}"
# Clean up the failed release directory (if one was created)
if [ -n "${NEW_RELEASE:-}" ]; then rm -rf "${NEW_RELEASE}"; fi
# Note: readiness signal is NOT created here — the watcher will do a full
# build on start and the eleventy.after hook creates the signal file when
# that build completes. This ensures plugins don't start until the system
# is truly stable (watcher running + build finished).
fi
# Start Eleventy in watch+incremental mode to rebuild only affected pages on content changes
# Wrapped in a supervisor loop that restarts on crash with exponential backoff
# The watcher writes to /app/data/site (current release via symlink)
# Watcher does a full build on first start, then switches to incremental mode.
# Needs same heap as initial build for that first pass. Runs after initial build
# completes, so never concurrent — 2048MB is safe within 3072MB cgroup.
# --expose-gc allows eleventy.config.js to call global.gc() after each build,
# forcing V8 to release freed heap pages back to the OS via madvise(MADV_DONTNEED).
# Without this, post-build allocations stay resident because watch mode has no
# allocation pressure to trigger GC naturally.
# --heapsnapshot-signal=SIGUSR2: for on-demand heap snapshot analysis.
# Heap at 2560 — watcher's initial full build peaks above 2304MB V8 heap (3,400
# pages in memory). Needs 3.5GB+ cgroup: watcher ~2800 peak + Indiekit ~600 = ~3400.
# Steady state after build is ~2300MB total.
export NODE_OPTIONS="--max-old-space-size=2560 --expose-gc --heapsnapshot-signal=SIGUSR2 --diagnostic-dir=/tmp"
# Syndication webhook — Eleventy triggers syndication immediately after incremental builds
export SYNDICATE_WEBHOOK_URL="http://localhost:8080/syndicate"
export SYNDICATE_SECRET_FILE="/app/data/config/.secret"
echo "==> Starting Eleventy watcher for auto-rebuild (heap: 2560MB, expose-gc)"
(
set +e # Disable errexit so the retry loop survives crashes
cd /app/pkg/eleventy-site
RESTART_COUNT=0
BACKOFF=5
MAX_BACKOFF=300
LAST_START=0
while true; do
NOW=$(date +%s)
# Reset backoff if the watcher ran for at least 5 minutes (healthy run)
if [ $LAST_START -gt 0 ] && [ $((NOW - LAST_START)) -ge 300 ]; then
RESTART_COUNT=0
BACKOFF=5
fi
LAST_START=$NOW
RESTART_COUNT=$((RESTART_COUNT + 1))
if [ $RESTART_COUNT -eq 1 ]; then
echo "[eleventy-watcher] Starting watcher"
else
echo "[eleventy-watcher] Restarting watcher (attempt $RESTART_COUNT, backoff ${BACKOFF}s)"
sleep $BACKOFF
# Exponential backoff: 5, 10, 20, 40, 80, 160, 300 (capped)
BACKOFF=$((BACKOFF * 2))
if [ $BACKOFF -gt $MAX_BACKOFF ]; then
BACKOFF=$MAX_BACKOFF
fi
fi
# Use absolute path — gosu's exec may not resolve relative paths from subshell cwd
gosu cloudron:cloudron /app/pkg/eleventy-site/node_modules/.bin/eleventy \
--watch --incremental --output=/app/data/site
EXIT_CODE=$?
echo "[eleventy-watcher] Watcher exited with code $EXIT_CODE at $(date '+%Y-%m-%d %H:%M:%S')"
done
) &
# Memory monitor — logs RSS for all Node.js processes every 10 minutes.
# Helps detect slow memory leaks over days. Output appears in `cloudron logs`.
# To analyze: cloudron logs --app rmendes.net | grep '\[mem-monitor\]'
(
MONITOR_INTERVAL=600 # 10 minutes
while true; do
sleep $MONITOR_INTERVAL
INDIEKIT_RSS=$(cat /proc/${INDIEKIT_PID}/status 2>/dev/null | grep ^VmRSS | awk '{print $2}')
INDIEKIT_SWAP=$(cat /proc/${INDIEKIT_PID}/status 2>/dev/null | grep ^VmSwap | awk '{print $2}')
# Find watcher PID dynamically (it may restart)
WATCHER_PID=$(pgrep -f "eleventy.*--watch" 2>/dev/null | head -1)
if [ -n "$WATCHER_PID" ]; then
WATCHER_RSS=$(cat /proc/${WATCHER_PID}/status 2>/dev/null | grep ^VmRSS | awk '{print $2}')
WATCHER_SWAP=$(cat /proc/${WATCHER_PID}/status 2>/dev/null | grep ^VmSwap | awk '{print $2}')
else
WATCHER_RSS="N/A"; WATCHER_SWAP="N/A"
fi
CGROUP_USED=$(cat /sys/fs/cgroup/memory.current 2>/dev/null)
CGROUP_MB=$((CGROUP_USED / 1024 / 1024))
echo "[mem-monitor] indiekit=${INDIEKIT_RSS}kB+${INDIEKIT_SWAP}kBswap eleventy=${WATCHER_RSS}kB+${WATCHER_SWAP}kBswap cgroup=${CGROUP_MB}MB"
done
) &
# Indiekit watchdog — auto-restart on crash (e.g., OOM during Eleventy build)
echo "==> All services started, watching Indiekit..."
while true; do
wait $INDIEKIT_PID
EXIT_CODE=$?
echo "==> Indiekit exited with code ${EXIT_CODE} — restarting in 5 seconds..."
sleep 5
# Restart Indiekit
cd /app/code
gosu cloudron:cloudron env NODE_OPTIONS="--max-old-space-size=1024" node node_modules/@indiekit/indiekit/bin/cli.js serve --config /app/data/config/indiekit.config.js &
INDIEKIT_PID=$!
# Wait for it to be ready before looping back to watch
for i in {1..30}; do
if curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/ | grep -q "200\|302"; then
echo "==> Indiekit restarted successfully (PID ${INDIEKIT_PID})"
break
fi
sleep 1
done
done