@yaks/sandbox 0.0.0-stage → 0.2.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +400 -2
- package/_dist/bubblewrap.d.ts +38 -0
- package/_dist/bubblewrap.d.ts.map +1 -0
- package/_dist/cloudflare.d.ts +136 -0
- package/_dist/cloudflare.d.ts.map +1 -0
- package/_dist/configuration.d.ts +13 -0
- package/_dist/configuration.d.ts.map +1 -0
- package/_dist/docker.d.ts +15 -0
- package/_dist/docker.d.ts.map +1 -0
- package/_dist/effects.d.ts +6 -0
- package/_dist/effects.d.ts.map +1 -0
- package/_dist/lifecycle.d.ts +38 -0
- package/_dist/lifecycle.d.ts.map +1 -0
- package/_dist/mod.d.ts +4 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/provider.d.ts +33 -0
- package/_dist/provider.d.ts.map +1 -0
- package/_dist/pve.d.ts +17 -0
- package/_dist/pve.d.ts.map +1 -0
- package/_dist/recovery.d.ts +71 -0
- package/_dist/recovery.d.ts.map +1 -0
- package/_dist/tools.d.ts +4 -0
- package/_dist/tools.d.ts.map +1 -0
- package/_dist/vocab.d.ts +5 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/archive.js +60 -0
- package/archive.js.map +1 -0
- package/archive.ts +49 -0
- package/bubblewrap.js +495 -0
- package/bubblewrap.js.map +1 -0
- package/bubblewrap.ts +555 -0
- package/cloudflare.js +434 -0
- package/cloudflare.js.map +1 -0
- package/cloudflare.ts +592 -0
- package/configuration.js +84 -0
- package/configuration.js.map +1 -0
- package/configuration.ts +120 -0
- package/deno.json +1 -0
- package/docker.js +149 -0
- package/docker.js.map +1 -0
- package/docker.ts +206 -0
- package/effects.js +86 -0
- package/effects.js.map +1 -0
- package/effects.ts +78 -0
- package/lifecycle.js +153 -0
- package/lifecycle.js.map +1 -0
- package/lifecycle.ts +207 -0
- package/mod.js +6 -0
- package/mod.js.map +1 -0
- package/mod.ts +7 -0
- package/package.json +64 -4
- package/provider.js +11 -0
- package/provider.js.map +1 -0
- package/provider.ts +44 -0
- package/pve.js +197 -0
- package/pve.js.map +1 -0
- package/pve.ts +259 -0
- package/recovery-script.js +187 -0
- package/recovery-script.js.map +1 -0
- package/recovery-script.ts +186 -0
- package/recovery.js +231 -0
- package/recovery.js.map +1 -0
- package/recovery.ts +317 -0
- package/sandbox-runner.js +218 -0
- package/sandbox-runner.js.map +1 -0
- package/sandbox-runner.ts +217 -0
- package/tools.js +42 -0
- package/tools.js.map +1 -0
- package/tools.ts +45 -0
- package/vocab.js +13 -0
- package/vocab.js.map +1 -0
- package/vocab.json +180 -0
- package/vocab.ts +11 -0
package/recovery.ts
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
import { bucketCode, BucketUnavailable, patient } from '@yaks/blob'
|
|
2
|
+
import { sleep } from '@yaks/fp'
|
|
3
|
+
import { script } from './recovery-script.js'
|
|
4
|
+
|
|
5
|
+
type Head = { key: string; size: number; at: string }
|
|
6
|
+
type Part = { partNumber: number; etag: string }
|
|
7
|
+
type State = {
|
|
8
|
+
get<T>(key: string): Promise<T | undefined>
|
|
9
|
+
put(key: string, value: unknown): Promise<unknown>
|
|
10
|
+
delete(key: string): Promise<unknown>
|
|
11
|
+
}
|
|
12
|
+
type Archive = {
|
|
13
|
+
createMultipartUpload(key: string): Promise<{
|
|
14
|
+
uploadId: string
|
|
15
|
+
uploadPart(part: number, bytes: Uint8Array): Promise<Part>
|
|
16
|
+
complete(parts: Part[]): Promise<unknown>
|
|
17
|
+
abort(): Promise<void>
|
|
18
|
+
}>
|
|
19
|
+
put(key: string, content: string): Promise<unknown>
|
|
20
|
+
list(options: { prefix: string; cursor?: string }): Promise<{
|
|
21
|
+
objects: { key: string }[]
|
|
22
|
+
truncated: boolean
|
|
23
|
+
cursor?: string
|
|
24
|
+
}>
|
|
25
|
+
delete(keys: string[]): Promise<unknown>
|
|
26
|
+
}
|
|
27
|
+
type Box = {
|
|
28
|
+
live(): boolean | Promise<boolean>
|
|
29
|
+
start?(): Promise<void>
|
|
30
|
+
exec(command: string): Promise<{
|
|
31
|
+
exitCode: number
|
|
32
|
+
stdout: string
|
|
33
|
+
stderr: string
|
|
34
|
+
}>
|
|
35
|
+
}
|
|
36
|
+
type Filesystem = {
|
|
37
|
+
live(): boolean | Promise<boolean>
|
|
38
|
+
start?(): Promise<void>
|
|
39
|
+
run(mode: string, ...args: string[]): Promise<string>
|
|
40
|
+
read(): AsyncIterable<Uint8Array>
|
|
41
|
+
restore(name: string, size: number): Promise<string>
|
|
42
|
+
}
|
|
43
|
+
type Recovery = {
|
|
44
|
+
prepare(): Promise<void>
|
|
45
|
+
save(): Promise<void>
|
|
46
|
+
use<T>(act: () => Promise<T>): Promise<T>
|
|
47
|
+
idle(busy: () => Promise<boolean>, stop: () => Promise<void>): Promise<void>
|
|
48
|
+
stop<T>(act: () => Promise<T>): Promise<T>
|
|
49
|
+
purge(stop: () => Promise<unknown>): Promise<void>
|
|
50
|
+
reset(): void
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
let quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'"
|
|
54
|
+
export let RECOVERY_HOST = 'workbench-recovery.internal'
|
|
55
|
+
export let ARCHIVE_PATH = '/.yak-recovery/snapshot.tar.gz'
|
|
56
|
+
let prefix = (id: string) => `workbench/${id}/`
|
|
57
|
+
let archiveName = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}\.tar\.gz$/
|
|
58
|
+
|
|
59
|
+
type Download = {
|
|
60
|
+
get(key: string): Promise<
|
|
61
|
+
{
|
|
62
|
+
body: ReadableStream<Uint8Array>
|
|
63
|
+
size: number
|
|
64
|
+
} | null
|
|
65
|
+
>
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A container can stream only its own archives through its outbound proxy. */
|
|
69
|
+
export let snapshot = async (
|
|
70
|
+
bucket: Download,
|
|
71
|
+
id: string,
|
|
72
|
+
request: Request,
|
|
73
|
+
): Promise<Response> => {
|
|
74
|
+
if (request.method != 'GET') return new Response(null, { status: 405 })
|
|
75
|
+
let name = new URL(request.url).pathname.slice(1)
|
|
76
|
+
if (!id || !archiveName.test(name)) return new Response(null, { status: 404 })
|
|
77
|
+
let found = await bucket.get(prefix(id) + name)
|
|
78
|
+
return found
|
|
79
|
+
? new Response(found.body, {
|
|
80
|
+
headers: { 'Content-Length': String(found.size) },
|
|
81
|
+
})
|
|
82
|
+
: new Response(null, { status: 404 })
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
let PART = 5 * 1024 * 1024
|
|
86
|
+
let NO_UPLOAD = 10024
|
|
87
|
+
let HEAD = 'workbench:head'
|
|
88
|
+
|
|
89
|
+
export let filesystem = (
|
|
90
|
+
box: Box,
|
|
91
|
+
read: () => AsyncIterable<Uint8Array>,
|
|
92
|
+
root = '/',
|
|
93
|
+
): Filesystem => {
|
|
94
|
+
let run = async (mode: string, ...args: string[]) => {
|
|
95
|
+
let result = await box.exec(
|
|
96
|
+
`python3 -c ${quote(script)} ${
|
|
97
|
+
[mode, root, ...args].map(quote).join(' ')
|
|
98
|
+
}`,
|
|
99
|
+
)
|
|
100
|
+
if (result.exitCode) throw new Error(`workbench snapshot: ${result.stderr}`)
|
|
101
|
+
return result.stdout.trim()
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
live: box.live,
|
|
105
|
+
start: box.start,
|
|
106
|
+
run,
|
|
107
|
+
read,
|
|
108
|
+
restore: (name: string, size: number) =>
|
|
109
|
+
run('restore', `http://${RECOVERY_HOST}/${name}`, String(size)),
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Rebatch byte streams for multipart storage without buffering an archive. */
|
|
114
|
+
export let chunks = async function* (
|
|
115
|
+
source: AsyncIterable<Uint8Array>,
|
|
116
|
+
size: number,
|
|
117
|
+
): AsyncIterable<Uint8Array<ArrayBuffer>> {
|
|
118
|
+
let buffer = new Uint8Array(size)
|
|
119
|
+
let used = 0
|
|
120
|
+
for await (let chunk of source) {
|
|
121
|
+
for (let offset = 0; offset < chunk.length;) {
|
|
122
|
+
let length = Math.min(size - used, chunk.length - offset)
|
|
123
|
+
buffer.set(chunk.subarray(offset, offset + length), used)
|
|
124
|
+
offset += length
|
|
125
|
+
used += length
|
|
126
|
+
if (used == size) {
|
|
127
|
+
yield buffer
|
|
128
|
+
buffer = new Uint8Array(size)
|
|
129
|
+
used = 0
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (used) yield buffer.subarray(0, used)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
let archived = async (
|
|
137
|
+
box: Filesystem,
|
|
138
|
+
bucket: Archive,
|
|
139
|
+
id: string,
|
|
140
|
+
size: number,
|
|
141
|
+
pause: (ms: number) => Promise<void>,
|
|
142
|
+
): Promise<Head> => {
|
|
143
|
+
let key = prefix(id) + crypto.randomUUID() + '.tar.gz'
|
|
144
|
+
let upload = await bucket.createMultipartUpload(key)
|
|
145
|
+
try {
|
|
146
|
+
let parts: Part[] = []
|
|
147
|
+
let received = 0
|
|
148
|
+
for await (let content of chunks(box.read(), PART)) {
|
|
149
|
+
received += content.length
|
|
150
|
+
let part = parts.length + 1
|
|
151
|
+
let uploaded = await patient(
|
|
152
|
+
() => upload.uploadPart(part, content),
|
|
153
|
+
pause,
|
|
154
|
+
3,
|
|
155
|
+
).catch((error) => {
|
|
156
|
+
console.warn('workbench snapshot part failed', {
|
|
157
|
+
key,
|
|
158
|
+
uploadId: upload.uploadId,
|
|
159
|
+
part,
|
|
160
|
+
bytes: content.length,
|
|
161
|
+
error: String(error),
|
|
162
|
+
})
|
|
163
|
+
throw error
|
|
164
|
+
})
|
|
165
|
+
parts.push(uploaded)
|
|
166
|
+
}
|
|
167
|
+
if (received != size) throw new Error('workbench snapshot is incomplete')
|
|
168
|
+
await upload.complete(parts)
|
|
169
|
+
} catch (error) {
|
|
170
|
+
try {
|
|
171
|
+
await patient(() => upload.abort(), pause, 3)
|
|
172
|
+
} catch (cleanup) {
|
|
173
|
+
if (bucketCode(cleanup) != NO_UPLOAD) {
|
|
174
|
+
throw new AggregateError(
|
|
175
|
+
[error, cleanup],
|
|
176
|
+
`workbench snapshot failed and could not abort its upload: ${error}; ${cleanup}`,
|
|
177
|
+
)
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
throw error instanceof BucketUnavailable ? error.cause : error
|
|
181
|
+
}
|
|
182
|
+
return { key, size, at: new Date().toISOString() }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Recoverable workbench files, independent of the container SDK. Immutable
|
|
186
|
+
* archives and receipts have no expiry; the DO holds only the current head.
|
|
187
|
+
* A failed archive or head write leaves the container running. An upload cut
|
|
188
|
+
* off where no `catch` runs (the object reset mid-save) is aborted by the
|
|
189
|
+
* bucket's rule for `workbench/` (workers/yak/README.md, bucket setup). */
|
|
190
|
+
export let recovery = (
|
|
191
|
+
box: Filesystem,
|
|
192
|
+
state: State,
|
|
193
|
+
bucket: Archive,
|
|
194
|
+
id: string,
|
|
195
|
+
pause: (ms: number) => Promise<void> = sleep,
|
|
196
|
+
): Recovery => {
|
|
197
|
+
let { run } = box
|
|
198
|
+
let prepared: Promise<void> | undefined
|
|
199
|
+
let checkpoint: Promise<void> | undefined
|
|
200
|
+
let fence = Promise.resolve()
|
|
201
|
+
let active = new Set<Promise<unknown>>()
|
|
202
|
+
let activity = 0
|
|
203
|
+
// Restore is shared by workspace calls. Snapshot and shutdown wait for
|
|
204
|
+
// those calls, and later calls wait for the snapshot and shutdown.
|
|
205
|
+
let locked = <T>(act: () => Promise<T>) => {
|
|
206
|
+
let result = Promise.allSettled([fence, ...active]).then(act)
|
|
207
|
+
fence = result.then(() => {}, () => {})
|
|
208
|
+
return result
|
|
209
|
+
}
|
|
210
|
+
let prepare = () =>
|
|
211
|
+
prepared ??= (async () => {
|
|
212
|
+
let woke = Date.now()
|
|
213
|
+
let running = await box.live()
|
|
214
|
+
if (!running) await box.start?.()
|
|
215
|
+
let made = await run(running ? 'existing' : 'fresh')
|
|
216
|
+
if (made != 'fresh') return
|
|
217
|
+
let head = await state.get<Head>(HEAD)
|
|
218
|
+
if (head) {
|
|
219
|
+
let name = head.key.slice(prefix(id).length)
|
|
220
|
+
if (!head.key.startsWith(prefix(id)) || !archiveName.test(name)) {
|
|
221
|
+
throw new Error('workbench snapshot key is invalid')
|
|
222
|
+
}
|
|
223
|
+
let started = Date.now()
|
|
224
|
+
let phases = await box.restore(name, head.size)
|
|
225
|
+
console.info('workbench restored', {
|
|
226
|
+
bytes: head.size,
|
|
227
|
+
// Starting the container and scanning its image, before the restore.
|
|
228
|
+
started: started - woke,
|
|
229
|
+
ms: Date.now() - started,
|
|
230
|
+
phases,
|
|
231
|
+
})
|
|
232
|
+
}
|
|
233
|
+
await run('ready')
|
|
234
|
+
})().catch((error) => {
|
|
235
|
+
prepared = undefined
|
|
236
|
+
throw error
|
|
237
|
+
})
|
|
238
|
+
let save = () =>
|
|
239
|
+
checkpoint ??= (async () => {
|
|
240
|
+
if (!await box.live()) return
|
|
241
|
+
await prepare()
|
|
242
|
+
let size = Number(await run('save'))
|
|
243
|
+
if (!Number.isSafeInteger(size) || size <= 0) {
|
|
244
|
+
throw new Error('workbench snapshot size is invalid')
|
|
245
|
+
}
|
|
246
|
+
// The tar file can be read afresh. Each attempt owns a separate upload,
|
|
247
|
+
// so a lost completion response cannot make a retry overwrite an archive.
|
|
248
|
+
let head = await patient(
|
|
249
|
+
() => archived(box, bucket, id, size, pause),
|
|
250
|
+
pause,
|
|
251
|
+
3,
|
|
252
|
+
1000,
|
|
253
|
+
)
|
|
254
|
+
let receipt = head.key.replace(/\.tar\.gz$/, '.json')
|
|
255
|
+
await patient(() => bucket.put(receipt, JSON.stringify(head)), pause)
|
|
256
|
+
await state.put(HEAD, head)
|
|
257
|
+
})().finally(() => {
|
|
258
|
+
checkpoint = undefined
|
|
259
|
+
})
|
|
260
|
+
let stop = async <T>(act: () => Promise<T>) => {
|
|
261
|
+
await save()
|
|
262
|
+
let result = await act()
|
|
263
|
+
prepared = undefined
|
|
264
|
+
return result
|
|
265
|
+
}
|
|
266
|
+
return {
|
|
267
|
+
prepare,
|
|
268
|
+
save: () => locked(save),
|
|
269
|
+
use: <T>(act: () => Promise<T>) => {
|
|
270
|
+
let result = fence.then(async () => {
|
|
271
|
+
try {
|
|
272
|
+
await prepare()
|
|
273
|
+
return await act()
|
|
274
|
+
} finally {
|
|
275
|
+
activity++
|
|
276
|
+
}
|
|
277
|
+
})
|
|
278
|
+
active.add(result)
|
|
279
|
+
let ended = () => active.delete(result)
|
|
280
|
+
result.then(ended, ended)
|
|
281
|
+
return result
|
|
282
|
+
},
|
|
283
|
+
idle: (busy, shutdown) => {
|
|
284
|
+
if (active.size) return Promise.resolve()
|
|
285
|
+
let seen = activity
|
|
286
|
+
return locked(async () => {
|
|
287
|
+
if (seen != activity || !await box.live() || await busy()) return
|
|
288
|
+
await save()
|
|
289
|
+
// A call that arrived during the snapshot waits for it, and finds the
|
|
290
|
+
// container still awake rather than a fresh one restoring the files.
|
|
291
|
+
if (active.size) return
|
|
292
|
+
await shutdown()
|
|
293
|
+
prepared = undefined
|
|
294
|
+
})
|
|
295
|
+
},
|
|
296
|
+
stop: (act) => locked(() => stop(act)),
|
|
297
|
+
// The caller reaches this only after the person confirms their purge.
|
|
298
|
+
// Stop first so no command can create unarchived state during removal.
|
|
299
|
+
purge: (stop: () => Promise<unknown>) =>
|
|
300
|
+
locked(async () => {
|
|
301
|
+
await stop()
|
|
302
|
+
let cursor: string | undefined
|
|
303
|
+
do {
|
|
304
|
+
let page = await bucket.list({ prefix: prefix(id), cursor })
|
|
305
|
+
if (page.objects.length) {
|
|
306
|
+
await bucket.delete(page.objects.map(({ key }) => key))
|
|
307
|
+
}
|
|
308
|
+
cursor = page.truncated ? page.cursor : undefined
|
|
309
|
+
} while (cursor)
|
|
310
|
+
await state.delete(HEAD)
|
|
311
|
+
prepared = undefined
|
|
312
|
+
}),
|
|
313
|
+
reset: () => {
|
|
314
|
+
prepared = undefined
|
|
315
|
+
},
|
|
316
|
+
}
|
|
317
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
// The sandbox's detached supervisor. Its socket, receipts and output live on
|
|
2
|
+
// the host, outside the bind mount commands see. Every child remains in this
|
|
3
|
+
// supervisor's limited scope; it cannot reach the user manager to escape it.
|
|
4
|
+
export let sandboxRunner = String.raw`
|
|
5
|
+
import base64, json, os, signal, socketserver, subprocess, sys, threading, time
|
|
6
|
+
|
|
7
|
+
root = sys.argv[1]
|
|
8
|
+
with open(root + '/config.json') as f:
|
|
9
|
+
config = json.load(f)
|
|
10
|
+
commands = root + '/commands'
|
|
11
|
+
os.makedirs(commands, mode=0o700, exist_ok=True)
|
|
12
|
+
lock = threading.RLock()
|
|
13
|
+
live = {}
|
|
14
|
+
|
|
15
|
+
def save(path, data):
|
|
16
|
+
temp = path + '.tmp'
|
|
17
|
+
with open(temp, 'w') as f:
|
|
18
|
+
json.dump(data, f)
|
|
19
|
+
os.replace(temp, path)
|
|
20
|
+
|
|
21
|
+
def path_for(id):
|
|
22
|
+
if not id or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-' for c in id):
|
|
23
|
+
raise ValueError('invalid command id')
|
|
24
|
+
return commands + '/' + id
|
|
25
|
+
|
|
26
|
+
def state(id):
|
|
27
|
+
try:
|
|
28
|
+
with open(path_for(id) + '.json') as f:
|
|
29
|
+
return json.load(f)
|
|
30
|
+
except FileNotFoundError:
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
# A supervisor that died cannot safely signal a recorded PID: it may have
|
|
34
|
+
# been reused. A scope is stopped before replacement, and old receipts end
|
|
35
|
+
# with unknown status, never a second launch of the same durable call.
|
|
36
|
+
for name in os.listdir(commands):
|
|
37
|
+
if name.endswith('.json'):
|
|
38
|
+
path = commands + '/' + name
|
|
39
|
+
with open(path) as f:
|
|
40
|
+
old = json.load(f)
|
|
41
|
+
if 'exit' not in old:
|
|
42
|
+
old['exit'] = {'code': None}
|
|
43
|
+
save(path, old)
|
|
44
|
+
|
|
45
|
+
with open('/proc/self/cgroup') as f:
|
|
46
|
+
group = next(line.strip()[3:] for line in f if line.startswith('0::'))
|
|
47
|
+
cgroup = '/sys/fs/cgroup' + group
|
|
48
|
+
with open(cgroup + '/cpu.max') as f:
|
|
49
|
+
quota, period = f.read().split()
|
|
50
|
+
with open(cgroup + '/memory.max') as f:
|
|
51
|
+
memory = f.read().strip()
|
|
52
|
+
with open(cgroup + '/pids.max') as f:
|
|
53
|
+
tasks = f.read().strip()
|
|
54
|
+
limits = config['limits']
|
|
55
|
+
if (quota == 'max' or int(quota) / int(period) > limits['cpuQuota'] / 100 + 0.00001
|
|
56
|
+
or memory == 'max' or int(memory) > limits['memoryMax']
|
|
57
|
+
or tasks == 'max' or int(tasks) > limits['tasksMax']):
|
|
58
|
+
raise RuntimeError('sandbox scope did not apply its CPU, memory and task limits')
|
|
59
|
+
|
|
60
|
+
def argv(args, cwd='/workspace', env=None):
|
|
61
|
+
result = list(config['bwrap'])
|
|
62
|
+
for key, value in (env or {}).items():
|
|
63
|
+
result += ['--setenv', key, value]
|
|
64
|
+
return result + ['--chdir', cwd, '--'] + args
|
|
65
|
+
|
|
66
|
+
# Fail before lending a machine if namespaces or the read-only system cannot
|
|
67
|
+
# actually execute. Never fall back to an unrestricted host command.
|
|
68
|
+
subprocess.run(argv(['/bin/bash', '-c', 'true']), check=True)
|
|
69
|
+
|
|
70
|
+
# One pre-existing reaper and one sequential control server keep look/kill
|
|
71
|
+
# available even when guest forks fill TasksMax. No per-request thread is
|
|
72
|
+
# needed to recover from task pressure.
|
|
73
|
+
def reap():
|
|
74
|
+
while True:
|
|
75
|
+
with lock:
|
|
76
|
+
for id, child in list(live.items()):
|
|
77
|
+
code = child.poll()
|
|
78
|
+
if code is not None:
|
|
79
|
+
value = state(id)
|
|
80
|
+
value['exit'] = {'code': code if code >= 0 else 128 - code}
|
|
81
|
+
save(path_for(id) + '.json', value)
|
|
82
|
+
live.pop(id, None)
|
|
83
|
+
time.sleep(0.025)
|
|
84
|
+
|
|
85
|
+
threading.Thread(target=reap, daemon=True).start()
|
|
86
|
+
|
|
87
|
+
# A path that holds no file the guest may read or write: the caller's mistake.
|
|
88
|
+
class PathFault(Exception):
|
|
89
|
+
pass
|
|
90
|
+
|
|
91
|
+
# A file operation, run in the guest on its path p. Python starts bare
|
|
92
|
+
# (-I -S) and a failure says the last line of its traceback alone: printing
|
|
93
|
+
# the whole one loads more of Python than the operation does. A path fault
|
|
94
|
+
# exits 3, so the host can tell it from a failure of ours.
|
|
95
|
+
def run_file(code, path, data=None):
|
|
96
|
+
script = ('import errno, os, sys\np = sys.argv[1]\ntry:\n ' + code.replace('\n', '\n ') +
|
|
97
|
+
'\nexcept Exception as e:\n print(f"{type(e).__name__}: {e}", file=sys.stderr)'
|
|
98
|
+
'\n sys.exit(3 if getattr(e, "errno", None) in (errno.ENOENT, errno.EACCES,'
|
|
99
|
+
' errno.ENOTDIR, errno.EISDIR, errno.EROFS) else 1)')
|
|
100
|
+
result = subprocess.run(argv(['/usr/bin/python3', '-I', '-S', '-c', script, path]),
|
|
101
|
+
input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
|
102
|
+
said = result.stderr.decode(errors='replace').strip()
|
|
103
|
+
if result.returncode == 3:
|
|
104
|
+
raise PathFault(said)
|
|
105
|
+
if result.returncode:
|
|
106
|
+
raise RuntimeError(said)
|
|
107
|
+
return result.stdout
|
|
108
|
+
|
|
109
|
+
# What each path in the JSON list p names, its links followed: the kind and,
|
|
110
|
+
# where it names something, its canonical path. An unreachable path is
|
|
111
|
+
# missing, as a shell's test -e says.
|
|
112
|
+
STAT = '''import json, stat
|
|
113
|
+
said = []
|
|
114
|
+
for q in json.loads(p):
|
|
115
|
+
try:
|
|
116
|
+
mode = os.stat(q).st_mode
|
|
117
|
+
except OSError:
|
|
118
|
+
said.append({'kind': 'dangling' if os.path.islink(q) else 'missing'})
|
|
119
|
+
continue
|
|
120
|
+
kind = 'file' if stat.S_ISREG(mode) else 'directory' if stat.S_ISDIR(mode) else 'other'
|
|
121
|
+
said.append({'kind': kind, 'canonical': os.path.realpath(q)})
|
|
122
|
+
sys.stdout.write(json.dumps(said))'''
|
|
123
|
+
|
|
124
|
+
def handle(request):
|
|
125
|
+
op = request['op']
|
|
126
|
+
if op == 'hello':
|
|
127
|
+
return {'cgroup': cgroup, 'cpu': [quota, period], 'memory': memory, 'tasks': tasks}
|
|
128
|
+
if op == 'start':
|
|
129
|
+
id = request['id']
|
|
130
|
+
with lock:
|
|
131
|
+
prior = state(id)
|
|
132
|
+
if prior is not None:
|
|
133
|
+
return prior
|
|
134
|
+
# The receipt precedes the external act; an ambiguous receipt is
|
|
135
|
+
# inspectable, but must never cause a durable call to run twice.
|
|
136
|
+
value = {}
|
|
137
|
+
save(path_for(id) + '.json', value)
|
|
138
|
+
try:
|
|
139
|
+
with open(path_for(id) + '.out', 'ab') as output:
|
|
140
|
+
child = subprocess.Popen(argv(['/bin/bash', '-c', request['command']],
|
|
141
|
+
request['cwd'], request['env']), stdin=subprocess.DEVNULL,
|
|
142
|
+
stdout=output, stderr=subprocess.STDOUT, start_new_session=True)
|
|
143
|
+
value['pid'] = child.pid
|
|
144
|
+
save(path_for(id) + '.json', value)
|
|
145
|
+
live[id] = child
|
|
146
|
+
except Exception:
|
|
147
|
+
value['exit'] = {'code': None}
|
|
148
|
+
save(path_for(id) + '.json', value)
|
|
149
|
+
raise
|
|
150
|
+
return value
|
|
151
|
+
if op == 'look':
|
|
152
|
+
with lock:
|
|
153
|
+
return state(request['id'])
|
|
154
|
+
if op == 'tail':
|
|
155
|
+
try:
|
|
156
|
+
with open(path_for(request['id']) + '.out', 'rb') as f:
|
|
157
|
+
# Scan backwards: a long-running agent's whole log is not a
|
|
158
|
+
# request's memory footprint. Keep arbitrarily wide lines.
|
|
159
|
+
blocks = []
|
|
160
|
+
end = f.seek(0, 2)
|
|
161
|
+
lines = 0
|
|
162
|
+
while end and lines <= request['n']:
|
|
163
|
+
size = min(end, 65536)
|
|
164
|
+
end -= size
|
|
165
|
+
f.seek(end)
|
|
166
|
+
block = f.read(size)
|
|
167
|
+
blocks.append(block)
|
|
168
|
+
lines += block.count(b'\n')
|
|
169
|
+
return b''.join(reversed(blocks)).decode(errors='replace').splitlines()[-request['n']:]
|
|
170
|
+
except FileNotFoundError:
|
|
171
|
+
return []
|
|
172
|
+
if op == 'kill':
|
|
173
|
+
with lock:
|
|
174
|
+
child = live.get(request['id'])
|
|
175
|
+
if child is not None and child.poll() is None:
|
|
176
|
+
try:
|
|
177
|
+
os.killpg(child.pid, getattr(signal, request['signal']))
|
|
178
|
+
except ProcessLookupError:
|
|
179
|
+
pass
|
|
180
|
+
return None
|
|
181
|
+
if op in ('read', 'export'):
|
|
182
|
+
code = 'sys.stdout.buffer.write(open(p, "rb").read())'
|
|
183
|
+
if op == 'export':
|
|
184
|
+
code = ('p = os.path.realpath(p); '
|
|
185
|
+
'assert p.startswith("/workspace/"), "export escapes workspace"; ' + code)
|
|
186
|
+
return base64.b64encode(run_file(code, request['path'])).decode()
|
|
187
|
+
if op == 'stat':
|
|
188
|
+
return json.loads(run_file(STAT, json.dumps(request['paths'])))
|
|
189
|
+
if op == 'write':
|
|
190
|
+
run_file('os.makedirs(os.path.dirname(p), exist_ok=True); '
|
|
191
|
+
'open(p, "wb").write(sys.stdin.buffer.read())',
|
|
192
|
+
request['path'], base64.b64decode(request['bytes']))
|
|
193
|
+
return None
|
|
194
|
+
raise ValueError('unknown sandbox operation')
|
|
195
|
+
|
|
196
|
+
class Handler(socketserver.StreamRequestHandler):
|
|
197
|
+
def handle(self):
|
|
198
|
+
try:
|
|
199
|
+
response = {'value': handle(json.loads(self.rfile.readline()))}
|
|
200
|
+
except PathFault as e:
|
|
201
|
+
response = {'error': str(e), 'refused': 'path'}
|
|
202
|
+
except Exception as e:
|
|
203
|
+
response = {'error': str(e)}
|
|
204
|
+
self.wfile.write((json.dumps(response) + '\n').encode())
|
|
205
|
+
|
|
206
|
+
class Server(socketserver.UnixStreamServer):
|
|
207
|
+
pass
|
|
208
|
+
|
|
209
|
+
sock = root + '/control.sock'
|
|
210
|
+
try:
|
|
211
|
+
os.unlink(sock)
|
|
212
|
+
except FileNotFoundError:
|
|
213
|
+
pass
|
|
214
|
+
with Server(sock, Handler) as server:
|
|
215
|
+
os.chmod(sock, 0o600)
|
|
216
|
+
server.serve_forever()
|
|
217
|
+
`;
|
|
218
|
+
//# sourceMappingURL=sandbox-runner.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sandbox-runner.js","sources":["./sandbox-runner.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,6EAA6E;AAC7E,6EAA6E;AAC7E,OAAO,IAAI,gBAAgB,OAAO,GAAG,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqNtC,CAAC,CAAA"}
|