-
Notifications
You must be signed in to change notification settings - Fork 8.1k
/
index.ts
242 lines (215 loc) · 7.54 KB
/
index.ts
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
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
import fs from 'fs';
import os from 'os';
import path from 'path';
// @ts-ignore
import puppeteer from 'puppeteer-core';
import rimraf from 'rimraf';
import * as Rx from 'rxjs';
import { map, share, mergeMap, filter, partition } from 'rxjs/operators';
import { InnerSubscriber } from 'rxjs/internal/InnerSubscriber';
import { HeadlessChromiumDriver } from '../driver';
import { args, IArgOptions } from './args';
import { safeChildProcess } from '../../safe_child_process';
import { getChromeLogLocation } from '../paths';
import { Logger } from '../../../../types';
type binaryPath = string;
type queueTimeout = number;
interface IBrowserConfig {
[key: string]: any;
}
const compactWhitespace = (str: string) => {
return str.replace(/\s+/, ' ');
};
export class HeadlessChromiumDriverFactory {
private binaryPath: binaryPath;
private logger: Logger;
private browserConfig: IBrowserConfig;
private queueTimeout: queueTimeout;
constructor(
binaryPath: binaryPath,
logger: any,
browserConfig: IBrowserConfig,
queueTimeout: queueTimeout
) {
this.binaryPath = binaryPath;
this.logger = logger.clone(['chromium-driver-factory']);
this.browserConfig = browserConfig;
this.queueTimeout = queueTimeout;
}
type = 'chromium';
test(
{ viewport, browserTimezone }: { viewport: IArgOptions['viewport']; browserTimezone: string },
logger: any
) {
const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'chromium-'));
const chromiumArgs = args({
userDataDir,
viewport,
verboseLogging: true,
disableSandbox: this.browserConfig.disableSandbox,
proxyConfig: this.browserConfig.proxy,
});
return puppeteer
.launch({
userDataDir,
executablePath: this.binaryPath,
ignoreHTTPSErrors: true,
args: chromiumArgs,
env: {
TZ: browserTimezone,
},
})
.catch((error: Error) => {
logger.warning(
`The Reporting plugin encountered issues launching Chromium in a self-test. You may have trouble generating reports: [${error}]`
);
logger.warning(`See Chromium's log output at "${getChromeLogLocation(this.binaryPath)}"`);
return null;
});
}
create({
viewport,
browserTimezone,
}: {
viewport: IArgOptions['viewport'];
browserTimezone: string;
}): Rx.Observable<any> {
return Rx.Observable.create(async (observer: InnerSubscriber<any, any>) => {
const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'chromium-'));
const chromiumArgs = args({
userDataDir,
viewport,
verboseLogging: this.logger.isVerbose,
disableSandbox: this.browserConfig.disableSandbox,
proxyConfig: this.browserConfig.proxy,
});
let browser: puppeteer.Browser;
let page: puppeteer.Page;
try {
browser = await puppeteer.launch({
userDataDir,
executablePath: this.binaryPath,
ignoreHTTPSErrors: true,
args: chromiumArgs,
env: {
TZ: browserTimezone,
},
});
page = await browser.newPage();
// All navigation/waitFor methods default to 30 seconds,
// which can cause the job to fail even if we bump timeouts in
// the config. Help alleviate errors like
// "TimeoutError: waiting for selector ".application" failed: timeout 30000ms exceeded"
// @ts-ignore outdated typedefs for puppteer
page.setDefaultTimeout(this.queueTimeout);
} catch (err) {
observer.error(new Error(`Error spawning Chromium browser: [${err}]`));
throw err;
}
safeChildProcess(
{
async kill() {
await browser.close();
},
},
observer
);
// Register with a few useful puppeteer event handlers:
// https://pptr.dev/#?product=Puppeteer&version=v1.10.0&show=api-event-error
// https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#class-page
const stderr$ = Rx.fromEvent(page as NodeJS.EventEmitter, 'console').pipe(
filter((line: any) => line._type === 'error'),
map((line: any) => line._text),
share()
);
const [consoleMessage$, message$] = partition(
(msg: string) => !!msg.match(/\[\d+\/\d+.\d+:\w+:CONSOLE\(\d+\)\]/)
)(stderr$);
const driver$ = Rx.of(
new HeadlessChromiumDriver(page, {
logger: this.logger,
})
);
const processError$ = Rx.fromEvent(page, 'error').pipe(
mergeMap(err => Rx.throwError(new Error(`Unable to spawn Chromium: [${err}]`)))
);
const processPageError$ = Rx.fromEvent(page, 'pageerror').pipe(
mergeMap(err => Rx.throwError(new Error(`Uncaught exception within the page: [${err}]`)))
);
const processRequestFailed$ = Rx.fromEvent(page, 'requestfailed').pipe(
mergeMap((req: any) => {
const failure = req.failure && req.failure();
if (failure) {
return Rx.throwError(
new Error(`Request to [${req.url()}] failed! [${failure.errorText}]`)
);
}
return Rx.throwError(new Error(`Unknown failure! [${JSON.stringify(req)}]`));
})
);
const processExit$ = Rx.fromEvent(browser, 'disconnected').pipe(
mergeMap(code =>
Rx.throwError(new Error(`Chromium exited with: [${JSON.stringify({ code })}]`))
)
);
const nssError$ = message$.pipe(
filter((line: string) => line.includes('error while loading shared libraries: libnss3.so')),
mergeMap(() => Rx.throwError(new Error(`You must install nss for Reporting to work`)))
);
const fontError$ = message$.pipe(
filter((line: string) =>
line.includes('Check failed: InitDefaultFont(). Could not find the default font')
),
mergeMap(() =>
Rx.throwError(new Error('You must install freetype and ttf-font for Reporting to work'))
)
);
const noUsableSandbox$ = message$.pipe(
filter((line: string) => line.includes('No usable sandbox! Update your kernel')),
mergeMap(() =>
Rx.throwError(
new Error(
compactWhitespace(`
Unable to use Chromium sandbox. This can be disabled at your own risk with
'xpack.reporting.capture.browser.chromium.disableSandbox'
`)
)
)
)
);
const exit$ = Rx.merge(
processError$,
processPageError$,
processRequestFailed$,
processExit$,
nssError$,
fontError$,
noUsableSandbox$
);
observer.next({
driver$,
consoleMessage$,
message$,
exit$,
});
// unsubscribe logic makes a best-effort attempt to delete the user data directory used by chromium
observer.add(() => {
this.logger.debug(`deleting chromium user data directory at [${userDataDir}]`);
// the unsubscribe function isn't `async` so we're going to make our best effort at
// deleting the userDataDir and if it fails log an error.
rimraf(userDataDir, err => {
if (err) {
return this.logger.error(
`error deleting user data directory at [${userDataDir}]: [${err}]`
);
}
});
});
});
}
}