-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
IndexingServiceTest.java
1407 lines (1200 loc) · 59.2 KB
/
IndexingServiceTest.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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2002-2017 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.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 org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.IntPredicate;
import org.neo4j.collection.primitive.PrimitiveLongCollections;
import org.neo4j.collection.primitive.PrimitiveLongObjectMap;
import org.neo4j.collection.primitive.PrimitiveLongSet;
import org.neo4j.graphdb.ResourceIterator;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.helpers.collection.BoundedIterable;
import org.neo4j.helpers.collection.Iterators;
import org.neo4j.helpers.collection.Visitor;
import org.neo4j.io.fs.FileSystemAbstraction;
import org.neo4j.io.pagecache.PageCache;
import org.neo4j.kernel.api.TokenNameLookup;
import org.neo4j.kernel.api.exceptions.index.IndexEntryConflictException;
import org.neo4j.kernel.api.exceptions.index.IndexNotFoundKernelException;
import org.neo4j.kernel.api.exceptions.index.IndexPopulationFailedKernelException;
import org.neo4j.kernel.api.index.IndexAccessor;
import org.neo4j.kernel.api.index.IndexEntryUpdate;
import org.neo4j.kernel.api.index.IndexPopulator;
import org.neo4j.kernel.api.index.IndexUpdater;
import org.neo4j.kernel.api.index.InternalIndexState;
import org.neo4j.kernel.api.index.SchemaIndexProvider;
import org.neo4j.kernel.api.schema.LabelSchemaDescriptor;
import org.neo4j.kernel.api.schema.SchemaDescriptorFactory;
import org.neo4j.kernel.api.schema.index.IndexDescriptor;
import org.neo4j.kernel.api.schema.index.IndexDescriptorFactory;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.impl.api.index.sampling.IndexSamplingConfig;
import org.neo4j.kernel.impl.api.index.sampling.IndexSamplingController;
import org.neo4j.kernel.impl.api.index.sampling.IndexSamplingMode;
import org.neo4j.kernel.impl.api.scan.LabelScanStoreProvider;
import org.neo4j.kernel.impl.store.UnderlyingStorageException;
import org.neo4j.kernel.impl.store.record.IndexRule;
import org.neo4j.kernel.impl.storemigration.StoreMigrationParticipant;
import org.neo4j.kernel.impl.transaction.command.Command.NodeCommand;
import org.neo4j.kernel.impl.transaction.command.Command.PropertyCommand;
import org.neo4j.kernel.impl.transaction.state.DefaultSchemaIndexProviderMap;
import org.neo4j.kernel.impl.transaction.state.DirectIndexUpdates;
import org.neo4j.kernel.impl.transaction.state.IndexUpdates;
import org.neo4j.kernel.impl.util.JobScheduler;
import org.neo4j.kernel.impl.util.Neo4jJobScheduler;
import org.neo4j.kernel.lifecycle.LifeRule;
import org.neo4j.kernel.lifecycle.LifecycleException;
import org.neo4j.logging.AssertableLogProvider;
import org.neo4j.logging.AssertableLogProvider.LogMatcherBuilder;
import org.neo4j.logging.NullLogProvider;
import org.neo4j.register.Register.DoubleLongRegister;
import org.neo4j.storageengine.api.schema.IndexReader;
import org.neo4j.storageengine.api.schema.IndexSample;
import org.neo4j.storageengine.api.schema.PopulationProgress;
import org.neo4j.test.DoubleLatch;
import static java.lang.String.format;
import static java.lang.System.currentTimeMillis;
import static java.util.Arrays.asList;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyList;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.RETURNS_MOCKS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;
import static org.neo4j.collection.primitive.PrimitiveLongCollections.setOf;
import static org.neo4j.helpers.collection.Iterators.asCollection;
import static org.neo4j.helpers.collection.Iterators.asResourceIterator;
import static org.neo4j.helpers.collection.Iterators.asSet;
import static org.neo4j.helpers.collection.Iterators.iterator;
import static org.neo4j.helpers.collection.Iterators.loop;
import static org.neo4j.helpers.collection.MapUtil.stringMap;
import static org.neo4j.kernel.api.index.InternalIndexState.FAILED;
import static org.neo4j.kernel.api.index.InternalIndexState.ONLINE;
import static org.neo4j.kernel.api.index.InternalIndexState.POPULATING;
import static org.neo4j.kernel.impl.api.index.IndexUpdateMode.RECOVERY;
import static org.neo4j.kernel.impl.api.index.TestSchemaIndexProviderDescriptor.PROVIDER_DESCRIPTOR;
import static org.neo4j.kernel.impl.api.index.sampling.IndexSamplingMode.TRIGGER_REBUILD_ALL;
import static org.neo4j.logging.AssertableLogProvider.inLog;
import static org.neo4j.register.Registers.newDoubleLongRegister;
import static org.neo4j.test.mockito.answer.AwaitAnswer.afterAwaiting;
public class IndexingServiceTest
{
@Rule
public final LifeRule life = new LifeRule();
@Rule
public ExpectedException expectedException = ExpectedException.none();
private static final LogMatcherBuilder logMatch = inLog( IndexingService.class );
private static final Runnable DO_NOTHING_CALLBACK = () -> {};
private final int labelId = 7;
private final int propertyKeyId = 15;
private final IndexDescriptor index = IndexDescriptorFactory.forLabel( labelId, propertyKeyId );
private final IndexPopulator populator = mock( IndexPopulator.class );
private final IndexUpdater updater = mock( IndexUpdater.class );
private final SchemaIndexProvider indexProvider = mock( SchemaIndexProvider.class );
private final IndexAccessor accessor = mock( IndexAccessor.class, RETURNS_MOCKS );
private final IndexStoreView storeView = mock( IndexStoreView.class );
private final TokenNameLookup nameLookup = mock( TokenNameLookup.class );
private final AssertableLogProvider logProvider = new AssertableLogProvider();
@Before
public void setUp()
{
when( populator.sampleResult() ).thenReturn( new IndexSample() );
when( storeView.indexSample( anyLong(), any( DoubleLongRegister.class ) ) )
.thenAnswer( invocation -> invocation.getArguments()[1] );
}
@Test
public void shouldBringIndexOnlineAndFlipOverToIndexAccessor() throws Exception
{
// given
when( accessor.newUpdater( any( IndexUpdateMode.class ) ) ).thenReturn(updater);
IndexingService indexingService = newIndexingServiceWithMockedDependencies( populator, accessor, withData() );
life.start();
// when
indexingService.createIndexes( IndexRule.indexRule( 0, index, PROVIDER_DESCRIPTOR ) );
IndexProxy proxy = indexingService.getIndexProxy( 0 );
waitForIndexesToComeOnline( indexingService, 0 );
verify( populator, timeout( 1000 ) ).close( true );
try (IndexUpdater updater = proxy.newUpdater( IndexUpdateMode.ONLINE ) )
{
updater.process( add( 10, "foo" ) );
}
// then
assertEquals( InternalIndexState.ONLINE, proxy.getState() );
InOrder order = inOrder( populator, accessor, updater);
order.verify( populator ).create();
order.verify( populator ).close( true );
order.verify( accessor ).newUpdater( IndexUpdateMode.RECOVERY );
order.verify( updater ).process( add( 10, "foo" ) );
order.verify( updater ).close();
}
@Test
public void indexCreationShouldBeIdempotent() throws Exception
{
// given
when( accessor.newUpdater( any( IndexUpdateMode.class ) ) ).thenReturn( updater );
IndexingService indexingService = newIndexingServiceWithMockedDependencies( populator, accessor, withData() );
life.start();
// when
indexingService.createIndexes( IndexRule.indexRule( 0, index, PROVIDER_DESCRIPTOR ) );
indexingService.createIndexes( IndexRule.indexRule( 0, index, PROVIDER_DESCRIPTOR ) );
// We are asserting that the second call to createIndex does not throw an exception.
waitForIndexesToComeOnline( indexingService, 0 );
}
@SuppressWarnings( "unchecked" )
@Test
public void shouldDeliverUpdatesThatOccurDuringPopulationToPopulator() throws Exception
{
// given
when( populator.newPopulatingUpdater( storeView ) ).thenReturn( updater );
CountDownLatch latch = new CountDownLatch( 1 );
doAnswer( afterAwaiting( latch ) ).when( populator ).add( anyList() );
IndexingService indexingService =
newIndexingServiceWithMockedDependencies( populator, accessor, withData( addNodeUpdate( 1, "value1" ) ) );
life.start();
// when
indexingService.createIndexes( IndexRule.indexRule( 0, index, PROVIDER_DESCRIPTOR ) );
IndexProxy proxy = indexingService.getIndexProxy( 0 );
assertEquals( InternalIndexState.POPULATING, proxy.getState() );
IndexEntryUpdate value2 = add( 2, "value2" );
try (IndexUpdater updater = proxy.newUpdater( IndexUpdateMode.ONLINE ) )
{
updater.process( value2 );
}
latch.countDown();
waitForIndexesToComeOnline( indexingService, 0 );
verify( populator, timeout( 1000 ) ).close( true );
// then
assertEquals( InternalIndexState.ONLINE, proxy.getState() );
InOrder order = inOrder( populator, accessor, updater);
order.verify( populator ).create();
order.verify( populator ).includeSample( add( 1, "value1" ) );
order.verify( populator ).add( any( IndexEntryUpdate.class ) );
// invoked from indexAllNodes(), empty because the id we added (2) is bigger than the one we indexed (1)
//
// (We don't get an update for value2 here because we mock a fake store that doesn't contain it
// just for the purpose of testing this behavior)
order.verify( populator ).newPopulatingUpdater( storeView );
order.verify( updater ).close();
order.verify( populator ).sampleResult();
order.verify( populator ).close( true );
verifyNoMoreInteractions( updater );
verifyNoMoreInteractions( populator );
verifyZeroInteractions( accessor );
}
@Test
public void shouldStillReportInternalIndexStateAsPopulatingWhenConstraintIndexIsDonePopulating() throws Exception
{
// given
when( accessor.newUpdater( any( IndexUpdateMode.class ) ) ).thenReturn(updater);
IndexingService indexingService = newIndexingServiceWithMockedDependencies( populator, accessor, withData() );
life.start();
// when
indexingService.createIndexes( constraintIndexRule( 0, labelId, propertyKeyId, PROVIDER_DESCRIPTOR ) );
IndexProxy proxy = indexingService.getIndexProxy( 0 );
// don't wait for index to come ONLINE here since we're testing that it doesn't
verify( populator, timeout( 2000 ) ).close( true );
try (IndexUpdater updater = proxy.newUpdater( IndexUpdateMode.ONLINE ) )
{
updater.process( add( 10, "foo" ) );
}
// then
assertEquals( InternalIndexState.POPULATING, proxy.getState() );
InOrder order = inOrder( populator, accessor, updater );
order.verify( populator ).create();
order.verify( populator ).close( true );
order.verify( accessor ).newUpdater( IndexUpdateMode.ONLINE );
order.verify(updater).process( add( 10, "foo" ) );
order.verify(updater).close();
}
@Test
public void shouldBringConstraintIndexOnlineWhenExplicitlyToldTo() throws Exception
{
// given
IndexingService indexingService = newIndexingServiceWithMockedDependencies( populator, accessor, withData() );
life.start();
// when
indexingService.createIndexes( constraintIndexRule( 0, labelId, propertyKeyId, PROVIDER_DESCRIPTOR ) );
IndexProxy proxy = indexingService.getIndexProxy( 0 );
indexingService.activateIndex( 0 );
// then
assertEquals( ONLINE, proxy.getState() );
InOrder order = inOrder( populator, accessor );
order.verify( populator ).create();
order.verify( populator ).close( true );
}
@Test
public void shouldLogIndexStateOnInit() throws Exception
{
// given
SchemaIndexProvider provider = mock( SchemaIndexProvider.class );
when( provider.getProviderDescriptor() ).thenReturn( PROVIDER_DESCRIPTOR );
when( provider.getOnlineAccessor( anyLong(), any( IndexDescriptor.class ), any( IndexSamplingConfig.class ) ) )
.thenReturn( mock( IndexAccessor.class ) );
SchemaIndexProviderMap providerMap = new DefaultSchemaIndexProviderMap( provider );
TokenNameLookup mockLookup = mock( TokenNameLookup.class );
IndexRule onlineIndex = indexRule( 1, 1, 1, PROVIDER_DESCRIPTOR );
IndexRule populatingIndex = indexRule( 2, 1, 2, PROVIDER_DESCRIPTOR );
IndexRule failedIndex = indexRule( 3, 2, 2, PROVIDER_DESCRIPTOR );
life.add( IndexingServiceFactory.createIndexingService( Config.empty(), mock( JobScheduler.class ), providerMap,
mock( IndexStoreView.class ), mockLookup, asList( onlineIndex, populatingIndex, failedIndex ),
logProvider, IndexingService.NO_MONITOR, DO_NOTHING_CALLBACK ) );
when( provider.getInitialState( onlineIndex.getId(), onlineIndex.getIndexDescriptor() ) )
.thenReturn( ONLINE );
when( provider.getInitialState( populatingIndex.getId(), populatingIndex.getIndexDescriptor() ) )
.thenReturn( InternalIndexState.POPULATING );
when( provider.getInitialState( failedIndex.getId(), failedIndex.getIndexDescriptor() ) )
.thenReturn( InternalIndexState.FAILED );
when(mockLookup.labelGetName( 1 )).thenReturn( "LabelOne" );
when( mockLookup.labelGetName( 2 ) ).thenReturn( "LabelTwo" );
when( mockLookup.propertyKeyGetName( 1 ) ).thenReturn( "propertyOne" );
when( mockLookup.propertyKeyGetName( 2 ) ).thenReturn( "propertyTwo" );
// when
life.init();
// then
logProvider.assertAtLeastOnce(
logMatch.debug( "IndexingService.init: index 1 on :LabelOne(propertyOne) is ONLINE" ),
logMatch.debug( "IndexingService.init: index 2 on :LabelOne(propertyTwo) is POPULATING" ),
logMatch.debug( "IndexingService.init: index 3 on :LabelTwo(propertyTwo) is FAILED" )
);
}
@Test
public void shouldLogIndexStateOnStart() throws Exception
{
// given
SchemaIndexProvider provider = mock( SchemaIndexProvider.class );
when( provider.getProviderDescriptor() ).thenReturn( PROVIDER_DESCRIPTOR );
SchemaIndexProviderMap providerMap = new DefaultSchemaIndexProviderMap( provider );
TokenNameLookup mockLookup = mock( TokenNameLookup.class );
IndexRule onlineIndex = indexRule( 1, 1, 1, PROVIDER_DESCRIPTOR );
IndexRule populatingIndex = indexRule( 2, 1, 2, PROVIDER_DESCRIPTOR );
IndexRule failedIndex = indexRule( 3, 2, 2, PROVIDER_DESCRIPTOR );
IndexingService indexingService = IndexingServiceFactory.createIndexingService( Config.empty(),
mock( JobScheduler.class ), providerMap, storeView, mockLookup,
asList( onlineIndex, populatingIndex, failedIndex ), logProvider, IndexingService.NO_MONITOR,
DO_NOTHING_CALLBACK );
when( provider.getInitialState( onlineIndex.getId(), onlineIndex.getIndexDescriptor() ) )
.thenReturn( ONLINE );
when( provider.getInitialState( populatingIndex.getId(), populatingIndex.getIndexDescriptor() ) )
.thenReturn( InternalIndexState.POPULATING );
when( provider.getInitialState( failedIndex.getId(), failedIndex.getIndexDescriptor() ) )
.thenReturn( InternalIndexState.FAILED );
indexingService.init();
when(mockLookup.labelGetName( 1 )).thenReturn( "LabelOne" );
when(mockLookup.labelGetName( 2 )).thenReturn( "LabelTwo" );
when(mockLookup.propertyKeyGetName( 1 )).thenReturn( "propertyOne" );
when(mockLookup.propertyKeyGetName( 2 )).thenReturn( "propertyTwo" );
when( storeView.indexSample( anyLong(), any( DoubleLongRegister.class ) ) ).thenReturn( newDoubleLongRegister( 32L, 32L ) );
logProvider.clear();
// when
indexingService.start();
// then
verify( provider ).getPopulationFailure( 3 );
logProvider.assertAtLeastOnce(
logMatch.debug( "IndexingService.start: index 1 on :LabelOne(propertyOne) is ONLINE" ),
logMatch.debug( "IndexingService.start: index 2 on :LabelOne(propertyTwo) is POPULATING" ),
logMatch.debug( "IndexingService.start: index 3 on :LabelTwo(propertyTwo) is FAILED" )
);
}
@Test
public void shouldFailToStartIfMissingIndexProvider() throws Exception
{
// GIVEN an indexing service that has a schema index provider X
String otherProviderKey = "something-completely-different";
SchemaIndexProvider.Descriptor otherDescriptor = new SchemaIndexProvider.Descriptor(
otherProviderKey, "no-version" );
IndexRule rule = indexRule( 1, 2, 3, otherDescriptor );
IndexingService indexing = newIndexingServiceWithMockedDependencies(
mock( IndexPopulator.class ), mock( IndexAccessor.class ),
new DataUpdates(), rule );
// WHEN trying to start up and initialize it with an index from provider Y
try
{
life.init();
fail( "initIndexes with mismatching index provider should fail" );
}
catch ( LifecycleException e )
{ // THEN starting up should fail
assertThat( e.getCause().getMessage(), containsString( "existing index" ) );
assertThat( e.getCause().getMessage(), containsString( otherProviderKey ) );
}
}
@Test
public void shouldSnapshotOnlineIndexes() throws Exception
{
// GIVEN
int indexId = 1;
int indexId2 = 2;
IndexRule rule1 = indexRule( indexId, 2, 3, PROVIDER_DESCRIPTOR );
IndexRule rule2 = indexRule( indexId2, 4, 5, PROVIDER_DESCRIPTOR );
IndexAccessor indexAccessor = mock( IndexAccessor.class );
IndexingService indexing = newIndexingServiceWithMockedDependencies(
mock( IndexPopulator.class ), indexAccessor,
new DataUpdates( ), rule1, rule2 );
File theFile = new File( "Blah" );
when( indexAccessor.snapshotFiles()).thenAnswer( newResourceIterator( theFile ) );
when( indexProvider.getInitialState( indexId, rule1.getIndexDescriptor() ) ).thenReturn( ONLINE );
when( indexProvider.getInitialState( indexId2, rule2.getIndexDescriptor() ) ).thenReturn( ONLINE );
when( storeView.indexSample( anyLong(), any( DoubleLongRegister.class ) ) )
.thenReturn( newDoubleLongRegister( 32L, 32L ) );
life.start();
// WHEN
ResourceIterator<File> files = indexing.snapshotStoreFiles();
// THEN
// We get a snapshot per online index
assertThat( asCollection( files ), equalTo( asCollection( iterator( theFile, theFile ) ) ) );
}
@Test
public void shouldNotSnapshotPopulatingIndexes() throws Exception
{
// GIVEN
CountDownLatch populatorLatch = new CountDownLatch(1);
IndexAccessor indexAccessor = mock(IndexAccessor.class);
int indexId = 1;
int indexId2 = 2;
IndexRule rule1 = indexRule( indexId, 2, 3, PROVIDER_DESCRIPTOR );
IndexRule rule2 = indexRule( indexId2, 4, 5, PROVIDER_DESCRIPTOR );
IndexingService indexing = newIndexingServiceWithMockedDependencies(
populator, indexAccessor,
new DataUpdates(), rule1, rule2 );
File theFile = new File( "Blah" );
doAnswer( waitForLatch( populatorLatch ) ).when( populator ).create();
when( indexAccessor.snapshotFiles() ).thenAnswer( newResourceIterator( theFile ) );
when( indexProvider.getInitialState( indexId, rule1.getIndexDescriptor() ) ).thenReturn( POPULATING );
when( indexProvider.getInitialState( indexId2, rule2.getIndexDescriptor() ) ).thenReturn( ONLINE );
when( storeView.indexSample( anyLong(), any( DoubleLongRegister.class ) ) ).thenReturn( newDoubleLongRegister( 32L, 32L ) );
life.start();
// WHEN
ResourceIterator<File> files = indexing.snapshotStoreFiles();
populatorLatch.countDown(); // only now, after the snapshot, is the population job allowed to finish
waitForIndexesToComeOnline( indexing, indexId, indexId2 );
// THEN
// We get a snapshot from the online index, but no snapshot from the populating one
assertThat( asCollection( files ), equalTo( asCollection( iterator( theFile ) ) ) );
}
@Test
public void shouldIgnoreActivateCallDuringRecovery() throws Exception
{
// given
IndexingService indexingService = newIndexingServiceWithMockedDependencies( populator, accessor, withData() );
// when
indexingService.activateIndex( 0 );
// then no exception should be thrown.
}
@Test
public void shouldLogTriggerSamplingOnAllIndexes() throws Exception
{
// given
IndexingService indexingService = newIndexingServiceWithMockedDependencies( populator, accessor, withData() );
IndexSamplingMode mode = TRIGGER_REBUILD_ALL;
// when
indexingService.triggerIndexSampling( mode );
// then
logProvider.assertAtLeastOnce(
logMatch.info( "Manual trigger for sampling all indexes [" + mode + "]" )
);
}
@Test
public void shouldLogTriggerSamplingOnAnIndexes() throws Exception
{
// given
long indexId = 0;
IndexSamplingMode mode = TRIGGER_REBUILD_ALL;
IndexDescriptor descriptor = IndexDescriptorFactory.forLabel( 0, 1 );
IndexingService indexingService = newIndexingServiceWithMockedDependencies( populator, accessor, withData(),
IndexRule.indexRule( indexId, descriptor, PROVIDER_DESCRIPTOR ) );
life.init();
life.start();
// when
indexingService.triggerIndexSampling( descriptor.schema() , mode );
// then
String userDescription = descriptor.schema().userDescription( nameLookup );
logProvider.assertAtLeastOnce(
logMatch.info( "Manual trigger for sampling index " + userDescription + " [" + mode + "]" )
);
}
@Test
public void applicationOfIndexUpdatesShouldThrowIfServiceIsShutdown()
throws IOException, IndexEntryConflictException
{
// Given
IndexingService indexingService = newIndexingServiceWithMockedDependencies( populator, accessor, withData() );
life.start();
life.shutdown();
try
{
// When
indexingService.apply( updates( asSet( add( 1, "foo" ) ) ) );
fail( "Should have thrown " + IllegalStateException.class.getSimpleName() );
}
catch ( IllegalStateException e )
{
// Then
assertThat( e.getMessage(), startsWith( "Can't apply index updates" ) );
}
}
private IndexUpdates updates( Iterable<IndexEntryUpdate<LabelSchemaDescriptor>> updates )
{
return new DirectIndexUpdates( updates );
}
@Test
public void applicationOfUpdatesShouldFlush() throws Exception
{
// Given
when( accessor.newUpdater( any( IndexUpdateMode.class ) ) ).thenReturn( updater );
IndexingService indexing = newIndexingServiceWithMockedDependencies( populator, accessor, withData() );
life.start();
indexing.createIndexes( IndexRule.indexRule( 0, index, PROVIDER_DESCRIPTOR ) );
waitForIndexesToComeOnline( indexing, 0 );
verify( populator, timeout( 1000 ) ).close( true );
// When
indexing.apply( updates( asList( add( 1, "foo" ), add( 2, "bar" ) ) ) );
// Then
InOrder inOrder = inOrder( updater );
inOrder.verify( updater ).process( add( 1, "foo" ) );
inOrder.verify( updater ).process( add( 2, "bar" ) );
inOrder.verify( updater ).close();
inOrder.verifyNoMoreInteractions();
}
@Test
public void closingOfValidatedUpdatesShouldCloseUpdaters() throws Exception
{
// Given
long indexId1 = 1;
long indexId2 = 2;
int labelId1 = 24;
int labelId2 = 42;
IndexingService indexing = newIndexingServiceWithMockedDependencies( populator, accessor, withData() );
IndexAccessor accessor1 = mock( IndexAccessor.class );
IndexUpdater updater1 = mock( IndexUpdater.class );
when( accessor1.newUpdater( any( IndexUpdateMode.class ) ) ).thenReturn( updater1 );
IndexAccessor accessor2 = mock( IndexAccessor.class );
IndexUpdater updater2 = mock( IndexUpdater.class );
when( accessor2.newUpdater( any( IndexUpdateMode.class ) ) ).thenReturn( updater2 );
when( indexProvider.getOnlineAccessor( eq( 1L ), any( IndexDescriptor.class ),
any( IndexSamplingConfig.class ) ) ).thenReturn( accessor1 );
when( indexProvider.getOnlineAccessor( eq( 2L ), any( IndexDescriptor.class ),
any( IndexSamplingConfig.class ) ) ).thenReturn( accessor2 );
life.start();
indexing.createIndexes( indexRule( indexId1, labelId1, propertyKeyId, PROVIDER_DESCRIPTOR ) );
indexing.createIndexes( indexRule( indexId2, labelId2, propertyKeyId, PROVIDER_DESCRIPTOR ) );
waitForIndexesToComeOnline( indexing, indexId1, indexId2 );
verify( populator, timeout( 1000 ).times( 2 ) ).close( true );
// When
indexing.apply( updates( asList(
add( 1, "foo", labelId1 ),
add( 2, "bar", labelId2 ) ) ) );
// Then
verify( updater1 ).close();
verify( updater2 ).close();
}
private void waitForIndexesToComeOnline( IndexingService indexing, long... indexRuleIds )
throws IndexNotFoundKernelException
{
long end = currentTimeMillis() + SECONDS.toMillis( 30 );
while ( !allOnline( indexing, indexRuleIds ) )
{
if ( currentTimeMillis() > end )
{
fail( "Indexes couldn't come online" );
}
}
}
private boolean allOnline( IndexingService indexing, long[] indexRuleIds ) throws IndexNotFoundKernelException
{
for ( long indexRuleId : indexRuleIds )
{
if ( indexing.getIndexProxy( indexRuleId ).getState() != InternalIndexState.ONLINE )
{
return false;
}
}
return true;
}
@SuppressWarnings( "unchecked" )
@Test
public void recoveredUpdatesShouldBeApplied() throws Exception
{
// Given
final long nodeId1 = 1;
final long nodeId2 = 2;
final PrimitiveLongSet nodeIds = setOf( nodeId1, nodeId2 );
final NodeUpdates nodeUpdate1 = addNodeUpdate( nodeId1, "foo" );
final NodeUpdates nodeUpdate2 = addNodeUpdate( nodeId2, "bar" );
final AtomicBoolean applyingRecoveredDataCalled = new AtomicBoolean();
final AtomicBoolean recoveredUpdatesAppliedCalled = new AtomicBoolean();
// Mockito not used here because it does not work well with mutable objects (set of recovered node ids in
// this case, which is cleared at the end of recovery).
// See https://code.google.com/p/mockito/issues/detail?id=126 and
// https://groups.google.com/forum/#!topic/mockito/_A4BpsEAY9s
IndexingService.Monitor monitor = new IndexingService.MonitorAdapter()
{
private Set<IndexEntryUpdate<LabelSchemaDescriptor>> updates = new HashSet<>();
@Override
public void applyingRecoveredData( PrimitiveLongSet recoveredNodeIds )
{
assertEquals( nodeIds, recoveredNodeIds );
applyingRecoveredDataCalled.set( true );
}
@Override
public void applyingRecoveredUpdate( IndexEntryUpdate<LabelSchemaDescriptor> indexUpdate )
{
updates.add( indexUpdate );
}
@Override
public void recoveredUpdatesApplied()
{
recoveredUpdatesAppliedCalled.set( true );
assertEquals( 2, updates.size() );
}
};
IndexingService indexing = newIndexingServiceWithMockedDependencies( populator, accessor, withData(), monitor );
indexing.createIndexes( IndexRule
.indexRule( 1, IndexDescriptorFactory.forLabel( labelId, index.schema().getPropertyId() ),
new SchemaIndexProvider.Descriptor( "quantum-dex", "25.0" ) ) );
when( storeView.nodeAsUpdates( eq( nodeId1 ) ) ).thenReturn( nodeUpdate1 );
when( storeView.nodeAsUpdates( eq( nodeId2 ) ) ).thenReturn( nodeUpdate2 );
// When
life.init();
IndexUpdates updates = nodeIdsAsIndexUpdates( nodeIds );
indexing.apply( updates );
life.start();
// Then
assertTrue( "applyingRecoveredData was not called", applyingRecoveredDataCalled.get() );
assertTrue( "recoveredUpdatesApplied was not called", recoveredUpdatesAppliedCalled.get() );
}
private IndexUpdates nodeIdsAsIndexUpdates( PrimitiveLongSet nodeIds )
{
return new IndexUpdates()
{
@Override
public Iterator<IndexEntryUpdate<LabelSchemaDescriptor>> iterator()
{
throw new UnsupportedOperationException();
}
@Override
public void collectUpdatedNodeIds( final PrimitiveLongSet target )
{
target.addAll( nodeIds.iterator() );
}
@Override
public void feed( PrimitiveLongObjectMap<List<PropertyCommand>> propCommands,
PrimitiveLongObjectMap<NodeCommand> nodeCommands )
{
throw new UnsupportedOperationException();
}
@Override
public boolean hasUpdates()
{
return !nodeIds.isEmpty();
}
};
}
/*
* See comments in IndexingService#createIndex
*/
@SuppressWarnings( "unchecked" )
@Test
public void shouldNotLoseIndexDescriptorDueToOtherSimilarIndexDuringRecovery() throws Exception
{
// GIVEN
long nodeId = 0, indexId = 1, otherIndexId = 2;
NodeUpdates update = addNodeUpdate( nodeId, "value" );
when( storeView.nodeAsUpdates( eq( nodeId ) ) ).thenReturn( update );
DoubleLongRegister register = mock( DoubleLongRegister.class );
when( register.readSecond() ).thenReturn( 42L );
when( storeView.indexSample( anyLong(), any( DoubleLongRegister.class ) ) )
.thenReturn( register );
// For some reason the usual accessor returned null from newUpdater, even when told to return the updater
// so spying on a real object instead.
IndexAccessor accessor = spy( new TrackingIndexAccessor() );
IndexRule index = IndexRule.indexRule( 1, this.index, PROVIDER_DESCRIPTOR );
IndexingService indexing = newIndexingServiceWithMockedDependencies(
populator, accessor, withData( update ), index
);
when( indexProvider.getInitialState( indexId, index.getIndexDescriptor() ) ).thenReturn( ONLINE );
life.init();
// WHEN dropping another index, which happens to have the same label/property... while recovering
IndexRule otherIndex = IndexRule.indexRule( otherIndexId, index.getIndexDescriptor(), PROVIDER_DESCRIPTOR );
indexing.createIndexes( otherIndex );
indexing.dropIndex( otherIndex );
indexing.apply( nodeIdsAsIndexUpdates( PrimitiveLongCollections.asSet(
PrimitiveLongCollections.iterator( nodeId ) ) ) );
// and WHEN finally creating our index again (at a later point in recovery)
indexing.createIndexes( index );
reset( accessor );
// and WHEN starting, i.e. completing recovery
life.start();
verify( accessor ).newUpdater( RECOVERY );
}
@Test
public void shouldWaitForRecoveredUniquenessConstraintIndexesToBeFullyPopulated() throws Exception
{
// I.e. when a uniqueness constraint is created, but database crashes before that schema record
// ends up in the store, so that next start have no choice but to rebuild it.
// GIVEN
final DoubleLatch latch = new DoubleLatch();
ControlledIndexPopulator populator = new ControlledIndexPopulator( latch );
final AtomicLong indexId = new AtomicLong( -1 );
IndexingService.Monitor monitor = new IndexingService.MonitorAdapter()
{
@Override
public void awaitingPopulationOfRecoveredIndex( long index, IndexDescriptor descriptor )
{
// When we see that we start to await the index to populate, notify the slow-as-heck
// populator that it can actually go and complete its job.
indexId.set( index );
latch.startAndWaitForAllToStart();
}
};
// leaving out the IndexRule here will have the index being populated from scratch
IndexingService indexing = newIndexingServiceWithMockedDependencies( populator, accessor,
withData( addNodeUpdate( 0, "value", 1 ) ), monitor );
// WHEN initializing, i.e. preparing for recovery
life.init();
// simulating an index being created as part of applying recovered transactions
long fakeOwningConstraintRuleId = 1;
indexing.createIndexes( constraintIndexRule( 2, labelId, propertyKeyId, PROVIDER_DESCRIPTOR,
fakeOwningConstraintRuleId ) );
// and then starting, i.e. considering recovery completed
life.start();
// THEN afterwards the index should be ONLINE
assertEquals( 2, indexId.get() );
assertEquals( ONLINE, indexing.getIndexProxy( indexId.get() ).getState() );
}
@Test
public void shouldCreateMultipleIndexesInOneCall() throws Exception
{
// GIVEN
IndexingService.Monitor monitor = IndexingService.NO_MONITOR;
IndexingService indexing = newIndexingServiceWithMockedDependencies( populator, accessor,
withData( addNodeUpdate( 0, "value", 1 ) ), monitor );
life.start();
// WHEN
IndexRule indexRule1 = indexRule( 0, 0, 0, PROVIDER_DESCRIPTOR );
IndexRule indexRule2 = indexRule( 1, 0, 1, PROVIDER_DESCRIPTOR );
IndexRule indexRule3 = indexRule( 2, 1, 0, PROVIDER_DESCRIPTOR );
indexing.createIndexes( indexRule1, indexRule2, indexRule3 );
// THEN
verify( indexProvider ).getPopulator( eq( 0L ), eq( IndexDescriptorFactory.forLabel( 0, 0 ) ),
any( IndexSamplingConfig.class ) );
verify( indexProvider ).getPopulator( eq( 1L ), eq( IndexDescriptorFactory.forLabel( 0, 1 ) ),
any( IndexSamplingConfig.class ) );
verify( indexProvider ).getPopulator( eq( 2L ), eq( IndexDescriptorFactory.forLabel( 1, 0 ) ),
any( IndexSamplingConfig.class ) );
waitForIndexesToComeOnline( indexing, 0, 1, 2 );
}
@Test
public void shouldStoreIndexFailureWhenFailingToCreateOnlineAccessorAfterPopulating() throws Exception
{
// given
long indexId = 1;
IndexingService indexing = newIndexingServiceWithMockedDependencies( populator, accessor, withData() );
IOException exception = new IOException( "Expected failure" );
when( nameLookup.labelGetName( labelId ) ).thenReturn( "TheLabel" );
when( nameLookup.propertyKeyGetName( propertyKeyId ) ).thenReturn( "propertyKey" );
when( indexProvider.getOnlineAccessor(
eq( indexId ), any( IndexDescriptor.class ), any( IndexSamplingConfig.class ) ) )
.thenThrow( exception );
life.start();
ArgumentCaptor<Boolean> closeArgs = ArgumentCaptor.forClass( Boolean.class );
// when
indexing.createIndexes( IndexRule.indexRule( indexId, index, PROVIDER_DESCRIPTOR ) );
verify( populator, timeout( 1000 ).times( 2 ) ).close( closeArgs.capture() );
// then
assertEquals( FAILED, indexing.getIndexProxy( 1 ).getState() );
assertEquals( asList( true, false ), closeArgs.getAllValues() );
assertThat( storedFailure(), containsString( format( "java.io.IOException: Expected failure%n\tat " ) ) );
logProvider.assertAtLeastOnce( inLog( IndexPopulationJob.class ).error( equalTo(
"Failed to populate index: [:TheLabel(propertyKey) [provider: {key=quantum-dex, version=25.0}]]" ),
causedBy( exception ) ) );
logProvider.assertNone( inLog( IndexPopulationJob.class ).info(
"Index population completed. Index is now online: [%s]",
":TheLabel(propertyKey) [provider: {key=quantum-dex, version=25.0}]" ) );
}
@Test
public void shouldStoreIndexFailureWhenFailingToCreateOnlineAccessorAfterRecoveringPopulatingIndex() throws Exception
{
// given
long indexId = 1;
IndexRule indexRule = IndexRule.indexRule( indexId, index, PROVIDER_DESCRIPTOR );
IndexingService indexing = newIndexingServiceWithMockedDependencies( populator, accessor, withData(), indexRule );
IOException exception = new IOException( "Expected failure" );
when( nameLookup.labelGetName( labelId ) ).thenReturn( "TheLabel" );
when( nameLookup.propertyKeyGetName( propertyKeyId ) ).thenReturn( "propertyKey" );
when( indexProvider.getInitialState( indexId, indexRule.getIndexDescriptor() ) ).thenReturn( POPULATING );
when( indexProvider.getOnlineAccessor(
eq( indexId ), any( IndexDescriptor.class ), any( IndexSamplingConfig.class ) ) )
.thenThrow( exception );
life.start();
ArgumentCaptor<Boolean> closeArgs = ArgumentCaptor.forClass( Boolean.class );
// when
verify( populator, timeout( 1000 ).times( 2 ) ).close( closeArgs.capture() );
// then
assertEquals( FAILED, indexing.getIndexProxy( 1 ).getState() );
assertEquals( asList( true, false ), closeArgs.getAllValues() );
assertThat( storedFailure(), containsString( format( "java.io.IOException: Expected failure%n\tat " ) ) );
logProvider.assertAtLeastOnce( inLog( IndexPopulationJob.class ).error( equalTo(
"Failed to populate index: [:TheLabel(propertyKey) [provider: {key=quantum-dex, version=25.0}]]" ),
causedBy( exception ) ) );
logProvider.assertNone( inLog( IndexPopulationJob.class ).info(
"Index population completed. Index is now online: [%s]",
":TheLabel(propertyKey) [provider: {key=quantum-dex, version=25.0}]" ) );
}
@Test
public void shouldLogIndexStateOutliersOnInit() throws Exception
{
// given
SchemaIndexProvider provider = mock( SchemaIndexProvider.class );
when( provider.getProviderDescriptor() ).thenReturn( PROVIDER_DESCRIPTOR );
when( provider.getOnlineAccessor( anyLong(), any( IndexDescriptor.class ), any( IndexSamplingConfig.class ) ) )
.thenReturn( mock( IndexAccessor.class ) );
SchemaIndexProviderMap providerMap = new DefaultSchemaIndexProviderMap( provider );
TokenNameLookup mockLookup = mock( TokenNameLookup.class );
List<IndexRule> indexes = new ArrayList<>();
int nextIndexId = 1;
IndexRule populatingIndex = indexRule( nextIndexId, nextIndexId++, 1, PROVIDER_DESCRIPTOR );
when( provider.getInitialState( populatingIndex.getId(), populatingIndex.getIndexDescriptor() ) ).thenReturn( POPULATING );
indexes.add( populatingIndex );
IndexRule failedIndex = indexRule( nextIndexId, nextIndexId++, 1, PROVIDER_DESCRIPTOR );
when( provider.getInitialState( failedIndex.getId(), failedIndex.getIndexDescriptor() ) ).thenReturn( FAILED );
indexes.add( failedIndex );
for ( int i = 0; i < 10; i++ )
{
IndexRule indexRule = indexRule( nextIndexId, nextIndexId++, 1, PROVIDER_DESCRIPTOR );
when( provider.getInitialState( indexRule.getId(), indexRule.getIndexDescriptor() ) ).thenReturn( ONLINE );
indexes.add( indexRule );
}
for ( int i = 0; i < nextIndexId; i++ )
{
when( mockLookup.labelGetName( i ) ).thenReturn( "Label" + i );
}
life.add( IndexingServiceFactory.createIndexingService( Config.empty(), mock( JobScheduler.class ), providerMap,
mock( IndexStoreView.class ), mockLookup, indexes,
logProvider, IndexingService.NO_MONITOR, DO_NOTHING_CALLBACK ) );
when( mockLookup.propertyKeyGetName( 1 ) ).thenReturn( "prop" );
// when
life.init();
// then
logProvider.assertAtLeastOnce(
logMatch.info( "IndexingService.init: index 1 on :Label1(prop) is POPULATING" ),
logMatch.info( "IndexingService.init: index 2 on :Label2(prop) is FAILED" ),
logMatch.info( "IndexingService.init: indexes not specifically mentioned above are ONLINE" )
);
logProvider.assertNone( logMatch.info( "IndexingService.init: index 3 on :Label3(prop) is ONLINE" ) );
}
@Test
public void shouldLogIndexStateOutliersOnStart() throws Exception
{
// given
SchemaIndexProvider provider = mock( SchemaIndexProvider.class );
when( provider.getProviderDescriptor() ).thenReturn( PROVIDER_DESCRIPTOR );
when( provider.getOnlineAccessor( anyLong(), any( IndexDescriptor.class ), any( IndexSamplingConfig.class ) ) )
.thenReturn( mock( IndexAccessor.class ) );