Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/lib/cluster/cluster-manager.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -883,13 +883,16 @@ export class ClusterManager {
}
this.links.get(id)?.stop()
this.links.delete(id)
this.prewarmed.get(id)?.stop()
this.prewarmed.delete(id)
await this.bridges.get(id)?.stop()
this.bridges.delete(id)
this.health.delete(id)
this.installs.delete(id)
this.directProbes.delete(id)
this.directState.delete(id)
this.hostFacts.delete(id)
for (const [ticket, entry] of this.tickets) if (entry.nodeId === id) this.tickets.delete(ticket)
this.repo.remove(id)
this._nodesChanged()
}
Expand Down Expand Up @@ -1038,6 +1041,7 @@ export class ClusterManager {
await entry.ready
} catch (err) {
if (this.slotRelays.get(vmId) === entry) this.slotRelays.delete(vmId)
await Promise.all([entry.kernel.stop().catch(() => {}), entry.worker.stop().catch(() => {})])
throw err
}
return paths
Expand Down Expand Up @@ -1219,7 +1223,10 @@ export class ClusterManager {
const append = (chunk) => {
job.log = (job.log + chunk.toString('utf8')).slice(-INSTALL_LOG_MAX)
}
let finished = false
const finish = (status, code, extra) => {
if (finished) return
finished = true
job.status = status
job.exit_code = code
job.finished_at = new Date().toISOString()
Expand All @@ -1235,6 +1242,7 @@ export class ClusterManager {
stream.on('exit', (exitCode) => {
code = exitCode
})
stream.on('error', (streamErr) => finish('failed', code, `stream 错误:${streamErr?.message || streamErr}`))
stream.on('close', () => finish(code === 0 ? 'done' : 'failed', code))
})
return job
Expand Down
25 changes: 21 additions & 4 deletions src/lib/cluster/cluster-routes.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,12 @@ export function createClusterRoutes({ manager, json, readBody, ok }) {

const cm = /^\/docker\/containers\/([^/]+)(?:\/(start|stop|restart|logs))?$/.exec(sub)
if (cm) {
const cid = decodeURIComponent(cm[1])
let cid
try {
cid = decodeURIComponent(cm[1])
} catch {
throw new ClusterError(400, 'invalid_container', '容器 ID 不合法')
}
const action = cm[2]
if (!action && m === 'DELETE') {
await removeContainer(manager.docker(id), cid)
Expand Down Expand Up @@ -174,7 +179,12 @@ export function createClusterRoutes({ manager, json, readBody, ok }) {

/** @returns {boolean} whether this upgrade belonged to the cluster shell */
function handleUpgrade(req, socket, head) {
const url = new URL(req.url || '/', 'http://local')
let url
try {
url = new URL(req.url || '/', 'http://local')
} catch {
return false
}
const sm = SHELL_RE.exec(url.pathname)
if (!sm) return false
const id = sm[1]
Expand Down Expand Up @@ -209,10 +219,12 @@ export function createClusterRoutes({ manager, json, readBody, ok }) {
if (stream) apply(msg)
else if (pending.length < 256) pending.push(msg)
})
ws.on('close', () => {
const onWsDone = () => {
closed = true
stream?.close()
})
}
ws.on('close', onWsDone)
ws.on('error', onWsDone)
try {
stream = await manager.openShell(id, size)
} catch (err) {
Expand All @@ -224,6 +236,11 @@ export function createClusterRoutes({ manager, json, readBody, ok }) {
stream.close()
return
}
stream.on('error', (err) => {
if (ws.readyState === ws.OPEN)
ws.send(JSON.stringify({ t: 'error', message: err?.message || 'shell stream error' }))
ws.close(1011)
})
stream.on('data', (chunk) => ws.readyState === ws.OPEN && ws.send(chunk))
stream.stderr?.on('data', (chunk) => ws.readyState === ws.OPEN && ws.send(chunk))
stream.on('exit', (code) => ws.readyState === ws.OPEN && ws.send(JSON.stringify({ t: 'exit', code })))
Expand Down
53 changes: 41 additions & 12 deletions src/lib/cluster/docker-remote.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,13 @@ export async function dockerRequest(
const agent = new http.Agent({ keepAlive: false })
agent.createConnection = () => stream
return new Promise((resolve, reject) => {
let settled = false
const finish = (fn, value) => {
if (settled) return
settled = true
clearTimeout(timer)
fn(value)
}
const req = http.request({
method,
path,
Expand All @@ -62,9 +69,10 @@ export async function dockerRequest(
req.destroy(new ClusterError(504, 'docker_timeout', `Docker API 超时:${method} ${path}`))
}, timeoutMs)
req.on('error', (err) => {
clearTimeout(timer)
stream.destroy?.()
stream.close?.()
reject(
finish(
reject,
err instanceof ClusterError
? err
: new ClusterError(502, 'docker_io_failed', `Docker API 失败:${err.message}`),
Expand All @@ -80,14 +88,19 @@ export async function dockerRequest(
chunks.push(chunk)
})
res.on('end', () => {
clearTimeout(timer)
// Done with this one-shot connection: close it rather than wait for the daemon to.
stream.destroy?.()
resolve({ status: res.statusCode || 0, headers: res.headers, body: Buffer.concat(chunks) })
finish(resolve, { status: res.statusCode || 0, headers: res.headers, body: Buffer.concat(chunks) })
})
res.on('error', (err) => {
clearTimeout(timer)
reject(new ClusterError(502, 'docker_io_failed', `Docker API 读取失败:${err.message}`))
stream.destroy?.()
finish(reject, new ClusterError(502, 'docker_io_failed', `Docker API 读取失败:${err.message}`))
})
res.once('close', () => {
if (!settled && !res.complete) {
stream.destroy?.()
finish(reject, new ClusterError(502, 'docker_io_failed', `Docker API 连接提前关闭:${method} ${path}`))
}
})
})
if (bodyStream) {
Expand Down Expand Up @@ -582,6 +595,13 @@ async function hijackExecStart(connect, execId, startBody) {
const agent = new http.Agent({ keepAlive: false })
agent.createConnection = () => socket
const stream = await new Promise((resolve, reject) => {
let settled = false
const finish = (fn, value) => {
if (settled) return
settled = true
clearTimeout(timer)
fn(value)
}
const req = http.request({
method: 'POST',
path: start,
Expand All @@ -598,31 +618,40 @@ async function hijackExecStart(connect, execId, startBody) {
req.destroy(new ClusterError(504, 'docker_timeout', `Docker API 超时:POST ${start}`))
}, 30_000)
req.on('upgrade', (_res, raw, head) => {
clearTimeout(timer)
if (head?.length) raw.unshift(head)
resolve(raw)
finish(resolve, raw)
})
// Only a refusal answers without 101 (no such exec, container stopped).
req.on('response', (res) => {
clearTimeout(timer)
const chunks = []
res.on('data', (chunk) => chunks.push(chunk))
res.on('end', () => {
socket.destroy()
const status = res.statusCode === 404 || res.statusCode === 409 ? res.statusCode : 502
reject(
finish(
reject,
new ClusterError(
status,
'docker_exec_failed',
dockerMessage({ status: res.statusCode, body: Buffer.concat(chunks) }),
),
)
})
res.on('error', (err) => {
socket.destroy()
finish(reject, new ClusterError(502, 'docker_io_failed', `Docker API 读取失败:${err.message}`))
})
res.once('close', () => {
if (!settled && !res.complete) {
socket.destroy()
finish(reject, new ClusterError(502, 'docker_io_failed', `Docker API 连接提前关闭:POST ${start}`))
}
})
})
req.on('error', (err) => {
clearTimeout(timer)
socket.destroy()
reject(
finish(
reject,
err instanceof ClusterError
? err
: new ClusterError(502, 'docker_io_failed', `Docker API 失败:${err.message}`),
Expand Down
4 changes: 4 additions & 0 deletions src/lib/cluster/socket-relay.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -144,11 +144,15 @@ export class SocketRelay {
sock.destroy()
return true
}
const onLocalClose = () => sock.destroy()
local.once('close', onLocalClose)
try {
await ready
} catch {
sock.destroy()
return false
} finally {
local.off?.('close', onLocalClose)
}
if (local.destroyed) {
sock.destroy()
Expand Down
9 changes: 7 additions & 2 deletions src/lib/cluster/ssh-link.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -424,9 +424,11 @@ async function execUnixStream(client, transport, socketPath, { long = false, sig
return
}
let settled = false
let readyTimer = null
const fail = (msg) => {
if (settled) return
settled = true
clearTimeout(readyTimer)
stream.close()
reject(new ClusterError(502, 'unix_bridge_failed', msg))
}
Expand All @@ -436,7 +438,7 @@ async function execUnixStream(client, transport, socketPath, { long = false, sig
const onEarlyClose = () => fail('桥接通道提前关闭')
stream.once('exit', onExit)
stream.once('close', onEarlyClose)
setTimeout(() => {
readyTimer = setTimeout(() => {
if (settled) return
settled = true
stream.off('exit', onExit)
Expand Down Expand Up @@ -599,7 +601,10 @@ export class SshLink extends EventEmitter {
let result
try {
const target = await this.resolveTarget()
if (gen !== this._generation) return
if (gen !== this._generation) {
target?.sock?.destroy?.()
return
}
result = await connectSsh(target)
} catch (err) {
if (gen !== this._generation) return
Expand Down
16 changes: 0 additions & 16 deletions src/lib/cluster/tar.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -66,19 +66,3 @@ export async function tarBuffer(entries) {
for await (const c of tarStream(entries)) chunks.push(c)
return Buffer.concat(chunks)
}

/** First entry of an uncompressed tar: `{name, type, size, body, linkname}` (`type` is the raw typeflag). */
export function readFirstTarEntry(buf) {
if (!Buffer.isBuffer(buf) || buf.length < 512) return null
const h = buf.subarray(0, 512)
const field = (off, len) => h.toString('utf8', off, off + len).replace(/\0.*$/s, '')
const size = Number.parseInt(field(124, 12).trim() || '0', 8)
const type = field(156, 1) || '0'
return {
name: field(0, 100),
type,
size,
linkname: field(157, 100),
body: buf.subarray(512, 512 + size),
}
}
57 changes: 41 additions & 16 deletions src/lib/http/respond.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,7 @@ function collectBody(req, maxBytes) {
const chunks = []
let size = 0
let settled = false
const fail = (error) => {
if (settled) return
settled = true
req.removeAllListeners('data')
req.on('data', () => {})
req.resume()
reject(error)
}
req.on('data', (c) => {
const onData = (c) => {
if (settled) return
size += c.length
if (size > maxBytes) {
Expand All @@ -44,22 +36,55 @@ function collectBody(req, maxBytes) {
return
}
chunks.push(c)
})
req.on('end', () => {
}
const onEnd = () => {
if (settled) return
settled = true
cleanup()
resolve(Buffer.concat(chunks))
})
req.on('error', (e) =>
}
const onError = (e) =>
fail(
makeError({
type: ErrorType.API,
code: 'request_stream_error',
message: String(e.message || e),
message: String(e?.message || e),
status: 400,
}),
),
)
)
const onAborted = () =>
fail(
makeError({
type: ErrorType.API,
code: 'request_aborted',
message: 'Request stream aborted before completion',
status: 400,
}),
)
const onClose = () => {
if (!settled && req.complete === false) onAborted()
}
const cleanup = () => {
req.off?.('data', onData)
req.off?.('end', onEnd)
req.off?.('error', onError)
req.off?.('aborted', onAborted)
req.off?.('close', onClose)
}
const fail = (error) => {
if (settled) return
settled = true
cleanup()
req.removeAllListeners?.('data')
req.on('data', () => {})
req.resume?.()
reject(error)
}
req.on('data', onData)
req.on('end', onEnd)
req.on('error', onError)
req.on('aborted', onAborted)
req.on('close', onClose)
})
}

Expand Down
Loading
Loading