-
Notifications
You must be signed in to change notification settings - Fork 565
Expand file tree
/
Copy pathSingleChronicleQueue.java
More file actions
1331 lines (1144 loc) · 49 KB
/
SingleChronicleQueue.java
File metadata and controls
1331 lines (1144 loc) · 49 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
/*
* Copyright 2016-2020 chronicle.software
*
* https://chronicle.software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.bytes.*;
import net.openhft.chronicle.bytes.internal.HeapBytesStore;
import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.OS;
import net.openhft.chronicle.core.analytics.AnalyticsFacade;
import net.openhft.chronicle.core.annotation.PackageLocal;
import net.openhft.chronicle.core.announcer.Announcer;
import net.openhft.chronicle.core.io.AbstractCloseable;
import net.openhft.chronicle.core.io.BackgroundResourceReleaser;
import net.openhft.chronicle.core.io.Closeable;
import net.openhft.chronicle.core.threads.*;
import net.openhft.chronicle.core.time.TimeProvider;
import net.openhft.chronicle.core.util.StringUtils;
import net.openhft.chronicle.core.values.LongValue;
import net.openhft.chronicle.queue.*;
import net.openhft.chronicle.queue.impl.*;
import net.openhft.chronicle.queue.impl.table.SingleTableStore;
import net.openhft.chronicle.queue.internal.AnalyticsHolder;
import net.openhft.chronicle.threads.DiskSpaceMonitor;
import net.openhft.chronicle.threads.TimingPauser;
import net.openhft.chronicle.wire.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.lang.ref.WeakReference;
import java.nio.channels.FileLock;
import java.nio.channels.NonWritableChannelException;
import java.security.SecureRandom;
import java.text.ParseException;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.function.*;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singletonMap;
import static net.openhft.chronicle.core.io.Closeable.closeQuietly;
import static net.openhft.chronicle.queue.TailerDirection.BACKWARD;
import static net.openhft.chronicle.queue.TailerDirection.NONE;
import static net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder.isQueueReplicationAvailable;
import static net.openhft.chronicle.wire.Wires.*;
public class SingleChronicleQueue extends AbstractCloseable implements RollingChronicleQueue {
public static final String SUFFIX = ".cq4";
public static final String QUEUE_METADATA_FILE = "metadata" + SingleTableStore.SUFFIX;
public static final String DISK_SPACE_CHECKER_NAME = DiskSpaceMonitor.DISK_SPACE_CHECKER_NAME;
private static final boolean SHOULD_CHECK_CYCLE = Jvm.getBoolean("chronicle.queue.checkrollcycle");
static final int WARN_SLOW_APPENDER_MS = Jvm.getInteger("chronicle.queue.warnSlowAppenderMs", 100);
@NotNull
protected final EventLoop eventLoop;
@NotNull
protected final TableStore<SCQMeta> metaStore;
@NotNull
protected final WireStorePool pool;
protected final boolean doubleBuffer;
final Supplier<TimingPauser> pauserSupplier;
final long timeoutMS;
@NotNull
final File path;
final String fileAbsolutePath;
// Uses this.closers as a lock. concurrent read, locking for write.
private final Map<BytesStore, LongValue> metaStoreMap = new ConcurrentHashMap<>();
private final StoreSupplier storeSupplier;
private final ThreadLocal<WeakReference<StoreTailer>> tlTailer = CleaningThreadLocal.withCleanup(wr -> Closeable.closeQuietly(wr.get()));
private final long epoch;
private final boolean isBuffered;
@NotNull
private final WireType wireType;
private final long blockSize;
private final long overlapSize;
@NotNull
private final Consumer<BytesRingBufferStats> onRingBufferStats;
private final long bufferCapacity;
private final int indexSpacing;
private final int indexCount;
@NotNull
private final TimeProvider time;
@NotNull
private final BiFunction<RollingChronicleQueue, Wire, SingleChronicleQueueStore> storeFactory;
private final Set<Closeable> closers = Collections.newSetFromMap(new IdentityHashMap<>());
private final boolean readOnly;
@NotNull
private final CycleCalculator cycleCalculator;
@Nullable
private final LongValue lastAcknowledgedIndexReplicated;
@Nullable
private final LongValue lastIndexReplicated;
@NotNull
private final DirectoryListing directoryListing;
@NotNull
private final QueueLock queueLock;
@NotNull
private final WriteLock writeLock;
private final boolean checkInterrupts;
@NotNull
private final RollingResourcesCache dateCache;
private final WriteLock appendLock;
private final StoreFileListener storeFileListener;
@NotNull
private final RollCycle rollCycle;
private final int deltaCheckpointInterval;
private final boolean useSparseFile;
private final long sparseCapacity;
final AppenderListener appenderListener;
@NotNull
private final FileShrinkage fileShrink;
protected int sourceId;
@NotNull
private Condition createAppenderCondition = NoOpCondition.INSTANCE;
protected final ThreadLocal<ExcerptAppender> strongExcerptAppenderThreadLocal = CleaningThreadLocal.withCloseQuietly(this::createNewAppenderOnceConditionIsMet);
private final long forceDirectoryListingRefreshIntervalMs;
private long[] chunkCount = {0};
protected SingleChronicleQueue(@NotNull final SingleChronicleQueueBuilder builder) {
try {
fileShrink = builder.fileShrinkage();
rollCycle = builder.rollCycle();
cycleCalculator = cycleCalculator(builder.rollTimeZone());
epoch = builder.epoch();
dateCache = new RollingResourcesCache(rollCycle, epoch, textToFile(builder), fileToText());
storeFileListener = builder.storeFileListener();
storeSupplier = new StoreSupplier();
pool = WireStorePool.withSupplier(storeSupplier, storeFileListener);
isBuffered = BufferMode.Asynchronous == builder.writeBufferMode();
path = builder.path();
if (!builder.readOnly())
//noinspection ResultOfMethodCallIgnored
path.mkdirs();
fileAbsolutePath = path.getAbsolutePath();
wireType = builder.wireType();
blockSize = builder.blockSize();
// the maximum message size is 1L << 30 so greater overlapSize has no effect
overlapSize = Math.min(Math.max(64 << 10, builder.blockSize() / 4), 1L << 30);
useSparseFile = builder.useSparseFiles();
sparseCapacity = builder.sparseCapacity();
eventLoop = builder.eventLoop();
bufferCapacity = builder.bufferCapacity();
onRingBufferStats = builder.onRingBufferStats();
indexCount = builder.indexCount();
indexSpacing = builder.indexSpacing();
time = builder.timeProvider();
pauserSupplier = builder.pauserSupplier();
// add a 20% random element to make it less likely threads will timeout at the same time.
timeoutMS = (long) (builder.timeoutMS() * (1 + 0.2 * new SecureRandom().nextFloat())); // Not time critical
storeFactory = builder.storeFactory();
checkInterrupts = builder.checkInterrupts();
metaStore = builder.metaStore();
doubleBuffer = builder.doubleBuffer();
if (metaStore.readOnly() && !builder.readOnly()) {
Jvm.warn().on(getClass(), "Forcing queue to be readOnly file=" + path);
// need to set this on builder as it is used elsewhere
builder.readOnly(metaStore.readOnly());
}
readOnly = builder.readOnly();
appenderListener = builder.appenderListener();
if (readOnly) {
this.directoryListing = new FileSystemDirectoryListing(path, fileNameToCycleFunction());
} else {
this.directoryListing = new TableDirectoryListing(metaStore, path.toPath(), fileNameToCycleFunction());
directoryListing.init();
}
this.directoryListing.refresh(true);
this.queueLock = isQueueReplicationAvailable() && !builder.readOnly()
? new TSQueueLock(metaStore, builder.pauserSupplier(), builder.timeoutMS() * 3 / 2)
: new NoopQueueLock();
this.writeLock = builder.writeLock();
// release the write lock if the process is dead
if (writeLock instanceof TableStoreWriteLock) {
((TableStoreWriteLock) writeLock).forceUnlockIfProcessIsDead();
}
this.appendLock = builder.appendLock();
if (readOnly) {
this.lastIndexReplicated = null;
this.lastAcknowledgedIndexReplicated = null;
} else {
this.lastIndexReplicated = metaStore.doWithExclusiveLock(ts -> ts.acquireValueFor("chronicle.lastIndexReplicated", -1L));
this.lastAcknowledgedIndexReplicated = metaStore.doWithExclusiveLock(ts -> ts.acquireValueFor("chronicle.lastAcknowledgedIndexReplicated", -1L));
}
this.deltaCheckpointInterval = builder.deltaCheckpointInterval();
this.forceDirectoryListingRefreshIntervalMs = builder.forceDirectoryListingRefreshIntervalMs();
sourceId = builder.sourceId();
Announcer.announce("net.openhft", "chronicle-queue",
AnalyticsFacade.isEnabled()
? singletonMap("Analytics", "Chronicle Queue reports usage statistics. Learn more or turn off: https://github.com/OpenHFT/Chronicle-Queue/blob/ea/DISCLAIMER.adoc")
: emptyMap());
final Map<String, String> additionalEventParameters = AnalyticsFacade.standardAdditionalProperties();
additionalEventParameters.put("wire_type", wireType.toString());
final String rollCycleName = rollCycle.toString();
if (!rollCycleName.startsWith("TEST"))
additionalEventParameters.put("roll_cycle", rollCycleName);
AnalyticsHolder.instance().sendEvent("started", additionalEventParameters);
disableThreadSafetyCheck(true);
} catch (Throwable t) {
close();
throw Jvm.rethrow(t);
}
}
protected void createAppenderCondition(@NotNull Condition createAppenderCondition) {
this.createAppenderCondition = createAppenderCondition;
}
protected CycleCalculator cycleCalculator(ZoneId zoneId) {
return DefaultCycleCalculator.INSTANCE;
}
/**
* @return tailer
* @deprecated call {@link #createTailer()} instead
*/
@Deprecated(/* to be removed in x.23 */)
@NotNull
StoreTailer acquireTailer() {
throwExceptionIfClosed();
StoreTailer tl = ThreadLocalHelper.getTL(tlTailer, this, q -> new StoreTailer(q, q.pool));
if (tl.isClosing()) {
tl = new StoreTailer(this, pool);
tlTailer.set(new WeakReference<>(tl));
}
return tl;
}
@NotNull
private Function<String, File> textToFile(@NotNull SingleChronicleQueueBuilder builder) {
return name -> new File(builder.path(), name + SUFFIX);
}
@NotNull
private Function<File, String> fileToText() {
return file -> {
String name = file.getName();
return name.substring(0, name.length() - SUFFIX.length());
};
}
@Override
public int sourceId() {
return sourceId;
}
/**
* when using replication to another host, this is the highest last index that has been confirmed to have been read by all of the remote host(s).
*/
@Override
public long lastAcknowledgedIndexReplicated() {
// throwExceptionIfClosed();
return lastAcknowledgedIndexReplicated == null ? -1 : lastAcknowledgedIndexReplicated.getVolatileValue(-1);
}
@Override
public void lastAcknowledgedIndexReplicated(long newValue) {
// throwExceptionIfClosed();
if (lastAcknowledgedIndexReplicated != null)
lastAcknowledgedIndexReplicated.setMaxValue(newValue);
}
@Override
public void refreshDirectoryListing() {
throwExceptionIfClosed();
directoryListing.refresh(true);
}
/**
* when using replication to another host, this is the maximum last index that has been sent to any of the remote host(s).
*/
@Override
public long lastIndexReplicated() {
return lastIndexReplicated == null ? -1 : lastIndexReplicated.getVolatileValue(-1);
}
@Override
public void lastIndexReplicated(long indexReplicated) {
if (lastIndexReplicated != null)
lastIndexReplicated.setMaxValue(indexReplicated);
}
@Override
public void clear() {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
@NotNull
public File file() {
return path;
}
@NotNull
@Override
public String fileAbsolutePath() {
return fileAbsolutePath;
}
@Override
public @NotNull String dumpLastHeader() {
StringBuilder sb = new StringBuilder(256);
try (SingleChronicleQueueStore wireStore = storeForCycle(lastCycle(), epoch, false, null)) {
sb.append(wireStore.dumpHeader());
}
return sb.toString();
}
@NotNull
@Override
public String dump() {
StringBuilder sb = new StringBuilder(1024);
sb.append(metaStore.dump());
for (int i = firstCycle(), max = lastCycle(); i <= max; i++) {
try (SingleChronicleQueueStore commonStore = storeForCycle(i, epoch, false, null)) {
if (commonStore != null)
sb.append(commonStore.dump());
}
}
return sb.toString();
}
@Override
public void dump(@NotNull Writer writer, long fromIndex, long toIndex) {
try {
long firstIndex = firstIndex();
writer.append("# firstIndex: ").append(Long.toHexString(firstIndex)).append("\n");
try (ExcerptTailer tailer = createTailer()) {
if (!tailer.moveToIndex(fromIndex)) {
if (firstIndex > fromIndex) {
tailer.toStart();
} else {
return;
}
}
Bytes<?> bytes = acquireBytes();
TextWire text = new TextWire(bytes);
while (true) {
try (DocumentContext dc = tailer.readingDocument()) {
if (!dc.isPresent()) {
writer.append("# no more messages at ").append(Long.toHexString(dc.index())).append("\n");
return;
}
if (dc.index() > toIndex)
return;
writer.append("# index: ").append(Long.toHexString(dc.index())).append("\n");
Wire wire = dc.wire();
long start = wire.bytes().readPosition();
try {
text.clear();
wire.copyTo(text);
writer.append(bytes.toString());
} catch (Exception e) {
wire.bytes().readPosition(start);
writer.append(wire.bytes()).append("\n");
}
}
}
}
} catch (Exception e) {
e.printStackTrace(new PrintWriter(writer));
} finally {
try {
writer.flush();
} catch (IOException e) {
Jvm.debug().on(SingleChronicleQueue.class, e);
}
}
}
// Used in testing.
public long chunkCount() {
return chunkCount[0];
}
@Override
public int indexCount() {
return indexCount;
}
@Override
public int indexSpacing() {
return indexSpacing;
}
@Override
public long epoch() {
return epoch;
}
@Override
@NotNull
public RollCycle rollCycle() {
return this.rollCycle;
}
@Override
public int deltaCheckpointInterval() {
return deltaCheckpointInterval;
}
@Override
public FileShrinkage fileShrinkage() {
return fileShrink;
}
/**
* @return if we uses a ring buffer to buffer the appends, the Excerpts are written to the Chronicle Queue using a background thread
*/
public boolean buffered() {
return this.isBuffered;
}
@NotNull
public EventLoop eventLoop() {
return this.eventLoop;
}
/**
* Construct a new {@link ExcerptAppender} once the {@link #createAppenderCondition} is met.
* <p>
* This should be called by any sub-classes that require an appender but don't want to use
* the thread-local one that can be acquired via {@link #acquireAppender()}
*
* @return The new appender
*/
@NotNull
protected ExcerptAppender createNewAppenderOnceConditionIsMet() {
try {
createAppenderCondition.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedRuntimeException("Interrupted waiting for condition to create appender", e);
}
return constructAppender();
}
/**
* Construct a new {@link ExcerptAppender}.
* <p>
* This is protected so sub-classes can override the creation of an appender,
* to create a new appender, sub-classes should call {@link #createNewAppenderOnceConditionIsMet()}
*
* @return The new appender
*/
@NotNull
protected ExcerptAppender constructAppender() {
final WireStorePool newPool = WireStorePool.withSupplier(storeSupplier, storeFileListener);
return new StoreAppender(this, newPool, checkInterrupts);
}
protected StoreFileListener storeFileListener() {
return storeFileListener;
}
// used by enterprise CQ
WireStoreSupplier storeSupplier() {
return storeSupplier;
}
@NotNull
@Override
public ExcerptAppender acquireAppender() {
throwExceptionIfClosed();
if (readOnly)
throw new IllegalStateException("Can't append to a read-only chronicle");
ExcerptAppender res = strongExcerptAppenderThreadLocal.get();
if (res.isClosing())
strongExcerptAppenderThreadLocal.set(res = createNewAppenderOnceConditionIsMet());
return res;
}
/**
* @return the {@link QueueLock} This lock is held while the queue replication cluster is back-filling.
* By Back-filling we mean that, as part of the fail-over process a sink, may actually have more data than a source,
* hence we need to back copy data from the sinks to the source upon startup.
* While we are doing this we lock the queue so that new appenders can not be created.
* <p>
* Queue locks have no impact if you are not using queue replication because the are implemented as a no-op.
*/
@NotNull
public QueueLock queueLock() {
return queueLock;
}
/**
* @return the {@link WriteLock} that is used to lock writes to the queue. This is the mechanism used to
* coordinate writes from multiple threads and processes.
* <p>This lock should only be held for a short time, as it will block progress of any writers to
* this queue. The default behaviour of {@link TableStoreWriteLock} is to override the lock after a timeout.
*
* <p>This is also used to protect rolling to the next cycle
*/
@NotNull
WriteLock writeLock() {
return writeLock;
}
/**
* @return the {@link WriteLock} that is used to lock appends. This is only used by Queue Enterprise
* sink replication handlers. See Queue Enterprise docs for more details.
*/
public WriteLock appendLock() {
return appendLock;
}
@NotNull
@Override
public ExcerptTailer createTailer(String id) {
throwExceptionIfClosed();
LongValue index = id == null
? null
: indexForId(id);
final StoreTailer storeTailer = new StoreTailer(this, pool, index);
directoryListing.refresh(true);
storeTailer.clearUsedByThread();
return storeTailer;
}
@Override
@NotNull
public LongValue indexForId(@NotNull String id) {
return this.metaStore.doWithExclusiveLock((ts) -> ts.acquireValueFor("index." + id, 0L));
}
@NotNull
@Override
public ExcerptTailer createTailer() {
throwExceptionIfClosed();
return createTailer(null);
}
@Nullable
@Override
public final SingleChronicleQueueStore storeForCycle(int cycle, final long epoch, boolean createIfAbsent, SingleChronicleQueueStore oldStore) {
return this.pool.acquire(cycle, epoch, createIfAbsent, oldStore);
}
@Override
public int nextCycle(int cycle, @NotNull TailerDirection direction) throws ParseException {
throwExceptionIfClosed();
return pool.nextCycle(cycle, direction);
}
/**
* Returns a number of excerpts in a cycle. May use a fast path to return the cycle length cached in indexing,
* which is updated last during append operation so may be possible that a single entry is available for reading
* but not acknowledged by this method yet.
*/
public long approximateExcerptsInCycle(int cycle) {
throwExceptionIfClosed();
// TODO: this function may require some re-work now that acquireTailer has been deprecated
StoreTailer tailer = acquireTailer();
try {
return tailer.moveToCycle(cycle) ? tailer.store.approximateLastSequenceNumber(tailer) + 1 : -1;
} catch (StreamCorruptedException e) {
throw new IllegalStateException(e);
} finally {
tailer.releaseStore();
}
}
/**
* Returns an exact number of excerpts in a cycle available for reading. This may be a computationally
* expensive operation.
*/
public long exactExcerptsInCycle(int cycle) {
throwExceptionIfClosed();
// TODO: this function may require some re-work now that acquireTailer has been deprecated
StoreTailer tailer = acquireTailer();
try {
return tailer.moveToCycle(cycle) ? tailer.store.exactLastSequenceNumber(tailer) + 1 : -1;
} catch (StreamCorruptedException e) {
throw new IllegalStateException(e);
} finally {
tailer.releaseStore();
}
}
/**
* Will give you the number of excerpts between 2 index?s ( as exists on the current file system ). If intermediate chronicle files are removed
* this will effect the result.
*
* @param fromIndex the lower index
* @param toIndex the higher index
* @return will give you the number of excerpts between 2 index?s. It?s not as simple as just subtracting one number from the other.
* @throws IllegalStateException if we are not able to read the chronicle files
*/
@Override
public long countExcerpts(long fromIndex, long toIndex) {
throwExceptionIfClosed();
if (fromIndex > toIndex) {
long temp = fromIndex;
fromIndex = toIndex;
toIndex = temp;
}
// if the are the same
if (fromIndex == toIndex)
return 0;
long result = 0;
// some of the sequences maybe at -1 so we will add 1 to the cycle and update the result
// accordingly
RollCycle rollCycle = rollCycle();
long sequenceNotSet = rollCycle.toSequenceNumber(-1);
if (rollCycle.toSequenceNumber(fromIndex) == sequenceNotSet) {
result++;
fromIndex++;
}
if (rollCycle.toSequenceNumber(toIndex) == sequenceNotSet) {
result--;
toIndex++;
}
int lowerCycle = rollCycle.toCycle(fromIndex);
int upperCycle = rollCycle.toCycle(toIndex);
if (lowerCycle == upperCycle)
return toIndex - fromIndex;
long upperSeqNum = rollCycle.toSequenceNumber(toIndex);
long lowerSeqNum = rollCycle.toSequenceNumber(fromIndex);
if (lowerCycle + 1 == upperCycle) {
long l = exactExcerptsInCycle(lowerCycle);
result += (l - lowerSeqNum) + upperSeqNum;
return result;
}
NavigableSet<Long> cycles;
try {
cycles = listCyclesBetween(lowerCycle, upperCycle);
} catch (Exception e) {
throw new IllegalStateException(e);
}
if (cycles.first() == lowerCycle) {
// because we are inclusive, for example if we were at the end, then this
// is 1 except rather than zero
long l = exactExcerptsInCycle(lowerCycle);
result += (l - lowerSeqNum);
} else
throw new IllegalStateException("Cycle not found, lower-cycle=" + Long.toHexString(lowerCycle));
if (cycles.last() == upperCycle) {
result += upperSeqNum;
} else
throw new IllegalStateException("Cycle not found, upper-cycle=" + Long.toHexString(upperCycle));
if (cycles.size() == 2)
return result;
final long[] array = cycles.stream().mapToLong(i -> i).toArray();
for (int i = 1; i < array.length - 1; i++) {
long x = exactExcerptsInCycle(Math.toIntExact(array[i]));
result += x;
}
return result;
}
public NavigableSet<Long> listCyclesBetween(int lowerCycle, int upperCycle) throws ParseException {
throwExceptionIfClosed();
return pool.listCyclesBetween(lowerCycle, upperCycle);
}
public <T> void addCloseListener(Closeable key) {
synchronized (closers) {
if (!closers.isEmpty())
closers.removeIf(Closeable::isClosed);
closers.add(key);
}
}
@SuppressWarnings("unchecked")
@Override
protected void performClose() {
synchronized (closers) {
metaStoreMap.values().forEach(Closeable::closeQuietly);
metaStoreMap.clear();
closers.forEach(Closeable::closeQuietly);
closers.clear();
// must be closed after closers.
closeQuietly(
createAppenderCondition,
directoryListing,
queueLock,
lastAcknowledgedIndexReplicated,
lastIndexReplicated,
writeLock,
appendLock,
pool,
metaStore);
closeQuietly(storeSupplier);
}
// close it if we created it.
if (eventLoop instanceof OnDemandEventLoop)
eventLoop.close();
}
@Override
protected void finalize() throws Throwable {
super.finalize();
warnAndCloseIfNotClosed();
}
public final void closeStore(@Nullable SingleChronicleQueueStore store) {
if (store != null)
this.pool.closeStore(store);
}
@Override
public final int cycle() {
return cycleCalculator.currentCycle(rollCycle, time, epoch);
}
public final int cycle(TimeProvider timeProvider) {
return cycleCalculator.currentCycle(rollCycle, timeProvider, epoch);
}
@Override
public long firstIndex() {
// TODO - as discussed, peter is going find another way to do this as this solution
// currently breaks tests in chronicle engine - see net.openhft.chronicle.engine.queue.LocalQueueRefTest
int cycle = firstCycle();
if (cycle == Integer.MAX_VALUE)
return Long.MAX_VALUE;
return rollCycle().toIndex(cycle, 0);
}
@Override
public long lastIndex() {
// This is a slow implementation that gets a Tailer/DocumentContext to find the last index
try (final ExcerptTailer tailer = createTailer().direction(BACKWARD).toEnd()) {
try (final DocumentContext documentContext = tailer.readingDocument()) {
if (documentContext.isPresent()) {
return documentContext.index();
} else {
return -1;
}
}
}
}
/**
* This method creates a tailer and count the number of messages between the start of the queue ( see @link firstIndex() ) and the end.
*
* @return the number of messages in the queue
*/
@Override
public long entryCount() {
try (final ExcerptTailer tailer = createTailer()) {
tailer.toEnd();
long lastIndex = tailer.index();
if (lastIndex == 0)
return 0;
return countExcerpts(firstIndex(), lastIndex);
}
}
@Nullable
String[] getList() {
return path.list();
}
private void setFirstAndLastCycle() {
long now = System.currentTimeMillis();
if (now <= directoryListing.lastRefreshTimeMS()) {
return;
}
boolean force = now - directoryListing.lastRefreshTimeMS() > forceDirectoryListingRefreshIntervalMs;
directoryListing.refresh(force);
}
@Override
public int firstCycle() {
setFirstAndLastCycle();
return directoryListing.getMinCreatedCycle();
}
/**
* allows the appenders to inform the queue that they have rolled
*
* @param cycle the cycle the appender has rolled to
*/
void onRoll(int cycle) {
directoryListing.onRoll(cycle);
}
@Override
public int lastCycle() {
setFirstAndLastCycle();
return directoryListing.getMaxCreatedCycle();
}
@NotNull
public Consumer<BytesRingBufferStats> onRingBufferStats() {
return this.onRingBufferStats;
}
public long blockSize() {
return this.blockSize;
}
// *************************************************************************
//
// *************************************************************************
public long overlapSize() {
return this.overlapSize;
}
@NotNull
@Override
public WireType wireType() {
return wireType;
}
public long bufferCapacity() {
return this.bufferCapacity;
}
@NotNull
@PackageLocal
MappedFile mappedFile(File file) throws FileNotFoundException {
long chunkSize = OS.pageAlign(blockSize);
long overlapSize = OS.pageAlign(Math.min(blockSize / 4, 1L << 30));
return useSparseFile
? MappedFile.ofSingle(file, sparseCapacity, readOnly)
: MappedFile.of(file, chunkSize, overlapSize, readOnly);
}
boolean isReadOnly() {
return readOnly;
}
@NotNull
@Override
public String toString() {
return this.getClass().getSimpleName() + "{" +
"sourceId=" + sourceId +
", file=" + path +
'}';
}
@NotNull
public TimeProvider time() {
return time;
}
@NotNull
private ToIntFunction<String> fileNameToCycleFunction() {
return name -> dateCache.parseCount(name.substring(0, name.length() - SUFFIX.length()));
}
void removeCloseListener(final StoreTailer storeTailer) {
synchronized (closers) {
closers.remove(storeTailer);
}
}
public TableStore metaStore() {
return metaStore;
}
void cleanupStoreFilesWithNoData() {
long start = System.nanoTime();
writeLock.lock();
Runnable fireOnReleasedEvent = null;
try {
int cycle = cycle();
for (int lastCycle = lastCycle(); lastCycle < cycle && lastCycle >= 0; lastCycle--) {
try (final SingleChronicleQueueStore store = this.pool.acquire(lastCycle, epoch(), false, null)) {
// file not found.
if (store == null)
break;
if (store.writePosition() == 0 && store.file().exists()) {
// try writing EOF
// if this blows up we should blow up too so don't catch anything
MappedBytes bytes = store.bytes();
try {
final Wire wire = wireType.apply(bytes);
wire.usePadding(true);
store.writeEOFAndShrink(wire, timeoutMS);
} finally {
bytes.releaseLast();
}
continue;
}
fireOnReleasedEvent = () -> storeFileListener.onReleased(store.cycle(), store.file());
break;
}
}
directoryListing.refresh(true);
} finally {
writeLock.unlock();
if(fireOnReleasedEvent != null)
BackgroundResourceReleaser.run(fireOnReleasedEvent);
long tookMillis = (System.nanoTime() - start) / 1_000_000;
if (tookMillis > WARN_SLOW_APPENDER_MS)
Jvm.perf().on(getClass(), "Took " + tookMillis + "ms to cleanupStoreFilesWithNoData");
}
}
public void tableStorePut(CharSequence key, long index) {
LongValue longValue = tableStoreAcquire(key, index);
if (longValue == null) return;
if (index == Long.MIN_VALUE)
longValue.setVolatileValue(index);
else
longValue.setMaxValue(index);
}
@Nullable
protected LongValue tableStoreAcquire(CharSequence key, long index) {
BytesStore keyBytes = asBytes(key);
LongValue longValue = metaStoreMap.get(keyBytes);
if (longValue == null) {
synchronized (closers) {
longValue = metaStoreMap.get(keyBytes);
if (longValue == null) {
longValue = metaStore.acquireValueFor(key, index);
int length = key.length();
HeapBytesStore<byte[]> key2 = HeapBytesStore.wrap(new byte[length]);
key2.write(0, keyBytes, 0, length);
metaStoreMap.put(key2, longValue);
return null;
}
}
}
return longValue;
}
public long tableStoreGet(CharSequence key) {
LongValue longValue = tableStoreAcquire(key, Long.MIN_VALUE);
if (longValue == null) return Long.MIN_VALUE;
return longValue.getVolatileValue();
}