Compare commits

...

27 Commits

Author SHA1 Message Date
liufumingren
a216aad2ce feat: 新增摄像头OSD叠加设置 & 在线状态迁移至ping心跳维护
- 新增 POST /camera/setOSD 接口,下发OSD叠加信息到录制客户端
- 将 Redis 在线状态维护从 setInfo 迁移到 ping 心跳机制
- WebSocket ping 处理中增加 Redis 在线状态刷新
- 移除 fetchTasks 中 pack_mode=1 的限制条件
- 更新 frp auth_token
2026-07-31 21:10:09 +08:00
liufumingren
ec67245b2c fix: start_time 减5秒 end_time 不减 2026-07-27 04:50:23 +08:00
liufumingren
3dee0c5403 fix: 添加 /record/force 路由兼容 qimen 调用 2026-07-27 04:35:20 +08:00
liufumingren
87b4902d10 fix: forceRecord 加日志排查推送失败 2026-07-27 04:30:31 +08:00
liufumingren
7909035cf4 fix: taskComplete 用 id 精准更新,避免 forceRecord 并发覆盖 2026-07-27 04:26:06 +08:00
liufumingren
788dfa0973 feat: setInfo 加 _source 来源标记便于追踪日志 2026-07-27 04:10:36 +08:00
liufumingren
3662c82e26 feat: POST /hikvision/forceRecord 强制录制推送 2026-07-27 03:31:54 +08:00
liufumingren
7f079c130f fix: taskComplete 失败回信携带 error 字段 2026-07-27 03:18:23 +08:00
liufumingren
7903e34a9c fix: fetchTasks 开始时间往前 5 秒覆盖扫描操作 2026-07-27 02:59:03 +08:00
liufumingren
10f5193f23 fix: fetchTasks 时间按 UTC 解析后转为 CST +08:00 2026-07-27 02:55:31 +08:00
liufumingren
8dbc238acf fix: fetchTasks 时间转为 ISO 8601 +08:00 格式 2026-07-27 02:36:06 +08:00
liufumingren
82d0271ee2 fix: fetchTasks 返回 end_time 2026-07-27 02:03:20 +08:00
liufumingren
8570e088a4 fix: fetchTasks 排除无结束时间和无设备的任务 2026-07-27 02:00:57 +08:00
liufumingren
65124242f6 fix: fetchTasks 拉取时即创建录像记录 status=created 2026-07-27 01:48:02 +08:00
liufumingren
7c1e449e35 feat: 海康录像任务服务 - fetchTasks/receiveTask/taskComplete 2026-07-27 01:39:11 +08:00
liufumingren
ce0c23bb8a fix: bind 接口 code/printer 改为可选参数(实际未使用) 2026-07-26 20:28:50 +08:00
liufumingren
fc9e514f93 feat: frp 录制电脑编排 + frps NewProxy 插件验证接口 + frpc 配置下发 2026-07-26 19:44:08 +08:00
liufumingren
56c8121590 feat: 新增注销和刷新信息接口,getInfo 补充 DB 字段下发,Redis 增加断线重连 2026-07-26 01:19:01 +08:00
liufumingren
1c2703e681 perf: npm install 添加 --prefer-offline --no-audit --no-fund 优化,20秒完成 2026-07-25 02:18:29 +08:00
liufumingren
f692a767f8 fix: 从活跃版本复制 node_modules 替代全量下载,npm install 秒过 2026-07-25 02:15:09 +08:00
liufumingren
80d84888a4 fix: bash -lc 改为 bash -c,避免嵌套登录 shell 导致 npm 静默失败 2026-07-25 02:11:31 +08:00
liufumingren
f6e9c20396 fix: runSsh 恢复为与参考项目一致的 bash -lc 方式 2026-07-25 02:09:10 +08:00
liufumingren
d2445c7309 refactor: 去掉冗余的 node_modules 复制步骤,简化部署流程 2026-07-25 02:06:19 +08:00
liufumingren
b4ad9c53c6 fix: runSsh 改用 base64 管道传脚本,彻底避免 bash -c 嵌套导致的输出卡住问题 2026-07-25 01:59:29 +08:00
liufumingren
b99995de24 fix: npm install 前强制清理 node_modules,避免残留状态导致 semver Invalid Version 错误 2026-07-25 01:56:49 +08:00
liufumingren
c5a6270ba7 fix: SSH 改用 bash -c 避免登录 shell 卡住,添加心跳保活 2026-07-25 01:50:23 +08:00
liufumingren
c5bd7138e8 feat: 添加蓝绿部署发布脚本系统
- 蓝绿部署 (v1/v2 双实例, 端口 4051/4052)

- 部署预检、远程部署、回滚

- 版本追踪、Git 安全 Hook

- Nginx upstream 自动切换
2026-07-25 01:31:13 +08:00
24 changed files with 2728 additions and 6 deletions

2
.githooks/pre-commit Normal file
View File

@ -0,0 +1,2 @@
#!/bin/sh
node script/git-safety-check.cjs

4
.gitignore vendored
View File

@ -13,3 +13,7 @@ run/
*.un~
typings/
.nyc_output/
tmp/
versioning/
config/deploy.config.local.cjs
*.rar

View File

@ -3,12 +3,14 @@ const Controller = require('egg').Controller;
class AuthController extends Controller {
async bind() {
const { ctx, app } = this;
const { roomId, code, printer, warehouse, computerId } = ctx.request.body;
const { roomId, warehouse, computerId } = ctx.request.body;
const code = ctx.request.body.code || '';
const printer = ctx.request.body.printer || '';
console.log('Received bind request with parameters:', { roomId, code, printer, warehouse, computerId });
if (!roomId || !code || !printer || !warehouse || !computerId) {
if (!roomId || !warehouse || !computerId) {
ctx.body = {
status: 'fail',
message: '缺少必要参数: roomId, code, printer, warehouse, computerId',
message: '缺少必要参数: roomId, warehouse, computerId',
};
return;
}
@ -64,6 +66,269 @@ class AuthController extends Controller {
};
}
}
// 外部通知注销电脑(强制下线)
async logout() {
const { ctx, app } = this;
const { warehouse, computerId } = ctx.request.body;
if (!warehouse || !computerId) {
ctx.body = {
status: 'fail',
message: '缺少必要参数: warehouse, computerId',
};
return;
}
try {
// 1. 核实数据库:确认电脑存在
const computerInfo = await app.mysql.get('wms').get('wms_print_computer', {
warehouse_id: warehouse,
id: computerId,
});
if (!computerInfo) {
ctx.body = {
status: 'fail',
message: '未在数据库中找到该电脑信息',
};
return;
}
console.log(`注销电脑: warehouse=${warehouse}, computerId=${computerId}, deleted_at=${computerInfo.deleted_at}`);
// 2. 从 Redis 查找电脑是否在线
const computerInfoKey = `warehouse:${warehouse}:printer:${computerId}`;
const cachedInfo = await app.redis.get(computerInfoKey);
if (!cachedInfo) {
// 电脑不在线,但数据库验证已通过,返回成功(已离线无需操作)
ctx.body = {
status: 'success',
message: '电脑当前离线,无需注销',
};
return;
}
const { uniqueId } = JSON.parse(cachedInfo);
// 3. 向客户端发送解绑注销命令
const res = await app.ws.sendTo(uniqueId, JSON.stringify({
method: 'setting.unbind',
data: { reason: '管理员强制注销' },
}));
// 4. 清理 Redis 中的在线状态
await app.redis.del(computerInfoKey);
await app.redis.del(uniqueId);
console.log(`已清理 Redis: ${computerInfoKey}, ${uniqueId}`);
if (res !== 1) {
ctx.body = {
status: 'fail',
message: '发送注销命令失败,电脑可能已断开连接',
};
return;
}
ctx.body = {
status: 'success',
message: '注销命令已发送',
};
} catch (error) {
console.error('注销电脑时发生错误:', error);
ctx.body = {
status: 'fail',
message: `注销失败: ${error.message}`,
};
}
}
// 外部通知电脑信息变更(拉取最新数据并推送给客户端)
// 自动检测 is_recording 变化,编排 frpc 启停
async refreshInfo() {
const { ctx, app } = this;
const { warehouse, computerId } = ctx.request.body;
if (!warehouse || !computerId) {
ctx.body = { status: 'fail', message: '缺少必要参数: warehouse, computerId' };
return;
}
try {
// 1. 从数据库拉取最新电脑信息
const computerInfo = await app.mysql.get('wms').get('wms_print_computer', {
warehouse_id: warehouse,
id: computerId,
});
if (!computerInfo) {
ctx.body = { status: 'fail', message: '未在数据库中找到该电脑信息' };
return;
}
// 2. 检查旧缓存,对比 is_recording 是否变化
const computerInfoKey = `warehouse:${warehouse}:printer:${computerId}`;
const oldCached = await app.redis.get(computerInfoKey);
const oldIsRecording = oldCached ? JSON.parse(oldCached).is_recording : null;
const newIsRecording = computerInfo.is_recording || 0;
console.log(`刷新电脑信息: warehouse=${warehouse}, computerId=${computerId}, is_recording: ${oldIsRecording} → ${newIsRecording}`);
// 3. 组装下发的 info 数据
const infoData = {
name: computerInfo.name || '',
status: computerInfo.status,
is_recording: newIsRecording,
recording_size_value: computerInfo.recording_size_value || 0,
recording_size_unit: computerInfo.recording_size_unit || '',
remote_play_url: computerInfo.remote_play_url || '',
recording_directory: computerInfo.recording_directory || '',
};
// 4. 查找目标电脑是否在线
const cachedInfo = await app.redis.get(computerInfoKey);
// === 场景A:电脑从非录制 → 录制,需要编排 frpc ===
if (newIsRecording === 1 && oldIsRecording !== 1) {
console.log(`电脑 ${computerId} 被设置为录制电脑,开始编排 frpc`);
// 4a. 扫描同仓库所有在线电脑
const warehousePattern = `warehouse:${warehouse}:printer:*`;
const onlineKeys = [];
let cursor = '0';
do {
const [nextCursor, keys] = await app.redis.scan(cursor, 'MATCH', warehousePattern, 'COUNT', 100);
cursor = nextCursor;
onlineKeys.push(...keys);
} while (cursor !== '0');
console.log(`仓库 ${warehouse} 在线电脑: ${onlineKeys.join(', ')}`);
// 4b. 通知其他在线电脑断开 frpc
const disconnectPromises = [];
for (const key of onlineKeys) {
if (key === computerInfoKey) continue; // 跳过自己
const otherData = await app.redis.get(key);
if (!otherData) continue;
const other = JSON.parse(otherData);
const otherComputerId = key.split(':').pop();
console.log(`通知电脑 ${otherComputerId} 断开 frpc`);
disconnectPromises.push(
app.ws.sendTo(other.uniqueId, JSON.stringify({
method: 'setting.frpcDisconnect',
data: { reason: '同仓库录制电脑已变更' },
}))
);
// 清理其他电脑的 Redis 在线状态
await app.redis.del(key);
await app.redis.del(other.uniqueId);
}
// 4c. 等待其他电脑断开(最多 5 秒)
if (disconnectPromises.length > 0) {
const timeout = app.config.frp.disconnect_timeout || 5000;
await Promise.race([
Promise.allSettled(disconnectPromises),
new Promise(resolve => setTimeout(resolve, timeout)),
]);
console.log('其他电脑 frpc 断开通知已发出,等待完成');
}
// 4d. 生成 frp token 并更新目标电脑
if (cachedInfo) {
const cached = JSON.parse(cachedInfo);
// 生成 frp 专用 token
const frpToken = app.jwt.sign(
{ warehouse, computerId, purpose: 'frp' },
app.config.jwt.secret,
{ expiresIn: '24h' }
);
const frpConfig = {
subdomain: `${app.config.frp.subdomain_prefix || 'w'}${warehouse}-c${computerId}`,
server_addr: app.config.frp.server_addr,
server_port: app.config.frp.server_port,
auth_token: app.config.frp.auth_token,
local_port: app.config.frp.local_port,
token: frpToken,
};
const updatedData = { ...cached, ...infoData, frp: frpConfig, _source: 'refreshInfo-recording' };
await app.redis.set(computerInfoKey, JSON.stringify(updatedData), 'EX', 300);
console.log(`[setInfo] 来源=refreshInfo(录制), computer=${computerId}, warehouse=${warehouse}`);
app.ws.sendTo(cached.uniqueId, JSON.stringify({
method: 'setting.setInfo',
data: updatedData,
message: '录制电脑配置已更新,请连接frpc',
}));
}
ctx.body = {
status: 'success',
message: `录制电脑已设置,已通知 ${disconnectPromises.length} 台其他电脑断开 frpc`,
data: infoData,
};
return;
}
// === 场景B:电脑从录制 → 非录制,断开 frpc ===
if (newIsRecording === 0 && oldIsRecording === 1) {
console.log(`电脑 ${computerId} 被取消录制,通知断开 frpc`);
if (cachedInfo) {
const cached = JSON.parse(cachedInfo);
app.ws.sendTo(cached.uniqueId, JSON.stringify({
method: 'setting.frpcDisconnect',
data: { reason: '录制电脑已被取消' },
}));
const updatedData = { ...cached, ...infoData, frp: null, _source: 'refreshInfo-unrecording' };
await app.redis.set(computerInfoKey, JSON.stringify(updatedData), 'EX', 300);
console.log(`[setInfo] 来源=refreshInfo(取消录制), computer=${computerId}, warehouse=${warehouse}`);
// 同时推送不带 frp 的更新 info
app.ws.sendTo(cached.uniqueId, JSON.stringify({
method: 'setting.setInfo',
data: updatedData,
message: '录制电脑已取消',
}));
}
ctx.body = {
status: 'success',
message: '录制电脑已取消,frpc 断开通知已发送',
data: infoData,
};
return;
}
// === 场景C:普通信息变更(is_recording 未变化或首次上线) ===
if (!cachedInfo) {
ctx.body = { status: 'success', message: '电脑当前离线,信息已保存,上线后将自动获取最新信息' };
return;
}
const cached = JSON.parse(cachedInfo);
const updatedData = { ...cached, ...infoData, _source: 'refreshInfo-normal' };
await app.redis.set(computerInfoKey, JSON.stringify(updatedData), 'EX', 300);
console.log(`[setInfo] 来源=refreshInfo(普通), computer=${computerId}, warehouse=${warehouse}`);
const res = await app.ws.sendTo(cached.uniqueId, JSON.stringify({
method: 'setting.setInfo',
data: updatedData,
message: '电脑信息已更新',
}));
ctx.body = {
status: res === 1 ? 'success' : 'fail',
message: res === 1 ? '信息已推送' : '推送失败,电脑可能已断开',
data: infoData,
};
} catch (error) {
console.error('刷新电脑信息时发生错误:', error);
ctx.body = { status: 'fail', message: `刷新失败: ${error.message}` };
}
}
}
module.exports = AuthController;

123
app/controller/frp.js Normal file
View File

@ -0,0 +1,123 @@
const { Controller } = require('egg');
/**
* frps NewProxy 插件验证接口
* frps 每次创建代理时调用此接口验证 subdomain 归属
*/
class FrpController extends Controller {
async newProxy() {
const { ctx, app } = this;
const { op, content } = ctx.request.body;
console.log('[Frp Plugin] 收到验证请求:', JSON.stringify(ctx.request.body));
if (op !== 'NewProxy') {
ctx.status = 200;
ctx.body = { reject: false, unchange: true };
return;
}
if (!content || !content.subdomain) {
console.log('[Frp Plugin] 拒绝: 缺少 subdomain');
ctx.status = 403;
ctx.body = { reject: true, rejectReason: '缺少 subdomain' };
return;
}
const subdomain = content.subdomain;
console.log(`[Frp Plugin] 验证 subdomain: ${subdomain}`);
// 解析 subdomain: w{warehouse}-c{computerId}
const match = subdomain.match(/^w(\d+)-c(\d+)$/);
if (!match) {
console.log(`[Frp Plugin] 拒绝: subdomain 格式不正确: ${subdomain}`);
ctx.status = 403;
ctx.body = { reject: true, rejectReason: 'subdomain 格式不正确' };
return;
}
const warehouse = match[1];
const computerId = match[2];
console.log(`[Frp Plugin] 解析结果: warehouse=${warehouse}, computerId=${computerId}`);
try {
// 1. 检查 Redis:该电脑是否在线且为录制电脑
const computerInfoKey = `warehouse:${warehouse}:printer:${computerId}`;
const cachedInfo = await app.redis.get(computerInfoKey);
if (!cachedInfo) {
console.log(`[Frp Plugin] 拒绝: 电脑不在线 warehouse=${warehouse}, computerId=${computerId}`);
ctx.status = 403;
ctx.body = { reject: true, rejectReason: '电脑不在线' };
return;
}
const onlineInfo = JSON.parse(cachedInfo);
if (onlineInfo.is_recording !== 1) {
console.log(`[Frp Plugin] 拒绝: 电脑不是录制电脑 warehouse=${warehouse}, computerId=${computerId}, is_recording=${onlineInfo.is_recording}`);
ctx.status = 403;
ctx.body = { reject: true, rejectReason: '电脑不是录制电脑' };
return;
}
// 2. 检查 DB:该电脑是否存在且未被删除
const computerInfo = await app.mysql.get('wms').get('wms_print_computer', {
warehouse_id: warehouse,
id: computerId,
});
if (!computerInfo) {
console.log(`[Frp Plugin] 拒绝: 数据库中不存在 warehouse=${warehouse}, computerId=${computerId}`);
ctx.status = 403;
ctx.body = { reject: true, rejectReason: '数据库中不存在该电脑' };
return;
}
if (computerInfo.deleted_at) {
console.log(`[Frp Plugin] 拒绝: 电脑已删除 warehouse=${warehouse}, computerId=${computerId}`);
ctx.status = 403;
ctx.body = { reject: true, rejectReason: '电脑已被删除' };
return;
}
// 3. 检查同仓库是否已有其他录制电脑在线
const warehousePattern = `warehouse:${warehouse}:printer:*`;
let cursor = '0';
let hasOtherRecording = false;
do {
const [nextCursor, keys] = await app.redis.scan(cursor, 'MATCH', warehousePattern, 'COUNT', 100);
cursor = nextCursor;
for (const key of keys) {
if (key === computerInfoKey) continue;
const otherData = await app.redis.get(key);
if (!otherData) continue;
const other = JSON.parse(otherData);
if (other.is_recording === 1) {
console.log(`[Frp Plugin] 拒绝: 同仓库已有其他录制电脑在线: ${key}`);
hasOtherRecording = true;
break;
}
}
if (hasOtherRecording) break;
} while (cursor !== '0');
if (hasOtherRecording) {
ctx.status = 200;
ctx.body = { reject: true, rejectReason: '同仓库已有其他录制电脑在线' };
return;
}
// 全部验证通过
console.log(`[Frp Plugin] 通过: warehouse=${warehouse}, computerId=${computerId}, name=${computerInfo.name}`);
ctx.status = 200;
ctx.body = { reject: false, unchange: true };
} catch (error) {
console.error('[Frp Plugin] 验证异常:', error);
ctx.status = 403;
ctx.body = { reject: true, rejectReason: `验证异常: ${error.message}` };
}
}
}
module.exports = FrpController;

116
app/controller/hikvision.js Normal file
View File

@ -0,0 +1,116 @@
const { Controller } = require('egg');
class HikvisionController extends Controller {
/**
* POST /hikvision/forceRecord
* 强制推送录制任务,事务重置录像行并推送
*/
async forceRecord() {
const { ctx } = this;
const { pack_task_id } = ctx.request.body;
if (!pack_task_id) {
ctx.body = { status: 'fail', message: '缺少 pack_task_id' };
return;
}
try {
const result = await ctx.service.hikvision.forceRecord({ pack_task_id });
ctx.body = result;
} catch (error) {
console.error('[HikvisionController] forceRecord 错误:', error);
ctx.body = { status: 'fail', message: error.message };
}
}
/**
* POST /camera/setOSD
* 主程序调用,下发 OSD 叠加信息到仓库中开启录制服务的客户端
* 入参: warehouse_id, rtspUrl, text, x?, y?
*/
async setCameraOSD() {
const { ctx, app } = this;
const { warehouse_id, rtspUrl, text } = ctx.request.body;
const x = ctx.request.body.x !== undefined ? ctx.request.body.x : -0.9;
const y = ctx.request.body.y !== undefined ? ctx.request.body.y : 0.8;
if (!warehouse_id) {
ctx.body = { status: 'fail', message: '缺少必要参数: warehouse_id' };
return;
}
if (!rtspUrl) {
ctx.body = { status: 'fail', message: '缺少必要参数: rtspUrl' };
return;
}
if (!text) {
ctx.body = { status: 'fail', message: '缺少必要参数: text' };
return;
}
try {
// 1. 扫描仓库下所有在线电脑,找到录制中的那台
const warehousePattern = `warehouse:${warehouse_id}:printer:*`;
let recordingClient = null;
let cursor = '0';
do {
const [nextCursor, keys] = await app.redis.scan(cursor, 'MATCH', warehousePattern, 'COUNT', 100);
cursor = nextCursor;
for (const key of keys) {
const raw = await app.redis.get(key);
if (!raw) continue;
const info = JSON.parse(raw);
if (info.is_recording === 1) {
recordingClient = info;
break;
}
}
if (recordingClient) break;
} while (cursor !== '0');
if (!recordingClient || !recordingClient.uniqueId) {
ctx.body = {
status: 'fail',
message: `仓库 ${warehouse_id} 中没有在线的录制电脑`,
};
return;
}
const roomId = recordingClient.uniqueId;
console.log(`[setCameraOSD] 发送 OSD 到房间 ${roomId}, rtspUrl=${rtspUrl}, text=${text}`);
// 2. 下发 setting.setCameraOSD 消息
const res = await app.ws.sendTo(roomId, JSON.stringify({
method: 'setting.setCameraOSD',
data: { rtspUrl, text, x, y },
}));
if (res !== 1) {
ctx.body = {
status: 'fail',
message: '录制电脑不在线,消息发送失败',
};
return;
}
console.log('[setCameraOSD] 消息发送成功');
ctx.body = {
status: 'success',
message: 'OSD 设置指令已下发',
result: {
warehouse_id,
computer_id: recordingClient.computerId,
rtspUrl,
text,
x,
y,
},
};
} catch (error) {
console.error('[setCameraOSD] 错误:', error);
ctx.body = { status: 'fail', message: error.message };
}
}
}
module.exports = HikvisionController;

View File

@ -61,6 +61,13 @@ class PrintController extends Controller {
if(msg=="ping"){
ws.send("pong");
// 维护 Redis 在线状态
if (ctx.print_computer_info) {
const { warehouse, computerId, uniqueId } = ctx.print_computer_info;
const key = `warehouse:${warehouse}:printer:${computerId}`;
await app.redis.set(key, JSON.stringify(ctx.print_computer_info), 'EX', 300);
await app.redis.expire(uniqueId, 300);
}
return;
}
// method过滤

View File

@ -5,6 +5,12 @@ module.exports = app => {
const { router, controller } = app;
router.get('/', controller.home.index);
router.post('/auth/bind', controller.auth.bind);
router.post('/auth/logout', controller.auth.logout);
router.post('/auth/refreshInfo', controller.auth.refreshInfo);
router.post('/frp/newProxy', controller.frp.newProxy);
router.post('/hikvision/forceRecord', controller.hikvision.forceRecord);
router.post('/record/force', controller.hikvision.forceRecord);
router.post('/camera/setOSD', controller.hikvision.setCameraOSD);
router.post('/sendToRoom', controller.home.sendToRoom);
app.ws.route('/ws', controller.print.ws);
};

View File

@ -17,13 +17,53 @@ class AuthService extends BaseService {
warehouse_id: warehouse,
id: computerId
});
// 检查电脑是否已被软删除,若是则通知客户端注销
if (computerInfo && computerInfo.deleted_at) {
console.log(`电脑 ${computerId} 已被标记删除(deleted_at: ${computerInfo.deleted_at}),通知客户端注销`);
// 清理 Redis 中的电脑在线信息
await this.app.redis.del(key);
await this.app.redis.del(uniqueId);
// 通知客户端执行解绑注销
return this.successResponse('setting.unbind', { reason: '电脑已被管理员删除' }, '电脑已注销');
}
if(computerInfo.status==0) {
//更新数据库为激活状态
await this.app.mysql.get("wms").update('wms_print_computer', { status: 1 }, { where: { warehouse_id: warehouse, id: computerId } });
}
console.log('查询打印机信息:', computerInfo);
this.app.redis.del(key); // 删除旧的打印机信息
this.app.redis.set(key, JSON.stringify(data), 'EX', 300); // 设置过期时间为 5分钟
// 将数据库中的电脑信息补充到下发数据中
if (computerInfo) {
data.name = computerInfo.name || '';
data.status = computerInfo.status;
data.is_recording = computerInfo.is_recording || 0;
data.recording_size_value = computerInfo.recording_size_value || 0;
data.recording_size_unit = computerInfo.recording_size_unit || '';
data.remote_play_url = computerInfo.remote_play_url || '';
data.recording_directory = computerInfo.recording_directory || '';
// 如果是录制电脑,生成 frp 连接配置
if (data.is_recording === 1) {
const frpToken = app.jwt.sign(
{ warehouse, computerId, purpose: 'frp' },
app.config.jwt.secret,
{ expiresIn: '24h' }
);
data.frp = {
subdomain: `${app.config.frp.subdomain_prefix || 'w'}${warehouse}-c${computerId}`,
server_addr: app.config.frp.server_addr,
server_port: app.config.frp.server_port,
auth_token: app.config.frp.auth_token,
local_port: app.config.frp.local_port,
token: frpToken,
};
}
}
data._source = 'getInfo'; // 标记来源
console.log(`[getInfo] 认证成功, computer=${computerId}, warehouse=${warehouse} (在线状态由 ping 维护)`);
return this.successResponse('setting.setInfo', data, 'Token 验证成功');
} catch (error) {
console.log(error);
@ -31,6 +71,29 @@ class AuthService extends BaseService {
}
}
/**
* 心跳 ping:客户端定期调用,维护 Redis 在线状态
* 写入/刷新 warehouse:{warehouse}:printer:{computerId},TTL 300 秒
*/
async ping() {
const { ctx, app } = this;
const info = ctx.print_computer_info;
if (!info) {
// 未登录,仅回 pong 不写 Redis
return this.successResponse('auth.ping', { timestamp: Date.now() }, 'pong');
}
const { warehouse, computerId, uniqueId } = info;
const key = `warehouse:${warehouse}:printer:${computerId}`;
// 写入/刷新电脑在线状态(含完整数据),TTL 5 分钟
await app.redis.set(key, JSON.stringify(info), 'EX', 300);
// 同时刷新 uniqueId 房间 key
await app.redis.expire(uniqueId, 300);
console.log(`[ping] 在线状态已刷新, computer=${computerId}, warehouse=${warehouse}`);
return this.successResponse('auth.ping', { timestamp: Date.now() }, 'pong');
}
async refreshToken(data) {
const { token } = data;
console.log('AuthService.refreshToken called with oldToken:', token);

413
app/service/hikvision.js Normal file
View File

@ -0,0 +1,413 @@
const BaseService = require('./base');
/**
* 海康录像任务服务
* 客户端通过 WebSocket 调用:
* hikvision.fetchTasks - 拉取待录像的打包任务
* hikvision.receiveTask - 确认接收任务,更新状态为 recording
* hikvision.taskComplete - 任务完成回调,写入结果
*/
class HikvisionService extends BaseService {
/**
* 将 MySQL DATETIME(存储为 UTC)转为 ISO 8601 北京时间 (+08:00)
* @param {string} datetime - DB 时间
* @param {number} offsetMs - 额外偏移(ms),负数=提前
*/
_toISO(datetime, offsetMs = 0) {
if (!datetime) return null;
const str = String(datetime).trim();
const utc = new Date(str + 'Z');
const cst = new Date(utc.getTime() + 8 * 3600000 + offsetMs);
return cst.toISOString().replace('Z', '+08:00');
}
/**
* 拉取待录像任务
* 查询 wms_pack_task 中 pack_mode=1 且无录像记录的任务
* 返回任务信息 + 摄像头信息 + 服务器信息
*/
async fetchTasks(data) {
const { app } = this;
const { print_computer_info } = this.ctx;
if (!print_computer_info) {
return this.errorResponse('hikvision.fetchTasks', '未绑定打印电脑信息');
}
const warehouseId = print_computer_info.warehouse;
try {
// 1. 查询该仓库待录像的打包任务(pack_mode=1, 状态不是已完成, 未删除)
const tasks = await app.mysql.get('wms').query(
`SELECT t.id, t.order_id, t.warehouse_id, t.workbench_id,
t.wave_no, t.waybill_code, t.device_ids, t.status AS task_status,
t.start_time, t.end_time, t.operator_text
FROM wms_pack_task t
WHERE t.warehouse_id = ?
AND t.deleted_at IS NULL
AND t.end_time IS NOT NULL
AND t.device_ids IS NOT NULL
AND t.device_ids != '[]'
AND t.id NOT IN (
SELECT v.pack_task_id FROM wms_pack_task_video v WHERE v.deleted_at IS NULL
)
ORDER BY t.id DESC
LIMIT 20`,
[warehouseId]
);
if (!tasks || tasks.length === 0) {
return this.successResponse('hikvision.fetchTasks', [], '暂无待录像任务');
}
// 2. 获取该仓库的摄像头服务器信息
const servers = await app.mysql.get('wms').select('wms_camera_server', {
where: { warehouse_id: warehouseId, deleted_at: null, status: 1 },
});
// 3. 获取该仓库的摄像头列表
const cameras = await app.mysql.get('wms').select('wms_camera', {
where: { warehouse_id: warehouseId, deleted_at: null, status: 1 },
});
// 4. 组装返回数据:每个任务的每个摄像头返回一条
const result = [];
for (const task of tasks) {
let deviceIds = [];
try {
deviceIds = typeof task.device_ids === 'string'
? JSON.parse(task.device_ids)
: (task.device_ids || []);
} catch (e) {
deviceIds = [];
}
for (const deviceId of deviceIds) {
// 按设备ID匹配摄像头
const matchedCamera = cameras.find(c => c.id === deviceId)
|| cameras.find(c => c.custom_name && c.custom_name.includes(`${task.workbench_id}号`))
|| cameras[0];
if (!matchedCamera) continue;
const matchedServer = servers.find(s => s.id === matchedCamera.server_id) || servers[0];
if (!matchedServer) continue;
// 先创建录像记录(状态=created),防止重复拉取
const existingVideo = await app.mysql.get('wms').get('wms_pack_task_video', {
pack_task_id: task.id,
deleted_at: null,
});
if (!existingVideo) {
await app.mysql.get('wms').insert('wms_pack_task_video', {
pack_task_id: task.id,
camera_id: matchedCamera.id,
video_url: '',
status: 'created',
});
console.log(`[Hikvision] 创建录像记录: pack_task=${task.id}, camera=${matchedCamera.id}`);
}
result.push({
pack_task_id: task.id,
device_id: deviceId,
uniqueCode: `${task.id}_${deviceId}`,
order_id: task.order_id,
warehouse_id: task.warehouse_id,
workbench_id: task.workbench_id,
wave_no: task.wave_no,
waybill_code: task.waybill_code,
task_status: task.task_status,
start_time: this._toISO(task.start_time, -5000),
end_time: this._toISO(task.end_time),
operator: task.operator_text,
camera: {
id: matchedCamera.id,
channel_id: matchedCamera.channel_id,
channel_name: matchedCamera.channel_name,
ip: matchedCamera.ip,
port: matchedCamera.port,
model: matchedCamera.model,
custom_name: matchedCamera.custom_name,
},
server: {
id: matchedServer.id,
brand: matchedServer.brand,
internal_ip: matchedServer.internal_ip,
internal_port: matchedServer.internal_port || 80,
username: matchedServer.username,
password: matchedServer.password,
},
});
}
}
console.log(`[Hikvision] 仓库 ${warehouseId} 返回 ${result.length} 个待录像任务`);
return this.successResponse('hikvision.fetchTasks', result, '查询成功');
} catch (error) {
console.error('[Hikvision] fetchTasks 错误:', error);
return this.errorResponse('hikvision.fetchTasks', error.message);
}
}
/**
* 客户端确认接收任务
* 创建 wms_pack_task_video 记录,状态改为 recording
*/
async receiveTask(data) {
const { app } = this;
const { taskId, uniqueCode, ok, message } = data || {};
if (!uniqueCode) {
return this.errorResponse('hikvision.receiveTask', '缺少 uniqueCode');
}
try {
// 从 uniqueCode 解析 pack_task_id(格式: {task_id}_{device_id})
const parts = uniqueCode.split('_');
const packTaskId = parseInt(parts[0]);
if (!packTaskId) {
return this.errorResponse('hikvision.receiveTask', '无法解析 pack_task_id');
}
if (ok) {
// 任务接收成功 → 创建录像记录,状态 recording
const existingVideo = await app.mysql.get('wms').get('wms_pack_task_video', {
pack_task_id: packTaskId,
deleted_at: null,
});
if (!existingVideo) {
await app.mysql.get('wms').insert('wms_pack_task_video', {
pack_task_id: packTaskId,
video_url: '',
status: 'recording',
remark: message || '任务已接收',
});
} else if (existingVideo.status === 'created') {
await app.mysql.get('wms').update('wms_pack_task_video',
{ status: 'recording', remark: message || '任务已接收' },
{ where: { id: existingVideo.id } }
);
}
console.log(`[Hikvision] 录像开始: pack_task=${packTaskId}, taskId=${taskId}`);
return this.successResponse('hikvision.receiveTask', { packTaskId, status: 'recording' }, '录像已开始');
} else {
// 任务接收失败
console.log(`[Hikvision] 任务接收失败: pack_task=${packTaskId}, message=${message}`);
return this.errorResponse('hikvision.receiveTask', message || '任务接收失败');
}
} catch (error) {
console.error('[Hikvision] receiveTask 错误:', error);
return this.errorResponse('hikvision.receiveTask', error.message);
}
}
/**
* 客户端回调:录像任务完成
* 成功 → 写入 video_url,状态 completed
* 失败 → 写入 remark,状态 failed
*/
async taskComplete(data) {
const { app } = this;
const { taskId, uniqueCode, status, success, output, size, duration, speed, fileUrl, error: errorMsg } = data || {};
if (!uniqueCode) {
return this.errorResponse('hikvision.taskComplete', '缺少 uniqueCode');
}
try {
const parts = uniqueCode.split('_');
const packTaskId = parseInt(parts[0]);
if (!packTaskId) {
return this.errorResponse('hikvision.taskComplete', '无法解析 pack_task_id');
}
if (success && status === 'completed') {
// 取最新的录像记录 ID 精准更新,避免 forceRecord 并发覆盖
const [latestVideo] = await app.mysql.get('wms').select('wms_pack_task_video', {
where: { pack_task_id: packTaskId, deleted_at: null },
orders: [['id', 'desc']],
limit: 1,
});
if (latestVideo) {
await app.mysql.get('wms').update('wms_pack_task_video',
{
video_url: fileUrl || output || '',
status: 'completed',
remark: `大小:${(size / 1024 / 1024).toFixed(2)}MB, 时长:${duration}s, 倍速:${speed}x`,
},
{ where: { id: latestVideo.id } }
);
}
console.log(`[Hikvision] 录像完成: pack_task=${packTaskId}, url=${fileUrl}, size=${size}`);
return this.successResponse('hikvision.taskComplete',
{ packTaskId, status: 'completed' }, '录像完成');
} else {
// 录像失败 - 同样精准更新最新记录
const [latestVideo] = await app.mysql.get('wms').select('wms_pack_task_video', {
where: { pack_task_id: packTaskId, deleted_at: null },
orders: [['id', 'desc']],
limit: 1,
});
if (latestVideo) {
await app.mysql.get('wms').update('wms_pack_task_video',
{ status: 'failed', remark: errorMsg || '录像失败' },
{ where: { id: latestVideo.id } }
);
}
console.log(`[Hikvision] 录像失败: pack_task=${packTaskId}, error=${errorMsg}`);
return this.successResponse('hikvision.taskComplete',
{ packTaskId, status: 'failed', error: errorMsg }, '录像失败已记录');
}
} catch (error) {
console.error('[Hikvision] taskComplete 错误:', error);
return this.errorResponse('hikvision.taskComplete', error.message);
}
}
/**
* 强制录制:外部 HTTP 调用,按 pack_task_id 强制推送录制任务
* 事务内重置已有录像行,推送成功后返回
*/
async forceRecord(data) {
const { app } = this;
const { pack_task_id } = data || {};
if (!pack_task_id) {
return { status: 'fail', message: '缺少 pack_task_id' };
}
try {
// 1. 查询打包任务
const task = await app.mysql.get('wms').get('wms_pack_task', {
id: pack_task_id,
deleted_at: null,
});
if (!task) {
return { status: 'fail', message: '打包任务不存在' };
}
if (!task.end_time || !task.device_ids || task.device_ids === '[]') {
return { status: 'fail', message: '打包任务未完成或无设备信息' };
}
// 2. 查询摄像头和服务器
const cameras = await app.mysql.get('wms').select('wms_camera', {
where: { warehouse_id: task.warehouse_id, deleted_at: null, status: 1 },
});
const servers = await app.mysql.get('wms').select('wms_camera_server', {
where: { warehouse_id: task.warehouse_id, deleted_at: null, status: 1 },
});
// 3. 找到同仓库的录制电脑
const warehousePattern = `warehouse:${task.warehouse_id}:printer:*`;
const onlineKeys = [];
let cursor = '0';
do {
const [nextCursor, keys] = await app.redis.scan(cursor, 'MATCH', warehousePattern, 'COUNT', 100);
cursor = nextCursor;
onlineKeys.push(...keys);
} while (cursor !== '0');
let recordingUniqueId = null;
for (const key of onlineKeys) {
const info = await app.redis.get(key);
if (!info) continue;
const parsed = JSON.parse(info);
if (parsed.is_recording === 1) {
recordingUniqueId = parsed.uniqueId;
break;
}
}
if (!recordingUniqueId) {
console.log(`[Hikvision] forceRecord 失败: 仓库 ${task.warehouse_id} 无录制电脑在线, 在线电脑: ${onlineKeys.length}台`);
return { status: 'fail', message: '该仓库无录制电脑在线' };
}
// 4. 事务:重置录像行
const deviceIds = typeof task.device_ids === 'string'
? JSON.parse(task.device_ids) : (task.device_ids || []);
const conn = await app.mysql.get('wms').beginTransaction();
try {
for (const deviceId of deviceIds) {
const matchedCamera = cameras.find(c => c.id === deviceId) || cameras[0];
if (!matchedCamera) continue;
const matchedServer = servers.find(s => s.id === matchedCamera.server_id) || servers[0];
if (!matchedServer) continue;
// 删除已有录像行,重新创建
await conn.delete('wms_pack_task_video', { pack_task_id: task.id });
await conn.insert('wms_pack_task_video', {
pack_task_id: task.id,
camera_id: matchedCamera.id,
video_url: '',
status: 'created',
});
await conn.commit();
console.log(`[Hikvision] 强制录制-重置录像行: pack_task=${task.id}`);
// 5. 推送录制任务
const payload = {
pack_task_id: task.id,
device_id: deviceId,
uniqueCode: `${task.id}_${deviceId}`,
order_id: task.order_id,
warehouse_id: task.warehouse_id,
workbench_id: task.workbench_id,
wave_no: task.wave_no,
waybill_code: task.waybill_code,
start_time: this._toISO(task.start_time, -5000),
end_time: this._toISO(task.end_time),
camera: {
id: matchedCamera.id,
channel_id: matchedCamera.channel_id,
channel_name: matchedCamera.channel_name,
ip: matchedCamera.ip,
port: matchedCamera.port,
model: matchedCamera.model,
},
server: {
id: matchedServer.id,
brand: matchedServer.brand,
internal_ip: matchedServer.internal_ip,
internal_port: matchedServer.internal_port || 80,
username: matchedServer.username,
password: matchedServer.password,
},
};
const sendRes = await app.ws.sendTo(recordingUniqueId, JSON.stringify({
method: 'hikvision.receiveTask',
data: payload,
}));
if (sendRes !== 1) {
return { status: 'fail', message: '推送失败,录制电脑可能已断开' };
}
console.log(`[Hikvision] 强制录制-已推送: pack_task=${task.id}, device=${deviceId}`);
}
} catch (txError) {
await conn.rollback();
throw txError;
}
return { status: 'success', message: '强制录制任务已推送', pack_task_id: task.id };
} catch (error) {
console.error('[Hikvision] forceRecord 错误:', error);
return { status: 'fail', message: error.message };
}
}
}
module.exports = HikvisionService;

View File

@ -58,6 +58,9 @@ module.exports = appInfo => {
port: 6379, // Redis端口
password: 'qwe2019@', // Redis密码(如果有)
db: 11, // 使用的数据库索引
retryStrategy: (times) => Math.min(times * 200, 5000), // 断线重连策略
maxRetriesPerRequest: 3,
reconnectOnError: (err) => err.message.includes('READONLY'),
},
};
config.websocket = {
@ -72,6 +75,16 @@ module.exports = appInfo => {
config.jwt = {
secret: 'E5#ex.g@,GfL_8?', // 请替换为自己的密钥
};
config.frp = {
server_addr: 'o.gztbyc.com', // frps 地址
server_port: 6005, // frps bindPort
auth_token: 'frpPrintToken2024', // frps auth.token
subdomain_host: 'o.gztbyc.com', // 子域名后缀
vhost_http_port: 18080, // frps HTTP 代理端口(内部)
local_port: 8080, // 客户端本地 web 服务端口
subdomain_prefix: 'w', // 子域名前缀
disconnect_timeout: 5000, // 等待其他电脑断开 frpc 的超时(ms)
};
return {
...config,
...userConfig,

View File

@ -0,0 +1,26 @@
# services.printer 部署配置示例
# 复制此文件为 deploy.config.local.cjs 并填入真实值
module.exports = {
production: {
host: '__FILL_SSH_HOST__',
port: 22,
username: '__FILL_SSH_USERNAME__',
privateKeyPath: 'C:/Users/your-user/.ssh/id_rsa',
deployRoot: '/www/wwwroot/services.printer',
sharedDirs: [ 'logs', 'run', 'tmp' ],
keepBackups: 5,
preDeployCommands: [
'node -v',
'npm -v',
],
postDeployCommands: [
'npm install --production',
'npm run stop || true',
'npm start',
],
healthCheckUrl: 'http://127.0.0.1:4051/',
sshOptions: [
'StrictHostKeyChecking=accept-new',
],
},
};

View File

@ -31,7 +31,14 @@
"test:local": "egg-bin test",
"cov": "egg-bin cov",
"lint": "eslint .",
"ci": "npm run lint && npm run cov"
"ci": "npm run lint && npm run cov",
"deploy": "node script/deploy-remote.cjs",
"deploy:precheck": "node script/deploy-precheck.cjs",
"deploy:version": "node script/deploy-version.cjs",
"deploy:ops": "node script/deploy-ops.cjs",
"deploy:rollback": "node script/rollback-remote.cjs",
"deploy:auth-check": "node script/deploy-auth-check.cjs",
"deploy:setup-hooks": "node script/setup-git-hooks.cjs"
},
"repository": {
"type": "git",

View File

@ -0,0 +1,42 @@
'use strict';
const { spawnSync } = require('node:child_process');
const { loadDeployConfig } = require('./deploy-lib.cjs');
function main() {
const config = loadDeployConfig('production');
const args = [ '-vv' ];
args.push('-p', String(config.port));
args.push('-i', config.privateKeyPath);
for (const option of config.sshOptions) {
args.push('-o', option);
}
args.push(`${config.username}@${config.host}`);
args.push('echo AUTH_CHECK_OK');
const result = spawnSync('ssh', args, {
encoding: 'utf8',
stdio: 'pipe',
shell: false,
});
const text = `${result.stdout || ''}\n${result.stderr || ''}`;
const summary = {
keyOffered: /Offering public key:/i.test(text) || /Will attempt key:/i.test(text),
keyAccepted: /Authenticated to .* using "publickey"/i.test(text) || /AUTH_CHECK_OK/i.test(text),
authFailed: /Permission denied|Authentication failed/i.test(text),
hostKeyFailed: /Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(text),
networkFailed: /Connection timed out|No route to host|Connection refused|Could not resolve hostname|Operation timed out/i.test(text),
};
console.log(JSON.stringify(summary, null, 2));
if (summary.keyAccepted) {
process.exit(0);
}
process.exit(1);
}
main();

354
script/deploy-lib.cjs Normal file
View File

@ -0,0 +1,354 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const ROOT = path.resolve(__dirname, '..');
const LOCAL_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.local.cjs');
const EXAMPLE_CONFIG_PATH = path.join(ROOT, 'config', 'deploy.config.example.cjs');
const DEFAULT_ENV = 'production';
const DEFAULT_EGG_MINIMAL_INCLUDE_PATHS = [
'app.js',
'app/**',
'package.json',
'package-lock.json',
];
const DEFAULT_POST_DEPLOY_COMMANDS = [
'npm install --production',
'npm run stop || true',
'npm start',
];
function quoteForBash(value) {
return `'${String(value).replace(/'/g, `'"'"'`)}'`;
}
function isGitAvailable() {
const result = spawnSync('git', [ 'rev-parse', '--git-dir' ], {
cwd: ROOT,
encoding: 'utf8',
stdio: 'pipe',
shell: false,
});
return result.status === 0;
}
/**
* 检查是否有未提交的更改
*/
function hasUncommittedChanges() {
if (!isGitAvailable()) return false;
const output = runCommandSafe('git', [ 'status', '--porcelain' ]);
return output.trim().length > 0;
}
function runCommand(command, args, options = {}) {
const result = spawnSync(command, args, {
cwd: options.cwd || ROOT,
encoding: 'utf8',
stdio: options.stdio || 'pipe',
shell: false,
});
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
const stderr = (result.stderr || '').trim();
const stdout = (result.stdout || '').trim();
throw new Error(stderr || stdout || `${command} exited with code ${result.status}`);
}
return (result.stdout || '').trim();
}
/**
* 安全执行命令,失败时返回空字符串而不是抛出异常
*/
function runCommandSafe(command, args, options = {}) {
const result = spawnSync(command, args, {
cwd: options.cwd || ROOT,
encoding: 'utf8',
stdio: 'pipe',
shell: false,
});
if (result.error || result.status !== 0) {
return '';
}
return (result.stdout || '').trim();
}
function ensureCommandAvailable(command, installHint) {
const result = spawnSync(command, [], {
cwd: ROOT,
encoding: 'utf8',
stdio: 'pipe',
shell: false,
});
if (result.error && result.error.code === 'ENOENT') {
throw new Error(`${command} 不可用。${installHint}`);
}
}
function getNowStamp() {
const now = new Date();
const pad = value => String(value).padStart(2, '0');
return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
}
function ensureTempDeployDir() {
const tempDir = path.join(ROOT, 'tmp', 'deploy');
fs.mkdirSync(tempDir, { recursive: true });
return tempDir;
}
function isPlaceholder(value) {
if (!value) {
return true;
}
return String(value).includes('__FILL_');
}
function normalizeDeployConfig(config, envName) {
const deployRoot = config.deployRoot || '/www/wwwroot/services.printer';
const privateKeyPath = config.privateKeyPath ? path.resolve(ROOT, config.privateKeyPath) : '';
const sshOptions = Array.isArray(config.sshOptions) ? [ ...config.sshOptions ] : [];
const preserveDirs = Array.isArray(config.preserveDirs) ? [ ...config.preserveDirs ] : [ 'config' ];
if (!preserveDirs.includes('config')) {
preserveDirs.push('config');
}
if (!sshOptions.some(option => /^IdentitiesOnly=/i.test(option))) {
sshOptions.push('IdentitiesOnly=yes');
}
if (!sshOptions.some(option => /^PreferredAuthentications=/i.test(option))) {
sshOptions.push('PreferredAuthentications=publickey');
}
if (!sshOptions.some(option => /^PubkeyAuthentication=/i.test(option))) {
sshOptions.push('PubkeyAuthentication=yes');
}
if (!sshOptions.some(option => /^PasswordAuthentication=/i.test(option))) {
sshOptions.push('PasswordAuthentication=no');
}
if (!sshOptions.some(option => /^KbdInteractiveAuthentication=/i.test(option))) {
sshOptions.push('KbdInteractiveAuthentication=no');
}
if (!sshOptions.some(option => /^BatchMode=/i.test(option))) {
sshOptions.push('BatchMode=yes');
}
if (!sshOptions.some(option => /^ConnectTimeout=/i.test(option))) {
sshOptions.push('ConnectTimeout=10');
}
const configuredPostDeployCommands = Array.isArray(config.postDeployCommands) && config.postDeployCommands.length > 0
? [ ...config.postDeployCommands ]
: [ ...DEFAULT_POST_DEPLOY_COMMANDS ];
if (!configuredPostDeployCommands.some(cmd => /^npm\s+install\s+--production(?:\s|$)/i.test(String(cmd).trim()))) {
configuredPostDeployCommands.unshift('npm install --production');
}
return {
envName,
host: config.host,
port: Number(config.port || 22),
username: config.username,
privateKeyPath,
deployRoot,
controlDir: `${deployRoot}/.deploy`,
incomingDir: `${deployRoot}/.deploy/incoming`,
backupDir: `${deployRoot}/.deploy/backups`,
stateDir: `${deployRoot}/.deploy/state`,
sharedDirs: Array.isArray(config.sharedDirs) ? config.sharedDirs : [ 'logs', 'run', 'tmp' ],
preserveDirs,
keepBackups: Number(config.keepBackups || 5),
preDeployCommands: Array.isArray(config.preDeployCommands) ? config.preDeployCommands : [],
postDeployCommands: configuredPostDeployCommands,
healthCheckUrl: config.healthCheckUrl || '',
deployIncludePaths: Array.isArray(config.deployIncludePaths) && config.deployIncludePaths.length > 0
? config.deployIncludePaths
: DEFAULT_EGG_MINIMAL_INCLUDE_PATHS,
deployExcludePaths: Array.isArray(config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ],
sshOptions,
};
}
function validateDeployConfig(config, configPath, envName) {
if (!config) {
throw new Error(`${configPath} 中未找到 ${envName} 配置。`);
}
const missing = [];
if (isPlaceholder(config.host)) missing.push('host');
if (isPlaceholder(config.username)) missing.push('username');
if (isPlaceholder(config.privateKeyPath)) missing.push('privateKeyPath');
if (missing.length > 0) {
throw new Error(`请先完善 SSH 配置字段: ${missing.join(', ')}。配置文件: ${configPath}`);
}
const resolvedPrivateKeyPath = path.resolve(ROOT, config.privateKeyPath);
if (!fs.existsSync(resolvedPrivateKeyPath)) {
throw new Error(`SSH 私钥不存在: ${resolvedPrivateKeyPath}。请先修正 config/deploy.config.local.cjs 中的 privateKeyPath。`);
}
}
function loadDeployConfig(envName = DEFAULT_ENV) {
if (!fs.existsSync(LOCAL_CONFIG_PATH)) {
throw new Error(`缺少本地部署配置 ${LOCAL_CONFIG_PATH}。请复制 ${EXAMPLE_CONFIG_PATH} 并填入 SSH 信息。`);
}
delete require.cache[LOCAL_CONFIG_PATH];
const loaded = require(LOCAL_CONFIG_PATH);
const config = loaded[envName];
validateDeployConfig(config, LOCAL_CONFIG_PATH, envName);
return normalizeDeployConfig(config, envName);
}
function buildSshBaseArgs(config) {
const args = [ '-p', String(config.port), '-i', config.privateKeyPath ];
for (const option of config.sshOptions) {
args.push('-o', option);
}
return args;
}
function runSsh(config, remoteScript, options = {}) {
const args = [
...buildSshBaseArgs(config),
`${config.username}@${config.host}`,
`bash -c ${quoteForBash(remoteScript)}`,
];
return runCommand('ssh', args, {
stdio: options.stdio || 'inherit',
});
}
function runScp(config, localPath, remotePath) {
const args = [ '-P', String(config.port), '-i', config.privateKeyPath ];
for (const option of config.sshOptions) {
args.push('-o', option);
}
args.push(
localPath,
`${config.username}@${config.host}:${remotePath}`,
);
return runCommand('scp', args, { stdio: 'inherit' });
}
function normalizeRule(rule) {
return String(rule || '').replace(/\\/g, '/').trim();
}
function pathMatchesRule(filePath, rule) {
const normalizedPath = String(filePath || '').replace(/\\/g, '/');
const normalizedRule = normalizeRule(rule);
if (!normalizedRule) {
return false;
}
if (normalizedRule.endsWith('/**')) {
const prefix = normalizedRule.slice(0, -3);
return normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`);
}
if (normalizedRule.endsWith('/')) {
return normalizedPath.startsWith(normalizedRule);
}
return normalizedPath === normalizedRule;
}
/**
* 递归遍历目录获取所有文件(非 git 模式回退方案)
*/
function walkDir(dir, basePath) {
const results = [];
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
const relativePath = path.relative(basePath, fullPath).replace(/\\/g, '/');
if (entry.isDirectory()) {
const skipDirs = [ '.git', 'node_modules', 'logs', 'run', 'tmp', '.deploy', '.vscode', '.idea' ];
if (skipDirs.includes(entry.name)) continue;
results.push(...walkDir(fullPath, basePath));
} else {
results.push(relativePath);
}
}
return results;
}
function listDeployableFiles(config) {
const includeRules = Array.isArray(config && config.deployIncludePaths) ? config.deployIncludePaths : DEFAULT_EGG_MINIMAL_INCLUDE_PATHS;
const excludeRules = Array.isArray(config && config.deployExcludePaths) ? config.deployExcludePaths : [ 'config/**' ];
let allFiles;
if (isGitAvailable()) {
const output = runCommandSafe('git', [ 'ls-files', '--cached', '--others', '--exclude-standard' ]);
allFiles = output
.split(/\r?\n/)
.map(item => item.trim())
.filter(Boolean)
.filter(item => !item.startsWith('.git/'))
.filter(item => fs.existsSync(path.join(ROOT, item)));
} else {
console.warn('[WARN] 未检测到 Git 仓库,使用文件系统遍历模式。建议初始化 Git 仓库以获得更精确的发布文件列表。');
allFiles = walkDir(ROOT, ROOT);
}
return Array.from(new Set(
allFiles
.filter(item => includeRules.some(rule => pathMatchesRule(item, rule)))
.filter(item => !excludeRules.some(rule => pathMatchesRule(item, rule)))
));
}
function buildArchive(stamp, config) {
const tempDir = ensureTempDeployDir();
const listPath = path.join(tempDir, `deploy-files-${stamp}.txt`);
const archivePath = path.join(tempDir, `release-${stamp}.tar.gz`);
const files = listDeployableFiles(config);
if (files.length === 0) {
throw new Error('git ls-files 未返回可发布文件,无法生成发布包。');
}
fs.writeFileSync(listPath, files.join('\n') + '\n', 'utf8');
runCommand('tar', [ '-czf', archivePath, '-T', listPath ], { stdio: 'inherit' });
return {
archivePath,
listPath,
};
}
function buildRemoteCleanupGuard(sharedDirs, preserveDirs = []) {
const preserved = [ '.deploy', ...sharedDirs, ...preserveDirs ];
return preserved.map(item => `! -name ${quoteForBash(item)}`).join(' ');
}
module.exports = {
ROOT,
buildArchive,
buildRemoteCleanupGuard,
ensureCommandAvailable,
getNowStamp,
hasUncommittedChanges,
isGitAvailable,
loadDeployConfig,
quoteForBash,
runCommand,
runCommandSafe,
runScp,
runSsh,
};

169
script/deploy-ops.cjs Normal file
View File

@ -0,0 +1,169 @@
'use strict';
const { loadDeployConfig, quoteForBash, runSsh } = require('./deploy-lib.cjs');
const COMMANDS = new Set([ 'inspect', 'smoke', 'verify', 'cleanup-backups', 'gateway-probe' ]);
function parseArgs(argv) {
const options = {
envName: 'production',
command: '',
args: [],
};
const tokens = [ ...argv ];
if (tokens.length === 0) {
throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe');
}
const first = tokens[0];
if (!COMMANDS.has(first)) {
options.envName = first;
tokens.shift();
}
if (tokens.length === 0) {
throw new Error('缺少命令: inspect | smoke | verify | cleanup-backups | gateway-probe');
}
options.command = tokens[0];
options.args = tokens.slice(1);
if (!COMMANDS.has(options.command)) {
throw new Error(`不支持的命令: ${options.command}`);
}
return options;
}
function getActivePortInfo(config) {
const currentMdPath = `${config.deployRoot}/current.md`;
const remoteScript = [
'set -euo pipefail',
`cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`,
].join('\n');
const output = runSsh(config, remoteScript, { stdio: 'pipe' });
const rawContent = String(output || '').trim();
if (!rawContent) {
throw new Error(
`无法读取远端 ${currentMdPath},内容为空或文件不存在。`
);
}
const version = rawContent.replace(/\r/g, '').trim();
if (version !== 'v1' && version !== 'v2') {
throw new Error(
`远端 current.md 内容无效: "${rawContent}",期望值为 v1 或 v2。文件路径: ${currentMdPath}`
);
}
const port = version === 'v1' ? 4051 : 4052;
return { port, version, rawContent };
}
function inspectState(config) {
const latestBackupFile = `${config.stateDir}/latest-backup.txt`;
const remoteScript = [
'set -euo pipefail',
`STATE_DIR=${quoteForBash(config.stateDir)}`,
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
`LATEST_FILE=${quoteForBash(latestBackupFile)}`,
'printf "[STATE]\\n"',
'ls -la "$STATE_DIR" 2>/dev/null || echo EMPTY',
'printf "\\n[LATEST_BACKUP]\\n"',
'if [ -f "$LATEST_FILE" ]; then cat "$LATEST_FILE"; else echo MISSING; fi',
'printf "\\n[BACKUPS]\\n"',
'ls -1 "$BACKUP_DIR" 2>/dev/null || echo EMPTY',
'printf "\\n[INSTANCES]\\n"',
'ls -la "$DEPLOY_ROOT/v1" 2>/dev/null | head -3 || echo "v1 EMPTY"',
'ls -la "$DEPLOY_ROOT/v2" 2>/dev/null | head -3 || echo "v2 EMPTY"',
'printf "\\n[CURRENT_MD]\\n"',
'cat "$DEPLOY_ROOT/current.md" 2>/dev/null || echo MISSING',
].join('\n');
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
}
function smokeRoutes(config) {
const { port } = getActivePortInfo(config);
const remoteScript = [
'set -euo pipefail',
`PORT=${port}`,
'for path in /; do',
' code=$(curl -sS -o /dev/null -w "%{http_code}" "http://127.0.0.1:$PORT$path" || true)',
' printf "%s %s\\n" "$path" "$code"',
'done',
].join('\n');
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
}
function cleanupBackups(config, names) {
if (!names.length) {
throw new Error('cleanup-backups 需要至少一个备份文件名');
}
const remoteScript = [
'set -euo pipefail',
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
...names.map((name, index) => `FILE_${index}=${quoteForBash(name)}`),
...names.map((_, index) => `if [ -f "$BACKUP_DIR/$FILE_${index}" ]; then rm -f "$BACKUP_DIR/$FILE_${index}"; echo "REMOVED $FILE_${index}"; else echo "MISS $FILE_${index}"; fi`),
].join('\n');
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
}
function gatewayProbe(config, probePort) {
let targetPort;
if (probePort && /^\d+$/.test(probePort)) {
targetPort = Number(probePort);
} else {
targetPort = getActivePortInfo(config).port;
}
const remoteScript = [
'set -euo pipefail',
`PORT=${targetPort}`,
'echo "[GATEWAY_PROBE] port=$PORT"',
'if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$PORT/" >/dev/null 2>&1; then',
' echo "GATEWAY_OK"',
'else',
' echo "GATEWAY_FAIL"',
'fi',
].join('\n');
return runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
}
function main() {
const options = parseArgs(process.argv.slice(2));
const config = loadDeployConfig(options.envName);
switch (options.command) {
case 'inspect':
console.log(inspectState(config));
break;
case 'smoke':
console.log(smokeRoutes(config));
break;
case 'verify': {
const activeInfo = getActivePortInfo(config);
console.log(`ACTIVE_VERSION=${activeInfo.version}`);
console.log(`ACTIVE_PORT=${activeInfo.port}`);
break;
}
case 'cleanup-backups':
console.log(cleanupBackups(config, options.args));
break;
case 'gateway-probe':
console.log(gatewayProbe(config, options.args[0] || ''));
break;
default:
throw new Error(`不支持的命令: ${options.command}`);
}
}
main();

View File

@ -0,0 +1,77 @@
'use strict';
const {
loadDeployConfig,
runSsh,
ensureCommandAvailable,
} = require('./deploy-lib.cjs');
function main() {
try {
[ 'ssh', 'scp', 'tar', 'git' ].forEach(cmd => ensureCommandAvailable(cmd, ''));
console.log('LOCAL_TOOLS_OK');
const config = loadDeployConfig('production');
const remoteScript = [
'set -euo pipefail',
`DEPLOY_ROOT=${JSON.stringify(config.deployRoot)}`,
'PARENT_DIR=$(dirname "$DEPLOY_ROOT")',
'if [ -d "$DEPLOY_ROOT" ]; then echo DEPLOY_ROOT_EXISTS; else echo DEPLOY_ROOT_MISSING; fi',
'if [ -d "$DEPLOY_ROOT" ] && [ -w "$DEPLOY_ROOT" ]; then echo DEPLOY_ROOT_WRITABLE; else echo DEPLOY_ROOT_NOT_WRITABLE; fi',
'if [ -d "$DEPLOY_ROOT/config" ]; then echo DEPLOY_CONFIG_EXISTS; else echo DEPLOY_CONFIG_MISSING; fi',
'if [ -d "$PARENT_DIR" ] && [ -w "$PARENT_DIR" ]; then echo PARENT_WRITABLE; else echo PARENT_NOT_WRITABLE; fi',
'if [ -d "$DEPLOY_ROOT/v1" ]; then echo V1_DIR_EXISTS; else echo V1_DIR_MISSING; fi',
'if [ -d "$DEPLOY_ROOT/v2" ]; then echo V2_DIR_EXISTS; else echo V2_DIR_MISSING; fi',
'if [ -f "$DEPLOY_ROOT/nginx-upstream.conf" ]; then echo NGINX_UPSTREAM_EXISTS; else echo NGINX_UPSTREAM_MISSING; fi',
'if command -v node >/dev/null 2>&1; then echo REMOTE_NODE_OK; node -v; else echo REMOTE_NODE_MISSING; fi',
'if command -v npm >/dev/null 2>&1; then echo REMOTE_NPM_OK; npm -v; else echo REMOTE_NPM_MISSING; fi',
'if command -v tar >/dev/null 2>&1; then echo REMOTE_TAR_OK; tar --version | head -n 1; else echo REMOTE_TAR_MISSING; fi',
'if command -v curl >/dev/null 2>&1; then',
' CURRENT_FILE="$DEPLOY_ROOT/current.md"',
' if [ -f "$CURRENT_FILE" ]; then',
' ACTIVE_VERSION=$(cat "$CURRENT_FILE" | tr -d "[:space:]")',
' if [ "$ACTIVE_VERSION" = "v1" ]; then',
' if curl -fsS http://127.0.0.1:4051/ >/dev/null; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi',
' elif [ "$ACTIVE_VERSION" = "v2" ]; then',
' if curl -fsS http://127.0.0.1:4052/ >/dev/null; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi',
' else',
' echo HEALTHCHECK_LOCAL_SKIP_UNKNOWN_VERSION',
' fi',
' else',
' V1_OK=false; V2_OK=false',
' if curl -fsS http://127.0.0.1:4051/ >/dev/null; then V1_OK=true; fi',
' if curl -fsS http://127.0.0.1:4052/ >/dev/null; then V2_OK=true; fi',
' if [ "$V1_OK" = "true" ] || [ "$V2_OK" = "true" ]; then echo HEALTHCHECK_LOCAL_OK; else echo HEALTHCHECK_LOCAL_FAIL; fi',
' fi',
'else echo REMOTE_CURL_MISSING; fi',
].join('\n');
const output = runSsh(config, remoteScript, { stdio: 'pipe' });
for (const line of output.split(/\r?\n/)) {
if (line.trim()) {
console.log(line.trim());
}
}
console.log('PRECHECK_OK');
} catch (error) {
const message = String(error && error.message ? error.message : '');
let reason = 'UNKNOWN';
if (/Permission denied|Authentication failed/i.test(message)) {
reason = 'AUTH';
} else if (/Connection timed out|No route to host|Connection refused|Could not resolve hostname/i.test(message)) {
reason = 'NETWORK';
} else if (/Host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(message)) {
reason = 'HOST_KEY';
} else if (/Operation timed out/i.test(message)) {
reason = 'TIMEOUT';
}
console.log('PRECHECK_FAIL');
console.log(`PRECHECK_REASON_${reason}`);
process.exit(1);
}
}
main();

439
script/deploy-remote.cjs Normal file
View File

@ -0,0 +1,439 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const {
ROOT,
buildArchive,
buildRemoteCleanupGuard,
ensureCommandAvailable,
getNowStamp,
isGitAvailable,
loadDeployConfig,
quoteForBash,
runCommand,
runCommandSafe,
runScp,
runSsh,
} = require('./deploy-lib.cjs');
/**
* 通过 SSH 读取远端 current.md 文件,获取当前活跃版本标识(v1 或 v2)
*/
function readRemoteCurrentVersion(config, deployRoot) {
const currentMdPath = `${deployRoot}/current.md`;
const script = `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`;
const output = runSsh(config, script, { stdio: 'pipe' });
const rawVersion = String(output || '').trim();
if (!rawVersion) {
throw new Error(
`无法读取远端当前版本文件: ${currentMdPath}。请确保远端已存在 ${deployRoot}/current.md 且内容为 v1 或 v2。`
);
}
const normalized = rawVersion.replace(/\r/g, '').trim();
if (normalized !== 'v1' && normalized !== 'v2') {
throw new Error(
`远端 current.md 内容无效: "${rawVersion}",期望值为 v1 或 v2。文件路径: ${currentMdPath}`
);
}
return normalized;
}
function resolveTargetDir(currentVersion, deployRoot) {
if (currentVersion === 'v1') return `${deployRoot}/v2`;
return `${deployRoot}/v1`;
}
function resolveTargetVersion(currentVersion) {
if (currentVersion === 'v1') return 'v2';
return 'v1';
}
function getTargetPort(targetVersion) {
if (targetVersion === 'v1') return 4051;
return 4052;
}
function getProcessTitle(version) {
return `egg-server-services.printer-${version}`;
}
function main() {
const envName = process.argv[2] || 'production';
const config = loadDeployConfig(envName);
ensureCommandAvailable('git', '请先安装 Git 并确保 git 在 PATH 中。');
ensureCommandAvailable('tar', '请先安装 tar,Windows 10/11 通常已内置 bsdtar。');
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
ensureCommandAvailable('scp', '请先安装 OpenSSH Client 并确保 scp 在 PATH 中。');
// 1. 部署前信息
console.log('========================================');
console.log('services.printer 蓝绿部署');
console.log(`环境: ${envName}`);
console.log(`目标: ${config.username}@${config.host}:${config.port}`);
console.log(`远端根目录: ${config.deployRoot}`);
console.log('========================================');
// 检查 Git 未提交更改
if (isGitAvailable()) {
const uncommitted = runCommandSafe('git', [ 'status', '--porcelain' ]);
if (uncommitted) {
console.warn('[WARN] 检测到未提交的更改:');
const changes = uncommitted.split(/\r?\n/).filter(Boolean);
for (const line of changes.slice(0, 10)) {
console.warn(` ${line}`);
}
if (changes.length > 10) {
console.warn(` ... 还有 ${changes.length - 10} 处更改`);
}
console.warn('[WARN] 未提交的更改不会被包含在发布包中!');
console.warn('[WARN] 建议先 git add && git commit 后再部署。');
}
}
// 2. 读取远端 current.md,确定目标目录
const currentVersion = readRemoteCurrentVersion(config, config.deployRoot);
const targetDir = resolveTargetDir(currentVersion, config.deployRoot);
console.log(`远端当前活跃版本: ${currentVersion},目标部署目录: ${targetDir}`);
// 3. 本地打包
console.log('[1/8] 正在本地打包...');
const stamp = getNowStamp();
const packageJson = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
const packageVersion = String(packageJson.version || '0.0.0');
let gitCommitShort = 'nogit';
if (isGitAvailable()) {
gitCommitShort = runCommandSafe('git', [ 'rev-parse', '--short', 'HEAD' ]) || 'nogit';
}
const releaseVersion = `v${packageVersion}-${stamp}-${gitCommitShort}`;
const { archivePath } = buildArchive(stamp, config);
console.log(`[1/8] 打包完成: ${archivePath}`);
const remoteArchive = `${config.incomingDir}/release-${stamp}.tar.gz`;
// 4. 远端创建目录结构
console.log('[2/8] 正在远端创建目录...');
const setupScript = [
'set -euo pipefail',
`mkdir -p ${quoteForBash(targetDir)} ${quoteForBash(config.incomingDir)} ${quoteForBash(config.backupDir)} ${quoteForBash(config.stateDir)}`,
].join('\n');
runSsh(config, setupScript);
console.log(`[2/8] 远端目录已就绪: ${targetDir}`);
// 5. 远端备份当前目标目录
console.log('[3/8] 正在备份远端目标目录...');
const backupScript = [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(targetDir)}`,
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
`STAMP=${quoteForBash(stamp)}`,
'if [ -f "$TARGET_DIR/package.json" ]; then',
' BACKUP_FILE="$BACKUP_DIR/backup-${STAMP}.tar.gz"',
' cd "$TARGET_DIR"',
' tar -czf "$BACKUP_FILE" . --exclude="./node_modules" --exclude="./.deploy" --exclude="./logs" --exclude="./run" --exclude="./tmp" 2>/dev/null || true',
' echo "已备份目标目录到: $BACKUP_FILE"',
'else',
' echo "目标目录为空,跳过备份"',
'fi',
].join('\n');
try {
const backupOutput = runSsh(config, backupScript, { stdio: 'pipe' });
console.log(String(backupOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 备份失败(非致命): ${err.message}`);
}
// 6. SCP 上传
console.log('[4/8] 正在上传发布包...');
runScp(config, archivePath, remoteArchive);
console.log(`[4/8] 发布包已上传到远端: ${remoteArchive}`);
// 7. 解压、安装依赖
const cleanupGuard = buildRemoteCleanupGuard(
[ ...config.sharedDirs, 'node_modules' ],
config.preserveDirs
);
const remoteScript = [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(targetDir)}`,
`REMOTE_ARCHIVE=${quoteForBash(remoteArchive)}`,
`ACTIVE_DIR=${quoteForBash(`${config.deployRoot}/${currentVersion}`)}`,
'cd "$TARGET_DIR"',
// 清理旧代码(保留 logs/run/tmp/node_modules/.deploy 等运行时目录)
`find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
'tar -xzf "$REMOTE_ARCHIVE" -C "$TARGET_DIR"',
'rm -f "$REMOTE_ARCHIVE"',
// 保留 config 目录
'if [ ! -d "$TARGET_DIR/config" ]; then',
' if [ -d "$ACTIVE_DIR/config" ]; then',
' cp -a "$ACTIVE_DIR/config" "$TARGET_DIR/config"',
' echo "已从活跃版本 ($ACTIVE_DIR) 复制 config 目录"',
' else',
` FALLBACK_DIR=${quoteForBash(config.deployRoot)}`,
' if [ -d "$FALLBACK_DIR/config" ]; then',
' cp -a "$FALLBACK_DIR/config" "$TARGET_DIR/config"',
' echo "已从根目录 ($FALLBACK_DIR) 复制 config 目录"',
' else',
' echo "[WARN] 未找到 config 目录来源,目标目录将缺少 config 配置!"',
' fi',
' fi',
'fi',
// 从活跃版本复制 node_modules(蓝绿部署核心优化,避免每次全量下载)
'if [ -d "$ACTIVE_DIR/node_modules" ]; then',
' echo "正在从活跃版本 ($ACTIVE_DIR) 复制 node_modules ..."',
' rm -rf "$TARGET_DIR/node_modules"',
' cp -a "$ACTIVE_DIR/node_modules" "$TARGET_DIR/node_modules"',
' echo "node_modules 复制完成"',
'fi',
// 增量更新依赖(node_modules 已存在,仅校验变更)
'npm install --production --prefer-offline --no-audit --no-fund',
].join('\n');
console.log('[5/8] 正在远端清理、解压、安装依赖...');
runSsh(config, remoteScript);
console.log(`[5/8] 远端目标目录已清理、解压并安装依赖: ${targetDir}`);
// 8. 目标版本信息
const targetVersion = resolveTargetVersion(currentVersion);
const targetPort = getTargetPort(targetVersion);
const targetTitle = getProcessTitle(targetVersion);
const currentTitle = getProcessTitle(currentVersion);
const startLogPath = `/tmp/services.printer-${targetVersion}-start.log`;
const currentMdPath = `${config.deployRoot}/current.md`;
const oldDir = `${config.deployRoot}/${currentVersion}`;
// 9. 停止目标目录可能残留的旧进程
const stopTargetScript = [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(targetDir)}`,
`TARGET_VERSION=${quoteForBash(targetVersion)}`,
`TARGET_TITLE=${quoteForBash(targetTitle)}`,
'TARGET_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
'TITLE_PIDS=$(ps -eo pid=,args= | awk -v t="$TARGET_TITLE" \'index($0, t) { print $1 }\')',
'ALL_PIDS=$(echo "$TARGET_PIDS $TITLE_PIDS" | tr " " "\\n" | sort -u | grep -v "^$" | tr "\\n" " ")',
'if [ -z "$ALL_PIDS" ]; then',
' echo "未找到目标目录 ($TARGET_VERSION) 残留进程"',
'else',
' echo "正在停止目标目录 ($TARGET_VERSION) 残留进程: $ALL_PIDS"',
' kill $ALL_PIDS || true',
' sleep 2',
' REMAIN=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
' if [ -n "$REMAIN" ]; then',
' kill -9 $REMAIN || true',
' fi',
' echo "目标目录 ($TARGET_VERSION) 残留进程已停止"',
'fi',
].join('\n');
try {
const stopTargetOutput = runSsh(config, stopTargetScript, { stdio: 'pipe' });
console.log(String(stopTargetOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 停止目标目录残留进程失败: ${err.message}`);
}
// 10. 检测并停止旧版根目录遗留进程(端口 4050 等)
const stopLegacyScript = [
'set -euo pipefail',
`ROOT_DIR=${quoteForBash(config.deployRoot)}`,
'LEGACY_PIDS=$(ps -eo pid=,args= | awk -v root="$ROOT_DIR" \'index($0, "baseDir") && index($0, root) && !index($0, root"/v1") && !index($0, root"/v2") { print $1 }\')',
'if [ -z "$LEGACY_PIDS" ]; then',
' echo "未发现旧版根目录遗留进程"',
'else',
' echo "发现旧版根目录遗留进程: $LEGACY_PIDS,正在停止..."',
' kill $LEGACY_PIDS || true',
' sleep 3',
' REMAIN=$(ps -eo pid=,args= | awk -v root="$ROOT_DIR" \'index($0, "baseDir") && index($0, root) && !index($0, root"/v1") && !index($0, root"/v2") { print $1 }\')',
' if [ -n "$REMAIN" ]; then',
' kill -9 $REMAIN || true',
' fi',
' echo "旧版根目录遗留进程已停止"',
'fi',
].join('\n');
try {
const legacyOutput = runSsh(config, stopLegacyScript, { stdio: 'pipe' });
console.log(String(legacyOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 旧版进程清理: ${err.message}`);
}
// 11. 启动新实例
console.log('[6/8] 正在启动新实例...');
const startScript = [
'set -euo pipefail',
`cd ${quoteForBash(targetDir)}`,
`nohup bash -lc 'npx egg-scripts start --daemon --title=${targetTitle} --sticky --port=${targetPort} --ignore-stderr' > ${quoteForBash(startLogPath)} 2>&1 &`,
`echo "已在 ${targetDir} 启动新实例 ${targetVersion} (title=${targetTitle}, 端口 ${targetPort}),启动日志: ${startLogPath}"`,
].join('\n');
const startOutput = runSsh(config, startScript, { stdio: 'pipe' });
console.log(String(startOutput || '').trim());
// 12. 健康检查
console.log('[7/8] 正在进行健康检查(最多等待 60 秒)...');
const healthCheckScript = [
'set -euo pipefail',
`TARGET_PORT=${targetPort}`,
'HEALTH_OK=false',
'for attempt in $(seq 1 30); do',
' if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then',
` echo "新实例 (${targetVersion}) 健康检查通过 (端口 $TARGET_PORT, 第 $attempt 次)"`,
' HEALTH_OK=true',
' break',
' fi',
' sleep 2',
'done',
'if [ "$HEALTH_OK" != "true" ]; then',
` echo "FATAL: 新实例 (${targetVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&2`,
' exit 1',
'fi',
].join('\n');
let healthPassed = false;
try {
const healthOutput = runSsh(config, healthCheckScript, { stdio: 'pipe' });
console.log(String(healthOutput || '').trim());
healthPassed = true;
} catch (err) {
console.error(`[FATAL] 新实例健康检查失败: ${err.message}`);
console.error(`[FATAL] 新实例 (${targetVersion}) 未能正常启动,保留当前活跃版本 (${currentVersion}) 不变。`);
console.error(`[FATAL] 请检查启动日志: ssh ${config.username}@${config.host} "cat ${startLogPath}"`);
console.error('[FATAL] 部署已中止,当前服务不受影响。');
// 清理失败的新实例
const cleanupFailedScript = [
'set -euo pipefail',
`TARGET_DIR=${quoteForBash(targetDir)}`,
'FAILED_PIDS=$(ps -eo pid=,args= | awk -v root="$TARGET_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
'if [ -n "$FAILED_PIDS" ]; then kill -9 $FAILED_PIDS || true; fi',
'echo "已清理失败的新实例进程"',
].join('\n');
try {
runSsh(config, cleanupFailedScript, { stdio: 'pipe' });
} catch (_) { /* ignore */ }
process.exit(1);
}
// 13. 切换 current.md
console.log('[8/8] 正在切换流量...');
const switchCurrentMdScript = [
'set -euo pipefail',
`printf '%s\\n' ${quoteForBash(targetVersion)} > ${quoteForBash(currentMdPath)}`,
`echo "current.md 已切换 -> ${targetVersion}"`,
].join('\n');
const switchOutput2 = runSsh(config, switchCurrentMdScript, { stdio: 'pipe' });
console.log(String(switchOutput2 || '').trim());
// 14. 切换 Nginx upstream 并 reload
const nginxUpstreamPath = `${config.deployRoot}/nginx-upstream.conf`;
const switchNginxScript = [
'set -euo pipefail',
`printf 'proxy_pass http://127.0.0.1:%s;\\n' ${targetPort} > ${quoteForBash(nginxUpstreamPath)}`,
'nginx -t && nginx -s reload',
`echo "Nginx upstream 已切换至 127.0.0.1:${targetPort}"`,
].join('\n');
try {
const nginxOutput = runSsh(config, switchNginxScript, { stdio: 'pipe' });
console.log(String(nginxOutput || '').trim());
} catch (err) {
console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`);
console.warn(`[WARN] 新实例已在端口 ${targetPort} 运行,但 Nginx 未自动切换。`);
console.warn(`[WARN] 请手动更新 ${nginxUpstreamPath} 并执行 nginx -s reload`);
}
// 15. 停止旧实例
const stopOldScript = [
'set -euo pipefail',
`OLD_DIR=${quoteForBash(oldDir)}`,
`OLD_VERSION=${quoteForBash(currentVersion)}`,
`OLD_TITLE=${quoteForBash(currentTitle)}`,
'OLD_PIDS=$(ps -eo pid=,args= | awk -v root="$OLD_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
'if [ -z "$OLD_PIDS" ]; then',
' echo "未找到旧实例 ($OLD_VERSION) 进程,跳过停止步骤"',
'else',
' echo "正在停止旧实例 ($OLD_VERSION): $OLD_PIDS"',
' kill $OLD_PIDS || true',
' sleep 3',
' OLD_PIDS_REMAIN=$(ps -eo pid=,args= | awk -v root="$OLD_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
' if [ -n "$OLD_PIDS_REMAIN" ]; then',
' echo "旧实例 ($OLD_VERSION) 仍有残留进程,强制停止: $OLD_PIDS_REMAIN"',
' kill -9 $OLD_PIDS_REMAIN || true',
' fi',
' echo "旧实例 ($OLD_VERSION) 已停止"',
'fi',
].join('\n');
try {
const stopOutput = runSsh(config, stopOldScript, { stdio: 'pipe' });
console.log(String(stopOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 停止旧实例失败: ${err.message}`);
console.warn(`[WARN] 旧实例 (${currentVersion}) 可能仍在运行,请人工确认并停止`);
}
// 16. 记录远端 release 状态
const remoteStateFile = `${config.stateDir}/current-release.json`;
const remoteHistoryFile = `${config.stateDir}/release-history.jsonl`;
const releaseEntry = {
releaseVersion,
packageVersion,
gitCommitShort,
deployRoot: config.deployRoot,
targetVersion,
targetPort,
deployedAt: new Date().toISOString(),
};
const releaseJson = JSON.stringify(releaseEntry);
const recordReleaseScript = [
'set -euo pipefail',
`STATE_FILE=${quoteForBash(remoteStateFile)}`,
`HISTORY_FILE=${quoteForBash(remoteHistoryFile)}`,
`ENTRY=${quoteForBash(releaseJson)}`,
'printf "%s\\n" "$ENTRY" > "$STATE_FILE"',
'printf "%s\\n" "$ENTRY" >> "$HISTORY_FILE"',
'echo "远端 release 状态已记录"',
].join('\n');
try {
const recordOutput = runSsh(config, recordReleaseScript, { stdio: 'pipe' });
console.log(String(recordOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 记录远端 release 状态失败: ${err.message}`);
}
// 17. 清理旧备份
const cleanupBackupsScript = [
'set -euo pipefail',
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
`KEEP=${Number(config.keepBackups)}`,
'cd "$BACKUP_DIR"',
'ls -1t backup-*.tar.gz 2>/dev/null | tail -n +$((KEEP + 1)) | while read -r f; do rm -f "$f"; echo "已清理旧备份: $f"; done',
'echo "备份清理完成(保留最近 ${KEEP} 个)"',
].join('\n');
try {
const cleanupOutput = runSsh(config, cleanupBackupsScript, { stdio: 'pipe' });
console.log(String(cleanupOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 清理旧备份失败: ${err.message}`);
}
// 18. 完成
console.log('========================================');
console.log(`发布完成: ${envName} -> ${config.username}@${config.host}:${targetDir}`);
console.log(`线上版本号: ${releaseVersion}`);
console.log(`当前活跃版本已切换为: ${targetVersion} (端口 ${targetPort})`);
console.log('========================================');
}
main();

165
script/deploy-version.cjs Normal file
View File

@ -0,0 +1,165 @@
'use strict';
const path = require('node:path');
const {
ensureCommandAvailable,
loadDeployConfig,
quoteForBash,
runSsh,
} = require('./deploy-lib.cjs');
function parseArgs(argv) {
const options = {
history: 0,
};
for (const item of argv) {
if (!item) continue;
if (item.startsWith('--history=')) {
const value = Number(item.slice('--history='.length));
if (Number.isFinite(value) && value > 0) {
options.history = Math.floor(value);
}
}
}
return options;
}
function queryActiveInstance(config) {
const currentMdFile = path.posix.join(config.deployRoot, 'current.md');
const remoteScript = [
'set -euo pipefail',
`FILE=${quoteForBash(currentMdFile)}`,
'if [ -f "$FILE" ]; then',
' cat "$FILE"',
'else',
' echo CURRENT_MD_NOT_FOUND',
'fi',
].join('\n');
const raw = runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
if (!raw || raw === 'CURRENT_MD_NOT_FOUND') {
return null;
}
const version = raw.replace(/[\r\n\s]/g, '');
if (version !== 'v1' && version !== 'v2') {
return null;
}
const port = version === 'v2' ? 4052 : 4051;
return { version, port, currentMd: raw.split('\n')[0].trim() };
}
function queryCurrentRelease(config) {
const releaseFile = path.posix.join(config.stateDir, 'current-release.json');
const remoteScript = [
'set -euo pipefail',
`FILE=${quoteForBash(releaseFile)}`,
'if [ -f "$FILE" ]; then',
' cat "$FILE"',
'else',
' echo ONLINE_VERSION_NOT_FOUND',
'fi',
].join('\n');
const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
if (!output || output === 'ONLINE_VERSION_NOT_FOUND') {
return null;
}
try {
return JSON.parse(output);
} catch (error) {
return output;
}
}
function queryReleaseHistory(config, limit) {
const historyFile = path.posix.join(config.stateDir, 'release-history.jsonl');
const remoteScript = [
'set -euo pipefail',
`FILE=${quoteForBash(historyFile)}`,
`LIMIT=${Number(limit)}`,
'if [ -f "$FILE" ]; then',
' tail -n "$LIMIT" "$FILE"',
'else',
' echo ONLINE_VERSION_HISTORY_NOT_FOUND',
'fi',
].join('\n');
const output = runSsh(config, remoteScript, { stdio: 'pipe' }).trim();
if (!output || output === 'ONLINE_VERSION_HISTORY_NOT_FOUND') {
return null;
}
const records = [];
for (const line of output.split(/\r?\n/)) {
const trimmed = line.trim();
if (!trimmed) continue;
try {
records.push(JSON.parse(trimmed));
} catch (error) {
records.push({ raw: trimmed });
}
}
return records;
}
function main() {
const envName = process.argv[2] || 'production';
const options = parseArgs(process.argv.slice(3));
const config = loadDeployConfig(envName);
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
const active = queryActiveInstance(config);
const currentRelease = queryCurrentRelease(config);
console.log('========================================');
console.log(`部署环境: ${envName}`);
console.log(`远端主机: ${config.username}@${config.host}:${config.port}`);
console.log(`部署根目录: ${config.deployRoot}`);
console.log('========================================');
if (active) {
console.log(`活跃版本: ${active.version} (端口 ${active.port})`);
} else {
console.log('活跃版本: 未检测到(current.md 不存在或无效)');
}
console.log('----------------------------------------');
if (currentRelease && typeof currentRelease === 'object') {
console.log('当前线上版本:');
console.log(` 发布版本: ${currentRelease.releaseVersion || 'N/A'}`);
console.log(` package版本: ${currentRelease.packageVersion || 'N/A'}`);
console.log(` Git commit: ${currentRelease.gitCommitShort || 'N/A'}`);
console.log(` 目标版本: ${currentRelease.targetVersion || 'N/A'} (端口 ${currentRelease.targetPort || 'N/A'})`);
console.log(` 发布时间: ${currentRelease.deployedAt || 'N/A'}`);
} else if (currentRelease) {
console.log(`当前线上版本 (原始): ${String(currentRelease)}`);
} else {
console.log('当前线上版本: 未记录');
}
if (options.history > 0) {
console.log('----------------------------------------');
console.log(`最近 ${options.history} 条发布记录:`);
const history = queryReleaseHistory(config, options.history);
if (history && history.length > 0) {
for (const record of history) {
if (record.releaseVersion) {
console.log(` ${record.releaseVersion} | ${record.targetVersion || '?'} | ${record.deployedAt || '?'}`);
} else {
console.log(` ${JSON.stringify(record)}`);
}
}
} else {
console.log(' (无历史记录)');
}
}
}
main();

View File

@ -0,0 +1,44 @@
'use strict';
const path = require('node:path');
const { runCommandSafe } = require('./deploy-lib.cjs');
const BLOCKED_PATH_PATTERNS = [
/^config\/config\.local\.js$/,
/^config\/deploy\.config\.local\.cjs$/,
/^tmp\/(?!deploy\/)(?!docs\/).+/,
/^logs\//,
/^run\//,
/\.pem$/i,
/\.key$/i,
/^\.env(?:\..+)?$/,
];
function normalizePath(filePath) {
return filePath.replace(/\\/g, '/');
}
function listStagedFiles() {
const output = runCommandSafe('git', [ 'diff', '--cached', '--name-only', '--diff-filter=ACMR' ]);
if (!output) return [];
return output.split(/\r?\n/).map(item => normalizePath(item.trim())).filter(Boolean);
}
function main() {
const stagedFiles = listStagedFiles();
const blocked = stagedFiles.filter(filePath => BLOCKED_PATH_PATTERNS.some(pattern => pattern.test(filePath)));
if (blocked.length === 0) {
console.log('git safety check passed');
return;
}
console.error('以下文件禁止提交到 git,请先取消暂存:');
for (const filePath of blocked) {
console.error(`- ${filePath}`);
}
console.error('建议使用 git restore --staged <file> 取消暂存,再继续提交。');
process.exit(1);
}
main();

196
script/rollback-remote.cjs Normal file
View File

@ -0,0 +1,196 @@
'use strict';
const path = require('node:path');
const {
buildRemoteCleanupGuard,
ensureCommandAvailable,
loadDeployConfig,
quoteForBash,
runSsh,
} = require('./deploy-lib.cjs');
function readRemoteCurrentVersion(config, deployRoot) {
const currentMdPath = `${deployRoot}/current.md`;
const script = `cat ${quoteForBash(currentMdPath)} 2>/dev/null || true`;
const output = runSsh(config, script, { stdio: 'pipe' });
const rawVersion = String(output || '').trim();
if (!rawVersion) {
throw new Error(
`无法读取远端当前版本文件: ${currentMdPath}。请确保远端已存在 ${deployRoot}/current.md 且内容为 v1 或 v2。`
);
}
const normalized = rawVersion.replace(/\r/g, '').trim();
if (normalized !== 'v1' && normalized !== 'v2') {
throw new Error(
`远端 current.md 内容无效: "${rawVersion}",期望值为 v1 或 v2。文件路径: ${currentMdPath}`
);
}
return normalized;
}
function getTargetPort(targetVersion) {
if (targetVersion === 'v1') return 4051;
return 4052;
}
function parseBackupArg(argv) {
const backupArg = argv.find(item => item.startsWith('--backup='));
if (!backupArg) return '';
return backupArg.slice('--backup='.length).trim();
}
function getProcessTitle(version) {
return `egg-server-services.printer-${version}`;
}
function main() {
const envName = process.argv[2] || 'production';
const config = loadDeployConfig(envName);
const backupName = parseBackupArg(process.argv.slice(3));
ensureCommandAvailable('ssh', '请先安装 OpenSSH Client 并确保 ssh 在 PATH 中。');
// 1. 读取远端 current.md
const currentVersion = readRemoteCurrentVersion(config, config.deployRoot);
const currentDir = `${config.deployRoot}/${currentVersion}`;
const currentPort = getTargetPort(currentVersion);
const currentTitle = getProcessTitle(currentVersion);
console.log(`远端当前活跃版本: ${currentVersion},活跃目录: ${currentDir},端口: ${currentPort}`);
// 2. 确定备份包
const latestBackupFile = path.posix.join(config.stateDir, 'latest-backup.txt');
const selectBackupScript = [
'set -euo pipefail',
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
`LATEST_BACKUP_FILE=${quoteForBash(latestBackupFile)}`,
`REQUESTED_BACKUP=${quoteForBash(backupName)}`,
'if [ -n "$REQUESTED_BACKUP" ]; then',
' TARGET_BACKUP="$REQUESTED_BACKUP"',
'elif [ -f "$LATEST_BACKUP_FILE" ]; then',
' TARGET_BACKUP="$(cat "$LATEST_BACKUP_FILE")"',
'else',
' echo "ERROR: 未找到最近一次发布备份,请通过 --backup=backup-时间戳.tar.gz 指定回退包。" >&2',
' exit 1',
'fi',
'if [ ! -f "$BACKUP_DIR/$TARGET_BACKUP" ]; then',
' echo "ERROR: 备份包不存在: $BACKUP_DIR/$TARGET_BACKUP" >&2',
' exit 1',
'fi',
'echo "SELECTED_BACKUP=$TARGET_BACKUP"',
'echo "$TARGET_BACKUP"',
].join('\n');
const selectedBackup = runSsh(config, selectBackupScript, { stdio: 'pipe' }).trim();
const backupFile = selectedBackup.replace(/^SELECTED_BACKUP=/, '').split('\n').pop().trim();
if (!backupFile || backupFile.startsWith('ERROR:')) {
throw new Error(selectedBackup);
}
console.log(`使用备份包: ${config.backupDir}/${backupFile}`);
// 3. 停止当前活跃实例
const stopCurrentScript = [
'set -euo pipefail',
`CURRENT_DIR=${quoteForBash(currentDir)}`,
`CURRENT_VERSION=${quoteForBash(currentVersion)}`,
'CURRENT_PIDS=$(ps -eo pid=,args= | awk -v root="$CURRENT_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
'if [ -z "$CURRENT_PIDS" ]; then',
' echo "未找到当前实例 ($CURRENT_VERSION) 进程"',
'else',
' echo "正在停止当前实例 ($CURRENT_VERSION): $CURRENT_PIDS"',
' kill $CURRENT_PIDS || true',
' sleep 3',
' REMAIN=$(ps -eo pid=,args= | awk -v root="$CURRENT_DIR" \'index($0, root) && $2 ~ /node$/ { print $1 }\')',
' if [ -n "$REMAIN" ]; then',
' kill -9 $REMAIN || true',
' fi',
' echo "当前实例 ($CURRENT_VERSION) 已停止"',
'fi',
].join('\n');
try {
const stopOutput = runSsh(config, stopCurrentScript, { stdio: 'pipe' });
console.log(String(stopOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 停止当前实例失败: ${err.message}`);
}
// 4. 清理当前活跃目录并解压备份包
const cleanupGuard = buildRemoteCleanupGuard(config.sharedDirs, config.preserveDirs);
const rollbackScript = [
'set -euo pipefail',
`CURRENT_DIR=${quoteForBash(currentDir)}`,
`BACKUP_DIR=${quoteForBash(config.backupDir)}`,
`BACKUP_FILE=${quoteForBash(backupFile)}`,
'cd "$CURRENT_DIR"',
`find . -mindepth 1 -maxdepth 1 ${cleanupGuard} -exec rm -rf {} +`,
'tar -xzf "$BACKUP_DIR/$BACKUP_FILE" -C "$CURRENT_DIR"',
'npm install --production',
'echo "备份包已解压并安装依赖: $BACKUP_FILE"',
].join('\n');
runSsh(config, rollbackScript);
console.log(`回滚包已解压到: ${currentDir}`);
// 5. 重启当前实例
const startLogPath = `/tmp/services.printer-${currentVersion}-rollback.log`;
const restartScript = [
'set -euo pipefail',
`cd ${quoteForBash(currentDir)}`,
`nohup bash -lc 'npx egg-scripts start --daemon --title=${currentTitle} --sticky --port=${currentPort} --ignore-stderr' > ${quoteForBash(startLogPath)} 2>&1 &`,
`echo "已在 ${currentDir} 重启实例 ${currentVersion} (title=${currentTitle}, 端口 ${currentPort}),启动日志: ${startLogPath}"`,
].join('\n');
const restartOutput = runSsh(config, restartScript, { stdio: 'pipe' });
console.log(String(restartOutput || '').trim());
// 6. 健康检查
const healthCheckScript = [
'set -euo pipefail',
`TARGET_PORT=${currentPort}`,
'for attempt in $(seq 1 30); do',
' if curl -fsS --connect-timeout 2 --max-time 4 "http://127.0.0.1:$TARGET_PORT/" >/dev/null 2>&1; then',
` echo "回滚实例 (${currentVersion}) 健康检查通过 (端口 $TARGET_PORT)"`,
' break',
' fi',
' if [ "$attempt" -eq 30 ]; then',
` echo "回滚实例 (${currentVersion}) 健康检查超时 (端口 $TARGET_PORT)" >&2`,
' exit 1',
' fi',
' sleep 2',
'done',
].join('\n');
try {
const healthOutput = runSsh(config, healthCheckScript, { stdio: 'pipe' });
console.log(String(healthOutput || '').trim());
} catch (err) {
console.warn(`[WARN] 回滚实例健康检查失败: ${err.message}`);
}
// 7. 确保 Nginx upstream 指向当前端口
const nginxUpstreamPath = `${config.deployRoot}/nginx-upstream.conf`;
const switchNginxScript = [
'set -euo pipefail',
`printf 'proxy_pass http://127.0.0.1:%s;\\n' ${currentPort} > ${quoteForBash(nginxUpstreamPath)}`,
'nginx -t && nginx -s reload',
`echo "Nginx upstream 已确认指向 127.0.0.1:${currentPort}"`,
].join('\n');
try {
const nginxOutput = runSsh(config, switchNginxScript, { stdio: 'pipe' });
console.log(String(nginxOutput || '').trim());
} catch (err) {
console.warn(`[WARN] Nginx upstream 切换失败: ${err.message}`);
}
console.log('========================================');
console.log(`回滚完成: ${currentVersion} (端口 ${currentPort})`);
console.log(`使用备份包: ${backupFile}`);
console.log('========================================');
}
main();

View File

@ -0,0 +1,45 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const { ROOT } = require('./deploy-lib.cjs');
function main() {
const hooksDir = path.join(ROOT, '.githooks');
const gitHooksDir = path.join(ROOT, '.git', 'hooks');
if (!fs.existsSync(hooksDir)) {
fs.mkdirSync(hooksDir, { recursive: true });
}
// 创建 pre-commit hook 脚本
const preCommitPath = path.join(hooksDir, 'pre-commit');
const preCommitContent = [
'#!/bin/sh',
'node script/git-safety-check.cjs',
'',
].join('\n');
fs.writeFileSync(preCommitPath, preCommitContent, { mode: 0o755 });
// 配置 git 使用 .githooks 目录
const { execSync } = require('node:child_process');
try {
execSync('git config core.hooksPath .githooks', { cwd: ROOT, encoding: 'utf8' });
console.log('Git hooks 已配置: core.hooksPath = .githooks');
} catch (error) {
console.warn('配置 git core.hooksPath 失败,请手动执行: git config core.hooksPath .githooks');
}
// 确保 .gitignore 中有 versioning 相关规则
const gitignorePath = path.join(ROOT, '.gitignore');
if (fs.existsSync(gitignorePath)) {
const content = fs.readFileSync(gitignorePath, 'utf8');
if (!content.includes('versioning/')) {
console.warn('建议在 .gitignore 中添加 versioning/ 规则以保护本地版本记录');
}
}
console.log('Git hooks 设置完成。');
}
main();

View File

@ -0,0 +1,27 @@
'use strict';
const { readVersionHistory } = require('./version-registry.cjs');
function parseLimit(argv) {
for (const item of argv) {
if (item.startsWith('--limit=')) {
const value = Number(item.slice('--limit='.length));
if (Number.isFinite(value) && value > 0) {
return Math.floor(value);
}
}
}
return 20;
}
function main() {
const limit = parseLimit(process.argv.slice(2));
const records = readVersionHistory(limit);
if (records.length === 0) {
console.log('LOCAL_VERSION_HISTORY_EMPTY');
return;
}
console.log(JSON.stringify(records, null, 2));
}
main();

24
script/version-record.cjs Normal file
View File

@ -0,0 +1,24 @@
'use strict';
const { recordVersionUpdate } = require('./version-registry.cjs');
function parseArgs(argv) {
let note = '';
for (const item of argv) {
if (item.startsWith('--note=')) {
note = item.slice('--note='.length).trim();
}
}
return { note };
}
function main() {
const options = parseArgs(process.argv.slice(2));
const entry = recordVersionUpdate({
source: 'version:record',
note: options.note || 'package-version-update',
});
console.log(JSON.stringify(entry, null, 2));
}
main();

View File

@ -0,0 +1,95 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const { ROOT, runCommand, runCommandSafe, isGitAvailable } = require('./deploy-lib.cjs');
const VERSION_DIR = path.join(ROOT, 'versioning');
const VERSION_HISTORY_FILE = path.join(VERSION_DIR, 'package-version-history.jsonl');
const VERSION_CURRENT_FILE = path.join(VERSION_DIR, 'package-version-current.json');
function ensureVersionDir() {
fs.mkdirSync(VERSION_DIR, { recursive: true });
}
function getPackageMeta() {
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8'));
const packageVersion = String(pkg.version || '0.0.0');
let gitCommit = '';
let gitCommitShort = '';
let gitBranch = '';
if (isGitAvailable()) {
try {
gitCommit = runCommand('git', [ 'rev-parse', 'HEAD' ]);
gitCommitShort = runCommand('git', [ 'rev-parse', '--short', 'HEAD' ]);
gitBranch = runCommand('git', [ 'rev-parse', '--abbrev-ref', 'HEAD' ]);
} catch (error) {
gitCommit = '';
gitCommitShort = '';
gitBranch = '';
}
}
return {
packageVersion,
gitCommit,
gitCommitShort,
gitBranch,
};
}
function recordVersionUpdate(options = {}) {
ensureVersionDir();
const meta = getPackageMeta();
const entry = {
recordedAt: new Date().toISOString(),
source: options.source || 'manual',
note: options.note || '',
packageVersion: meta.packageVersion,
gitCommit: meta.gitCommit,
gitCommitShort: meta.gitCommitShort,
gitBranch: meta.gitBranch,
releaseVersion: options.releaseVersion || '',
deployRoot: options.deployRoot || '',
remoteBackupFile: options.remoteBackupFile || '',
remoteStateFile: options.remoteStateFile || '',
remoteHistoryFile: options.remoteHistoryFile || '',
};
fs.appendFileSync(VERSION_HISTORY_FILE, `${JSON.stringify(entry)}\n`, 'utf8');
fs.writeFileSync(VERSION_CURRENT_FILE, `${JSON.stringify(entry, null, 2)}\n`, 'utf8');
return entry;
}
function readVersionHistory(limit = 20) {
if (!fs.existsSync(VERSION_HISTORY_FILE)) {
return [];
}
const lines = fs.readFileSync(VERSION_HISTORY_FILE, 'utf8')
.split(/\r?\n/)
.map(item => item.trim())
.filter(Boolean);
const take = Math.max(1, Number(limit || 20));
const selected = lines.slice(-take);
const records = [];
for (const line of selected) {
try {
records.push(JSON.parse(line));
} catch (error) {
records.push({ raw: line });
}
}
return records;
}
module.exports = {
VERSION_CURRENT_FILE,
VERSION_DIR,
VERSION_HISTORY_FILE,
readVersionHistory,
recordVersionUpdate,
};