446d0ac606eecfd9423a96d3b3dbc731a036567f
[controller.git] / atomix-storage / src / main / java / io / atomix / storage / journal / MappedJournalSegmentWriter.java
1 /*
2  * Copyright 2017-present Open Networking Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package io.atomix.storage.journal;
17
18 import com.esotericsoftware.kryo.KryoException;
19 import io.atomix.storage.journal.index.JournalIndex;
20
21 import java.io.IOException;
22 import java.nio.BufferOverflowException;
23 import java.nio.BufferUnderflowException;
24 import java.nio.ByteBuffer;
25 import java.nio.MappedByteBuffer;
26 import java.nio.channels.FileChannel;
27 import java.util.zip.CRC32;
28 import org.eclipse.jdt.annotation.NonNull;
29
30 /**
31  * Segment writer.
32  * <p>
33  * The format of an entry in the log is as follows:
34  * <ul>
35  * <li>64-bit index</li>
36  * <li>8-bit boolean indicating whether a term change is contained in the entry</li>
37  * <li>64-bit optional term</li>
38  * <li>32-bit signed entry length, including the entry type ID</li>
39  * <li>8-bit signed entry type ID</li>
40  * <li>n-bit entry bytes</li>
41  * </ul>
42  *
43  * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
44  */
45 final class MappedJournalSegmentWriter<E> extends JournalSegmentWriter<E> {
46   private final @NonNull MappedByteBuffer mappedBuffer;
47   private final ByteBuffer buffer;
48
49   private Indexed<E> lastEntry;
50
51   MappedJournalSegmentWriter(
52       FileChannel channel,
53       JournalSegment<E> segment,
54       int maxEntrySize,
55       JournalIndex index,
56       JournalSerdes namespace) {
57     super(channel, segment, maxEntrySize, index, namespace);
58     mappedBuffer = mapBuffer(channel, maxSegmentSize);
59     buffer = mappedBuffer.slice();
60     reset(0);
61   }
62
63   MappedJournalSegmentWriter(JournalSegmentWriter<E> previous, int position) {
64     super(previous);
65     mappedBuffer = mapBuffer(channel, maxSegmentSize);
66     buffer = mappedBuffer.slice().position(position);
67     lastEntry = previous.getLastEntry();
68   }
69
70   private static @NonNull MappedByteBuffer mapBuffer(FileChannel channel, int maxSegmentSize) {
71     try {
72       return channel.map(FileChannel.MapMode.READ_WRITE, 0, maxSegmentSize);
73     } catch (IOException e) {
74       throw new StorageException(e);
75     }
76   }
77
78   @Override
79   @NonNull MappedByteBuffer buffer() {
80     return mappedBuffer;
81   }
82
83   @Override
84   MappedJournalSegmentWriter<E> toMapped() {
85     return this;
86   }
87
88   @Override
89   FileChannelJournalSegmentWriter<E> toFileChannel() {
90     final int position = buffer.position();
91     close();
92     return new FileChannelJournalSegmentWriter<>(this, position);
93   }
94
95   @Override
96   void reset(long index) {
97     long nextIndex = firstIndex;
98
99     // Clear the buffer indexes.
100     buffer.position(JournalSegmentDescriptor.BYTES);
101
102     // Record the current buffer position.
103     int position = buffer.position();
104
105     // Read the entry length.
106     buffer.mark();
107
108     try {
109       int length = buffer.getInt();
110
111       // If the length is non-zero, read the entry.
112       while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
113
114         // Read the checksum of the entry.
115         final long checksum = buffer.getInt() & 0xFFFFFFFFL;
116
117         // Slice off the entry's bytes
118         final ByteBuffer entryBytes = buffer.slice();
119         entryBytes.limit(length);
120
121         // Compute the checksum for the entry bytes.
122         final CRC32 crc32 = new CRC32();
123         crc32.update(entryBytes);
124
125         // If the stored checksum does not equal the computed checksum, do not proceed further
126         if (checksum != crc32.getValue()) {
127           break;
128         }
129
130         entryBytes.rewind();
131         final E entry = namespace.deserialize(entryBytes);
132         lastEntry = new Indexed<>(nextIndex, entry, length);
133         this.index.index(nextIndex, position);
134         nextIndex++;
135
136         // Update the current position for indexing.
137         position = buffer.position() + length;
138         buffer.position(position);
139
140         length = buffer.mark().getInt();
141       }
142
143       // Reset the buffer to the previous mark.
144       buffer.reset();
145     } catch (BufferUnderflowException e) {
146       buffer.reset();
147     }
148   }
149
150   @Override
151   Indexed<E> getLastEntry() {
152     return lastEntry;
153   }
154
155   @Override
156   @SuppressWarnings("unchecked")
157   <T extends E> Indexed<T> append(T entry) {
158     // Store the entry index.
159     final long index = getNextIndex();
160
161     // Serialize the entry.
162     int position = buffer.position();
163     if (position + ENTRY_HEADER_BYTES > buffer.limit()) {
164       throw new BufferOverflowException();
165     }
166
167     buffer.position(position + ENTRY_HEADER_BYTES);
168
169     try {
170       namespace.serialize(entry, buffer);
171     } catch (KryoException e) {
172       throw new BufferOverflowException();
173     }
174
175     final int length = buffer.position() - (position + ENTRY_HEADER_BYTES);
176
177     // If the entry length exceeds the maximum entry size then throw an exception.
178     if (length > maxEntrySize) {
179       // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
180       buffer.position(position);
181       throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
182     }
183
184     // Compute the checksum for the entry.
185     final CRC32 crc32 = new CRC32();
186     buffer.position(position + ENTRY_HEADER_BYTES);
187     ByteBuffer slice = buffer.slice();
188     slice.limit(length);
189     crc32.update(slice);
190     final long checksum = crc32.getValue();
191
192     // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
193     buffer.position(position).putInt(length).putInt((int) checksum).position(position + ENTRY_HEADER_BYTES + length);
194
195     // Update the last entry with the correct index/term/length.
196     Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
197     this.lastEntry = indexedEntry;
198     this.index.index(index, position);
199     return (Indexed<T>) indexedEntry;
200   }
201
202   @Override
203   void truncate(long index) {
204     // If the index is greater than or equal to the last index, skip the truncate.
205     if (index >= getLastIndex()) {
206       return;
207     }
208
209     // Reset the last entry.
210     lastEntry = null;
211
212     // Truncate the index.
213     this.index.truncate(index);
214
215     if (index < firstIndex) {
216       // Reset the writer to the first entry.
217       buffer.position(JournalSegmentDescriptor.BYTES);
218     } else {
219       // Reset the writer to the given index.
220       reset(index);
221     }
222
223     // Zero the entry header at current buffer position.
224     int position = buffer.position();
225     // Note: we issue a single putLong() instead of two putInt()s.
226     buffer.putLong(0).position(position);
227   }
228
229   @Override
230   void flush() {
231     mappedBuffer.force();
232   }
233
234   @Override
235   void close() {
236     flush();
237     try {
238       BufferCleaner.freeBuffer(mappedBuffer);
239     } catch (IOException e) {
240       throw new StorageException(e);
241     }
242   }
243 }