-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathkubernetesJobLauncher.js
More file actions
374 lines (335 loc) · 10.9 KB
/
Copy pathkubernetesJobLauncher.js
File metadata and controls
374 lines (335 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
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
204
205
206
207
208
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
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
299
300
301
302
303
304
305
306
307
308
309
310
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
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
import crypto from 'crypto';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { spawn } from 'child_process';
export class KubernetesJobLauncher {
constructor(options = {}) {
this.kubectlPath = options.kubectlPath || process.env.KUBECTL_PATH || 'kubectl';
this.kubeconfig = options.kubeconfig || process.env.KUBECONFIG || null;
this.kubeconfigInlineB64 = options.kubeconfigInlineB64 || process.env.KUBECONFIG_INLINE_B64 || null;
this.inlineKubeconfigPath = null;
this.namespace = options.namespace || process.env.K8S_NAMESPACE || 'rtms';
}
async ensureNamespace() {
const result = await this.kubectl(['get', 'namespace', this.namespace], { allowFailure: true });
if (result.code === 0) return { created: false, namespace: this.namespace };
await this.kubectl(['create', 'namespace', this.namespace]);
return { created: true, namespace: this.namespace };
}
async launchJob(options = {}) {
const streamId = options.streamId || `test-${Date.now()}`;
const jobName = options.jobName || buildKubernetesJobName(streamId, options.prefix);
const envelopeSecretName = options.envelope
? options.envelopeSecretName || `${jobName}-envelope`
: options.envelopeSecretName || null;
if (options.envelope) {
await this.applyManifest(buildEnvelopeSecretManifest({
namespace: this.namespace,
secretName: envelopeSecretName,
envelope: options.envelope,
labels: {
app: 'rtms-compute',
'rtms.zoom/sample': 'distributed',
'rtms.zoom/job-name': jobName
}
}));
}
const manifest = buildJobManifest({
...options,
namespace: this.namespace,
jobName,
envelopeSecretName,
streamId
});
const result = await this.applyManifest(manifest);
if (envelopeSecretName) {
await this.attachSecretToJob(envelopeSecretName, jobName);
}
return {
jobName,
envelopeSecretName,
namespace: this.namespace,
manifest,
stdout: result.stdout,
stderr: result.stderr
};
}
async waitForJobComplete(jobName, timeoutSeconds = 60) {
return this.kubectl([
'-n',
this.namespace,
'wait',
'--for=condition=complete',
`job/${jobName}`,
`--timeout=${timeoutSeconds}s`
]);
}
async getJob(jobName) {
const result = await this.kubectl(['-n', this.namespace, 'get', 'job', jobName, '-o', 'json']);
return JSON.parse(result.stdout);
}
async logs(jobName) {
const result = await this.kubectl(['-n', this.namespace, 'logs', `job/${jobName}`]);
return result.stdout;
}
async deleteJob(jobName) {
return this.kubectl(['-n', this.namespace, 'delete', 'job', jobName, '--ignore-not-found=true']);
}
async deleteSecret(secretName) {
return this.kubectl(['-n', this.namespace, 'delete', 'secret', secretName, '--ignore-not-found=true']);
}
async attachSecretToJob(secretName, jobName) {
const job = await this.getJob(jobName);
const ownerReference = {
apiVersion: 'batch/v1',
kind: 'Job',
name: job.metadata.name,
uid: job.metadata.uid
};
return this.kubectl([
'-n',
this.namespace,
'patch',
'secret',
secretName,
'--type=merge',
'-p',
JSON.stringify({
metadata: {
ownerReferences: [ownerReference]
}
})
]);
}
async applyManifest(manifest) {
return this.kubectl(['apply', '-f', '-'], {
input: JSON.stringify(manifest)
});
}
async kubectl(args, options = {}) {
const env = { ...process.env };
const kubeconfig = this.kubeconfig || this.getInlineKubeconfigPath();
if (kubeconfig) env.KUBECONFIG = kubeconfig;
return runCommand(this.kubectlPath, args, {
env,
input: options.input,
allowFailure: options.allowFailure
});
}
getInlineKubeconfigPath() {
if (!this.kubeconfigInlineB64) return null;
if (this.inlineKubeconfigPath) return this.inlineKubeconfigPath;
const hash = crypto
.createHash('sha256')
.update(this.kubeconfigInlineB64)
.digest('hex')
.slice(0, 16);
const filePath = path.join(os.tmpdir(), `rtms-kubeconfig-${hash}.yaml`);
const content = Buffer.from(this.kubeconfigInlineB64, 'base64').toString('utf8');
fs.writeFileSync(filePath, content, { mode: 0o600 });
this.inlineKubeconfigPath = filePath;
return filePath;
}
}
export function buildKubernetesJobName(streamId, prefix = 'rtms') {
const hash = crypto.createHash('sha256').update(String(streamId)).digest('hex').slice(0, 24);
return `${sanitizeKubernetesName(prefix)}-${hash}`;
}
function buildJobManifest(options = {}) {
const image = options.image || process.env.K8S_COMPUTE_IMAGE || process.env.K8S_TEST_IMAGE || 'busybox:1.36';
const shouldUseImageEntrypoint = options.useImageEntrypoint ?? (
process.env.K8S_USE_IMAGE_ENTRYPOINT === 'true' ||
Boolean(process.env.K8S_COMPUTE_IMAGE && !options.command && !options.args)
);
const secretName = options.secretName || process.env.K8S_COMPUTE_SECRET_NAME || null;
const secretMountPath = options.secretMountPath || process.env.K8S_COMPUTE_SECRET_MOUNT_PATH || null;
const serviceAccountName = options.serviceAccountName || process.env.K8S_COMPUTE_SERVICE_ACCOUNT || null;
const cpuRequest = options.cpuRequest || process.env.K8S_COMPUTE_CPU_REQUEST || '1';
const memoryRequest = options.memoryRequest || process.env.K8S_COMPUTE_MEMORY_REQUEST || '4Gi';
const cpuLimit = options.cpuLimit || process.env.K8S_COMPUTE_CPU_LIMIT || '2';
const memoryLimit = options.memoryLimit || process.env.K8S_COMPUTE_MEMORY_LIMIT || '8Gi';
const envelopeSecretName = options.envelopeSecretName || null;
const envelopeFilePath = options.envelopeFilePath || '/var/run/rtms/envelope.json';
const envelopeRef = options.envelopeRef || `regional-store:/streams/${encodeURIComponent(options.streamId)}`;
const command = shouldUseImageEntrypoint ? undefined : options.command || ['sh', '-c'];
const commandArgs = shouldUseImageEntrypoint ? undefined : options.args || [
[
'echo "busybox RTMS launch test"',
'echo "stream=$RTMS_STREAM_ID region=$REGION_CODE envelope_ref=$RTMS_ENVELOPE_REF"',
'date -u',
'sleep 3'
].join('; ')
];
const labels = {
app: shouldUseImageEntrypoint ? 'rtms-compute' : 'rtms-compute-test',
'rtms.zoom/sample': 'distributed',
...normalizeLabelMap(options.labels)
};
const volumeMounts = [];
const volumes = [];
if (envelopeSecretName) {
volumeMounts.push({
name: 'rtms-envelope',
mountPath: '/var/run/rtms',
readOnly: true
});
volumes.push({
name: 'rtms-envelope',
secret: {
secretName: envelopeSecretName
}
});
}
if (secretName && secretMountPath) {
volumeMounts.push({
name: 'rtms-compute-secrets',
mountPath: secretMountPath,
readOnly: true
});
volumes.push({
name: 'rtms-compute-secrets',
secret: {
secretName
}
});
}
const regionCode = options.regionCode || process.env.SPOKE_REGION || process.env.REGION_CODE || 'test';
const container = {
name: 'rtms-compute',
image,
imagePullPolicy: options.imagePullPolicy || 'IfNotPresent',
resources: {
requests: {
cpu: String(cpuRequest),
memory: String(memoryRequest)
},
limits: {
cpu: String(cpuLimit),
memory: String(memoryLimit)
}
},
env: normalizeEnv({
RTMS_STREAM_ID: options.streamId,
RTMS_ENVELOPE_FILE: envelopeSecretName ? envelopeFilePath : '',
RTMS_ENVELOPE_REF: envelopeRef,
RTMS_SECRET_DIR: secretMountPath || '',
REGION_CODE: regionCode,
SPOKE_REGION: regionCode,
REGIONAL_STORE_URL: options.regionalStoreUrl || process.env.REGIONAL_STORE_URL || '',
CENTRAL_STORE_URL: options.centralStoreUrl || process.env.CENTRAL_STORE_URL || '',
...(options.env || {})
}),
volumeMounts: volumeMounts.length > 0 ? volumeMounts : undefined,
...(secretName ? { envFrom: [{ secretRef: { name: secretName } }] } : {})
};
if (command) {
container.command = command;
}
if (commandArgs) {
container.args = commandArgs;
}
const podSpec = {
restartPolicy: 'Never',
terminationGracePeriodSeconds: Number(options.terminationGracePeriodSeconds ?? 30),
containers: [container]
};
if (serviceAccountName) {
podSpec.serviceAccountName = serviceAccountName;
}
if (volumes.length > 0) {
podSpec.volumes = volumes;
}
return {
apiVersion: 'batch/v1',
kind: 'Job',
metadata: {
name: options.jobName,
namespace: options.namespace,
labels
},
spec: {
backoffLimit: Number(options.backoffLimit ?? 0),
ttlSecondsAfterFinished: Number(options.ttlSecondsAfterFinished ?? 300),
template: {
metadata: { labels },
spec: podSpec
}
}
};
}
function buildEnvelopeSecretManifest(options = {}) {
return {
apiVersion: 'v1',
kind: 'Secret',
metadata: {
name: options.secretName,
namespace: options.namespace,
labels: normalizeLabelMap(options.labels)
},
type: 'Opaque',
stringData: {
'envelope.json': JSON.stringify(options.envelope, null, 2)
}
};
}
function normalizeEnv(values) {
return Object.entries(values)
.filter(([_name, value]) => value !== undefined && value !== null)
.map(([name, value]) => ({ name, value: String(value) }));
}
function normalizeLabelMap(values = {}) {
return Object.fromEntries(
Object.entries(values).map(([key, value]) => [
sanitizeLabelKey(key),
sanitizeLabelValue(value)
])
);
}
function sanitizeKubernetesName(value) {
const sanitized = String(value || 'rtms')
.toLowerCase()
.replace(/[^a-z0-9-]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 40);
return sanitized || 'rtms';
}
function sanitizeLabelKey(value) {
return String(value || 'label')
.replace(/[^A-Za-z0-9_.\\/-]+/g, '-')
.slice(0, 63);
}
function sanitizeLabelValue(value) {
return String(value || '')
.replace(/[^A-Za-z0-9_.-]+/g, '-')
.slice(0, 63);
}
function runCommand(command, args, options = {}) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
env: options.env || process.env,
stdio: ['pipe', 'pipe', 'pipe']
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => {
stdout += chunk.toString();
});
child.stderr.on('data', (chunk) => {
stderr += chunk.toString();
});
child.on('error', reject);
child.on('close', (code) => {
const result = { code, stdout, stderr };
if (code === 0 || options.allowFailure) {
resolve(result);
return;
}
const error = new Error(`${command} ${args.join(' ')} failed with code ${code}: ${stderr || stdout}`);
error.result = result;
reject(error);
});
if (options.input) child.stdin.write(options.input);
child.stdin.end();
});
}