/
DocumentStoreIndexerBase.java
356 lines (314 loc) · 17.6 KB
/
DocumentStoreIndexerBase.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
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
/*
* 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.jackrabbit.oak.index.indexer.document;
import com.codahale.metrics.MetricRegistry;
import com.google.common.base.Stopwatch;
import com.google.common.io.Closer;
import org.apache.jackrabbit.oak.api.CommitFailedException;
import org.apache.jackrabbit.oak.index.IndexHelper;
import org.apache.jackrabbit.oak.index.IndexerSupport;
import org.apache.jackrabbit.oak.index.indexer.document.flatfile.DefaultMemoryManager;
import org.apache.jackrabbit.oak.index.indexer.document.flatfile.FlatFileNodeStoreBuilder;
import org.apache.jackrabbit.oak.index.indexer.document.flatfile.FlatFileStore;
import org.apache.jackrabbit.oak.index.indexer.document.flatfile.MemoryManager;
import org.apache.jackrabbit.oak.plugins.document.Collection;
import org.apache.jackrabbit.oak.plugins.document.DocumentNodeState;
import org.apache.jackrabbit.oak.plugins.document.DocumentNodeStore;
import org.apache.jackrabbit.oak.plugins.document.RevisionVector;
import org.apache.jackrabbit.oak.plugins.document.mongo.DocumentStoreSplitter;
import org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentStore;
import org.apache.jackrabbit.oak.plugins.document.mongo.MongoDocumentTraverser;
import org.apache.jackrabbit.oak.plugins.document.util.MongoConnection;
import org.apache.jackrabbit.oak.plugins.index.IndexConstants;
import org.apache.jackrabbit.oak.plugins.index.IndexUpdateCallback;
import org.apache.jackrabbit.oak.plugins.index.NodeTraversalCallback;
import org.apache.jackrabbit.oak.plugins.index.progress.IndexingProgressReporter;
import org.apache.jackrabbit.oak.plugins.index.progress.MetricRateEstimator;
import org.apache.jackrabbit.oak.plugins.index.search.IndexDefinition;
import org.apache.jackrabbit.oak.plugins.memory.MemoryNodeStore;
import org.apache.jackrabbit.oak.plugins.metric.MetricStatisticsProvider;
import org.apache.jackrabbit.oak.spi.commit.CommitInfo;
import org.apache.jackrabbit.oak.spi.commit.EmptyHook;
import org.apache.jackrabbit.oak.spi.filter.PathFilter;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.spi.state.NodeState;
import org.apache.jackrabbit.oak.spi.state.NodeStateUtils;
import org.apache.jackrabbit.oak.spi.state.NodeStore;
import org.apache.jackrabbit.oak.stats.StatisticsProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Predicate;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.apache.jackrabbit.oak.index.indexer.document.flatfile.FlatFileNodeStoreBuilder.OAK_INDEXER_SORTED_FILE_PATH;
import static org.apache.jackrabbit.oak.plugins.index.IndexConstants.TYPE_PROPERTY_NAME;
public abstract class DocumentStoreIndexerBase implements Closeable{
private final Logger log = LoggerFactory.getLogger(getClass());
private final Logger traversalLog = LoggerFactory.getLogger(DocumentStoreIndexerBase.class.getName()+".traversal");
protected final Closer closer = Closer.create();
protected final IndexHelper indexHelper;
protected List<NodeStateIndexerProvider> indexerProviders;
protected final IndexerSupport indexerSupport;
private final Set<String> indexerPaths = new HashSet<>();
private static final int MAX_DOWNLOAD_ATTEMPTS = Integer.parseInt(System.getProperty("oak.indexer.maxDownloadRetries", "5")) + 1;
public DocumentStoreIndexerBase(IndexHelper indexHelper, IndexerSupport indexerSupport) {
this.indexHelper = indexHelper;
this.indexerSupport = indexerSupport;
}
protected void setProviders() throws IOException {
this.indexerProviders = createProviders();
}
private static class MongoNodeStateEntryTraverserFactory implements NodeStateEntryTraverserFactory {
/**
* This counter is part of this traverser's id and is helpful in identifying logs from different traversers that
* run concurrently.
*/
private static final AtomicInteger traverserInstanceCounter = new AtomicInteger(0);
/**
* An prefix for ID of traversers (value is acronym for NodeStateEntryTraverser).
*/
private static final String TRAVERSER_ID_PREFIX = "NSET";
private final RevisionVector rootRevision;
private final DocumentNodeStore documentNodeStore;
private final MongoDocumentStore documentStore;
private final Logger traversalLogger;
private final CompositeIndexer indexer;
private MongoNodeStateEntryTraverserFactory(RevisionVector rootRevision, DocumentNodeStore documentNodeStore,
MongoDocumentStore documentStore, Logger traversalLogger, CompositeIndexer indexer) {
this.rootRevision = rootRevision;
this.documentNodeStore = documentNodeStore;
this.documentStore = documentStore;
this.traversalLogger = traversalLogger;
this.indexer = indexer;
}
@Override
public NodeStateEntryTraverser create(MongoDocumentTraverser.TraversingRange traversingRange) {
IndexingProgressReporter progressReporterPerTask =
new IndexingProgressReporter(IndexUpdateCallback.NOOP, NodeTraversalCallback.NOOP);
String entryTraverserID = TRAVERSER_ID_PREFIX + traverserInstanceCounter.incrementAndGet();
//As first traversal is for dumping change the message prefix
progressReporterPerTask.setMessagePrefix("Dumping from " + entryTraverserID);
return new NodeStateEntryTraverser(entryTraverserID, rootRevision,
documentNodeStore, documentStore, traversingRange)
.withProgressCallback((id) -> {
try {
progressReporterPerTask.traversedNode(() -> id);
} catch (CommitFailedException e) {
throw new RuntimeException(e);
}
traversalLogger.trace(id);
});
}
}
private FlatFileStore buildFlatFileStore(NodeState checkpointedState, CompositeIndexer indexer, Predicate<String> pathPredicate, Set<String> preferredPathElements) throws IOException {
Stopwatch flatFileStoreWatch = Stopwatch.createStarted();
int executionCount = 1;
CompositeException lastException = null;
List<File> previousDownloadDirs = new ArrayList<>();
FlatFileStore flatFileStore = null;
//TODO How to ensure we can safely read from secondary
DocumentNodeState rootDocumentState = (DocumentNodeState) checkpointedState;
DocumentNodeStore nodeStore = (DocumentNodeStore) indexHelper.getNodeStore();
DocumentStoreSplitter splitter = new DocumentStoreSplitter(getMongoDocumentStore());
List<Long> lastModifiedBreakPoints = splitter.split(Collection.NODES, 0L ,10);
FlatFileNodeStoreBuilder builder = null;
int backOffTimeInMillis = 5000;
MemoryManager memoryManager = new DefaultMemoryManager();
while (flatFileStore == null && executionCount <= MAX_DOWNLOAD_ATTEMPTS) {
try {
builder = new FlatFileNodeStoreBuilder(indexHelper.getWorkDir(), memoryManager)
.withLastModifiedBreakPoints(lastModifiedBreakPoints)
.withBlobStore(indexHelper.getGCBlobStore())
.withPreferredPathElements((preferredPathElements != null) ? preferredPathElements : indexer.getRelativeIndexedNodeNames())
.addExistingDataDumpDir(indexerSupport.getExistingDataDumpDir())
.withPathPredicate(pathPredicate)
.withNodeStateEntryTraverserFactory(new MongoNodeStateEntryTraverserFactory(rootDocumentState.getRootRevision(),
nodeStore, getMongoDocumentStore(), traversalLog, indexer));
for (File dir : previousDownloadDirs) {
builder.addExistingDataDumpDir(dir);
}
flatFileStore = builder.build();
closer.register(flatFileStore);
} catch (CompositeException e) {
e.logAllExceptions("Underlying throwable caught during download", log);
log.info("Could not build flat file store. Execution count {}. Retries left {}. Time elapsed {}",
executionCount, MAX_DOWNLOAD_ATTEMPTS - executionCount, flatFileStoreWatch);
lastException = e;
previousDownloadDirs.add(builder.getFlatFileStoreDir());
if (executionCount < MAX_DOWNLOAD_ATTEMPTS) {
try {
log.info("Waiting for {} millis before retrying", backOffTimeInMillis);
Thread.sleep(backOffTimeInMillis);
backOffTimeInMillis *= 2;
} catch (InterruptedException ie) {
log.error("Interrupted while waiting before retrying download ", ie);
}
}
}
executionCount++;
}
if (flatFileStore == null) {
throw new IOException("Could not build flat file store", lastException);
}
log.info("Completed the flat file store build in {}", flatFileStoreWatch);
return flatFileStore;
}
/**
*
* @return an Instance of FlatFileStore, whose getFlatFileStorePath() method can be used to get the absolute path to this store.
* @throws IOException
* @throws CommitFailedException
*/
public FlatFileStore buildFlatFileStore() throws IOException, CommitFailedException {
NodeState checkpointedState = indexerSupport.retrieveNodeStateForCheckpoint();
NodeStore copyOnWriteStore = new MemoryNodeStore(checkpointedState);
NodeBuilder builder = copyOnWriteStore.getRoot().builder();
NodeState root = builder.getNodeState();
indexerSupport.updateIndexDefinitions(builder);
IndexDefinition.Builder indexDefBuilder = new IndexDefinition.Builder();
Set<String> preferredPathElements = new HashSet<>();
Set<IndexDefinition> indexDefinitions = new HashSet<>();
for (String indexPath : indexHelper.getIndexPaths()) {
NodeBuilder idxBuilder = IndexerSupport.childBuilder(builder, indexPath, false);
IndexDefinition indexDf = indexDefBuilder.defn(idxBuilder.getNodeState()).indexPath(indexPath).root(root).build();
preferredPathElements.addAll(indexDf.getRelativeNodeNames());
indexDefinitions.add(indexDf);
}
Predicate<String> predicate = s -> indexDefinitions.stream().anyMatch(indexDef -> indexDef.getPathFilter().filter(s) != PathFilter.Result.EXCLUDE);
FlatFileStore flatFileStore = buildFlatFileStore(checkpointedState, null, predicate, preferredPathElements);
log.info("FlatFileStore built at {}. To use this flatFileStore in a reindex step, set System Property-{} with value {}",
flatFileStore.getFlatFileStorePath(), OAK_INDEXER_SORTED_FILE_PATH, flatFileStore.getFlatFileStorePath());
return flatFileStore;
}
public void reindex() throws CommitFailedException, IOException {
IndexingProgressReporter progressReporter =
new IndexingProgressReporter(IndexUpdateCallback.NOOP, NodeTraversalCallback.NOOP);
configureEstimators(progressReporter);
NodeState checkpointedState = indexerSupport.retrieveNodeStateForCheckpoint();
NodeStore copyOnWriteStore = new MemoryNodeStore(checkpointedState);
indexerSupport.switchIndexLanesAndReindexFlag(copyOnWriteStore);
NodeBuilder builder = copyOnWriteStore.getRoot().builder();
CompositeIndexer indexer = prepareIndexers(copyOnWriteStore, builder, progressReporter);
if (indexer.isEmpty()) {
return;
}
closer.register(indexer);
FlatFileStore flatFileStore = buildFlatFileStore(checkpointedState, indexer, indexer::shouldInclude, null);
progressReporter.reset();
if (flatFileStore.getEntryCount() > 0){
FlatFileStore finalFlatFileStore = flatFileStore;
progressReporter.setNodeCountEstimator((String basePath, Set<String> indexPaths) -> finalFlatFileStore.getEntryCount());
}
progressReporter.reindexingTraversalStart("/");
preIndexOpertaions(indexer.getIndexers());
Stopwatch indexerWatch = Stopwatch.createStarted();
for (NodeStateEntry entry : flatFileStore) {
reportDocumentRead(entry.getPath(), progressReporter);
indexer.index(entry);
}
progressReporter.reindexingTraversalEnd();
progressReporter.logReport();
log.info("Completed the indexing in {}", indexerWatch);
copyOnWriteStore.merge(builder, EmptyHook.INSTANCE, CommitInfo.EMPTY);
indexerSupport.postIndexWork(copyOnWriteStore);
}
private MongoDocumentStore getMongoDocumentStore() {
return checkNotNull(indexHelper.getService(MongoDocumentStore.class));
}
private void configureEstimators(IndexingProgressReporter progressReporter) {
StatisticsProvider statsProvider = indexHelper.getStatisticsProvider();
if (statsProvider instanceof MetricStatisticsProvider) {
MetricRegistry registry = ((MetricStatisticsProvider) statsProvider).getRegistry();
progressReporter.setTraversalRateEstimator(new MetricRateEstimator("async", registry));
}
long nodesCount = getEstimatedDocumentCount();
if (nodesCount > 0) {
progressReporter.setNodeCountEstimator((String basePath, Set<String> indexPaths) -> nodesCount);
progressReporter.setEstimatedCount(nodesCount);
log.info("Estimated number of documents in Mongo are {}", nodesCount);
}
}
private long getEstimatedDocumentCount(){
MongoConnection mongoConnection = indexHelper.getService(MongoConnection.class);
if (mongoConnection != null) {
return mongoConnection.getDatabase().getCollection("nodes").count();
}
return 0;
}
@Override
public void close() throws IOException {
closer.close();
}
private void reportDocumentRead(String id, IndexingProgressReporter progressReporter) {
try {
progressReporter.traversedNode(() -> id);
} catch (CommitFailedException e) {
throw new RuntimeException(e);
}
traversalLog.trace(id);
}
protected CompositeIndexer prepareIndexers(NodeStore copyOnWriteStore, NodeBuilder builder,
IndexingProgressReporter progressReporter) {
NodeState root = copyOnWriteStore.getRoot();
List<NodeStateIndexer> indexers = new ArrayList<>();
for (String indexPath : indexHelper.getIndexPaths()) {
NodeState indexState = NodeStateUtils.getNode(root, indexPath);
NodeBuilder idxBuilder = IndexerSupport.childBuilder(builder, indexPath, false);
String type = indexState.getString(TYPE_PROPERTY_NAME);
if (type == null) {
log.warn("No 'type' property found on indexPath [{}]. Skipping it", indexPath);
continue;
}
removeIndexState(idxBuilder);
idxBuilder.setProperty(IndexConstants.REINDEX_PROPERTY_NAME, false);
for (NodeStateIndexerProvider indexerProvider : indexerProviders) {
NodeStateIndexer indexer = indexerProvider.getIndexer(type, indexPath, idxBuilder, root, progressReporter);
if (indexer != null) {
indexers.add(indexer);
closer.register(indexer);
progressReporter.registerIndex(indexPath, true, -1);
indexerPaths.add(indexPath);
}
}
}
return new CompositeIndexer(indexers);
}
protected abstract List<NodeStateIndexerProvider> createProviders() throws IOException;
protected abstract void preIndexOpertaions(List<NodeStateIndexer> indexers);
//TODO OAK-7098 - Taken from IndexUpdate. Refactor to abstract out common logic like this
private void removeIndexState(NodeBuilder definition) {
// as we don't know the index content node name
// beforehand, we'll remove all child nodes
for (String rm : definition.getChildNodeNames()) {
if (NodeStateUtils.isHidden(rm)) {
NodeBuilder childNode = definition.getChildNode(rm);
if (!childNode.getBoolean(IndexConstants.REINDEX_RETAIN)) {
definition.getChildNode(rm).remove();
}
}
}
}
}