-
-
Notifications
You must be signed in to change notification settings - Fork 175
/
Copy pathcreate-chrome-docker-target.js
213 lines (190 loc) Β· 5.84 KB
/
create-chrome-docker-target.js
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
const debug = require('debug')('loki:chrome:docker');
const { execSync } = require('child_process');
const execa = require('execa');
const waitPort = require('wait-port');
const CDP = require('chrome-remote-interface');
const getRandomPort = require('find-free-port-sync');
const {
ChromeError,
ensureDependencyAvailable,
getAbsoluteURL,
getLocalIPAddress,
createStaticServer,
} = require('@loki/core');
const { createChromeTarget } = require('@loki/target-chrome-core');
const { getNetworkHost } = require('./get-network-host');
const getExecutor = (dockerWithSudo) => (dockerPath, args) => {
if (dockerWithSudo) {
return execa('sudo', [dockerPath, ...args]);
}
return execa(dockerPath, args);
};
function createChromeDockerTarget({
baseUrl = 'http://localhost:6006',
chromeDockerImage = 'yukinying/chrome-headless-browser-stable:118.0.5993.117',
chromeFlags = ['--headless', '--disable-gpu', '--hide-scrollbars'],
dockerNet = null,
dockerWithSudo = false,
chromeDockerWithoutSeccomp = false,
}) {
let debuggerPort;
let staticServer;
let staticServerPath;
let staticServerPort;
let dockerId;
let host;
let dockerUrl = getAbsoluteURL(baseUrl);
const isLocalFile = dockerUrl.indexOf('file:') === 0;
const dockerPath = 'docker';
const runArgs = ['run', '--rm', '-d', '-P'];
const execute = getExecutor(dockerWithSudo);
if (!chromeDockerWithoutSeccomp) {
runArgs.push('--security-opt=seccomp=unconfined');
}
runArgs.push('--add-host=host.docker.internal:host-gateway');
if (isLocalFile) {
const ip = 'host.docker.internal';
staticServerPort = getRandomPort();
staticServerPath = dockerUrl.substr('file:'.length);
dockerUrl = `http://${ip}:${staticServerPort}`;
} else if (dockerUrl.indexOf('http://localhost') === 0) {
const ip = getLocalIPAddress();
if (!ip) {
throw new Error(
'Unable to detect local IP address, try passing --host argument'
);
}
dockerUrl = dockerUrl.replace('localhost', ip);
}
async function getIsImageDownloaded(imageName) {
const { exitCode, stdout, stderr } = await execute(dockerPath, [
'images',
'-q',
imageName,
]);
if (exitCode !== 0) {
throw new Error(`Failed querying docker, ${stderr}`);
}
return stdout.trim().length !== 0;
}
async function ensureImageDownloaded() {
ensureDependencyAvailable('docker');
const isImageDownloaded = await getIsImageDownloaded(chromeDockerImage);
if (!isImageDownloaded) {
await execute(dockerPath, ['pull', chromeDockerImage]);
}
}
async function start() {
ensureDependencyAvailable('docker');
debuggerPort = getRandomPort();
if (isLocalFile) {
staticServer = createStaticServer(staticServerPath);
staticServer.listen(staticServerPort);
debug(`Starting static file server at ${dockerUrl}`);
}
const dockerArgs = runArgs.concat([
'--shm-size=1g',
'-p',
`${debuggerPort}:${debuggerPort}`,
]);
if (dockerNet) {
dockerArgs.push(`--net=${dockerNet}`);
}
dockerArgs.push(chromeDockerImage);
const args = dockerArgs
.concat([
'--disable-datasaver-prompt',
'--no-first-run',
'--disable-extensions',
'--remote-debugging-address=0.0.0.0',
`--remote-debugging-port=${debuggerPort}`,
])
.concat(chromeFlags);
debug(
`Launching chrome in docker with command "${dockerPath} ${args.join(
' '
)}"`
);
const { exitCode, stdout, stderr } = await execute(dockerPath, args);
if (exitCode === 0) {
dockerId = stdout;
const logs = execute(dockerPath, ['logs', dockerId, '--follow']);
const errorLogs = [];
logs.stderr.on('data', (chunk) => {
errorLogs.push(chunk);
});
host = await getNetworkHost(execute, dockerId);
try {
await waitPort({
host,
port: debuggerPort,
interval: 100,
timeout: 5000,
});
} catch (error) {
if (
error.message.startsWith('Timed out waiting for') &&
errorLogs.length !== 0
) {
throw new ChromeError(
`Chrome failed to start with ${
errorLogs.length === 1 ? 'error' : 'errors'
} ${errorLogs
.map((e) => `"${e.toString('utf8').trim()}"`)
.join(', ')}`
);
}
throw error;
} finally {
if (logs.exitCode === null && !logs.killed) {
logs.kill();
}
}
debug(`Docker started with id ${dockerId}`);
} else {
throw new Error(`Failed starting docker, ${stderr}`);
}
}
async function stop() {
if (dockerId) {
debug(`Killing chrome docker instance with id ${dockerId}`);
try {
await execute(dockerPath, ['kill', dockerId]);
} catch (e) {
if (e.toString().indexOf('No such container') === -1) {
throw e;
}
}
} else {
debug('No chrome docker instance to kill');
}
if (staticServer) {
staticServer.close();
}
}
async function createNewDebuggerInstance() {
debug(`Launching new tab with debugger at port ${host}:${debuggerPort}`);
const target = await CDP.New({ host, port: debuggerPort });
debug(`Launched with target id ${target.id}`);
const client = await CDP({ host, port: debuggerPort, target });
client.close = () => {
debug('Closing tab');
return CDP.Close({ host, port: debuggerPort, id: target.id });
};
return client;
}
process.on('SIGINT', () => {
if (dockerId) {
const maybeSudo = dockerWithSudo ? 'sudo ' : '';
execSync(`${maybeSudo}${dockerPath} kill ${dockerId}`);
}
});
return createChromeTarget(
start,
stop,
createNewDebuggerInstance,
dockerUrl,
ensureImageDownloaded
);
}
module.exports = { createChromeDockerTarget };