Repository navigation
Expand file tree
/
Copy pathinstall.bash
More file actions
executable file
·320 lines (291 loc) · 14.5 KB
/
Copy pathinstall.bash
File metadata and controls
executable file
·320 lines (291 loc) · 14.5 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
#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────────────────
# ThingsPanel All-in-One — Linux / macOS 安装脚本
#
# 用法(推荐):
# curl -fsSL https://install.thingspanel.io/install.sh | sh
#
# 本地运行:
# chmod +x install.sh && ./install.sh
# ─────────────────────────────────────────────────────────────────────────────
set -eu
# ── 常量 ──────────────────────────────────────────────────────────────────────
RAW_BASE="https://install.thingspanel.io"
INSTALL_DIR="${INSTALL_DIR:-/opt/thingspanel}"
HTTP_PORT="${HTTP_PORT:-8080}"
MQTT_PORT="${MQTT_PORT:-1883}"
MIN_DOCKER_VERSION="20.10"
SUDO_CMD=""
UPDATE_ENGINE_SHA256="c47e5c54a6484af5171787c66fc08731dbd30bcbe9745e933f27350a3674c442"
# ── 颜色输出 ──────────────────────────────────────────────────────────────────
RED='\033[0;31m'; YELLOW='\033[1;33m'; GREEN='\033[0;32m'
BLUE='\033[0;34m'; BOLD='\033[1m'; RESET='\033[0m'
info() { echo -e "${BLUE}[INFO]${RESET} $*"; }
success() { echo -e "${GREEN}[OK]${RESET} $*"; }
warn() { echo -e "${YELLOW}[WARN]${RESET} $*"; }
error() { echo -e "${RED}[ERROR]${RESET} $*" >&2; exit 1; }
step() { echo -e "\n${BOLD}▶ $*${RESET}"; }
# ── 工具函数 ──────────────────────────────────────────────────────────────────
command_exists() { command -v "$1" >/dev/null 2>&1; }
check_existing_thingsvis_database() {
command_exists python3 || error "检查已有安装的数据源需要 Python 3;旧配置未修改。"
local old_compose_state
old_compose_state=$(python3 - "$INSTALL_DIR" <<'PY'
import os, stat, sys
try:
root = sys.argv[1]
root_info = os.lstat(root)
if not stat.S_ISDIR(root_info.st_mode): raise ValueError('not a directory')
path = os.path.join(root, 'docker-compose.yml')
metadata = os.lstat(path)
if not stat.S_ISREG(metadata.st_mode): raise ValueError('not a regular file')
with open(path, 'rb') as stream: stream.read(1)
print('present')
except FileNotFoundError:
print('missing')
except (OSError, ValueError):
sys.exit(1)
PY
) || error "无法读取已有 Compose 配置;旧配置未修改。"
[ "$old_compose_state" = present ] || return 0
if ! (set -o pipefail; cd "$INSTALL_DIR" && { rendered=$(docker compose config --format json 2>/dev/null) || rendered=$(docker compose config --no-interpolate --format json 2>/dev/null); } && printf '%s' "$rendered" | python3 -c '
import json, sys
from urllib.parse import urlsplit
def environment(value):
if isinstance(value, dict): return value
if isinstance(value, list):
result = {}
for item in value:
if not isinstance(item, str) or "=" not in item: raise ValueError()
key, val = item.split("=", 1)
if key in result: raise ValueError()
result[key] = val
return result
raise ValueError()
try:
services = json.load(sys.stdin)["services"]
vis = environment(services["thingsvis-server"]["environment"])
backend = environment(services["backend"]["environment"])
url = vis.get("DATABASE_URL")
if not isinstance(url, str): raise ValueError()
parsed_url = urlsplit(url)
if parsed_url.scheme not in ("postgres", "postgresql") or not parsed_url.hostname or "$" in parsed_url.hostname: raise ValueError()
required = ("GOTP_DB_PSQL_HOST", "GOTP_DB_PSQL_PORT", "GOTP_DB_PSQL_USERNAME", "GOTP_DB_PSQL_DBNAME")
if any(not isinstance(backend.get(key), (str, int)) or not str(backend[key]).strip() or "$" in str(backend[key]) for key in required): raise ValueError()
if backend["GOTP_DB_PSQL_HOST"] == "postgres" and not isinstance(services.get("postgres"), dict): raise ValueError()
selectors = ("GOTP_DB_PSQL_DBTYPE", "GOTP_DB_DRIVER", "GOTP_DB_PROVIDER", "GOTP_DB_TYPE", "DB_DRIVER", "DB_PROVIDER", "DB_TYPE", "DATABASE_TYPE", "DATABASE_PROVIDER", "DATABASE_DRIVER")
for key, value in backend.items():
name = str(key).upper()
if name.startswith(("GOTP_DB_MYSQL_", "GOTP_DB_MARIADB_")) and value not in (None, ""): raise ValueError()
if name in selectors and str(value).lower() not in ("postgres", "postgresql", "pg"): raise ValueError()
if name == "DATABASE_URL" and (not isinstance(value, str) or urlsplit(value).scheme not in ("postgres", "postgresql")): raise ValueError()
sys.exit(0)
except Exception:
sys.exit(1)
'); then
error "无法确认已有平台和 ThingsVis 使用受支持的 PostgreSQL 配置;旧配置未修改。"
fi
}
version_gte() {
printf '%s\n%s\n' "$2" "$1" | sort -V -c 2>/dev/null
}
run_privileged() {
if [ -n "$SUDO_CMD" ]; then
"$SUDO_CMD" "$@"
else
"$@"
fi
}
ensure_install_dir_access() {
step "检查安装目录权限"
if [ "$(id -u)" -eq 0 ]; then
success "当前用户可写入 $INSTALL_DIR"
return
fi
if [ -d "$INSTALL_DIR" ] && [ -w "$INSTALL_DIR" ]; then
success "当前用户可写入 $INSTALL_DIR"
return
fi
local parent_dir
parent_dir="$INSTALL_DIR"
while [ ! -d "$parent_dir" ]; do
local next_parent
next_parent="$(dirname "$parent_dir")"
if [ "$next_parent" = "$parent_dir" ]; then
break
fi
parent_dir="$next_parent"
done
if [ ! -d "$INSTALL_DIR" ] && [ -d "$parent_dir" ] && [ -w "$parent_dir" ]; then
success "当前用户可创建 $INSTALL_DIR"
return
fi
if ! command_exists sudo; then
error "当前用户没有权限写入 ${INSTALL_DIR},且未找到 sudo。请使用有权限的用户运行,或设置 INSTALL_DIR 到可写目录。"
fi
SUDO_CMD="sudo"
info "${INSTALL_DIR} 需要管理员权限,接下来会通过 sudo 创建和写入安装文件。"
run_privileged -v || error "无法获取 sudo 权限,安装已停止"
success "已获得安装目录写入权限"
}
run_safe_update() {
command_exists python3 || error "安装需要 Python 3;现有配置未修改。"
python3 -c 'import sys; sys.exit(0 if sys.version_info >= (3, 8) else 1)' || error "安装需要 Python 3.8 或更新版本;现有配置未修改。"
local engine="" temporary="" candidate="" directory=""
if [ -n "${BASH_SOURCE[0]:-}" ] && [ -f "${BASH_SOURCE[0]}" ]; then
directory="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
candidate="$directory/config/native/update.py"
fi
if [ -n "$candidate" ] && [ -f "$candidate" ] && python3 - "$candidate" "$UPDATE_ENGINE_SHA256" <<'PY'
import hashlib, pathlib, sys
sys.exit(0 if hashlib.sha256(pathlib.Path(sys.argv[1]).read_bytes()).hexdigest() == sys.argv[2] else 1)
PY
then
engine="$candidate"
else
temporary="$(mktemp -d "${TMPDIR:-/tmp}/thingspanel-updater.XXXXXX")"
engine="$temporary/update.py"
if command_exists curl; then
curl -fsSL --connect-timeout 15 --max-time 180 "$RAW_BASE/config/native/update.py" -o "$engine" || { rm -rf "$temporary"; error "更新器下载失败;现有配置未修改。"; }
elif command_exists wget; then
wget -q --timeout=180 -O "$engine" "$RAW_BASE/config/native/update.py" || { rm -rf "$temporary"; error "更新器下载失败;现有配置未修改。"; }
else
rm -rf "$temporary"
error "需要 curl 或 wget;现有配置未修改。"
fi
if ! python3 - "$engine" "$UPDATE_ENGINE_SHA256" <<'PY'
import hashlib, pathlib, sys
sys.exit(0 if hashlib.sha256(pathlib.Path(sys.argv[1]).read_bytes()).hexdigest() == sys.argv[2] else 1)
PY
then
rm -rf "$temporary"
error "更新器内容与本入口固定摘要不一致;现有配置未修改。"
fi
fi
local args=(python3 "$engine" --root "$INSTALL_DIR" --base-url "$RAW_BASE")
if [ -n "${TP_VERSION:-}" ]; then args+=(--expected-version "$TP_VERSION"); fi
if [ -n "${TP_PLUGIN_TRUST_ROOT:-}" ]; then args+=(--plugin-trust-root "$TP_PLUGIN_TRUST_ROOT"); fi
# Signed releases: a trust root is supplied out of band (never from the payload).
if [ -n "${TP_RELEASE_TRUST_ROOT:-}" ]; then args+=(--release-trust-root "$TP_RELEASE_TRUST_ROOT"); fi
if [ "${TP_REQUIRE_SIGNED_RELEASE:-}" = "1" ]; then args+=(--require-signed-release); fi
if [ -n "${TP_REVOKED_VERSIONS:-}" ]; then
for revoked in ${TP_REVOKED_VERSIONS//,/ }; do args+=(--revoked-version "$revoked"); done
fi
if ! run_privileged "${args[@]}"; then
[ -z "$temporary" ] || rm -rf "$temporary"
error "安装未完成;请保留 .thingspanel-update 中的恢复记录。"
fi
[ -z "$temporary" ] || rm -rf "$temporary"
}
# ── Banner ────────────────────────────────────────────────────────────────────
print_banner() {
echo -e "${BOLD}"
echo ""
echo " ╔══════════════════════════════════════╗"
echo " ║ ThingsPanel ║"
echo " ║ Installer ║"
echo " ╚══════════════════════════════════════╝"
echo ""
echo -e "${RESET}"
}
# ── 环境检测 ──────────────────────────────────────────────────────────────────
check_os() {
step "检测操作系统"
OS="$(uname -s)"
ARCH="$(uname -m)"
case "$OS" in
Linux|Darwin) ;;
*) error "不支持的操作系统: $OS(请在 Linux 或 macOS 上运行)" ;;
esac
success "操作系统: $OS ($ARCH)"
}
check_docker() {
step "检测 Docker"
if ! command_exists docker; then
error "未找到 Docker。请先安装 Docker Engine(Linux)或 Docker Desktop(macOS):\n https://docs.docker.com/get-docker/"
fi
DOCKER_VER="$(docker version --format '{{.Server.Version}}' 2>/dev/null || echo '0.0')"
if ! version_gte "$DOCKER_VER" "$MIN_DOCKER_VERSION"; then
error "Docker 版本过低(当前: $DOCKER_VER,需要 >= $MIN_DOCKER_VERSION)"
fi
success "Docker $DOCKER_VER"
if docker compose version >/dev/null 2>&1; then
COMPOSE_VER="$(docker compose version --short 2>/dev/null || echo '2.0')"
success "Docker Compose v2 $COMPOSE_VER"
else
error "未找到 docker compose(v2)。请升级 Docker 或安装 Docker Compose Plugin:\n https://docs.docker.com/compose/install/"
fi
}
check_ports() {
step "检测端口占用"
local ports=("$HTTP_PORT" "$MQTT_PORT")
for port in "${ports[@]}"; do
if command_exists ss; then
if ss -tuln 2>/dev/null | grep -q ":${port} "; then
warn "端口 ${port} 已被占用,可通过 HTTP_PORT= 或 MQTT_PORT= 指定其他端口"
else
success "端口 $port 可用"
fi
elif command_exists lsof; then
if lsof -i ":${port}" >/dev/null 2>&1; then
warn "端口 ${port} 已被占用"
else
success "端口 $port 可用"
fi
fi
done
}
check_memory() {
step "检测内存"
local mem_kb=0
if [ -f /proc/meminfo ]; then
mem_kb=$(awk '/MemTotal/{print $2}' /proc/meminfo)
elif command_exists sysctl; then
mem_kb=$(( $(sysctl -n hw.memsize 2>/dev/null || echo 0) / 1024 ))
fi
local mem_gb=$(( mem_kb / 1024 / 1024 ))
if [ "$mem_gb" -lt 2 ]; then
warn "内存不足 2GB(当前约 ${mem_gb}GB),可能影响稳定性"
else
success "内存: 约 ${mem_gb}GB"
fi
}
# ── 创建目录结构 ───────────────────────────────────────────────────────────────
setup_directories() {
step "创建目录结构"
run_privileged mkdir -p "$INSTALL_DIR"
success "目录: $INSTALL_DIR"
}
# ── 安装完成提示 ───────────────────────────────────────────────────────────────
print_success() {
echo ""
echo -e "${GREEN}╔══════════════════════════════════════════════════════╗${RESET}"
echo -e "${GREEN}║ ThingsPanel 安装成功! ║${RESET}"
echo -e "${GREEN}╚══════════════════════════════════════════════════════╝${RESET}"
echo ""
echo -e " 🌐 Web 界面: ${BOLD}http://localhost:${HTTP_PORT}${RESET}"
echo -e " 📡 MQTT: ${BOLD}localhost:${MQTT_PORT}${RESET}"
echo ""
echo -e " 📁 安装目录: ${INSTALL_DIR}"
echo ""
echo -e "${BOLD}常用命令:${RESET}"
echo " 查看服务状态: docker compose -f ${INSTALL_DIR}/docker-compose.yml ps"
echo " 查看后端日志: docker compose -f ${INSTALL_DIR}/docker-compose.yml logs -f backend"
echo " 停止所有服务: docker compose -f ${INSTALL_DIR}/docker-compose.yml down"
echo " 升级到新版本: ${INSTALL_DIR}/upgrade.sh"
echo ""
}
# ── 主流程 ─────────────────────────────────────────────────────���──────────────
main() {
print_banner
check_os
check_docker
check_existing_thingsvis_database
check_ports
check_memory
ensure_install_dir_access
setup_directories
run_safe_update
print_success
}
main "$@"