Skip to content

Commit 8ef395f

Browse files
committed
Refactor configuration management by replacing config.js with config-store.js, enhancing error handling and logging in admin.js and auth.js, and updating Docker image references in build-runner.yml. Clean up code formatting across multiple files for improved readability.
1 parent 31ae6e9 commit 8ef395f

File tree

8 files changed

+336
-281
lines changed

8 files changed

+336
-281
lines changed

.github/workflows/build-runner.yml

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ on:
44
push:
55
branches: ["main"]
66
tags: ["v*"]
7-
pull_request:
8-
branches: ["main"]
7+
paths:
8+
- "CodeRunner/**"
99
workflow_dispatch:
1010

1111
concurrency:
@@ -42,8 +42,8 @@ jobs:
4242
uses: docker/metadata-action@v5
4343
with:
4444
images: |
45-
sunwuyuan/coderun
46-
ghcr.io/zerocatdev/coderun
45+
sunwuyuan/coderunner
46+
ghcr.io/zerocatdev/coderunner
4747
tags: |
4848
type=ref,event=branch
4949
type=ref,event=pr
@@ -59,7 +59,7 @@ jobs:
5959
- name: Build and push Docker image
6060
uses: docker/build-push-action@v5
6161
with:
62-
context: .
62+
context: CodeRunner
6363
push: ${{ github.event_name != 'pull_request' }}
6464
tags: ${{ steps.meta.outputs.tags }}
6565
labels: ${{ steps.meta.outputs.labels }}

server.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
#!/usr/bin/env node
22

33
const { app, server } = require('./app');
4-
const config = require('./services/config');
4+
const configStore = require('./services/config-store');
55
const debug = require('debug')('coderun:server');
66

77
// 获取端口
8-
const port = normalizePort(config.server.port);
8+
const port = normalizePort(configStore.get('server.port'));
99
app.set('port', port);
1010

1111
// 启动服务器

services/admin.js

Lines changed: 84 additions & 81 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,22 @@
1-
const axios = require('axios');
2-
const docker = new (require('dockerode'))();
3-
const sessionManager = require('./session-manager');
4-
const config = require('./config');
5-
const authService = require('./auth');
1+
const axios = require("axios");
2+
const docker = new (require("dockerode"))();
3+
const sessionManager = require("./session-manager");
4+
const configStore = require("./config-store");
5+
const authService = require("./auth");
66

77
class AdminService {
88
constructor() {
9-
this.config = config.admin;
10-
this.config.site = config.site.url;
11-
this.config.authSite = config.site.authSite;
12-
this.config.jwtSecret = config.jwt.secret;
13-
149
// Delay initialization to avoid circular dependency
1510
setTimeout(() => {
16-
this.terminalService = require('./terminal').terminalService;
11+
this.terminalService = require("./terminal").terminalService;
1712
this.initializeAdmin().catch(console.error);
1813
}, 1000);
1914
}
2015

2116
logRequest(method, url, data = null) {
22-
console.log(`[AdminService] 📤 [${new Date().toISOString()}] ${method.toUpperCase()} ${url}`);
17+
console.log(
18+
`[AdminService] 📤 [${new Date().toISOString()}] ${method.toUpperCase()} ${url}`
19+
);
2320
if (data) {
2421
//console.log('Request Data:', JSON.stringify(data, null, 2));
2522
}
@@ -31,39 +28,48 @@ class AdminService {
3128
}
3229

3330
logError(method, url, error) {
34-
console.error(`[AdminService] ❌ [${new Date().toISOString()}] ${method.toUpperCase()} ${url} - 错误:`, error.message);
31+
console.error(
32+
`[AdminService] ❌ [${new Date().toISOString()}] ${method.toUpperCase()} ${url} - 错误:`,
33+
error.message
34+
);
3535
if (error.response) {
36-
console.error('[AdminService] ❌ 错误响应:', JSON.stringify(error.response.data, null, 2));
36+
console.error(
37+
"[AdminService] ❌ 错误响应:",
38+
JSON.stringify(error.response.data, null, 2)
39+
);
3740
}
3841
}
3942

4043
async initializeAdmin() {
4144
try {
42-
console.log('[AdminService] 🚀 初始化管理服务...');
45+
console.log("[AdminService] 🚀 初始化管理服务...");
4346

4447
// 确保已注册
4548
await authService.getRunnerConfig();
4649

4750
// Start reporting interval
48-
setInterval(() => this.reportDeviceStatus(), this.config.reportInterval);
51+
setInterval(
52+
() => this.reportDeviceStatus(),
53+
configStore.get("admin.report_interval")
54+
);
4955

5056
// Initial report
5157
await this.reportDeviceStatus();
5258

5359
// Initial config fetch
5460
await this.fetchRemoteConfig();
5561

56-
console.log('[AdminService] ✅ 管理服务初始化成功');
62+
console.log("[AdminService] ✅ 管理服务初始化成功");
5763
} catch (error) {
58-
console.error('[AdminService] ❌ 初始化管理服务失败:', error.message);
64+
console.error("[AdminService] ❌ 初始化管理服务失败:", error.message);
5965
}
6066
}
6167

6268
async getSystemInfo() {
63-
console.log('[AdminService] 📊 收集系统信息...');
69+
console.log("[AdminService] 📊 收集系统信息...");
6470
const [dockerInfo, dockerVersion] = await Promise.all([
6571
docker.info(),
66-
docker.version()
72+
docker.version(),
6773
]);
6874

6975
const info = {
@@ -76,110 +82,107 @@ class AdminService {
7682
total: dockerInfo.Containers,
7783
running: dockerInfo.ContainersRunning,
7884
paused: dockerInfo.ContainersPaused,
79-
stopped: dockerInfo.ContainersStopped
80-
}
85+
stopped: dockerInfo.ContainersStopped,
86+
},
8187
},
8288
system: {
8389
platform: process.platform,
8490
arch: process.arch,
8591
version: process.version,
8692
memory: process.memoryUsage(),
87-
uptime: process.uptime()
93+
uptime: process.uptime(),
8894
},
8995
coderun: {
90-
version: require('../package.json').version,
91-
poolSize: this.config.poolSize,
96+
version: require("../package.json").version,
97+
poolSize: configStore.get("admin.pool_size"),
9298
activeConnections: sessionManager.getActiveSessionCount(),
93-
pooledContainers: this.terminalService ? this.terminalService.containerPool.length : 0,
94-
site: this.config.site,
95-
lastConfigUpdate: this.config.lastConfigUpdate,
96-
lastReport: this.config.lastReport,
97-
deviceId: await authService.getDeviceId()
98-
}
99+
pooledContainers: this.terminalService
100+
? this.terminalService.containerPool.length
101+
: 0,
102+
site: configStore.get("site.url"),
103+
lastConfigUpdate: configStore.get("admin.last_config_update"),
104+
lastReport: configStore.get("admin.last_report"),
105+
deviceId: await authService.getDeviceId(),
106+
},
99107
};
100108

101-
console.log('[AdminService] 📊 系统信息收集完成');
109+
console.log("[AdminService] 📊 系统信息收集完成");
102110
return info;
103111
}
104112

105113
async reportDeviceStatus() {
106-
if (!this.config.authSite) return;
114+
const authSite = configStore.get("site.auth_site");
115+
if (!authSite) return;
107116

108-
const url = `${this.config.authSite}/coderun/device`;
117+
const url = `${authSite}/coderun/device`;
109118
try {
110119
const systemInfo = await this.getSystemInfo();
111120
const runnerToken = await authService.getRunnerToken();
112-
this.logRequest('POST', url, systemInfo);
113-
const response = await axios.post(
114-
url,
115-
systemInfo,
116-
{
117-
headers: { 'Authorization': `Bearer ${runnerToken}` }
118-
}
119-
);
120-
this.logResponse('POST', url, response);
121+
this.logRequest("POST", url, systemInfo);
122+
const response = await axios.post(url, systemInfo, {
123+
headers: { Authorization: `Bearer ${runnerToken}` },
124+
});
125+
this.logResponse("POST", url, response);
121126

122-
this.config.lastReport = new Date();
127+
configStore.set("admin.last_report", new Date().toISOString());
123128
await authService.updateLastUpdated();
124-
console.log('[AdminService] ✅ 设备状态上报成功'+new Date().toISOString());
129+
console.log(
130+
"[AdminService] ✅ 设备状态上报成功" + new Date().toISOString()
131+
);
125132
} catch (error) {
126-
this.logError('POST', url, error);
127-
console.error('[AdminService] ❌ 设备状态上报失败:', error);
133+
this.logError("POST", url, error);
134+
console.error("[AdminService] ❌ 设备状态上报失败:", error);
128135
}
129136
}
130137

131138
async fetchRemoteConfig() {
132-
if (!this.config.authSite) return;
139+
const authSite = configStore.get("site.auth_site");
140+
if (!authSite) return;
133141

134-
const url = `${this.config.authSite}/coderun/config`;
142+
const url = `${authSite}/coderun/config`;
135143
try {
136144
const runnerToken = await authService.getRunnerToken();
137-
this.logRequest('GET', url);
138-
const response = await axios.get(
139-
url,
140-
{
141-
headers: { 'Authorization': `Bearer ${runnerToken}` }
142-
}
143-
);
144-
this.logResponse('GET', url, response);
145+
this.logRequest("GET", url);
146+
const response = await axios.get(url, {
147+
headers: { Authorization: `Bearer ${runnerToken}` },
148+
});
149+
this.logResponse("GET", url, response);
145150

146151
const newConfig = response.data;
147152

148-
console.log('[AdminService] 📝 应用新配置');
153+
console.log("[AdminService] 📝 应用新配置");
149154
console.log(newConfig);
150155

151156
if (newConfig.config) {
152-
// 更新全局 JWT secret
153-
if (newConfig.config.jwtSecret) {
154-
config.jwt.secret = newConfig.config.jwtSecret;
155-
}
156-
157-
// 更新 admin 配置
158-
this.config = {
159-
...this.config,
160-
...newConfig.config,
161-
lastConfigUpdate: new Date()
162-
};
157+
// Update config store with remote values
158+
configStore.updateFromRemote(newConfig.config);
163159

164160
// Apply pool size changes if needed
165161
if (newConfig.config.poolSize !== undefined && this.terminalService) {
166-
console.log(`[AdminService] 🔄 更新容器池大小到 ${newConfig.config.poolSize}`);
167-
this.terminalService.CONTAINER_POOL_SIZE = newConfig.config.poolSize;
162+
const newPoolSize = configStore.get("docker.container_pool_size");
163+
console.log(`[AdminService] 🔄 更新容器池大小到 ${newPoolSize}`);
164+
this.terminalService.CONTAINER_POOL_SIZE = newPoolSize;
168165
await this.terminalService.maintainContainerPool();
169166
}
170167
}
171168

172169
await authService.updateLastUpdated();
173-
console.log('[AdminService] ✅ 远程配置更新成功');
174-
return this.config;
170+
console.log("[AdminService] ✅ 远程配置更新成功");
171+
return configStore.getByPrefix("admin");
175172
} catch (error) {
176-
this.logError('GET', url, error);
177-
console.error('[AdminService] ❌ 获取远程配置失败:', error.message);
173+
this.logError("GET", url, error);
174+
console.error("[AdminService] ❌ 获取远程配置失败:", error.message);
178175

179176
// Check for 401 status and specific error message
180-
if (error.response && error.response.status === 401 &&
181-
error.response.data && error.response.data.error === 'Invalid runner token or device not found') {
182-
console.error('[AdminService] ❌ Runner令牌无效或设备未找到,程序将退出');
177+
if (
178+
error.response &&
179+
error.response.status === 401 &&
180+
error.response.data &&
181+
error.response.data.error === "Invalid runner token or device not found"
182+
) {
183+
console.error(
184+
"[AdminService] ❌ Runner令牌无效或设备未找到,程序将退出"
185+
);
183186
process.exit(1);
184187
}
185188

@@ -188,15 +191,15 @@ class AdminService {
188191
}
189192

190193
getConfig() {
191-
return this.config;
194+
return configStore.getByPrefix("admin");
192195
}
193196

194197
async validateAuthToken(token) {
195198
const runnerToken = await authService.getRunnerToken();
196199
const isValid = token === runnerToken;
197-
console.log(`[AdminService] 🔒 认证令牌验证: ${isValid ? '成功' : '失败'}`);
200+
console.log(`[AdminService] 🔒 认证令牌验证: ${isValid ? "成功" : "失败"}`);
198201
return isValid;
199202
}
200203
}
201204

202-
module.exports = new AdminService();
205+
module.exports = new AdminService();

0 commit comments

Comments
 (0)