-
-
Notifications
You must be signed in to change notification settings - Fork 71
/
crawler.js
731 lines (564 loc) · 20.3 KB
/
crawler.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
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
const child_process = require("child_process");
const path = require("path");
const fs = require("fs");
const fsp = require("fs/promises");
// to ignore HTTPS error for HEAD check
const HTTPS_AGENT = require("https").Agent({
rejectUnauthorized: false,
});
const HTTP_AGENT = require("http").Agent();
const fetch = require("node-fetch");
const puppeteer = require("puppeteer-core");
const { Cluster } = require("puppeteer-cluster");
const AbortController = require("abort-controller");
const Sitemapper = require("sitemapper");
const { v4: uuidv4 } = require("uuid");
const Redis = require("ioredis");
const warcio = require("warcio");
const behaviors = fs.readFileSync("/app/node_modules/browsertrix-behaviors/dist/behaviors.js", "utf-8");
const TextExtract = require("./util/textextract");
const { ScreenCaster } = require("./util/screencaster");
const { parseArgs } = require("./util/argParser");
const { getBrowserExe, loadProfile } = require("./util/browser");
const { BEHAVIOR_LOG_FUNC, HTML_TYPES, DEFAULT_SELECTORS } = require("./util/constants");
const { BlockRules } = require("./util/blockrules");
// ============================================================================
class Crawler {
constructor() {
this.headers = {};
this.seenList = new Set();
this.emulateDevice = null;
// links crawled counter
this.numLinks = 0;
// pages file
this.pagesFH = null;
// was the limit hit?
this.limitHit = false;
this.userAgent = "";
this.params = parseArgs();
this.debugLogging = this.params.logging.includes("debug");
this.profileDir = loadProfile(this.params.profile);
if (this.params.profile) {
this.statusLog("With Browser Profile: " + this.params.profile);
}
this.emulateDevice = this.params.emulateDevice;
this.debugLog("Seeds", this.params.scopedSeeds);
this.captureBasePrefix = `http://${process.env.PROXY_HOST}:${process.env.PROXY_PORT}/${this.params.collection}/record`;
this.capturePrefix = this.captureBasePrefix + "/id_/";
this.gotoOpts = {
waitUntil: this.params.waitUntil,
timeout: this.params.timeout
};
// root collections dir
this.collDir = path.join(this.params.cwd, "collections", this.params.collection);
// pages directory
this.pagesDir = path.join(this.collDir, "pages");
// pages file
this.pagesFile = path.join(this.pagesDir, "pages.jsonl");
this.blockRules = null;
}
statusLog(...args) {
console.log(...args);
}
debugLog(...args) {
if (this.debugLogging) {
console.log(...args);
}
}
configureUA() {
// override userAgent
if (this.params.userAgent) {
if (this.emulateDevice) {
this.emulateDevice.userAgent = this.params.userAgent;
}
this.userAgent = this.params.userAgent;
return;
}
this.browserExe = getBrowserExe();
// if device set, it overrides the default Chrome UA
if (this.emulateDevice) {
this.userAgent = this.emulateDevice.userAgent;
} else {
let version = process.env.BROWSER_VERSION;
try {
version = child_process.execFileSync(this.browserExe, ["--product-version"], {encoding: "utf8"}).trim();
} catch(e) {
console.error(e);
}
this.userAgent = `Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${version} Safari/537.36`;
}
// suffix to append to default userAgent
if (this.params.userAgentSuffix) {
this.userAgent += " " + this.params.userAgentSuffix;
if (this.emulateDevice) {
this.emulateDevice.userAgent += " " + this.params.userAgentSuffix;
}
}
}
bootstrap() {
let opts = {};
if (this.params.logging.includes("pywb")) {
opts = {stdio: "inherit", cwd: this.params.cwd};
}
else{
opts = {stdio: "ignore", cwd: this.params.cwd};
}
this.configureUA();
this.headers = {"User-Agent": this.userAgent};
const subprocesses = [];
subprocesses.push(child_process.spawn("redis-server", {...opts, cwd: "/tmp/"}));
child_process.spawnSync("wb-manager", ["init", this.params.collection], opts);
opts.env = {...process.env, COLL: this.params.collection, ROLLOVER_SIZE: this.params.rolloverSize};
subprocesses.push(child_process.spawn("uwsgi", [path.join(__dirname, "uwsgi.ini")], opts));
process.on("exit", () => {
for (const proc of subprocesses) {
proc.kill();
}
});
if (!this.params.headless) {
child_process.spawn("Xvfb", [
process.env.DISPLAY,
"-listen",
"tcp",
"-screen",
"0",
process.env.GEOMETRY,
"-ac",
"+extension",
"RANDR"
]);
}
}
get chromeArgs() {
// Chrome Flags, including proxy server
return [
"--no-xshm", // needed for Chrome >80 (check if puppeteer adds automatically)
`--proxy-server=http://${process.env.PROXY_HOST}:${process.env.PROXY_PORT}`,
"--no-sandbox",
"--disable-background-media-suspend",
"--autoplay-policy=no-user-gesture-required",
"--disable-features=IsolateOrigins,site-per-process",
"--disable-popup-blocking",
"--disable-backgrounding-occluded-windows",
];
}
get puppeteerArgs() {
// Puppeter Options
return {
headless: this.params.headless,
executablePath: this.browserExe,
ignoreHTTPSErrors: true,
args: this.chromeArgs,
userDataDir: this.profileDir,
defaultViewport: null,
};
}
async run() {
await fsp.mkdir(this.params.cwd, {recursive: true});
this.bootstrap();
try {
await this.crawl();
process.exit(0);
} catch(e) {
console.error("Crawl failed");
console.error(e);
process.exit(1);
}
}
_behaviorLog({data, type}) {
switch (type) {
case "info":
console.log(JSON.stringify(data));
break;
case "debug":
default:
if (this.params.behaviorsLogDebug) {
console.log("behavior debug: " + JSON.stringify(data));
}
}
}
async crawlPage({page, data}) {
try {
if (this.screencaster) {
await this.screencaster.newTarget(page.target());
}
if (this.emulateDevice) {
await page.emulate(this.emulateDevice);
}
if (this.params.profile) {
await page._client.send("Network.setBypassServiceWorker", {bypass: true});
}
if (this.params.behaviorOpts && !page.__bx_inited) {
await page.exposeFunction(BEHAVIOR_LOG_FUNC, (logdata) => this._behaviorLog(logdata));
await page.evaluateOnNewDocument(behaviors + `;\nself.__bx_behaviors.init(${this.params.behaviorOpts});`);
page.__bx_inited = true;
}
// run custom driver here
await this.driver({page, data, crawler: this});
const title = await page.title();
let text = "";
if (this.params.text) {
const client = await page.target().createCDPSession();
const result = await client.send("DOM.getDocument", {"depth": -1, "pierce": true});
text = await new TextExtract(result).parseTextFromDom();
}
await this.writePage(data.url, title, this.params.text, text);
if (this.params.behaviorOpts) {
await Promise.allSettled(page.frames().map(frame => frame.evaluate("self.__bx_behaviors.run();")));
}
await this.writeStats();
if (this.screencaster) {
await this.screencaster.endTarget(page.target());
}
} catch (e) {
console.warn(e);
}
}
async createWARCInfo(filename) {
const warcVersion = "WARC/1.0";
const type = "warcinfo";
const packageFileJSON = JSON.parse(await fsp.readFile("../app/package.json"));
const warcioPackageJSON = JSON.parse(await fsp.readFile("/app/node_modules/warcio/package.json"));
const pywbVersion = child_process.execSync("pywb -V", {encoding: "utf8"}).trim().split(" ")[1];
const info = {
"software": `Browsertrix-Crawler ${packageFileJSON.version} (with warcio.js ${warcioPackageJSON.version} pywb ${pywbVersion})`,
"format": "WARC File Format 1.0"
};
const warcInfo = {...info, ...this.params.warcInfo, };
const record = await warcio.WARCRecord.createWARCInfo({filename, type, warcVersion}, warcInfo);
const buffer = await warcio.WARCSerializer.serialize(record, {gzip: true});
return buffer;
}
async getFileSize(filename) {
const stats = await fsp.stat(filename);
return stats.size;
}
async crawl() {
try {
this.driver = require(this.params.driver);
} catch(e) {
console.warn(e);
return;
}
// Puppeteer Cluster init and options
this.cluster = await Cluster.launch({
concurrency: this.params.newContext,
maxConcurrency: this.params.workers,
skipDuplicateUrls: true,
timeout: this.params.timeout * 2,
puppeteerOptions: this.puppeteerArgs,
puppeteer,
monitor: this.params.logging.includes("stats")
});
this.cluster.task((opts) => this.crawlPage(opts));
await this.initPages();
if (this.params.blockRules && this.params.blockRules.length) {
this.blockRules = new BlockRules(this.params.blockRules, this.captureBasePrefix, this.params.blockMessage, (text) => this.debugLog(text));
}
if (this.params.screencastPort) {
this.screencaster = new ScreenCaster(this.cluster, this.params.screencastPort);
this.debugLog(`Screencast Server started on: ${this.params.screencastPort}`);
}
for (let i = 0; i < this.params.scopedSeeds.length; i++) {
const seed = this.params.scopedSeeds[i];
this.queueUrl(i, seed.url, 0);
if (seed.sitemap) {
await this.parseSitemap(seed.sitemap, i);
}
}
await this.cluster.idle();
await this.cluster.close();
this.writeStats();
if (this.pagesFH) {
await this.pagesFH.sync();
await this.pagesFH.close();
}
// extra wait for all resources to land into WARCs
await this.awaitPendingClear();
if (this.params.combineWARC) {
await this.combineWARC();
}
if (this.params.generateCDX) {
this.statusLog("Generating CDX");
child_process.spawnSync("wb-manager", ["reindex", this.params.collection], {stdio: "inherit", cwd: this.params.cwd});
}
if (this.params.generateWACZ) {
this.statusLog("Generating WACZ");
const archiveDir = path.join(this.collDir, "archive");
// Get a list of the warcs inside
const warcFileList = await fsp.readdir(archiveDir);
// Build the argument list to pass to the wacz create command
const waczFilename = this.params.collection.concat(".wacz");
const waczPath = path.join(this.collDir, waczFilename);
const argument_list = ["create", "-o", waczPath, "--pages", this.pagesFile, "-f"];
warcFileList.forEach((val, index) => argument_list.push(path.join(archiveDir, val))); // eslint-disable-line no-unused-vars
// Run the wacz create command
child_process.spawnSync("wacz" , argument_list, {stdio: "inherit"});
this.debugLog(`WACZ successfully generated and saved to: ${waczPath}`);
}
}
async writeStats() {
if (this.params.statsFilename) {
const total = this.cluster.allTargetCount;
const workersRunning = this.cluster.workersBusy.length;
const numCrawled = total - this.cluster.jobQueue.size() - workersRunning;
const limit = {max: this.params.limit || 0, hit: this.limitHit};
const stats = {numCrawled, workersRunning, total, limit};
try {
await fsp.writeFile(this.params.statsFilename, JSON.stringify(stats, null, 2));
} catch (err) {
console.warn("Stats output failed", err);
}
}
}
async loadPage(page, urlData, selectorOptsList = DEFAULT_SELECTORS) {
const {url, seedId, depth} = urlData;
if (!await this.isHTML(url)) {
try {
await this.directFetchCapture(url);
return;
} catch (e) {
// ignore failed direct fetch attempt, do browser-based capture
}
}
if (this.blockRules) {
await this.blockRules.initPage(page);
}
try {
await page.goto(url, this.gotoOpts);
} catch (e) {
console.warn(`Load timeout for ${url}`, e);
}
const seed = this.params.scopedSeeds[seedId];
// skip extraction if at max depth
if (seed.isAtMaxDepth(depth) || !selectorOptsList) {
return;
}
for (const opts of selectorOptsList) {
const links = await this.extractLinks(page, opts);
this.queueInScopeUrls(seedId, links, depth);
}
}
async extractLinks(page, {selector = "a[href]", extract = "href", isAttribute = false} = {}) {
const results = [];
const loadProp = (selector, extract) => {
return [...document.querySelectorAll(selector)].map(elem => elem[extract]);
};
const loadAttr = (selector, extract) => {
return [...document.querySelectorAll(selector)].map(elem => elem.getAttribute(extract));
};
const loadFunc = isAttribute ? loadAttr : loadProp;
try {
const linkResults = await Promise.allSettled(page.frames().map(frame => frame.evaluate(loadFunc, selector, extract)));
if (linkResults) {
for (const linkResult of linkResults) {
if (!linkResult.value) continue;
for (const link of linkResult.value) {
results.push(link);
}
}
}
} catch (e) {
console.warn("Link Extraction failed", e);
}
return results;
}
queueInScopeUrls(seedId, urls, depth) {
try {
depth += 1;
const seed = this.params.scopedSeeds[seedId];
for (const url of urls) {
const captureUrl = seed.isIncluded(url, depth);
if (captureUrl) {
this.queueUrl(seedId, captureUrl, depth);
}
}
} catch (e) {
console.error("Queuing Error: ", e);
}
}
queueUrl(seedId, url, depth) {
if (this.seenList.has(url)) {
return false;
}
this.seenList.add(url);
if (this.numLinks >= this.params.limit && this.params.limit > 0) {
this.limitHit = true;
return false;
}
this.numLinks++;
this.cluster.queue({url, seedId, depth});
return true;
}
async initPages() {
try {
let createNew = false;
// create pages dir if doesn't exist and write pages.jsonl header
if (fs.existsSync(this.pagesDir) != true){
await fsp.mkdir(this.pagesDir);
createNew = true;
}
this.pagesFH = await fsp.open(this.pagesFile, "a");
if (createNew) {
const header = {"format": "json-pages-1.0", "id": "pages", "title": "All Pages"};
if (this.params.text) {
header["hasText"] = true;
this.statusLog("Text Extraction: Enabled");
} else {
header["hasText"] = false;
this.statusLog("Text Extraction: Disabled");
}
const header_formatted = JSON.stringify(header).concat("\n");
await this.pagesFH.writeFile(header_formatted);
}
} catch(err) {
console.error("pages/pages.jsonl creation failed", err);
}
}
async writePage(url, title, text, text_content){
const id = uuidv4();
const row = {"id": id, "url": url, "title": title};
if (text == true){
row["text"] = text_content;
}
const processedRow = JSON.stringify(row).concat("\n");
try {
this.pagesFH.writeFile(processedRow);
}
catch (err) {
console.warn("pages/pages.jsonl append failed", err);
}
}
resolveAgent(urlParsed) {
return urlParsed.protocol === "https:" ? HTTPS_AGENT : HTTP_AGENT;
}
async isHTML(url) {
try {
const resp = await fetch(url, {
method: "HEAD",
headers: this.headers,
agent: this.resolveAgent
});
if (resp.status >= 400) {
this.debugLog(`Skipping HEAD check ${url}, invalid status ${resp.status}`);
return true;
}
const contentType = resp.headers.get("Content-Type");
// just load if no content-type
if (!contentType) {
return true;
}
const mime = contentType.split(";")[0];
if (HTML_TYPES.includes(mime)) {
return true;
}
return false;
} catch(e) {
// can't confirm not html, so try in browser
return true;
}
}
async directFetchCapture(url) {
//console.log(`Direct capture: ${this.capturePrefix}${url}`);
const abort = new AbortController();
const signal = abort.signal;
await fetch(this.capturePrefix + url, {signal, headers: this.headers});
abort.abort();
}
async awaitPendingClear() {
this.statusLog("Waiting to ensure pending data is written to WARCs...");
const redis = new Redis("redis://localhost/0");
while (true) {
const res = await redis.get(`pywb:${this.params.collection}:pending`);
if (res === "0" || !res) {
break;
}
this.debugLog(`Still waiting for ${res} pending requests to finish...`);
await this.sleep(1000);
}
}
sleep(time) {
return new Promise(resolve => setTimeout(resolve, time));
}
async parseSitemap(url, seedId) {
const sitemapper = new Sitemapper({
url,
timeout: 15000,
requestHeaders: this.headers
});
try {
const { sites } = await sitemapper.fetch();
this.queueInScopeUrls(seedId, sites, 0);
} catch(e) {
console.warn(e);
}
}
async combineWARC() {
this.statusLog("Generating Combined WARCs");
// Get the list of created Warcs
const warcLists = await fsp.readdir(path.join(this.collDir, "archive"));
this.debugLog(`Combining ${warcLists.length} WARCs...`);
const fileSizeObjects = []; // Used to sort the created warc by fileSize
// Go through a list of the created works and create an array sorted by their filesize with the largest file first.
for (let i = 0; i < warcLists.length; i++) {
let fileName = path.join(this.collDir, "archive", warcLists[i]);
let fileSize = await this.getFileSize(fileName);
fileSizeObjects.push({"fileSize": fileSize, "fileName": fileName});
fileSizeObjects.sort(function(a, b){
return b.fileSize - a.fileSize;
});
}
const generatedCombinedWarcs = [];
// Used to name combined warcs, default to -1 for first increment
let combinedWarcNumber = -1;
// write combine WARC to collection root
let combinedWarcFullPath = "";
// fileHandler
let fh = null;
// Iterate through the sorted file size array.
for (let j = 0; j < fileSizeObjects.length; j++) {
// if need to rollover to new warc
let doRollover = false;
// set to true for first warc
if (combinedWarcNumber < 0) {
doRollover = true;
} else {
// Check the size of the existing combined warc.
const currentCombinedWarcSize = await this.getFileSize(combinedWarcFullPath);
// If adding the current warc to the existing combined file creates a file smaller than the rollover size add the data to the combinedWarc
const proposedWarcSize = fileSizeObjects[j].fileSize + currentCombinedWarcSize;
doRollover = (proposedWarcSize >= this.params.rolloverSize);
}
if (doRollover) {
// If adding the current warc to the existing combined file creates a file larger than the rollover size do the following:
// 1. increment the combinedWarcNumber
// 2. create the name of the new combinedWarcFile
// 3. Write the header out to the new file
// 4. Write out the current warc data to the combinedFile
combinedWarcNumber = combinedWarcNumber + 1;
const combinedWarcName = `${this.params.collection}_${combinedWarcNumber}.warc.gz`;
// write combined warcs to root collection dir as they're output of a collection (like wacz)
combinedWarcFullPath = path.join(this.collDir, combinedWarcName);
if (fh) {
fh.end();
}
fh = fs.createWriteStream(combinedWarcFullPath, {flags: "a"});
generatedCombinedWarcs.push(combinedWarcName);
const warcBuffer = await this.createWARCInfo(combinedWarcName);
fh.write(warcBuffer);
}
this.debugLog(`Appending WARC ${fileSizeObjects[j].fileName}`);
const reader = fs.createReadStream(fileSizeObjects[j].fileName);
const p = new Promise((resolve) => {
reader.on("end", () => resolve());
});
reader.pipe(fh, {end: false});
await p;
}
if (fh) {
await fh.end();
}
this.debugLog(`Combined WARCs saved as: ${generatedCombinedWarcs}`);
}
}
module.exports.Crawler = Crawler;