307 lines
13 KiB
JavaScript
307 lines
13 KiB
JavaScript
/* DevBox · 部署:一键拉仓库 + 构建 + 重启 + 健康检查 */
|
||
(function () {
|
||
'use strict'
|
||
const { el, panelTitle, copy, output, downloadText, debounce } = DB
|
||
const pane = (title, right) => { const p = el('div', { class: 'panel' }); if (title) p.append(panelTitle(title, right)); return p }
|
||
const btn = (label, fn, cls = '') => el('button', { class: 'btn ' + cls, text: label, onclick: fn })
|
||
const field = (label, control) => el('label', { class: 'field' }, el('span', { text: label }), control)
|
||
|
||
const INSTALLS = {
|
||
auto: '自动检测(推荐)',
|
||
npm: 'npm ci(干净安装 lock 里的版本)',
|
||
pnpm: 'pnpm install --frozen-lockfile',
|
||
yarn: 'yarn install --immutable',
|
||
pip: 'pip install -r requirements.txt',
|
||
composer: 'composer install --no-dev',
|
||
none: '不需要(纯静态 / 手动)',
|
||
}
|
||
const RUNS = {
|
||
systemd: 'systemd 服务(推荐,开机自启)',
|
||
pm2: 'pm2(Node 生态,进程管理)',
|
||
docker: 'docker compose(容器)',
|
||
none: '只拉代码,不重启',
|
||
}
|
||
|
||
const shq = (s) => '"' + String(s).replace(/"/g, '\\"') + '"'
|
||
|
||
DB.tool({
|
||
id: 'deploy',
|
||
name: '一键部署脚本',
|
||
group: 'web',
|
||
icon: 'terminal',
|
||
desc: '填仓库和目录,生成服务器上能直接跑的拉取 + 构建 + 重启脚本,附带 systemd 与 Nginx 配置',
|
||
keywords: ['deploy', 'deployment', 'git', 'pull', 'ci', 'systemd', 'nginx', 'pm2', '部署', '上线', '发布', '服务器'],
|
||
mount(root) {
|
||
const cfg = {
|
||
repo: 'https://github.com/syc65535/devbox.git',
|
||
ref: 'main',
|
||
dir: '/srv/devbox',
|
||
name: 'devbox',
|
||
install: 'auto',
|
||
build: 'npm run build',
|
||
run: 'systemd',
|
||
port: '3000',
|
||
user: 'www-data',
|
||
start: 'npm start',
|
||
health: '/',
|
||
nginx: true,
|
||
domain: 'box.example.com',
|
||
ssh: 'root@你的服务器IP',
|
||
}
|
||
|
||
const inputs = {}
|
||
const add = (key, node) => { inputs[key] = node; return node }
|
||
const text = (key, ph) => add(key, el('input', { type: 'text', placeholder: ph || '', value: cfg[key] }))
|
||
const select = (key, options) => {
|
||
const s = el('select')
|
||
for (const [v, label] of Object.entries(options)) {
|
||
s.append(el('option', { value: v, text: label, selected: v === cfg[key] }))
|
||
}
|
||
return add(key, s)
|
||
}
|
||
|
||
const repoIn = text('repo', 'https://github.com/owner/repo.git')
|
||
const refIn = text('ref', 'main')
|
||
const dirIn = text('dir', '/srv/app')
|
||
const nameIn = text('name', 'my-app')
|
||
const installIn = select('install', INSTALLS)
|
||
const buildIn = text('build', '留空表示不需要构建')
|
||
const runIn = select('run', RUNS)
|
||
const portIn = text('port', '3000')
|
||
const userIn = text('user', 'www-data')
|
||
const startIn = text('start', 'npm start')
|
||
const healthIn = text('health', '/')
|
||
const domainIn = text('domain', 'example.com')
|
||
const sshIn = text('ssh', 'root@1.2.3.4')
|
||
const nginxBox = el('input', { type: 'checkbox', checked: true })
|
||
|
||
const outScript = output()
|
||
const outUnit = output()
|
||
const outNginx = output()
|
||
const oneLine = el('pre', { class: 'out flush', style: { minHeight: '0' } })
|
||
const hintBox = el('div', { class: 'hint' })
|
||
|
||
const installBlock = (mode, repo) => {
|
||
const lines = []
|
||
if (mode === 'none') return '# 依赖:跳过(按需自己装)'
|
||
if (mode === 'npm') lines.push('npm ci --no-audit --no-fund')
|
||
else if (mode === 'pnpm') lines.push('corepack enable >/dev/null 2>&1 || true', 'pnpm install --frozen-lockfile')
|
||
else if (mode === 'yarn') lines.push('corepack enable >/dev/null 2>&1 || true', 'yarn install --immutable')
|
||
else if (mode === 'pip') lines.push('python3 -m pip install --upgrade pip', 'python3 -m pip install -r requirements.txt')
|
||
else if (mode === 'composer') lines.push('composer install --no-dev --optimize-autoloader')
|
||
else {
|
||
lines.push('if [ -f pnpm-lock.yaml ]; then')
|
||
lines.push(' corepack enable >/dev/null 2>&1 || true; pnpm install --frozen-lockfile')
|
||
lines.push('elif [ -f yarn.lock ]; then')
|
||
lines.push(' corepack enable >/dev/null 2>&1 || true; yarn install --immutable')
|
||
lines.push('elif [ -f package-lock.json ]; then')
|
||
lines.push(' npm ci --no-audit --no-fund')
|
||
lines.push('elif [ -f package.json ]; then')
|
||
lines.push(' npm install --no-audit --no-fund')
|
||
lines.push('elif [ -f requirements.txt ]; then')
|
||
lines.push(' python3 -m pip install -r requirements.txt')
|
||
lines.push('elif [ -f composer.json ]; then')
|
||
lines.push(' composer install --no-dev --optimize-autoloader')
|
||
lines.push('else')
|
||
lines.push(' echo " (没有识别到依赖清单,跳过)"')
|
||
lines.push('fi')
|
||
}
|
||
return lines.join('\n')
|
||
}
|
||
|
||
const restartBlock = (run, name) => {
|
||
if (run === 'none') return '# 重启:跳过(只更新了代码)'
|
||
if (run === 'systemd') return [
|
||
`if systemctl list-unit-files | grep -q '^${name}.service'; then`,
|
||
` sudo systemctl restart ${name}`,
|
||
'else',
|
||
` echo " 还没装 ${name}.service,把下面的 unit 装到 /etc/systemd/system/ 再跑一次"`,
|
||
'fi',
|
||
].join('\n')
|
||
if (run === 'pm2') return [
|
||
`if command -v pm2 >/dev/null 2>&1; then`,
|
||
` pm2 restart ${name} --update-env 2>/dev/null || pm2 start npm --name ${name} -- start`,
|
||
' pm2 save >/dev/null 2>&1 || true',
|
||
'else',
|
||
' echo " 没装 pm2:npm i -g pm2"',
|
||
'fi',
|
||
].join('\n')
|
||
return [
|
||
'if [ -f docker-compose.yml ] || [ -f compose.yaml ]; then',
|
||
' docker compose up -d --build',
|
||
'else',
|
||
' echo " 目录里没有 compose 文件,跳过容器重启"',
|
||
'fi',
|
||
].join('\n')
|
||
}
|
||
|
||
const buildScript = () => {
|
||
const dir = cfg.dir.replace(/\/+$/, '')
|
||
const healthPath = cfg.health.startsWith('/') ? cfg.health : '/' + cfg.health
|
||
const port = String(cfg.port).replace(/\D/g, '') || '3000'
|
||
const lines = []
|
||
lines.push('#!/usr/bin/env bash')
|
||
lines.push('# 由 DevBox 生成 · ' + new Date().toISOString().slice(0, 10))
|
||
lines.push(`# 用法:ssh ${cfg.ssh} 'bash -s' < deploy.sh`)
|
||
lines.push('set -euo pipefail')
|
||
lines.push('')
|
||
lines.push(`REPO=${shq(cfg.repo)}`)
|
||
lines.push(`REF=${shq(cfg.ref || 'main')}`)
|
||
lines.push(`APP_DIR=${shq(dir)}`)
|
||
lines.push(`APP_NAME=${shq(cfg.name || 'app')}`)
|
||
lines.push(`PORT=${shq(port)}`)
|
||
lines.push('')
|
||
lines.push(`log() { printf '\\033[36m▸ %s\\033[0m\\n' "$*"; }`)
|
||
lines.push(`die() { printf '\\033[31m✗ %s\\033[0m\\n' "$*" >&2; exit 1; }`)
|
||
lines.push('')
|
||
lines.push('command -v git >/dev/null 2>&1 || die "没装 git:apt-get update && apt-get install -y git"')
|
||
lines.push('')
|
||
lines.push('log "目标 $APP_NAME → $APP_DIR(分支 $REF)"')
|
||
lines.push('if [ -d "$APP_DIR/.git" ]; then')
|
||
lines.push(' log "已存在,拉取最新代码"')
|
||
lines.push(' git -C "$APP_DIR" fetch --depth=1 origin "$REF"')
|
||
lines.push(' git -C "$APP_DIR" reset --hard FETCH_HEAD')
|
||
lines.push(' git -C "$APP_DIR" clean -fdx -e node_modules -e .env -e data')
|
||
lines.push('else')
|
||
lines.push(' log "首次部署,克隆仓库"')
|
||
lines.push(' mkdir -p "$(dirname "$APP_DIR")"')
|
||
lines.push(' git clone --depth=1 --branch "$REF" "$REPO" "$APP_DIR"')
|
||
lines.push('fi')
|
||
lines.push('')
|
||
lines.push('cd "$APP_DIR"')
|
||
lines.push('')
|
||
lines.push('log "安装依赖"')
|
||
lines.push(installBlock(cfg.install, cfg.repo))
|
||
if (cfg.build.trim()) {
|
||
lines.push('')
|
||
lines.push('log "构建"')
|
||
lines.push(cfg.build.trim())
|
||
}
|
||
lines.push('')
|
||
lines.push('log "重启服务"')
|
||
lines.push(restartBlock(cfg.run, cfg.name || 'app'))
|
||
if (cfg.run !== 'none') {
|
||
lines.push('')
|
||
lines.push('log "健康检查 http://127.0.0.1:$PORT' + healthPath + '"')
|
||
lines.push('for i in $(seq 1 20); do')
|
||
lines.push(' if curl -fsS "http://127.0.0.1:$PORT' + healthPath + '" >/dev/null 2>&1; then')
|
||
lines.push(' log "服务已就绪"; break')
|
||
lines.push(' fi')
|
||
lines.push(' if [ "$i" = "20" ]; then')
|
||
lines.push(' die "20 秒没起来,看看日志:journalctl -u $APP_NAME -n 50 --no-pager"')
|
||
lines.push(' fi')
|
||
lines.push(' sleep 1')
|
||
lines.push('done')
|
||
}
|
||
lines.push('')
|
||
lines.push('log "完成:$APP_NAME 现在跑的是 $(git -C "$APP_DIR" rev-parse --short HEAD)"')
|
||
return lines.join('\n')
|
||
}
|
||
|
||
const buildUnit = () => `[Unit]
|
||
Description=${cfg.name}
|
||
After=network.target
|
||
|
||
[Service]
|
||
Type=simple
|
||
User=${cfg.user || 'www-data'}
|
||
WorkingDirectory=${cfg.dir}
|
||
Environment=NODE_ENV=production
|
||
Environment=PORT=${cfg.port}
|
||
ExecStart=/usr/bin/env ${cfg.start || 'npm start'}
|
||
Restart=always
|
||
RestartSec=3
|
||
StandardOutput=journal
|
||
StandardError=journal
|
||
|
||
[Install]
|
||
WantedBy=multi-user.target`
|
||
|
||
const buildNginx = () => `server {
|
||
listen 80;
|
||
listen [::]:80;
|
||
server_name ${cfg.domain || 'example.com'};
|
||
client_max_body_size 50m;
|
||
|
||
location / {
|
||
proxy_pass http://127.0.0.1:${cfg.port};
|
||
proxy_http_version 1.1;
|
||
proxy_set_header Host $host;
|
||
proxy_set_header X-Real-IP $remote_addr;
|
||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||
proxy_set_header X-Forwarded-Proto $scheme;
|
||
proxy_set_header Upgrade $http_upgrade;
|
||
proxy_set_header Connection "upgrade";
|
||
proxy_read_timeout 120s;
|
||
}
|
||
}`
|
||
|
||
let p5, p6
|
||
const render = () => {
|
||
for (const k of Object.keys(inputs)) cfg[k] = inputs[k].value
|
||
cfg.nginx = nginxBox.checked
|
||
const script = buildScript()
|
||
outScript.set(script)
|
||
oneLine.textContent = `ssh ${cfg.ssh || 'root@服务器'} 'bash -s' < deploy.sh`
|
||
oneLine.dataset.raw = oneLine.textContent
|
||
outUnit.set(buildUnit())
|
||
outNginx.set(buildNginx())
|
||
p5.hidden = cfg.run !== 'systemd'
|
||
p6.hidden = !cfg.nginx
|
||
hintBox.textContent = cfg.nginx
|
||
? `Nginx 转发到 127.0.0.1:${cfg.port},域名 ${cfg.domain};HTTPS 用 certbot --nginx 一条命令签发。`
|
||
: `没有开 Nginx:直接访问 http://服务器IP:${cfg.port},记得放行防火墙端口。`
|
||
}
|
||
|
||
const lazy = debounce(render, 140)
|
||
root.addEventListener('input', lazy)
|
||
root.addEventListener('change', lazy)
|
||
|
||
const p1 = pane('项目')
|
||
p1.append(el('div', { class: 'grid2' },
|
||
field('仓库地址(https 最省事)', repoIn),
|
||
field('分支 / tag', refIn),
|
||
field('服务器上的部署目录', dirIn),
|
||
field('应用名(服务名 / pm2 名)', nameIn)))
|
||
|
||
const p2 = pane('构建与运行')
|
||
p2.append(el('div', { class: 'grid2' },
|
||
field('依赖安装', installIn),
|
||
field('构建命令', buildIn),
|
||
field('重启方式', runIn),
|
||
field('端口', portIn),
|
||
field('运行用户', userIn),
|
||
field('启动命令', startIn),
|
||
field('健康检查路径', healthIn),
|
||
field('SSH 目标(只影响那行一键命令)', sshIn)))
|
||
p2.append(el('div', { class: 'row', style: { marginTop: '12px', alignItems: 'flex-end' } },
|
||
el('label', { class: 'check', style: { paddingBottom: '11px', whiteSpace: 'nowrap' } }, nginxBox, el('span', { text: '附带 Nginx 配置' })),
|
||
el('label', { class: 'field', style: { flex: '1' } }, el('span', { text: '域名(Nginx server_name)' }), domainIn)))
|
||
hintBox.style.marginTop = '10px'
|
||
p2.append(hintBox)
|
||
|
||
const p3 = pane('① 一键执行(本地跑,自动在服务器上执行)')
|
||
p3.append(
|
||
el('div', { class: 'hint', text: '先在本地存成 deploy.sh(点右上「下载」),再执行下面这行;首次部署会遇到域名解析、权限等提示,按提示装 git / systemd 即可。' }),
|
||
el('div', { class: 'row', style: { marginTop: '10px' } }, btn('复制这一行', () => copy(oneLine.dataset.raw))),
|
||
oneLine)
|
||
|
||
const p4 = pane('② 部署脚本 deploy.sh', btn('下载 deploy.sh', () => downloadText('deploy.sh', outScript.text, 'text/x-sh')))
|
||
p4.append(outScript.node)
|
||
|
||
p5 = pane('③ systemd 单元(首次部署时装一次)')
|
||
p5.append(
|
||
el('div', { class: 'hint', text: '存成 /etc/systemd/system/<应用名>.service,然后执行:sudo systemctl daemon-reload && sudo systemctl enable --now <应用名>' }),
|
||
outUnit.node)
|
||
|
||
p6 = pane('④ Nginx 反向代理(可选)')
|
||
p6.append(
|
||
el('div', { class: 'hint', text: '存成 /etc/nginx/sites-available/<应用名>.conf,软链到 sites-enabled,nginx -t 通过后 reload;再 certbot --nginx -d 域名 上 HTTPS。' }),
|
||
outNginx.node)
|
||
|
||
root.append(p1, p2, p3, p4, p5, p6)
|
||
render()
|
||
},
|
||
})
|
||
})()
|