server.js 34.2 KB
Newer Older
zk's avatar
zk committed
1
2
3
4
5
const http = require("http");
const fs = require("fs");
const path = require("path");
const { spawn } = require("child_process");
const crypto = require("crypto");
zk's avatar
zk committed
6
7
8

const PORT = Number(process.env.PORT || 3066);
const POLL_INTERVAL_MS = Number(process.env.POLL_INTERVAL_MS || 10000);
zk's avatar
zk committed
9
const SSH_TIMEOUT_MS = Number(process.env.SSH_TIMEOUT_MS || 20000);
zk's avatar
zk committed
10
11
12
13
14
15
16
17
const REFRESH_CONCURRENCY = clampInt(process.env.REFRESH_CONCURRENCY, 1, 32, 8);
const ASSET_REFRESH_INTERVAL_MS = Number(process.env.ASSET_REFRESH_INTERVAL_MS || 30 * 60 * 1000);
const ASSET_SSH_TIMEOUT_MS = Number(process.env.ASSET_SSH_TIMEOUT_MS || 30000);
const ASSET_CONCURRENCY = clampInt(process.env.ASSET_CONCURRENCY, 1, 16, 3);
const ASSET_MAX_ITEMS = clampInt(process.env.ASSET_MAX_ITEMS, 20, 1000, 160);
const ASSET_PATHS = parseCsv(process.env.ASSET_PATHS || "/models,/public,/data");
const BACKUP_INTERVAL_MS = Number(process.env.BACKUP_INTERVAL_MS || 24 * 60 * 60 * 1000);
const BACKUP_RETENTION = clampInt(process.env.BACKUP_RETENTION, 1, 365, 30);
zk's avatar
zk committed
18
19
20
const ROOT = __dirname;
const DATA_DIR = path.join(ROOT, "data");
const CONFIG_PATH = path.join(DATA_DIR, "servers.json");
zk's avatar
zk committed
21
const BACKUP_DIR = path.join(DATA_DIR, "backups");
zk's avatar
zk committed
22
23
24
25
26
27
28
29
30
31
32
33
34
const PUBLIC_DIR = path.join(ROOT, "public");

const MIME_TYPES = {
  ".html": "text/html; charset=utf-8",
  ".css": "text/css; charset=utf-8",
  ".js": "application/javascript; charset=utf-8",
  ".json": "application/json; charset=utf-8",
  ".svg": "image/svg+xml; charset=utf-8",
  ".png": "image/png",
  ".ico": "image/x-icon"
};

let statusCache = new Map();
zk's avatar
zk committed
35
let assetCache = new Map();
zk's avatar
zk committed
36
let lastRefresh = null;
zk's avatar
zk committed
37
let lastAssetRefresh = null;
zk's avatar
zk committed
38
39
let refreshInFlight = null;
let refreshInFlightIncludesModels = false;
zk's avatar
zk committed
40
let assetRefreshInFlight = null;
zk's avatar
zk committed
41

zk's avatar
zk committed
42
43
44
45
46
47
48
function createId() {
  if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
  return [4, 2, 2, 2, 6]
    .map((bytes) => crypto.randomBytes(bytes).toString("hex"))
    .join("-");
}

zk's avatar
zk committed
49
50
51
52
function ensureDataFile() {
  if (!fs.existsSync(DATA_DIR)) {
    fs.mkdirSync(DATA_DIR, { recursive: true });
  }
zk's avatar
zk committed
53
54
55
  if (!fs.existsSync(BACKUP_DIR)) {
    fs.mkdirSync(BACKUP_DIR, { recursive: true });
  }
zk's avatar
zk committed
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
  if (!fs.existsSync(CONFIG_PATH)) {
    fs.writeFileSync(CONFIG_PATH, "[]\n", "utf8");
  }
}

function loadServers() {
  ensureDataFile();
  try {
    const raw = fs.readFileSync(CONFIG_PATH, "utf8");
    const parsed = JSON.parse(raw);
    return Array.isArray(parsed) ? parsed.map(normalizeServer).filter(Boolean) : [];
  } catch (error) {
    console.error("Failed to read server config:", error.message);
    return [];
  }
}

function saveServers(servers) {
  ensureDataFile();
  const tmp = `${CONFIG_PATH}.tmp`;
  fs.writeFileSync(tmp, `${JSON.stringify(servers, null, 2)}\n`, "utf8");
  fs.renameSync(tmp, CONFIG_PATH);
}

zk's avatar
zk committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
function backupServerConfig(reason) {
  ensureDataFile();
  if (!fs.existsSync(CONFIG_PATH)) return;
  const stamp = compactTimestamp(new Date());
  const suffix = reason ? `.${reason}` : "";
  const target = path.join(BACKUP_DIR, `servers.${stamp}${suffix}.json`);
  try {
    fs.copyFileSync(CONFIG_PATH, target);
    pruneBackups();
  } catch (error) {
    console.warn(`Server config backup failed: ${error.message}`);
  }
}

function pruneBackups() {
  if (!fs.existsSync(BACKUP_DIR)) return;
  const backups = fs
    .readdirSync(BACKUP_DIR)
    .filter((name) => /^servers\.\d{14}.*\.json$/.test(name))
    .map((name) => ({
      name,
      filePath: path.join(BACKUP_DIR, name),
      mtimeMs: fs.statSync(path.join(BACKUP_DIR, name)).mtimeMs
    }))
    .sort((a, b) => b.mtimeMs - a.mtimeMs);

  backups.slice(BACKUP_RETENTION).forEach((backup) => {
    try {
      fs.unlinkSync(backup.filePath);
    } catch (error) {
      console.warn(`Failed to prune backup ${backup.name}: ${error.message}`);
    }
  });
}

function compactTimestamp(date) {
  const pad = (value) => String(value).padStart(2, "0");
  return [
    date.getFullYear(),
    pad(date.getMonth() + 1),
    pad(date.getDate()),
    pad(date.getHours()),
    pad(date.getMinutes()),
    pad(date.getSeconds())
  ].join("");
}

function parseCsv(value) {
  return String(value || "")
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean)
    .slice(0, 24);
}

zk's avatar
zk committed
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
function normalizeServer(input) {
  if (!input || typeof input !== "object") return null;
  const host = String(input.host || "").trim();
  if (!host) return null;

  const name = String(input.name || host).trim();
  const user = String(input.user || "root").trim();
  const command = normalizeCommand(input.command);
  const group = normalizeGroup(input.group || input.team);
  const tags = Array.isArray(input.tags)
    ? input.tags.map((tag) => String(tag).trim()).filter(Boolean).slice(0, 6)
    : String(input.tags || "")
        .split(",")
        .map((tag) => tag.trim())
        .filter(Boolean)
        .slice(0, 6);

  return {
zk's avatar
zk committed
153
    id: String(input.id || createId()),
zk's avatar
zk committed
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
    name,
    host,
    port: clampInt(input.port, 1, 65535, 22),
    user,
    gpuCount: optionalInt(input.gpuCount, 0, 32),
    command,
    group,
    tags,
    models: normalizeModels(input.models),
    gpuModels: normalizeGpuModels(input.gpuModels)
  };
}

function normalizeGroup(group) {
  const value = String(group || "").replace(/\s+/g, " ").trim();
  return value || "未分组";
}

function normalizeModels(models) {
  if (!Array.isArray(models)) return [];
  return models.map(normalizeModelName).filter(Boolean).slice(0, 32);
}

function normalizeGpuModels(gpuModels) {
  if (!Array.isArray(gpuModels)) return [];
  return gpuModels
    .map((gpu) => {
      if (!gpu || typeof gpu !== "object") return null;
      const index = optionalInt(gpu.index, 0, 31);
      return {
        index,
        model: normalizeModelName(gpu.model),
        vendor: normalizeModelName(gpu.vendor)
      };
    })
    .filter((gpu) => gpu && (gpu.model || gpu.vendor))
    .slice(0, 32);
}

function clampInt(value, min, max, fallback) {
  const parsed = Number.parseInt(value, 10);
  if (!Number.isFinite(parsed)) return fallback;
  return Math.min(max, Math.max(min, parsed));
}

function optionalInt(value, min, max) {
  if (value === undefined || value === null || value === "") return 0;
  return clampInt(value, min, max, 0);
}

zk's avatar
zk committed
204
function publicServer(server, options = {}) {
zk's avatar
zk committed
205
  const cached = statusCache.get(server.id);
zk's avatar
zk committed
206
  const assets = assetCache.get(server.id);
zk's avatar
zk committed
207
208
  return {
    ...server,
zk's avatar
zk committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
    status: cached || createPendingStatus(server),
    assets: publicAssetStatus(assets || createPendingAssetStatus(), options.includeAssetDetails)
  };
}

function publicAssetStatus(assets, includeDetails) {
  const modelItems = assets.modelItems || [];
  const dockerImages = assets.dockerImages || [];
  const summary = {
    state: assets.state,
    updatedAt: assets.updatedAt,
    latencyMs: assets.latencyMs,
    paths: assets.paths,
    modelCount: assets.modelCount || modelItems.length,
    dockerCount: assets.dockerCount || dockerImages.length,
    searchText: assetSearchText(modelItems, dockerImages),
    error: assets.error || null
  };
  if (includeDetails) {
    summary.modelItems = modelItems;
    summary.dockerImages = dockerImages;
  } else {
    summary.modelItems = [];
    summary.dockerImages = [];
  }
  return summary;
}

function assetSearchText(modelItems, dockerImages) {
  return [
    ...modelItems.flatMap((item) => [item.name, item.path, item.root]),
    ...dockerImages.flatMap((image) => [image.repository, image.tag, image.imageId])
  ]
    .filter(Boolean)
    .join(" ")
    .slice(0, 12000);
}

function createPendingAssetStatus() {
  return {
    state: "pending",
    updatedAt: null,
    latencyMs: null,
    paths: ASSET_PATHS,
    modelCount: 0,
    dockerCount: 0,
    modelItems: [],
    dockerImages: [],
    error: null
zk's avatar
zk committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
  };
}

function createPendingStatus(server) {
  const totalCount = server.gpuCount || 0;
  const gpus = applySavedModels(
    Array.from({ length: totalCount }, (_, index) => ({
      index,
      state: "unknown",
      utilization: null,
      memoryUtilization: null,
      memoryUsedMiB: null,
      memoryTotalMiB: null,
      temperatureC: null,
      powerW: null,
      raw: ""
    })),
    server
  );
  return {
    state: "pending",
    summary: "等待刷新",
    updatedAt: null,
    latencyMs: null,
    busyCount: 0,
    freeCount: totalCount,
    totalCount,
    models: server.models && server.models.length ? server.models : collectModels(gpus),
    gpus,
    error: null
  };
}

async function refreshAll(options = {}) {
  const includeModels = Boolean(options.includeModels);
  if (refreshInFlight) {
    if (!includeModels || refreshInFlightIncludesModels) return refreshInFlight;
    await refreshInFlight;
  }
  const servers = loadServers();
  refreshInFlightIncludesModels = includeModels;
zk's avatar
zk committed
299
  refreshInFlight = mapWithConcurrency(servers, REFRESH_CONCURRENCY, (server) => refreshServer(server, { includeModels }))
zk's avatar
zk committed
300
301
302
303
304
305
306
307
308
309
310
    .then((results) => {
      lastRefresh = new Date().toISOString();
      return results;
    })
    .finally(() => {
      refreshInFlight = null;
      refreshInFlightIncludesModels = false;
    });
  return refreshInFlight;
}

zk's avatar
zk committed
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
async function refreshAssetsAll() {
  if (assetRefreshInFlight) return assetRefreshInFlight;
  const servers = loadServers();
  assetRefreshInFlight = mapWithConcurrency(servers, ASSET_CONCURRENCY, refreshServerAssets)
    .then((results) => {
      lastAssetRefresh = new Date().toISOString();
      return results;
    })
    .finally(() => {
      assetRefreshInFlight = null;
    });
  return assetRefreshInFlight;
}

async function mapWithConcurrency(items, limit, worker) {
  const results = new Array(items.length);
  let nextIndex = 0;
  const workerCount = Math.min(limit, items.length);
  const runners = Array.from({ length: workerCount }, async () => {
    while (nextIndex < items.length) {
      const current = nextIndex;
      nextIndex += 1;
      results[current] = await worker(items[current], current);
    }
  });
  await Promise.all(runners);
  return results;
}

zk's avatar
zk committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
async function refreshServer(server, options = {}) {
  const includeModels = Boolean(options.includeModels);
  const started = Date.now();
  try {
    const output = await runProbeCommand(server);
    const parsed = parseProbeOutput(output.stdout, server.gpuCount, server.command);
    let gpus = applySavedModels(parsed.gpus, server);
    let models = collectModels(gpus);
    if (includeModels) {
      try {
        const modelOutput = await runProbeCommand(server, buildModelCommand(server.command));
        const modelByIndex = parseModelOutput(modelOutput.stdout, server.command);
        gpus = mergeGpuModels(gpus, modelByIndex);
        models = collectModels(gpus);
      } catch (modelError) {
        console.warn(`Model detection failed for ${server.host}: ${modelError.message}`);
      }
    }
    const totalCount = Math.max(parsed.totalCount, gpus.length);
    const busyCount = gpus.filter((gpu) => gpu.state === "busy").length;
    const latencyMs = Date.now() - started;
    const status = {
      state: "online",
      summary: parsed.busyCount > 0 ? `${parsed.busyCount}/${parsed.totalCount} 占用` : "全部空闲",
      updatedAt: new Date().toISOString(),
      latencyMs,
      busyCount,
      freeCount: Math.max(totalCount - busyCount, 0),
      totalCount,
      models,
      gpus,
      error: null
    };
    if (busyCount > 0) {
      status.summary = `${busyCount}/${totalCount} 占用`;
    }
    statusCache.set(server.id, status);
    if (server.gpuCount !== totalCount || includeModels) {
      persistDetectedServerInfo(server.id, {
        gpuCount: totalCount,
        models: includeModels ? models : undefined,
        gpuModels: includeModels ? extractGpuModels(gpus) : undefined
      });
    }
    return { id: server.id, ok: true };
  } catch (error) {
    const pending = createPendingStatus(server);
    const status = {
      state: "offline",
      summary: "连接失败",
      updatedAt: new Date().toISOString(),
      latencyMs: Date.now() - started,
      busyCount: 0,
      freeCount: 0,
      totalCount: server.gpuCount,
      models: pending.models,
      gpus: pending.gpus,
      error: error.message
    };
    statusCache.set(server.id, status);
    return { id: server.id, ok: false, error: error.message };
  }
}

zk's avatar
zk committed
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
async function refreshServerAssets(server) {
  const started = Date.now();
  try {
    const output = await runProbeCommand(server, buildAssetCommand(), ASSET_SSH_TIMEOUT_MS);
    const parsed = parseAssetOutput(output.stdout);
    const status = {
      state: "online",
      updatedAt: new Date().toISOString(),
      latencyMs: Date.now() - started,
      paths: ASSET_PATHS,
      modelCount: parsed.modelItems.length,
      dockerCount: parsed.dockerImages.length,
      modelItems: parsed.modelItems,
      dockerImages: parsed.dockerImages,
      error: null
    };
    assetCache.set(server.id, status);
    return { id: server.id, ok: true };
  } catch (error) {
    const previous = assetCache.get(server.id) || createPendingAssetStatus();
    const status = {
      ...previous,
      state: "failed",
      updatedAt: new Date().toISOString(),
      latencyMs: Date.now() - started,
      paths: ASSET_PATHS,
      error: error.message
    };
    assetCache.set(server.id, status);
    return { id: server.id, ok: false, error: error.message };
  }
}

function runProbeCommand(server, remoteCommand = buildRemoteCommand(server.command), timeoutMs = SSH_TIMEOUT_MS) {
zk's avatar
zk committed
438
439
440
441
442
443
444
445
  const target = server.user ? `${server.user}@${server.host}` : server.host;
  const sshPath = process.env.SSH_PATH || (process.platform === "win32" ? "C:\\Windows\\System32\\OpenSSH\\ssh.exe" : "ssh");
  const args = [
    "-p",
    String(server.port),
    "-o",
    "BatchMode=yes",
    "-o",
zk's avatar
zk committed
446
    `ConnectTimeout=${Math.ceil(timeoutMs / 1000)}`,
zk's avatar
zk committed
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
    "-o",
    "StrictHostKeyChecking=accept-new",
    target,
    remoteCommand
  ];

  return new Promise((resolve, reject) => {
    const child = spawn(sshPath, args, { windowsHide: true });
    let stdout = "";
    let stderr = "";
    let settled = false;

    const timer = setTimeout(() => {
      if (settled) return;
      settled = true;
      child.kill();
zk's avatar
zk committed
463
464
      reject(new Error(`SSH 超时 (${Math.ceil(timeoutMs / 1000)}s)`));
    }, timeoutMs);
zk's avatar
zk committed
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503

    child.stdout.on("data", (chunk) => {
      stdout += chunk.toString("utf8");
    });
    child.stderr.on("data", (chunk) => {
      stderr += chunk.toString("utf8");
    });
    child.on("error", (error) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      reject(new Error(`无法启动 ssh: ${error.message}`));
    });
    child.on("close", (code) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      if (code === 0) {
        resolve({ stdout, stderr });
      } else {
        reject(new Error(cleanError(stderr || stdout || `ssh exit ${code}`)));
      }
    });
  });
}

function normalizeCommand(command) {
  const value = String(command || "hy-smi").trim();
  return value === "nvidia-smi" ? "nvidia-smi" : "hy-smi";
}

function buildRemoteCommand(command) {
  if (command === "nvidia-smi") {
    return [
      "nvidia-smi",
      "--query-gpu=index,utilization.gpu,utilization.memory,memory.used,memory.total,temperature.gpu,power.draw",
      "--format=csv,noheader,nounits"
    ].join(" ");
  }
zk's avatar
zk committed
504
  return buildHySmiCommand("");
zk's avatar
zk committed
505
506
507
508
509
510
511
512
513
514
}

function buildModelCommand(command) {
  if (command === "nvidia-smi") {
    return [
      "nvidia-smi",
      "--query-gpu=index,name",
      "--format=csv,noheader,nounits"
    ].join(" ");
  }
zk's avatar
zk committed
515
516
517
  return buildHySmiCommand("--showproductname");
}

zk's avatar
zk committed
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
function buildAssetCommand() {
  const paths = ASSET_PATHS.length ? ASSET_PATHS : ["/models", "/public", "/data"];
  const pathList = paths.map(shellQuote).join(" ");
  const perPathLimit = Math.max(20, Math.ceil(ASSET_MAX_ITEMS / paths.length));
  const modelCommand = [
    `for p in ${pathList}; do`,
    `if [ -d "$p" ]; then`,
    `{`,
    `find "$p" -mindepth 1 -maxdepth 2 -type d ! -name '.*' ! -name '__pycache__' -printf 'MODEL\\t%p\\td\\t%TY-%Tm-%Td %TH:%TM\\n' 2>/dev/null;`,
    `find "$p" -mindepth 1 -maxdepth 1 -type f \\( -iname '*.gguf' -o -iname '*.safetensors' -o -iname '*.bin' -o -iname '*.onnx' -o -iname '*.pt' -o -iname '*.pth' -o -iname '*.ckpt' \\) -printf 'MODEL\\t%p\\tf\\t%TY-%Tm-%Td %TH:%TM\\n' 2>/dev/null;`,
    `} | head -n ${perPathLimit};`,
    `fi;`,
    `done | head -n ${ASSET_MAX_ITEMS}`
  ].join(" ");
  const dockerCommand = [
    "docker images",
    "--format 'DOCKER\\t{{.Repository}}\\t{{.Tag}}\\t{{.ID}}\\t{{.Size}}\\t{{.CreatedSince}}'",
    `2>/dev/null | head -n ${ASSET_MAX_ITEMS}`
  ].join(" ");
  return [
    "printf '__GPU_MONITOR_MODELS__\\n';",
    modelCommand,
    "; printf '__GPU_MONITOR_DOCKER__\\n';",
    dockerCommand,
    "|| true"
  ].join(" ");
}

zk's avatar
zk committed
546
547
548
549
550
551
552
function buildHySmiCommand(args) {
  const command = ["hy-smi", args].filter(Boolean).join(" ");
  return `(${command} 2>/dev/null || bash -ilc ${shellQuote(command)})`;
}

function shellQuote(value) {
  return `'${String(value).replace(/'/g, `'\\''`)}'`;
zk's avatar
zk committed
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
}

function persistDetectedServerInfo(serverId, detected) {
  const servers = loadServers();
  const index = servers.findIndex((server) => server.id === serverId);
  if (index === -1) return;
  const next = { ...servers[index] };
  let changed = false;

  if (detected.gpuCount && next.gpuCount !== detected.gpuCount) {
    next.gpuCount = detected.gpuCount;
    changed = true;
  }
  if (Array.isArray(detected.models)) {
    next.models = detected.models;
    changed = true;
  }
  if (Array.isArray(detected.gpuModels)) {
    next.gpuModels = detected.gpuModels;
    changed = true;
  }

  if (!changed) return;
  servers[index] = next;
  saveServers(servers);
}

function cleanError(message) {
  return String(message)
    .replace(/\r/g, "")
    .split("\n")
    .map((line) => line.trim())
    .filter(Boolean)
    .slice(-3)
    .join(" | ")
    .slice(0, 240);
}

function parseProbeOutput(output, expectedCount, command) {
  if (command === "nvidia-smi") {
    return parseNvidiaSmi(output, expectedCount);
  }
  return parseHySmi(output, expectedCount);
}

function parseNvidiaSmi(output, expectedCount) {
  const lines = String(output || "")
    .split(/\r?\n/)
    .map((line) => line.trim())
    .filter(Boolean);
  const byIndex = new Map();

  for (const line of lines) {
    const parts = line.split(",").map((part) => part.trim());
    if (parts.length < 7) continue;
    const index = Number.parseInt(parts[0], 10);
    if (!Number.isFinite(index)) continue;
    const gpu = createGpu(index);
    gpu.utilization = parseNullableNumber(parts[1]);
    gpu.memoryUtilization = parseNullableNumber(parts[2]);
    gpu.memoryUsedMiB = parseNullableNumber(parts[3]);
    gpu.memoryTotalMiB = parseNullableNumber(parts[4]);
    gpu.temperatureC = parseNullableNumber(parts[5]);
    gpu.powerW = parseNullableNumber(parts[6]);
    gpu.raw = line.slice(0, 280);
    if (gpu.memoryUtilization === null && gpu.memoryTotalMiB) {
      gpu.memoryUtilization = Math.round(((gpu.memoryUsedMiB || 0) / gpu.memoryTotalMiB) * 1000) / 10;
    }
    byIndex.set(index, gpu);
  }

  return finalizeParsedGpus(byIndex, expectedCount);
}

function parseHySmiWithProduct(output, expectedCount) {
  const [metricsOutput, productOutput = ""] = String(output || "").split("__GPU_MONITOR_PRODUCT__");
  const parsed = parseHySmi(metricsOutput, expectedCount);
  const productByIndex = parseHyProductNames(productOutput);
  if (productByIndex.size === 0) return parsed;

  const gpus = parsed.gpus.map((gpu) => ({
    ...gpu,
    ...(productByIndex.get(gpu.index) || {})
  }));
  return {
    ...parsed,
    models: collectModels(gpus),
    gpus
  };
}

function parseModelOutput(output, command) {
  if (command === "nvidia-smi") {
    return parseNvidiaModels(output);
  }
  return parseHyProductNames(output);
}

zk's avatar
zk committed
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
function parseAssetOutput(output) {
  const modelItems = [];
  const dockerImages = [];
  let section = "";
  const lines = String(output || "").split(/\r?\n/);

  for (const rawLine of lines) {
    const line = rawLine.trim();
    if (!line) continue;
    if (line === "__GPU_MONITOR_MODELS__") {
      section = "models";
      continue;
    }
    if (line === "__GPU_MONITOR_DOCKER__") {
      section = "docker";
      continue;
    }
    if (section === "models" && line.startsWith("MODEL\t")) {
      const parts = line.split("\t");
      const filePath = parts[1] || "";
      const type = parts[2] === "f" ? "file" : "dir";
      const modifiedAt = parts[3] || "";
      const name = path.posix.basename(filePath.replace(/\\/g, "/"));
      if (filePath && name) {
        modelItems.push({
          name: normalizeAssetName(name),
          path: filePath,
          root: assetRoot(filePath),
          type,
          modifiedAt
        });
      }
      continue;
    }
    if (section === "docker" && line.startsWith("DOCKER\t")) {
      const parts = line.split("\t");
      const repository = normalizeAssetName(parts[1]);
      if (!repository || repository === "<none>") continue;
      dockerImages.push({
        repository,
        tag: normalizeAssetName(parts[2]) || "<none>",
        imageId: normalizeAssetName(parts[3]),
        size: normalizeAssetName(parts[4]),
        created: normalizeAssetName(parts.slice(5).join(" "))
      });
    }
  }

  return {
    modelItems: dedupeBy(modelItems, (item) => `${item.path}:${item.type}`).slice(0, ASSET_MAX_ITEMS),
    dockerImages: dedupeBy(dockerImages, (item) => `${item.repository}:${item.tag}:${item.imageId}`).slice(0, ASSET_MAX_ITEMS)
  };
}

function normalizeAssetName(value) {
  return String(value || "").replace(/\s+/g, " ").trim();
}

function assetRoot(filePath) {
  const normalized = String(filePath || "").replace(/\\/g, "/");
  const root = ASSET_PATHS.find((assetPath) => normalized === assetPath || normalized.startsWith(`${assetPath}/`));
  return root || normalized.split("/").slice(0, 2).join("/") || "/";
}

function dedupeBy(items, keyFn) {
  const seen = new Set();
  const result = [];
  for (const item of items) {
    const key = keyFn(item);
    if (seen.has(key)) continue;
    seen.add(key);
    result.push(item);
  }
  return result;
}

zk's avatar
zk committed
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
function parseNvidiaModels(output) {
  const byIndex = new Map();
  const lines = String(output || "")
    .split(/\r?\n/)
    .map((line) => line.trim())
    .filter(Boolean);

  for (const line of lines) {
    const parts = line.split(",").map((part) => part.trim());
    if (parts.length < 2) continue;
    const index = Number.parseInt(parts[0], 10);
    const model = normalizeModelName(parts.slice(1).join(", "));
    if (Number.isFinite(index) && model) {
      byIndex.set(index, { model });
    }
  }

  return byIndex;
}

function parseHyProductNames(output) {
  const byIndex = new Map();
  const lines = String(output || "").split(/\r?\n/);

  for (const line of lines) {
    const series = line.match(/\b(?:HCU|DCU|GPU)\[(\d{1,2})\].*?\bCard\s+Series\s*:\s*(.+)$/i);
    if (series) {
      const index = Number.parseInt(series[1], 10);
      const existing = byIndex.get(index) || {};
      byIndex.set(index, { ...existing, model: normalizeModelName(series[2]) });
      continue;
    }

    const vendor = line.match(/\b(?:HCU|DCU|GPU)\[(\d{1,2})\].*?\bCard\s+Vendor\s*:\s*(.+)$/i);
    if (vendor) {
      const index = Number.parseInt(vendor[1], 10);
      const existing = byIndex.get(index) || {};
      byIndex.set(index, { ...existing, vendor: normalizeModelName(vendor[2]) });
    }
  }

  return byIndex;
}

function parseHySmi(output, expectedCount) {
  const lines = String(output || "").split(/\r?\n/);
  const byIndex = new Map();

  for (const line of lines) {
    const index = getGpuIndex(line);
    if (index === null || index < 0 || index > 31) continue;
    const existing = byIndex.get(index) || createGpu(index);
    const next = parseGpuLine(line, existing);
    byIndex.set(index, next);
  }

  if (byIndex.size === 0) {
    const metricLines = lines.filter((line) => /^\s*\d{1,2}\s+/.test(line) && /%|MiB|GiB|W|C/i.test(line));
    metricLines.slice(0, expectedCount).forEach((line, index) => {
      byIndex.set(index, parseGpuLine(line, createGpu(index)));
    });
  }

  return finalizeParsedGpus(byIndex, expectedCount);
}

function finalizeParsedGpus(byIndex, expectedCount) {
  const detectedCount = byIndex.size ? Math.max(...byIndex.keys()) + 1 : 0;
  const totalCount = Math.max(expectedCount || 0, detectedCount);
  const gpus = Array.from({ length: totalCount }, (_, index) => {
    const parsed = byIndex.get(index) || createGpu(index);
    const busy = isGpuBusy(parsed);
    return {
      ...parsed,
      state: busy ? "busy" : parsed.utilization === null && parsed.memoryUsedMiB === null ? "unknown" : "free"
    };
  });

  return {
    totalCount,
    busyCount: gpus.filter((gpu) => gpu.state === "busy").length,
    models: collectModels(gpus),
    gpus
  };
}

function createGpu(index) {
  return {
    index,
    state: "unknown",
    utilization: null,
    memoryUtilization: null,
    memoryUsedMiB: null,
    memoryTotalMiB: null,
    temperatureC: null,
    powerW: null,
    model: null,
    vendor: null,
    raw: ""
  };
}

function getGpuIndex(line) {
  const patterns = [
    /^\s*\|\s*(\d{1,2})\s+[^|]+?\|/,
    /^\s*(\d{1,2})\s+\d+(?:\.\d+)?C\s+/i,
    /^\s*(\d{1,2})\s+(?:DCU|GPU|card)/i,
    /\b(?:DCU|GPU|card)\s*[:#-]?\s*(\d{1,2})\b/i
  ];
  for (const pattern of patterns) {
    const match = String(line).match(pattern);
    if (match) return Number.parseInt(match[1], 10);
  }
  return null;
}

function parseGpuLine(line, gpu) {
  const next = { ...gpu, raw: [gpu.raw, line.trim()].filter(Boolean).join(" | ").slice(0, 280) };
  const percentages = [...String(line).matchAll(/(\d+(?:\.\d+)?)\s*%/g)]
    .map((match) => Number.parseFloat(match[1]))
    .filter((value) => value >= 0 && value <= 100);
  if (percentages.length) {
    next.utilization = percentages[percentages.length - 1];
  }

  if (/^\s*\d{1,2}\s+\d+(?:\.\d+)?C\s+/i.test(line) && percentages.length >= 2) {
    next.memoryUtilization = percentages[0];
    next.utilization = percentages[1];
  }

  const temp = String(line).match(/(\d+(?:\.\d+)?)\s*C\b/i);
  if (temp) next.temperatureC = Number.parseFloat(temp[1]);

  const power = String(line).match(/(\d+(?:\.\d+)?)\s*W\b/i);
  if (power) next.powerW = Number.parseFloat(power[1]);

  const memory = String(line).match(/(\d+(?:\.\d+)?)\s*(MiB|GiB|MB|GB)\s*\/\s*(\d+(?:\.\d+)?)\s*(MiB|GiB|MB|GB)/i);
  if (memory) {
    next.memoryUsedMiB = toMiB(Number.parseFloat(memory[1]), memory[2]);
    next.memoryTotalMiB = toMiB(Number.parseFloat(memory[3]), memory[4]);
  }

  return next;
}

function toMiB(value, unit) {
  return /g/i.test(unit) ? Math.round(value * 1024) : Math.round(value);
}

function parseNullableNumber(value) {
  const normalized = String(value || "").replace(/[^\d.-]/g, "");
  if (!normalized || normalized.toLowerCase() === "nan") return null;
  const parsed = Number.parseFloat(normalized);
  return Number.isFinite(parsed) ? parsed : null;
}

function normalizeModelName(value) {
  const text = String(value || "")
    .replace(/\s+/g, " ")
    .replace(/^[-:]+|[-:]+$/g, "")
    .trim();
  if (!text || /^N\/A$/i.test(text) || /^unknown$/i.test(text)) return null;
  return text;
}

function collectModels(gpus) {
  const models = [];
  for (const gpu of gpus) {
    if (gpu.model && !models.includes(gpu.model)) models.push(gpu.model);
  }
  return models;
}

function applySavedModels(gpus, server) {
  const savedByIndex = new Map((server.gpuModels || []).map((gpu) => [gpu.index, gpu]));
  const fallbackModel = (server.models || []).length === 1 ? server.models[0] : null;
  return gpus.map((gpu) => {
    const saved = savedByIndex.get(gpu.index) || {};
    return {
      ...gpu,
      model: gpu.model || saved.model || fallbackModel || null,
      vendor: gpu.vendor || saved.vendor || null
    };
  });
}

function mergeGpuModels(gpus, modelByIndex) {
  const detectedCount = modelByIndex.size ? Math.max(...modelByIndex.keys()) + 1 : 0;
  const totalCount = Math.max(gpus.length, detectedCount);
  return Array.from({ length: totalCount }, (_, index) => gpus[index] || createGpu(index)).map((gpu) => {
    const detected = modelByIndex.get(gpu.index) || {};
    return {
      ...gpu,
      model: detected.model || gpu.model || null,
      vendor: detected.vendor || gpu.vendor || null
    };
  });
}

function extractGpuModels(gpus) {
  return gpus
    .map((gpu) => ({
      index: gpu.index,
      model: gpu.model || null,
      vendor: gpu.vendor || null
    }))
    .filter((gpu) => gpu.model || gpu.vendor);
}

function isGpuBusy(gpu) {
  const utilBusy = typeof gpu.utilization === "number" && gpu.utilization >= 10;
  const memoryPercentBusy = typeof gpu.memoryUtilization === "number" && gpu.memoryUtilization >= 10;
  const memBusy = typeof gpu.memoryUsedMiB === "number" && gpu.memoryUsedMiB >= 512;
  return utilBusy || memoryPercentBusy || memBusy;
}

function sendJson(res, statusCode, payload) {
  const body = JSON.stringify(payload);
  res.writeHead(statusCode, {
    "Content-Type": "application/json; charset=utf-8",
    "Cache-Control": "no-store"
  });
  res.end(body);
}

function readJson(req) {
  return new Promise((resolve, reject) => {
    let body = "";
    req.on("data", (chunk) => {
      body += chunk.toString("utf8");
      if (body.length > 1024 * 1024) {
        reject(new Error("请求体过大"));
        req.destroy();
      }
    });
    req.on("end", () => {
      if (!body.trim()) return resolve({});
      try {
        resolve(JSON.parse(body));
      } catch {
        reject(new Error("JSON 格式无效"));
      }
    });
    req.on("error", reject);
  });
}

function serveStatic(req, res) {
  const url = new URL(req.url, `http://${req.headers.host}`);
  const requestedPath = decodeURIComponent(url.pathname === "/" ? "/index.html" : url.pathname);
  const filePath = path.normalize(path.join(PUBLIC_DIR, requestedPath));
  if (!filePath.startsWith(PUBLIC_DIR)) {
    res.writeHead(403);
    res.end("Forbidden");
    return;
  }

  fs.readFile(filePath, (error, content) => {
    if (error) {
      res.writeHead(404);
      res.end("Not found");
      return;
    }
    const ext = path.extname(filePath);
    res.writeHead(200, {
      "Content-Type": MIME_TYPES[ext] || "application/octet-stream",
      "Cache-Control": "no-store"
    });
    res.end(content);
  });
}

async function handleApi(req, res) {
  const url = new URL(req.url, `http://${req.headers.host}`);
  const parts = url.pathname.split("/").filter(Boolean);

  if (req.method === "GET" && url.pathname === "/api/servers") {
zk's avatar
zk committed
1004
1005
    const includeAssetDetails = url.searchParams.get("assetDetails") === "1";
    const servers = loadServers().map((server) => publicServer(server, { includeAssetDetails }));
zk's avatar
zk committed
1006
1007
1008
    sendJson(res, 200, {
      servers,
      lastRefresh,
zk's avatar
zk committed
1009
      lastAssetRefresh,
zk's avatar
zk committed
1010
      pollIntervalMs: POLL_INTERVAL_MS,
zk's avatar
zk committed
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
      refreshing: Boolean(refreshInFlight),
      assetRefreshing: Boolean(assetRefreshInFlight),
      assetRefreshIntervalMs: ASSET_REFRESH_INTERVAL_MS,
      assetPaths: ASSET_PATHS
    });
    return;
  }

  if (req.method === "GET" && parts[0] === "api" && parts[1] === "servers" && parts[2] && parts[3] === "assets") {
    const servers = loadServers();
    const server = servers.find((item) => item.id === parts[2]);
    if (!server) {
      sendJson(res, 404, { error: "服务器不存在" });
      return;
    }
    sendJson(res, 200, {
      assets: publicAssetStatus(assetCache.get(server.id) || createPendingAssetStatus(), true)
zk's avatar
zk committed
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
    });
    return;
  }

  if (req.method === "POST" && url.pathname === "/api/servers") {
    try {
      const body = await readJson(req);
      const server = normalizeServer(body);
      if (!server) {
        sendJson(res, 400, { error: "服务器地址不能为空" });
        return;
      }
      const servers = loadServers();
      servers.push(server);
      saveServers(servers);
      refreshServer(server, { includeModels: true }).catch((error) => console.error(error));
      sendJson(res, 201, { server: publicServer(server) });
    } catch (error) {
      sendJson(res, 400, { error: error.message });
    }
    return;
  }

  if (req.method === "PATCH" && parts[0] === "api" && parts[1] === "servers" && parts[2]) {
    try {
      const body = await readJson(req);
      const servers = loadServers();
      const index = servers.findIndex((server) => server.id === parts[2]);
      if (index === -1) {
        sendJson(res, 404, { error: "服务器不存在" });
        return;
      }
      const updated = normalizeServer({ ...servers[index], ...body, id: servers[index].id });
      if (!updated) {
        sendJson(res, 400, { error: "服务器地址不能为空" });
        return;
      }
      servers[index] = updated;
      saveServers(servers);
      refreshServer(updated, { includeModels: true }).catch((error) => console.error(error));
      sendJson(res, 200, { server: publicServer(updated) });
    } catch (error) {
      sendJson(res, 400, { error: error.message });
    }
    return;
  }

  if (req.method === "DELETE" && parts[0] === "api" && parts[1] === "servers" && parts[2]) {
    const servers = loadServers();
    const nextServers = servers.filter((server) => server.id !== parts[2]);
    if (nextServers.length === servers.length) {
      sendJson(res, 404, { error: "服务器不存在" });
      return;
    }
    saveServers(nextServers);
    statusCache.delete(parts[2]);
    sendJson(res, 200, { ok: true });
    return;
  }

  if (req.method === "POST" && url.pathname === "/api/refresh") {
    const result = await refreshAll({ includeModels: true });
    sendJson(res, 200, { ok: true, result, lastRefresh });
    return;
  }

zk's avatar
zk committed
1094
1095
1096
1097
1098
1099
  if (req.method === "POST" && url.pathname === "/api/assets/refresh") {
    const result = await refreshAssetsAll();
    sendJson(res, 200, { ok: true, result, lastAssetRefresh });
    return;
  }

zk's avatar
zk committed
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
  sendJson(res, 404, { error: "API 不存在" });
}

const server = http.createServer((req, res) => {
  if (req.url.startsWith("/api/")) {
    handleApi(req, res).catch((error) => {
      console.error(error);
      sendJson(res, 500, { error: error.message });
    });
    return;
  }
  serveStatic(req, res);
});

ensureDataFile();
zk's avatar
zk committed
1115
backupServerConfig("startup");
zk's avatar
zk committed
1116
refreshAll().catch((error) => console.error(error));
zk's avatar
zk committed
1117
1118
1119
setTimeout(() => {
  refreshAssetsAll().catch((error) => console.error(error));
}, 2000);
zk's avatar
zk committed
1120
1121
1122
setInterval(() => {
  refreshAll().catch((error) => console.error(error));
}, POLL_INTERVAL_MS);
zk's avatar
zk committed
1123
1124
1125
1126
1127
1128
setInterval(() => {
  backupServerConfig("scheduled");
}, BACKUP_INTERVAL_MS);
setInterval(() => {
  refreshAssetsAll().catch((error) => console.error(error));
}, ASSET_REFRESH_INTERVAL_MS);
zk's avatar
zk committed
1129
1130
1131
1132

server.listen(PORT, "0.0.0.0", () => {
  console.log(`GPU/DCU monitor is running at http://localhost:${PORT}`);
});