001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.activemq.store.kahadb;
018
019import static org.apache.activemq.store.kahadb.disk.journal.Location.NOT_SET;
020
021import java.io.ByteArrayInputStream;
022import java.io.ByteArrayOutputStream;
023import java.io.DataInput;
024import java.io.DataOutput;
025import java.io.EOFException;
026import java.io.File;
027import java.io.IOException;
028import java.io.InputStream;
029import java.io.InterruptedIOException;
030import java.io.ObjectInputStream;
031import java.io.ObjectOutputStream;
032import java.io.OutputStream;
033import java.util.ArrayList;
034import java.util.Arrays;
035import java.util.Collection;
036import java.util.Collections;
037import java.util.Date;
038import java.util.HashMap;
039import java.util.HashSet;
040import java.util.Iterator;
041import java.util.LinkedHashMap;
042import java.util.LinkedHashSet;
043import java.util.LinkedList;
044import java.util.List;
045import java.util.Map;
046import java.util.Map.Entry;
047import java.util.Set;
048import java.util.SortedSet;
049import java.util.TreeMap;
050import java.util.TreeSet;
051import java.util.concurrent.ConcurrentHashMap;
052import java.util.concurrent.ConcurrentMap;
053import java.util.concurrent.Executors;
054import java.util.concurrent.ScheduledExecutorService;
055import java.util.concurrent.ThreadFactory;
056import java.util.concurrent.TimeUnit;
057import java.util.concurrent.atomic.AtomicBoolean;
058import java.util.concurrent.atomic.AtomicLong;
059import java.util.concurrent.atomic.AtomicReference;
060import java.util.concurrent.locks.ReentrantReadWriteLock;
061
062import org.apache.activemq.ActiveMQMessageAuditNoSync;
063import org.apache.activemq.broker.BrokerService;
064import org.apache.activemq.broker.BrokerServiceAware;
065import org.apache.activemq.broker.region.Destination;
066import org.apache.activemq.broker.region.Queue;
067import org.apache.activemq.broker.region.Topic;
068import org.apache.activemq.command.MessageAck;
069import org.apache.activemq.command.TransactionId;
070import org.apache.activemq.openwire.OpenWireFormat;
071import org.apache.activemq.protobuf.Buffer;
072import org.apache.activemq.store.MessageStore;
073import org.apache.activemq.store.MessageStoreStatistics;
074import org.apache.activemq.store.MessageStoreSubscriptionStatistics;
075import org.apache.activemq.store.TopicMessageStore;
076import org.apache.activemq.store.kahadb.data.KahaAckMessageFileMapCommand;
077import org.apache.activemq.store.kahadb.data.KahaAddMessageCommand;
078import org.apache.activemq.store.kahadb.data.KahaCommitCommand;
079import org.apache.activemq.store.kahadb.data.KahaDestination;
080import org.apache.activemq.store.kahadb.data.KahaEntryType;
081import org.apache.activemq.store.kahadb.data.KahaPrepareCommand;
082import org.apache.activemq.store.kahadb.data.KahaProducerAuditCommand;
083import org.apache.activemq.store.kahadb.data.KahaRemoveDestinationCommand;
084import org.apache.activemq.store.kahadb.data.KahaRemoveMessageCommand;
085import org.apache.activemq.store.kahadb.data.KahaRewrittenDataFileCommand;
086import org.apache.activemq.store.kahadb.data.KahaRollbackCommand;
087import org.apache.activemq.store.kahadb.data.KahaSubscriptionCommand;
088import org.apache.activemq.store.kahadb.data.KahaTraceCommand;
089import org.apache.activemq.store.kahadb.data.KahaTransactionInfo;
090import org.apache.activemq.store.kahadb.data.KahaUpdateMessageCommand;
091import org.apache.activemq.store.kahadb.disk.index.BTreeIndex;
092import org.apache.activemq.store.kahadb.disk.index.BTreeVisitor;
093import org.apache.activemq.store.kahadb.disk.index.ListIndex;
094import org.apache.activemq.store.kahadb.disk.journal.DataFile;
095import org.apache.activemq.store.kahadb.disk.journal.Journal;
096import org.apache.activemq.store.kahadb.disk.journal.Journal.JournalDiskSyncStrategy;
097import org.apache.activemq.store.kahadb.disk.journal.Location;
098import org.apache.activemq.store.kahadb.disk.journal.TargetedDataFileAppender;
099import org.apache.activemq.store.kahadb.disk.page.Page;
100import org.apache.activemq.store.kahadb.disk.page.PageFile;
101import org.apache.activemq.store.kahadb.disk.page.Transaction;
102import org.apache.activemq.store.kahadb.disk.util.LocationMarshaller;
103import org.apache.activemq.store.kahadb.disk.util.LongMarshaller;
104import org.apache.activemq.store.kahadb.disk.util.Marshaller;
105import org.apache.activemq.store.kahadb.disk.util.Sequence;
106import org.apache.activemq.store.kahadb.disk.util.SequenceSet;
107import org.apache.activemq.store.kahadb.disk.util.StringMarshaller;
108import org.apache.activemq.store.kahadb.disk.util.VariableMarshaller;
109import org.apache.activemq.util.ByteSequence;
110import org.apache.activemq.util.DataByteArrayInputStream;
111import org.apache.activemq.util.DataByteArrayOutputStream;
112import org.apache.activemq.util.IOExceptionSupport;
113import org.apache.activemq.util.IOHelper;
114import org.apache.activemq.util.ServiceStopper;
115import org.apache.activemq.util.ServiceSupport;
116import org.apache.activemq.util.ThreadPoolUtils;
117import org.slf4j.Logger;
118import org.slf4j.LoggerFactory;
119import org.slf4j.MDC;
120
121public abstract class MessageDatabase extends ServiceSupport implements BrokerServiceAware {
122
123    protected BrokerService brokerService;
124
125    public static final String PROPERTY_LOG_SLOW_ACCESS_TIME = "org.apache.activemq.store.kahadb.LOG_SLOW_ACCESS_TIME";
126    public static final int LOG_SLOW_ACCESS_TIME = Integer.getInteger(PROPERTY_LOG_SLOW_ACCESS_TIME, 0);
127    public static final File DEFAULT_DIRECTORY = new File("KahaDB");
128    protected static final Buffer UNMATCHED;
129    static {
130        UNMATCHED = new Buffer(new byte[]{});
131    }
132    private static final Logger LOG = LoggerFactory.getLogger(MessageDatabase.class);
133
134    static final int CLOSED_STATE = 1;
135    static final int OPEN_STATE = 2;
136    static final long NOT_ACKED = -1;
137
138    static final int VERSION = 6;
139
140    static final byte COMPACTED_JOURNAL_FILE = DataFile.STANDARD_LOG_FILE + 1;
141
142    protected class Metadata {
143        protected Page<Metadata> page;
144        protected int state;
145        protected BTreeIndex<String, StoredDestination> destinations;
146        protected Location lastUpdate;
147        protected Location firstInProgressTransactionLocation;
148        protected Location producerSequenceIdTrackerLocation = null;
149        protected Location ackMessageFileMapLocation = null;
150        protected transient ActiveMQMessageAuditNoSync producerSequenceIdTracker = new ActiveMQMessageAuditNoSync();
151        protected transient Map<Integer, Set<Integer>> ackMessageFileMap = new HashMap<>();
152        protected int version = VERSION;
153        protected int openwireVersion = OpenWireFormat.DEFAULT_STORE_VERSION;
154
155        public void read(DataInput is) throws IOException {
156            state = is.readInt();
157            destinations = new BTreeIndex<>(pageFile, is.readLong());
158            if (is.readBoolean()) {
159                lastUpdate = LocationMarshaller.INSTANCE.readPayload(is);
160            } else {
161                lastUpdate = null;
162            }
163            if (is.readBoolean()) {
164                firstInProgressTransactionLocation = LocationMarshaller.INSTANCE.readPayload(is);
165            } else {
166                firstInProgressTransactionLocation = null;
167            }
168            try {
169                if (is.readBoolean()) {
170                    producerSequenceIdTrackerLocation = LocationMarshaller.INSTANCE.readPayload(is);
171                } else {
172                    producerSequenceIdTrackerLocation = null;
173                }
174            } catch (EOFException expectedOnUpgrade) {
175            }
176            try {
177                version = is.readInt();
178            } catch (EOFException expectedOnUpgrade) {
179                version = 1;
180            }
181            if (version >= 5 && is.readBoolean()) {
182                ackMessageFileMapLocation = LocationMarshaller.INSTANCE.readPayload(is);
183            } else {
184                ackMessageFileMapLocation = null;
185            }
186            try {
187                openwireVersion = is.readInt();
188            } catch (EOFException expectedOnUpgrade) {
189                openwireVersion = OpenWireFormat.DEFAULT_LEGACY_VERSION;
190            }
191            LOG.info("KahaDB is version " + version);
192        }
193
194        public void write(DataOutput os) throws IOException {
195            os.writeInt(state);
196            os.writeLong(destinations.getPageId());
197
198            if (lastUpdate != null) {
199                os.writeBoolean(true);
200                LocationMarshaller.INSTANCE.writePayload(lastUpdate, os);
201            } else {
202                os.writeBoolean(false);
203            }
204
205            if (firstInProgressTransactionLocation != null) {
206                os.writeBoolean(true);
207                LocationMarshaller.INSTANCE.writePayload(firstInProgressTransactionLocation, os);
208            } else {
209                os.writeBoolean(false);
210            }
211
212            if (producerSequenceIdTrackerLocation != null) {
213                os.writeBoolean(true);
214                LocationMarshaller.INSTANCE.writePayload(producerSequenceIdTrackerLocation, os);
215            } else {
216                os.writeBoolean(false);
217            }
218            os.writeInt(VERSION);
219            if (ackMessageFileMapLocation != null) {
220                os.writeBoolean(true);
221                LocationMarshaller.INSTANCE.writePayload(ackMessageFileMapLocation, os);
222            } else {
223                os.writeBoolean(false);
224            }
225            os.writeInt(this.openwireVersion);
226        }
227    }
228
229    class MetadataMarshaller extends VariableMarshaller<Metadata> {
230        @Override
231        public Metadata readPayload(DataInput dataIn) throws IOException {
232            Metadata rc = createMetadata();
233            rc.read(dataIn);
234            return rc;
235        }
236
237        @Override
238        public void writePayload(Metadata object, DataOutput dataOut) throws IOException {
239            object.write(dataOut);
240        }
241    }
242
243    protected PageFile pageFile;
244    protected Journal journal;
245    protected Metadata metadata = new Metadata();
246
247    protected MetadataMarshaller metadataMarshaller = new MetadataMarshaller();
248
249    protected boolean failIfDatabaseIsLocked;
250
251    protected boolean deleteAllMessages;
252    protected File directory = DEFAULT_DIRECTORY;
253    protected File indexDirectory = null;
254    protected ScheduledExecutorService scheduler;
255    private final Object schedulerLock = new Object();
256
257    protected JournalDiskSyncStrategy journalDiskSyncStrategy = JournalDiskSyncStrategy.ALWAYS;
258    protected boolean archiveDataLogs;
259    protected File directoryArchive;
260    protected AtomicLong journalSize = new AtomicLong(0);
261    long journalDiskSyncInterval = 1000;
262    long checkpointInterval = 5*1000;
263    long cleanupInterval = 30*1000;
264    int journalMaxFileLength = Journal.DEFAULT_MAX_FILE_LENGTH;
265    int journalMaxWriteBatchSize = Journal.DEFAULT_MAX_WRITE_BATCH_SIZE;
266    boolean enableIndexWriteAsync = false;
267    int setIndexWriteBatchSize = PageFile.DEFAULT_WRITE_BATCH_SIZE;
268    private String preallocationScope = Journal.PreallocationScope.ENTIRE_JOURNAL.name();
269    private String preallocationStrategy = Journal.PreallocationStrategy.SPARSE_FILE.name();
270
271    protected AtomicBoolean opened = new AtomicBoolean();
272    private boolean ignoreMissingJournalfiles = false;
273    private int indexCacheSize = 10000;
274    private boolean checkForCorruptJournalFiles = false;
275    private boolean checksumJournalFiles = true;
276    protected boolean forceRecoverIndex = false;
277    private boolean archiveCorruptedIndex = false;
278    private boolean useIndexLFRUEviction = false;
279    private float indexLFUEvictionFactor = 0.2f;
280    private boolean enableIndexDiskSyncs = true;
281    private boolean enableIndexRecoveryFile = true;
282    private boolean enableIndexPageCaching = true;
283    ReentrantReadWriteLock checkpointLock = new ReentrantReadWriteLock();
284
285    private boolean enableAckCompaction = true;
286    private int compactAcksAfterNoGC = 10;
287    private boolean compactAcksIgnoresStoreGrowth = false;
288    private int checkPointCyclesWithNoGC;
289    private int journalLogOnLastCompactionCheck;
290    private boolean enableSubscriptionStatistics = false;
291
292    //only set when using JournalDiskSyncStrategy.PERIODIC
293    protected final AtomicReference<Location> lastAsyncJournalUpdate = new AtomicReference<>();
294
295    @Override
296    public void doStart() throws Exception {
297        load();
298    }
299
300    @Override
301    public void doStop(ServiceStopper stopper) throws Exception {
302        unload();
303    }
304
305    public void allowIOResumption() {
306        if (pageFile != null) {
307            pageFile.allowIOResumption();
308        }
309        if (journal != null) {
310            journal.allowIOResumption();
311        }
312    }
313
314    private void loadPageFile() throws IOException {
315        this.indexLock.writeLock().lock();
316        try {
317            final PageFile pageFile = getPageFile();
318            pageFile.load();
319            pageFile.tx().execute(new Transaction.Closure<IOException>() {
320                @Override
321                public void execute(Transaction tx) throws IOException {
322                    if (pageFile.getPageCount() == 0) {
323                        // First time this is created.. Initialize the metadata
324                        Page<Metadata> page = tx.allocate();
325                        assert page.getPageId() == 0;
326                        page.set(metadata);
327                        metadata.page = page;
328                        metadata.state = CLOSED_STATE;
329                        metadata.destinations = new BTreeIndex<>(pageFile, tx.allocate().getPageId());
330
331                        tx.store(metadata.page, metadataMarshaller, true);
332                    } else {
333                        Page<Metadata> page = tx.load(0, metadataMarshaller);
334                        metadata = page.get();
335                        metadata.page = page;
336                    }
337                    metadata.destinations.setKeyMarshaller(StringMarshaller.INSTANCE);
338                    metadata.destinations.setValueMarshaller(new StoredDestinationMarshaller());
339                    metadata.destinations.load(tx);
340                }
341            });
342            // Load up all the destinations since we need to scan all the indexes to figure out which journal files can be deleted.
343            // Perhaps we should just keep an index of file
344            storedDestinations.clear();
345            pageFile.tx().execute(new Transaction.Closure<IOException>() {
346                @Override
347                public void execute(Transaction tx) throws IOException {
348                    for (Iterator<Entry<String, StoredDestination>> iterator = metadata.destinations.iterator(tx); iterator.hasNext();) {
349                        Entry<String, StoredDestination> entry = iterator.next();
350                        StoredDestination sd = loadStoredDestination(tx, entry.getKey(), entry.getValue().subscriptions!=null);
351                        storedDestinations.put(entry.getKey(), sd);
352
353                        if (checkForCorruptJournalFiles) {
354                            // sanity check the index also
355                            if (!entry.getValue().locationIndex.isEmpty(tx)) {
356                                if (entry.getValue().orderIndex.nextMessageId <= 0) {
357                                    throw new IOException("Detected uninitialized orderIndex nextMessageId with pending messages for " + entry.getKey());
358                                }
359                            }
360                        }
361                    }
362                }
363            });
364            pageFile.flush();
365        } finally {
366            this.indexLock.writeLock().unlock();
367        }
368    }
369
370    private void startCheckpoint() {
371        if (checkpointInterval == 0 && cleanupInterval == 0) {
372            LOG.info("periodic checkpoint/cleanup disabled, will ocurr on clean shutdown/restart");
373            return;
374        }
375        synchronized (schedulerLock) {
376            if (scheduler == null || scheduler.isShutdown()) {
377                scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
378
379                    @Override
380                    public Thread newThread(Runnable r) {
381                        Thread schedulerThread = new Thread(r);
382
383                        schedulerThread.setName("ActiveMQ Journal Checkpoint Worker");
384                        schedulerThread.setDaemon(true);
385
386                        return schedulerThread;
387                    }
388                });
389
390                // Short intervals for check-point and cleanups
391                long delay;
392                if (journal.isJournalDiskSyncPeriodic()) {
393                    delay = Math.min(journalDiskSyncInterval > 0 ? journalDiskSyncInterval : checkpointInterval, 500);
394                } else {
395                    delay = Math.min(checkpointInterval > 0 ? checkpointInterval : cleanupInterval, 500);
396                }
397
398                scheduler.scheduleWithFixedDelay(new CheckpointRunner(), 0, delay, TimeUnit.MILLISECONDS);
399            }
400        }
401    }
402
403    private final class CheckpointRunner implements Runnable {
404
405        private long lastCheckpoint = System.currentTimeMillis();
406        private long lastCleanup = System.currentTimeMillis();
407        private long lastSync = System.currentTimeMillis();
408        private Location lastAsyncUpdate = null;
409
410        @Override
411        public void run() {
412            try {
413                // Decide on cleanup vs full checkpoint here.
414                if (opened.get()) {
415                    long now = System.currentTimeMillis();
416                    if (journal.isJournalDiskSyncPeriodic() &&
417                            journalDiskSyncInterval > 0 && (now - lastSync >= journalDiskSyncInterval)) {
418                        Location currentUpdate = lastAsyncJournalUpdate.get();
419                        if (currentUpdate != null && !currentUpdate.equals(lastAsyncUpdate)) {
420                            lastAsyncUpdate = currentUpdate;
421                            if (LOG.isTraceEnabled()) {
422                                LOG.trace("Writing trace command to trigger journal sync");
423                            }
424                            store(new KahaTraceCommand(), true, null, null);
425                        }
426                        lastSync = now;
427                    }
428                    if (cleanupInterval > 0 && (now - lastCleanup >= cleanupInterval)) {
429                        checkpointCleanup(true);
430                        lastCleanup = now;
431                        lastCheckpoint = now;
432                    } else if (checkpointInterval > 0 && (now - lastCheckpoint >= checkpointInterval)) {
433                        checkpointCleanup(false);
434                        lastCheckpoint = now;
435                    }
436                }
437            } catch (IOException ioe) {
438                LOG.error("Checkpoint failed", ioe);
439                brokerService.handleIOException(ioe);
440            } catch (Throwable e) {
441                LOG.error("Checkpoint failed", e);
442                brokerService.handleIOException(IOExceptionSupport.create(e));
443            }
444        }
445    }
446
447    public void open() throws IOException {
448        if( opened.compareAndSet(false, true) ) {
449            getJournal().start();
450            try {
451                loadPageFile();
452            } catch (Throwable t) {
453                LOG.warn("Index corrupted. Recovering the index through journal replay. Cause:" + t);
454                if (LOG.isDebugEnabled()) {
455                    LOG.debug("Index load failure", t);
456                }
457                // try to recover index
458                try {
459                    pageFile.unload();
460                } catch (Exception ignore) {}
461                if (archiveCorruptedIndex) {
462                    pageFile.archive();
463                } else {
464                    pageFile.delete();
465                }
466                metadata = createMetadata();
467                //The metadata was recreated after a detect corruption so we need to
468                //reconfigure anything that was configured on the old metadata on startup
469                configureMetadata();
470                pageFile = null;
471                loadPageFile();
472            }
473            recover();
474            startCheckpoint();
475        }
476    }
477
478    public void load() throws IOException {
479        this.indexLock.writeLock().lock();
480        try {
481            IOHelper.mkdirs(directory);
482            if (deleteAllMessages) {
483                getJournal().start();
484                getJournal().delete();
485                getJournal().close();
486                journal = null;
487                getPageFile().delete();
488                LOG.info("Persistence store purged.");
489                deleteAllMessages = false;
490            }
491
492            open();
493            store(new KahaTraceCommand().setMessage("LOADED " + new Date()));
494        } finally {
495            this.indexLock.writeLock().unlock();
496        }
497    }
498
499    public void close() throws IOException, InterruptedException {
500        if (opened.compareAndSet(true, false)) {
501            checkpointLock.writeLock().lock();
502            try {
503                if (metadata.page != null) {
504                    checkpointUpdate(true);
505                }
506                pageFile.unload();
507                metadata = createMetadata();
508            } finally {
509                checkpointLock.writeLock().unlock();
510            }
511            journal.close();
512            synchronized(schedulerLock) {
513                if (scheduler != null) {
514                    ThreadPoolUtils.shutdownGraceful(scheduler, -1);
515                    scheduler = null;
516                }
517            }
518            // clear the cache and journalSize on shutdown of the store
519            storeCache.clear();
520            journalSize.set(0);
521        }
522    }
523
524    public void unload() throws IOException, InterruptedException {
525        this.indexLock.writeLock().lock();
526        try {
527            if( pageFile != null && pageFile.isLoaded() ) {
528                metadata.state = CLOSED_STATE;
529                metadata.firstInProgressTransactionLocation = getInProgressTxLocationRange()[0];
530
531                if (metadata.page != null) {
532                    pageFile.tx().execute(new Transaction.Closure<IOException>() {
533                        @Override
534                        public void execute(Transaction tx) throws IOException {
535                            tx.store(metadata.page, metadataMarshaller, true);
536                        }
537                    });
538                }
539            }
540        } finally {
541            this.indexLock.writeLock().unlock();
542        }
543        close();
544    }
545
546    // public for testing
547    @SuppressWarnings("rawtypes")
548    public Location[] getInProgressTxLocationRange() {
549        Location[] range = new Location[]{null, null};
550        synchronized (inflightTransactions) {
551            if (!inflightTransactions.isEmpty()) {
552                for (List<Operation> ops : inflightTransactions.values()) {
553                    if (!ops.isEmpty()) {
554                        trackMaxAndMin(range, ops);
555                    }
556                }
557            }
558            if (!preparedTransactions.isEmpty()) {
559                for (List<Operation> ops : preparedTransactions.values()) {
560                    if (!ops.isEmpty()) {
561                        trackMaxAndMin(range, ops);
562                    }
563                }
564            }
565        }
566        return range;
567    }
568
569    @SuppressWarnings("rawtypes")
570    private void trackMaxAndMin(Location[] range, List<Operation> ops) {
571        Location t = ops.get(0).getLocation();
572        if (range[0] == null || t.compareTo(range[0]) <= 0) {
573            range[0] = t;
574        }
575        t = ops.get(ops.size() -1).getLocation();
576        if (range[1] == null || t.compareTo(range[1]) >= 0) {
577            range[1] = t;
578        }
579    }
580
581    class TranInfo {
582        TransactionId id;
583        Location location;
584
585        class opCount {
586            int add;
587            int remove;
588        }
589        HashMap<KahaDestination, opCount> destinationOpCount = new HashMap<>();
590
591        @SuppressWarnings("rawtypes")
592        public void track(Operation operation) {
593            if (location == null ) {
594                location = operation.getLocation();
595            }
596            KahaDestination destination;
597            boolean isAdd = false;
598            if (operation instanceof AddOperation) {
599                AddOperation add = (AddOperation) operation;
600                destination = add.getCommand().getDestination();
601                isAdd = true;
602            } else {
603                RemoveOperation removeOpperation = (RemoveOperation) operation;
604                destination = removeOpperation.getCommand().getDestination();
605            }
606            opCount opCount = destinationOpCount.get(destination);
607            if (opCount == null) {
608                opCount = new opCount();
609                destinationOpCount.put(destination, opCount);
610            }
611            if (isAdd) {
612                opCount.add++;
613            } else {
614                opCount.remove++;
615            }
616        }
617
618        @Override
619        public String toString() {
620           StringBuffer buffer = new StringBuffer();
621           buffer.append(location).append(";").append(id).append(";\n");
622           for (Entry<KahaDestination, opCount> op : destinationOpCount.entrySet()) {
623               buffer.append(op.getKey()).append('+').append(op.getValue().add).append(',').append('-').append(op.getValue().remove).append(';');
624           }
625           return buffer.toString();
626        }
627    }
628
629    @SuppressWarnings("rawtypes")
630    public String getTransactions() {
631
632        ArrayList<TranInfo> infos = new ArrayList<>();
633        synchronized (inflightTransactions) {
634            if (!inflightTransactions.isEmpty()) {
635                for (Entry<TransactionId, List<Operation>> entry : inflightTransactions.entrySet()) {
636                    TranInfo info = new TranInfo();
637                    info.id = entry.getKey();
638                    for (Operation operation : entry.getValue()) {
639                        info.track(operation);
640                    }
641                    infos.add(info);
642                }
643            }
644        }
645        synchronized (preparedTransactions) {
646            if (!preparedTransactions.isEmpty()) {
647                for (Entry<TransactionId, List<Operation>> entry : preparedTransactions.entrySet()) {
648                    TranInfo info = new TranInfo();
649                    info.id = entry.getKey();
650                    for (Operation operation : entry.getValue()) {
651                        info.track(operation);
652                    }
653                    infos.add(info);
654                }
655            }
656        }
657        return infos.toString();
658    }
659
660    /**
661     * Move all the messages that were in the journal into long term storage. We
662     * just replay and do a checkpoint.
663     *
664     * @throws IOException
665     * @throws IOException
666     * @throws IllegalStateException
667     */
668    private void recover() throws IllegalStateException, IOException {
669        this.indexLock.writeLock().lock();
670        try {
671
672            long start = System.currentTimeMillis();
673            Location afterProducerAudit = recoverProducerAudit();
674            Location afterAckMessageFile = recoverAckMessageFileMap();
675            Location lastIndoubtPosition = getRecoveryPosition();
676
677            if (afterProducerAudit != null && afterProducerAudit.equals(metadata.ackMessageFileMapLocation)) {
678                // valid checkpoint, possible recover from afterAckMessageFile
679                afterProducerAudit = null;
680            }
681            Location recoveryPosition = minimum(afterProducerAudit, afterAckMessageFile);
682            recoveryPosition = minimum(recoveryPosition, lastIndoubtPosition);
683
684            if (recoveryPosition != null) {
685                int redoCounter = 0;
686                int dataFileRotationTracker = recoveryPosition.getDataFileId();
687                LOG.info("Recovering from the journal @" + recoveryPosition);
688                while (recoveryPosition != null) {
689                    try {
690                        JournalCommand<?> message = load(recoveryPosition);
691                        metadata.lastUpdate = recoveryPosition;
692                        process(message, recoveryPosition, lastIndoubtPosition);
693                        redoCounter++;
694                    } catch (IOException failedRecovery) {
695                        if (isIgnoreMissingJournalfiles()) {
696                            LOG.debug("Failed to recover data at position:" + recoveryPosition, failedRecovery);
697                            // track this dud location
698                            journal.corruptRecoveryLocation(recoveryPosition);
699                        } else {
700                            throw new IOException("Failed to recover data at position:" + recoveryPosition, failedRecovery);
701                        }
702                    }
703                    recoveryPosition = journal.getNextLocation(recoveryPosition);
704                    // hold on to the minimum number of open files during recovery
705                    if (recoveryPosition != null && dataFileRotationTracker != recoveryPosition.getDataFileId()) {
706                        dataFileRotationTracker = recoveryPosition.getDataFileId();
707                        journal.cleanup();
708                    }
709                    if (LOG.isInfoEnabled() && redoCounter % 100000 == 0) {
710                        LOG.info("@" + recoveryPosition + ", " + redoCounter + " entries recovered ..");
711                    }
712                }
713                if (LOG.isInfoEnabled()) {
714                    long end = System.currentTimeMillis();
715                    LOG.info("Recovery replayed " + redoCounter + " operations from the journal in " + ((end - start) / 1000.0f) + " seconds.");
716                }
717            }
718
719            // We may have to undo some index updates.
720            pageFile.tx().execute(new Transaction.Closure<IOException>() {
721                @Override
722                public void execute(Transaction tx) throws IOException {
723                    recoverIndex(tx);
724                }
725            });
726
727            // rollback any recovered inflight local transactions, and discard any inflight XA transactions.
728            Set<TransactionId> toRollback = new HashSet<>();
729            Set<TransactionId> toDiscard = new HashSet<>();
730            synchronized (inflightTransactions) {
731                for (Iterator<TransactionId> it = inflightTransactions.keySet().iterator(); it.hasNext(); ) {
732                    TransactionId id = it.next();
733                    if (id.isLocalTransaction()) {
734                        toRollback.add(id);
735                    } else {
736                        toDiscard.add(id);
737                    }
738                }
739                for (TransactionId tx: toRollback) {
740                    if (LOG.isDebugEnabled()) {
741                        LOG.debug("rolling back recovered indoubt local transaction " + tx);
742                    }
743                    store(new KahaRollbackCommand().setTransactionInfo(TransactionIdConversion.convertToLocal(tx)), false, null, null);
744                }
745                for (TransactionId tx: toDiscard) {
746                    if (LOG.isDebugEnabled()) {
747                        LOG.debug("discarding recovered in-flight XA transaction " + tx);
748                    }
749                    inflightTransactions.remove(tx);
750                }
751            }
752
753            synchronized (preparedTransactions) {
754                for (TransactionId txId : preparedTransactions.keySet()) {
755                    LOG.warn("Recovered prepared XA TX: [{}]", txId);
756                }
757            }
758
759        } finally {
760            this.indexLock.writeLock().unlock();
761        }
762    }
763
764    @SuppressWarnings("unused")
765    private KahaTransactionInfo createLocalTransactionInfo(TransactionId tx) {
766        return TransactionIdConversion.convertToLocal(tx);
767    }
768
769    private Location minimum(Location x,
770                             Location y) {
771        Location min = null;
772        if (x != null) {
773            min = x;
774            if (y != null) {
775                int compare = y.compareTo(x);
776                if (compare < 0) {
777                    min = y;
778                }
779            }
780        } else {
781            min = y;
782        }
783        return min;
784    }
785
786    private Location recoverProducerAudit() throws IOException {
787        if (metadata.producerSequenceIdTrackerLocation != null) {
788            try {
789                KahaProducerAuditCommand audit = (KahaProducerAuditCommand) load(metadata.producerSequenceIdTrackerLocation);
790                ObjectInputStream objectIn = new ObjectInputStream(audit.getAudit().newInput());
791                int maxNumProducers = getMaxFailoverProducersToTrack();
792                int maxAuditDepth = getFailoverProducersAuditDepth();
793                metadata.producerSequenceIdTracker = (ActiveMQMessageAuditNoSync) objectIn.readObject();
794                metadata.producerSequenceIdTracker.setAuditDepth(maxAuditDepth);
795                metadata.producerSequenceIdTracker.setMaximumNumberOfProducersToTrack(maxNumProducers);
796                return getNextInitializedLocation(metadata.producerSequenceIdTrackerLocation);
797            } catch (Exception e) {
798                LOG.warn("Cannot recover message audit", e);
799                return journal.getNextLocation(null);
800            }
801        } else {
802            // got no audit stored so got to recreate via replay from start of the journal
803            return journal.getNextLocation(null);
804        }
805    }
806
807    @SuppressWarnings("unchecked")
808    private Location recoverAckMessageFileMap() throws IOException {
809        if (metadata.ackMessageFileMapLocation != null) {
810            try {
811                KahaAckMessageFileMapCommand audit = (KahaAckMessageFileMapCommand) load(metadata.ackMessageFileMapLocation);
812                ObjectInputStream objectIn = new ObjectInputStream(audit.getAckMessageFileMap().newInput());
813                metadata.ackMessageFileMap = (Map<Integer, Set<Integer>>) objectIn.readObject();
814                return getNextInitializedLocation(metadata.ackMessageFileMapLocation);
815            } catch (Exception e) {
816                LOG.warn("Cannot recover ackMessageFileMap", e);
817                return journal.getNextLocation(null);
818            }
819        } else {
820            // got no ackMessageFileMap stored so got to recreate via replay from start of the journal
821            return journal.getNextLocation(null);
822        }
823    }
824
825    protected void recoverIndex(Transaction tx) throws IOException {
826        long start = System.currentTimeMillis();
827        // It is possible index updates got applied before the journal updates..
828        // in that case we need to removed references to messages that are not in the journal
829        final Location lastAppendLocation = journal.getLastAppendLocation();
830        long undoCounter=0;
831
832        // Go through all the destinations to see if they have messages past the lastAppendLocation
833        for (String key : storedDestinations.keySet()) {
834            StoredDestination sd = storedDestinations.get(key);
835
836            final ArrayList<Long> matches = new ArrayList<>();
837            // Find all the Locations that are >= than the last Append Location.
838            sd.locationIndex.visit(tx, new BTreeVisitor.GTEVisitor<Location, Long>(lastAppendLocation) {
839                @Override
840                protected void matched(Location key, Long value) {
841                    matches.add(value);
842                }
843            });
844
845            for (Long sequenceId : matches) {
846                MessageKeys keys = sd.orderIndex.remove(tx, sequenceId);
847                if (keys != null) {
848                    sd.locationIndex.remove(tx, keys.location);
849                    sd.messageIdIndex.remove(tx, keys.messageId);
850                    metadata.producerSequenceIdTracker.rollback(keys.messageId);
851                    undoCounter++;
852                    decrementAndSubSizeToStoreStat(key, keys.location.getSize());
853                    // TODO: do we need to modify the ack positions for the pub sub case?
854                }
855            }
856        }
857
858        if (undoCounter > 0) {
859            // The rolledback operations are basically in flight journal writes.  To avoid getting
860            // these the end user should do sync writes to the journal.
861            if (LOG.isInfoEnabled()) {
862                long end = System.currentTimeMillis();
863                LOG.info("Rolled back " + undoCounter + " messages from the index in " + ((end - start) / 1000.0f) + " seconds.");
864            }
865        }
866
867        undoCounter = 0;
868        start = System.currentTimeMillis();
869
870        // Lets be extra paranoid here and verify that all the datafiles being referenced
871        // by the indexes still exists.
872
873        final SequenceSet ss = new SequenceSet();
874        for (StoredDestination sd : storedDestinations.values()) {
875            // Use a visitor to cut down the number of pages that we load
876            sd.locationIndex.visit(tx, new BTreeVisitor<Location, Long>() {
877                int last=-1;
878
879                @Override
880                public boolean isInterestedInKeysBetween(Location first, Location second) {
881                    if( first==null ) {
882                        return !ss.contains(0, second.getDataFileId());
883                    } else if( second==null ) {
884                        return true;
885                    } else {
886                        return !ss.contains(first.getDataFileId(), second.getDataFileId());
887                    }
888                }
889
890                @Override
891                public void visit(List<Location> keys, List<Long> values) {
892                    for (Location l : keys) {
893                        int fileId = l.getDataFileId();
894                        if( last != fileId ) {
895                            ss.add(fileId);
896                            last = fileId;
897                        }
898                    }
899                }
900
901            });
902        }
903        HashSet<Integer> missingJournalFiles = new HashSet<>();
904        while (!ss.isEmpty()) {
905            missingJournalFiles.add((int) ss.removeFirst());
906        }
907
908        for (Entry<Integer, Set<Integer>> entry : metadata.ackMessageFileMap.entrySet()) {
909            missingJournalFiles.add(entry.getKey());
910            for (Integer i : entry.getValue()) {
911                missingJournalFiles.add(i);
912            }
913        }
914
915        missingJournalFiles.removeAll(journal.getFileMap().keySet());
916
917        if (!missingJournalFiles.isEmpty()) {
918            LOG.warn("Some journal files are missing: " + missingJournalFiles);
919        }
920
921        ArrayList<BTreeVisitor.Predicate<Location>> knownCorruption = new ArrayList<>();
922        ArrayList<BTreeVisitor.Predicate<Location>> missingPredicates = new ArrayList<>();
923        for (Integer missing : missingJournalFiles) {
924            missingPredicates.add(new BTreeVisitor.BetweenVisitor<Location, Long>(new Location(missing, 0), new Location(missing + 1, 0)));
925        }
926
927        if (checkForCorruptJournalFiles) {
928            Collection<DataFile> dataFiles = journal.getFileMap().values();
929            for (DataFile dataFile : dataFiles) {
930                int id = dataFile.getDataFileId();
931                // eof to next file id
932                missingPredicates.add(new BTreeVisitor.BetweenVisitor<Location, Long>(new Location(id, dataFile.getLength()), new Location(id + 1, 0)));
933                Sequence seq = dataFile.getCorruptedBlocks().getHead();
934                while (seq != null) {
935                    BTreeVisitor.BetweenVisitor<Location, Long> visitor =
936                        new BTreeVisitor.BetweenVisitor<>(new Location(id, (int) seq.getFirst()), new Location(id, (int) seq.getLast() + 1));
937                    missingPredicates.add(visitor);
938                    knownCorruption.add(visitor);
939                    seq = seq.getNext();
940                }
941            }
942        }
943
944        if (!missingPredicates.isEmpty()) {
945            for (Entry<String, StoredDestination> sdEntry : storedDestinations.entrySet()) {
946                final StoredDestination sd = sdEntry.getValue();
947                final LinkedHashMap<Long, Location> matches = new LinkedHashMap<>();
948                sd.locationIndex.visit(tx, new BTreeVisitor.OrVisitor<Location, Long>(missingPredicates) {
949                    @Override
950                    protected void matched(Location key, Long value) {
951                        matches.put(value, key);
952                    }
953                });
954
955                // If some message references are affected by the missing data files...
956                if (!matches.isEmpty()) {
957
958                    // We either 'gracefully' recover dropping the missing messages or
959                    // we error out.
960                    if( ignoreMissingJournalfiles ) {
961                        // Update the index to remove the references to the missing data
962                        for (Long sequenceId : matches.keySet()) {
963                            MessageKeys keys = sd.orderIndex.remove(tx, sequenceId);
964                            sd.locationIndex.remove(tx, keys.location);
965                            sd.messageIdIndex.remove(tx, keys.messageId);
966                            LOG.info("[" + sdEntry.getKey() + "] dropped: " + keys.messageId + " at corrupt location: " + keys.location);
967                            undoCounter++;
968                            decrementAndSubSizeToStoreStat(sdEntry.getKey(), keys.location.getSize());
969                            // TODO: do we need to modify the ack positions for the pub sub case?
970                        }
971                    } else {
972                        LOG.error("[" + sdEntry.getKey() + "] references corrupt locations: " + matches);
973                        throw new IOException("Detected missing/corrupt journal files referenced by:[" + sdEntry.getKey() + "] " +matches.size()+" messages affected.");
974                    }
975                }
976            }
977        }
978
979        if (!ignoreMissingJournalfiles) {
980            if (!knownCorruption.isEmpty()) {
981                LOG.error("Detected corrupt journal files. " + knownCorruption);
982                throw new IOException("Detected corrupt journal files. " + knownCorruption);
983            }
984
985            if (!missingJournalFiles.isEmpty()) {
986                LOG.error("Detected missing journal files. " + missingJournalFiles);
987                throw new IOException("Detected missing journal files. " + missingJournalFiles);
988            }
989        }
990
991        if (undoCounter > 0) {
992            // The rolledback operations are basically in flight journal writes.  To avoid getting these the end user
993            // should do sync writes to the journal.
994            if (LOG.isInfoEnabled()) {
995                long end = System.currentTimeMillis();
996                LOG.info("Detected missing/corrupt journal files.  Dropped " + undoCounter + " messages from the index in " + ((end - start) / 1000.0f) + " seconds.");
997            }
998        }
999    }
1000
1001    private Location nextRecoveryPosition;
1002    private Location lastRecoveryPosition;
1003
1004    public void incrementalRecover() throws IOException {
1005        this.indexLock.writeLock().lock();
1006        try {
1007            if( nextRecoveryPosition == null ) {
1008                if( lastRecoveryPosition==null ) {
1009                    nextRecoveryPosition = getRecoveryPosition();
1010                } else {
1011                    nextRecoveryPosition = journal.getNextLocation(lastRecoveryPosition);
1012                }
1013            }
1014            while (nextRecoveryPosition != null) {
1015                lastRecoveryPosition = nextRecoveryPosition;
1016                metadata.lastUpdate = lastRecoveryPosition;
1017                JournalCommand<?> message = load(lastRecoveryPosition);
1018                process(message, lastRecoveryPosition, (IndexAware) null);
1019                nextRecoveryPosition = journal.getNextLocation(lastRecoveryPosition);
1020            }
1021        } finally {
1022            this.indexLock.writeLock().unlock();
1023        }
1024    }
1025
1026    public Location getLastUpdatePosition() throws IOException {
1027        return metadata.lastUpdate;
1028    }
1029
1030    private Location getRecoveryPosition() throws IOException {
1031
1032        if (!this.forceRecoverIndex) {
1033
1034            // If we need to recover the transactions..
1035            if (metadata.firstInProgressTransactionLocation != null) {
1036                return metadata.firstInProgressTransactionLocation;
1037            }
1038
1039            // Perhaps there were no transactions...
1040            if( metadata.lastUpdate!=null) {
1041                // Start replay at the record after the last one recorded in the index file.
1042                return getNextInitializedLocation(metadata.lastUpdate);
1043            }
1044        }
1045        // This loads the first position.
1046        return journal.getNextLocation(null);
1047    }
1048
1049    private Location getNextInitializedLocation(Location location) throws IOException {
1050        Location mayNotBeInitialized = journal.getNextLocation(location);
1051        if (location.getSize() == NOT_SET && mayNotBeInitialized.getSize() != NOT_SET) {
1052            // need to init size and type to skip
1053            return journal.getNextLocation(mayNotBeInitialized);
1054        } else {
1055            return mayNotBeInitialized;
1056        }
1057    }
1058
1059    protected void checkpointCleanup(final boolean cleanup) throws IOException {
1060        long start;
1061        this.indexLock.writeLock().lock();
1062        try {
1063            start = System.currentTimeMillis();
1064            if( !opened.get() ) {
1065                return;
1066            }
1067        } finally {
1068            this.indexLock.writeLock().unlock();
1069        }
1070        checkpointUpdate(cleanup);
1071        long end = System.currentTimeMillis();
1072        if (LOG_SLOW_ACCESS_TIME > 0 && end - start > LOG_SLOW_ACCESS_TIME) {
1073            if (LOG.isInfoEnabled()) {
1074                LOG.info("Slow KahaDB access: cleanup took " + (end - start));
1075            }
1076        }
1077    }
1078
1079    public ByteSequence toByteSequence(JournalCommand<?> data) throws IOException {
1080        int size = data.serializedSizeFramed();
1081        DataByteArrayOutputStream os = new DataByteArrayOutputStream(size + 1);
1082        os.writeByte(data.type().getNumber());
1083        data.writeFramed(os);
1084        return os.toByteSequence();
1085    }
1086
1087    // /////////////////////////////////////////////////////////////////
1088    // Methods call by the broker to update and query the store.
1089    // /////////////////////////////////////////////////////////////////
1090    public Location store(JournalCommand<?> data) throws IOException {
1091        return store(data, false, null,null);
1092    }
1093
1094    public Location store(JournalCommand<?> data, Runnable onJournalStoreComplete) throws IOException {
1095        return store(data, false, null, null, onJournalStoreComplete);
1096    }
1097
1098    public Location store(JournalCommand<?> data, boolean sync, IndexAware before,Runnable after) throws IOException {
1099        return store(data, sync, before, after, null);
1100    }
1101
1102    /**
1103     * All updated are are funneled through this method. The updates are converted
1104     * to a JournalMessage which is logged to the journal and then the data from
1105     * the JournalMessage is used to update the index just like it would be done
1106     * during a recovery process.
1107     */
1108    public Location store(JournalCommand<?> data, boolean sync, IndexAware before, Runnable after, Runnable onJournalStoreComplete) throws IOException {
1109        try {
1110            ByteSequence sequence = toByteSequence(data);
1111            Location location;
1112
1113            checkpointLock.readLock().lock();
1114            try {
1115
1116                long start = System.currentTimeMillis();
1117                location = onJournalStoreComplete == null ? journal.write(sequence, sync) : journal.write(sequence, onJournalStoreComplete) ;
1118                long start2 = System.currentTimeMillis();
1119                //Track the last async update so we know if we need to sync at the next checkpoint
1120                if (!sync && journal.isJournalDiskSyncPeriodic()) {
1121                    lastAsyncJournalUpdate.set(location);
1122                }
1123                process(data, location, before);
1124
1125                long end = System.currentTimeMillis();
1126                if (LOG_SLOW_ACCESS_TIME > 0 && end - start > LOG_SLOW_ACCESS_TIME) {
1127                    if (LOG.isInfoEnabled()) {
1128                        LOG.info("Slow KahaDB access: Journal append took: "+(start2-start)+" ms, Index update took "+(end-start2)+" ms");
1129                    }
1130                }
1131            } finally {
1132                checkpointLock.readLock().unlock();
1133            }
1134
1135            if (after != null) {
1136                after.run();
1137            }
1138
1139            if (scheduler == null && opened.get()) {
1140                startCheckpoint();
1141            }
1142            return location;
1143        } catch (IOException ioe) {
1144            LOG.error("KahaDB failed to store to Journal, command of type: " + data.type(), ioe);
1145            brokerService.handleIOException(ioe);
1146            throw ioe;
1147        }
1148    }
1149
1150    /**
1151     * Loads a previously stored JournalMessage
1152     *
1153     * @param location
1154     * @return
1155     * @throws IOException
1156     */
1157    public JournalCommand<?> load(Location location) throws IOException {
1158        long start = System.currentTimeMillis();
1159        ByteSequence data = journal.read(location);
1160        long end = System.currentTimeMillis();
1161        if( LOG_SLOW_ACCESS_TIME>0 && end-start > LOG_SLOW_ACCESS_TIME) {
1162            if (LOG.isInfoEnabled()) {
1163                LOG.info("Slow KahaDB access: Journal read took: "+(end-start)+" ms");
1164            }
1165        }
1166        DataByteArrayInputStream is = new DataByteArrayInputStream(data);
1167        byte readByte = is.readByte();
1168        KahaEntryType type = KahaEntryType.valueOf(readByte);
1169        if( type == null ) {
1170            try {
1171                is.close();
1172            } catch (IOException e) {}
1173            throw new IOException("Could not load journal record, null type information from: " + readByte + " at location: "+location);
1174        }
1175        JournalCommand<?> message = (JournalCommand<?>)type.createMessage();
1176        message.mergeFramed(is);
1177        return message;
1178    }
1179
1180    /**
1181     * do minimal recovery till we reach the last inDoubtLocation
1182     * @param data
1183     * @param location
1184     * @param inDoubtlocation
1185     * @throws IOException
1186     */
1187    void process(JournalCommand<?> data, final Location location, final Location inDoubtlocation) throws IOException {
1188        if (inDoubtlocation != null && location.compareTo(inDoubtlocation) >= 0) {
1189            process(data, location, (IndexAware) null);
1190        } else {
1191            // just recover producer audit
1192            data.visit(new Visitor() {
1193                @Override
1194                public void visit(KahaAddMessageCommand command) throws IOException {
1195                    metadata.producerSequenceIdTracker.isDuplicate(command.getMessageId());
1196                }
1197            });
1198        }
1199    }
1200
1201    // /////////////////////////////////////////////////////////////////
1202    // Journaled record processing methods. Once the record is journaled,
1203    // these methods handle applying the index updates. These may be called
1204    // from the recovery method too so they need to be idempotent
1205    // /////////////////////////////////////////////////////////////////
1206
1207    void process(JournalCommand<?> data, final Location location, final IndexAware onSequenceAssignedCallback) throws IOException {
1208        data.visit(new Visitor() {
1209            @Override
1210            public void visit(KahaAddMessageCommand command) throws IOException {
1211                process(command, location, onSequenceAssignedCallback);
1212            }
1213
1214            @Override
1215            public void visit(KahaRemoveMessageCommand command) throws IOException {
1216                process(command, location);
1217            }
1218
1219            @Override
1220            public void visit(KahaPrepareCommand command) throws IOException {
1221                process(command, location);
1222            }
1223
1224            @Override
1225            public void visit(KahaCommitCommand command) throws IOException {
1226                process(command, location, onSequenceAssignedCallback);
1227            }
1228
1229            @Override
1230            public void visit(KahaRollbackCommand command) throws IOException {
1231                process(command, location);
1232            }
1233
1234            @Override
1235            public void visit(KahaRemoveDestinationCommand command) throws IOException {
1236                process(command, location);
1237            }
1238
1239            @Override
1240            public void visit(KahaSubscriptionCommand command) throws IOException {
1241                process(command, location);
1242            }
1243
1244            @Override
1245            public void visit(KahaProducerAuditCommand command) throws IOException {
1246                processLocation(location);
1247            }
1248
1249            @Override
1250            public void visit(KahaAckMessageFileMapCommand command) throws IOException {
1251                processLocation(location);
1252            }
1253
1254            @Override
1255            public void visit(KahaTraceCommand command) {
1256                processLocation(location);
1257            }
1258
1259            @Override
1260            public void visit(KahaUpdateMessageCommand command) throws IOException {
1261                process(command, location);
1262            }
1263
1264            @Override
1265            public void visit(KahaRewrittenDataFileCommand command) throws IOException {
1266                process(command, location);
1267            }
1268        });
1269    }
1270
1271    @SuppressWarnings("rawtypes")
1272    protected void process(final KahaAddMessageCommand command, final Location location, final IndexAware runWithIndexLock) throws IOException {
1273        if (command.hasTransactionInfo()) {
1274            List<Operation> inflightTx = getInflightTx(command.getTransactionInfo());
1275            inflightTx.add(new AddOperation(command, location, runWithIndexLock));
1276        } else {
1277            this.indexLock.writeLock().lock();
1278            try {
1279                pageFile.tx().execute(new Transaction.Closure<IOException>() {
1280                    @Override
1281                    public void execute(Transaction tx) throws IOException {
1282                        long assignedIndex = updateIndex(tx, command, location);
1283                        if (runWithIndexLock != null) {
1284                            runWithIndexLock.sequenceAssignedWithIndexLocked(assignedIndex);
1285                        }
1286                    }
1287                });
1288
1289            } finally {
1290                this.indexLock.writeLock().unlock();
1291            }
1292        }
1293    }
1294
1295    protected void process(final KahaUpdateMessageCommand command, final Location location) throws IOException {
1296        this.indexLock.writeLock().lock();
1297        try {
1298            pageFile.tx().execute(new Transaction.Closure<IOException>() {
1299                @Override
1300                public void execute(Transaction tx) throws IOException {
1301                    updateIndex(tx, command, location);
1302                }
1303            });
1304        } finally {
1305            this.indexLock.writeLock().unlock();
1306        }
1307    }
1308
1309    @SuppressWarnings("rawtypes")
1310    protected void process(final KahaRemoveMessageCommand command, final Location location) throws IOException {
1311        if (command.hasTransactionInfo()) {
1312           List<Operation> inflightTx = getInflightTx(command.getTransactionInfo());
1313           inflightTx.add(new RemoveOperation(command, location));
1314        } else {
1315            this.indexLock.writeLock().lock();
1316            try {
1317                pageFile.tx().execute(new Transaction.Closure<IOException>() {
1318                    @Override
1319                    public void execute(Transaction tx) throws IOException {
1320                        updateIndex(tx, command, location);
1321                    }
1322                });
1323            } finally {
1324                this.indexLock.writeLock().unlock();
1325            }
1326        }
1327    }
1328
1329    protected void process(final KahaRemoveDestinationCommand command, final Location location) throws IOException {
1330        this.indexLock.writeLock().lock();
1331        try {
1332            pageFile.tx().execute(new Transaction.Closure<IOException>() {
1333                @Override
1334                public void execute(Transaction tx) throws IOException {
1335                    updateIndex(tx, command, location);
1336                }
1337            });
1338        } finally {
1339            this.indexLock.writeLock().unlock();
1340        }
1341    }
1342
1343    protected void process(final KahaSubscriptionCommand command, final Location location) throws IOException {
1344        this.indexLock.writeLock().lock();
1345        try {
1346            pageFile.tx().execute(new Transaction.Closure<IOException>() {
1347                @Override
1348                public void execute(Transaction tx) throws IOException {
1349                    updateIndex(tx, command, location);
1350                }
1351            });
1352        } finally {
1353            this.indexLock.writeLock().unlock();
1354        }
1355    }
1356
1357    protected void processLocation(final Location location) {
1358        this.indexLock.writeLock().lock();
1359        try {
1360            metadata.lastUpdate = location;
1361        } finally {
1362            this.indexLock.writeLock().unlock();
1363        }
1364    }
1365
1366    @SuppressWarnings("rawtypes")
1367    protected void process(KahaCommitCommand command, final Location location, final IndexAware before) throws IOException {
1368        TransactionId key = TransactionIdConversion.convert(command.getTransactionInfo());
1369        List<Operation> inflightTx;
1370        synchronized (inflightTransactions) {
1371            inflightTx = inflightTransactions.remove(key);
1372            if (inflightTx == null) {
1373                inflightTx = preparedTransactions.remove(key);
1374            }
1375        }
1376        if (inflightTx == null) {
1377            // only non persistent messages in this tx
1378            if (before != null) {
1379                before.sequenceAssignedWithIndexLocked(-1);
1380            }
1381            return;
1382        }
1383
1384        final List<Operation> messagingTx = inflightTx;
1385        indexLock.writeLock().lock();
1386        try {
1387            pageFile.tx().execute(new Transaction.Closure<IOException>() {
1388                @Override
1389                public void execute(Transaction tx) throws IOException {
1390                    for (Operation op : messagingTx) {
1391                        op.execute(tx);
1392                    }
1393                }
1394            });
1395            metadata.lastUpdate = location;
1396        } finally {
1397            indexLock.writeLock().unlock();
1398        }
1399    }
1400
1401    @SuppressWarnings("rawtypes")
1402    protected void process(KahaPrepareCommand command, Location location) {
1403        TransactionId key = TransactionIdConversion.convert(command.getTransactionInfo());
1404        synchronized (inflightTransactions) {
1405            List<Operation> tx = inflightTransactions.remove(key);
1406            if (tx != null) {
1407                preparedTransactions.put(key, tx);
1408            }
1409        }
1410    }
1411
1412    @SuppressWarnings("rawtypes")
1413    protected void process(KahaRollbackCommand command, Location location)  throws IOException {
1414        TransactionId key = TransactionIdConversion.convert(command.getTransactionInfo());
1415        List<Operation> updates = null;
1416        synchronized (inflightTransactions) {
1417            updates = inflightTransactions.remove(key);
1418            if (updates == null) {
1419                updates = preparedTransactions.remove(key);
1420            }
1421        }
1422    }
1423
1424    protected void process(KahaRewrittenDataFileCommand command, Location location)  throws IOException {
1425        final TreeSet<Integer> completeFileSet = new TreeSet<>(journal.getFileMap().keySet());
1426
1427        // Mark the current journal file as a compacted file so that gc checks can skip
1428        // over logs that are smaller compaction type logs.
1429        DataFile current = journal.getDataFileById(location.getDataFileId());
1430        current.setTypeCode(command.getRewriteType());
1431
1432        if (completeFileSet.contains(command.getSourceDataFileId()) && command.getSkipIfSourceExists()) {
1433            // Move offset so that next location read jumps to next file.
1434            location.setOffset(journalMaxFileLength);
1435        }
1436    }
1437
1438    // /////////////////////////////////////////////////////////////////
1439    // These methods do the actual index updates.
1440    // /////////////////////////////////////////////////////////////////
1441
1442    protected final ReentrantReadWriteLock indexLock = new ReentrantReadWriteLock();
1443    private final HashSet<Integer> journalFilesBeingReplicated = new HashSet<>();
1444
1445    long updateIndex(Transaction tx, KahaAddMessageCommand command, Location location) throws IOException {
1446        StoredDestination sd = getStoredDestination(command.getDestination(), tx);
1447
1448        // Skip adding the message to the index if this is a topic and there are
1449        // no subscriptions.
1450        if (sd.subscriptions != null && sd.subscriptions.isEmpty(tx)) {
1451            return -1;
1452        }
1453
1454        // Add the message.
1455        int priority = command.getPrioritySupported() ? command.getPriority() : javax.jms.Message.DEFAULT_PRIORITY;
1456        long id = sd.orderIndex.getNextMessageId();
1457        Long previous = sd.locationIndex.put(tx, location, id);
1458        if (previous == null) {
1459            previous = sd.messageIdIndex.put(tx, command.getMessageId(), id);
1460            if (previous == null) {
1461                incrementAndAddSizeToStoreStat(command.getDestination(), location.getSize());
1462                sd.orderIndex.put(tx, priority, id, new MessageKeys(command.getMessageId(), location));
1463                if (sd.subscriptions != null && !sd.subscriptions.isEmpty(tx)) {
1464                    addAckLocationForNewMessage(tx, command.getDestination(), sd, id);
1465                }
1466                metadata.lastUpdate = location;
1467            } else {
1468
1469                MessageKeys messageKeys = sd.orderIndex.get(tx, previous);
1470                if (messageKeys != null && messageKeys.location.compareTo(location) < 0) {
1471                    // If the message ID is indexed, then the broker asked us to store a duplicate before the message was dispatched and acked, we ignore this add attempt
1472                    LOG.warn("Duplicate message add attempt rejected. Destination: {}://{}, Message id: {}", command.getDestination().getType(), command.getDestination().getName(), command.getMessageId());
1473                }
1474                sd.messageIdIndex.put(tx, command.getMessageId(), previous);
1475                sd.locationIndex.remove(tx, location);
1476                id = -1;
1477            }
1478        } else {
1479            // restore the previous value.. Looks like this was a redo of a previously
1480            // added message. We don't want to assign it a new id as the other indexes would
1481            // be wrong..
1482            sd.locationIndex.put(tx, location, previous);
1483            // ensure sequence is not broken
1484            sd.orderIndex.revertNextMessageId();
1485            metadata.lastUpdate = location;
1486        }
1487        // record this id in any event, initial send or recovery
1488        metadata.producerSequenceIdTracker.isDuplicate(command.getMessageId());
1489
1490       return id;
1491    }
1492
1493    void trackPendingAdd(KahaDestination destination, Long seq) {
1494        StoredDestination sd = storedDestinations.get(key(destination));
1495        if (sd != null) {
1496            sd.trackPendingAdd(seq);
1497        }
1498    }
1499
1500    void trackPendingAddComplete(KahaDestination destination, Long seq) {
1501        StoredDestination sd = storedDestinations.get(key(destination));
1502        if (sd != null) {
1503            sd.trackPendingAddComplete(seq);
1504        }
1505    }
1506
1507    void updateIndex(Transaction tx, KahaUpdateMessageCommand updateMessageCommand, Location location) throws IOException {
1508        KahaAddMessageCommand command = updateMessageCommand.getMessage();
1509        StoredDestination sd = getStoredDestination(command.getDestination(), tx);
1510
1511        Long id = sd.messageIdIndex.get(tx, command.getMessageId());
1512        if (id != null) {
1513            MessageKeys previousKeys = sd.orderIndex.put(
1514                    tx,
1515                    command.getPrioritySupported() ? command.getPriority() : javax.jms.Message.DEFAULT_PRIORITY,
1516                    id,
1517                    new MessageKeys(command.getMessageId(), location)
1518            );
1519            sd.locationIndex.put(tx, location, id);
1520            incrementAndAddSizeToStoreStat(command.getDestination(), location.getSize());
1521
1522            if (previousKeys != null) {
1523                //Remove the existing from the size
1524                decrementAndSubSizeToStoreStat(command.getDestination(), previousKeys.location.getSize());
1525
1526                //update all the subscription metrics
1527                if (enableSubscriptionStatistics && sd.ackPositions != null && location.getSize() != previousKeys.location.getSize()) {
1528                    Iterator<Entry<String, SequenceSet>> iter = sd.ackPositions.iterator(tx);
1529                    while (iter.hasNext()) {
1530                        Entry<String, SequenceSet> e = iter.next();
1531                        if (e.getValue().contains(id)) {
1532                            incrementAndAddSizeToStoreStat(key(command.getDestination()), e.getKey(), location.getSize());
1533                            decrementAndSubSizeToStoreStat(key(command.getDestination()), e.getKey(), previousKeys.location.getSize());
1534                        }
1535                    }
1536                }
1537
1538                // on first update previous is original location, on recovery/replay it may be the updated location
1539                if(!previousKeys.location.equals(location)) {
1540                    sd.locationIndex.remove(tx, previousKeys.location);
1541                }
1542            }
1543            metadata.lastUpdate = location;
1544        } else {
1545            //Add the message if it can't be found
1546            this.updateIndex(tx, command, location);
1547        }
1548    }
1549
1550    void updateIndex(Transaction tx, KahaRemoveMessageCommand command, Location ackLocation) throws IOException {
1551        StoredDestination sd = getStoredDestination(command.getDestination(), tx);
1552        if (!command.hasSubscriptionKey()) {
1553
1554            // In the queue case we just remove the message from the index..
1555            Long sequenceId = sd.messageIdIndex.remove(tx, command.getMessageId());
1556            if (sequenceId != null) {
1557                MessageKeys keys = sd.orderIndex.remove(tx, sequenceId);
1558                if (keys != null) {
1559                    sd.locationIndex.remove(tx, keys.location);
1560                    decrementAndSubSizeToStoreStat(command.getDestination(), keys.location.getSize());
1561                    recordAckMessageReferenceLocation(ackLocation, keys.location);
1562                    metadata.lastUpdate = ackLocation;
1563                }  else if (LOG.isDebugEnabled()) {
1564                    LOG.debug("message not found in order index: " + sequenceId  + " for: " + command.getMessageId());
1565                }
1566            } else if (LOG.isDebugEnabled()) {
1567                LOG.debug("message not found in sequence id index: " + command.getMessageId());
1568            }
1569        } else {
1570            // In the topic case we need remove the message once it's been acked
1571            // by all the subs
1572            Long sequence = sd.messageIdIndex.get(tx, command.getMessageId());
1573
1574            // Make sure it's a valid message id...
1575            if (sequence != null) {
1576                String subscriptionKey = command.getSubscriptionKey();
1577                if (command.getAck() != UNMATCHED) {
1578                    sd.orderIndex.get(tx, sequence);
1579                    byte priority = sd.orderIndex.lastGetPriority();
1580                    sd.subscriptionAcks.put(tx, subscriptionKey, new LastAck(sequence, priority));
1581                }
1582
1583                MessageKeys keys = sd.orderIndex.get(tx, sequence);
1584                if (keys != null) {
1585                    recordAckMessageReferenceLocation(ackLocation, keys.location);
1586                }
1587                // The following method handles deleting un-referenced messages.
1588                removeAckLocation(command, tx, sd, subscriptionKey, sequence);
1589                metadata.lastUpdate = ackLocation;
1590            } else if (LOG.isDebugEnabled()) {
1591                LOG.debug("on ack, no message sequence exists for id: " + command.getMessageId() + " and sub: " + command.getSubscriptionKey());
1592            }
1593
1594        }
1595    }
1596
1597    private void recordAckMessageReferenceLocation(Location ackLocation, Location messageLocation) {
1598        Set<Integer> referenceFileIds = metadata.ackMessageFileMap.get(Integer.valueOf(ackLocation.getDataFileId()));
1599        if (referenceFileIds == null) {
1600            referenceFileIds = new HashSet<>();
1601            referenceFileIds.add(messageLocation.getDataFileId());
1602            metadata.ackMessageFileMap.put(ackLocation.getDataFileId(), referenceFileIds);
1603        } else {
1604            Integer id = Integer.valueOf(messageLocation.getDataFileId());
1605            if (!referenceFileIds.contains(id)) {
1606                referenceFileIds.add(id);
1607            }
1608        }
1609    }
1610
1611    void updateIndex(Transaction tx, KahaRemoveDestinationCommand command, Location location) throws IOException {
1612        StoredDestination sd = getStoredDestination(command.getDestination(), tx);
1613        sd.orderIndex.remove(tx);
1614
1615        sd.locationIndex.clear(tx);
1616        sd.locationIndex.unload(tx);
1617        tx.free(sd.locationIndex.getPageId());
1618
1619        sd.messageIdIndex.clear(tx);
1620        sd.messageIdIndex.unload(tx);
1621        tx.free(sd.messageIdIndex.getPageId());
1622
1623        if (sd.subscriptions != null) {
1624            sd.subscriptions.clear(tx);
1625            sd.subscriptions.unload(tx);
1626            tx.free(sd.subscriptions.getPageId());
1627
1628            sd.subscriptionAcks.clear(tx);
1629            sd.subscriptionAcks.unload(tx);
1630            tx.free(sd.subscriptionAcks.getPageId());
1631
1632            sd.ackPositions.clear(tx);
1633            sd.ackPositions.unload(tx);
1634            tx.free(sd.ackPositions.getHeadPageId());
1635
1636            sd.subLocations.clear(tx);
1637            sd.subLocations.unload(tx);
1638            tx.free(sd.subLocations.getHeadPageId());
1639        }
1640
1641        String key = key(command.getDestination());
1642        storedDestinations.remove(key);
1643        metadata.destinations.remove(tx, key);
1644        clearStoreStats(command.getDestination());
1645        storeCache.remove(key(command.getDestination()));
1646    }
1647
1648    void updateIndex(Transaction tx, KahaSubscriptionCommand command, Location location) throws IOException {
1649        StoredDestination sd = getStoredDestination(command.getDestination(), tx);
1650        final String subscriptionKey = command.getSubscriptionKey();
1651
1652        // If set then we are creating it.. otherwise we are destroying the sub
1653        if (command.hasSubscriptionInfo()) {
1654            Location existing = sd.subLocations.get(tx, subscriptionKey);
1655            if (existing != null && existing.compareTo(location) == 0) {
1656                // replay on recovery, ignore
1657                LOG.trace("ignoring journal replay of replay of sub from: " + location);
1658                return;
1659            }
1660
1661            sd.subscriptions.put(tx, subscriptionKey, command);
1662            sd.subLocations.put(tx, subscriptionKey, location);
1663            long ackLocation=NOT_ACKED;
1664            if (!command.getRetroactive()) {
1665                ackLocation = sd.orderIndex.nextMessageId-1;
1666            } else {
1667                addAckLocationForRetroactiveSub(tx, sd, subscriptionKey);
1668            }
1669            sd.subscriptionAcks.put(tx, subscriptionKey, new LastAck(ackLocation));
1670            sd.subscriptionCache.add(subscriptionKey);
1671        } else {
1672            // delete the sub...
1673            sd.subscriptions.remove(tx, subscriptionKey);
1674            sd.subLocations.remove(tx, subscriptionKey);
1675            sd.subscriptionAcks.remove(tx, subscriptionKey);
1676            sd.subscriptionCache.remove(subscriptionKey);
1677            removeAckLocationsForSub(command, tx, sd, subscriptionKey);
1678            MessageStoreSubscriptionStatistics subStats = getSubStats(key(command.getDestination()));
1679            if (subStats != null) {
1680                subStats.removeSubscription(subscriptionKey);
1681            }
1682
1683            if (sd.subscriptions.isEmpty(tx)) {
1684                // remove the stored destination
1685                KahaRemoveDestinationCommand removeDestinationCommand = new KahaRemoveDestinationCommand();
1686                removeDestinationCommand.setDestination(command.getDestination());
1687                updateIndex(tx, removeDestinationCommand, null);
1688                clearStoreStats(command.getDestination());
1689            }
1690        }
1691    }
1692
1693    private void checkpointUpdate(final boolean cleanup) throws IOException {
1694        checkpointLock.writeLock().lock();
1695        try {
1696            this.indexLock.writeLock().lock();
1697            try {
1698                Set<Integer> filesToGc = pageFile.tx().execute(new Transaction.CallableClosure<Set<Integer>, IOException>() {
1699                    @Override
1700                    public Set<Integer> execute(Transaction tx) throws IOException {
1701                        return checkpointUpdate(tx, cleanup);
1702                    }
1703                });
1704                pageFile.flush();
1705                // after the index update such that partial removal does not leave dangling references in the index.
1706                journal.removeDataFiles(filesToGc);
1707            } finally {
1708                this.indexLock.writeLock().unlock();
1709            }
1710
1711        } finally {
1712            checkpointLock.writeLock().unlock();
1713        }
1714    }
1715
1716    /**
1717     * @param tx
1718     * @throws IOException
1719     */
1720    Set<Integer> checkpointUpdate(Transaction tx, boolean cleanup) throws IOException {
1721        MDC.put("activemq.persistenceDir", getDirectory().getName());
1722        LOG.debug("Checkpoint started.");
1723
1724        // reflect last update exclusive of current checkpoint
1725        Location lastUpdate = metadata.lastUpdate;
1726
1727        metadata.state = OPEN_STATE;
1728        metadata.producerSequenceIdTrackerLocation = checkpointProducerAudit();
1729        metadata.ackMessageFileMapLocation = checkpointAckMessageFileMap();
1730        Location[] inProgressTxRange = getInProgressTxLocationRange();
1731        metadata.firstInProgressTransactionLocation = inProgressTxRange[0];
1732        tx.store(metadata.page, metadataMarshaller, true);
1733
1734        final TreeSet<Integer> gcCandidateSet = new TreeSet<>();
1735        if (cleanup) {
1736
1737            final TreeSet<Integer> completeFileSet = new TreeSet<>(journal.getFileMap().keySet());
1738            gcCandidateSet.addAll(completeFileSet);
1739
1740            if (LOG.isTraceEnabled()) {
1741                LOG.trace("Last update: " + lastUpdate + ", full gc candidates set: " + gcCandidateSet);
1742            }
1743
1744            if (lastUpdate != null) {
1745                // we won't delete past the last update, ackCompaction journal can be a candidate in error
1746                gcCandidateSet.removeAll(new TreeSet<Integer>(gcCandidateSet.tailSet(lastUpdate.getDataFileId())));
1747            }
1748
1749            // Don't GC files under replication
1750            if( journalFilesBeingReplicated!=null ) {
1751                gcCandidateSet.removeAll(journalFilesBeingReplicated);
1752            }
1753
1754            if (metadata.producerSequenceIdTrackerLocation != null) {
1755                int dataFileId = metadata.producerSequenceIdTrackerLocation.getDataFileId();
1756                if (gcCandidateSet.contains(dataFileId) && gcCandidateSet.first() == dataFileId) {
1757                    // rewrite so we don't prevent gc
1758                    metadata.producerSequenceIdTracker.setModified(true);
1759                    if (LOG.isTraceEnabled()) {
1760                        LOG.trace("rewriting producerSequenceIdTracker:" + metadata.producerSequenceIdTrackerLocation);
1761                    }
1762                }
1763                gcCandidateSet.remove(dataFileId);
1764                if (LOG.isTraceEnabled()) {
1765                    LOG.trace("gc candidates after producerSequenceIdTrackerLocation:" + metadata.producerSequenceIdTrackerLocation + ", " + gcCandidateSet);
1766                }
1767            }
1768
1769            if (metadata.ackMessageFileMapLocation != null) {
1770                int dataFileId = metadata.ackMessageFileMapLocation.getDataFileId();
1771                gcCandidateSet.remove(dataFileId);
1772                if (LOG.isTraceEnabled()) {
1773                    LOG.trace("gc candidates after ackMessageFileMapLocation:" + metadata.ackMessageFileMapLocation + ", " + gcCandidateSet);
1774                }
1775            }
1776
1777            // Don't GC files referenced by in-progress tx
1778            if (inProgressTxRange[0] != null) {
1779                for (int pendingTx=inProgressTxRange[0].getDataFileId(); pendingTx <= inProgressTxRange[1].getDataFileId(); pendingTx++) {
1780                    gcCandidateSet.remove(pendingTx);
1781                }
1782            }
1783            if (LOG.isTraceEnabled()) {
1784                LOG.trace("gc candidates after in progress tx range:" + Arrays.asList(inProgressTxRange) + ", " + gcCandidateSet);
1785            }
1786
1787            // Go through all the destinations to see if any of them can remove GC candidates.
1788            for (Entry<String, StoredDestination> entry : storedDestinations.entrySet()) {
1789                if( gcCandidateSet.isEmpty() ) {
1790                    break;
1791                }
1792
1793                // Use a visitor to cut down the number of pages that we load
1794                entry.getValue().locationIndex.visit(tx, new BTreeVisitor<Location, Long>() {
1795                    int last=-1;
1796                    @Override
1797                    public boolean isInterestedInKeysBetween(Location first, Location second) {
1798                        if( first==null ) {
1799                            SortedSet<Integer> subset = gcCandidateSet.headSet(second.getDataFileId()+1);
1800                            if( !subset.isEmpty() && subset.last() == second.getDataFileId() ) {
1801                                subset.remove(second.getDataFileId());
1802                            }
1803                            return !subset.isEmpty();
1804                        } else if( second==null ) {
1805                            SortedSet<Integer> subset = gcCandidateSet.tailSet(first.getDataFileId());
1806                            if( !subset.isEmpty() && subset.first() == first.getDataFileId() ) {
1807                                subset.remove(first.getDataFileId());
1808                            }
1809                            return !subset.isEmpty();
1810                        } else {
1811                            SortedSet<Integer> subset = gcCandidateSet.subSet(first.getDataFileId(), second.getDataFileId()+1);
1812                            if( !subset.isEmpty() && subset.first() == first.getDataFileId() ) {
1813                                subset.remove(first.getDataFileId());
1814                            }
1815                            if( !subset.isEmpty() && subset.last() == second.getDataFileId() ) {
1816                                subset.remove(second.getDataFileId());
1817                            }
1818                            return !subset.isEmpty();
1819                        }
1820                    }
1821
1822                    @Override
1823                    public void visit(List<Location> keys, List<Long> values) {
1824                        for (Location l : keys) {
1825                            int fileId = l.getDataFileId();
1826                            if( last != fileId ) {
1827                                gcCandidateSet.remove(fileId);
1828                                last = fileId;
1829                            }
1830                        }
1831                    }
1832                });
1833
1834                // Durable Subscription
1835                if (entry.getValue().subLocations != null) {
1836                    Iterator<Entry<String, Location>> iter = entry.getValue().subLocations.iterator(tx);
1837                    while (iter.hasNext()) {
1838                        Entry<String, Location> subscription = iter.next();
1839                        int dataFileId = subscription.getValue().getDataFileId();
1840
1841                        // Move subscription along if it has no outstanding messages that need ack'd
1842                        // and its in the last log file in the journal.
1843                        if (!gcCandidateSet.isEmpty() && gcCandidateSet.first() == dataFileId) {
1844                            final StoredDestination destination = entry.getValue();
1845                            final String subscriptionKey = subscription.getKey();
1846                            SequenceSet pendingAcks = destination.ackPositions.get(tx, subscriptionKey);
1847
1848                            // When pending is size one that is the next message Id meaning there
1849                            // are no pending messages currently.
1850                            if (pendingAcks == null || pendingAcks.isEmpty() ||
1851                                (pendingAcks.size() == 1 && pendingAcks.getTail().range() == 1)) {
1852
1853                                if (LOG.isTraceEnabled()) {
1854                                    LOG.trace("Found candidate for rewrite: {} from file {}", entry.getKey(), dataFileId);
1855                                }
1856
1857                                final KahaSubscriptionCommand kahaSub =
1858                                    destination.subscriptions.get(tx, subscriptionKey);
1859                                destination.subLocations.put(
1860                                    tx, subscriptionKey, checkpointSubscriptionCommand(kahaSub));
1861
1862                                // Skips the remove from candidates if we rewrote the subscription
1863                                // in order to prevent duplicate subscription commands on recover.
1864                                // If another subscription is on the same file and isn't rewritten
1865                                // than it will remove the file from the set.
1866                                continue;
1867                            }
1868                        }
1869
1870                        gcCandidateSet.remove(dataFileId);
1871                    }
1872                }
1873
1874                if (LOG.isTraceEnabled()) {
1875                    LOG.trace("gc candidates after dest:" + entry.getKey() + ", " + gcCandidateSet);
1876                }
1877            }
1878
1879            // check we are not deleting file with ack for in-use journal files
1880            if (LOG.isTraceEnabled()) {
1881                LOG.trace("gc candidates: " + gcCandidateSet);
1882                LOG.trace("ackMessageFileMap: " +  metadata.ackMessageFileMap);
1883            }
1884
1885            boolean ackMessageFileMapMod = false;
1886            Iterator<Integer> candidates = gcCandidateSet.iterator();
1887            while (candidates.hasNext()) {
1888                Integer candidate = candidates.next();
1889                Set<Integer> referencedFileIds = metadata.ackMessageFileMap.get(candidate);
1890                if (referencedFileIds != null) {
1891                    for (Integer referencedFileId : referencedFileIds) {
1892                        if (completeFileSet.contains(referencedFileId) && !gcCandidateSet.contains(referencedFileId)) {
1893                            // active file that is not targeted for deletion is referenced so don't delete
1894                            candidates.remove();
1895                            break;
1896                        }
1897                    }
1898                    if (gcCandidateSet.contains(candidate)) {
1899                        ackMessageFileMapMod |= (metadata.ackMessageFileMap.remove(candidate) != null);
1900                    } else {
1901                        if (LOG.isTraceEnabled()) {
1902                            LOG.trace("not removing data file: " + candidate
1903                                    + " as contained ack(s) refer to referenced file: " + referencedFileIds);
1904                        }
1905                    }
1906                }
1907            }
1908
1909            if (!gcCandidateSet.isEmpty()) {
1910                LOG.debug("Cleanup removing the data files: {}", gcCandidateSet);
1911                for (Integer candidate : gcCandidateSet) {
1912                    for (Set<Integer> ackFiles : metadata.ackMessageFileMap.values()) {
1913                        ackMessageFileMapMod |= ackFiles.remove(candidate);
1914                    }
1915                }
1916                if (ackMessageFileMapMod) {
1917                    checkpointUpdate(tx, false);
1918                }
1919            } else if (isEnableAckCompaction()) {
1920                if (++checkPointCyclesWithNoGC >= getCompactAcksAfterNoGC()) {
1921                    // First check length of journal to make sure it makes sense to even try.
1922                    //
1923                    // If there is only one journal file with Acks in it we don't need to move
1924                    // it since it won't be chained to any later logs.
1925                    //
1926                    // If the logs haven't grown since the last time then we need to compact
1927                    // otherwise there seems to still be room for growth and we don't need to incur
1928                    // the overhead.  Depending on configuration this check can be avoided and
1929                    // Ack compaction will run any time the store has not GC'd a journal file in
1930                    // the configured amount of cycles.
1931                    if (metadata.ackMessageFileMap.size() > 1 &&
1932                        (journalLogOnLastCompactionCheck == journal.getCurrentDataFileId() || isCompactAcksIgnoresStoreGrowth())) {
1933
1934                        LOG.trace("No files GC'd checking if threshold to ACK compaction has been met.");
1935                        try {
1936                            scheduler.execute(new AckCompactionRunner());
1937                        } catch (Exception ex) {
1938                            LOG.warn("Error on queueing the Ack Compactor", ex);
1939                        }
1940                    } else {
1941                        LOG.trace("Journal activity detected, no Ack compaction scheduled.");
1942                    }
1943
1944                    checkPointCyclesWithNoGC = 0;
1945                } else {
1946                    LOG.trace("Not yet time to check for compaction: {} of {} cycles",
1947                              checkPointCyclesWithNoGC, getCompactAcksAfterNoGC());
1948                }
1949
1950                journalLogOnLastCompactionCheck = journal.getCurrentDataFileId();
1951            }
1952        }
1953        MDC.remove("activemq.persistenceDir");
1954
1955        LOG.debug("Checkpoint done.");
1956        return gcCandidateSet;
1957    }
1958
1959    private final class AckCompactionRunner implements Runnable {
1960
1961        @Override
1962        public void run() {
1963
1964            int journalToAdvance = -1;
1965            Set<Integer> journalLogsReferenced = new HashSet<>();
1966
1967            //flag to know whether the ack forwarding completed without an exception
1968            boolean forwarded = false;
1969
1970            try {
1971                //acquire the checkpoint lock to prevent other threads from
1972                //running a checkpoint while this is running
1973                //
1974                //Normally this task runs on the same executor as the checkpoint task
1975                //so this ack compaction runner wouldn't run at the same time as the checkpoint task.
1976                //
1977                //However, there are two cases where this isn't always true.
1978                //First, the checkpoint() method is public and can be called through the
1979                //PersistenceAdapter interface by someone at the same time this is running.
1980                //Second, a checkpoint is called during shutdown without using the executor.
1981                //
1982                //In the future it might be better to just remove the checkpointLock entirely
1983                //and only use the executor but this would need to be examined for any unintended
1984                //consequences
1985                checkpointLock.readLock().lock();
1986
1987                try {
1988
1989                    // Lock index to capture the ackMessageFileMap data
1990                    indexLock.writeLock().lock();
1991
1992                    // Map keys might not be sorted, find the earliest log file to forward acks
1993                    // from and move only those, future cycles can chip away at more as needed.
1994                    // We won't move files that are themselves rewritten on a previous compaction.
1995                    List<Integer> journalFileIds = new ArrayList<>(metadata.ackMessageFileMap.keySet());
1996                    Collections.sort(journalFileIds);
1997                    for (Integer journalFileId : journalFileIds) {
1998                        DataFile current = journal.getDataFileById(journalFileId);
1999                        if (current != null && current.getTypeCode() != COMPACTED_JOURNAL_FILE) {
2000                            journalToAdvance = journalFileId;
2001                            break;
2002                        }
2003                    }
2004
2005                    // Check if we found one, or if we only found the current file being written to.
2006                    if (journalToAdvance == -1 || journalToAdvance == journal.getCurrentDataFileId()) {
2007                        return;
2008                    }
2009
2010                    journalLogsReferenced.addAll(metadata.ackMessageFileMap.get(journalToAdvance));
2011
2012                } finally {
2013                    indexLock.writeLock().unlock();
2014                }
2015
2016                try {
2017                    // Background rewrite of the old acks
2018                    forwardAllAcks(journalToAdvance, journalLogsReferenced);
2019                    forwarded = true;
2020                } catch (IOException ioe) {
2021                    LOG.error("Forwarding of acks failed", ioe);
2022                    brokerService.handleIOException(ioe);
2023                } catch (Throwable e) {
2024                    LOG.error("Forwarding of acks failed", e);
2025                    brokerService.handleIOException(IOExceptionSupport.create(e));
2026                }
2027            } finally {
2028                checkpointLock.readLock().unlock();
2029            }
2030
2031            try {
2032                if (forwarded) {
2033                    // Checkpoint with changes from the ackMessageFileMap
2034                    checkpointUpdate(false);
2035                }
2036            } catch (IOException ioe) {
2037                LOG.error("Checkpoint failed", ioe);
2038                brokerService.handleIOException(ioe);
2039            } catch (Throwable e) {
2040                LOG.error("Checkpoint failed", e);
2041                brokerService.handleIOException(IOExceptionSupport.create(e));
2042            }
2043        }
2044    }
2045
2046    private void forwardAllAcks(Integer journalToRead, Set<Integer> journalLogsReferenced) throws IllegalStateException, IOException {
2047        LOG.trace("Attempting to move all acks in journal:{} to the front.", journalToRead);
2048
2049        DataFile forwardsFile = journal.reserveDataFile();
2050        forwardsFile.setTypeCode(COMPACTED_JOURNAL_FILE);
2051        LOG.trace("Reserved file for forwarded acks: {}", forwardsFile);
2052
2053        Map<Integer, Set<Integer>> updatedAckLocations = new HashMap<>();
2054
2055        try (TargetedDataFileAppender appender = new TargetedDataFileAppender(journal, forwardsFile);) {
2056            KahaRewrittenDataFileCommand compactionMarker = new KahaRewrittenDataFileCommand();
2057            compactionMarker.setSourceDataFileId(journalToRead);
2058            compactionMarker.setRewriteType(forwardsFile.getTypeCode());
2059
2060            ByteSequence payload = toByteSequence(compactionMarker);
2061            appender.storeItem(payload, Journal.USER_RECORD_TYPE, false);
2062            LOG.trace("Marked ack rewrites file as replacing file: {}", journalToRead);
2063
2064            final Location limit = new Location(journalToRead + 1, 0);
2065            Location nextLocation = getNextLocationForAckForward(new Location(journalToRead, 0), limit);
2066            while (nextLocation != null) {
2067                JournalCommand<?> command = null;
2068                try {
2069                    command = load(nextLocation);
2070                } catch (IOException ex) {
2071                    LOG.trace("Error loading command during ack forward: {}", nextLocation);
2072                }
2073
2074                if (command != null && command instanceof KahaRemoveMessageCommand) {
2075                    payload = toByteSequence(command);
2076                    Location location = appender.storeItem(payload, Journal.USER_RECORD_TYPE, false);
2077                    updatedAckLocations.put(location.getDataFileId(), journalLogsReferenced);
2078                }
2079
2080                nextLocation = getNextLocationForAckForward(nextLocation, limit);
2081            }
2082        }
2083
2084        LOG.trace("ACKS forwarded, updates for ack locations: {}", updatedAckLocations);
2085
2086        // Lock index while we update the ackMessageFileMap.
2087        indexLock.writeLock().lock();
2088
2089        // Update the ack map with the new locations of the acks
2090        for (Entry<Integer, Set<Integer>> entry : updatedAckLocations.entrySet()) {
2091            Set<Integer> referenceFileIds = metadata.ackMessageFileMap.get(entry.getKey());
2092            if (referenceFileIds == null) {
2093                referenceFileIds = new HashSet<>();
2094                referenceFileIds.addAll(entry.getValue());
2095                metadata.ackMessageFileMap.put(entry.getKey(), referenceFileIds);
2096            } else {
2097                referenceFileIds.addAll(entry.getValue());
2098            }
2099        }
2100
2101        // remove the old location data from the ack map so that the old journal log file can
2102        // be removed on next GC.
2103        metadata.ackMessageFileMap.remove(journalToRead);
2104
2105        indexLock.writeLock().unlock();
2106
2107        LOG.trace("ACK File Map following updates: {}", metadata.ackMessageFileMap);
2108    }
2109
2110    private Location getNextLocationForAckForward(final Location nextLocation, final Location limit) {
2111        //getNextLocation() can throw an IOException, we should handle it and set
2112        //nextLocation to null and abort gracefully
2113        //Should not happen in the normal case
2114        Location location = null;
2115        try {
2116            location = journal.getNextLocation(nextLocation, limit);
2117        } catch (IOException e) {
2118            LOG.warn("Failed to load next journal location after: {}, reason: {}", nextLocation, e);
2119            if (LOG.isDebugEnabled()) {
2120                LOG.debug("Failed to load next journal location after: {}", nextLocation, e);
2121            }
2122        }
2123        return location;
2124    }
2125
2126    final Runnable nullCompletionCallback = new Runnable() {
2127        @Override
2128        public void run() {
2129        }
2130    };
2131
2132    private Location checkpointProducerAudit() throws IOException {
2133        if (metadata.producerSequenceIdTracker == null || metadata.producerSequenceIdTracker.modified()) {
2134            ByteArrayOutputStream baos = new ByteArrayOutputStream();
2135            ObjectOutputStream oout = new ObjectOutputStream(baos);
2136            oout.writeObject(metadata.producerSequenceIdTracker);
2137            oout.flush();
2138            oout.close();
2139            // using completion callback allows a disk sync to be avoided when enableJournalDiskSyncs = false
2140            Location location = store(new KahaProducerAuditCommand().setAudit(new Buffer(baos.toByteArray())), nullCompletionCallback);
2141            try {
2142                location.getLatch().await();
2143            } catch (InterruptedException e) {
2144                throw new InterruptedIOException(e.toString());
2145            }
2146            return location;
2147        }
2148        return metadata.producerSequenceIdTrackerLocation;
2149    }
2150
2151    private Location checkpointAckMessageFileMap() throws IOException {
2152        ByteArrayOutputStream baos = new ByteArrayOutputStream();
2153        ObjectOutputStream oout = new ObjectOutputStream(baos);
2154        oout.writeObject(metadata.ackMessageFileMap);
2155        oout.flush();
2156        oout.close();
2157        // using completion callback allows a disk sync to be avoided when enableJournalDiskSyncs = false
2158        Location location = store(new KahaAckMessageFileMapCommand().setAckMessageFileMap(new Buffer(baos.toByteArray())), nullCompletionCallback);
2159        try {
2160            location.getLatch().await();
2161        } catch (InterruptedException e) {
2162            throw new InterruptedIOException(e.toString());
2163        }
2164        return location;
2165    }
2166
2167    private Location checkpointSubscriptionCommand(KahaSubscriptionCommand subscription) throws IOException {
2168
2169        ByteSequence sequence = toByteSequence(subscription);
2170        Location location = journal.write(sequence, nullCompletionCallback) ;
2171
2172        try {
2173            location.getLatch().await();
2174        } catch (InterruptedException e) {
2175            throw new InterruptedIOException(e.toString());
2176        }
2177        return location;
2178    }
2179
2180    public HashSet<Integer> getJournalFilesBeingReplicated() {
2181        return journalFilesBeingReplicated;
2182    }
2183
2184    // /////////////////////////////////////////////////////////////////
2185    // StoredDestination related implementation methods.
2186    // /////////////////////////////////////////////////////////////////
2187
2188    protected final HashMap<String, StoredDestination> storedDestinations = new HashMap<>();
2189
2190    static class MessageKeys {
2191        final String messageId;
2192        final Location location;
2193
2194        public MessageKeys(String messageId, Location location) {
2195            this.messageId=messageId;
2196            this.location=location;
2197        }
2198
2199        @Override
2200        public String toString() {
2201            return "["+messageId+","+location+"]";
2202        }
2203    }
2204
2205    protected class MessageKeysMarshaller extends VariableMarshaller<MessageKeys> {
2206        final LocationSizeMarshaller locationSizeMarshaller = new LocationSizeMarshaller();
2207
2208        @Override
2209        public MessageKeys readPayload(DataInput dataIn) throws IOException {
2210            return new MessageKeys(dataIn.readUTF(), locationSizeMarshaller.readPayload(dataIn));
2211        }
2212
2213        @Override
2214        public void writePayload(MessageKeys object, DataOutput dataOut) throws IOException {
2215            dataOut.writeUTF(object.messageId);
2216            locationSizeMarshaller.writePayload(object.location, dataOut);
2217        }
2218    }
2219
2220    class LastAck {
2221        long lastAckedSequence;
2222        byte priority;
2223
2224        public LastAck(LastAck source) {
2225            this.lastAckedSequence = source.lastAckedSequence;
2226            this.priority = source.priority;
2227        }
2228
2229        public LastAck() {
2230            this.priority = MessageOrderIndex.HI;
2231        }
2232
2233        public LastAck(long ackLocation) {
2234            this.lastAckedSequence = ackLocation;
2235            this.priority = MessageOrderIndex.LO;
2236        }
2237
2238        public LastAck(long ackLocation, byte priority) {
2239            this.lastAckedSequence = ackLocation;
2240            this.priority = priority;
2241        }
2242
2243        @Override
2244        public String toString() {
2245            return "[" + lastAckedSequence + ":" + priority + "]";
2246        }
2247    }
2248
2249    protected class LastAckMarshaller implements Marshaller<LastAck> {
2250
2251        @Override
2252        public void writePayload(LastAck object, DataOutput dataOut) throws IOException {
2253            dataOut.writeLong(object.lastAckedSequence);
2254            dataOut.writeByte(object.priority);
2255        }
2256
2257        @Override
2258        public LastAck readPayload(DataInput dataIn) throws IOException {
2259            LastAck lastAcked = new LastAck();
2260            lastAcked.lastAckedSequence = dataIn.readLong();
2261            if (metadata.version >= 3) {
2262                lastAcked.priority = dataIn.readByte();
2263            }
2264            return lastAcked;
2265        }
2266
2267        @Override
2268        public int getFixedSize() {
2269            return 9;
2270        }
2271
2272        @Override
2273        public LastAck deepCopy(LastAck source) {
2274            return new LastAck(source);
2275        }
2276
2277        @Override
2278        public boolean isDeepCopySupported() {
2279            return true;
2280        }
2281    }
2282
2283    class StoredDestination {
2284
2285        MessageOrderIndex orderIndex = new MessageOrderIndex();
2286        BTreeIndex<Location, Long> locationIndex;
2287        BTreeIndex<String, Long> messageIdIndex;
2288
2289        // These bits are only set for Topics
2290        BTreeIndex<String, KahaSubscriptionCommand> subscriptions;
2291        BTreeIndex<String, LastAck> subscriptionAcks;
2292        HashMap<String, MessageOrderCursor> subscriptionCursors;
2293        ListIndex<String, SequenceSet> ackPositions;
2294        ListIndex<String, Location> subLocations;
2295
2296        // Transient data used to track which Messages are no longer needed.
2297        final TreeMap<Long, Long> messageReferences = new TreeMap<>();
2298        final HashSet<String> subscriptionCache = new LinkedHashSet<>();
2299
2300        public void trackPendingAdd(Long seq) {
2301            orderIndex.trackPendingAdd(seq);
2302        }
2303
2304        public void trackPendingAddComplete(Long seq) {
2305            orderIndex.trackPendingAddComplete(seq);
2306        }
2307
2308        @Override
2309        public String toString() {
2310            return "nextSeq:" + orderIndex.nextMessageId + ",lastRet:" + orderIndex.cursor + ",pending:" + orderIndex.pendingAdditions.size();
2311        }
2312    }
2313
2314    protected class StoredDestinationMarshaller extends VariableMarshaller<StoredDestination> {
2315
2316        final MessageKeysMarshaller messageKeysMarshaller = new MessageKeysMarshaller();
2317
2318        @Override
2319        public StoredDestination readPayload(final DataInput dataIn) throws IOException {
2320            final StoredDestination value = new StoredDestination();
2321            value.orderIndex.defaultPriorityIndex = new BTreeIndex<>(pageFile, dataIn.readLong());
2322            value.locationIndex = new BTreeIndex<>(pageFile, dataIn.readLong());
2323            value.messageIdIndex = new BTreeIndex<>(pageFile, dataIn.readLong());
2324
2325            if (dataIn.readBoolean()) {
2326                value.subscriptions = new BTreeIndex<>(pageFile, dataIn.readLong());
2327                value.subscriptionAcks = new BTreeIndex<>(pageFile, dataIn.readLong());
2328                if (metadata.version >= 4) {
2329                    value.ackPositions = new ListIndex<>(pageFile, dataIn.readLong());
2330                } else {
2331                    // upgrade
2332                    pageFile.tx().execute(new Transaction.Closure<IOException>() {
2333                        @Override
2334                        public void execute(Transaction tx) throws IOException {
2335                            LinkedHashMap<String, SequenceSet> temp = new LinkedHashMap<>();
2336
2337                            if (metadata.version >= 3) {
2338                                // migrate
2339                                BTreeIndex<Long, HashSet<String>> oldAckPositions =
2340                                        new BTreeIndex<>(pageFile, dataIn.readLong());
2341                                oldAckPositions.setKeyMarshaller(LongMarshaller.INSTANCE);
2342                                oldAckPositions.setValueMarshaller(HashSetStringMarshaller.INSTANCE);
2343                                oldAckPositions.load(tx);
2344
2345
2346                                // Do the initial build of the data in memory before writing into the store
2347                                // based Ack Positions List to avoid a lot of disk thrashing.
2348                                Iterator<Entry<Long, HashSet<String>>> iterator = oldAckPositions.iterator(tx);
2349                                while (iterator.hasNext()) {
2350                                    Entry<Long, HashSet<String>> entry = iterator.next();
2351
2352                                    for(String subKey : entry.getValue()) {
2353                                        SequenceSet pendingAcks = temp.get(subKey);
2354                                        if (pendingAcks == null) {
2355                                            pendingAcks = new SequenceSet();
2356                                            temp.put(subKey, pendingAcks);
2357                                        }
2358
2359                                        pendingAcks.add(entry.getKey());
2360                                    }
2361                                }
2362                            }
2363                            // Now move the pending messages to ack data into the store backed
2364                            // structure.
2365                            value.ackPositions = new ListIndex<>(pageFile, tx.allocate());
2366                            value.ackPositions.setKeyMarshaller(StringMarshaller.INSTANCE);
2367                            value.ackPositions.setValueMarshaller(SequenceSet.Marshaller.INSTANCE);
2368                            value.ackPositions.load(tx);
2369                            for(String subscriptionKey : temp.keySet()) {
2370                                value.ackPositions.put(tx, subscriptionKey, temp.get(subscriptionKey));
2371                            }
2372
2373                        }
2374                    });
2375                }
2376
2377                if (metadata.version >= 5) {
2378                    value.subLocations = new ListIndex<>(pageFile, dataIn.readLong());
2379                } else {
2380                    // upgrade
2381                    pageFile.tx().execute(new Transaction.Closure<IOException>() {
2382                        @Override
2383                        public void execute(Transaction tx) throws IOException {
2384                            value.subLocations = new ListIndex<>(pageFile, tx.allocate());
2385                            value.subLocations.setKeyMarshaller(StringMarshaller.INSTANCE);
2386                            value.subLocations.setValueMarshaller(LocationMarshaller.INSTANCE);
2387                            value.subLocations.load(tx);
2388                        }
2389                    });
2390                }
2391            }
2392            if (metadata.version >= 2) {
2393                value.orderIndex.lowPriorityIndex = new BTreeIndex<>(pageFile, dataIn.readLong());
2394                value.orderIndex.highPriorityIndex = new BTreeIndex<>(pageFile, dataIn.readLong());
2395            } else {
2396                // upgrade
2397                pageFile.tx().execute(new Transaction.Closure<IOException>() {
2398                    @Override
2399                    public void execute(Transaction tx) throws IOException {
2400                        value.orderIndex.lowPriorityIndex = new BTreeIndex<>(pageFile, tx.allocate());
2401                        value.orderIndex.lowPriorityIndex.setKeyMarshaller(LongMarshaller.INSTANCE);
2402                        value.orderIndex.lowPriorityIndex.setValueMarshaller(messageKeysMarshaller);
2403                        value.orderIndex.lowPriorityIndex.load(tx);
2404
2405                        value.orderIndex.highPriorityIndex = new BTreeIndex<>(pageFile, tx.allocate());
2406                        value.orderIndex.highPriorityIndex.setKeyMarshaller(LongMarshaller.INSTANCE);
2407                        value.orderIndex.highPriorityIndex.setValueMarshaller(messageKeysMarshaller);
2408                        value.orderIndex.highPriorityIndex.load(tx);
2409                    }
2410                });
2411            }
2412
2413            return value;
2414        }
2415
2416        @Override
2417        public void writePayload(StoredDestination value, DataOutput dataOut) throws IOException {
2418            dataOut.writeLong(value.orderIndex.defaultPriorityIndex.getPageId());
2419            dataOut.writeLong(value.locationIndex.getPageId());
2420            dataOut.writeLong(value.messageIdIndex.getPageId());
2421            if (value.subscriptions != null) {
2422                dataOut.writeBoolean(true);
2423                dataOut.writeLong(value.subscriptions.getPageId());
2424                dataOut.writeLong(value.subscriptionAcks.getPageId());
2425                dataOut.writeLong(value.ackPositions.getHeadPageId());
2426                dataOut.writeLong(value.subLocations.getHeadPageId());
2427            } else {
2428                dataOut.writeBoolean(false);
2429            }
2430            dataOut.writeLong(value.orderIndex.lowPriorityIndex.getPageId());
2431            dataOut.writeLong(value.orderIndex.highPriorityIndex.getPageId());
2432        }
2433    }
2434
2435    static class KahaSubscriptionCommandMarshaller extends VariableMarshaller<KahaSubscriptionCommand> {
2436        final static KahaSubscriptionCommandMarshaller INSTANCE = new KahaSubscriptionCommandMarshaller();
2437
2438        @Override
2439        public KahaSubscriptionCommand readPayload(DataInput dataIn) throws IOException {
2440            KahaSubscriptionCommand rc = new KahaSubscriptionCommand();
2441            rc.mergeFramed((InputStream)dataIn);
2442            return rc;
2443        }
2444
2445        @Override
2446        public void writePayload(KahaSubscriptionCommand object, DataOutput dataOut) throws IOException {
2447            object.writeFramed((OutputStream)dataOut);
2448        }
2449    }
2450
2451    protected StoredDestination getStoredDestination(KahaDestination destination, Transaction tx) throws IOException {
2452        String key = key(destination);
2453        StoredDestination rc = storedDestinations.get(key);
2454        if (rc == null) {
2455            boolean topic = destination.getType() == KahaDestination.DestinationType.TOPIC || destination.getType() == KahaDestination.DestinationType.TEMP_TOPIC;
2456            rc = loadStoredDestination(tx, key, topic);
2457            // Cache it. We may want to remove/unload destinations from the
2458            // cache that are not used for a while
2459            // to reduce memory usage.
2460            storedDestinations.put(key, rc);
2461        }
2462        return rc;
2463    }
2464
2465    protected StoredDestination getExistingStoredDestination(KahaDestination destination, Transaction tx) throws IOException {
2466        String key = key(destination);
2467        StoredDestination rc = storedDestinations.get(key);
2468        if (rc == null && metadata.destinations.containsKey(tx, key)) {
2469            rc = getStoredDestination(destination, tx);
2470        }
2471        return rc;
2472    }
2473
2474    /**
2475     * @param tx
2476     * @param key
2477     * @param topic
2478     * @return
2479     * @throws IOException
2480     */
2481    private StoredDestination loadStoredDestination(Transaction tx, String key, boolean topic) throws IOException {
2482        // Try to load the existing indexes..
2483        StoredDestination rc = metadata.destinations.get(tx, key);
2484        if (rc == null) {
2485            // Brand new destination.. allocate indexes for it.
2486            rc = new StoredDestination();
2487            rc.orderIndex.allocate(tx);
2488            rc.locationIndex = new BTreeIndex<>(pageFile, tx.allocate());
2489            rc.messageIdIndex = new BTreeIndex<>(pageFile, tx.allocate());
2490
2491            if (topic) {
2492                rc.subscriptions = new BTreeIndex<>(pageFile, tx.allocate());
2493                rc.subscriptionAcks = new BTreeIndex<>(pageFile, tx.allocate());
2494                rc.ackPositions = new ListIndex<>(pageFile, tx.allocate());
2495                rc.subLocations = new ListIndex<>(pageFile, tx.allocate());
2496            }
2497            metadata.destinations.put(tx, key, rc);
2498        }
2499
2500        // Configure the marshalers and load.
2501        rc.orderIndex.load(tx);
2502
2503        // Figure out the next key using the last entry in the destination.
2504        rc.orderIndex.configureLast(tx);
2505
2506        rc.locationIndex.setKeyMarshaller(new LocationSizeMarshaller());
2507        rc.locationIndex.setValueMarshaller(LongMarshaller.INSTANCE);
2508        rc.locationIndex.load(tx);
2509
2510        rc.messageIdIndex.setKeyMarshaller(StringMarshaller.INSTANCE);
2511        rc.messageIdIndex.setValueMarshaller(LongMarshaller.INSTANCE);
2512        rc.messageIdIndex.load(tx);
2513
2514        //go through an upgrade old index if older than version 6
2515        if (metadata.version < 6) {
2516            for (Iterator<Entry<Location, Long>> iterator = rc.locationIndex.iterator(tx); iterator.hasNext(); ) {
2517                Entry<Location, Long> entry = iterator.next();
2518                // modify so it is upgraded
2519                rc.locationIndex.put(tx, entry.getKey(), entry.getValue());
2520            }
2521            //upgrade the order index
2522            for (Iterator<Entry<Long, MessageKeys>> iterator = rc.orderIndex.iterator(tx); iterator.hasNext(); ) {
2523                Entry<Long, MessageKeys> entry = iterator.next();
2524                //call get so that the last priority is updated
2525                rc.orderIndex.get(tx, entry.getKey());
2526                rc.orderIndex.put(tx, rc.orderIndex.lastGetPriority(), entry.getKey(), entry.getValue());
2527            }
2528        }
2529
2530        // If it was a topic...
2531        if (topic) {
2532
2533            rc.subscriptions.setKeyMarshaller(StringMarshaller.INSTANCE);
2534            rc.subscriptions.setValueMarshaller(KahaSubscriptionCommandMarshaller.INSTANCE);
2535            rc.subscriptions.load(tx);
2536
2537            rc.subscriptionAcks.setKeyMarshaller(StringMarshaller.INSTANCE);
2538            rc.subscriptionAcks.setValueMarshaller(new LastAckMarshaller());
2539            rc.subscriptionAcks.load(tx);
2540
2541            rc.ackPositions.setKeyMarshaller(StringMarshaller.INSTANCE);
2542            rc.ackPositions.setValueMarshaller(SequenceSet.Marshaller.INSTANCE);
2543            rc.ackPositions.load(tx);
2544
2545            rc.subLocations.setKeyMarshaller(StringMarshaller.INSTANCE);
2546            rc.subLocations.setValueMarshaller(LocationMarshaller.INSTANCE);
2547            rc.subLocations.load(tx);
2548
2549            rc.subscriptionCursors = new HashMap<>();
2550
2551            if (metadata.version < 3) {
2552
2553                // on upgrade need to fill ackLocation with available messages past last ack
2554                for (Iterator<Entry<String, LastAck>> iterator = rc.subscriptionAcks.iterator(tx); iterator.hasNext(); ) {
2555                    Entry<String, LastAck> entry = iterator.next();
2556                    for (Iterator<Entry<Long, MessageKeys>> orderIterator =
2557                            rc.orderIndex.iterator(tx, new MessageOrderCursor(entry.getValue().lastAckedSequence)); orderIterator.hasNext(); ) {
2558                        Long sequence = orderIterator.next().getKey();
2559                        addAckLocation(tx, rc, sequence, entry.getKey());
2560                    }
2561                    // modify so it is upgraded
2562                    rc.subscriptionAcks.put(tx, entry.getKey(), entry.getValue());
2563                }
2564            }
2565
2566            // Configure the message references index
2567            Iterator<Entry<String, SequenceSet>> subscriptions = rc.ackPositions.iterator(tx);
2568            while (subscriptions.hasNext()) {
2569                Entry<String, SequenceSet> subscription = subscriptions.next();
2570                SequenceSet pendingAcks = subscription.getValue();
2571                if (pendingAcks != null && !pendingAcks.isEmpty()) {
2572                    Long lastPendingAck = pendingAcks.getTail().getLast();
2573                    for (Long sequenceId : pendingAcks) {
2574                        Long current = rc.messageReferences.get(sequenceId);
2575                        if (current == null) {
2576                            current = new Long(0);
2577                        }
2578
2579                        // We always add a trailing empty entry for the next position to start from
2580                        // so we need to ensure we don't count that as a message reference on reload.
2581                        if (!sequenceId.equals(lastPendingAck)) {
2582                            current = current.longValue() + 1;
2583                        } else {
2584                            current = Long.valueOf(0L);
2585                        }
2586
2587                        rc.messageReferences.put(sequenceId, current);
2588                    }
2589                }
2590            }
2591
2592            // Configure the subscription cache
2593            for (Iterator<Entry<String, LastAck>> iterator = rc.subscriptionAcks.iterator(tx); iterator.hasNext(); ) {
2594                Entry<String, LastAck> entry = iterator.next();
2595                rc.subscriptionCache.add(entry.getKey());
2596            }
2597
2598            if (rc.orderIndex.nextMessageId == 0) {
2599                // check for existing durable sub all acked out - pull next seq from acks as messages are gone
2600                if (!rc.subscriptionAcks.isEmpty(tx)) {
2601                    for (Iterator<Entry<String, LastAck>> iterator = rc.subscriptionAcks.iterator(tx); iterator.hasNext();) {
2602                        Entry<String, LastAck> entry = iterator.next();
2603                        rc.orderIndex.nextMessageId =
2604                                Math.max(rc.orderIndex.nextMessageId, entry.getValue().lastAckedSequence +1);
2605                    }
2606                }
2607            } else {
2608                // update based on ackPositions for unmatched, last entry is always the next
2609                if (!rc.messageReferences.isEmpty()) {
2610                    Long nextMessageId = (Long) rc.messageReferences.keySet().toArray()[rc.messageReferences.size() - 1];
2611                    rc.orderIndex.nextMessageId =
2612                            Math.max(rc.orderIndex.nextMessageId, nextMessageId);
2613                }
2614            }
2615        }
2616
2617        if (metadata.version < VERSION) {
2618            // store again after upgrade
2619            metadata.destinations.put(tx, key, rc);
2620        }
2621        return rc;
2622    }
2623
2624    /**
2625     * Clear the counter for the destination, if one exists.
2626     *
2627     * @param kahaDestination
2628     */
2629    protected void clearStoreStats(KahaDestination kahaDestination) {
2630        String key = key(kahaDestination);
2631        MessageStoreStatistics storeStats = getStoreStats(key);
2632        MessageStoreSubscriptionStatistics subStats = getSubStats(key);
2633        if (storeStats != null) {
2634            storeStats.reset();
2635        }
2636        if (subStats != null) {
2637            subStats.reset();
2638        }
2639    }
2640
2641    /**
2642     * Update MessageStoreStatistics
2643     *
2644     * @param kahaDestination
2645     * @param size
2646     */
2647    protected void incrementAndAddSizeToStoreStat(KahaDestination kahaDestination, long size) {
2648        incrementAndAddSizeToStoreStat(key(kahaDestination), size);
2649    }
2650
2651    protected void incrementAndAddSizeToStoreStat(String kahaDestKey, long size) {
2652        MessageStoreStatistics storeStats = getStoreStats(kahaDestKey);
2653        if (storeStats != null) {
2654            storeStats.getMessageCount().increment();
2655            if (size > 0) {
2656                storeStats.getMessageSize().addSize(size);
2657            }
2658        }
2659    }
2660
2661    protected void decrementAndSubSizeToStoreStat(KahaDestination kahaDestination, long size) {
2662        decrementAndSubSizeToStoreStat(key(kahaDestination), size);
2663    }
2664
2665    protected void decrementAndSubSizeToStoreStat(String kahaDestKey, long size) {
2666        MessageStoreStatistics storeStats = getStoreStats(kahaDestKey);
2667        if (storeStats != null) {
2668            storeStats.getMessageCount().decrement();
2669            if (size > 0) {
2670                storeStats.getMessageSize().addSize(-size);
2671            }
2672        }
2673    }
2674
2675    protected void incrementAndAddSizeToStoreStat(KahaDestination kahaDestination, String subKey, long size) {
2676        incrementAndAddSizeToStoreStat(key(kahaDestination), subKey, size);
2677    }
2678
2679    protected void incrementAndAddSizeToStoreStat(String kahaDestKey, String subKey, long size) {
2680        if (enableSubscriptionStatistics) {
2681            MessageStoreSubscriptionStatistics subStats = getSubStats(kahaDestKey);
2682            if (subStats != null && subKey != null) {
2683                subStats.getMessageCount(subKey).increment();
2684                if (size > 0) {
2685                    subStats.getMessageSize(subKey).addSize(size);
2686                }
2687            }
2688        }
2689    }
2690
2691
2692    protected void decrementAndSubSizeToStoreStat(String kahaDestKey, String subKey, long size) {
2693        if (enableSubscriptionStatistics) {
2694            MessageStoreSubscriptionStatistics subStats = getSubStats(kahaDestKey);
2695            if (subStats != null && subKey != null) {
2696                subStats.getMessageCount(subKey).decrement();
2697                if (size > 0) {
2698                    subStats.getMessageSize(subKey).addSize(-size);
2699                }
2700            }
2701        }
2702    }
2703
2704    protected void decrementAndSubSizeToStoreStat(KahaDestination kahaDestination, String subKey, long size) {
2705        decrementAndSubSizeToStoreStat(key(kahaDestination), subKey, size);
2706    }
2707
2708    /**
2709     * This is a map to cache MessageStores for a specific
2710     * KahaDestination key
2711     */
2712    protected final ConcurrentMap<String, MessageStore> storeCache =
2713            new ConcurrentHashMap<>();
2714
2715    /**
2716     * Locate the storeMessageSize counter for this KahaDestination
2717     */
2718    protected MessageStoreStatistics getStoreStats(String kahaDestKey) {
2719        MessageStoreStatistics storeStats = null;
2720        try {
2721            MessageStore messageStore = storeCache.get(kahaDestKey);
2722            if (messageStore != null) {
2723                storeStats = messageStore.getMessageStoreStatistics();
2724            }
2725        } catch (Exception e1) {
2726             LOG.error("Getting size counter of destination failed", e1);
2727        }
2728
2729        return storeStats;
2730    }
2731
2732    protected MessageStoreSubscriptionStatistics getSubStats(String kahaDestKey) {
2733        MessageStoreSubscriptionStatistics subStats = null;
2734        try {
2735            MessageStore messageStore = storeCache.get(kahaDestKey);
2736            if (messageStore instanceof TopicMessageStore) {
2737                subStats = ((TopicMessageStore)messageStore).getMessageStoreSubStatistics();
2738            }
2739        } catch (Exception e1) {
2740             LOG.error("Getting size counter of destination failed", e1);
2741        }
2742
2743        return subStats;
2744    }
2745
2746    /**
2747     * Determine whether this Destination matches the DestinationType
2748     *
2749     * @param destination
2750     * @param type
2751     * @return
2752     */
2753    protected boolean matchType(Destination destination,
2754            KahaDestination.DestinationType type) {
2755        if (destination instanceof Topic
2756                && type.equals(KahaDestination.DestinationType.TOPIC)) {
2757            return true;
2758        } else if (destination instanceof Queue
2759                && type.equals(KahaDestination.DestinationType.QUEUE)) {
2760            return true;
2761        }
2762        return false;
2763    }
2764
2765    class LocationSizeMarshaller implements Marshaller<Location> {
2766
2767        public LocationSizeMarshaller() {
2768
2769        }
2770
2771        @Override
2772        public Location readPayload(DataInput dataIn) throws IOException {
2773            Location rc = new Location();
2774            rc.setDataFileId(dataIn.readInt());
2775            rc.setOffset(dataIn.readInt());
2776            if (metadata.version >= 6) {
2777                rc.setSize(dataIn.readInt());
2778            }
2779            return rc;
2780        }
2781
2782        @Override
2783        public void writePayload(Location object, DataOutput dataOut)
2784                throws IOException {
2785            dataOut.writeInt(object.getDataFileId());
2786            dataOut.writeInt(object.getOffset());
2787            dataOut.writeInt(object.getSize());
2788        }
2789
2790        @Override
2791        public int getFixedSize() {
2792            return 12;
2793        }
2794
2795        @Override
2796        public Location deepCopy(Location source) {
2797            return new Location(source);
2798        }
2799
2800        @Override
2801        public boolean isDeepCopySupported() {
2802            return true;
2803        }
2804    }
2805
2806    private void addAckLocation(Transaction tx, StoredDestination sd, Long messageSequence, String subscriptionKey) throws IOException {
2807        SequenceSet sequences = sd.ackPositions.get(tx, subscriptionKey);
2808        if (sequences == null) {
2809            sequences = new SequenceSet();
2810            sequences.add(messageSequence);
2811            sd.ackPositions.add(tx, subscriptionKey, sequences);
2812        } else {
2813            sequences.add(messageSequence);
2814            sd.ackPositions.put(tx, subscriptionKey, sequences);
2815        }
2816
2817        Long count = sd.messageReferences.get(messageSequence);
2818        if (count == null) {
2819            count = Long.valueOf(0L);
2820        }
2821        count = count.longValue() + 1;
2822        sd.messageReferences.put(messageSequence, count);
2823    }
2824
2825    // new sub is interested in potentially all existing messages
2826    private void addAckLocationForRetroactiveSub(Transaction tx, StoredDestination sd, String subscriptionKey) throws IOException {
2827        SequenceSet allOutstanding = new SequenceSet();
2828        Iterator<Map.Entry<String, SequenceSet>> iterator = sd.ackPositions.iterator(tx);
2829        while (iterator.hasNext()) {
2830            SequenceSet set = iterator.next().getValue();
2831            for (Long entry : set) {
2832                allOutstanding.add(entry);
2833            }
2834        }
2835        sd.ackPositions.put(tx, subscriptionKey, allOutstanding);
2836
2837        for (Long ackPosition : allOutstanding) {
2838            Long count = sd.messageReferences.get(ackPosition);
2839
2840            // There might not be a reference if the ackLocation was the last
2841            // one which is a placeholder for the next incoming message and
2842            // no value was added to the message references table.
2843            if (count != null) {
2844                count = count.longValue() + 1;
2845                sd.messageReferences.put(ackPosition, count);
2846            }
2847        }
2848    }
2849
2850    // on a new message add, all existing subs are interested in this message
2851    private void addAckLocationForNewMessage(Transaction tx, KahaDestination kahaDest,
2852            StoredDestination sd, Long messageSequence) throws IOException {
2853        for(String subscriptionKey : sd.subscriptionCache) {
2854            SequenceSet sequences = sd.ackPositions.get(tx, subscriptionKey);
2855            if (sequences == null) {
2856                sequences = new SequenceSet();
2857                sequences.add(new Sequence(messageSequence, messageSequence + 1));
2858                sd.ackPositions.add(tx, subscriptionKey, sequences);
2859            } else {
2860                sequences.add(new Sequence(messageSequence, messageSequence + 1));
2861                sd.ackPositions.put(tx, subscriptionKey, sequences);
2862            }
2863
2864            MessageKeys key = sd.orderIndex.get(tx, messageSequence);
2865            incrementAndAddSizeToStoreStat(kahaDest, subscriptionKey,
2866                    key.location.getSize());
2867
2868            Long count = sd.messageReferences.get(messageSequence);
2869            if (count == null) {
2870                count = Long.valueOf(0L);
2871            }
2872            count = count.longValue() + 1;
2873            sd.messageReferences.put(messageSequence, count);
2874            sd.messageReferences.put(messageSequence + 1, Long.valueOf(0L));
2875        }
2876    }
2877
2878    private void removeAckLocationsForSub(KahaSubscriptionCommand command,
2879            Transaction tx, StoredDestination sd, String subscriptionKey) throws IOException {
2880        if (!sd.ackPositions.isEmpty(tx)) {
2881            SequenceSet sequences = sd.ackPositions.remove(tx, subscriptionKey);
2882            if (sequences == null || sequences.isEmpty()) {
2883                return;
2884            }
2885
2886            ArrayList<Long> unreferenced = new ArrayList<>();
2887
2888            for(Long sequenceId : sequences) {
2889                Long references = sd.messageReferences.get(sequenceId);
2890                if (references != null) {
2891                    references = references.longValue() - 1;
2892
2893                    if (references.longValue() > 0) {
2894                        sd.messageReferences.put(sequenceId, references);
2895                    } else {
2896                        sd.messageReferences.remove(sequenceId);
2897                        unreferenced.add(sequenceId);
2898                    }
2899                }
2900            }
2901
2902            for(Long sequenceId : unreferenced) {
2903                // Find all the entries that need to get deleted.
2904                ArrayList<Entry<Long, MessageKeys>> deletes = new ArrayList<>();
2905                sd.orderIndex.getDeleteList(tx, deletes, sequenceId);
2906
2907                // Do the actual deletes.
2908                for (Entry<Long, MessageKeys> entry : deletes) {
2909                    sd.locationIndex.remove(tx, entry.getValue().location);
2910                    sd.messageIdIndex.remove(tx, entry.getValue().messageId);
2911                    sd.orderIndex.remove(tx, entry.getKey());
2912                    decrementAndSubSizeToStoreStat(command.getDestination(), entry.getValue().location.getSize());
2913                }
2914            }
2915        }
2916    }
2917
2918    /**
2919     * @param tx
2920     * @param sd
2921     * @param subscriptionKey
2922     * @param messageSequence
2923     * @throws IOException
2924     */
2925    private void removeAckLocation(KahaRemoveMessageCommand command,
2926            Transaction tx, StoredDestination sd, String subscriptionKey,
2927            Long messageSequence) throws IOException {
2928        // Remove the sub from the previous location set..
2929        if (messageSequence != null) {
2930            SequenceSet range = sd.ackPositions.get(tx, subscriptionKey);
2931            if (range != null && !range.isEmpty()) {
2932                range.remove(messageSequence);
2933                if (!range.isEmpty()) {
2934                    sd.ackPositions.put(tx, subscriptionKey, range);
2935                } else {
2936                    sd.ackPositions.remove(tx, subscriptionKey);
2937                }
2938
2939                MessageKeys key = sd.orderIndex.get(tx, messageSequence);
2940                decrementAndSubSizeToStoreStat(command.getDestination(), subscriptionKey,
2941                        key.location.getSize());
2942
2943                // Check if the message is reference by any other subscription.
2944                Long count = sd.messageReferences.get(messageSequence);
2945                if (count != null) {
2946                    long references = count.longValue() - 1;
2947                    if (references > 0) {
2948                        sd.messageReferences.put(messageSequence, Long.valueOf(references));
2949                        return;
2950                    } else {
2951                        sd.messageReferences.remove(messageSequence);
2952                    }
2953                }
2954
2955                // Find all the entries that need to get deleted.
2956                ArrayList<Entry<Long, MessageKeys>> deletes = new ArrayList<>();
2957                sd.orderIndex.getDeleteList(tx, deletes, messageSequence);
2958
2959                // Do the actual deletes.
2960                for (Entry<Long, MessageKeys> entry : deletes) {
2961                    sd.locationIndex.remove(tx, entry.getValue().location);
2962                    sd.messageIdIndex.remove(tx, entry.getValue().messageId);
2963                    sd.orderIndex.remove(tx, entry.getKey());
2964                    decrementAndSubSizeToStoreStat(command.getDestination(), entry.getValue().location.getSize());
2965                }
2966            }
2967        }
2968    }
2969
2970    public LastAck getLastAck(Transaction tx, StoredDestination sd, String subscriptionKey) throws IOException {
2971        return sd.subscriptionAcks.get(tx, subscriptionKey);
2972    }
2973
2974    protected long getStoredMessageCount(Transaction tx, StoredDestination sd, String subscriptionKey) throws IOException {
2975        if (sd.ackPositions != null) {
2976            SequenceSet messageSequences = sd.ackPositions.get(tx, subscriptionKey);
2977            if (messageSequences != null) {
2978                long result = messageSequences.rangeSize();
2979                // if there's anything in the range the last value is always the nextMessage marker, so remove 1.
2980                return result > 0 ? result - 1 : 0;
2981            }
2982        }
2983
2984        return 0;
2985    }
2986
2987    protected long getStoredMessageSize(Transaction tx, StoredDestination sd, String subscriptionKey) throws IOException {
2988        long locationSize = 0;
2989
2990        if (sd.ackPositions != null) {
2991            //grab the messages attached to this subscription
2992            SequenceSet messageSequences = sd.ackPositions.get(tx, subscriptionKey);
2993
2994            if (messageSequences != null) {
2995                Sequence head = messageSequences.getHead();
2996                if (head != null) {
2997                    //get an iterator over the order index starting at the first unacked message
2998                    //and go over each message to add up the size
2999                    Iterator<Entry<Long, MessageKeys>> iterator = sd.orderIndex.iterator(tx,
3000                            new MessageOrderCursor(head.getFirst()));
3001
3002                    while (iterator.hasNext()) {
3003                        Entry<Long, MessageKeys> entry = iterator.next();
3004                        locationSize += entry.getValue().location.getSize();
3005                    }
3006                }
3007            }
3008        }
3009
3010        return locationSize;
3011    }
3012
3013    protected String key(KahaDestination destination) {
3014        return destination.getType().getNumber() + ":" + destination.getName();
3015    }
3016
3017    // /////////////////////////////////////////////////////////////////
3018    // Transaction related implementation methods.
3019    // /////////////////////////////////////////////////////////////////
3020    @SuppressWarnings("rawtypes")
3021    private final LinkedHashMap<TransactionId, List<Operation>> inflightTransactions = new LinkedHashMap<>();
3022    @SuppressWarnings("rawtypes")
3023    protected final LinkedHashMap<TransactionId, List<Operation>> preparedTransactions = new LinkedHashMap<>();
3024    protected final Set<String> ackedAndPrepared = new HashSet<>();
3025    protected final Set<String> rolledBackAcks = new HashSet<>();
3026
3027    // messages that have prepared (pending) acks cannot be re-dispatched unless the outcome is rollback,
3028    // till then they are skipped by the store.
3029    // 'at most once' XA guarantee
3030    public void trackRecoveredAcks(ArrayList<MessageAck> acks) {
3031        this.indexLock.writeLock().lock();
3032        try {
3033            for (MessageAck ack : acks) {
3034                ackedAndPrepared.add(ack.getLastMessageId().toProducerKey());
3035            }
3036        } finally {
3037            this.indexLock.writeLock().unlock();
3038        }
3039    }
3040
3041    public void forgetRecoveredAcks(ArrayList<MessageAck> acks, boolean rollback) throws IOException {
3042        if (acks != null) {
3043            this.indexLock.writeLock().lock();
3044            try {
3045                for (MessageAck ack : acks) {
3046                    final String id = ack.getLastMessageId().toProducerKey();
3047                    ackedAndPrepared.remove(id);
3048                    if (rollback) {
3049                        rolledBackAcks.add(id);
3050                    }
3051                }
3052            } finally {
3053                this.indexLock.writeLock().unlock();
3054            }
3055        }
3056    }
3057
3058    @SuppressWarnings("rawtypes")
3059    private List<Operation> getInflightTx(KahaTransactionInfo info) {
3060        TransactionId key = TransactionIdConversion.convert(info);
3061        List<Operation> tx;
3062        synchronized (inflightTransactions) {
3063            tx = inflightTransactions.get(key);
3064            if (tx == null) {
3065                tx = Collections.synchronizedList(new ArrayList<Operation>());
3066                inflightTransactions.put(key, tx);
3067            }
3068        }
3069        return tx;
3070    }
3071
3072    @SuppressWarnings("unused")
3073    private TransactionId key(KahaTransactionInfo transactionInfo) {
3074        return TransactionIdConversion.convert(transactionInfo);
3075    }
3076
3077    abstract class Operation <T extends JournalCommand<T>> {
3078        final T command;
3079        final Location location;
3080
3081        public Operation(T command, Location location) {
3082            this.command = command;
3083            this.location = location;
3084        }
3085
3086        public Location getLocation() {
3087            return location;
3088        }
3089
3090        public T getCommand() {
3091            return command;
3092        }
3093
3094        abstract public void execute(Transaction tx) throws IOException;
3095    }
3096
3097    class AddOperation extends Operation<KahaAddMessageCommand> {
3098        final IndexAware runWithIndexLock;
3099        public AddOperation(KahaAddMessageCommand command, Location location, IndexAware runWithIndexLock) {
3100            super(command, location);
3101            this.runWithIndexLock = runWithIndexLock;
3102        }
3103
3104        @Override
3105        public void execute(Transaction tx) throws IOException {
3106            long seq = updateIndex(tx, command, location);
3107            if (runWithIndexLock != null) {
3108                runWithIndexLock.sequenceAssignedWithIndexLocked(seq);
3109            }
3110        }
3111    }
3112
3113    class RemoveOperation extends Operation<KahaRemoveMessageCommand> {
3114
3115        public RemoveOperation(KahaRemoveMessageCommand command, Location location) {
3116            super(command, location);
3117        }
3118
3119        @Override
3120        public void execute(Transaction tx) throws IOException {
3121            updateIndex(tx, command, location);
3122        }
3123    }
3124
3125    // /////////////////////////////////////////////////////////////////
3126    // Initialization related implementation methods.
3127    // /////////////////////////////////////////////////////////////////
3128
3129    private PageFile createPageFile() throws IOException {
3130        if (indexDirectory == null) {
3131            indexDirectory = directory;
3132        }
3133        IOHelper.mkdirs(indexDirectory);
3134        PageFile index = new PageFile(indexDirectory, "db");
3135        index.setEnableWriteThread(isEnableIndexWriteAsync());
3136        index.setWriteBatchSize(getIndexWriteBatchSize());
3137        index.setPageCacheSize(indexCacheSize);
3138        index.setUseLFRUEviction(isUseIndexLFRUEviction());
3139        index.setLFUEvictionFactor(getIndexLFUEvictionFactor());
3140        index.setEnableDiskSyncs(isEnableIndexDiskSyncs());
3141        index.setEnableRecoveryFile(isEnableIndexRecoveryFile());
3142        index.setEnablePageCaching(isEnableIndexPageCaching());
3143        return index;
3144    }
3145
3146    private Journal createJournal() throws IOException {
3147        Journal manager = new Journal();
3148        manager.setDirectory(directory);
3149        manager.setMaxFileLength(getJournalMaxFileLength());
3150        manager.setCheckForCorruptionOnStartup(checkForCorruptJournalFiles);
3151        manager.setChecksum(checksumJournalFiles || checkForCorruptJournalFiles);
3152        manager.setWriteBatchSize(getJournalMaxWriteBatchSize());
3153        manager.setArchiveDataLogs(isArchiveDataLogs());
3154        manager.setSizeAccumulator(journalSize);
3155        manager.setEnableAsyncDiskSync(isEnableJournalDiskSyncs());
3156        manager.setPreallocationScope(Journal.PreallocationScope.valueOf(preallocationScope.trim().toUpperCase()));
3157        manager.setPreallocationStrategy(
3158                Journal.PreallocationStrategy.valueOf(preallocationStrategy.trim().toUpperCase()));
3159        manager.setJournalDiskSyncStrategy(journalDiskSyncStrategy);
3160        if (getDirectoryArchive() != null) {
3161            IOHelper.mkdirs(getDirectoryArchive());
3162            manager.setDirectoryArchive(getDirectoryArchive());
3163        }
3164        return manager;
3165    }
3166
3167    private Metadata createMetadata() {
3168        Metadata md = new Metadata();
3169        md.producerSequenceIdTracker.setAuditDepth(getFailoverProducersAuditDepth());
3170        md.producerSequenceIdTracker.setMaximumNumberOfProducersToTrack(getMaxFailoverProducersToTrack());
3171        return md;
3172    }
3173
3174    protected abstract void configureMetadata();
3175
3176    public int getJournalMaxWriteBatchSize() {
3177        return journalMaxWriteBatchSize;
3178    }
3179
3180    public void setJournalMaxWriteBatchSize(int journalMaxWriteBatchSize) {
3181        this.journalMaxWriteBatchSize = journalMaxWriteBatchSize;
3182    }
3183
3184    public File getDirectory() {
3185        return directory;
3186    }
3187
3188    public void setDirectory(File directory) {
3189        this.directory = directory;
3190    }
3191
3192    public boolean isDeleteAllMessages() {
3193        return deleteAllMessages;
3194    }
3195
3196    public void setDeleteAllMessages(boolean deleteAllMessages) {
3197        this.deleteAllMessages = deleteAllMessages;
3198    }
3199
3200    public void setIndexWriteBatchSize(int setIndexWriteBatchSize) {
3201        this.setIndexWriteBatchSize = setIndexWriteBatchSize;
3202    }
3203
3204    public int getIndexWriteBatchSize() {
3205        return setIndexWriteBatchSize;
3206    }
3207
3208    public void setEnableIndexWriteAsync(boolean enableIndexWriteAsync) {
3209        this.enableIndexWriteAsync = enableIndexWriteAsync;
3210    }
3211
3212    boolean isEnableIndexWriteAsync() {
3213        return enableIndexWriteAsync;
3214    }
3215
3216    /**
3217     * @deprecated use {@link #getJournalDiskSyncStrategyEnum} or {@link #getJournalDiskSyncStrategy} instead
3218     * @return
3219     */
3220    @Deprecated
3221    public boolean isEnableJournalDiskSyncs() {
3222        return journalDiskSyncStrategy == JournalDiskSyncStrategy.ALWAYS;
3223    }
3224
3225    /**
3226     * @deprecated use {@link #setEnableJournalDiskSyncs} instead
3227     * @param syncWrites
3228     */
3229    @Deprecated
3230    public void setEnableJournalDiskSyncs(boolean syncWrites) {
3231        if (syncWrites) {
3232            journalDiskSyncStrategy = JournalDiskSyncStrategy.ALWAYS;
3233        } else {
3234            journalDiskSyncStrategy = JournalDiskSyncStrategy.NEVER;
3235        }
3236    }
3237
3238    public JournalDiskSyncStrategy getJournalDiskSyncStrategyEnum() {
3239        return journalDiskSyncStrategy;
3240    }
3241
3242    public String getJournalDiskSyncStrategy() {
3243        return journalDiskSyncStrategy.name();
3244    }
3245
3246    public void setJournalDiskSyncStrategy(String journalDiskSyncStrategy) {
3247        this.journalDiskSyncStrategy = JournalDiskSyncStrategy.valueOf(journalDiskSyncStrategy.trim().toUpperCase());
3248    }
3249
3250    public long getJournalDiskSyncInterval() {
3251        return journalDiskSyncInterval;
3252    }
3253
3254    public void setJournalDiskSyncInterval(long journalDiskSyncInterval) {
3255        this.journalDiskSyncInterval = journalDiskSyncInterval;
3256    }
3257
3258    public long getCheckpointInterval() {
3259        return checkpointInterval;
3260    }
3261
3262    public void setCheckpointInterval(long checkpointInterval) {
3263        this.checkpointInterval = checkpointInterval;
3264    }
3265
3266    public long getCleanupInterval() {
3267        return cleanupInterval;
3268    }
3269
3270    public void setCleanupInterval(long cleanupInterval) {
3271        this.cleanupInterval = cleanupInterval;
3272    }
3273
3274    public void setJournalMaxFileLength(int journalMaxFileLength) {
3275        this.journalMaxFileLength = journalMaxFileLength;
3276    }
3277
3278    public int getJournalMaxFileLength() {
3279        return journalMaxFileLength;
3280    }
3281
3282    public void setMaxFailoverProducersToTrack(int maxFailoverProducersToTrack) {
3283        this.metadata.producerSequenceIdTracker.setMaximumNumberOfProducersToTrack(maxFailoverProducersToTrack);
3284    }
3285
3286    public int getMaxFailoverProducersToTrack() {
3287        return this.metadata.producerSequenceIdTracker.getMaximumNumberOfProducersToTrack();
3288    }
3289
3290    public void setFailoverProducersAuditDepth(int failoverProducersAuditDepth) {
3291        this.metadata.producerSequenceIdTracker.setAuditDepth(failoverProducersAuditDepth);
3292    }
3293
3294    public int getFailoverProducersAuditDepth() {
3295        return this.metadata.producerSequenceIdTracker.getAuditDepth();
3296    }
3297
3298    public PageFile getPageFile() throws IOException {
3299        if (pageFile == null) {
3300            pageFile = createPageFile();
3301        }
3302        return pageFile;
3303    }
3304
3305    public Journal getJournal() throws IOException {
3306        if (journal == null) {
3307            journal = createJournal();
3308        }
3309        return journal;
3310    }
3311
3312    protected Metadata getMetadata() {
3313        return metadata;
3314    }
3315
3316    public boolean isFailIfDatabaseIsLocked() {
3317        return failIfDatabaseIsLocked;
3318    }
3319
3320    public void setFailIfDatabaseIsLocked(boolean failIfDatabaseIsLocked) {
3321        this.failIfDatabaseIsLocked = failIfDatabaseIsLocked;
3322    }
3323
3324    public boolean isIgnoreMissingJournalfiles() {
3325        return ignoreMissingJournalfiles;
3326    }
3327
3328    public void setIgnoreMissingJournalfiles(boolean ignoreMissingJournalfiles) {
3329        this.ignoreMissingJournalfiles = ignoreMissingJournalfiles;
3330    }
3331
3332    public int getIndexCacheSize() {
3333        return indexCacheSize;
3334    }
3335
3336    public void setIndexCacheSize(int indexCacheSize) {
3337        this.indexCacheSize = indexCacheSize;
3338    }
3339
3340    public boolean isCheckForCorruptJournalFiles() {
3341        return checkForCorruptJournalFiles;
3342    }
3343
3344    public void setCheckForCorruptJournalFiles(boolean checkForCorruptJournalFiles) {
3345        this.checkForCorruptJournalFiles = checkForCorruptJournalFiles;
3346    }
3347
3348    public boolean isChecksumJournalFiles() {
3349        return checksumJournalFiles;
3350    }
3351
3352    public void setChecksumJournalFiles(boolean checksumJournalFiles) {
3353        this.checksumJournalFiles = checksumJournalFiles;
3354    }
3355
3356    @Override
3357    public void setBrokerService(BrokerService brokerService) {
3358        this.brokerService = brokerService;
3359    }
3360
3361    /**
3362     * @return the archiveDataLogs
3363     */
3364    public boolean isArchiveDataLogs() {
3365        return this.archiveDataLogs;
3366    }
3367
3368    /**
3369     * @param archiveDataLogs the archiveDataLogs to set
3370     */
3371    public void setArchiveDataLogs(boolean archiveDataLogs) {
3372        this.archiveDataLogs = archiveDataLogs;
3373    }
3374
3375    /**
3376     * @return the directoryArchive
3377     */
3378    public File getDirectoryArchive() {
3379        return this.directoryArchive;
3380    }
3381
3382    /**
3383     * @param directoryArchive the directoryArchive to set
3384     */
3385    public void setDirectoryArchive(File directoryArchive) {
3386        this.directoryArchive = directoryArchive;
3387    }
3388
3389    public boolean isArchiveCorruptedIndex() {
3390        return archiveCorruptedIndex;
3391    }
3392
3393    public void setArchiveCorruptedIndex(boolean archiveCorruptedIndex) {
3394        this.archiveCorruptedIndex = archiveCorruptedIndex;
3395    }
3396
3397    public float getIndexLFUEvictionFactor() {
3398        return indexLFUEvictionFactor;
3399    }
3400
3401    public void setIndexLFUEvictionFactor(float indexLFUEvictionFactor) {
3402        this.indexLFUEvictionFactor = indexLFUEvictionFactor;
3403    }
3404
3405    public boolean isUseIndexLFRUEviction() {
3406        return useIndexLFRUEviction;
3407    }
3408
3409    public void setUseIndexLFRUEviction(boolean useIndexLFRUEviction) {
3410        this.useIndexLFRUEviction = useIndexLFRUEviction;
3411    }
3412
3413    public void setEnableIndexDiskSyncs(boolean enableIndexDiskSyncs) {
3414        this.enableIndexDiskSyncs = enableIndexDiskSyncs;
3415    }
3416
3417    public void setEnableIndexRecoveryFile(boolean enableIndexRecoveryFile) {
3418        this.enableIndexRecoveryFile = enableIndexRecoveryFile;
3419    }
3420
3421    public void setEnableIndexPageCaching(boolean enableIndexPageCaching) {
3422        this.enableIndexPageCaching = enableIndexPageCaching;
3423    }
3424
3425    public boolean isEnableIndexDiskSyncs() {
3426        return enableIndexDiskSyncs;
3427    }
3428
3429    public boolean isEnableIndexRecoveryFile() {
3430        return enableIndexRecoveryFile;
3431    }
3432
3433    public boolean isEnableIndexPageCaching() {
3434        return enableIndexPageCaching;
3435    }
3436
3437    // /////////////////////////////////////////////////////////////////
3438    // Internal conversion methods.
3439    // /////////////////////////////////////////////////////////////////
3440
3441    class MessageOrderCursor{
3442        long defaultCursorPosition;
3443        long lowPriorityCursorPosition;
3444        long highPriorityCursorPosition;
3445        MessageOrderCursor(){
3446        }
3447
3448        MessageOrderCursor(long position){
3449            this.defaultCursorPosition=position;
3450            this.lowPriorityCursorPosition=position;
3451            this.highPriorityCursorPosition=position;
3452        }
3453
3454        MessageOrderCursor(MessageOrderCursor other){
3455            this.defaultCursorPosition=other.defaultCursorPosition;
3456            this.lowPriorityCursorPosition=other.lowPriorityCursorPosition;
3457            this.highPriorityCursorPosition=other.highPriorityCursorPosition;
3458        }
3459
3460        MessageOrderCursor copy() {
3461            return new MessageOrderCursor(this);
3462        }
3463
3464        void reset() {
3465            this.defaultCursorPosition=0;
3466            this.highPriorityCursorPosition=0;
3467            this.lowPriorityCursorPosition=0;
3468        }
3469
3470        void increment() {
3471            if (defaultCursorPosition!=0) {
3472                defaultCursorPosition++;
3473            }
3474            if (highPriorityCursorPosition!=0) {
3475                highPriorityCursorPosition++;
3476            }
3477            if (lowPriorityCursorPosition!=0) {
3478                lowPriorityCursorPosition++;
3479            }
3480        }
3481
3482        @Override
3483        public String toString() {
3484           return "MessageOrderCursor:[def:" + defaultCursorPosition
3485                   + ", low:" + lowPriorityCursorPosition
3486                   + ", high:" +  highPriorityCursorPosition + "]";
3487        }
3488
3489        public void sync(MessageOrderCursor other) {
3490            this.defaultCursorPosition=other.defaultCursorPosition;
3491            this.lowPriorityCursorPosition=other.lowPriorityCursorPosition;
3492            this.highPriorityCursorPosition=other.highPriorityCursorPosition;
3493        }
3494    }
3495
3496    class MessageOrderIndex {
3497        static final byte HI = 9;
3498        static final byte LO = 0;
3499        static final byte DEF = 4;
3500
3501        long nextMessageId;
3502        BTreeIndex<Long, MessageKeys> defaultPriorityIndex;
3503        BTreeIndex<Long, MessageKeys> lowPriorityIndex;
3504        BTreeIndex<Long, MessageKeys> highPriorityIndex;
3505        final MessageOrderCursor cursor = new MessageOrderCursor();
3506        Long lastDefaultKey;
3507        Long lastHighKey;
3508        Long lastLowKey;
3509        byte lastGetPriority;
3510        final List<Long> pendingAdditions = new LinkedList<>();
3511        final MessageKeysMarshaller messageKeysMarshaller = new MessageKeysMarshaller();
3512
3513        MessageKeys remove(Transaction tx, Long key) throws IOException {
3514            MessageKeys result = defaultPriorityIndex.remove(tx, key);
3515            if (result == null && highPriorityIndex!=null) {
3516                result = highPriorityIndex.remove(tx, key);
3517                if (result ==null && lowPriorityIndex!=null) {
3518                    result = lowPriorityIndex.remove(tx, key);
3519                }
3520            }
3521            return result;
3522        }
3523
3524        void load(Transaction tx) throws IOException {
3525            defaultPriorityIndex.setKeyMarshaller(LongMarshaller.INSTANCE);
3526            defaultPriorityIndex.setValueMarshaller(messageKeysMarshaller);
3527            defaultPriorityIndex.load(tx);
3528            lowPriorityIndex.setKeyMarshaller(LongMarshaller.INSTANCE);
3529            lowPriorityIndex.setValueMarshaller(messageKeysMarshaller);
3530            lowPriorityIndex.load(tx);
3531            highPriorityIndex.setKeyMarshaller(LongMarshaller.INSTANCE);
3532            highPriorityIndex.setValueMarshaller(messageKeysMarshaller);
3533            highPriorityIndex.load(tx);
3534        }
3535
3536        void allocate(Transaction tx) throws IOException {
3537            defaultPriorityIndex = new BTreeIndex<>(pageFile, tx.allocate());
3538            if (metadata.version >= 2) {
3539                lowPriorityIndex = new BTreeIndex<>(pageFile, tx.allocate());
3540                highPriorityIndex = new BTreeIndex<>(pageFile, tx.allocate());
3541            }
3542        }
3543
3544        void configureLast(Transaction tx) throws IOException {
3545            // Figure out the next key using the last entry in the destination.
3546            TreeSet<Long> orderedSet = new TreeSet<>();
3547
3548            addLast(orderedSet, highPriorityIndex, tx);
3549            addLast(orderedSet, defaultPriorityIndex, tx);
3550            addLast(orderedSet, lowPriorityIndex, tx);
3551
3552            if (!orderedSet.isEmpty()) {
3553                nextMessageId = orderedSet.last() + 1;
3554            }
3555        }
3556
3557        private void addLast(TreeSet<Long> orderedSet, BTreeIndex<Long, MessageKeys> index, Transaction tx) throws IOException {
3558            if (index != null) {
3559                Entry<Long, MessageKeys> lastEntry = index.getLast(tx);
3560                if (lastEntry != null) {
3561                    orderedSet.add(lastEntry.getKey());
3562                }
3563            }
3564        }
3565
3566        void clear(Transaction tx) throws IOException {
3567            this.remove(tx);
3568            this.resetCursorPosition();
3569            this.allocate(tx);
3570            this.load(tx);
3571            this.configureLast(tx);
3572        }
3573
3574        void remove(Transaction tx) throws IOException {
3575            defaultPriorityIndex.clear(tx);
3576            defaultPriorityIndex.unload(tx);
3577            tx.free(defaultPriorityIndex.getPageId());
3578            if (lowPriorityIndex != null) {
3579                lowPriorityIndex.clear(tx);
3580                lowPriorityIndex.unload(tx);
3581
3582                tx.free(lowPriorityIndex.getPageId());
3583            }
3584            if (highPriorityIndex != null) {
3585                highPriorityIndex.clear(tx);
3586                highPriorityIndex.unload(tx);
3587                tx.free(highPriorityIndex.getPageId());
3588            }
3589        }
3590
3591        void resetCursorPosition() {
3592            this.cursor.reset();
3593            lastDefaultKey = null;
3594            lastHighKey = null;
3595            lastLowKey = null;
3596        }
3597
3598        void setBatch(Transaction tx, Long sequence) throws IOException {
3599            if (sequence != null) {
3600                Long nextPosition = new Long(sequence.longValue() + 1);
3601                lastDefaultKey = sequence;
3602                cursor.defaultCursorPosition = nextPosition.longValue();
3603                lastHighKey = sequence;
3604                cursor.highPriorityCursorPosition = nextPosition.longValue();
3605                lastLowKey = sequence;
3606                cursor.lowPriorityCursorPosition = nextPosition.longValue();
3607            }
3608        }
3609
3610        void setBatch(Transaction tx, LastAck last) throws IOException {
3611            setBatch(tx, last.lastAckedSequence);
3612            if (cursor.defaultCursorPosition == 0
3613                    && cursor.highPriorityCursorPosition == 0
3614                    && cursor.lowPriorityCursorPosition == 0) {
3615                long next = last.lastAckedSequence + 1;
3616                switch (last.priority) {
3617                    case DEF:
3618                        cursor.defaultCursorPosition = next;
3619                        cursor.highPriorityCursorPosition = next;
3620                        break;
3621                    case HI:
3622                        cursor.highPriorityCursorPosition = next;
3623                        break;
3624                    case LO:
3625                        cursor.lowPriorityCursorPosition = next;
3626                        cursor.defaultCursorPosition = next;
3627                        cursor.highPriorityCursorPosition = next;
3628                        break;
3629                }
3630            }
3631        }
3632
3633        void stoppedIterating() {
3634            if (lastDefaultKey!=null) {
3635                cursor.defaultCursorPosition=lastDefaultKey.longValue()+1;
3636            }
3637            if (lastHighKey!=null) {
3638                cursor.highPriorityCursorPosition=lastHighKey.longValue()+1;
3639            }
3640            if (lastLowKey!=null) {
3641                cursor.lowPriorityCursorPosition=lastLowKey.longValue()+1;
3642            }
3643            lastDefaultKey = null;
3644            lastHighKey = null;
3645            lastLowKey = null;
3646        }
3647
3648        void getDeleteList(Transaction tx, ArrayList<Entry<Long, MessageKeys>> deletes, Long sequenceId)
3649                throws IOException {
3650            if (defaultPriorityIndex.containsKey(tx, sequenceId)) {
3651                getDeleteList(tx, deletes, defaultPriorityIndex, sequenceId);
3652            } else if (highPriorityIndex != null && highPriorityIndex.containsKey(tx, sequenceId)) {
3653                getDeleteList(tx, deletes, highPriorityIndex, sequenceId);
3654            } else if (lowPriorityIndex != null && lowPriorityIndex.containsKey(tx, sequenceId)) {
3655                getDeleteList(tx, deletes, lowPriorityIndex, sequenceId);
3656            }
3657        }
3658
3659        void getDeleteList(Transaction tx, ArrayList<Entry<Long, MessageKeys>> deletes,
3660                BTreeIndex<Long, MessageKeys> index, Long sequenceId) throws IOException {
3661
3662            Iterator<Entry<Long, MessageKeys>> iterator = index.iterator(tx, sequenceId, null);
3663            deletes.add(iterator.next());
3664        }
3665
3666        long getNextMessageId() {
3667            return nextMessageId++;
3668        }
3669
3670        void revertNextMessageId() {
3671            nextMessageId--;
3672        }
3673
3674        MessageKeys get(Transaction tx, Long key) throws IOException {
3675            MessageKeys result = defaultPriorityIndex.get(tx, key);
3676            if (result == null) {
3677                result = highPriorityIndex.get(tx, key);
3678                if (result == null) {
3679                    result = lowPriorityIndex.get(tx, key);
3680                    lastGetPriority = LO;
3681                } else {
3682                    lastGetPriority = HI;
3683                }
3684            } else {
3685                lastGetPriority = DEF;
3686            }
3687            return result;
3688        }
3689
3690        MessageKeys put(Transaction tx, int priority, Long key, MessageKeys value) throws IOException {
3691            if (priority == javax.jms.Message.DEFAULT_PRIORITY) {
3692                return defaultPriorityIndex.put(tx, key, value);
3693            } else if (priority > javax.jms.Message.DEFAULT_PRIORITY) {
3694                return highPriorityIndex.put(tx, key, value);
3695            } else {
3696                return lowPriorityIndex.put(tx, key, value);
3697            }
3698        }
3699
3700        Iterator<Entry<Long, MessageKeys>> iterator(Transaction tx) throws IOException{
3701            return new MessageOrderIterator(tx,cursor,this);
3702        }
3703
3704        Iterator<Entry<Long, MessageKeys>> iterator(Transaction tx, MessageOrderCursor m) throws IOException{
3705            return new MessageOrderIterator(tx,m,this);
3706        }
3707
3708        public byte lastGetPriority() {
3709            return lastGetPriority;
3710        }
3711
3712        public boolean alreadyDispatched(Long sequence) {
3713            return (cursor.highPriorityCursorPosition > 0 && cursor.highPriorityCursorPosition >= sequence) ||
3714                    (cursor.defaultCursorPosition > 0 && cursor.defaultCursorPosition >= sequence) ||
3715                    (cursor.lowPriorityCursorPosition > 0 && cursor.lowPriorityCursorPosition >= sequence);
3716        }
3717
3718        public void trackPendingAdd(Long seq) {
3719            synchronized (pendingAdditions) {
3720                pendingAdditions.add(seq);
3721            }
3722        }
3723
3724        public void trackPendingAddComplete(Long seq) {
3725            synchronized (pendingAdditions) {
3726                pendingAdditions.remove(seq);
3727            }
3728        }
3729
3730        public Long minPendingAdd() {
3731            synchronized (pendingAdditions) {
3732                if (!pendingAdditions.isEmpty()) {
3733                    return pendingAdditions.get(0);
3734                } else {
3735                    return null;
3736                }
3737            }
3738        }
3739
3740        class MessageOrderIterator implements Iterator<Entry<Long, MessageKeys>>{
3741            Iterator<Entry<Long, MessageKeys>>currentIterator;
3742            final Iterator<Entry<Long, MessageKeys>>highIterator;
3743            final Iterator<Entry<Long, MessageKeys>>defaultIterator;
3744            final Iterator<Entry<Long, MessageKeys>>lowIterator;
3745
3746            MessageOrderIterator(Transaction tx, MessageOrderCursor m, MessageOrderIndex messageOrderIndex) throws IOException {
3747                Long pendingAddLimiter = messageOrderIndex.minPendingAdd();
3748                this.defaultIterator = defaultPriorityIndex.iterator(tx, m.defaultCursorPosition, pendingAddLimiter);
3749                if (highPriorityIndex != null) {
3750                    this.highIterator = highPriorityIndex.iterator(tx, m.highPriorityCursorPosition, pendingAddLimiter);
3751                } else {
3752                    this.highIterator = null;
3753                }
3754                if (lowPriorityIndex != null) {
3755                    this.lowIterator = lowPriorityIndex.iterator(tx, m.lowPriorityCursorPosition, pendingAddLimiter);
3756                } else {
3757                    this.lowIterator = null;
3758                }
3759            }
3760
3761            @Override
3762            public boolean hasNext() {
3763                if (currentIterator == null) {
3764                    if (highIterator != null) {
3765                        if (highIterator.hasNext()) {
3766                            currentIterator = highIterator;
3767                            return currentIterator.hasNext();
3768                        }
3769                        if (defaultIterator.hasNext()) {
3770                            currentIterator = defaultIterator;
3771                            return currentIterator.hasNext();
3772                        }
3773                        if (lowIterator.hasNext()) {
3774                            currentIterator = lowIterator;
3775                            return currentIterator.hasNext();
3776                        }
3777                        return false;
3778                    } else {
3779                        currentIterator = defaultIterator;
3780                        return currentIterator.hasNext();
3781                    }
3782                }
3783                if (highIterator != null) {
3784                    if (currentIterator.hasNext()) {
3785                        return true;
3786                    }
3787                    if (currentIterator == highIterator) {
3788                        if (defaultIterator.hasNext()) {
3789                            currentIterator = defaultIterator;
3790                            return currentIterator.hasNext();
3791                        }
3792                        if (lowIterator.hasNext()) {
3793                            currentIterator = lowIterator;
3794                            return currentIterator.hasNext();
3795                        }
3796                        return false;
3797                    }
3798
3799                    if (currentIterator == defaultIterator) {
3800                        if (lowIterator.hasNext()) {
3801                            currentIterator = lowIterator;
3802                            return currentIterator.hasNext();
3803                        }
3804                        return false;
3805                    }
3806                }
3807                return currentIterator.hasNext();
3808            }
3809
3810            @Override
3811            public Entry<Long, MessageKeys> next() {
3812                Entry<Long, MessageKeys> result = currentIterator.next();
3813                if (result != null) {
3814                    Long key = result.getKey();
3815                    if (highIterator != null) {
3816                        if (currentIterator == defaultIterator) {
3817                            lastDefaultKey = key;
3818                        } else if (currentIterator == highIterator) {
3819                            lastHighKey = key;
3820                        } else {
3821                            lastLowKey = key;
3822                        }
3823                    } else {
3824                        lastDefaultKey = key;
3825                    }
3826                }
3827                return result;
3828            }
3829
3830            @Override
3831            public void remove() {
3832                throw new UnsupportedOperationException();
3833            }
3834        }
3835    }
3836
3837    private static class HashSetStringMarshaller extends VariableMarshaller<HashSet<String>> {
3838        final static HashSetStringMarshaller INSTANCE = new HashSetStringMarshaller();
3839
3840        @Override
3841        public void writePayload(HashSet<String> object, DataOutput dataOut) throws IOException {
3842            ByteArrayOutputStream baos = new ByteArrayOutputStream();
3843            ObjectOutputStream oout = new ObjectOutputStream(baos);
3844            oout.writeObject(object);
3845            oout.flush();
3846            oout.close();
3847            byte[] data = baos.toByteArray();
3848            dataOut.writeInt(data.length);
3849            dataOut.write(data);
3850        }
3851
3852        @Override
3853        @SuppressWarnings("unchecked")
3854        public HashSet<String> readPayload(DataInput dataIn) throws IOException {
3855            int dataLen = dataIn.readInt();
3856            byte[] data = new byte[dataLen];
3857            dataIn.readFully(data);
3858            ByteArrayInputStream bais = new ByteArrayInputStream(data);
3859            ObjectInputStream oin = new ObjectInputStream(bais);
3860            try {
3861                return (HashSet<String>) oin.readObject();
3862            } catch (ClassNotFoundException cfe) {
3863                IOException ioe = new IOException("Failed to read HashSet<String>: " + cfe);
3864                ioe.initCause(cfe);
3865                throw ioe;
3866            }
3867        }
3868    }
3869
3870    public File getIndexDirectory() {
3871        return indexDirectory;
3872    }
3873
3874    public void setIndexDirectory(File indexDirectory) {
3875        this.indexDirectory = indexDirectory;
3876    }
3877
3878    interface IndexAware {
3879        public void sequenceAssignedWithIndexLocked(long index);
3880    }
3881
3882    public String getPreallocationScope() {
3883        return preallocationScope;
3884    }
3885
3886    public void setPreallocationScope(String preallocationScope) {
3887        this.preallocationScope = preallocationScope;
3888    }
3889
3890    public String getPreallocationStrategy() {
3891        return preallocationStrategy;
3892    }
3893
3894    public void setPreallocationStrategy(String preallocationStrategy) {
3895        this.preallocationStrategy = preallocationStrategy;
3896    }
3897
3898    public int getCompactAcksAfterNoGC() {
3899        return compactAcksAfterNoGC;
3900    }
3901
3902    /**
3903     * Sets the number of GC cycles where no journal logs were removed before an attempt to
3904     * move forward all the acks in the last log that contains them and is otherwise unreferenced.
3905     * <p>
3906     * A value of -1 will disable this feature.
3907     *
3908     * @param compactAcksAfterNoGC
3909     *      Number of empty GC cycles before we rewrite old ACKS.
3910     */
3911    public void setCompactAcksAfterNoGC(int compactAcksAfterNoGC) {
3912        this.compactAcksAfterNoGC = compactAcksAfterNoGC;
3913    }
3914
3915    /**
3916     * Returns whether Ack compaction will ignore that the store is still growing
3917     * and run more often.
3918     *
3919     * @return the compactAcksIgnoresStoreGrowth current value.
3920     */
3921    public boolean isCompactAcksIgnoresStoreGrowth() {
3922        return compactAcksIgnoresStoreGrowth;
3923    }
3924
3925    /**
3926     * Configure if Ack compaction will occur regardless of continued growth of the
3927     * journal logs meaning that the store has not run out of space yet.  Because the
3928     * compaction operation can be costly this value is defaulted to off and the Ack
3929     * compaction is only done when it seems that the store cannot grow and larger.
3930     *
3931     * @param compactAcksIgnoresStoreGrowth the compactAcksIgnoresStoreGrowth to set
3932     */
3933    public void setCompactAcksIgnoresStoreGrowth(boolean compactAcksIgnoresStoreGrowth) {
3934        this.compactAcksIgnoresStoreGrowth = compactAcksIgnoresStoreGrowth;
3935    }
3936
3937    /**
3938     * Returns whether Ack compaction is enabled
3939     *
3940     * @return enableAckCompaction
3941     */
3942    public boolean isEnableAckCompaction() {
3943        return enableAckCompaction;
3944    }
3945
3946    /**
3947     * Configure if the Ack compaction task should be enabled to run
3948     *
3949     * @param enableAckCompaction
3950     */
3951    public void setEnableAckCompaction(boolean enableAckCompaction) {
3952        this.enableAckCompaction = enableAckCompaction;
3953    }
3954
3955    /**
3956     * @return
3957     */
3958    public boolean isEnableSubscriptionStatistics() {
3959        return enableSubscriptionStatistics;
3960    }
3961
3962    /**
3963     * Enable caching statistics for each subscription to allow non-blocking
3964     * retrieval of metrics.  This could incur some overhead to compute if there are a lot
3965     * of subscriptions.
3966     *
3967     * @param enableSubscriptionStatistics
3968     */
3969    public void setEnableSubscriptionStatistics(boolean enableSubscriptionStatistics) {
3970        this.enableSubscriptionStatistics = enableSubscriptionStatistics;
3971    }
3972}