-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathstart.sh
More file actions
423 lines (365 loc) · 14.6 KB
/
start.sh
File metadata and controls
423 lines (365 loc) · 14.6 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
#!/bin/sh
# SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
# SPDX-License-Identifier: AGPL-3.0-or-later
set -e
# ----------------------------------------------------------------------------
# start.sh
# - Generates self-signed certificates for FRP Server and FRP Clients
# - Generates haproxy.cfg from haproxy.cfg.template (in /run/harp if available)
# - Reads HP_SHARED_KEY or HP_SHARED_KEY_FILE
# - Comments out HTTPS frontends if no /certs/cert.pem is found
# - Starts FRP server (frps) on HP_FRP_ADDRESS
# - Starts the Python SPOE agent on HP_SPOA_ADDRESS
# - Launches Python SPOE HTTP Control API on 127.0.0.1:8200
# - Finally runs HAProxy in the foreground
#
# NOTE:
# Certificates are generated in the /certs/frp folder - they are used only by FRP and AppAPI.
# If HP_FRP_DISABLE_TLS is set to "false"(default), self-signed certificates will be generated:
# - CA key and certificate (ca.key, ca.crt)
# - Server key, CSR, and certificate (server.key, server.csr, server.crt)
# - Client key, CSR, and certificate (client.key, client.csr, client.crt)
# We do not generate /certs/cert.pem file, as for HaProxy it is admin task to mount generated cert if needed.
# ----------------------------------------------------------------------------
HP_WAIT_AGENT_HTTP=${HP_WAIT_AGENT_HTTP:-60}
HP_WAIT_SPOA=${HP_WAIT_SPOA:-60}
HP_WAIT_FRP=${HP_WAIT_FRP:-30}
HP_WAIT_INTERVAL=${HP_WAIT_INTERVAL:-0.5}
HP_VERBOSE_START=${HP_VERBOSE_START:-1}
log() {
if [ "$HP_VERBOSE_START" -eq 1 ]; then
echo "$@"
fi
}
# ----------------------------------------------------------------------------
# Determine config directory - use /run/harp if available (for read-only rootfs)
# If user mounted config files at root, use root paths for backward compatibility
# ----------------------------------------------------------------------------
CFG_DIR=""
if [ -f "/haproxy.cfg" ] || [ -f "/frps.toml" ] || [ -f "/frpc-docker.toml" ]; then
log "INFO: Found user-provided config file(s) at root, using root paths."
elif [ -d "/run/harp" ] || mkdir -p /run/harp 2>/dev/null; then
CFG_DIR="/run/harp"
fi
# ----------------------------------------------------------------------------
# Helper function to strip surrounding quotes from a string.
# This is useful because users sometimes accidentally include quotes in
# docker-compose environment variables (e.g., HP_SHARED_KEY="secret").
# In YAML, this includes the literal quotes in the value.
# ----------------------------------------------------------------------------
strip_quotes() {
# Remove leading and trailing double or single quotes
echo "$1" | sed -e 's/^"//' -e 's/"$//' -e "s/^'//" -e "s/'$//"
}
wait_for_tcp() {
# $1 host, $2 port, $3 timeout(s), $4 interval(s)
host="$1"; port="$2"; timeout="${3:-30}"; interval="${4:-0.5}"
start_ts="$(date +%s)"
while :; do
if nc -z -w 1 "$host" "$port" >/dev/null 2>&1; then
return 0
fi
now="$(date +%s)"; elapsed=$(( now - start_ts ))
if [ "$elapsed" -ge "$timeout" ]; then
echo "ERROR: Timeout waiting for TCP $host:$port to become ready (after ${timeout}s)."
return 1
fi
sleep "$interval"
done
}
wait_for_http() {
# $1 url, $2 timeout(s), $3 interval(s)
url="$1"; timeout="${2:-60}"; interval="${3:-0.5}"
start_ts="$(date +%s)"
while :; do
if curl -fsS --max-time 2 "$url" >/dev/null 2>&1; then
return 0
fi
now="$(date +%s)"; elapsed=$(( now - start_ts ))
if [ "$elapsed" -ge "$timeout" ]; then
echo "ERROR: Timeout waiting for HTTP $url to become ready (after ${timeout}s)."
return 1
fi
sleep "$interval"
done
}
# ----------------------------------------------------------------------------
# Resolve HP_SHARED_KEY once for the whole process (env or file)
# ----------------------------------------------------------------------------
if [ -n "$HP_SHARED_KEY" ] && [ -n "$HP_SHARED_KEY_FILE" ]; then
echo "ERROR: Only one of HP_SHARED_KEY or HP_SHARED_KEY_FILE should be specified."
exit 1
fi
if [ -z "$HP_SHARED_KEY" ] && [ -n "$HP_SHARED_KEY_FILE" ]; then
if [ ! -f "$HP_SHARED_KEY_FILE" ]; then
echo "ERROR: HP_SHARED_KEY_FILE is specified but the file does not exist."
exit 1
fi
if [ ! -s "$HP_SHARED_KEY_FILE" ]; then
echo "ERROR: HP_SHARED_KEY_FILE is specified but is empty."
exit 1
fi
HP_SHARED_KEY="$(cat "$HP_SHARED_KEY_FILE")"
fi
if [ -z "$HP_SHARED_KEY" ]; then
echo "ERROR: Either HP_SHARED_KEY or HP_SHARED_KEY_FILE must be set."
exit 1
fi
# Validate HP_SHARED_KEY contains only ASCII characters (required by SPOE library)
NON_ASCII_COUNT=$(printf '%s' "$HP_SHARED_KEY" | LC_ALL=C tr -d '\040-\176' | wc -c)
if [ "$NON_ASCII_COUNT" -gt 0 ]; then
echo "ERROR: HP_SHARED_KEY contains non-ASCII characters."
echo "Please use only printable ASCII characters (a-z, A-Z, 0-9, and symbols like !@#\$%^&*...)."
exit 1
fi
# Strip surrounding quotes if user accidentally included them in env vars
HP_SHARED_KEY="$(strip_quotes "$HP_SHARED_KEY")"
export HP_SHARED_KEY
# Strip surrounding quotes from other commonly affected environment variables
NC_INSTANCE_URL="$(strip_quotes "$NC_INSTANCE_URL")"
HP_FRP_ADDRESS="$(strip_quotes "$HP_FRP_ADDRESS")"
HP_EXAPPS_ADDRESS="$(strip_quotes "${HP_EXAPPS_ADDRESS:-}")"
HP_EXAPPS_HTTPS_ADDRESS="$(strip_quotes "${HP_EXAPPS_HTTPS_ADDRESS:-}")"
export NC_INSTANCE_URL HP_FRP_ADDRESS HP_EXAPPS_ADDRESS HP_EXAPPS_HTTPS_ADDRESS
# Check if the required environment variables are set
if [ -z "$HP_FRP_ADDRESS" ]; then
echo "ERROR: HP_FRP_ADDRESS is not set."
exit 1
fi
if [ -z "$NC_INSTANCE_URL" ]; then
echo "ERROR: NC_INSTANCE_URL is not set."
exit 1
fi
# Initialize FRP_HOST and FRP_PORT once to avoid parsing HP_FRP_ADDRESS multiple times.
FRP_HOST="$(echo "$HP_FRP_ADDRESS" | cut -d':' -f1)"
FRP_PORT="$(echo "$HP_FRP_ADDRESS" | cut -d':' -f2)"
# Initialize SPOA_HOST and SPOA_PORT from HP_SPOA_ADDRESS (default 127.0.0.1:9600).
HP_SPOA_ADDRESS="${HP_SPOA_ADDRESS:-127.0.0.1:9600}"
SPOA_HOST="$(echo "$HP_SPOA_ADDRESS" | cut -d':' -f1)"
SPOA_PORT="$(echo "$HP_SPOA_ADDRESS" | cut -d':' -f2)"
# ----------------------------------------------------------------------------
# Map HP_LOG_LEVEL (our user-friendly strings) to valid HAProxy log levels
# ----------------------------------------------------------------------------
case "${HP_LOG_LEVEL}" in
debug)
HP_LOG_LEVEL_HAPROXY="debug"
;;
info)
HP_LOG_LEVEL_HAPROXY="info"
;;
warning)
HP_LOG_LEVEL_HAPROXY="warning"
;;
error)
HP_LOG_LEVEL_HAPROXY="err"
;;
*)
echo "WARNING: Unrecognized HP_LOG_LEVEL='${HP_LOG_LEVEL}', defaulting to 'warning'"
HP_LOG_LEVEL_HAPROXY="warning"
;;
esac
export HP_LOG_LEVEL_HAPROXY
# ----------------------------------------------------------------------------
# Generate self-signed certs for FRP unless HP_FRP_DISABLE_TLS=true
# ----------------------------------------------------------------------------
if [ "${HP_FRP_DISABLE_TLS}" != "true" ]; then
if [ ! -d "/certs/frp" ]; then
mkdir -p /certs/frp
log "INFO: /certs/frp directory created."
log "INFO: Generating self-signed certificates in /certs/frp..."
# Write OpenSSL configuration for server to /certs/frp/server-openssl.cnf.
cat > /certs/frp/server-openssl.cnf <<EOF
[ req ]
default_bits = 2048
default_md = sha256
prompt = no
distinguished_name = dn
req_extensions = req_ext
[ dn ]
CN = harp.nc
[ req_ext ]
subjectAltName = DNS:harp.nc
EOF
# Generate CA key and certificate.
openssl genrsa -out /certs/frp/ca.key 2048
openssl req -x509 -new -nodes -key /certs/frp/ca.key -subj "/CN=harp.nc" -days 5000 -out /certs/frp/ca.crt
# Generate server key and CSR.
openssl genrsa -out /certs/frp/server.key 2048
openssl req -new -sha256 -key /certs/frp/server.key -subj "/CN=harp.nc" \
-reqexts req_ext -config /certs/frp/server-openssl.cnf -out /certs/frp/server.csr
# Sign the server certificate with the CA.
openssl x509 -req -days 365 -sha256 -in /certs/frp/server.csr \
-CA /certs/frp/ca.crt -CAkey /certs/frp/ca.key -CAcreateserial \
-extfile /certs/frp/server-openssl.cnf -extensions req_ext -out /certs/frp/server.crt
# Generate client key.
openssl genrsa -out /certs/frp/client.key 2048
# Write OpenSSL configuration for client to /certs/frp/client-openssl.cnf.
cat > /certs/frp/client-openssl.cnf <<EOF
[ req ]
default_bits = 2048
default_md = sha256
prompt = no
distinguished_name = dn
req_extensions = req_ext
[ dn ]
CN = harp.client.nc
[ req_ext ]
subjectAltName = DNS:harp.client.nc
EOF
# Generate client CSR & sign with CA.
openssl req -new -sha256 -key /certs/frp/client.key -subj "/CN=harp.client.nc" \
-config /certs/frp/client-openssl.cnf -out /certs/frp/client.csr
openssl x509 -req -days 365 -sha256 -in /certs/frp/client.csr \
-CA /certs/frp/ca.crt -CAkey /certs/frp/ca.key -CAcreateserial \
-extfile /certs/frp/client-openssl.cnf -extensions req_ext -out /certs/frp/client.crt
log "INFO: Certificate generation completed."
fi
else
log "INFO: HP_FRP_DISABLE_TLS is set to true. Skipping certificate generation."
fi
# ----------------------------------------------------------------------------
# Generate final haproxy.cfg if not already present
# ----------------------------------------------------------------------------
if [ -f "${CFG_DIR}/haproxy.cfg" ]; then
log "INFO: ${CFG_DIR}/haproxy.cfg already present. Skipping config generation..."
else
log "INFO: Creating ${CFG_DIR}/haproxy.cfg from haproxy.cfg.template..."
# Use envsubst to render the main configuration.
envsubst < /haproxy.cfg.template > "${CFG_DIR}/haproxy.cfg"
# If we do not have a SSL cert for HAProxy, comment out the HTTPS frontends
if [ -f "/certs/cert.pem" ]; then
log "INFO: Found /certs/cert.pem, HTTPS frontends remain enabled."
sed -i "/_HTTPS_FRONTEND_/ s|_HTTPS_FRONTEND_ ||g" "${CFG_DIR}/haproxy.cfg"
chmod 644 /certs/cert.pem
else
log "INFO: No /certs/cert.pem found, disabling HTTPS frontends..."
sed -i "/_HTTPS_FRONTEND_/ s|^|#|g" "${CFG_DIR}/haproxy.cfg"
fi
fi
if [ "$HP_VERBOSE_START" -eq 1 ]; then
log "INFO: Final ${CFG_DIR}/haproxy.cfg:"
cat "${CFG_DIR}/haproxy.cfg"
fi
# ----------------------------------------------------------------------------
# Prepare FRP configuration
# ----------------------------------------------------------------------------
if [ ! -f "${CFG_DIR}/frps.toml" ]; then
if [ "${HP_FRP_DISABLE_TLS}" != "true" ]; then
cat <<EOF >"${CFG_DIR}/frps.toml"
bindAddr = "${FRP_HOST}"
bindPort = ${FRP_PORT}
proxyBindAddr = "127.0.0.1"
transport.tls.force = true
transport.tls.certFile = "/certs/frp/server.crt"
transport.tls.keyFile = "/certs/frp/server.key"
transport.tls.trustedCaFile = "/certs/frp/ca.crt"
log.to = "${CFG_DIR}/frps.log"
log.level = "info"
log.maxDays = 3
maxPortsPerClient = 1
allowPorts = [
{ start = 23000, end = 23999 },
{ start = 24000, end = 24099 }
]
[[httpPlugins]]
addr = "127.0.0.1:8200"
path = "/frp_handler"
ops = ["Login"]
EOF
else
cat <<EOF >"${CFG_DIR}/frps.toml"
bindAddr = "${FRP_HOST}"
bindPort = ${FRP_PORT}
proxyBindAddr = "127.0.0.1"
transport.tls.force = false
log.to = "${CFG_DIR}/frps.log"
log.level = "info"
log.maxDays = 3
maxPortsPerClient = 1
allowPorts = [
{ start = 23000, end = 23999 },
{ start = 24000, end = 24099 }
]
[[httpPlugins]]
addr = "127.0.0.1:8200"
path = "/frp_handler"
ops = ["Login"]
EOF
fi
log "INFO: FRP server configuration generated at ${CFG_DIR}/frps.toml."
if [ "$HP_VERBOSE_START" -eq 1 ]; then
log "INFO: Generated ${CFG_DIR}/frps.toml:"
cat "${CFG_DIR}/frps.toml"
fi
else
log "INFO: ${CFG_DIR}/frps.toml already exists. Skipping FRP server configuration generation..."
fi
# ----------------------------------------------------------------------------
# Prepare FRP client configuration for Docker if /var/run/docker.sock is present
# ----------------------------------------------------------------------------
if [ -e "/var/run/docker.sock" ]; then
LOCAL_FRP_HOST="$FRP_HOST"
[ "$LOCAL_FRP_HOST" = "0.0.0.0" ] && LOCAL_FRP_HOST="127.0.0.1"
if [ ! -f "${CFG_DIR}/frpc-docker.toml" ]; then
log "INFO: Detected /var/run/docker.sock, generating ${CFG_DIR}/frpc-docker.toml configuration file..."
if [ "${HP_FRP_DISABLE_TLS}" != "true" ]; then
cat <<EOF >"${CFG_DIR}/frpc-docker.toml"
serverAddr = "${LOCAL_FRP_HOST}"
serverPort = ${FRP_PORT}
transport.tls.enable = true
transport.tls.certFile = "/certs/frp/client.crt"
transport.tls.keyFile = "/certs/frp/client.key"
transport.tls.trustedCaFile = "/certs/frp/ca.crt"
transport.tls.serverName = "harp.nc"
metadatas.token = "${HP_SHARED_KEY}"
[[proxies]]
remotePort = 24000
type = "tcp"
name = "bundled-deploy-daemon"
[proxies.plugin]
type = "unix_domain_socket"
unixPath = "/var/run/docker.sock"
EOF
else
cat <<EOF >"${CFG_DIR}/frpc-docker.toml"
serverAddr = "${LOCAL_FRP_HOST}"
serverPort = ${FRP_PORT}
transport.tls.enable = false
metadatas.token = "${HP_SHARED_KEY}"
[[proxies]]
remotePort = 24000
type = "tcp"
name = "bundled-deploy-daemon"
[proxies.plugin]
type = "unix_domain_socket"
unixPath = "/var/run/docker.sock"
EOF
fi
if [ "$HP_VERBOSE_START" -eq 1 ]; then
log "INFO: Generated ${CFG_DIR}/frpc-docker.toml:"
cat "${CFG_DIR}/frpc-docker.toml"
fi
else
log "INFO: ${CFG_DIR}/frpc-docker.toml already exists. Skipping generation..."
fi
fi
log "INFO: Starting Python HaProxy Agent on 127.0.0.1:8200 and ${HP_SPOA_ADDRESS}..."
nohup python3 /usr/local/bin/haproxy_agent.py &
# Wait deterministically for the agent to be ready (HTTP) and for SPOA (TCP)
log "INFO: Waiting for HaRP Agent HTTP (GET http://127.0.0.1:8200/info) to be ready..."
wait_for_http "http://127.0.0.1:8200/info" "$HP_WAIT_AGENT_HTTP" "$HP_WAIT_INTERVAL"
log "INFO: Waiting for SPOA port ${HP_SPOA_ADDRESS}..."
wait_for_tcp "$SPOA_HOST" "$SPOA_PORT" "$HP_WAIT_SPOA" "$HP_WAIT_INTERVAL"
log "INFO: Starting FRP server on ${HP_FRP_ADDRESS}..."
frps -c "${CFG_DIR}/frps.toml" &
# Wait for FRP port to be listening before starting frpc
LOCAL_FRP_HOST="$FRP_HOST"
[ "$LOCAL_FRP_HOST" = "0.0.0.0" ] && LOCAL_FRP_HOST="127.0.0.1"
log "INFO: Waiting for FRP server port ${LOCAL_FRP_HOST}:${FRP_PORT}..."
wait_for_tcp "$LOCAL_FRP_HOST" "$FRP_PORT" "$HP_WAIT_FRP" "$HP_WAIT_INTERVAL"
if [ -e "/var/run/docker.sock" ]; then
log "INFO: Starting FRP client for Docker Engine..."
frpc -c "${CFG_DIR}/frpc-docker.toml" &
fi
log "INFO: Starting HAProxy..."
exec haproxy -f "${CFG_DIR}/haproxy.cfg" -W -db