-
Notifications
You must be signed in to change notification settings - Fork 624
/
MockDirectoryWrapper.cs
1552 lines (1420 loc) · 59.5 KB
/
MockDirectoryWrapper.cs
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.Runtime.CompilerServices;
using J2N.Threading.Atomic;
using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Support;
using Lucene.Net.Support.Threading;
using Lucene.Net.Util;
using RandomizedTesting.Generators;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Console = Lucene.Net.Util.SystemConsole;
using JCG = J2N.Collections.Generic;
#if FEATURE_SERIALIZABLE_EXCEPTIONS
using System.Runtime.Serialization;
#endif
namespace Lucene.Net.Store
{
/*
* 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.
*/
/// <summary>
/// Enum for controlling hard disk throttling.
/// Set via <see cref="MockDirectoryWrapper.Throttling"/>
/// <para/>
/// WARNING: can make tests very slow.
/// </summary>
public enum Throttling
{
/// <summary>
/// always emulate a slow hard disk. could be very slow! </summary>
ALWAYS,
/// <summary>
/// sometimes (2% of the time) emulate a slow hard disk. </summary>
SOMETIMES,
/// <summary>
/// never throttle output </summary>
NEVER
}
/// <summary>
/// This is a Directory Wrapper that adds methods
/// intended to be used only by unit tests.
/// It also adds a number of features useful for testing:
/// <list type="bullet">
/// <item>
/// <description>
/// Instances created by <see cref="LuceneTestCase.NewDirectory()"/> are tracked
/// to ensure they are disposed by the test.
/// </description>
/// </item>
/// <item>
/// <description>
/// When a <see cref="MockDirectoryWrapper"/> is disposed, it will throw an exception if
/// it has any open files against it (with a stacktrace indicating where
/// they were opened from).
/// </description>
/// </item>
/// <item>
/// <description>
/// When a <see cref="MockDirectoryWrapper"/> is disposed, it runs <see cref="Index.CheckIndex"/> to test if
/// the index was corrupted.
/// </description>
/// </item>
/// <item>
/// <description>
/// <see cref="MockDirectoryWrapper"/> simulates some "features" of Windows, such as
/// refusing to write/delete to open files.
/// </description>
/// </item>
/// </list>
/// </summary>
public class MockDirectoryWrapper : BaseDirectoryWrapper
{
internal long maxSize;
// Max actual bytes used. this is set by MockRAMOutputStream:
internal long maxUsedSize;
internal double randomIOExceptionRate;
internal double randomIOExceptionRateOnOpen;
internal Random randomState;
internal bool noDeleteOpenFile = true;
internal bool assertNoDeleteOpenFile = false;
internal bool preventDoubleWrite = true;
internal bool trackDiskUsage = false;
internal bool wrapLockFactory = true;
internal bool allowRandomFileNotFoundException = true;
internal bool allowReadingFilesStillOpenForWrite = false;
private ISet<string> unSyncedFiles;
private ISet<string> createdFiles;
private ISet<string> openFilesForWrite = new JCG.HashSet<string>(StringComparer.Ordinal);
internal ISet<string> openLocks = new ConcurrentHashSet<string>(StringComparer.Ordinal);
internal volatile bool crashed;
private readonly ThrottledIndexOutput throttledOutput; // LUCENENET: marked readonly
private Throttling throttling = Throttling.SOMETIMES;
protected LockFactory m_lockFactory;
internal readonly AtomicInt32 inputCloneCount = new AtomicInt32();
// use this for tracking files for crash.
// additionally: provides debugging information in case you leave one open
private readonly ConcurrentDictionary<IDisposable, Exception> openFileHandles = new ConcurrentDictionary<IDisposable, Exception>(IdentityEqualityComparer<IDisposable>.Default);
// NOTE: we cannot initialize the Map here due to the
// order in which our constructor actually does this
// member initialization vs when it calls super. It seems
// like super is called, then our members are initialized:
private IDictionary<string, int> openFiles;
// Only tracked if noDeleteOpenFile is true: if an attempt
// is made to delete an open file, we enroll it here.
private ISet<string> openFilesDeleted;
private void Init()
{
UninterruptableMonitor.Enter(this);
try
{
if (openFiles is null)
{
openFiles = new Dictionary<string, int>(StringComparer.Ordinal);
openFilesDeleted = new JCG.HashSet<string>(StringComparer.Ordinal);
}
if (createdFiles is null)
{
createdFiles = new JCG.HashSet<string>(StringComparer.Ordinal);
}
if (unSyncedFiles is null)
{
unSyncedFiles = new JCG.HashSet<string>(StringComparer.Ordinal);
}
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
public MockDirectoryWrapper(Random random, Directory @delegate)
: base(@delegate)
{
// must make a private random since our methods are
// called from different threads; else test failures may
// not be reproducible from the original seed
this.randomState = new J2N.Randomizer(random.NextInt64());
this.throttledOutput = new ThrottledIndexOutput(ThrottledIndexOutput.MBitsToBytes(40 + randomState.Next(10)), 5 + randomState.Next(5), null);
// force wrapping of lockfactory
this.m_lockFactory = new MockLockFactoryWrapper(this, @delegate.LockFactory);
Init();
}
public virtual int InputCloneCount => inputCloneCount;
public virtual bool TrackDiskUsage
{
get => trackDiskUsage; // LUCENENET specific - added getter (to follow MSDN property guidelines)
set => trackDiskUsage = value;
}
/// <summary>
/// If set to true, we throw an <see cref="IOException"/> if the same
/// file is opened by <see cref="CreateOutput(string, IOContext)"/>, ever.
/// </summary>
public virtual bool PreventDoubleWrite
{
get => preventDoubleWrite; // LUCENENET specific - added getter (to follow MSDN property guidelines)
set => preventDoubleWrite = value;
}
/// <summary>
/// If set to true (the default), when we throw random
/// <see cref="IOException"/> on <see cref="OpenInput(string, IOContext)"/> or
/// <see cref="CreateOutput(string, IOContext)"/>, we may
/// sometimes throw <see cref="FileNotFoundException"/>.
/// </summary>
public virtual bool AllowRandomFileNotFoundException
{
get => allowRandomFileNotFoundException; // LUCENENET specific - added getter (to follow MSDN property guidelines)
set => allowRandomFileNotFoundException = value;
}
/// <summary>
/// If set to true, you can open an inputstream on a file
/// that is still open for writes.
/// </summary>
public virtual bool AllowReadingFilesStillOpenForWrite
{
get => allowRandomFileNotFoundException; // LUCENENET specific - added getter (to follow MSDN property guidelines)
set => allowReadingFilesStillOpenForWrite = value;
}
// LUCENENET specific - de-nested Throttling enum
public virtual Throttling Throttling
{
get => throttling; // LUCENENET specific - added getter (to follow MSDN property guidelines)
set => throttling = value;
}
/// <summary>
/// Returns true if <see cref="FilterDirectory.m_input"/> must sync its files.
/// Currently, only <see cref="NRTCachingDirectory"/> requires sync'ing its files
/// because otherwise they are cached in an internal <see cref="RAMDirectory"/>. If
/// other directories require that too, they should be added to this method.
/// </summary>
private bool MustSync()
{
Directory @delegate = m_input;
while (@delegate is FilterDirectory filterDirectory)
{
@delegate = filterDirectory.Delegate;
}
return @delegate is NRTCachingDirectory;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void Sync(ICollection<string> names)
{
UninterruptableMonitor.Enter(this);
try
{
MaybeYield();
MaybeThrowDeterministicException();
if (crashed)
{
throw new IOException("cannot sync after crash");
}
// don't wear out our hardware so much in tests.
if (LuceneTestCase.Rarely(randomState) || MustSync())
{
foreach (string name in names)
{
// randomly fail with IOE on any file
MaybeThrowIOException(name);
m_input.Sync(new[] { name });
unSyncedFiles.Remove(name);
}
}
else
{
unSyncedFiles.ExceptWith(names);
}
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
public long GetSizeInBytes()
{
UninterruptableMonitor.Enter(this);
try
{
if (m_input is RAMDirectory ramDirectory)
{
return ramDirectory.GetSizeInBytes();
}
else
{
// hack
long size = 0;
foreach (string file in m_input.ListAll())
{
size += m_input.FileLength(file);
}
return size;
}
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
/// <summary>
/// Simulates a crash of OS or machine by overwriting
/// unsynced files.
/// </summary>
public virtual void Crash()
{
UninterruptableMonitor.Enter(this);
try
{
crashed = true;
openFiles = new Dictionary<string, int>(StringComparer.Ordinal);
openFilesForWrite = new JCG.HashSet<string>(StringComparer.Ordinal);
openFilesDeleted = new JCG.HashSet<string>(StringComparer.Ordinal);
using IEnumerator<string> it = unSyncedFiles.GetEnumerator();
unSyncedFiles = new JCG.HashSet<string>(StringComparer.Ordinal);
// first force-close all files, so we can corrupt on windows etc.
// clone the file map, as these guys want to remove themselves on close.
var m = new JCG.Dictionary<IDisposable, Exception>(openFileHandles, IdentityEqualityComparer<IDisposable>.Default);
foreach (IDisposable f in m.Keys)
{
try
{
f.Dispose();
}
catch (Exception ignored) when (ignored.IsException())
{
//Debug.WriteLine("Crash(): f.Dispose() FAILED for {0}:\n{1}", f.ToString(), ignored.ToString());
}
}
while (it.MoveNext())
{
string name = it.Current;
int damage = randomState.Next(5);
string action = null;
if (damage == 0)
{
action = "deleted";
DeleteFile(name, true);
}
else if (damage == 1)
{
action = "zeroed";
// Zero out file entirely
long length = FileLength(name);
var zeroes = new byte[256];
long upto = 0;
using IndexOutput @out = m_input.CreateOutput(name, LuceneTestCase.NewIOContext(randomState));
while (upto < length)
{
var limit = (int)Math.Min(length - upto, zeroes.Length);
@out.WriteBytes(zeroes, 0, limit);
upto += limit;
}
}
else if (damage == 2)
{
action = "partially truncated";
// Partially Truncate the file:
// First, make temp file and copy only half this
// file over:
string tempFileName;
while (true)
{
tempFileName = "" + randomState.Next();
if (!LuceneTestCase.SlowFileExists(m_input, tempFileName))
{
break;
}
}
using (IndexOutput tempOut = m_input.CreateOutput(tempFileName, LuceneTestCase.NewIOContext(randomState)))
using (IndexInput ii = m_input.OpenInput(name, LuceneTestCase.NewIOContext(randomState)))
{
tempOut.CopyBytes(ii, ii.Length / 2);
}
// Delete original and copy bytes back:
DeleteFile(name, true);
using (IndexOutput @out = m_input.CreateOutput(name, LuceneTestCase.NewIOContext(randomState)))
using (IndexInput ii = m_input.OpenInput(tempFileName, LuceneTestCase.NewIOContext(randomState)))
{
@out.CopyBytes(ii, ii.Length);
}
DeleteFile(tempFileName, true);
}
else if (damage == 3)
{
// The file survived intact:
action = "didn't change";
}
else
{
action = "fully truncated";
// Totally truncate the file to zero bytes
DeleteFile(name, true);
using IndexOutput @out = m_input.CreateOutput(name, LuceneTestCase.NewIOContext(randomState));
@out.Length = 0;
}
if (LuceneTestCase.Verbose)
{
Console.WriteLine("MockDirectoryWrapper: " + action + " unsynced file: " + name);
}
}
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
public virtual void ClearCrash()
{
UninterruptableMonitor.Enter(this);
try
{
crashed = false;
openLocks.Clear();
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
public virtual long MaxSizeInBytes
{
get => maxSize;
set => maxSize = value;
}
/// <summary>
/// Returns the peek actual storage used (bytes) in this
/// directory.
/// </summary>
public virtual long MaxUsedSizeInBytes => maxUsedSize;
public virtual void ResetMaxUsedSizeInBytes()
{
this.maxUsedSize = GetRecomputedActualSizeInBytes();
}
/// <summary>
/// Emulate Windows whereby deleting an open file is not
/// allowed (raise <see cref="IOException"/>).
/// </summary>
public virtual bool NoDeleteOpenFile
{
get => noDeleteOpenFile;
set => noDeleteOpenFile = value;
}
/// <summary>
/// Trip a test assert if there is an attempt
/// to delete an open file.
/// </summary>
public virtual bool AssertNoDeleteOpenFile
{
get => assertNoDeleteOpenFile;
set => assertNoDeleteOpenFile = value;
}
/// <summary>
/// If 0.0, no exceptions will be thrown. Else this should
/// be a double 0.0 - 1.0. We will randomly throw an
/// <see cref="IOException"/> on the first write to a <see cref="Stream"/> based
/// on this probability.
/// </summary>
public virtual double RandomIOExceptionRate
{
get => randomIOExceptionRate;
set => randomIOExceptionRate = value;
}
/// <summary>
/// If 0.0, no exceptions will be thrown during <see cref="OpenInput(string, IOContext)"/>
/// and <see cref="CreateOutput(string, IOContext)"/>. Else this should
/// be a double 0.0 - 1.0 and we will randomly throw an
/// <see cref="IOException"/> in <see cref="OpenInput(string, IOContext)"/> and <see cref="CreateOutput(string, IOContext)"/> with
/// this probability.
/// </summary>
public virtual double RandomIOExceptionRateOnOpen
{
get => randomIOExceptionRateOnOpen;
set => randomIOExceptionRateOnOpen = value;
}
internal virtual void MaybeThrowIOException(string message)
{
if (randomState.NextDouble() < randomIOExceptionRate)
{
if (LuceneTestCase.Verbose)
{
Console.WriteLine(Thread.CurrentThread.Name + ": MockDirectoryWrapper: now throw random exception" + (message is null ? "" : " (" + message + ")"));
}
throw new IOException("a random IOException" + (message is null ? "" : " (" + message + ")"));
}
}
internal virtual void MaybeThrowIOExceptionOnOpen(string name)
{
if (randomState.NextDouble() < randomIOExceptionRateOnOpen)
{
if (LuceneTestCase.Verbose)
{
Console.WriteLine(Thread.CurrentThread.Name + ": MockDirectoryWrapper: now throw random exception during open file=" + name);
}
if (allowRandomFileNotFoundException == false || randomState.NextBoolean())
{
throw new IOException("a random IOException (" + name + ")");
}
else
{
throw randomState.NextBoolean() ? (IOException)new FileNotFoundException("a random IOException (" + name + ")") : new DirectoryNotFoundException("a random IOException (" + name + ")");
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public override void DeleteFile(string name)
{
UninterruptableMonitor.Enter(this);
try
{
MaybeYield();
DeleteFile(name, false);
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
// if there are any exceptions in OpenFileHandles
// capture those as inner exceptions
private Exception WithAdditionalErrorInformation(Exception t, string name, bool input)
{
UninterruptableMonitor.Enter(this);
try
{
foreach (var ent in openFileHandles)
{
if (input && ent.Key is MockIndexInputWrapper mockIndexInputWrapper && mockIndexInputWrapper.name.Equals(name, StringComparison.Ordinal))
{
t = CreateException(t, ent.Value);
break;
}
else if (!input && ent.Key is MockIndexOutputWrapper mockIndexOutputWrapper && mockIndexOutputWrapper.name.Equals(name, StringComparison.Ordinal))
{
t = CreateException(t, ent.Value);
break;
}
}
return t;
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Exception CreateException(Exception exception, Exception innerException) // LUCENENET: CA1822: Mark members as static
{
return (Exception)Activator.CreateInstance(exception.GetType(), exception.Message, innerException);
}
private void MaybeYield()
{
if (randomState.NextBoolean())
{
Thread.Yield();
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void DeleteFile(string name, bool forced)
{
UninterruptableMonitor.Enter(this);
try
{
MaybeYield();
MaybeThrowDeterministicException();
if (crashed && !forced)
{
throw new IOException("cannot delete after crash");
}
if (unSyncedFiles.Contains(name))
{
unSyncedFiles.Remove(name);
}
if (!forced && (noDeleteOpenFile || assertNoDeleteOpenFile))
{
if (openFiles.ContainsKey(name))
{
openFilesDeleted.Add(name);
if (!assertNoDeleteOpenFile)
{
throw WithAdditionalErrorInformation(new IOException("MockDirectoryWrapper: file \"" + name + "\" is still open: cannot delete"), name, true);
}
else
{
throw WithAdditionalErrorInformation(AssertionError.Create("MockDirectoryWrapper: file \"" + name + "\" is still open: cannot delete"), name, true);
}
}
else
{
openFilesDeleted.Remove(name);
}
}
m_input.DeleteFile(name);
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
public virtual ICollection<string> GetOpenDeletedFiles()
{
UninterruptableMonitor.Enter(this);
try
{
return new JCG.HashSet<string>(openFilesDeleted, StringComparer.Ordinal);
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
private bool failOnCreateOutput = true;
public virtual bool FailOnCreateOutput
{
get => failOnCreateOutput; // LUCENENET specific - added getter (to follow MSDN property guidelines)
set => failOnCreateOutput = value;
}
public override IndexOutput CreateOutput(string name, IOContext context)
{
UninterruptableMonitor.Enter(this);
try
{
MaybeThrowDeterministicException();
MaybeThrowIOExceptionOnOpen(name);
MaybeYield();
if (failOnCreateOutput)
{
MaybeThrowDeterministicException();
}
if (crashed)
{
throw new IOException("cannot createOutput after crash");
}
Init();
UninterruptableMonitor.Enter(this);
try
{
if (preventDoubleWrite && createdFiles.Contains(name) && !name.Equals("segments.gen", StringComparison.Ordinal))
{
throw new IOException("file \"" + name + "\" was already written to");
}
}
finally
{
UninterruptableMonitor.Exit(this);
}
if ((noDeleteOpenFile || assertNoDeleteOpenFile) && openFiles.ContainsKey(name))
{
if (!assertNoDeleteOpenFile)
{
throw new IOException("MockDirectoryWrapper: file \"" + name + "\" is still open: cannot overwrite");
}
else
{
throw AssertionError.Create("MockDirectoryWrapper: file \"" + name + "\" is still open: cannot overwrite");
}
}
if (crashed)
{
throw new IOException("cannot createOutput after crash");
}
unSyncedFiles.Add(name);
createdFiles.Add(name);
if (m_input is RAMDirectory ramdir)
{
RAMFile file = new RAMFile(ramdir);
ramdir.m_fileMap.TryGetValue(name, out RAMFile existing);
// Enforce write once:
if (existing != null && !name.Equals("segments.gen", StringComparison.Ordinal) && preventDoubleWrite)
{
throw new IOException("file " + name + " already exists");
}
else
{
if (existing != null)
{
ramdir.m_sizeInBytes.AddAndGet(-existing.GetSizeInBytes()); // LUCENENET: GetAndAdd in Lucene, but we are not using the value
existing.directory = null;
}
ramdir.m_fileMap[name] = file;
}
}
//System.out.println(Thread.currentThread().getName() + ": MDW: create " + name);
IndexOutput delegateOutput = m_input.CreateOutput(name, LuceneTestCase.NewIOContext(randomState, context));
if (randomState.Next(10) == 0)
{
// once in a while wrap the IO in a Buffered IO with random buffer sizes
delegateOutput = new BufferedIndexOutputWrapper(1 + randomState.Next(BufferedIndexOutput.DEFAULT_BUFFER_SIZE), delegateOutput);
}
IndexOutput io = new MockIndexOutputWrapper(this, delegateOutput, name);
AddFileHandle(io, name, Handle.Output);
openFilesForWrite.Add(name);
// throttling REALLY slows down tests, so don't do it very often for SOMETIMES.
if (throttling == Throttling.ALWAYS || (throttling == Throttling.SOMETIMES && randomState.Next(50) == 0) && !(m_input is RateLimitedDirectoryWrapper))
{
if (LuceneTestCase.Verbose)
{
Console.WriteLine("MockDirectoryWrapper: throttling indexOutput (" + name + ")");
}
return throttledOutput.NewFromDelegate(io);
}
else
{
return io;
}
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
internal enum Handle
{
Input,
Output,
Slice
}
internal void AddFileHandle(IDisposable c, string name, Handle handle)
{
//Trace.TraceInformation("Add {0} {1}", c, name);
UninterruptableMonitor.Enter(this);
try
{
if (openFiles.TryGetValue(name, out int v))
{
v++;
//Debug.WriteLine("Add {0} - {1} - {2}", c, name, v);
openFiles[name] = v;
}
else
{
//Debug.WriteLine("Add {0} - {1} - {2}", c, name, 1);
openFiles[name] = 1;
}
openFileHandles[c] = RuntimeException.Create("unclosed Index" + handle.ToString() + ": " + name);
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
private bool failOnOpenInput = true;
public virtual bool FailOnOpenInput
{
get => failOnOpenInput; // LUCENENET specific - added getter (to follow MSDN property guidelines)
set => failOnOpenInput = value;
}
public override IndexInput OpenInput(string name, IOContext context)
{
UninterruptableMonitor.Enter(this);
try
{
MaybeThrowDeterministicException();
MaybeThrowIOExceptionOnOpen(name);
MaybeYield();
if (failOnOpenInput)
{
MaybeThrowDeterministicException();
}
if (!LuceneTestCase.SlowFileExists(m_input, name))
{
throw randomState.NextBoolean() ? (IOException)new FileNotFoundException(name + " in dir=" + m_input) : new DirectoryNotFoundException(name + " in dir=" + m_input);
}
// cannot open a file for input if it's still open for
// output, except for segments.gen and segments_N
if (!allowReadingFilesStillOpenForWrite && openFilesForWrite.Contains(name) && !name.StartsWith("segments", StringComparison.Ordinal))
{
throw WithAdditionalErrorInformation(new IOException("MockDirectoryWrapper: file \"" + name + "\" is still open for writing"), name, false);
}
IndexInput delegateInput = m_input.OpenInput(name, LuceneTestCase.NewIOContext(randomState, context));
IndexInput ii;
int randomInt = randomState.Next(500);
if (randomInt == 0)
{
if (LuceneTestCase.Verbose)
{
Console.WriteLine("MockDirectoryWrapper: using SlowClosingMockIndexInputWrapper for file " + name);
}
ii = new SlowClosingMockIndexInputWrapper(this, name, delegateInput);
}
else if (randomInt == 1)
{
if (LuceneTestCase.Verbose)
{
Console.WriteLine("MockDirectoryWrapper: using SlowOpeningMockIndexInputWrapper for file " + name);
}
ii = new SlowOpeningMockIndexInputWrapper(this, name, delegateInput);
}
else
{
ii = new MockIndexInputWrapper(this, name, delegateInput);
}
AddFileHandle(ii, name, Handle.Input);
return ii;
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
/// <summary>
/// Provided for testing purposes. Use <see cref="GetSizeInBytes()"/> instead. </summary>
public long GetRecomputedSizeInBytes()
{
UninterruptableMonitor.Enter(this);
try
{
if (!(m_input is RAMDirectory))
{
return GetSizeInBytes();
}
long size = 0;
foreach (RAMFile file in ((RAMDirectory)m_input).m_fileMap.Values)
{
size += file.GetSizeInBytes();
}
return size;
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
/// <summary>
/// Like <see cref="GetRecomputedSizeInBytes()"/>, but, uses actual file
/// lengths rather than buffer allocations (which are
/// quantized up to nearest
/// <see cref="RAMOutputStream.BUFFER_SIZE"/> (now 1024) bytes.
/// </summary>
public long GetRecomputedActualSizeInBytes()
{
UninterruptableMonitor.Enter(this);
try
{
if (!(m_input is RAMDirectory))
{
return GetSizeInBytes();
}
long size = 0;
foreach (RAMFile file in ((RAMDirectory)m_input).m_fileMap.Values)
{
size += file.Length;
}
return size;
}
finally
{
UninterruptableMonitor.Exit(this);
}
}
// NOTE: this is off by default; see LUCENE-5574
private bool assertNoUnreferencedFilesOnClose;
public virtual bool AssertNoUnreferencedFilesOnDispose // LUCENENET specific: Renamed from AssertNoUnreferencedFilesOnClose
{
get => assertNoUnreferencedFilesOnClose; // LUCENENET specific - added getter (to follow MSDN property guidelines)
set => assertNoUnreferencedFilesOnClose = value;
}
/// <summary>
/// Set to false if you want to return the pure lockfactory
/// and not wrap it with <see cref="MockLockFactoryWrapper"/>.
/// <para/>
/// Be careful if you turn this off: <see cref="MockDirectoryWrapper"/> might
/// no longer be able to detect if you forget to close an <see cref="IndexWriter"/>,
/// and spit out horribly scary confusing exceptions instead of
/// simply telling you that.
/// </summary>
public virtual bool WrapLockFactory
{
get => wrapLockFactory; // LUCENENET specific - added getter (to follow MSDN property guidelines)
set => wrapLockFactory = value;
}
protected override void Dispose(bool disposing)
{
UninterruptableMonitor.Enter(this);
try
{
if (disposing)
{
// files that we tried to delete, but couldn't because readers were open.
// all that matters is that we tried! (they will eventually go away)
ISet<string> pendingDeletions = new JCG.HashSet<string>(openFilesDeleted, StringComparer.Ordinal);
MaybeYield();
if (openFiles is null)
{
openFiles = new Dictionary<string, int>(StringComparer.Ordinal);
openFilesDeleted = new JCG.HashSet<string>(StringComparer.Ordinal);
}
if (openFiles.Count > 0)
{
// print the first one as its very verbose otherwise
Exception cause = openFileHandles.Values.FirstOrDefault();
// RuntimeException instead ofIOException because
// super() does not throw IOException currently:
throw RuntimeException.Create("MockDirectoryWrapper: cannot close: there are still open files: "
+ Collections.ToString(openFiles), cause);
}
if (openLocks.Count > 0)
{
throw RuntimeException.Create("MockDirectoryWrapper: cannot close: there are still open locks: "
+ Collections.ToString(openLocks));
}
IsOpen = false;
if (CheckIndexOnDispose)
{
randomIOExceptionRate = 0.0;
randomIOExceptionRateOnOpen = 0.0;
if (DirectoryReader.IndexExists(this))
{
if (LuceneTestCase.Verbose)
{
Console.WriteLine("\nNOTE: MockDirectoryWrapper: now crush");
}
Crash(); // corrupt any unsynced-files
if (LuceneTestCase.Verbose)
{
Console.WriteLine("\nNOTE: MockDirectoryWrapper: now run CheckIndex");
}
TestUtil.CheckIndex(this, CrossCheckTermVectorsOnDispose);
// TODO: factor this out / share w/ TestIW.assertNoUnreferencedFiles
if (assertNoUnreferencedFilesOnClose)
{
// now look for unreferenced files: discount ones that we tried to delete but could not
ISet<string> allFiles = new JCG.HashSet<string>(ListAll());
allFiles.ExceptWith(pendingDeletions);
string[] startFiles = allFiles.ToArray(/*new string[0]*/);
IndexWriterConfig iwc = new IndexWriterConfig(LuceneTestCase.TEST_VERSION_CURRENT, null);
iwc.SetIndexDeletionPolicy(NoDeletionPolicy.INSTANCE);
new IndexWriter(m_input, iwc).Rollback();
string[] endFiles = m_input.ListAll();
ISet<string> startSet = new JCG.SortedSet<string>(startFiles, StringComparer.Ordinal);
ISet<string> endSet = new JCG.SortedSet<string>(endFiles, StringComparer.Ordinal);
if (pendingDeletions.Contains("segments.gen") && endSet.Contains("segments.gen"))
{
// this is possible if we hit an exception while writing segments.gen, we try to delete it
// and it ends out in pendingDeletions (but IFD wont remove this).
startSet.Add("segments.gen");
if (LuceneTestCase.Verbose)
{
Console.WriteLine("MDW: Unreferenced check: Ignoring segments.gen that we could not delete.");
}
}
// its possible we cannot delete the segments_N on windows if someone has it open and
// maybe other files too, depending on timing. normally someone on windows wouldnt have
// an issue (IFD would nuke this stuff eventually), but we pass NoDeletionPolicy...
foreach (string file in pendingDeletions)
{