Project

General

Profile

1
package eu.dnetlib.data.mapreduce.hbase.index;
2

    
3
import java.io.ByteArrayOutputStream;
4
import java.io.IOException;
5
import java.nio.charset.StandardCharsets;
6
import java.util.List;
7
import java.util.Map.Entry;
8
import java.util.zip.GZIPOutputStream;
9

    
10
import eu.dnetlib.functionality.index.solr.feed.ResultTransformer;
11
import eu.dnetlib.functionality.index.solr.feed.ResultTransformer.Mode;
12
import org.apache.commons.codec.binary.Base64;
13
import org.apache.commons.lang.exception.ExceptionUtils;
14
import org.apache.commons.logging.Log;
15
import org.apache.commons.logging.LogFactory;
16
import org.apache.hadoop.conf.Configuration;
17
import org.apache.hadoop.io.Text;
18
import org.apache.hadoop.mapreduce.Mapper;
19
import org.apache.solr.client.solrj.SolrServerException;
20
import org.apache.solr.client.solrj.impl.CloudSolrClient;
21
import org.apache.solr.client.solrj.response.SolrPingResponse;
22
import org.apache.solr.client.solrj.response.UpdateResponse;
23
import org.apache.solr.common.SolrInputDocument;
24

    
25
import com.google.common.collect.Lists;
26

    
27
import eu.dnetlib.data.mapreduce.JobParams;
28
import eu.dnetlib.data.proto.TypeProtos.Type;
29
import eu.dnetlib.functionality.index.solr.feed.InputDocumentFactory;
30
import eu.dnetlib.functionality.index.solr.feed.StreamingInputDocumentFactory;
31
import eu.dnetlib.miscutils.datetime.HumanTime;
32
import eu.dnetlib.miscutils.functional.xml.ApplyXslt;
33

    
34
public class IndexFeedMapper extends Mapper<Text, Text, Text, Text> {
35

    
36
	private static final Log log = LogFactory.getLog(IndexFeedMapper.class); // NOPMD by marko on 11/24/08 5:02 PM
37

    
38
	private InputDocumentFactory documentFactory;
39

    
40
	private CloudSolrClient solrServer;
41

    
42
	private String version;
43

    
44
	private String dsId;
45

    
46
	private int shutdownWaitTime = 10000;
47

    
48
	private int bufferFlushThreshold = 100;
49

    
50
	private ApplyXslt dmfToRecord;
51

    
52
	private List<SolrInputDocument> buffer;
53

    
54
	private int backoffTimeMs = 5000;
55

    
56
	private boolean simulation = false;
57

    
58
	private final static int MAX_INIT_RETRIES = 10;
59

    
60
	private final static int MAX_FEED_RETRIES = 10;
61

    
62
	@Override
63
	protected void setup(final Context context) throws IOException, InterruptedException {
64

    
65
		logConfiguration(context.getConfiguration());
66

    
67
		dsId = context.getConfiguration().get(JobParams.INDEX_DSID);
68
		shutdownWaitTime = Integer.parseInt(context.getConfiguration().get(JobParams.INDEX_SHUTDOWN_WAIT));
69
		bufferFlushThreshold = Integer.parseInt(context.getConfiguration().get(JobParams.INDEX_BUFFER_FLUSH_TRESHOLD));
70
		documentFactory = new StreamingInputDocumentFactory();
71
		version = InputDocumentFactory.getParsedDateField(context.getConfiguration().get(JobParams.INDEX_FEED_TIME));
72
		buffer = Lists.newArrayList();
73
		simulation = Boolean.parseBoolean(context.getConfiguration().get(JobParams.INDEX_FEED_SIMULATION_MODE));
74

    
75
		final String xslt = new String(Base64.decodeBase64(context.getConfiguration().get(JobParams.INDEX_XSLT)));
76

    
77
		log.info("got xslt: \n" + xslt);
78
		log.info("got version: " + version);
79
		log.info("simulation: " + simulation);
80
		log.info("buffer size: " + bufferFlushThreshold);
81

    
82
		dmfToRecord = new ApplyXslt(xslt);
83

    
84
		final String baseURL = context.getConfiguration().get(JobParams.INDEX_SOLR_URL);
85
		log.info("solr server baseURL: " + baseURL);
86

    
87
		final String collection = context.getConfiguration().get(JobParams.INDEX_SOLR_COLLECTION);
88
		log.info("solr server collection: " + collection);
89

    
90
		int count = 0;
91
		while (count <= MAX_INIT_RETRIES) {
92
			try {
93
				count++;
94
				log.info("initializing solr server...");
95
				solrServer = new CloudSolrClient.Builder()
96
						.withZkHost(baseURL)
97
						.build();
98

    
99
				solrServer.connect();
100

    
101
				solrServer.setParallelUpdates(true);
102
				solrServer.setDefaultCollection(collection);
103

    
104
				final SolrPingResponse rsp = solrServer.ping();
105

    
106
				if (rsp.getStatus() != 0) throw new SolrServerException("bad init status: " + rsp.getStatus());
107
				else {
108
					break;
109
				}
110

    
111
			} catch (final Throwable e) {
112
				if (solrServer != null) {
113
					solrServer.close();
114
				}
115
				context.getCounter("index init", e.getMessage()).increment(1);
116
				log.error(String.format("failed to init solr client wait %dms, error:\n%s", backoffTimeMs, ExceptionUtils.getStackTrace(e)));
117

    
118
				Thread.sleep(backoffTimeMs);
119
			}
120
		}
121

    
122
		if (count >= MAX_INIT_RETRIES) throw new IOException("reached max retries trying to connect to solr server: " + MAX_INIT_RETRIES);
123
	}
124

    
125
	@Override
126
	protected void map(final Text key, final Text value, final Context context) throws IOException, InterruptedException {
127

    
128
		String indexRecord = "";
129
		SolrInputDocument doc = null;
130

    
131
		try {
132
			indexRecord = dmfToRecord.evaluate(value.toString());
133
			doc = documentFactory.parseDocument(version, indexRecord, dsId, "dnetResult", new ResultTransformer(Mode.base64) {
134
				@Override
135
				public String apply(final String s) {
136

    
137
					return org.apache.solr.common.util.Base64.byteArrayToBase64(zip(s));
138
				}
139
			});
140
			if ((doc == null) || doc.isEmpty()) throw new EmptySolrDocumentException();
141

    
142
		} catch (final Throwable e) {
143
			context.getCounter("index feed", "skipped records").increment(1);
144
			handleError(key, value, context, indexRecord, doc, e);
145
			return;
146
		}
147
		int count = 0;
148
		while (count <= MAX_FEED_RETRIES) {
149
			count++;
150
			try {
151
				addDocument(context, doc);
152
				return;
153
			} catch (final Throwable e) {
154
				context.getCounter("index feed", "retries").increment(1);
155
				handleError(key, value, context, indexRecord, doc, e);
156
				log.info(String.format("failed to feed documents, waiting %dms", backoffTimeMs));
157
				Thread.sleep(backoffTimeMs);
158
			}
159
		}
160
	}
161

    
162
	public byte[] zip(final String s) {
163
		if ((s == null) || (s.length() == 0)) {
164
			throw new IllegalArgumentException("Cannot zip null or empty string");
165
		}
166

    
167
		try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
168
			try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) {
169
				gzipOutputStream.write(s.getBytes(StandardCharsets.UTF_8));
170
			}
171
			return byteArrayOutputStream.toByteArray();
172
		} catch(IOException e) {
173
			throw new RuntimeException("Failed to zip content", e);
174
		}
175
	}
176

    
177
	private void addDocument(final Context context, final SolrInputDocument doc) throws SolrServerException, IOException, EmptySolrDocumentException {
178
		buffer.add(doc);
179
		if (buffer.size() >= bufferFlushThreshold) {
180
			doAdd(buffer, context);
181
		}
182
	}
183

    
184
	private void doAdd(final List<SolrInputDocument> buffer, final Context context) throws SolrServerException, IOException {
185
		if (!simulation) {
186
			final long start = System.currentTimeMillis();
187
			final UpdateResponse rsp = solrServer.add(buffer);
188
			final long stop = System.currentTimeMillis() - start;
189
			log.info("feed time for " + buffer.size() + " records : " + HumanTime.exactly(stop) + "\n");
190

    
191
			final int status = rsp.getStatus();
192

    
193
			context.getCounter("index feed", "status code: " + status).increment(buffer.size());
194

    
195
			if (status != 0) throw new SolrServerException("bad status: " + status);
196

    
197
			for (final SolrInputDocument doc : buffer) {
198
				context.getCounter("index entity", getEntityType(doc)).increment(1);
199
			}
200
		}
201
		buffer.clear();
202
	}
203

    
204
	@Override
205
	protected void cleanup(final Context context) throws IOException, InterruptedException {
206
		super.cleanup(context);
207
		try {
208
			if (!buffer.isEmpty()) {
209
				doAdd(buffer, context);
210
			}
211
			log.info("\nwaiting " + shutdownWaitTime + "ms before shutdown");
212
			Thread.sleep(shutdownWaitTime);
213
			solrServer.close();
214
		} catch (final SolrServerException e) {
215
			log.error("couldn't shutdown server " + e.getMessage());
216
		}
217
	}
218

    
219
	private void handleError(final Text key, final Text value, final Context context, final String indexRecord, final SolrInputDocument doc, final Throwable e)
220
			throws IOException, InterruptedException {
221
		context.getCounter("index feed", e.getClass().getName()).increment(1);
222
		context.write(key, printRottenRecord(context.getTaskAttemptID().toString(), value, indexRecord, doc));
223
		// e.printStackTrace(System.err);
224
	}
225

    
226
	private Text printRottenRecord(final String taskid, final Text value, final String indexRecord, final SolrInputDocument doc) {
227
		return new Text("\n**********************************\n" + "task: " + taskid + "\n"
228
				+ check("original", value.toString() + check("indexRecord", indexRecord) + check("solrDoc", doc)));
229
	}
230

    
231
	private String check(final String label, final Object value) {
232
		if ((value != null) && !value.toString().isEmpty()) return "\n " + label + ":\n" + value + "\n";
233
		return "\n";
234
	}
235

    
236
	private void logConfiguration(final Configuration conf) {
237
		log.info("job configutation #################");
238
		for (final Entry<String, String> e : conf) {
239
			log.info("'" + e.getKey() + "' : '" + e.getValue() + "'");
240
		}
241
		log.info("end of job configutation #################\n\n");
242
	}
243

    
244
	private String getEntityType(final SolrInputDocument doc) {
245
		if (!doc.containsKey("oaftype")) return "unknown";
246

    
247
		final Type type = Type.valueOf(doc.getFieldValue("oaftype").toString());
248
		switch (type) {
249
		case result:
250
			if (!doc.containsKey("resulttypeid")) return "result";
251
			return doc.getFieldValue("resulttypeid").toString();
252
		default:
253
			return type.toString();
254
		}
255
	}
256

    
257
}
(5-5/7)