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