forked from apache/nutch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDeduplicationJob.java
More file actions
422 lines (373 loc) · 15.3 KB
/
Copy pathDeduplicationJob.java
File metadata and controls
422 lines (373 loc) · 15.3 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
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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nutch.crawl;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.invoke.MethodHandles;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Counter;
import org.apache.hadoop.mapreduce.CounterGroup;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.nutch.metadata.Nutch;
import org.apache.nutch.metrics.NutchMetrics;
import org.apache.nutch.util.NutchConfiguration;
import org.apache.nutch.util.NutchJob;
import org.apache.nutch.util.NutchTool;
import org.apache.nutch.util.URLUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Generic deduplicator which groups fetched URLs with the same digest and marks
* all of them as duplicate except the one with the highest score (based on the
* score in the crawldb, which is not necessarily the same as the score
* indexed). If two (or more) documents have the same score, then the document
* with the latest timestamp is kept. If the documents have the same timestamp
* then the one with the shortest URL is kept. The documents marked as duplicate
* can then be deleted with the command CleaningJob.
*/
public class DeduplicationJob extends NutchTool implements Tool {
private static final Logger LOG = LoggerFactory
.getLogger(MethodHandles.lookup().lookupClass());
protected final static Text urlKey = new Text("_URLTEMPKEY_");
protected final static String DEDUPLICATION_GROUP_MODE = "deduplication.group.mode";
protected final static String DEDUPLICATION_COMPARE_ORDER = "deduplication.compare.order";
protected final static String UTF_8 = StandardCharsets.UTF_8.toString();
public static class DBFilter extends
Mapper<Text, CrawlDatum, BytesWritable, CrawlDatum> {
private String groupMode;
@Override
public void setup(Mapper<Text, CrawlDatum, BytesWritable, CrawlDatum>.Context context) {
Configuration conf = context.getConfiguration();
groupMode = conf.get(DEDUPLICATION_GROUP_MODE);
}
@Override
public void map(Text key, CrawlDatum value, Context context)
throws IOException, InterruptedException {
if (value.getStatus() == CrawlDatum.STATUS_DB_FETCHED
|| value.getStatus() == CrawlDatum.STATUS_DB_NOTMODIFIED) {
// || value.getStatus() ==CrawlDatum.STATUS_DB_GONE){
byte[] signature = value.getSignature();
if (signature == null)
return;
String url = key.toString();
BytesWritable sig = null;
byte[] data;
switch (groupMode) {
case "none":
sig = new BytesWritable(signature);
break;
case "host":
byte[] host = URLUtil.getHost(url).getBytes();
data = new byte[signature.length + host.length];
System.arraycopy(signature, 0, data, 0, signature.length);
System.arraycopy(host, 0, data, signature.length, host.length);
sig = new BytesWritable(data);
break;
case "domain":
byte[] domain = URLUtil.getDomainName(url).getBytes();
data = new byte[signature.length + domain.length];
System.arraycopy(signature, 0, data, 0, signature.length);
System.arraycopy(domain, 0, data, signature.length, domain.length);
sig = new BytesWritable(data);
break;
}
// add the URL as a temporary MD
value.getMetaData().put(urlKey, key);
// reduce on the signature optionally grouped on host or domain or not at all
context.write(sig, value);
}
}
}
public static class DedupReducer<K extends Writable>
extends Reducer<K, CrawlDatum, Text, CrawlDatum> {
protected String[] compareOrder;
// Cached counter reference for performance
private Counter documentsMarkedDuplicateCounter;
@Override
public void setup(
Reducer<K, CrawlDatum, Text, CrawlDatum>.Context context) {
Configuration conf = context.getConfiguration();
compareOrder = conf.get(DEDUPLICATION_COMPARE_ORDER).split(",");
// Initialize cached counter reference
initCounters(context);
}
/**
* Initialize cached counter references to avoid repeated lookups in hot paths.
*/
private void initCounters(Context context) {
documentsMarkedDuplicateCounter = context.getCounter(
NutchMetrics.GROUP_DEDUP, NutchMetrics.DEDUP_DOCUMENTS_MARKED_DUPLICATE_TOTAL);
}
protected void writeOutAsDuplicate(CrawlDatum datum,
Context context)
throws IOException, InterruptedException {
datum.setStatus(CrawlDatum.STATUS_DB_DUPLICATE);
Text key = (Text) datum.getMetaData().remove(urlKey);
documentsMarkedDuplicateCounter.increment(1);
context.write(key, datum);
}
@Override
public void reduce(K key, Iterable<CrawlDatum> values, Context context)
throws IOException, InterruptedException {
CrawlDatum existingDoc = null;
for (CrawlDatum newDoc : values) {
if (existingDoc == null) {
existingDoc = new CrawlDatum();
existingDoc.set(newDoc);
continue;
}
CrawlDatum duplicate = getDuplicate(existingDoc, newDoc);
if (duplicate != null) {
writeOutAsDuplicate(duplicate, context);
if (duplicate == existingDoc) {
// keep new
existingDoc.set(newDoc);
}
}
}
}
protected CrawlDatum getDuplicate(CrawlDatum existingDoc, CrawlDatum newDoc) {
for (int i = 0; i < compareOrder.length; i++) {
switch (compareOrder[i]) {
case "score":
// compare based on score
if (existingDoc.getScore() < newDoc.getScore()) {
return existingDoc;
} else if (existingDoc.getScore() > newDoc.getScore()) {
// mark new one as duplicate
return newDoc;
}
break;
case "fetchTime":
// same score? delete the one which is oldest
if (existingDoc.getFetchTime() > newDoc.getFetchTime()) {
// mark new one as duplicate
return newDoc;
} else if (existingDoc.getFetchTime() < newDoc.getFetchTime()) {
// mark existing one as duplicate
return existingDoc;
}
break;
case "httpsOverHttp":
// prefer https:// over http:// if URLs are identical except for the
// protocol
String url1 = existingDoc.getMetaData().get(urlKey).toString();
String url2 = newDoc.getMetaData().get(urlKey).toString();
if (url1.startsWith("https://") && url2.startsWith("http://")
&& url1.substring(8).equals(url2.substring(7))) {
// existingDoc with https://, mark newDoc as duplicate
return newDoc;
} else if (url2.startsWith("https://") && url1.startsWith("http://")
&& url2.substring(8).equals(url1.substring(7))) {
// newDoc with https://, mark existingDoc as duplicate
return existingDoc;
}
break;
case "urlLength":
// keep the one which has the shortest URL
// normalized by decoding percent-encoded sequences
String urlExisting = existingDoc.getMetaData().get(urlKey).toString();
String urlnewDoc = newDoc.getMetaData().get(urlKey).toString();
try {
urlExisting = URLDecoder.decode(urlExisting, UTF_8);
} catch (UnsupportedEncodingException | IllegalArgumentException e) {
LOG.error("Error decoding: {}", urlExisting, e);
// use the encoded URL
}
try {
urlnewDoc = URLDecoder.decode(urlnewDoc, UTF_8);
} catch (UnsupportedEncodingException | IllegalArgumentException e) {
LOG.error("Error decoding: {}", urlnewDoc, e);
// use the encoded URL
}
if (urlExisting.length() < urlnewDoc.length()) {
// mark new one as duplicate
return newDoc;
} else if (urlExisting.length() > urlnewDoc.length()) {
// mark existing one as duplicate
return existingDoc;
}
break;
}
}
return null; // no decision possible
}
}
/** Combine multiple new entries for a url. */
public static class StatusUpdateReducer extends
Reducer<Text, CrawlDatum, Text, CrawlDatum> {
@Override
public void setup(Reducer<Text, CrawlDatum, Text, CrawlDatum>.Context context) {
}
private CrawlDatum old = new CrawlDatum();
private CrawlDatum duplicate = new CrawlDatum();
@Override
public void reduce(Text key, Iterable<CrawlDatum> values,
Context context)
throws IOException, InterruptedException {
boolean duplicateSet = false;
for (CrawlDatum val : values) {
if (val.getStatus() == CrawlDatum.STATUS_DB_DUPLICATE) {
duplicate.set(val);
duplicateSet = true;
} else {
old.set(val);
}
}
// keep the duplicate if there is one
if (duplicateSet) {
context.write(key, duplicate);
return;
}
// no duplicate? keep old one then
context.write(key, old);
}
}
@Override
public int run(String[] args) throws IOException {
if (args.length < 1) {
System.err.println("Usage: DeduplicationJob <crawldb> [-group <none|host|domain>] [-compareOrder <score>,<fetchTime>,<httpsOverHttp>,<urlLength>]");
return 1;
}
String group = "none";
Path crawlDb = new Path(args[0]);
String compareOrder = "score,fetchTime,urlLength";
for (int i = 1; i < args.length; i++) {
if (args[i].equals("-group"))
group = args[++i];
if (args[i].equals("-compareOrder")) {
compareOrder = args[++i];
if (compareOrder.indexOf("score") == -1 ||
compareOrder.indexOf("fetchTime") == -1 ||
compareOrder.indexOf("urlLength") == -1) {
System.err.println("DeduplicationJob: compareOrder must contain score, fetchTime and urlLength.");
return 1;
}
}
}
StopWatch stopWatch = new StopWatch();
stopWatch.start();
LOG.info("DeduplicationJob: starting");
Path tempDir = new Path(crawlDb, "dedup-temp-"
+ Integer.toString(new Random().nextInt(Integer.MAX_VALUE)));
Job job = Job.getInstance(getConf(), "Nutch DeduplicationJob: " + crawlDb);
Configuration conf = job.getConfiguration();
conf.set(DEDUPLICATION_GROUP_MODE, group);
conf.set(DEDUPLICATION_COMPARE_ORDER, compareOrder);
job.setJarByClass(DeduplicationJob.class);
FileInputFormat.addInputPath(job, new Path(crawlDb, CrawlDb.CURRENT_NAME));
job.setInputFormatClass(SequenceFileInputFormat.class);
FileOutputFormat.setOutputPath(job, tempDir);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
job.setMapOutputKeyClass(BytesWritable.class);
job.setMapOutputValueClass(CrawlDatum.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(CrawlDatum.class);
job.setMapperClass(DBFilter.class);
job.setReducerClass(DedupReducer.class);
FileSystem fs = tempDir.getFileSystem(getConf());
try {
boolean success = job.waitForCompletion(true);
if (!success) {
String message = NutchJob.getJobFailureLogMessage("Crawl", job);
LOG.error(message);
fs.delete(tempDir, true);
throw new RuntimeException(message);
}
long dups = job.getCounters()
.findCounter(NutchMetrics.GROUP_DEDUP, NutchMetrics.DEDUP_DOCUMENTS_MARKED_DUPLICATE_TOTAL)
.getValue();
LOG.info("Deduplication: {} documents marked as duplicates", dups);
} catch (IOException | InterruptedException | ClassNotFoundException e) {
LOG.error("DeduplicationJob:", e);
fs.delete(tempDir, true);
return -1;
}
// merge with existing crawl db
LOG.info("Deduplication: Updating status of duplicate urls into crawl db.");
Job mergeJob = CrawlDb.createJob(getConf(), crawlDb);
FileInputFormat.addInputPath(mergeJob, tempDir);
mergeJob.setReducerClass(StatusUpdateReducer.class);
mergeJob.setJarByClass(DeduplicationJob.class);
fs = crawlDb.getFileSystem(getConf());
Path outPath = FileOutputFormat.getOutputPath(job);
Path lock = CrawlDb.lock(getConf(), crawlDb, false);
try {
boolean success = mergeJob.waitForCompletion(true);
if (!success) {
String message = NutchJob.getJobFailureLogMessage("Crawl", mergeJob);
LOG.error(message);
fs.delete(tempDir, true);
NutchJob.cleanupAfterFailure(outPath, lock, fs);
throw new RuntimeException(message);
}
} catch (IOException | InterruptedException | ClassNotFoundException e) {
LOG.error("DeduplicationMergeJob:", e);
fs.delete(tempDir, true);
NutchJob.cleanupAfterFailure(outPath, lock, fs);
return -1;
}
CrawlDb.install(mergeJob, crawlDb);
// clean up
fs.delete(tempDir, true);
stopWatch.stop();
LOG.info("Deduplication finished, elapsed: {} ms",
stopWatch.getTime(TimeUnit.MILLISECONDS));
return 0;
}
public static void main(String[] args) throws Exception {
int result = ToolRunner.run(NutchConfiguration.create(),
new DeduplicationJob(), args);
System.exit(result);
}
@Override
public Map<String, Object> run(Map<String, Object> args, String crawlId) throws Exception {
Map<String, Object> results = new HashMap<>();
String[] arg = new String[1];
String crawldb;
if(args.containsKey(Nutch.ARG_CRAWLDB)) {
crawldb = (String)args.get(Nutch.ARG_CRAWLDB);
}
else {
crawldb = crawlId+"/crawldb";
}
arg[0] = crawldb;
int res = run(arg);
results.put(Nutch.VAL_RESULT, Integer.toString(res));
return results;
}
}