feat: 支持设置应用/容器 CPU 与内存性能上限
This commit is contained in:
1 parent
0bfbb9a64a
commit
fbc8a5cb38
5 files changed
+172
-2
No files matched your search
+99
-1
@@ -234,6 +234,7 @@ async function inspectAll() {
|
||||
state: c.State, restarts: old.restarts || 0, health: old.health || '',
|
||||
startedAt: old.startedAt || '', exitCode: old.exitCode ?? 0,
|
||||
restartPolicy: old.restartPolicy || '', memLimitCfg: old.memLimitCfg || 0,
|
||||
nanoCpus: old.nanoCpus || 0, pidsLimit: old.pidsLimit || 0,
|
||||
privileged: !!old.privileged, user: old.user || '', healthcheck: !!old.healthcheck,
|
||||
dockerSock: !!old.dockerSock, inspected: !!old.inspected,
|
||||
};
|
||||
@@ -248,6 +249,8 @@ async function inspectAll() {
|
||||
next.exitCode = d.State?.ExitCode ?? 0;
|
||||
next.restartPolicy = d.HostConfig?.RestartPolicy?.Name || 'no';
|
||||
next.memLimitCfg = d.HostConfig?.Memory || 0;
|
||||
next.nanoCpus = d.HostConfig?.NanoCpus || 0;
|
||||
next.pidsLimit = d.HostConfig?.PidsLimit || 0;
|
||||
next.privileged = !!d.HostConfig?.Privileged;
|
||||
next.user = d.Config?.User || '';
|
||||
next.healthcheck = !!(d.Config?.Healthcheck && (d.Config.Healthcheck.Test || []).length);
|
||||
@@ -284,7 +287,7 @@ function buildApps(containers) {
|
||||
id: c.Id, name: strip((c.Names || [])[0]), service: svcOf(c.Labels),
|
||||
image: c.Image, state: c.State, status: c.Status,
|
||||
health: m.health || '', restarts: m.restarts || 0, startedAt: m.startedAt || '', exitCode: m.exitCode ?? 0,
|
||||
restartPolicy: m.restartPolicy || '', memLimitCfg: m.memLimitCfg || 0,
|
||||
restartPolicy: m.restartPolicy || '', memLimitCfg: m.memLimitCfg || 0, nanoCpus: m.nanoCpus || 0,
|
||||
privileged: !!m.privileged, healthcheck: !!m.healthcheck, dockerSock: !!m.dockerSock,
|
||||
ports: (c.Ports || []).filter(pp => pp.PublicPort).length,
|
||||
runMs: c.State === 'running' && m.startedAt ? Math.max(0, Date.now() - Date.parse(m.startedAt)) : null,
|
||||
@@ -994,6 +997,7 @@ app.get('/api/containers', async (req, res) => {
|
||||
image: c.Image, state: c.State, status: c.Status, created: c.Created,
|
||||
project: projectOf(c.Labels), service: svcOf(c.Labels),
|
||||
health: m.health || '', restarts: m.restarts || 0,
|
||||
limits: { cpus: (m.nanoCpus || 0) / 1e9, memMB: Math.round((m.memLimitCfg || 0) / 1048576), pids: m.pidsLimit || 0 },
|
||||
startedAt: m.startedAt || '',
|
||||
runMs: c.State === 'running' && m.startedAt ? Math.max(0, Date.now() - Date.parse(m.startedAt)) : null,
|
||||
ports: (c.Ports || []).map(p => ({ ip: p.IP, private: p.PrivatePort, public: p.PublicPort, type: p.Type })),
|
||||
@@ -1280,6 +1284,100 @@ app.post('/api/images/pull', async (req, res) => {
|
||||
|
||||
const BUILTIN_NETS = ['bridge', 'host', 'none'];
|
||||
|
||||
/* ---------------- 性能限制 ---------------- */
|
||||
const LIMITS_PATH = path.join(path.dirname(SETTINGS_PATH), 'limits.json');
|
||||
let limitsStore = { apps: {}, containers: {} };
|
||||
try { limitsStore = JSON.parse(fs.readFileSync(LIMITS_PATH, 'utf8')); } catch (e) {}
|
||||
function saveLimits() {
|
||||
try { fs.mkdirSync(path.dirname(LIMITS_PATH), { recursive: true }); fs.writeFileSync(LIMITS_PATH, JSON.stringify(limitsStore, null, 2)); } catch (e) {}
|
||||
}
|
||||
|
||||
function limitPayload(cpus, memMB) {
|
||||
const c = Number(cpus) || 0;
|
||||
const m = Number(memMB) || 0;
|
||||
if (c < 0 || m < 0) throw new Error('限制值不能为负');
|
||||
const opt = { NanoCpus: c > 0 ? Math.round(c * 1e9) : 0 };
|
||||
if (m > 0) { opt.Memory = Math.round(m * 1048576); opt.MemorySwap = -1; }
|
||||
else { opt.Memory = 0; opt.MemorySwap = 0; }
|
||||
return opt;
|
||||
}
|
||||
|
||||
app.get('/api/limits', (req, res) => res.json(limitsStore));
|
||||
|
||||
app.post('/api/containers/:id/limits', async (req, res) => {
|
||||
try {
|
||||
const rawCpus = Number(req.body && req.body.cpus) || 0;
|
||||
const rawMem = Number(req.body && req.body.memMB) || 0;
|
||||
const clearing = rawCpus <= 0 && rawMem <= 0;
|
||||
const opt = clearing ? { CpuQuota: -1 } : limitPayload(rawCpus, rawMem);
|
||||
const c = docker.getContainer(req.params.id);
|
||||
const info = await c.inspect();
|
||||
await c.update(opt);
|
||||
const name = strip(info.Name || '');
|
||||
if (clearing) delete limitsStore.containers[name];
|
||||
else limitsStore.containers[name] = { cpus: rawCpus, memMB: rawMem };
|
||||
saveLimits();
|
||||
const st = meta.get(info.Id) || {};
|
||||
st.nanoCpus = clearing ? 0 : opt.NanoCpus; st.memLimitCfg = clearing ? 0 : (opt.Memory || 0);
|
||||
meta.set(info.Id, st);
|
||||
pushEvent('info', null, clearing ? `取消容器限制 ${name}` : `设置容器限制 ${name}`,
|
||||
clearing ? 'CPU 已解除;内存上限需重建容器才彻底移除' : `${opt.NanoCpus ? (opt.NanoCpus / 1e9).toFixed(2) + ' 核' : '不限 CPU'} · ${opt.Memory ? (opt.Memory / 1048576).toFixed(0) + ' MB' : '不限内存'}`);
|
||||
res.json({ ok: true, clearing, applied: opt, note: clearing ? 'CPU 限制已解除;内存上限需重建容器(docker compose up -d --force-recreate)才能完全移除' : '' });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.post('/api/apps/:key/limits', async (req, res) => {
|
||||
try {
|
||||
const rawCpus = Number(req.body && req.body.cpus) || 0;
|
||||
const rawMem = Number(req.body && req.body.memMB) || 0;
|
||||
const clearing = rawCpus <= 0 && rawMem <= 0;
|
||||
const opt = clearing ? { CpuQuota: -1 } : limitPayload(rawCpus, rawMem);
|
||||
const key = String(req.params.key);
|
||||
const conts = await docker.listContainers({ all: true });
|
||||
const mine = conts.filter(c => appKeyOf(c) === key);
|
||||
if (!mine.length) return res.status(404).json({ error: '该应用下没有容器' });
|
||||
const results = [];
|
||||
for (const c of mine) {
|
||||
try {
|
||||
await docker.getContainer(c.Id).update(opt);
|
||||
const st = meta.get(c.Id) || {};
|
||||
st.nanoCpus = clearing ? 0 : opt.NanoCpus; st.memLimitCfg = clearing ? 0 : (opt.Memory || 0);
|
||||
meta.set(c.Id, st);
|
||||
results.push({ name: strip((c.Names || [])[0]), ok: true });
|
||||
} catch (e) { results.push({ name: strip((c.Names || [])[0]), ok: false, error: e.message }); }
|
||||
}
|
||||
if (clearing) delete limitsStore.apps[key];
|
||||
else limitsStore.apps[key] = { cpus: rawCpus, memMB: rawMem };
|
||||
saveLimits();
|
||||
const ok = results.filter(r => r.ok).length;
|
||||
pushEvent('info', null, clearing ? `取消应用限制 ${key}` : `设置应用限制 ${key}`,
|
||||
`${ok}/${results.length} 个容器生效 · ${clearing ? '已解除 CPU;内存需重建容器' : `${opt.NanoCpus ? (opt.NanoCpus / 1e9).toFixed(2) + ' 核' : '不限 CPU'} / ${opt.Memory ? (opt.Memory / 1048576).toFixed(0) + ' MB' : '不限内存'}`}`);
|
||||
res.json({ ok: true, clearing, applied: ok, total: results.length, results, note: clearing ? 'CPU 限制已解除;内存上限需重建容器才能完全移除' : '' });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
app.post('/api/limits/reapply', async (req, res) => {
|
||||
try {
|
||||
const conts = await docker.listContainers({ all: true });
|
||||
let applied = 0, failed = 0;
|
||||
for (const c of conts) {
|
||||
const key = appKeyOf(c);
|
||||
const name = strip((c.Names || [])[0]);
|
||||
const lim = limitsStore.apps[key] || limitsStore.containers[name];
|
||||
if (!lim) continue;
|
||||
try {
|
||||
const opt = limitPayload(lim.cpus, lim.memMB);
|
||||
await docker.getContainer(c.Id).update(opt);
|
||||
const st = meta.get(c.Id) || {};
|
||||
st.nanoCpus = opt.NanoCpus; st.memLimitCfg = opt.Memory || 0;
|
||||
meta.set(c.Id, st);
|
||||
applied++;
|
||||
} catch (e) { failed++; }
|
||||
}
|
||||
res.json({ ok: true, applied, failed });
|
||||
} catch (e) { res.status(500).json({ error: e.message }); }
|
||||
});
|
||||
|
||||
/* ---------------- Compose 批量部署 ---------------- */
|
||||
function safeSubdir(dir) {
|
||||
const d = String(dir || '').trim().replace(/^\/+|\/+$/g, '');
|
||||
|
||||
Reference in new issue
Block a user