Search in sources :

Example 66 with ChronicleQueue

use of net.openhft.chronicle.queue.ChronicleQueue in project Chronicle-Queue by OpenHFT.

the class TailerTest method reproduce.

@Test
public void reproduce() {
    IOTools.deleteDirWithFiles(QUEUE_PATH.toFile());
    long firstOutputIndex = Long.MAX_VALUE;
    long lastOutputIndex = Long.MIN_VALUE;
    try (ChronicleQueue q = createQueue();
        ExcerptAppender appender = q.acquireAppender();
        ExcerptTailer tailer = q.createTailer()) {
        for (int i = 0; i < 5; i++) {
            final String text = "Hello World " + i;
            try (DocumentContext dc = appender.writingDocument()) {
                dc.wire().writeText(text);
            }
            System.out.format("Appended \"%s\" at %d%n", text, appender.lastIndexAppended());
            firstOutputIndex = Math.min(firstOutputIndex, appender.lastIndexAppended());
            lastOutputIndex = Math.max(lastOutputIndex, appender.lastIndexAppended());
        }
        System.out.format("firstOutputIndex = %d%n", firstOutputIndex);
        System.out.format("lastOutputIndex = %d%n", lastOutputIndex);
        System.out.println("Reading initial");
        drainTailer(tailer);
    }
    try (ChronicleQueue q = createQueue();
        ExcerptTailer tailer = q.createTailer()) {
        initRecovery(tailer, firstOutputIndex + OFFSET);
        final List<String> messages = drainTailer(tailer);
        assertEquals("Hello World " + OFFSET, messages.get(0));
    }
}
Also used : ChronicleQueue(net.openhft.chronicle.queue.ChronicleQueue) ExcerptAppender(net.openhft.chronicle.queue.ExcerptAppender) DocumentContext(net.openhft.chronicle.wire.DocumentContext) ExcerptTailer(net.openhft.chronicle.queue.ExcerptTailer) Test(org.junit.Test)

Example 67 with ChronicleQueue

use of net.openhft.chronicle.queue.ChronicleQueue in project Chronicle-Queue by OpenHFT.

the class LatencyDistributionMain method run.

public void run(String[] args) throws InterruptedException {
    File tmpDir = getTmpDir();
    SingleChronicleQueueBuilder builder = SingleChronicleQueueBuilder.fieldlessBinary(tmpDir).blockSize(128 << 20);
    try (ChronicleQueue queue = builder.writeBufferMode(BUFFER_MODE).readBufferMode(BufferMode.None).build();
        ChronicleQueue queue2 = builder.writeBufferMode(BufferMode.None).readBufferMode(BUFFER_MODE).build()) {
        runTest(queue, queue2);
    }
    IOTools.deleteDirWithFiles(tmpDir, 2);
}
Also used : SingleChronicleQueueBuilder(net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder) ChronicleQueue(net.openhft.chronicle.queue.ChronicleQueue) File(java.io.File)

Example 68 with ChronicleQueue

use of net.openhft.chronicle.queue.ChronicleQueue in project Chronicle-Queue by OpenHFT.

the class LatencyDistributionMain method runTest.

protected void runTest(@NotNull ChronicleQueue queue, @NotNull ChronicleQueue queue2) throws InterruptedException {
    Histogram histogramCo = new Histogram();
    Histogram histogramIn = new Histogram();
    Histogram histogramWr = new Histogram();
    Thread pretoucher = new Thread(() -> {
        ExcerptAppender appender = queue.acquireAppender();
        try {
            while (!Thread.currentThread().isInterrupted()) {
                appender.pretouch();
                Jvm.pause(50);
            }
        } catch (Exception e) {
            if (!appender.isClosed())
                e.printStackTrace();
        }
    });
    pretoucher.setDaemon(true);
    pretoucher.start();
    ExcerptAppender appender = queue.acquireAppender();
    // two queues as most like in a different process.
    ExcerptTailer tailer = queue2.createTailer();
    String name = getClass().getName();
    Thread tailerThread = new Thread(() -> {
        AffinityLock lock = null;
        try {
            if (Jvm.getBoolean("enableTailerAffinity") || !Jvm.getBoolean("disableAffinity")) {
                lock = Affinity.acquireLock();
            }
            int counter = 0;
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    // if (SAMPLING)
                    // sampler.thread(Thread.currentThread());
                    // boolean found = tailer.readDocument(myReadMarshallable);
                    boolean found;
                    try (DocumentContext dc = tailer.readingDocument()) {
                        found = dc.isPresent();
                        if (found) {
                            int count = counter++;
                            if (count == WARMUP) {
                                histogramCo.reset();
                                histogramIn.reset();
                                histogramWr.reset();
                            }
                            Bytes<?> bytes = dc.wire().bytes();
                            long startCo = bytes.readLong();
                            long startIn = bytes.readLong();
                            long now = System.nanoTime();
                            histogramCo.sample(now - startCo);
                            histogramIn.sample(now - startIn);
                            if (count % INTLOG_INTERVAL == 0)
                                System.out.println("read  " + count);
                        }
                    }
                /*
                        if (SAMPLING) {
                            StackTraceElement[] stack = sampler.getAndReset();
                            if (stack != null) {
                                if (!stack[0].getClassName().equals(name) &&
                                        !stack[0].getClassName().equals("java.lang.Thread")) {
                                    StringBuilder sb = new StringBuilder();
                                    Jvm.trimStackTrace(sb, stack);
                                   // System.out.println(sb);
                                }
                            } else if (!found) {
                                Thread.yield();
                            }
                        }
                        */
                } catch (Exception e) {
                    break;
                }
            }
        } finally {
            if (lock != null) {
                lock.release();
            }
        }
    });
    Thread appenderThread = new Thread(() -> {
        AffinityLock lock = null;
        try {
            if (Jvm.getBoolean("enableAppenderAffinity") || !Jvm.getBoolean("disableAffinity")) {
                lock = Affinity.acquireLock();
            }
            long next = System.nanoTime();
            long interval = 1_000_000_000 / throughput;
            Map<String, Integer> stackCount = new LinkedHashMap<>();
            BytesStore<?, ?> bytes24 = BytesStore.nativeStoreFrom(new byte[Main.size - 16]);
            for (int i = -WARMUP; i < iterations; i++) {
                long s0 = System.nanoTime();
                if (s0 < next) {
                    do ; while (System.nanoTime() < next);
                    // if we failed to come out of the spin loop on time, reset next.
                    next = System.nanoTime();
                }
                if (SAMPLING) {
                    sampler.thread(Thread.currentThread());
                }
                long start = System.nanoTime();
                try (@NotNull DocumentContext dc = appender.writingDocument(false)) {
                    Wire wire = dc.wire();
                    Bytes<?> bytes2 = wire.bytes();
                    // when it should have started
                    bytes2.writeLong(next);
                    // when it actually started.
                    bytes2.writeLong(start);
                    bytes2.write(bytes24);
                    ThroughputMain.addToEndOfCache(wire);
                }
                long time = System.nanoTime() - start;
                histogramWr.sample(start - next);
                if (SAMPLING && time > 1e3 && i > 0) {
                    StackTraceElement[] stack = sampler.getAndReset();
                    if (stack != null) {
                        if (!stack[0].getClassName().equals(name) && !stack[0].getClassName().equals("java.lang.Thread")) {
                            StringBuilder sb = new StringBuilder();
                            Jvm.trimStackTrace(sb, stack);
                            stackCount.compute(sb.toString(), (k, v) -> v == null ? 1 : v + 1);
                        }
                    }
                }
                next += interval;
                if (i % INTLOG_INTERVAL == 0)
                    System.out.println("wrote " + i);
            }
            stackCount.entrySet().stream().filter(e -> e.getValue() > 1).forEach(System.out::println);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (lock != null) {
                lock.release();
            }
        }
    });
    tailerThread.start();
    appenderThread.start();
    appenderThread.join();
    pretoucher.interrupt();
    pretoucher.join();
    // Pause to allow tailer to catch up (if needed)
    Jvm.pause(500);
    tailerThread.interrupt();
    tailerThread.join();
    System.out.println("wr: " + histogramWr.toLongMicrosFormat());
    System.out.println("in: " + histogramIn.toLongMicrosFormat());
    System.out.println("co: " + histogramCo.toLongMicrosFormat());
}
Also used : StackSampler(net.openhft.chronicle.core.threads.StackSampler) ExcerptTailer(net.openhft.chronicle.queue.ExcerptTailer) DocumentContext(net.openhft.chronicle.wire.DocumentContext) Histogram(net.openhft.chronicle.core.util.Histogram) ChronicleQueue(net.openhft.chronicle.queue.ChronicleQueue) BytesStore(net.openhft.chronicle.bytes.BytesStore) Wire(net.openhft.chronicle.wire.Wire) Main(net.openhft.chronicle.queue.benchmark.Main) Jvm(net.openhft.chronicle.core.Jvm) File(java.io.File) BufferMode(net.openhft.chronicle.queue.BufferMode) Time(net.openhft.chronicle.core.util.Time) LinkedHashMap(java.util.LinkedHashMap) SingleChronicleQueueBuilder(net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder) Nullable(org.jetbrains.annotations.Nullable) Bytes(net.openhft.chronicle.bytes.Bytes) AffinityLock(net.openhft.affinity.AffinityLock) IOTools(net.openhft.chronicle.core.io.IOTools) Map(java.util.Map) ExcerptAppender(net.openhft.chronicle.queue.ExcerptAppender) NotNull(org.jetbrains.annotations.NotNull) Affinity(net.openhft.affinity.Affinity) Histogram(net.openhft.chronicle.core.util.Histogram) Wire(net.openhft.chronicle.wire.Wire) NotNull(org.jetbrains.annotations.NotNull) ExcerptTailer(net.openhft.chronicle.queue.ExcerptTailer) AffinityLock(net.openhft.affinity.AffinityLock) LinkedHashMap(java.util.LinkedHashMap) ExcerptAppender(net.openhft.chronicle.queue.ExcerptAppender) DocumentContext(net.openhft.chronicle.wire.DocumentContext)

Example 69 with ChronicleQueue

use of net.openhft.chronicle.queue.ChronicleQueue in project Chronicle-Queue by OpenHFT.

the class SingleChronicleQueueTest method testSingleWire.

// *************************************************************************
// 
// *************************************************************************
@Test
public void testSingleWire() {
    final File file = createTempFile("testSingleWire");
    try {
        final ChronicleQueue chronicle = createQueue(file);
        final ExcerptAppender appender = chronicle.acquireAppender();
        appender.writeDocument(wire -> wire.write("FirstName").text("Steve"));
        appender.writeDocument(wire -> wire.write("Surname").text("Jobs"));
        StringBuilder first = new StringBuilder();
        StringBuilder surname = new StringBuilder();
        final ExcerptTailer tailer = chronicle.createTailer();
        tailer.readDocument(wire -> wire.read("FirstName").text(first));
        tailer.readDocument(wire -> wire.read("Surname").text(surname));
        Assert.assertEquals("Steve Jobs", first + " " + surname);
    } finally {
        file.delete();
    }
}
Also used : ChronicleQueue(net.openhft.chronicle.queue.ChronicleQueue) ExcerptAppender(net.openhft.chronicle.queue.ExcerptAppender) File(java.io.File) ExcerptTailer(net.openhft.chronicle.queue.ExcerptTailer) Test(org.junit.Test)

Example 70 with ChronicleQueue

use of net.openhft.chronicle.queue.ChronicleQueue in project Chronicle-Queue by OpenHFT.

the class ChronicleReader method execute.

public void execute() {
    long lastObservedTailIndex;
    long highestReachedIndex = 0L;
    boolean isFirstIteration = true;
    boolean retryLastOperation;
    boolean queueHasBeenModified;
    final AtomicLong matchCounter = new AtomicLong(0L);
    do {
        try (final ChronicleQueue queue = createQueue();
            final QueueEntryHandler messageConverter = entryHandlerFactory.get()) {
            final ExcerptTailer tailer = queue.createTailer();
            MessageHistory.set(new VanillaMessageHistory());
            tlTailer = ThreadLocal.withInitial(queue::createTailer);
            do {
                if (highestReachedIndex != 0L) {
                    tailer.moveToIndex(highestReachedIndex);
                }
                final Bytes textConversionTarget = Bytes.elasticByteBuffer();
                try {
                    moveToSpecifiedPosition(queue, tailer, isFirstIteration);
                    lastObservedTailIndex = tailer.index();
                    Consumer<String> messageConsumer = text -> applyFiltersAndLog(text, tailer.index(), matchCounter);
                    BooleanSupplier readOne;
                    if (methodReaderInterface == null) {
                        readOne = () -> readOne(messageConverter, tailer, messageConsumer);
                    } else {
                        // TODO: consider unifying this with messageConverter
                        Bytes<ByteBuffer> bytes = Bytes.elasticHeapByteBuffer(256);
                        Wire wire = wireType.apply(bytes);
                        if (wire instanceof TextWire)
                            ((TextWire) wire).useTextDocuments();
                        MethodWriterBuilder<?> mwb = wire.methodWriterBuilder(methodReaderInterface);
                        if (showMessageHistory)
                            mwb.updateInterceptor((methodName, t) -> {
                                MessageHistory messageHistory = MessageHistory.get();
                                // this is an attempt to recognise that no MH was read and instead the method reader called reset(...) on it
                                if (messageHistory.sources() != 1 || messageHistory.timings() != 1)
                                    bytes.append(messageHistory + System.lineSeparator());
                                return true;
                            });
                        MethodReader methodReader = tailer.methodReader(mwb.build());
                        readOne = () -> {
                            boolean found = methodReader.readOne();
                            if (found)
                                messageConsumer.accept(bytes.toString());
                            bytes.clear();
                            return found;
                        };
                    }
                    while (!Thread.currentThread().isInterrupted()) {
                        boolean found = readOne.getAsBoolean();
                        if (!found) {
                            if (tailInputSource) {
                                pauser.pause();
                            }
                            break;
                        } else {
                            if (matchLimitReached(matchCounter.get())) {
                                break;
                            }
                        }
                        pauser.reset();
                    }
                } finally {
                    textConversionTarget.releaseLast();
                    highestReachedIndex = tailer.index();
                    isFirstIteration = false;
                }
                queueHasBeenModified = queueHasBeenModifiedSinceLastCheck(lastObservedTailIndex);
                retryLastOperation = false;
                if (!running || matchLimitReached(matchCounter.get()))
                    return;
            } while (tailerDirection != BACKWARD && (tailInputSource || queueHasBeenModified));
        } catch (final RuntimeException e) {
            if (e.getCause() != null && e.getCause() instanceof DateTimeParseException) {
                // ignore this error - due to a race condition between
                // the reader creating a Queue (with default roll-cycle due to no files on disk)
                // and the writer appending to the Queue with a non-default roll-cycle
                retryLastOperation = true;
            } else {
                throw e;
            }
        }
    } while (retryLastOperation);
}
Also used : MethodReader(net.openhft.chronicle.bytes.MethodReader) FORWARD(net.openhft.chronicle.queue.TailerDirection.FORWARD) BACKWARD(net.openhft.chronicle.queue.TailerDirection.BACKWARD) TailerDirection(net.openhft.chronicle.queue.TailerDirection) NotComparableException(net.openhft.chronicle.queue.impl.single.NotComparableException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Jvm(net.openhft.chronicle.core.Jvm) ByteBuffer(java.nio.ByteBuffer) ArrayList(java.util.ArrayList) BooleanSupplier(java.util.function.BooleanSupplier) Bytes(net.openhft.chronicle.bytes.Bytes) SingleChronicleQueue(net.openhft.chronicle.queue.impl.single.SingleChronicleQueue) net.openhft.chronicle.wire(net.openhft.chronicle.wire) MethodWriterBuilder(net.openhft.chronicle.bytes.MethodWriterBuilder) ParseException(java.text.ParseException) Path(java.nio.file.Path) Pauser(net.openhft.chronicle.threads.Pauser) ExcerptTailer(net.openhft.chronicle.queue.ExcerptTailer) Files(java.nio.file.Files) NO_OP(net.openhft.chronicle.queue.impl.StoreFileListener.NO_OP) ChronicleQueue(net.openhft.chronicle.queue.ChronicleQueue) Consumer(java.util.function.Consumer) SingleChronicleQueueBuilder(net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder) Nullable(org.jetbrains.annotations.Nullable) AtomicLong(java.util.concurrent.atomic.AtomicLong) DateTimeParseException(java.time.format.DateTimeParseException) List(java.util.List) ToolsUtil(net.openhft.chronicle.queue.util.ToolsUtil) Pattern(java.util.regex.Pattern) NotNull(org.jetbrains.annotations.NotNull) BinarySearch(net.openhft.chronicle.queue.impl.single.BinarySearch) BinarySearchComparator(net.openhft.chronicle.queue.reader.comparator.BinarySearchComparator) ByteBuffer(java.nio.ByteBuffer) ExcerptTailer(net.openhft.chronicle.queue.ExcerptTailer) Bytes(net.openhft.chronicle.bytes.Bytes) DateTimeParseException(java.time.format.DateTimeParseException) AtomicLong(java.util.concurrent.atomic.AtomicLong) SingleChronicleQueue(net.openhft.chronicle.queue.impl.single.SingleChronicleQueue) ChronicleQueue(net.openhft.chronicle.queue.ChronicleQueue) BooleanSupplier(java.util.function.BooleanSupplier) MethodReader(net.openhft.chronicle.bytes.MethodReader)

Aggregations

ChronicleQueue (net.openhft.chronicle.queue.ChronicleQueue)80 Test (org.junit.Test)59 ExcerptAppender (net.openhft.chronicle.queue.ExcerptAppender)37 ExcerptTailer (net.openhft.chronicle.queue.ExcerptTailer)37 File (java.io.File)36 DocumentContext (net.openhft.chronicle.wire.DocumentContext)21 ArrayList (java.util.ArrayList)16 SingleChronicleQueueBuilder (net.openhft.chronicle.queue.impl.single.SingleChronicleQueueBuilder)14 MethodReader (net.openhft.chronicle.bytes.MethodReader)12 List (java.util.List)11 IOException (java.io.IOException)9 MappedFile (net.openhft.chronicle.bytes.MappedFile)8 Path (java.nio.file.Path)7 Bytes (net.openhft.chronicle.bytes.Bytes)7 Collections (java.util.Collections)6 RollCycles (net.openhft.chronicle.queue.RollCycles)6 NotNull (org.jetbrains.annotations.NotNull)6 ByteBuffer (java.nio.ByteBuffer)5 MappedBytes (net.openhft.chronicle.bytes.MappedBytes)5 Histogram (net.openhft.chronicle.core.util.Histogram)5