forked from elastic/elasticsearch
/
BufferedRestClient.java
244 lines (207 loc) · 8.2 KB
/
BufferedRestClient.java
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
/*
* Copyright 2013 the original author or authors.
*
* Licensed 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.elasticsearch.hadoop.rest;
import java.io.Closeable;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.elasticsearch.hadoop.cfg.Settings;
import org.elasticsearch.hadoop.rest.dto.Node;
import org.elasticsearch.hadoop.rest.dto.Shard;
import org.elasticsearch.hadoop.rest.dto.mapping.Field;
import org.elasticsearch.hadoop.serialization.BulkCommands;
import org.elasticsearch.hadoop.serialization.Command;
import org.elasticsearch.hadoop.serialization.ScrollReader;
import org.elasticsearch.hadoop.util.Assert;
import org.elasticsearch.hadoop.util.BytesArray;
import org.elasticsearch.hadoop.util.BytesRef;
import org.elasticsearch.hadoop.util.unit.TimeValue;
/**
* Rest client performing high-level operations using buffers to improve performance. Stateful in that once created, it is used to perform updates against the same index.
*/
public class BufferedRestClient implements Closeable {
private static Log log = LogFactory.getLog(BufferedRestClient.class);
// serialization artifacts
private int bufferEntriesThreshold;
private final BytesArray data = new BytesArray(0);
private int dataEntries = 0;
private boolean requiresRefreshAfterBulk = false;
private boolean executedBulkWrite = false;
private BytesRef objectAlreadySerialized;
private boolean writeInitialized = false;
private RestClient client;
private String index;
private Resource resource;
private Command command;
private final Settings settings;
public BufferedRestClient(Settings settings) {
this.settings = settings;
this.client = new RestClient(settings);
String tempIndex = settings.getTargetResource();
if (tempIndex == null) {
tempIndex = "";
}
this.index = tempIndex;
this.resource = new Resource(index);
}
/** postpone writing initialization since we can do only reading so there's no need to allocate buffers */
private void lazyInitWriting() {
if (!writeInitialized) {
writeInitialized = true;
data.bytes(new byte[settings.getBatchSizeInBytes()], 0);
objectAlreadySerialized = new BytesRef();
bufferEntriesThreshold = settings.getBatchSizeInEntries();
requiresRefreshAfterBulk = settings.getBatchRefreshAfterWrite();
this.command = BulkCommands.create(settings);
}
}
/**
* Returns a pageable (scan based) result to the given query.
*
* @param query scan query
* @param reader scroll reader
* @return a scroll query
*/
ScrollQuery scan(String query, ScrollReader reader) throws IOException {
String[] scrollInfo = client.scan(query);
String scrollId = scrollInfo[0];
long totalSize = Long.parseLong(scrollInfo[1]);
return new ScrollQuery(this, scrollId, totalSize, reader);
}
/**
* Writes the objects to index.
*
* @param object object to add to the index
*/
public void writeToIndex(Object object) throws IOException {
Assert.hasText(index, "no index given");
Assert.notNull(object, "no object data given");
lazyInitWriting();
doWriteToIndex(command.write(object));
}
/**
* Writes the objects to index.
*
* @param data as a byte array
* @param size the length to use from the given array
*/
public void writeProcessedToIndex(BytesArray ba) throws IOException {
Assert.hasText(index, "no index given");
Assert.notNull(ba, "no data given");
Assert.isTrue(ba.size() > 0, "no data given");
lazyInitWriting();
objectAlreadySerialized.add(ba);
doWriteToIndex(objectAlreadySerialized);
}
private void doWriteToIndex(BytesRef payload) throws IOException {
// check space first
if (payload.size() > data.available()) {
flushBatch();
}
payload.write(data);
dataEntries++;
if (bufferEntriesThreshold > 0 && dataEntries >= bufferEntriesThreshold) {
flushBatch();
}
}
private void flushBatch() throws IOException {
if (log.isDebugEnabled()) {
log.debug(String.format("Flushing batch of [%d] bytes/[%s] entries", data.size(), dataEntries));
}
client.bulk(index, data.bytes(), data.size());
data.reset();
dataEntries = 0;
executedBulkWrite = true;
}
@Override
public void close() {
try {
if (data.size() > 0) {
flushBatch();
}
if (requiresRefreshAfterBulk && executedBulkWrite) {
// refresh batch
client.refresh(index);
if (log.isDebugEnabled()) {
log.debug(String.format("Refreshing index [%s]", index));
}
}
} catch (IOException ex) {
log.warn("Cannot flush data batch", ex);
}
client.close();
}
public RestClient getRestClient() {
return client;
}
public Map<Shard, Node> getTargetShards() throws IOException {
Map<String, Node> nodes = client.getNodes();
List<List<Map<String, Object>>> info = client.targetShards(resource.targetShards());
Map<Shard, Node> shards = new LinkedHashMap<Shard, Node>(info.size());
for (List<Map<String, Object>> shardGroup : info) {
// find the first started shard in each group (round-robin)
for (Map<String, Object> shardData : shardGroup) {
Shard shard = new Shard(shardData);
if (shard.getState().isStarted()) {
Node node = nodes.get(shard.getNode());
Assert.notNull(node, "Cannot find node with id [" + shard.getNode() + "]");
shards.put(shard, node);
break;
}
}
}
return shards;
}
public Map<Shard, Node> getTargetPrimaryShards() throws IOException {
Map<String, Node> nodes = client.getNodes();
List<List<Map<String, Object>>> info = client.targetShards(resource.targetShards());
Map<Shard, Node> shards = new LinkedHashMap<Shard, Node>(info.size());
for (List<Map<String, Object>> shardGroup : info) {
// consider only primary shards
for (Map<String, Object> shardData : shardGroup) {
Shard shard = new Shard(shardData);
if (shard.isPrimary()) {
Node node = nodes.get(shard.getNode());
Assert.notNull(node, "Cannot find node with id [" + shard.getNode() + "]");
shards.put(shard, node);
break;
}
}
}
return shards;
}
public Field getMapping() throws IOException {
return Field.parseField((Map<String, Object>) client.getMapping(resource.mapping()));
}
public List<Object[]> scroll(String scrollId, ScrollReader reader) throws IOException {
return reader.read(client.scroll(scrollId));
}
public boolean indexExists() {
return client.exists(resource.indexAndType());
}
public void putMapping(BytesArray mapping) {
client.putMapping(resource.index(), resource.mapping(), mapping.bytes());
}
public boolean touch() {
return client.touch(resource.index());
}
public boolean waitForYellow() throws IOException {
return client.health(resource.index(), RestClient.HEALTH.YELLOW, TimeValue.timeValueSeconds(10));
}
}