-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
MultipleIndexPopulator.java
699 lines (625 loc) · 24.9 KB
/
MultipleIndexPopulator.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
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
/*
* Copyright (c) 2002-2019 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.kernel.impl.api.index;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
import org.neo4j.function.ThrowingConsumer;
import org.neo4j.helpers.collection.Pair;
import org.neo4j.helpers.collection.Visitor;
import org.neo4j.internal.kernel.api.InternalIndexState;
import org.neo4j.internal.kernel.api.schema.SchemaDescriptor;
import org.neo4j.internal.kernel.api.schema.SchemaDescriptorSupplier;
import org.neo4j.kernel.api.exceptions.index.FlipFailedKernelException;
import org.neo4j.kernel.api.exceptions.index.IndexEntryConflictException;
import org.neo4j.kernel.api.exceptions.index.IndexPopulationFailedKernelException;
import org.neo4j.kernel.api.index.IndexEntryUpdate;
import org.neo4j.kernel.api.index.IndexPopulator;
import org.neo4j.kernel.api.index.IndexUpdater;
import org.neo4j.storageengine.api.NodePropertyAccessor;
import org.neo4j.kernel.impl.api.SchemaState;
import org.neo4j.logging.Log;
import org.neo4j.logging.LogProvider;
import org.neo4j.storageengine.api.EntityType;
import org.neo4j.storageengine.api.schema.CapableIndexDescriptor;
import org.neo4j.storageengine.api.schema.IndexSample;
import org.neo4j.storageengine.api.schema.PopulationProgress;
import org.neo4j.util.FeatureToggles;
import static java.lang.String.format;
import static org.eclipse.collections.impl.utility.ArrayIterate.contains;
import static org.neo4j.kernel.impl.api.index.IndexPopulationFailure.failure;
/**
* {@link IndexPopulator} that allow population of multiple indexes during one iteration.
* Performs operations by calling corresponding operations of particular index populators.
*
* There are two ways data is fed to this multi-populator:
* <ul>
* <li>{@link #indexAllEntities()}, which is a blocking call and will scan the entire store and
* and generate updates that are fed into the {@link IndexPopulator populators}. Only a single call to this
* method should be made during the life time of a {@link MultipleIndexPopulator} and should be called by the
* same thread instantiating this instance.</li>
* <li>{@link #queueUpdate(IndexEntryUpdate)} which queues updates which will be read by the thread currently executing
* {@link #indexAllEntities()} and incorporated into that data stream. Calls to this method may come from any number
* of concurrent threads.</li>
* </ul>
*
* Usage of this class should be something like:
* <ol>
* <li>Instantiation.</li>
* <li>One or more calls to {@link #addPopulator(IndexPopulator, CapableIndexDescriptor, FlippableIndexProxy, FailedIndexProxyFactory, String)}.</li>
* <li>Call to {@link #create()} to create data structures and files to start accepting updates.</li>
* <li>Call to {@link #indexAllEntities()} (blocking call).</li>
* <li>While all nodes are being indexed, calls to {@link #queueUpdate(IndexEntryUpdate)} are accepted.</li>
* <li>Call to {@link #flipAfterPopulation(boolean)} after successful population, or {@link #fail(Throwable)} if not</li>
* </ol>
*/
public class MultipleIndexPopulator implements IndexPopulator
{
public static final String QUEUE_THRESHOLD_NAME = "queue_threshold";
static final String BATCH_SIZE_NAME = "batch_size";
private final int QUEUE_THRESHOLD = FeatureToggles.getInteger( getClass(), QUEUE_THRESHOLD_NAME, 20_000 );
private final int BATCH_SIZE = FeatureToggles.getInteger( BatchingMultipleIndexPopulator.class, BATCH_SIZE_NAME, 10_000 );
// Concurrency queue since multiple concurrent threads may enqueue updates into it. It is important for this queue
// to have fast #size() method since it might be drained in batches
final Queue<IndexEntryUpdate<?>> updatesQueue = new LinkedBlockingQueue<>();
// Populators are added into this list. The same thread adding populators will later call #indexAllEntities.
// Multiple concurrent threads might fail individual populations.
// Failed populations are removed from this list while iterating over it.
final List<IndexPopulation> populations = new CopyOnWriteArrayList<>();
private final IndexStoreView storeView;
private final LogProvider logProvider;
protected final Log log;
private final EntityType type;
private final SchemaState schemaState;
private final PhaseTracker phaseTracker;
private StoreScan<IndexPopulationFailedKernelException> storeScan;
public MultipleIndexPopulator( IndexStoreView storeView, LogProvider logProvider, EntityType type, SchemaState schemaState )
{
this.storeView = storeView;
this.logProvider = logProvider;
this.log = logProvider.getLog( IndexPopulationJob.class );
this.type = type;
this.schemaState = schemaState;
this.phaseTracker = new LoggingPhaseTracker( logProvider.getLog( IndexPopulationJob.class ) );
}
IndexPopulation addPopulator( IndexPopulator populator, CapableIndexDescriptor capableIndexDescriptor, FlippableIndexProxy flipper,
FailedIndexProxyFactory failedIndexProxyFactory, String indexUserDescription )
{
IndexPopulation population = createPopulation( populator, capableIndexDescriptor, flipper, failedIndexProxyFactory, indexUserDescription );
populations.add( population );
return population;
}
private IndexPopulation createPopulation( IndexPopulator populator, CapableIndexDescriptor capableIndexDescriptor, FlippableIndexProxy flipper,
FailedIndexProxyFactory failedIndexProxyFactory, String indexUserDescription )
{
return new IndexPopulation( populator, capableIndexDescriptor, flipper, failedIndexProxyFactory, indexUserDescription );
}
boolean hasPopulators()
{
return !populations.isEmpty();
}
@Override
public void create()
{
forEachPopulation( population ->
{
log.info( "Index population started: [%s]", population.indexUserDescription );
population.create();
} );
}
@Override
public void drop()
{
throw new UnsupportedOperationException( "Can't drop indexes from this populator implementation" );
}
@Override
public void add( Collection<? extends IndexEntryUpdate<?>> updates )
{
throw new UnsupportedOperationException( "Can't populate directly using this populator implementation. " );
}
StoreScan<IndexPopulationFailedKernelException> indexAllEntities()
{
int[] entityTokenIds = entityTokenIds();
int[] propertyKeyIds = propertyKeyIds();
IntPredicate propertyKeyIdFilter = propertyKeyId -> contains( propertyKeyIds, propertyKeyId );
if ( type == EntityType.RELATIONSHIP )
{
storeScan = storeView.visitRelationships( entityTokenIds, propertyKeyIdFilter, new EntityPopulationVisitor() );
}
else
{
storeScan = storeView.visitNodes( entityTokenIds, propertyKeyIdFilter, new EntityPopulationVisitor(), null, false );
}
storeScan.setPhaseTracker( phaseTracker );
return new DelegatingStoreScan<IndexPopulationFailedKernelException>( storeScan )
{
@Override
public void run() throws IndexPopulationFailedKernelException
{
super.run();
flushAll();
}
};
}
/**
* Queues an update to be fed into the index populators. These updates come from changes being made
* to storage while a concurrent scan is happening to keep populators up to date with all latest changes.
*
* @param update {@link IndexEntryUpdate} to queue.
*/
void queueUpdate( IndexEntryUpdate<?> update )
{
updatesQueue.add( update );
}
/**
* Called if forced failure from the outside
*
* @param failure index population failure.
*/
public void fail( Throwable failure )
{
for ( IndexPopulation population : populations )
{
fail( population, failure );
}
}
protected void fail( IndexPopulation population, Throwable failure )
{
if ( !removeFromOngoingPopulations( population ) )
{
return;
}
// If the cause of index population failure is a conflict in a (unique) index, the conflict is the failure
if ( failure instanceof IndexPopulationFailedKernelException )
{
Throwable cause = failure.getCause();
if ( cause instanceof IndexEntryConflictException )
{
failure = cause;
}
}
log.error( format( "Failed to populate index: [%s]", population.indexUserDescription ), failure );
// The flipper will have already flipped to a failed index context here, but
// it will not include the cause of failure, so we do another flip to a failed
// context that does.
// The reason for having the flipper transition to the failed index context in the first
// place is that we would otherwise introduce a race condition where updates could come
// in to the old context, if something failed in the job we send to the flipper.
IndexPopulationFailure indexPopulationFailure = failure( failure );
population.flipToFailed( indexPopulationFailure );
try
{
population.populator.markAsFailed( indexPopulationFailure.asString() );
population.populator.close( false );
}
catch ( Throwable e )
{
log.error( format( "Unable to close failed populator for index: [%s]",
population.indexUserDescription ), e );
}
}
@Override
public void verifyDeferredConstraints( NodePropertyAccessor accessor )
{
throw new UnsupportedOperationException( "Should not be called directly" );
}
@Override
public MultipleIndexUpdater newPopulatingUpdater( NodePropertyAccessor accessor )
{
Map<SchemaDescriptor,Pair<IndexPopulation,IndexUpdater>> updaters = new HashMap<>();
forEachPopulation( population ->
{
IndexUpdater updater = population.populator.newPopulatingUpdater( accessor );
updaters.put( population.schema(), Pair.of( population, updater ) );
} );
return new MultipleIndexUpdater( this, updaters, logProvider );
}
@Override
public void close( boolean populationCompletedSuccessfully )
{
phaseTracker.stop();
// closing the populators happens in flip, fail or individually when they are completed
}
@Override
public void markAsFailed( String failure )
{
throw new UnsupportedOperationException( "Multiple index populator can't be marked as failed." );
}
@Override
public void includeSample( IndexEntryUpdate<?> update )
{
throw new UnsupportedOperationException( "Multiple index populator can't perform index sampling." );
}
@Override
public IndexSample sampleResult()
{
throw new UnsupportedOperationException( "Multiple index populator can't perform index sampling." );
}
void resetIndexCounts()
{
forEachPopulation( this::resetIndexCountsForPopulation );
}
private void resetIndexCountsForPopulation( IndexPopulation indexPopulation )
{
storeView.replaceIndexCounts( indexPopulation.indexId, 0, 0, 0 );
}
void flipAfterPopulation( boolean verifyBeforeFlipping )
{
for ( IndexPopulation population : populations )
{
try
{
population.flip( verifyBeforeFlipping );
}
catch ( Throwable t )
{
fail( population, t );
}
}
}
private int[] propertyKeyIds()
{
return populations.stream().flatMapToInt( this::propertyKeyIds ).distinct().toArray();
}
private IntStream propertyKeyIds( IndexPopulation population )
{
return IntStream.of( population.schema().getPropertyIds() );
}
private int[] entityTokenIds()
{
return populations.stream().flatMapToInt( population -> Arrays.stream( population.schema().getEntityTokenIds() ) ).toArray();
}
public void cancel()
{
forEachPopulation( this::cancelIndexPopulation );
}
void cancelIndexPopulation( IndexPopulation indexPopulation )
{
indexPopulation.cancel();
}
private boolean removeFromOngoingPopulations( IndexPopulation indexPopulation )
{
return populations.remove( indexPopulation );
}
boolean populateFromQueueBatched( long currentlyIndexedNodeId )
{
return populateFromQueue( QUEUE_THRESHOLD, currentlyIndexedNodeId );
}
void flushAll()
{
populations.forEach( this::flush );
}
protected void flush( IndexPopulation population )
{
phaseTracker.enterPhase( PhaseTracker.Phase.WRITE );
doFlush( population );
}
void doFlush( IndexPopulation population )
{
try
{
population.populator.add( population.takeCurrentBatch() );
}
catch ( Throwable failure )
{
fail( population, failure );
}
}
/**
* Populates external updates from the update queue if there are {@code queueThreshold} or more queued updates.
*
* @return whether or not there were external updates applied.
*/
boolean populateFromQueue( int queueThreshold, long currentlyIndexedNodeId )
{
int queueSize = updatesQueue.size();
if ( queueSize > 0 && queueSize >= queueThreshold )
{
// Before applying updates from the updates queue any pending scan updates needs to be applied, i.e. flushed.
// This is because 'currentlyIndexedNodeId' is based on how far the scan has come.
flushAll();
try ( MultipleIndexUpdater updater = newPopulatingUpdater( storeView ) )
{
do
{
// no need to check for null as nobody else is emptying this queue
IndexEntryUpdate<?> update = updatesQueue.poll();
storeScan.acceptUpdate( updater, update, currentlyIndexedNodeId );
}
while ( !updatesQueue.isEmpty() );
}
return true;
}
return false;
}
private void forEachPopulation( ThrowingConsumer<IndexPopulation,Exception> action )
{
for ( IndexPopulation population : populations )
{
try
{
action.accept( population );
}
catch ( Throwable failure )
{
fail( population, failure );
}
}
}
public static class MultipleIndexUpdater implements IndexUpdater
{
private final Map<SchemaDescriptor,Pair<IndexPopulation,IndexUpdater>> populationsWithUpdaters;
private final MultipleIndexPopulator multipleIndexPopulator;
private final Log log;
MultipleIndexUpdater( MultipleIndexPopulator multipleIndexPopulator,
Map<SchemaDescriptor,Pair<IndexPopulation,IndexUpdater>> populationsWithUpdaters, LogProvider logProvider )
{
this.multipleIndexPopulator = multipleIndexPopulator;
this.populationsWithUpdaters = populationsWithUpdaters;
this.log = logProvider.getLog( getClass() );
}
@Override
public void process( IndexEntryUpdate<?> update )
{
Pair<IndexPopulation,IndexUpdater> pair = populationsWithUpdaters.get( update.indexKey().schema() );
if ( pair != null )
{
IndexPopulation population = pair.first();
IndexUpdater updater = pair.other();
try
{
population.populator.includeSample( update );
updater.process( update );
}
catch ( Throwable t )
{
try
{
updater.close();
}
catch ( Throwable ce )
{
log.error( format( "Failed to close index updater: [%s]", updater ), ce );
}
populationsWithUpdaters.remove( update.indexKey().schema() );
multipleIndexPopulator.fail( population, t );
}
}
}
@Override
public void close()
{
for ( Pair<IndexPopulation,IndexUpdater> pair : populationsWithUpdaters.values() )
{
IndexPopulation population = pair.first();
IndexUpdater updater = pair.other();
try
{
updater.close();
}
catch ( Throwable t )
{
multipleIndexPopulator.fail( population, t );
}
}
populationsWithUpdaters.clear();
}
}
public class IndexPopulation implements SchemaDescriptorSupplier
{
public final IndexPopulator populator;
final FlippableIndexProxy flipper;
private final long indexId;
private final CapableIndexDescriptor capableIndexDescriptor;
private final IndexCountsRemover indexCountsRemover;
private final FailedIndexProxyFactory failedIndexProxyFactory;
private final String indexUserDescription;
private boolean populationOngoing = true;
private final ReentrantLock populatorLock = new ReentrantLock();
List<IndexEntryUpdate<?>> batchedUpdates;
IndexPopulation( IndexPopulator populator, CapableIndexDescriptor capableIndexDescriptor, FlippableIndexProxy flipper,
FailedIndexProxyFactory failedIndexProxyFactory, String indexUserDescription )
{
this.populator = populator;
this.capableIndexDescriptor = capableIndexDescriptor;
this.indexId = capableIndexDescriptor.getId();
this.flipper = flipper;
this.failedIndexProxyFactory = failedIndexProxyFactory;
this.indexUserDescription = indexUserDescription;
this.indexCountsRemover = new IndexCountsRemover( storeView, indexId );
this.batchedUpdates = new ArrayList<>( BATCH_SIZE );
}
private void flipToFailed( IndexPopulationFailure failure )
{
flipper.flipTo( new FailedIndexProxy( capableIndexDescriptor, indexUserDescription, populator, failure, indexCountsRemover, logProvider ) );
}
void create()
{
populatorLock.lock();
try
{
if ( populationOngoing )
{
populator.create();
}
}
finally
{
populatorLock.unlock();
}
}
void cancel()
{
populatorLock.lock();
try
{
if ( populationOngoing )
{
populator.close( false );
resetIndexCountsForPopulation( this );
removeFromOngoingPopulations( this );
populationOngoing = false;
}
}
finally
{
populatorLock.unlock();
}
}
private void onUpdate( IndexEntryUpdate<?> update )
{
populator.includeSample( update );
if ( batch( update ) )
{
flush( this );
}
}
void flip( boolean verifyBeforeFlipping ) throws FlipFailedKernelException
{
phaseTracker.enterPhase( PhaseTracker.Phase.FLIP );
flipper.flip( () ->
{
populatorLock.lock();
try
{
if ( populationOngoing )
{
populator.add( takeCurrentBatch() );
populateFromQueue( 0, Long.MAX_VALUE );
if ( populations.contains( IndexPopulation.this ) )
{
if ( verifyBeforeFlipping )
{
populator.verifyDeferredConstraints( storeView );
}
IndexSample sample = populator.sampleResult();
storeView.replaceIndexCounts( indexId, sample.uniqueValues(), sample.sampleSize(), sample.indexSize() );
populator.close( true );
schemaState.clear();
return true;
}
}
return false;
}
finally
{
populationOngoing = false;
populatorLock.unlock();
}
}, failedIndexProxyFactory );
removeFromOngoingPopulations( this );
logCompletionMessage();
}
private void logCompletionMessage()
{
InternalIndexState postPopulationState = flipper.getState();
String messageTemplate = isIndexPopulationOngoing( postPopulationState )
? "Index created. Starting data checks. Index [%s] is %s."
: "Index creation finished. Index [%s] is %s.";
log.info( messageTemplate, indexUserDescription, postPopulationState.name() );
}
private boolean isIndexPopulationOngoing( InternalIndexState postPopulationState )
{
return InternalIndexState.POPULATING == postPopulationState;
}
@Override
public SchemaDescriptor schema()
{
return capableIndexDescriptor.schema();
}
public boolean batch( IndexEntryUpdate<?> update )
{
batchedUpdates.add( update );
return batchedUpdates.size() >= BATCH_SIZE;
}
Collection<IndexEntryUpdate<?>> takeCurrentBatch()
{
if ( batchedUpdates.isEmpty() )
{
return Collections.emptyList();
}
Collection<IndexEntryUpdate<?>> batch = batchedUpdates;
batchedUpdates = new ArrayList<>( BATCH_SIZE );
return batch;
}
}
private class EntityPopulationVisitor implements Visitor<EntityUpdates,
IndexPopulationFailedKernelException>
{
@Override
public boolean visit( EntityUpdates updates )
{
add( updates );
return populateFromQueueBatched( updates.getEntityId() );
}
private void add( EntityUpdates updates )
{
// This is called from a full store node scan, meaning that all node properties are included in the
// EntityUpdates object. Therefore no additional properties need to be loaded.
for ( IndexEntryUpdate<IndexPopulation> indexUpdate : updates.forIndexKeys( populations ) )
{
indexUpdate.indexKey().onUpdate( indexUpdate );
}
}
}
protected static class DelegatingStoreScan<E extends Exception> implements StoreScan<E>
{
private final StoreScan<E> delegate;
DelegatingStoreScan( StoreScan<E> delegate )
{
this.delegate = delegate;
}
@Override
public void run() throws E
{
delegate.run();
}
@Override
public void stop()
{
delegate.stop();
}
@Override
public void acceptUpdate( MultipleIndexUpdater updater, IndexEntryUpdate<?> update, long currentlyIndexedNodeId )
{
delegate.acceptUpdate( updater, update, currentlyIndexedNodeId );
}
@Override
public PopulationProgress getProgress()
{
return delegate.getProgress();
}
@Override
public void setPhaseTracker( PhaseTracker phaseTracker )
{
delegate.setPhaseTracker( phaseTracker );
}
}
}