-
Notifications
You must be signed in to change notification settings - Fork 162
Expand file tree
/
Copy pathrunner-session.ts
More file actions
389 lines (368 loc) · 11 KB
/
Copy pathrunner-session.ts
File metadata and controls
389 lines (368 loc) · 11 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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
import { AppError } from '../../utils/errors.ts';
import {
runCmd,
runCmdBackground,
type ExecResult,
type ExecBackgroundResult,
} from '../../utils/exec.ts';
import { withKeyedLock } from '../../utils/keyed-lock.ts';
import { isProcessAlive } from '../../utils/process-identity.ts';
import type { DeviceInfo } from '../../utils/device.ts';
import { buildSimctlArgsForDevice } from './simctl.ts';
import {
waitForRunner,
getFreePort,
logChunk,
cleanupTempFile,
RUNNER_STARTUP_TIMEOUT_MS,
RUNNER_DESTINATION_TIMEOUT_SECONDS,
} from './runner-transport.ts';
import {
acquireXcodebuildSimulatorSetRedirect,
ensureXctestrun,
IOS_RUNNER_CONTAINER_BUNDLE_IDS,
prepareXctestrunWithEnv,
resolveRunnerDestination,
resolveRunnerMaxConcurrentDestinationsFlag,
runnerPrepProcesses,
} from './runner-xctestrun.ts';
import type { RunnerCommand } from './runner-contract.ts';
export type RunnerSession = {
sessionId: string;
device: DeviceInfo;
deviceId: string;
port: number;
xctestrunPath: string;
jsonPath: string;
testPromise: Promise<ExecResult>;
child: ExecBackgroundResult['child'];
ready: boolean;
simulatorSetRedirect?: { release: () => Promise<void> };
};
const runnerSessions = new Map<string, RunnerSession>();
const runnerSessionLocks = new Map<string, Promise<unknown>>();
const RUNNER_STOP_WAIT_TIMEOUT_MS = 10_000;
const RUNNER_SHUTDOWN_TIMEOUT_MS = 15_000;
function withRunnerSessionLock<T>(deviceId: string, task: () => Promise<T>): Promise<T> {
return withKeyedLock(runnerSessionLocks, deviceId, task);
}
export async function ensureRunnerSession(
device: DeviceInfo,
options: { verbose?: boolean; logPath?: string; traceLogPath?: string },
): Promise<RunnerSession> {
return await withRunnerSessionLock(device.id, async () => {
const existing = runnerSessions.get(device.id);
if (existing) {
if (isRunnerProcessAlive(existing.child.pid)) {
return existing;
}
await stopRunnerSessionInternal(device.id, existing);
}
await ensureBootedIfNeeded(device);
await cleanupStaleSimulatorRunnerBundles(device);
const xctestrun = await ensureXctestrun(device, options);
const port = await getFreePort();
const { xctestrunPath, jsonPath } = await prepareXctestrunWithEnv(
xctestrun,
{ AGENT_DEVICE_RUNNER_PORT: String(port) },
`session-${device.id}-${port}`,
);
const simulatorSetRedirect = await acquireXcodebuildSimulatorSetRedirect(device);
let child: ExecBackgroundResult['child'];
let testPromise: Promise<ExecResult>;
try {
({ child, wait: testPromise } = runCmdBackground(
'xcodebuild',
[
'test-without-building',
'-only-testing',
'AgentDeviceRunnerUITests/RunnerTests/testCommand',
'-parallel-testing-enabled',
'NO',
'-test-timeouts-enabled',
'NO',
'-collect-test-diagnostics',
'never',
resolveRunnerMaxConcurrentDestinationsFlag(device),
'1',
'-destination-timeout',
String(RUNNER_DESTINATION_TIMEOUT_SECONDS),
'-xctestrun',
xctestrunPath,
'-destination',
resolveRunnerDestination(device),
],
{
allowFailure: true,
env: { ...process.env, AGENT_DEVICE_RUNNER_PORT: String(port) },
detached: true,
},
));
} catch (error) {
await simulatorSetRedirect?.release();
throw error;
}
child.stdout?.on('data', (chunk: string) => {
logChunk(chunk, options.logPath, options.traceLogPath, options.verbose);
});
child.stderr?.on('data', (chunk: string) => {
logChunk(chunk, options.logPath, options.traceLogPath, options.verbose);
});
const session: RunnerSession = {
sessionId: `${device.id}:${port}:${Date.now()}`,
device,
deviceId: device.id,
port,
xctestrunPath,
jsonPath,
testPromise,
child,
ready: false,
simulatorSetRedirect: simulatorSetRedirect ?? undefined,
};
runnerSessions.set(device.id, session);
return session;
});
}
async function cleanupStaleSimulatorRunnerBundles(device: DeviceInfo): Promise<void> {
if (device.kind !== 'simulator') {
return;
}
for (const bundleId of IOS_RUNNER_CONTAINER_BUNDLE_IDS) {
const result = await runCmd(
'xcrun',
buildSimctlArgsForDevice(device, ['uninstall', device.id, bundleId]),
{
allowFailure: true,
},
);
if (result.exitCode !== 0) {
const output = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
!output.includes('not installed') &&
!output.includes('found nothing') &&
!output.includes('no such file') &&
!output.includes('invalid device') &&
!output.includes('could not find')
) {
// Best-effort cleanup only; xcodebuild may still be able to install.
continue;
}
}
}
}
export function getRunnerSessionSnapshot(
deviceId: string,
): { sessionId: string; alive: boolean } | null {
const session = runnerSessions.get(deviceId);
if (!session) return null;
return {
sessionId: session.sessionId,
alive: isRunnerProcessAlive(session.child.pid),
};
}
export async function stopRunnerSession(session: RunnerSession): Promise<void> {
await withRunnerSessionLock(session.deviceId, async () => {
await stopRunnerSessionInternal(session.deviceId, session);
});
}
async function stopRunnerSessionInternal(
deviceId: string,
sessionOverride?: RunnerSession,
): Promise<void> {
const session = sessionOverride ?? runnerSessions.get(deviceId);
if (!session) return;
try {
await waitForRunner(
session.device,
session.port,
{
command: 'shutdown',
} as RunnerCommand,
undefined,
RUNNER_SHUTDOWN_TIMEOUT_MS,
);
} catch {
await killRunnerProcessTree(session.child.pid, 'SIGTERM');
}
try {
await Promise.race([
session.testPromise,
new Promise<void>((resolve) => setTimeout(resolve, RUNNER_STOP_WAIT_TIMEOUT_MS)),
]);
} catch {
// ignore
}
await killRunnerProcessTree(session.child.pid, 'SIGKILL');
cleanupTempFile(session.xctestrunPath);
cleanupTempFile(session.jsonPath);
await session.simulatorSetRedirect?.release();
if (runnerSessions.get(deviceId) === session) {
runnerSessions.delete(deviceId);
}
}
export async function stopIosRunnerSession(deviceId: string): Promise<void> {
await withRunnerSessionLock(deviceId, async () => {
await stopRunnerSessionInternal(deviceId);
});
}
export async function abortAllIosRunnerSessions(): Promise<void> {
const activeSessions = Array.from(runnerSessions.values());
const prepProcesses = Array.from(runnerPrepProcesses);
await Promise.allSettled(
activeSessions.map(async (session) => {
await killRunnerProcessTree(session.child.pid, 'SIGINT');
}),
);
await Promise.allSettled(
prepProcesses.map(async (child) => {
await killRunnerProcessTree(child.pid, 'SIGINT');
}),
);
await Promise.allSettled(
activeSessions.map(async (session) => {
await killRunnerProcessTree(session.child.pid, 'SIGTERM');
}),
);
await Promise.allSettled(
prepProcesses.map(async (child) => {
await killRunnerProcessTree(child.pid, 'SIGTERM');
}),
);
await Promise.allSettled(
activeSessions.map(async (session) => {
await killRunnerProcessTree(session.child.pid, 'SIGKILL');
}),
);
await Promise.allSettled(
prepProcesses.map(async (child) => {
await killRunnerProcessTree(child.pid, 'SIGKILL');
runnerPrepProcesses.delete(child);
}),
);
await Promise.allSettled(
activeSessions.map(async (session) => {
await session.simulatorSetRedirect?.release();
}),
);
}
export async function stopAllIosRunnerSessions(): Promise<void> {
await abortAllIosRunnerSessions();
const pending = Array.from(runnerSessions.keys());
await Promise.allSettled(
pending.map(async (deviceId) => {
await stopIosRunnerSession(deviceId);
}),
);
const prepProcesses = Array.from(runnerPrepProcesses);
await Promise.allSettled(
prepProcesses.map(async (child) => {
try {
await killRunnerProcessTree(child.pid, 'SIGTERM');
await killRunnerProcessTree(child.pid, 'SIGKILL');
} finally {
runnerPrepProcesses.delete(child);
}
}),
);
}
function isRunnerProcessAlive(pid: number | undefined): boolean {
if (!pid) return false;
return isProcessAlive(pid);
}
async function killRunnerProcessTree(
pid: number | undefined,
signal: 'SIGINT' | 'SIGTERM' | 'SIGKILL',
): Promise<void> {
if (!pid || pid <= 0) return;
try {
process.kill(-pid, signal);
} catch {
// ignore
}
try {
process.kill(pid, signal);
} catch {
// ignore
}
const pkillSignal = signal === 'SIGINT' ? 'INT' : signal === 'SIGTERM' ? 'TERM' : 'KILL';
try {
await runCmd('pkill', [`-${pkillSignal}`, '-P', String(pid)], { allowFailure: true });
} catch {
// ignore
}
}
function ensureBootedIfNeeded(device: DeviceInfo): Promise<void> {
if (device.kind !== 'simulator') {
return Promise.resolve();
}
return ensureBooted(device);
}
async function ensureBooted(device: DeviceInfo): Promise<void> {
await runCmd('xcrun', buildSimctlArgsForDevice(device, ['bootstatus', device.id, '-b']), {
timeoutMs: RUNNER_STARTUP_TIMEOUT_MS,
});
}
export function validateRunnerDevice(device: DeviceInfo): void {
if (device.platform !== 'ios' && device.platform !== 'macos') {
throw new AppError(
'UNSUPPORTED_PLATFORM',
`Unsupported platform for iOS runner: ${device.platform}`,
);
}
if (device.kind !== 'simulator' && device.kind !== 'device') {
throw new AppError(
'UNSUPPORTED_OPERATION',
`Unsupported iOS device kind for runner: ${device.kind}`,
);
}
}
export async function executeRunnerCommandWithSession(
device: DeviceInfo,
session: RunnerSession,
command: RunnerCommand,
logPath: string | undefined,
timeoutMs: number,
signal?: AbortSignal,
): Promise<Record<string, unknown>> {
const response = await waitForRunner(
device,
session.port,
command,
logPath,
timeoutMs,
session,
signal,
);
return await parseRunnerResponse(response, session, logPath);
}
export async function parseRunnerResponse(
response: Response,
session: RunnerSession,
logPath?: string,
): Promise<Record<string, unknown>> {
const text = await response.text();
let json: any = {};
try {
json = JSON.parse(text);
} catch {
throw new AppError('COMMAND_FAILED', 'Invalid runner response', { text });
}
if (!json.ok) {
const errorCode =
typeof json.error?.code === 'string' && json.error.code.trim().length > 0
? json.error.code
: 'COMMAND_FAILED';
throw new AppError(errorCode, json.error?.message ?? 'Runner error', {
runner: json,
xcodebuild: {
exitCode: 1,
stdout: '',
stderr: '',
},
logPath,
});
}
session.ready = true;
return json.data ?? {};
}