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.disk.journal;
018
019import java.io.EOFException;
020import java.io.File;
021import java.io.FileNotFoundException;
022import java.io.FilenameFilter;
023import java.io.IOException;
024import java.io.RandomAccessFile;
025import java.io.UnsupportedEncodingException;
026import java.nio.ByteBuffer;
027import java.nio.channels.ClosedByInterruptException;
028import java.nio.channels.FileChannel;
029import java.util.Arrays;
030import java.util.Collections;
031import java.util.HashMap;
032import java.util.Iterator;
033import java.util.LinkedHashMap;
034import java.util.LinkedList;
035import java.util.Map;
036import java.util.Set;
037import java.util.TreeMap;
038import java.util.concurrent.ConcurrentHashMap;
039import java.util.concurrent.Executors;
040import java.util.concurrent.Future;
041import java.util.concurrent.ScheduledExecutorService;
042import java.util.concurrent.ScheduledFuture;
043import java.util.concurrent.ThreadFactory;
044import java.util.concurrent.TimeUnit;
045import java.util.concurrent.atomic.AtomicLong;
046import java.util.concurrent.atomic.AtomicReference;
047import java.util.zip.Adler32;
048import java.util.zip.Checksum;
049
050import org.apache.activemq.store.kahadb.disk.util.LinkedNode;
051import org.apache.activemq.store.kahadb.disk.util.LinkedNodeList;
052import org.apache.activemq.store.kahadb.disk.util.Sequence;
053import org.apache.activemq.util.ByteSequence;
054import org.apache.activemq.util.DataByteArrayInputStream;
055import org.apache.activemq.util.DataByteArrayOutputStream;
056import org.apache.activemq.util.IOHelper;
057import org.apache.activemq.util.RecoverableRandomAccessFile;
058import org.apache.activemq.util.ThreadPoolUtils;
059import org.slf4j.Logger;
060import org.slf4j.LoggerFactory;
061
062/**
063 * Manages DataFiles
064 */
065public class Journal {
066    public static final String CALLER_BUFFER_APPENDER = "org.apache.kahadb.journal.CALLER_BUFFER_APPENDER";
067    public static final boolean callerBufferAppender = Boolean.parseBoolean(System.getProperty(CALLER_BUFFER_APPENDER, "false"));
068
069    private static final int PREALLOC_CHUNK_SIZE = 1024*1024;
070
071    // ITEM_HEAD_SPACE = length + type+ reserved space + SOR
072    public static final int RECORD_HEAD_SPACE = 4 + 1;
073
074    public static final byte USER_RECORD_TYPE = 1;
075    public static final byte BATCH_CONTROL_RECORD_TYPE = 2;
076    // Batch Control Item holds a 4 byte size of the batch and a 8 byte checksum of the batch.
077    public static final byte[] BATCH_CONTROL_RECORD_MAGIC = bytes("WRITE BATCH");
078    public static final int BATCH_CONTROL_RECORD_SIZE = RECORD_HEAD_SPACE + BATCH_CONTROL_RECORD_MAGIC.length + 4 + 8;
079    public static final byte[] BATCH_CONTROL_RECORD_HEADER = createBatchControlRecordHeader();
080    public static final byte[] EMPTY_BATCH_CONTROL_RECORD = createEmptyBatchControlRecordHeader();
081    public static final int EOF_INT = ByteBuffer.wrap(new byte[]{'-', 'q', 'M', 'a'}).getInt();
082    public static final byte EOF_EOT = '4';
083    public static final byte[] EOF_RECORD = createEofBatchAndLocationRecord();
084
085    private ScheduledExecutorService scheduler;
086
087    // tackle corruption when checksum is disabled or corrupt with zeros, minimize data loss
088    public void corruptRecoveryLocation(Location recoveryPosition) throws IOException {
089        DataFile dataFile = getDataFile(recoveryPosition);
090        // with corruption on recovery we have no faith in the content - slip to the next batch record or eof
091        DataFileAccessor reader = accessorPool.openDataFileAccessor(dataFile);
092        try {
093            int nextOffset = findNextBatchRecord(reader, recoveryPosition.getOffset() + 1);
094            Sequence sequence = new Sequence(recoveryPosition.getOffset(), nextOffset >= 0 ? nextOffset - 1 : dataFile.getLength() - 1);
095            LOG.warn("Corrupt journal records found in '{}' between offsets: {}", dataFile.getFile(), sequence);
096
097            // skip corruption on getNextLocation
098            recoveryPosition.setOffset((int) sequence.getLast() + 1);
099            recoveryPosition.setSize(-1);
100
101            dataFile.corruptedBlocks.add(sequence);
102        } catch (IOException e) {
103        } finally {
104            accessorPool.closeDataFileAccessor(reader);
105        }
106    }
107
108    public DataFileAccessorPool getAccessorPool() {
109        return accessorPool;
110    }
111
112    public void allowIOResumption() {
113        if (appender instanceof DataFileAppender) {
114            DataFileAppender dataFileAppender = (DataFileAppender)appender;
115            dataFileAppender.shutdown = false;
116        }
117    }
118
119    public enum PreallocationStrategy {
120        SPARSE_FILE,
121        OS_KERNEL_COPY,
122        ZEROS,
123        CHUNKED_ZEROS;
124    }
125
126    public enum PreallocationScope {
127        ENTIRE_JOURNAL,
128        ENTIRE_JOURNAL_ASYNC,
129        NONE;
130    }
131
132    public enum JournalDiskSyncStrategy {
133        ALWAYS,
134        PERIODIC,
135        NEVER;
136    }
137
138    private static byte[] createBatchControlRecordHeader() {
139        try (DataByteArrayOutputStream os = new DataByteArrayOutputStream();) {
140            os.writeInt(BATCH_CONTROL_RECORD_SIZE);
141            os.writeByte(BATCH_CONTROL_RECORD_TYPE);
142            os.write(BATCH_CONTROL_RECORD_MAGIC);
143            ByteSequence sequence = os.toByteSequence();
144            sequence.compact();
145            return sequence.getData();
146        } catch (IOException e) {
147            throw new RuntimeException("Could not create batch control record header.", e);
148        }
149    }
150
151    private static byte[] createEmptyBatchControlRecordHeader() {
152        try (DataByteArrayOutputStream os = new DataByteArrayOutputStream();) {
153            os.writeInt(BATCH_CONTROL_RECORD_SIZE);
154            os.writeByte(BATCH_CONTROL_RECORD_TYPE);
155            os.write(BATCH_CONTROL_RECORD_MAGIC);
156            os.writeInt(0);
157            os.writeLong(0l);
158            ByteSequence sequence = os.toByteSequence();
159            sequence.compact();
160            return sequence.getData();
161        } catch (IOException e) {
162            throw new RuntimeException("Could not create empty batch control record header.", e);
163        }
164    }
165
166    private static byte[] createEofBatchAndLocationRecord() {
167        try (DataByteArrayOutputStream os = new DataByteArrayOutputStream();) {
168            os.writeInt(EOF_INT);
169            os.writeByte(EOF_EOT);
170            ByteSequence sequence = os.toByteSequence();
171            sequence.compact();
172            return sequence.getData();
173        } catch (IOException e) {
174            throw new RuntimeException("Could not create eof header.", e);
175        }
176    }
177
178    public static final String DEFAULT_DIRECTORY = ".";
179    public static final String DEFAULT_ARCHIVE_DIRECTORY = "data-archive";
180    public static final String DEFAULT_FILE_PREFIX = "db-";
181    public static final String DEFAULT_FILE_SUFFIX = ".log";
182    public static final int DEFAULT_MAX_FILE_LENGTH = 1024 * 1024 * 32;
183    public static final int DEFAULT_CLEANUP_INTERVAL = 1000 * 30;
184    public static final int DEFAULT_MAX_WRITE_BATCH_SIZE = 1024 * 1024 * 4;
185
186    private static final Logger LOG = LoggerFactory.getLogger(Journal.class);
187
188    protected final Map<WriteKey, WriteCommand> inflightWrites = new ConcurrentHashMap<WriteKey, WriteCommand>();
189
190    protected File directory = new File(DEFAULT_DIRECTORY);
191    protected File directoryArchive;
192    private boolean directoryArchiveOverridden = false;
193
194    protected String filePrefix = DEFAULT_FILE_PREFIX;
195    protected String fileSuffix = DEFAULT_FILE_SUFFIX;
196    protected boolean started;
197
198    protected int maxFileLength = DEFAULT_MAX_FILE_LENGTH;
199    protected int writeBatchSize = DEFAULT_MAX_WRITE_BATCH_SIZE;
200
201    protected FileAppender appender;
202    protected DataFileAccessorPool accessorPool;
203
204    protected Map<Integer, DataFile> fileMap = new HashMap<Integer, DataFile>();
205    protected Map<File, DataFile> fileByFileMap = new LinkedHashMap<File, DataFile>();
206    protected LinkedNodeList<DataFile> dataFiles = new LinkedNodeList<DataFile>();
207
208    protected final AtomicReference<Location> lastAppendLocation = new AtomicReference<Location>();
209    protected ScheduledFuture cleanupTask;
210    protected AtomicLong totalLength = new AtomicLong();
211    protected boolean archiveDataLogs;
212    private ReplicationTarget replicationTarget;
213    protected boolean checksum;
214    protected boolean checkForCorruptionOnStartup;
215    protected boolean enableAsyncDiskSync = true;
216    private int nextDataFileId = 1;
217    private Object dataFileIdLock = new Object();
218    private final AtomicReference<DataFile> currentDataFile = new AtomicReference<>(null);
219    private volatile DataFile nextDataFile;
220
221    protected PreallocationScope preallocationScope = PreallocationScope.ENTIRE_JOURNAL;
222    protected PreallocationStrategy preallocationStrategy = PreallocationStrategy.SPARSE_FILE;
223    private File osKernelCopyTemplateFile = null;
224    private ByteBuffer preAllocateDirectBuffer = null;
225
226    protected JournalDiskSyncStrategy journalDiskSyncStrategy = JournalDiskSyncStrategy.ALWAYS;
227
228    public interface DataFileRemovedListener {
229        void fileRemoved(DataFile datafile);
230    }
231
232    private DataFileRemovedListener dataFileRemovedListener;
233
234    public synchronized void start() throws IOException {
235        if (started) {
236            return;
237        }
238
239        long start = System.currentTimeMillis();
240        accessorPool = new DataFileAccessorPool(this);
241        started = true;
242
243        appender = callerBufferAppender ? new CallerBufferingDataFileAppender(this) : new DataFileAppender(this);
244
245        File[] files = directory.listFiles(new FilenameFilter() {
246            @Override
247            public boolean accept(File dir, String n) {
248                return dir.equals(directory) && n.startsWith(filePrefix) && n.endsWith(fileSuffix);
249            }
250        });
251
252        if (files != null) {
253            for (File file : files) {
254                try {
255                    String n = file.getName();
256                    String numStr = n.substring(filePrefix.length(), n.length()-fileSuffix.length());
257                    int num = Integer.parseInt(numStr);
258                    DataFile dataFile = new DataFile(file, num);
259                    fileMap.put(dataFile.getDataFileId(), dataFile);
260                    totalLength.addAndGet(dataFile.getLength());
261                } catch (NumberFormatException e) {
262                    // Ignore file that do not match the pattern.
263                }
264            }
265
266            // Sort the list so that we can link the DataFiles together in the
267            // right order.
268            LinkedList<DataFile> l = new LinkedList<>(fileMap.values());
269            Collections.sort(l);
270            for (DataFile df : l) {
271                if (df.getLength() == 0) {
272                    // possibly the result of a previous failed write
273                    LOG.info("ignoring zero length, partially initialised journal data file: " + df);
274                    continue;
275                } else if (l.getLast().equals(df) && isUnusedPreallocated(df)) {
276                    continue;
277                }
278                dataFiles.addLast(df);
279                fileByFileMap.put(df.getFile(), df);
280
281                if( isCheckForCorruptionOnStartup() ) {
282                    lastAppendLocation.set(recoveryCheck(df));
283                }
284            }
285        }
286
287        if (preallocationScope != PreallocationScope.NONE) {
288            switch (preallocationStrategy) {
289                case SPARSE_FILE:
290                    break;
291                case OS_KERNEL_COPY: {
292                    osKernelCopyTemplateFile = createJournalTemplateFile();
293                }
294                break;
295                case CHUNKED_ZEROS: {
296                    preAllocateDirectBuffer = allocateDirectBuffer(PREALLOC_CHUNK_SIZE);
297                }
298                break;
299                case ZEROS: {
300                    preAllocateDirectBuffer = allocateDirectBuffer(getMaxFileLength());
301                }
302                break;
303            }
304        }
305        scheduler = Executors.newScheduledThreadPool(1, new ThreadFactory() {
306            @Override
307            public Thread newThread(Runnable r) {
308                Thread schedulerThread = new Thread(r);
309                schedulerThread.setName("ActiveMQ Journal Scheduled executor");
310                schedulerThread.setDaemon(true);
311                return schedulerThread;
312            }
313        });
314
315        // init current write file
316        if (dataFiles.isEmpty()) {
317            nextDataFileId = 1;
318            rotateWriteFile();
319        } else {
320            currentDataFile.set(dataFiles.getTail());
321            nextDataFileId = currentDataFile.get().dataFileId + 1;
322        }
323
324        if( lastAppendLocation.get()==null ) {
325            DataFile df = dataFiles.getTail();
326            lastAppendLocation.set(recoveryCheck(df));
327        }
328
329        // ensure we don't report unused space of last journal file in size metric
330        int lastFileLength = dataFiles.getTail().getLength();
331        if (totalLength.get() > lastFileLength && lastAppendLocation.get().getOffset() > 0) {
332            totalLength.addAndGet(lastAppendLocation.get().getOffset() - lastFileLength);
333        }
334
335        cleanupTask = scheduler.scheduleAtFixedRate(new Runnable() {
336            @Override
337            public void run() {
338                cleanup();
339            }
340        }, DEFAULT_CLEANUP_INTERVAL, DEFAULT_CLEANUP_INTERVAL, TimeUnit.MILLISECONDS);
341
342        long end = System.currentTimeMillis();
343        LOG.trace("Startup took: "+(end-start)+" ms");
344    }
345
346    private ByteBuffer allocateDirectBuffer(int size) {
347        ByteBuffer buffer = ByteBuffer.allocateDirect(size);
348        buffer.put(EOF_RECORD);
349        return buffer;
350    }
351
352    public void preallocateEntireJournalDataFile(RecoverableRandomAccessFile file) {
353
354        if (PreallocationScope.NONE != preallocationScope) {
355
356            try {
357                if (PreallocationStrategy.OS_KERNEL_COPY == preallocationStrategy) {
358                    doPreallocationKernelCopy(file);
359                } else if (PreallocationStrategy.ZEROS == preallocationStrategy) {
360                    doPreallocationZeros(file);
361                } else if (PreallocationStrategy.CHUNKED_ZEROS == preallocationStrategy) {
362                    doPreallocationChunkedZeros(file);
363                } else {
364                    doPreallocationSparseFile(file);
365                }
366            } catch (Throwable continueWithNoPrealloc) {
367                // error on preallocation is non fatal, and we don't want to leak the journal handle
368                LOG.error("cound not preallocate journal data file", continueWithNoPrealloc);
369            }
370        }
371    }
372
373    private void doPreallocationSparseFile(RecoverableRandomAccessFile file) {
374        final ByteBuffer journalEof = ByteBuffer.wrap(EOF_RECORD);
375        try {
376            FileChannel channel = file.getChannel();
377            channel.position(0);
378            channel.write(journalEof);
379            channel.position(maxFileLength - 5);
380            journalEof.rewind();
381            channel.write(journalEof);
382            channel.force(false);
383            channel.position(0);
384        } catch (ClosedByInterruptException ignored) {
385            LOG.trace("Could not preallocate journal file with sparse file", ignored);
386        } catch (IOException e) {
387            LOG.error("Could not preallocate journal file with sparse file", e);
388        }
389    }
390
391    private void doPreallocationZeros(RecoverableRandomAccessFile file) {
392        preAllocateDirectBuffer.rewind();
393        try {
394            FileChannel channel = file.getChannel();
395            channel.write(preAllocateDirectBuffer);
396            channel.force(false);
397            channel.position(0);
398        } catch (ClosedByInterruptException ignored) {
399            LOG.trace("Could not preallocate journal file with zeros", ignored);
400        } catch (IOException e) {
401            LOG.error("Could not preallocate journal file with zeros", e);
402        }
403    }
404
405    private void doPreallocationKernelCopy(RecoverableRandomAccessFile file) {
406        try (RandomAccessFile templateRaf = new RandomAccessFile(osKernelCopyTemplateFile, "rw");){
407            templateRaf.getChannel().transferTo(0, getMaxFileLength(), file.getChannel());
408        } catch (ClosedByInterruptException ignored) {
409            LOG.trace("Could not preallocate journal file with kernel copy", ignored);
410        } catch (FileNotFoundException e) {
411            LOG.error("Could not find the template file on disk at " + osKernelCopyTemplateFile.getAbsolutePath(), e);
412        } catch (IOException e) {
413            LOG.error("Could not transfer the template file to journal, transferFile=" + osKernelCopyTemplateFile.getAbsolutePath(), e);
414        }
415    }
416
417    private File createJournalTemplateFile() {
418        String fileName = "db-log.template";
419        File rc = new File(directory, fileName);
420        try (RandomAccessFile templateRaf = new RandomAccessFile(rc, "rw");) {
421            templateRaf.getChannel().write(ByteBuffer.wrap(EOF_RECORD));
422            templateRaf.setLength(maxFileLength);
423            templateRaf.getChannel().force(true);
424        } catch (FileNotFoundException e) {
425            LOG.error("Could not find the template file on disk at " + osKernelCopyTemplateFile.getAbsolutePath(), e);
426        } catch (IOException e) {
427            LOG.error("Could not transfer the template file to journal, transferFile=" + osKernelCopyTemplateFile.getAbsolutePath(), e);
428        }
429        return rc;
430    }
431
432    private void doPreallocationChunkedZeros(RecoverableRandomAccessFile file) {
433        preAllocateDirectBuffer.limit(preAllocateDirectBuffer.capacity());
434        preAllocateDirectBuffer.rewind();
435        try {
436            FileChannel channel = file.getChannel();
437
438            int remLen = maxFileLength;
439            while (remLen > 0) {
440                if (remLen < preAllocateDirectBuffer.remaining()) {
441                    preAllocateDirectBuffer.limit(remLen);
442                }
443                int writeLen = channel.write(preAllocateDirectBuffer);
444                remLen -= writeLen;
445                preAllocateDirectBuffer.rewind();
446            }
447
448            channel.force(false);
449            channel.position(0);
450        } catch (ClosedByInterruptException ignored) {
451            LOG.trace("Could not preallocate journal file with zeros", ignored);
452        } catch (IOException e) {
453            LOG.error("Could not preallocate journal file with zeros! Will continue without preallocation", e);
454        }
455    }
456
457    private static byte[] bytes(String string) {
458        try {
459            return string.getBytes("UTF-8");
460        } catch (UnsupportedEncodingException e) {
461            throw new RuntimeException(e);
462        }
463    }
464
465    public boolean isUnusedPreallocated(DataFile dataFile) throws IOException {
466        int firstBatchRecordSize = -1;
467        if (preallocationScope == PreallocationScope.ENTIRE_JOURNAL_ASYNC) {
468            Location location = new Location();
469            location.setDataFileId(dataFile.getDataFileId());
470            location.setOffset(0);
471
472            DataFileAccessor reader = accessorPool.openDataFileAccessor(dataFile);
473            try {
474                firstBatchRecordSize = checkBatchRecord(reader, location.getOffset());
475            } catch (Exception ignored) {
476            } finally {
477                accessorPool.closeDataFileAccessor(reader);
478            }
479        }
480        return firstBatchRecordSize == 0;
481    }
482
483    protected Location recoveryCheck(DataFile dataFile) throws IOException {
484        Location location = new Location();
485        location.setDataFileId(dataFile.getDataFileId());
486        location.setOffset(0);
487
488        DataFileAccessor reader = accessorPool.openDataFileAccessor(dataFile);
489        try {
490            while (true) {
491                int size = checkBatchRecord(reader, location.getOffset());
492                if (size >= 0 && location.getOffset() + BATCH_CONTROL_RECORD_SIZE + size <= dataFile.getLength()) {
493                    if (size == 0) {
494                        // eof batch record
495                        break;
496                    }
497                    location.setOffset(location.getOffset() + BATCH_CONTROL_RECORD_SIZE + size);
498                } else {
499
500                    // Perhaps it's just some corruption... scan through the
501                    // file to find the next valid batch record. We
502                    // may have subsequent valid batch records.
503                    int nextOffset = findNextBatchRecord(reader, location.getOffset() + 1);
504                    if (nextOffset >= 0) {
505                        Sequence sequence = new Sequence(location.getOffset(), nextOffset - 1);
506                        LOG.warn("Corrupt journal records found in '{}' between offsets: {}", dataFile.getFile(), sequence);
507                        dataFile.corruptedBlocks.add(sequence);
508                        location.setOffset(nextOffset);
509                    } else {
510                        break;
511                    }
512                }
513            }
514
515        } catch (IOException e) {
516        } finally {
517            accessorPool.closeDataFileAccessor(reader);
518        }
519
520        int existingLen = dataFile.getLength();
521        dataFile.setLength(location.getOffset());
522        if (existingLen > dataFile.getLength()) {
523            totalLength.addAndGet(dataFile.getLength() - existingLen);
524        }
525
526        if (!dataFile.corruptedBlocks.isEmpty()) {
527            // Is the end of the data file corrupted?
528            if (dataFile.corruptedBlocks.getTail().getLast() + 1 == location.getOffset()) {
529                dataFile.setLength((int) dataFile.corruptedBlocks.removeLastSequence().getFirst());
530            }
531        }
532
533        return location;
534    }
535
536    private int findNextBatchRecord(DataFileAccessor reader, int offset) throws IOException {
537        ByteSequence header = new ByteSequence(BATCH_CONTROL_RECORD_HEADER);
538        byte data[] = new byte[1024*4];
539        ByteSequence bs = new ByteSequence(data, 0, reader.read(offset, data));
540
541        int pos = 0;
542        while (true) {
543            pos = bs.indexOf(header, pos);
544            if (pos >= 0) {
545                return offset + pos;
546            } else {
547                // need to load the next data chunck in..
548                if (bs.length != data.length) {
549                    // If we had a short read then we were at EOF
550                    return -1;
551                }
552                offset += bs.length - BATCH_CONTROL_RECORD_HEADER.length;
553                bs = new ByteSequence(data, 0, reader.read(offset, data));
554                pos = 0;
555            }
556        }
557    }
558
559    public int checkBatchRecord(DataFileAccessor reader, int offset) throws IOException {
560        byte controlRecord[] = new byte[BATCH_CONTROL_RECORD_SIZE];
561
562        try (DataByteArrayInputStream controlIs = new DataByteArrayInputStream(controlRecord);) {
563
564            reader.readFully(offset, controlRecord);
565
566            // check for journal eof
567            if (Arrays.equals(EOF_RECORD, Arrays.copyOfRange(controlRecord, 0, EOF_RECORD.length))) {
568                // eof batch
569                return 0;
570            }
571
572            // Assert that it's a batch record.
573            for (int i = 0; i < BATCH_CONTROL_RECORD_HEADER.length; i++) {
574                if (controlIs.readByte() != BATCH_CONTROL_RECORD_HEADER[i]) {
575                    return -1;
576                }
577            }
578
579            int size = controlIs.readInt();
580            if (size < 0 || size > Integer.MAX_VALUE - (BATCH_CONTROL_RECORD_SIZE + EOF_RECORD.length)) {
581                return -1;
582            }
583
584            if (isChecksum()) {
585
586                long expectedChecksum = controlIs.readLong();
587                if (expectedChecksum == 0) {
588                    // Checksuming was not enabled when the record was stored.
589                    // we can't validate the record :(
590                    return size;
591                }
592
593                byte data[] = new byte[size];
594                reader.readFully(offset + BATCH_CONTROL_RECORD_SIZE, data);
595
596                Checksum checksum = new Adler32();
597                checksum.update(data, 0, data.length);
598
599                if (expectedChecksum != checksum.getValue()) {
600                    return -1;
601                }
602            }
603            return size;
604        }
605    }
606
607    void addToTotalLength(int size) {
608        totalLength.addAndGet(size);
609    }
610
611    public long length() {
612        return totalLength.get();
613    }
614
615    private void rotateWriteFile() throws IOException {
616       synchronized (dataFileIdLock) {
617            DataFile dataFile = nextDataFile;
618            if (dataFile == null) {
619                dataFile = newDataFile();
620            }
621            synchronized (currentDataFile) {
622                fileMap.put(dataFile.getDataFileId(), dataFile);
623                fileByFileMap.put(dataFile.getFile(), dataFile);
624                dataFiles.addLast(dataFile);
625                currentDataFile.set(dataFile);
626            }
627            nextDataFile = null;
628        }
629        if (PreallocationScope.ENTIRE_JOURNAL_ASYNC == preallocationScope) {
630            preAllocateNextDataFileFuture = scheduler.submit(preAllocateNextDataFileTask);
631        }
632    }
633
634    private Runnable preAllocateNextDataFileTask = new Runnable() {
635        @Override
636        public void run() {
637            if (nextDataFile == null) {
638                synchronized (dataFileIdLock){
639                    try {
640                        nextDataFile = newDataFile();
641                    } catch (IOException e) {
642                        LOG.warn("Failed to proactively allocate data file", e);
643                    }
644                }
645            }
646        }
647    };
648
649    private volatile Future preAllocateNextDataFileFuture;
650
651    private DataFile newDataFile() throws IOException {
652        int nextNum = nextDataFileId++;
653        File file = getFile(nextNum);
654        DataFile nextWriteFile = new DataFile(file, nextNum);
655        preallocateEntireJournalDataFile(nextWriteFile.appendRandomAccessFile());
656        return nextWriteFile;
657    }
658
659
660    public DataFile reserveDataFile() {
661        synchronized (dataFileIdLock) {
662            int nextNum = nextDataFileId++;
663            File file = getFile(nextNum);
664            DataFile reservedDataFile = new DataFile(file, nextNum);
665            synchronized (currentDataFile) {
666                fileMap.put(reservedDataFile.getDataFileId(), reservedDataFile);
667                fileByFileMap.put(file, reservedDataFile);
668                if (dataFiles.isEmpty()) {
669                    dataFiles.addLast(reservedDataFile);
670                } else {
671                    dataFiles.getTail().linkBefore(reservedDataFile);
672                }
673            }
674            return reservedDataFile;
675        }
676    }
677
678    public File getFile(int nextNum) {
679        String fileName = filePrefix + nextNum + fileSuffix;
680        File file = new File(directory, fileName);
681        return file;
682    }
683
684    DataFile getDataFile(Location item) throws IOException {
685        Integer key = Integer.valueOf(item.getDataFileId());
686        DataFile dataFile = null;
687        synchronized (currentDataFile) {
688            dataFile = fileMap.get(key);
689        }
690        if (dataFile == null) {
691            LOG.error("Looking for key " + key + " but not found in fileMap: " + fileMap);
692            throw new IOException("Could not locate data file " + getFile(item.getDataFileId()));
693        }
694        return dataFile;
695    }
696
697    public void close() throws IOException {
698        synchronized (this) {
699            if (!started) {
700                return;
701            }
702            cleanupTask.cancel(true);
703            if (preAllocateNextDataFileFuture != null) {
704                preAllocateNextDataFileFuture.cancel(true);
705            }
706            ThreadPoolUtils.shutdownGraceful(scheduler, 4000);
707            accessorPool.close();
708        }
709        // the appender can be calling back to to the journal blocking a close AMQ-5620
710        appender.close();
711        synchronized (currentDataFile) {
712            fileMap.clear();
713            fileByFileMap.clear();
714            dataFiles.clear();
715            lastAppendLocation.set(null);
716            started = false;
717        }
718    }
719
720    public synchronized void cleanup() {
721        if (accessorPool != null) {
722            accessorPool.disposeUnused();
723        }
724    }
725
726    public synchronized boolean delete() throws IOException {
727
728        // Close all open file handles...
729        appender.close();
730        accessorPool.close();
731
732        boolean result = true;
733        for (Iterator<DataFile> i = fileMap.values().iterator(); i.hasNext();) {
734            DataFile dataFile = i.next();
735            result &= dataFile.delete();
736        }
737
738        if (preAllocateNextDataFileFuture != null) {
739            preAllocateNextDataFileFuture.cancel(true);
740        }
741        synchronized (dataFileIdLock) {
742            if (nextDataFile != null) {
743                nextDataFile.delete();
744                nextDataFile = null;
745            }
746        }
747
748        totalLength.set(0);
749        synchronized (currentDataFile) {
750            fileMap.clear();
751            fileByFileMap.clear();
752            lastAppendLocation.set(null);
753            dataFiles = new LinkedNodeList<DataFile>();
754        }
755        // reopen open file handles...
756        accessorPool = new DataFileAccessorPool(this);
757        appender = new DataFileAppender(this);
758        return result;
759    }
760
761    public void removeDataFiles(Set<Integer> files) throws IOException {
762        for (Integer key : files) {
763            // Can't remove the data file (or subsequent files) that is currently being written to.
764            if (key >= lastAppendLocation.get().getDataFileId()) {
765                continue;
766            }
767            DataFile dataFile = null;
768            synchronized (currentDataFile) {
769                dataFile = fileMap.remove(key);
770                if (dataFile != null) {
771                    fileByFileMap.remove(dataFile.getFile());
772                    dataFile.unlink();
773                }
774            }
775            if (dataFile != null) {
776                forceRemoveDataFile(dataFile);
777            }
778        }
779    }
780
781    private void forceRemoveDataFile(DataFile dataFile) throws IOException {
782        accessorPool.disposeDataFileAccessors(dataFile);
783        totalLength.addAndGet(-dataFile.getLength());
784        if (archiveDataLogs) {
785            File directoryArchive = getDirectoryArchive();
786            if (directoryArchive.exists()) {
787                LOG.debug("Archive directory exists: {}", directoryArchive);
788            } else {
789                if (directoryArchive.isAbsolute())
790                if (LOG.isDebugEnabled()) {
791                    LOG.debug("Archive directory [{}] does not exist - creating it now",
792                            directoryArchive.getAbsolutePath());
793                }
794                IOHelper.mkdirs(directoryArchive);
795            }
796            LOG.debug("Moving data file {} to {} ", dataFile, directoryArchive.getCanonicalPath());
797            dataFile.move(directoryArchive);
798            LOG.debug("Successfully moved data file");
799        } else {
800            LOG.debug("Deleting data file: {}", dataFile);
801            if (dataFile.delete()) {
802                LOG.debug("Discarded data file: {}", dataFile);
803            } else {
804                LOG.warn("Failed to discard data file : {}", dataFile.getFile());
805            }
806        }
807        if (dataFileRemovedListener != null) {
808            dataFileRemovedListener.fileRemoved(dataFile);
809        }
810    }
811
812    /**
813     * @return the maxFileLength
814     */
815    public int getMaxFileLength() {
816        return maxFileLength;
817    }
818
819    /**
820     * @param maxFileLength the maxFileLength to set
821     */
822    public void setMaxFileLength(int maxFileLength) {
823        this.maxFileLength = maxFileLength;
824    }
825
826    @Override
827    public String toString() {
828        return directory.toString();
829    }
830
831    public Location getNextLocation(Location location) throws IOException, IllegalStateException {
832        return getNextLocation(location, null);
833    }
834
835    public Location getNextLocation(Location location, Location limit) throws IOException, IllegalStateException {
836        Location cur = null;
837        while (true) {
838            if (cur == null) {
839                if (location == null) {
840                    DataFile head = null;
841                    synchronized (currentDataFile) {
842                        head = dataFiles.getHead();
843                    }
844                    if (head == null) {
845                        return null;
846                    }
847                    cur = new Location();
848                    cur.setDataFileId(head.getDataFileId());
849                    cur.setOffset(0);
850                } else {
851                    // Set to the next offset..
852                    if (location.getSize() == -1) {
853                        cur = new Location(location);
854                    } else {
855                        cur = new Location(location);
856                        cur.setOffset(location.getOffset() + location.getSize());
857                    }
858                }
859            } else {
860                cur.setOffset(cur.getOffset() + cur.getSize());
861            }
862
863            DataFile dataFile = getDataFile(cur);
864
865            // Did it go into the next file??
866            if (dataFile.getLength() <= cur.getOffset()) {
867                synchronized (currentDataFile) {
868                    dataFile = dataFile.getNext();
869                }
870                if (dataFile == null) {
871                    return null;
872                } else {
873                    cur.setDataFileId(dataFile.getDataFileId().intValue());
874                    cur.setOffset(0);
875                    if (limit != null && cur.compareTo(limit) >= 0) {
876                        LOG.trace("reached limit: {} at: {}", limit, cur);
877                        return null;
878                    }
879                }
880            }
881
882            // Load in location size and type.
883            DataFileAccessor reader = accessorPool.openDataFileAccessor(dataFile);
884            try {
885                reader.readLocationDetails(cur);
886            } catch (EOFException eof) {
887                LOG.trace("EOF on next: " + location + ", cur: " + cur);
888                throw eof;
889            } finally {
890                accessorPool.closeDataFileAccessor(reader);
891            }
892
893            Sequence corruptedRange = dataFile.corruptedBlocks.get(cur.getOffset());
894            if (corruptedRange != null) {
895                // skip corruption
896                cur.setSize((int) corruptedRange.range());
897            } else if (cur.getSize() == EOF_INT && cur.getType() == EOF_EOT ||
898                    (cur.getType() == 0 && cur.getSize() == 0)) {
899                // eof - jump to next datafile
900                // EOF_INT and EOF_EOT replace 0,0 - we need to react to both for
901                // replay of existing journals
902                // possibly journal is larger than maxFileLength after config change
903                cur.setSize(EOF_RECORD.length);
904                cur.setOffset(Math.max(maxFileLength, dataFile.getLength()));
905            } else if (cur.getType() == USER_RECORD_TYPE) {
906                // Only return user records.
907                return cur;
908            }
909        }
910    }
911
912    public ByteSequence read(Location location) throws IOException, IllegalStateException {
913        DataFile dataFile = getDataFile(location);
914        DataFileAccessor reader = accessorPool.openDataFileAccessor(dataFile);
915        ByteSequence rc = null;
916        try {
917            rc = reader.readRecord(location);
918        } finally {
919            accessorPool.closeDataFileAccessor(reader);
920        }
921        return rc;
922    }
923
924    public Location write(ByteSequence data, boolean sync) throws IOException, IllegalStateException {
925        Location loc = appender.storeItem(data, Location.USER_TYPE, sync);
926        return loc;
927    }
928
929    public Location write(ByteSequence data, Runnable onComplete) throws IOException, IllegalStateException {
930        Location loc = appender.storeItem(data, Location.USER_TYPE, onComplete);
931        return loc;
932    }
933
934    public void update(Location location, ByteSequence data, boolean sync) throws IOException {
935        DataFile dataFile = getDataFile(location);
936        DataFileAccessor updater = accessorPool.openDataFileAccessor(dataFile);
937        try {
938            updater.updateRecord(location, data, sync);
939        } finally {
940            accessorPool.closeDataFileAccessor(updater);
941        }
942    }
943
944    public PreallocationStrategy getPreallocationStrategy() {
945        return preallocationStrategy;
946    }
947
948    public void setPreallocationStrategy(PreallocationStrategy preallocationStrategy) {
949        this.preallocationStrategy = preallocationStrategy;
950    }
951
952    public PreallocationScope getPreallocationScope() {
953        return preallocationScope;
954    }
955
956    public void setPreallocationScope(PreallocationScope preallocationScope) {
957        this.preallocationScope = preallocationScope;
958    }
959
960    public File getDirectory() {
961        return directory;
962    }
963
964    public void setDirectory(File directory) {
965        this.directory = directory;
966    }
967
968    public String getFilePrefix() {
969        return filePrefix;
970    }
971
972    public void setFilePrefix(String filePrefix) {
973        this.filePrefix = filePrefix;
974    }
975
976    public Map<WriteKey, WriteCommand> getInflightWrites() {
977        return inflightWrites;
978    }
979
980    public Location getLastAppendLocation() {
981        return lastAppendLocation.get();
982    }
983
984    public void setLastAppendLocation(Location lastSyncedLocation) {
985        this.lastAppendLocation.set(lastSyncedLocation);
986    }
987
988    public File getDirectoryArchive() {
989        if (!directoryArchiveOverridden && (directoryArchive == null)) {
990            // create the directoryArchive relative to the journal location
991            directoryArchive = new File(directory.getAbsolutePath() +
992                    File.separator + DEFAULT_ARCHIVE_DIRECTORY);
993        }
994        return directoryArchive;
995    }
996
997    public void setDirectoryArchive(File directoryArchive) {
998        directoryArchiveOverridden = true;
999        this.directoryArchive = directoryArchive;
1000    }
1001
1002    public boolean isArchiveDataLogs() {
1003        return archiveDataLogs;
1004    }
1005
1006    public void setArchiveDataLogs(boolean archiveDataLogs) {
1007        this.archiveDataLogs = archiveDataLogs;
1008    }
1009
1010    public DataFile getDataFileById(int dataFileId) {
1011        synchronized (currentDataFile) {
1012            return fileMap.get(Integer.valueOf(dataFileId));
1013        }
1014    }
1015
1016    public DataFile getCurrentDataFile(int capacity) throws IOException {
1017        //First just acquire the currentDataFile lock and return if no rotation needed
1018        synchronized (currentDataFile) {
1019            if (currentDataFile.get().getLength() + capacity < maxFileLength) {
1020                return currentDataFile.get();
1021            }
1022        }
1023
1024        //AMQ-6545 - if rotation needed, acquire dataFileIdLock first to prevent deadlocks
1025        //then re-check if rotation is needed
1026        synchronized (dataFileIdLock) {
1027            synchronized (currentDataFile) {
1028                if (currentDataFile.get().getLength() + capacity >= maxFileLength) {
1029                    rotateWriteFile();
1030                }
1031                return currentDataFile.get();
1032            }
1033        }
1034    }
1035
1036    public Integer getCurrentDataFileId() {
1037        synchronized (currentDataFile) {
1038            return currentDataFile.get().getDataFileId();
1039        }
1040    }
1041
1042    /**
1043     * Get a set of files - only valid after start()
1044     *
1045     * @return files currently being used
1046     */
1047    public Set<File> getFiles() {
1048        synchronized (currentDataFile) {
1049            return fileByFileMap.keySet();
1050        }
1051    }
1052
1053    public Map<Integer, DataFile> getFileMap() {
1054        synchronized (currentDataFile) {
1055            return new TreeMap<Integer, DataFile>(fileMap);
1056        }
1057    }
1058
1059    public long getDiskSize() {
1060        return totalLength.get();
1061    }
1062
1063    public void setReplicationTarget(ReplicationTarget replicationTarget) {
1064        this.replicationTarget = replicationTarget;
1065    }
1066
1067    public ReplicationTarget getReplicationTarget() {
1068        return replicationTarget;
1069    }
1070
1071    public String getFileSuffix() {
1072        return fileSuffix;
1073    }
1074
1075    public void setFileSuffix(String fileSuffix) {
1076        this.fileSuffix = fileSuffix;
1077    }
1078
1079    public boolean isChecksum() {
1080        return checksum;
1081    }
1082
1083    public void setChecksum(boolean checksumWrites) {
1084        this.checksum = checksumWrites;
1085    }
1086
1087    public boolean isCheckForCorruptionOnStartup() {
1088        return checkForCorruptionOnStartup;
1089    }
1090
1091    public void setCheckForCorruptionOnStartup(boolean checkForCorruptionOnStartup) {
1092        this.checkForCorruptionOnStartup = checkForCorruptionOnStartup;
1093    }
1094
1095    public void setWriteBatchSize(int writeBatchSize) {
1096        this.writeBatchSize = writeBatchSize;
1097    }
1098
1099    public int getWriteBatchSize() {
1100        return writeBatchSize;
1101    }
1102
1103    public void setSizeAccumulator(AtomicLong storeSizeAccumulator) {
1104       this.totalLength = storeSizeAccumulator;
1105    }
1106
1107    public void setEnableAsyncDiskSync(boolean val) {
1108        this.enableAsyncDiskSync = val;
1109    }
1110
1111    public boolean isEnableAsyncDiskSync() {
1112        return enableAsyncDiskSync;
1113    }
1114
1115    public JournalDiskSyncStrategy getJournalDiskSyncStrategy() {
1116        return journalDiskSyncStrategy;
1117    }
1118
1119    public void setJournalDiskSyncStrategy(JournalDiskSyncStrategy journalDiskSyncStrategy) {
1120        this.journalDiskSyncStrategy = journalDiskSyncStrategy;
1121    }
1122
1123    public boolean isJournalDiskSyncPeriodic() {
1124        return JournalDiskSyncStrategy.PERIODIC.equals(journalDiskSyncStrategy);
1125    }
1126
1127    public void setDataFileRemovedListener(DataFileRemovedListener dataFileRemovedListener) {
1128        this.dataFileRemovedListener = dataFileRemovedListener;
1129    }
1130
1131    public static class WriteCommand extends LinkedNode<WriteCommand> {
1132        public final Location location;
1133        public final ByteSequence data;
1134        final boolean sync;
1135        public final Runnable onComplete;
1136
1137        public WriteCommand(Location location, ByteSequence data, boolean sync) {
1138            this.location = location;
1139            this.data = data;
1140            this.sync = sync;
1141            this.onComplete = null;
1142        }
1143
1144        public WriteCommand(Location location, ByteSequence data, Runnable onComplete) {
1145            this.location = location;
1146            this.data = data;
1147            this.onComplete = onComplete;
1148            this.sync = false;
1149        }
1150    }
1151
1152    public static class WriteKey {
1153        private final int file;
1154        private final long offset;
1155        private final int hash;
1156
1157        public WriteKey(Location item) {
1158            file = item.getDataFileId();
1159            offset = item.getOffset();
1160            // TODO: see if we can build a better hash
1161            hash = (int)(file ^ offset);
1162        }
1163
1164        @Override
1165        public int hashCode() {
1166            return hash;
1167        }
1168
1169        @Override
1170        public boolean equals(Object obj) {
1171            if (obj instanceof WriteKey) {
1172                WriteKey di = (WriteKey)obj;
1173                return di.file == file && di.offset == offset;
1174            }
1175            return false;
1176        }
1177    }
1178}