forked from apache/lucenenet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestControlledRealTimeReopenThread.cs
More file actions
1031 lines (899 loc) · 41.4 KB
/
Copy pathTestControlledRealTimeReopenThread.cs
File metadata and controls
1031 lines (899 loc) · 41.4 KB
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
using J2N.Threading;
using J2N.Threading.Atomic;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Store;
using Lucene.Net.Support.Threading;
using Lucene.Net.Util;
using NUnit.Framework;
using RandomizedTesting.Generators;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using JCG = J2N.Collections.Generic;
using Assert = Lucene.Net.TestFramework.Assert;
using Lucene.Net.Attributes;
namespace Lucene.Net.Search
{
/*
* 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.
*/
using Analyzer = Lucene.Net.Analysis.Analyzer;
using Directory = Lucene.Net.Store.Directory;
using DirectoryReader = Lucene.Net.Index.DirectoryReader;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using IIndexableField = Lucene.Net.Index.IIndexableField;
using IndexCommit = Lucene.Net.Index.IndexCommit;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using IndexWriterConfig = Lucene.Net.Index.IndexWriterConfig;
using IOUtils = Lucene.Net.Util.IOUtils;
using KeepOnlyLastCommitDeletionPolicy = Lucene.Net.Index.KeepOnlyLastCommitDeletionPolicy;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using NoMergePolicy = Lucene.Net.Index.NoMergePolicy;
using NRTCachingDirectory = Lucene.Net.Store.NRTCachingDirectory;
using OpenMode = Lucene.Net.Index.OpenMode;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using SnapshotDeletionPolicy = Lucene.Net.Index.SnapshotDeletionPolicy;
using Term = Lucene.Net.Index.Term;
using TextField = Lucene.Net.Documents.TextField;
using ThreadedIndexingAndSearchingTestCase = Lucene.Net.Index.ThreadedIndexingAndSearchingTestCase;
using TrackingIndexWriter = Lucene.Net.Index.TrackingIndexWriter;
using Version = Lucene.Net.Util.LuceneVersion;
[SuppressCodecs("SimpleText", "Memory", "Direct")]
[TestFixture]
public class TestControlledRealTimeReopenThread : ThreadedIndexingAndSearchingTestCase
{
// Not guaranteed to reflect deletes:
private SearcherManager nrtNoDeletes;
// Is guaranteed to reflect deletes:
private SearcherManager nrtDeletes;
private TrackingIndexWriter genWriter;
private ControlledRealTimeReopenThread<IndexSearcher> nrtDeletesThread;
private ControlledRealTimeReopenThread<IndexSearcher> nrtNoDeletesThread;
private readonly DisposableThreadLocal<long?> lastGens = new DisposableThreadLocal<long?>();
private bool warmCalled;
// LUCENENET specific - cleanup DisposableThreadLocal instances
public override void OneTimeTearDown()
{
lastGens.Dispose();
base.OneTimeTearDown();
}
[Test]
[Slow]
public virtual void TestControlledRealTimeReopenThread_Mem()
{
RunTest("TestControlledRealTimeReopenThread");
}
protected override IndexSearcher GetFinalSearcher()
{
if (Verbose)
{
Console.WriteLine("TEST: finalSearcher maxGen=" + maxGen);
}
nrtDeletesThread.WaitForGeneration(maxGen);
return nrtDeletes.Acquire();
}
protected override Directory GetDirectory(Directory @in)
{
// Randomly swap in NRTCachingDir
if (Random.NextBoolean())
{
if (Verbose)
{
Console.WriteLine("TEST: wrap NRTCachingDir");
}
return new NRTCachingDirectory(@in, 5.0, 60.0);
}
else
{
return @in;
}
}
protected override void UpdateDocuments(Term id, IEnumerable<IEnumerable<IIndexableField>> docs)
{
long gen = genWriter.UpdateDocuments(id, docs);
// Randomly verify the update "took":
if (Random.Next(20) == 2)
{
if (Verbose)
{
Console.WriteLine(Thread.CurrentThread.Name + ": nrt: verify " + id);
}
nrtDeletesThread.WaitForGeneration(gen);
IndexSearcher s = nrtDeletes.Acquire();
if (Verbose)
{
Console.WriteLine(Thread.CurrentThread.Name + ": nrt: got searcher=" + s);
}
try
{
assertEquals(docs.Count(), s.Search(new TermQuery(id), 10).TotalHits);
}
finally
{
nrtDeletes.Release(s);
}
}
lastGens.Value = gen;
}
protected override void AddDocuments(Term id, IEnumerable<IEnumerable<IIndexableField>> docs)
{
long gen = genWriter.AddDocuments(docs);
// Randomly verify the add "took":
if (Random.Next(20) == 2)
{
if (Verbose)
{
Console.WriteLine(Thread.CurrentThread.Name + ": nrt: verify " + id);
}
nrtNoDeletesThread.WaitForGeneration(gen);
IndexSearcher s = nrtNoDeletes.Acquire();
if (Verbose)
{
Console.WriteLine(Thread.CurrentThread.Name + ": nrt: got searcher=" + s);
}
try
{
assertEquals(docs.Count(), s.Search(new TermQuery(id), 10).TotalHits);
}
finally
{
nrtNoDeletes.Release(s);
}
}
lastGens.Value = gen;
}
protected override void AddDocument(Term id, IEnumerable<IIndexableField> doc)
{
long gen = genWriter.AddDocument(doc);
// Randomly verify the add "took":
if (Random.Next(20) == 2)
{
if (Verbose)
{
Console.WriteLine(Thread.CurrentThread.Name + ": nrt: verify " + id);
}
nrtNoDeletesThread.WaitForGeneration(gen);
IndexSearcher s = nrtNoDeletes.Acquire();
if (Verbose)
{
Console.WriteLine(Thread.CurrentThread.Name + ": nrt: got searcher=" + s);
}
try
{
assertEquals(1, s.Search(new TermQuery(id), 10).TotalHits);
}
finally
{
nrtNoDeletes.Release(s);
}
}
lastGens.Value = gen;
}
protected override void UpdateDocument(Term id, IEnumerable<IIndexableField> doc)
{
long gen = genWriter.UpdateDocument(id, doc);
// Randomly verify the update "took":
if (Random.Next(20) == 2)
{
if (Verbose)
{
Console.WriteLine(Thread.CurrentThread.Name + ": nrt: verify " + id);
}
nrtDeletesThread.WaitForGeneration(gen);
IndexSearcher s = nrtDeletes.Acquire();
if (Verbose)
{
Console.WriteLine(Thread.CurrentThread.Name + ": nrt: got searcher=" + s);
}
try
{
assertEquals(1, s.Search(new TermQuery(id), 10).TotalHits);
}
finally
{
nrtDeletes.Release(s);
}
}
lastGens.Value = gen;
}
protected override void DeleteDocuments(Term id)
{
long gen = genWriter.DeleteDocuments(id);
// randomly verify the delete "took":
if (Random.Next(20) == 7)
{
if (Verbose)
{
Console.WriteLine(Thread.CurrentThread.Name + ": nrt: verify del " + id);
}
nrtDeletesThread.WaitForGeneration(gen);
IndexSearcher s = nrtDeletes.Acquire();
if (Verbose)
{
Console.WriteLine(Thread.CurrentThread.Name + ": nrt: got searcher=" + s);
}
try
{
assertEquals(0, s.Search(new TermQuery(id), 10).TotalHits);
}
finally
{
nrtDeletes.Release(s);
}
}
lastGens.Value = gen;
}
protected override void DoAfterWriter(TaskScheduler es)
{
double minReopenSec = 0.01 + 0.05 * Random.NextDouble();
double maxReopenSec = minReopenSec * (1.0 + 10 * Random.NextDouble());
if (Verbose)
{
Console.WriteLine("TEST: make SearcherManager maxReopenSec=" + maxReopenSec + " minReopenSec=" + minReopenSec);
}
genWriter = new TrackingIndexWriter(m_writer);
SearcherFactory sf = new SearcherFactoryAnonymousClass(this, es);
nrtNoDeletes = new SearcherManager(m_writer, false, sf);
nrtDeletes = new SearcherManager(m_writer, true, sf);
nrtDeletesThread = new ControlledRealTimeReopenThread<IndexSearcher>(genWriter, nrtDeletes, maxReopenSec, minReopenSec);
nrtDeletesThread.Name = "NRTDeletes Reopen Thread";
nrtDeletesThread.Priority = (ThreadPriority)Math.Min((int)Thread.CurrentThread.Priority + 2, (int)ThreadPriority.Highest);
nrtDeletesThread.IsBackground = (true);
nrtDeletesThread.Start();
nrtNoDeletesThread = new ControlledRealTimeReopenThread<IndexSearcher>(genWriter, nrtNoDeletes, maxReopenSec, minReopenSec);
nrtNoDeletesThread.Name = "NRTNoDeletes Reopen Thread";
nrtNoDeletesThread.Priority = (ThreadPriority)Math.Min((int)Thread.CurrentThread.Priority + 2, (int)ThreadPriority.Highest);
nrtNoDeletesThread.IsBackground = (true);
nrtNoDeletesThread.Start();
}
private sealed class SearcherFactoryAnonymousClass : SearcherFactory
{
private readonly TestControlledRealTimeReopenThread outerInstance;
private readonly TaskScheduler es;
public SearcherFactoryAnonymousClass(TestControlledRealTimeReopenThread outerInstance, TaskScheduler es)
{
this.outerInstance = outerInstance;
this.es = es;
}
public override IndexSearcher NewSearcher(IndexReader r)
{
outerInstance.warmCalled = true;
IndexSearcher s = new IndexSearcher(r, es);
s.Search(new TermQuery(new Term("body", "united")), 10);
return s;
}
}
protected override void DoAfterIndexingThreadDone()
{
long? gen = lastGens.Value;
if (gen != null)
{
AddMaxGen((long)gen);
}
}
private long maxGen = -1;
private void AddMaxGen(long gen)
{
UninterruptableMonitor.Enter(this);
try
{
maxGen = Math.Max(gen, maxGen);
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
protected override void DoSearching(TaskScheduler es, long stopTime)
{
RunSearchThreads(stopTime);
}
protected override IndexSearcher GetCurrentSearcher()
{
// Test doesn't assert deletions until the end, so we
// can randomize whether dels must be applied
SearcherManager nrt;
if (Random.NextBoolean())
{
nrt = nrtDeletes;
}
else
{
nrt = nrtNoDeletes;
}
return nrt.Acquire();
}
protected override void ReleaseSearcher(IndexSearcher s)
{
// NOTE: a bit iffy... technically you should release
// against the same SearcherManager you acquired from... but
// both impls just decRef the underlying reader so we
// can get away w/ cheating:
nrtNoDeletes.Release(s);
}
protected override void DoClose()
{
Assert.IsTrue(warmCalled);
if (Verbose)
{
Console.WriteLine("TEST: now close SearcherManagers");
}
nrtDeletesThread.Dispose();
nrtDeletes.Dispose();
nrtNoDeletesThread.Dispose();
nrtNoDeletes.Dispose();
}
/*
* LUCENE-3528 - NRTManager hangs in certain situations
*/
[Test]
public virtual void TestThreadStarvationNoDeleteNRTReader()
{
IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random));
conf.SetMergePolicy(Random.NextBoolean() ? NoMergePolicy.COMPOUND_FILES : NoMergePolicy.NO_COMPOUND_FILES);
Directory d = NewDirectory();
CountdownEvent latch = new CountdownEvent(1);
CountdownEvent signal = new CountdownEvent(1);
LatchedIndexWriter _writer = new LatchedIndexWriter(d, conf, latch, signal);
TrackingIndexWriter writer = new TrackingIndexWriter(_writer);
SearcherManager manager = new SearcherManager(_writer, false, null);
Document doc = new Document();
doc.Add(NewTextField("test", "test", Field.Store.YES));
writer.AddDocument(doc);
manager.MaybeRefresh();
var t = new ThreadAnonymousClass(latch, signal, writer, manager);
t.Start();
_writer.waitAfterUpdate = true; // wait in addDocument to let some reopens go through
long lastGen = writer.UpdateDocument(new Term("foo", "bar"), doc); // once this returns the doc is already reflected in the last reopen
assertFalse(manager.IsSearcherCurrent()); // false since there is a delete in the queue
IndexSearcher searcher = manager.Acquire();
try
{
assertEquals(2, searcher.IndexReader.NumDocs);
}
finally
{
manager.Release(searcher);
}
ControlledRealTimeReopenThread<IndexSearcher> thread = new ControlledRealTimeReopenThread<IndexSearcher>(writer, manager, 0.01, 0.01);
thread.Start(); // start reopening
if (Verbose)
{
Console.WriteLine("waiting now for generation " + lastGen);
}
AtomicBoolean finished = new AtomicBoolean(false);
var waiter = new ThreadAnonymousClass2(lastGen, thread, finished);
waiter.Start();
manager.MaybeRefresh();
waiter.Join(1000);
if (!finished)
{
waiter.Interrupt();
fail("thread deadlocked on waitForGeneration");
}
thread.Dispose();
thread.Join();
IOUtils.Dispose(manager, _writer, d);
}
private sealed class ThreadAnonymousClass : ThreadJob
{
private readonly CountdownEvent latch;
private readonly CountdownEvent signal;
private readonly TrackingIndexWriter writer;
private readonly SearcherManager manager;
public ThreadAnonymousClass(CountdownEvent latch, CountdownEvent signal, TrackingIndexWriter writer, SearcherManager manager)
{
this.latch = latch;
this.signal = signal;
this.writer = writer;
this.manager = manager;
}
public override void Run()
{
try
{
signal.Wait();
manager.MaybeRefresh();
writer.DeleteDocuments(new TermQuery(new Term("foo", "barista")));
manager.MaybeRefresh(); // kick off another reopen so we inc. the internal gen
}
catch (Exception e) when (e.IsException())
{
e.PrintStackTrace();
}
finally
{
latch.Reset(latch.CurrentCount == 0 ? 0 : latch.CurrentCount - 1); // let the add below finish
}
}
}
private sealed class ThreadAnonymousClass2 : ThreadJob
{
private readonly long lastGen;
private readonly ControlledRealTimeReopenThread<IndexSearcher> thread;
private readonly AtomicBoolean finished;
public ThreadAnonymousClass2(long lastGen, ControlledRealTimeReopenThread<IndexSearcher> thread, AtomicBoolean finished)
{
this.lastGen = lastGen;
this.thread = thread;
this.finished = finished;
}
public override void Run()
{
try
{
thread.WaitForGeneration(lastGen);
}
catch (Exception ie) when (ie.IsInterruptedException())
{
Thread.CurrentThread.Interrupt();
throw RuntimeException.Create(ie);
}
finished.Value = true;
}
}
public class LatchedIndexWriter : IndexWriter
{
internal CountdownEvent latch;
internal bool waitAfterUpdate = false;
internal CountdownEvent signal;
public LatchedIndexWriter(Directory d, IndexWriterConfig conf, CountdownEvent latch, CountdownEvent signal)
: base(d, conf)
{
this.latch = latch;
this.signal = signal;
}
public override void UpdateDocument(Term term, IEnumerable<IIndexableField> doc, Analyzer analyzer)
{
base.UpdateDocument(term, doc, analyzer);
try
{
if (waitAfterUpdate)
{
signal.Reset(signal.CurrentCount == 0 ? 0 : signal.CurrentCount - 1);
latch.Wait();
}
}
catch (Exception ie) when (ie.IsInterruptedException())
{
throw new Util.ThreadInterruptedException(ie);
}
}
}
[Test]
public virtual void TestEvilSearcherFactory()
{
Directory dir = NewDirectory();
RandomIndexWriter w = new RandomIndexWriter(Random, dir);
w.Commit();
IndexReader other = DirectoryReader.Open(dir);
SearcherFactory theEvilOne = new SearcherFactoryAnonymousClass2(other);
try
{
_ = new SearcherManager(w.IndexWriter, false, theEvilOne); // LUCENENET: discard result of constructor
fail("didn't hit expected exception");
}
catch (Exception ise) when (ise.IsIllegalStateException())
{
// expected
}
w.Dispose();
other.Dispose();
dir.Dispose();
}
private sealed class SearcherFactoryAnonymousClass2 : SearcherFactory
{
private readonly IndexReader other;
public SearcherFactoryAnonymousClass2(IndexReader other)
{
this.other = other;
}
public override IndexSearcher NewSearcher(IndexReader ignored)
{
return LuceneTestCase.NewSearcher(other);
}
}
[Test]
public virtual void TestListenerCalled()
{
Directory dir = NewDirectory();
IndexWriter iw = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, null));
AtomicBoolean afterRefreshCalled = new AtomicBoolean(false);
SearcherManager sm = new SearcherManager(iw, true, new SearcherFactory());
sm.AddListener(new RefreshListenerAnonymousClass(afterRefreshCalled));
iw.AddDocument(new Document());
iw.Commit();
assertFalse(afterRefreshCalled);
sm.MaybeRefreshBlocking();
assertTrue(afterRefreshCalled);
sm.Dispose();
iw.Dispose();
dir.Dispose();
}
private sealed class RefreshListenerAnonymousClass : ReferenceManager.IRefreshListener
{
private readonly AtomicBoolean afterRefreshCalled;
public RefreshListenerAnonymousClass(AtomicBoolean afterRefreshCalled)
{
this.afterRefreshCalled = afterRefreshCalled;
}
public void BeforeRefresh()
{
}
public void AfterRefresh(bool didRefresh)
{
if (didRefresh)
{
afterRefreshCalled.Value = true;
}
}
}
// LUCENE-5461
[Test]
public virtual void TestCRTReopen()
{
//test behaving badly
//should be high enough
int maxStaleSecs = 20;
//build crap data just to store it.
string s = " abcdefghijklmnopqrstuvwxyz ";
char[] chars = s.ToCharArray();
StringBuilder builder = new StringBuilder(2048);
for (int i = 0; i < 2048; i++)
{
builder.Append(chars[Random.Next(chars.Length)]);
}
string content = builder.ToString();
SnapshotDeletionPolicy sdp = new SnapshotDeletionPolicy(new KeepOnlyLastCommitDeletionPolicy());
Directory dir = new NRTCachingDirectory(NewFSDirectory(CreateTempDir("nrt")), 5, 128);
IndexWriterConfig config = new IndexWriterConfig(
#pragma warning disable 612, 618
Version.LUCENE_46,
#pragma warning restore 612, 618
new MockAnalyzer(Random));
config.SetIndexDeletionPolicy(sdp);
config.SetOpenMode(OpenMode.CREATE_OR_APPEND);
IndexWriter iw = new IndexWriter(dir, config);
SearcherManager sm = new SearcherManager(iw, true, new SearcherFactory());
TrackingIndexWriter tiw = new TrackingIndexWriter(iw);
ControlledRealTimeReopenThread<IndexSearcher> controlledRealTimeReopenThread =
new ControlledRealTimeReopenThread<IndexSearcher>(tiw, sm, maxStaleSecs, 0);
controlledRealTimeReopenThread.IsBackground = true;
controlledRealTimeReopenThread.Start();
IList<ThreadJob> commitThreads = new JCG.List<ThreadJob>();
for (int i = 0; i < 500; i++)
{
if (i > 0 && i % 50 == 0)
{
ThreadJob commitThread = new RunnableAnonymousClass(sdp, dir, iw);
commitThread.Start();
commitThreads.Add(commitThread);
}
Document d = new Document();
d.Add(new TextField("count", i + "", Field.Store.NO));
d.Add(new TextField("content", content, Field.Store.YES));
long start = J2N.Time.NanoTime() / J2N.Time.MillisecondsPerNanosecond; // LUCENENET: Use NanoTime() rather than CurrentTimeMilliseconds() for more accurate/reliable results
long l = tiw.AddDocument(d);
controlledRealTimeReopenThread.WaitForGeneration(l);
long wait = (J2N.Time.NanoTime() / J2N.Time.MillisecondsPerNanosecond) - start; // LUCENENET: Use NanoTime() rather than CurrentTimeMilliseconds() for more accurate/reliable results
assertTrue("waited too long for generation " + wait, wait < (maxStaleSecs * 1000));
IndexSearcher searcher = sm.Acquire();
TopDocs td = searcher.Search(new TermQuery(new Term("count", i + "")), 10);
sm.Release(searcher);
assertEquals(1, td.TotalHits);
}
foreach (ThreadJob commitThread in commitThreads)
{
commitThread.Join();
}
controlledRealTimeReopenThread.Dispose();
sm.Dispose();
iw.Dispose();
dir.Dispose();
}
private sealed class RunnableAnonymousClass : ThreadJob
{
private readonly SnapshotDeletionPolicy sdp;
private readonly Directory dir;
private readonly IndexWriter iw;
public RunnableAnonymousClass(SnapshotDeletionPolicy sdp, Directory dir, IndexWriter iw)
{
this.sdp = sdp;
this.dir = dir;
this.iw = iw;
}
public override void Run()
{
try
{
iw.Commit();
IndexCommit ic = sdp.Snapshot();
foreach (string name in ic.FileNames)
{
//distribute, and backup
//System.out.println(names);
assertTrue(SlowFileExists(dir, name));
}
}
catch (Exception e) when (e.IsException())
{
throw RuntimeException.Create(e);
}
}
}
/// <summary>
/// This test was purposely written in a way that demonstrates how to use the
/// ControlledRealTimeReopenThread. It contains separate Asserts for each of
/// several use cases rather then trying to brake these use cases up into
/// separate unit tests. This combined approach makes the behavior of
/// ControlledRealTimeReopenThread easier to understand.
/// </summary>
// LUCENENET specific - An extra test to demonstrate use of ControlledRealTimeReopen.
[Test]
[LuceneNetSpecific]
[Ignore("Run Manually (contains timing code that doesn't play well with other tests)")]
public void TestStraightForwardDemonstration()
{
RAMDirectory indexDir = new RAMDirectory();
Analyzer standardAnalyzer = new StandardAnalyzer(TEST_VERSION_CURRENT);
IndexWriterConfig indexConfig = new IndexWriterConfig(TEST_VERSION_CURRENT, standardAnalyzer);
IndexWriter indexWriter = new IndexWriter(indexDir, indexConfig);
TrackingIndexWriter trackingWriter = new TrackingIndexWriter(indexWriter);
Document doc = new Document();
doc.Add(new Int32Field("id", 1, Field.Store.YES));
doc.Add(new StringField("name", "Doc1", Field.Store.YES));
trackingWriter.AddDocument(doc);
SearcherManager searcherManager = new SearcherManager(indexWriter, applyAllDeletes: true, null);
//Reopen SearcherManager every 1 secs via background thread if no thread waiting for newer generation.
//Reopen SearcherManager after .2 secs if another thread IS waiting on a newer generation.
var controlledRealTimeReopenThread = new ControlledRealTimeReopenThread<IndexSearcher>(trackingWriter, searcherManager, 1, 0.2);
//Start() will start a separate thread that will invoke the object's Run(). However,
//calling Run() directly would execute that code on the current thread rather then a new thread
//which would defeat the purpose of using controlledRealTimeReopenThread. This aspect of the API
//is not as intuitive as it could be. ie. Call Start() not Run().
controlledRealTimeReopenThread.IsBackground = true; //Set as a background thread
controlledRealTimeReopenThread.Name = "Controlled Real Time Reopen Thread";
controlledRealTimeReopenThread.Priority = (ThreadPriority)Math.Min((int)Thread.CurrentThread.Priority + 2, (int)ThreadPriority.Highest);
controlledRealTimeReopenThread.Start();
//An indexSearcher only sees Doc1
// In Java, to obtain a threadsafe IndexSearcher reference, the following pattern could
// be used. This also works in .NET.
//IndexSearcher indexSearcher = searcherManager.Acquire();
//try
//{
// TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1);
// assertEquals(1, topDocs.TotalHits); //There is only one doc
//}
//finally
//{
// searcherManager.Release(indexSearcher);
//}
// However, in .NET it can be done like this with less code. We get an instance of
// ReferenceContext<IndexSearcher> in a using block so the call to searcherManager.Release()
// happens implicitly. ReferenceContext<IndexSearcher> is a ref struct so it doesn't allocate
// on the heap and will be deallocated at the end of this block automatically.
using (var context = searcherManager.GetContext())
{
IndexSearcher indexSearcher = context.Reference;
TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1);
assertEquals(1, topDocs.TotalHits); //There is only one doc
}
using (var context = searcherManager.GetContext())
{
IndexSearcher indexSearcher = context.Reference;
TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1);
assertEquals(1, topDocs.TotalHits); //There is only one doc
}
//Add a 2nd document
doc = new Document();
doc.Add(new Int32Field("id", 2, Field.Store.YES));
doc.Add(new StringField("name", "Doc2", Field.Store.YES));
trackingWriter.AddDocument(doc);
//Demonstrate that we can only see the first doc because we haven't
//waited 1 sec or called WaitForGeneration
// In Java, to obtain a threadsafe IndexSearcher reference, the following pattern could
// be used. This also works in .NET.
//indexSearcher = searcherManager.Acquire();
//try
//{
// TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1);
// assertEquals(1, topDocs.TotalHits); //Can see both docs due to auto refresh after 1.1 secs
//}
//finally
//{
// searcherManager.Release(indexSearcher);
//}
// However, in .NET it can be done like this with less code. We get an instance of
// ReferenceContext<IndexSearcher> in a using block so the call to searcherManager.Release()
// happens implicitly. ReferenceContext<IndexSearcher> is a ref struct so it doesn't allocate
// on the heap and will be deallocated at the end of this block automatically.
using (var context = searcherManager.GetContext())
{
IndexSearcher indexSearcher = context.Reference;
TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1);
assertEquals(1, topDocs.TotalHits); //Can see both docs due to auto refresh after 1.1 secs
}
//Demonstrate that we can see both docs after we wait a little more
//then 1 sec so that controlledRealTimeReopenThread max interval is exceeded
//and it calls MaybeRefresh
Thread.Sleep(1100); //wait 1.1 secs as ms
using (var context = searcherManager.GetContext())
{
IndexSearcher indexSearcher = context.Reference;
TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1);
assertEquals(2, topDocs.TotalHits); //Can see both docs due to auto refresh after 1.1 secs
}
//Add a 3rd document
doc = new Document();
doc.Add(new Int32Field("id", 3, Field.Store.YES));
doc.Add(new StringField("name", "Doc3", Field.Store.YES));
long generation = trackingWriter.AddDocument(doc);
//Demonstrate that if we call WaitForGeneration our wait will be
// .2 secs or less (the min interval we set earlier) and then we will
//see all 3 documents.
Stopwatch stopwatch = Stopwatch.StartNew();
controlledRealTimeReopenThread.WaitForGeneration(generation);
stopwatch.Stop();
assertTrue(stopwatch.Elapsed.TotalMilliseconds <= 200 + 30); //30ms is fudged factor to account for call overhead.
// In Java, to obtain a threadsafe IndexSearcher reference, the following pattern could
// be used. This also works in .NET.
//indexSearcher = searcherManager.Acquire();
//try
//{
// TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1);
// assertEquals(3, topDocs.TotalHits); //Can see both docs due to auto refresh after 1.1 secs
//}
//finally
//{
// searcherManager.Release(indexSearcher);
//}
// However, in .NET it can be done like this with less code. We get an instance of
// ReferenceContext<IndexSearcher> in a using block so the call to searcherManager.Release()
// happens implicitly. ReferenceContext<IndexSearcher> is a ref struct so it doesn't allocate
// on the heap and will be deallocated at the end of this block automatically.
using (var context = searcherManager.GetContext())
{
IndexSearcher indexSearcher = context.Reference;
TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1);
assertEquals(3, topDocs.TotalHits); //Can see both docs due to auto refresh after 1.1 secs
}
controlledRealTimeReopenThread.Dispose();
searcherManager.Dispose();
indexWriter.Dispose();
indexDir.Dispose();
}
/// <summary>
/// In this test multiple threads are created each of which is waiting on the same
/// generation before doing a search. These threads will all stack up on the
/// WaitForGeneration(generation) call. All threads should return from this call
/// in approximately in the time expected, namely the value for targetMinStaleSec passed
/// to ControlledRealTimeReopenThread in it's constructor.
/// </summary>
// LUCENENET specific - An extra test to test multithreaded use of ControlledRealTimeReopen.
[Test]
[LuceneNetSpecific]
[Ignore("Run Manually (contains timing code that doesn't play well with other tests)")]
public void TestMultithreadedWaitForGeneration()
{
Thread CreateWorker(int threadNum, ControlledRealTimeReopenThread<IndexSearcher> controlledReopen, long generation,
SearcherManager searcherManager, List<ThreadOutput> outputList)
{
ThreadStart threadStart = delegate
{
Stopwatch stopwatch = Stopwatch.StartNew();
controlledReopen.WaitForGeneration(generation);
stopwatch.Stop();
double milliSecsWaited = stopwatch.Elapsed.TotalMilliseconds;
int numRecs = 0;
IndexSearcher indexSearcher = searcherManager.Acquire();
try
{
TopDocs topDocs = indexSearcher.Search(new MatchAllDocsQuery(), 1);
numRecs = topDocs.TotalHits;
}
finally
{
searcherManager.Release(indexSearcher);
}
lock (outputList)
{
outputList.Add(new ThreadOutput { ThreadNum = threadNum, NumRecs = numRecs, MilliSecsWaited = milliSecsWaited });
}
};
return new Thread(threadStart);
}
int threadCount = 3;
List<ThreadOutput> outputList = new List<ThreadOutput>();
RAMDirectory indexDir = new RAMDirectory();
Analyzer standardAnalyzer = new StandardAnalyzer(TEST_VERSION_CURRENT);
IndexWriterConfig indexConfig = new IndexWriterConfig(TEST_VERSION_CURRENT, standardAnalyzer);
IndexWriter indexWriter = new IndexWriter(indexDir, indexConfig);
TrackingIndexWriter trackingWriter = new TrackingIndexWriter(indexWriter);
//Add two documents
Document doc = new Document();
doc.Add(new Int32Field("id", 1, Field.Store.YES));
doc.Add(new StringField("name", "Doc1", Field.Store.YES));
long generation = trackingWriter.AddDocument(doc);
doc.Add(new Int32Field("id", 2, Field.Store.YES));
doc.Add(new StringField("name", "Doc3", Field.Store.YES));
generation = trackingWriter.AddDocument(doc);
SearcherManager searcherManager = new SearcherManager(indexWriter, applyAllDeletes: true, null);
//Reopen SearcherManager every 2 secs via background thread if no thread waiting for newer generation.
//Reopen SearcherManager after .2 secs if another thread IS waiting on a newer generation.
double maxRefreshSecs = 2.0;
double minRefreshSecs = .2;
var controlledRealTimeReopenThread = new ControlledRealTimeReopenThread<IndexSearcher>(trackingWriter, searcherManager, maxRefreshSecs, minRefreshSecs);
//Start() will start a separate thread that will invoke the object's Run(). However,
//calling Run() directly would execute that code on the current thread rather then a new thread
//which would defeat the purpose of using controlledRealTimeReopenThread. This aspect of the API
//is not as intuitive as it could be. ie. Call Start() not Run().
controlledRealTimeReopenThread.IsBackground = true; //Set as a background thread
controlledRealTimeReopenThread.Name = "Controlled Real Time Reopen Thread";
controlledRealTimeReopenThread.Priority = (ThreadPriority)Math.Min((int)Thread.CurrentThread.Priority + 2, (int)ThreadPriority.Highest);
controlledRealTimeReopenThread.Start();
//Create the threads for doing searchers
List<Thread> threadList = new List<Thread>();
for (int i = 1; i <= threadCount; i++)
{
threadList.Add(CreateWorker(i, controlledRealTimeReopenThread, generation, searcherManager, outputList));
}
//Start all the threads
foreach (Thread thread in threadList)
{
thread.Start();
}
//wait for the threads to finish.
foreach (Thread thread in threadList)
{
thread.Join(); //will wait here until the thread terminates.
}
//Now make sure that no thread waited longer then our min refresh time
//plus a small fudge factor. Also verify that all threads reported back and
//each saw 2 records.