增加个服务安装文件

This commit is contained in:
2026-05-15 18:25:22 +08:00
parent bf41e82a43
commit 659054beb7
+96
View File
@@ -0,0 +1,96 @@
#!/bin/bash
#
# meshgo 安装脚本(Linux
# 功能:git pull 拉取最新代码 → 编译 → 安装到 /opt/meshgo
#
set -e
APP_NAME="meshgo"
INSTALL_DIR="/opt/${APP_NAME}"
DATA_DIR="/var/lib/${APP_NAME}"
REPO_DIR="$(cd "$(dirname "$0")" && pwd)"
echo "=== meshgo 安装脚本 ==="
echo "安装目录: ${INSTALL_DIR}"
echo "仓库目录: ${REPO_DIR}"
echo ""
# ---------------------------------------------------------------------------
# 1. git pull 拉取最新代码
# ---------------------------------------------------------------------------
echo "[1/5] 拉取最新代码..."
cd "${REPO_DIR}"
if ! git diff-index --quiet HEAD -- 2>/dev/null; then
echo "警告:本地有未提交的更改,将暂存后拉取..."
git stash push -m "install.sh auto stash $(date +%Y%m%d%H%M%S)"
fi
git pull origin main
echo "[1/5] 完成"
echo ""
# ---------------------------------------------------------------------------
# 2. 编译
# ---------------------------------------------------------------------------
echo "[2/5] 编译..."
CGO_ENABLED=1 go build -ldflags="-s -w" -o meshgo .
echo "[2/5] 完成: meshgo"
echo ""
# ---------------------------------------------------------------------------
# 3. 创建用户和数据目录
# ---------------------------------------------------------------------------
echo "[3/5] 创建用户和数据目录..."
id -u ${APP_NAME} &>/dev/null || sudo useradd -r -s /usr/sbin/nologin -d /nonexistent ${APP_NAME}
sudo mkdir -p "${INSTALL_DIR}"
sudo mkdir -p "${DATA_DIR}"
echo "[3/5] 完成"
echo ""
# ---------------------------------------------------------------------------
# 4. 复制到安装目录并设置权限
# ---------------------------------------------------------------------------
echo "[4/5] 复制到 ${INSTALL_DIR}..."
sudo cp meshgo "${INSTALL_DIR}/"
sudo chown -R ${APP_NAME}:${APP_NAME} "${INSTALL_DIR}"
sudo chown -R ${APP_NAME}:${APP_NAME} "${DATA_DIR}"
echo "[4/5] 完成"
echo ""
# ---------------------------------------------------------------------------
# 5. 安装 systemd 服务
# ---------------------------------------------------------------------------
echo "[5/5] 安装 systemd 服务..."
sudo tee /etc/systemd/system/${APP_NAME}.service > /dev/null <<EOF
[Unit]
Description=meshgo MQTT Broker
Documentation=https://github.com/mochi-mqtt/server
After=network.target
[Service]
Type=simple
User=${APP_NAME}
Group=${APP_NAME}
ExecStart=${INSTALL_DIR}/meshgo
ExecReload=/bin/kill -HUP \$MAINPID
Restart=on-failure
RestartSec=5s
StandardOutput=journal
StandardError=journal
SyslogIdentifier=${APP_NAME}
ReadWritePaths=${DATA_DIR}
PrivateTmp=true
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl daemon-reload
echo "[5/5] 完成"
echo ""
echo "=== 安装完成 ==="
echo ""
echo "配置文件(程序首次运行自动生成):/etc/meshgo/config.yaml"
echo "二进制文件:${INSTALL_DIR}/meshgo"
echo ""