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