f5d4ed9d04a9554de4ec935c6b54b85720158973
[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     try {
59       mappedBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, segment.descriptor().maxSegmentSize());
60     } catch (IOException e) {
61       throw new StorageException(e);
62     }
63     this.buffer = mappedBuffer.slice();
64     reset(0);
65   }
66
67   @Override
68   @NonNull MappedByteBuffer buffer() {
69     return mappedBuffer;
70   }
71
72   @Override
73   MappedJournalSegmentWriter<E> toMapped() {
74     return this;
75   }
76
77   @Override
78   FileChannelJournalSegmentWriter<E> toFileChannel() {
79     close();
80     return new FileChannelJournalSegmentWriter<>(channel, segment, maxEntrySize, index, namespace);
81   }
82
83   @Override
84   public void reset(long index) {
85     long nextIndex = firstIndex;
86
87     // Clear the buffer indexes.
88     buffer.position(JournalSegmentDescriptor.BYTES);
89
90     // Record the current buffer position.
91     int position = buffer.position();
92
93     // Read the entry length.
94     buffer.mark();
95
96     try {
97       int length = buffer.getInt();
98
99       // If the length is non-zero, read the entry.
100       while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
101
102         // Read the checksum of the entry.
103         final long checksum = buffer.getInt() & 0xFFFFFFFFL;
104
105         // Slice off the entry's bytes
106         final ByteBuffer entryBytes = buffer.slice();
107         entryBytes.limit(length);
108
109         // Compute the checksum for the entry bytes.
110         final CRC32 crc32 = new CRC32();
111         crc32.update(entryBytes);
112
113         // If the stored checksum does not equal the computed checksum, do not proceed further
114         if (checksum != crc32.getValue()) {
115           break;
116         }
117
118         entryBytes.rewind();
119         final E entry = namespace.deserialize(entryBytes);
120         lastEntry = new Indexed<>(nextIndex, entry, length);
121         this.index.index(nextIndex, position);
122         nextIndex++;
123
124         // Update the current position for indexing.
125         position = buffer.position() + length;
126         buffer.position(position);
127
128         buffer.mark();
129         length = buffer.getInt();
130       }
131
132       // Reset the buffer to the previous mark.
133       buffer.reset();
134     } catch (BufferUnderflowException e) {
135       buffer.reset();
136     }
137   }
138
139   @Override
140   public long getLastIndex() {
141     return lastEntry != null ? lastEntry.index() : segment.index() - 1;
142   }
143
144   @Override
145   public Indexed<E> getLastEntry() {
146     return lastEntry;
147   }
148
149   @Override
150   public long getNextIndex() {
151     if (lastEntry != null) {
152       return lastEntry.index() + 1;
153     } else {
154       return firstIndex;
155     }
156   }
157
158   @Override
159   public void append(Indexed<E> entry) {
160     final long nextIndex = getNextIndex();
161
162     // If the entry's index is greater than the next index in the segment, skip some entries.
163     if (entry.index() > nextIndex) {
164       throw new IndexOutOfBoundsException("Entry index is not sequential");
165     }
166
167     // If the entry's index is less than the next index, truncate the segment.
168     if (entry.index() < nextIndex) {
169       truncate(entry.index() - 1);
170     }
171     append(entry.entry());
172   }
173
174   @Override
175   @SuppressWarnings("unchecked")
176   public <T extends E> Indexed<T> append(T entry) {
177     // Store the entry index.
178     final long index = getNextIndex();
179
180     // Serialize the entry.
181     int position = buffer.position();
182     if (position + Integer.BYTES + Integer.BYTES > buffer.limit()) {
183       throw new BufferOverflowException();
184     }
185
186     buffer.position(position + Integer.BYTES + Integer.BYTES);
187
188     try {
189       namespace.serialize(entry, buffer);
190     } catch (KryoException e) {
191       throw new BufferOverflowException();
192     }
193
194     final int length = buffer.position() - (position + Integer.BYTES + Integer.BYTES);
195
196     // If the entry length exceeds the maximum entry size then throw an exception.
197     if (length > maxEntrySize) {
198       // Just reset the buffer. There's no need to zero the bytes since we haven't written the length or checksum.
199       buffer.position(position);
200       throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
201     }
202
203     // Compute the checksum for the entry.
204     final CRC32 crc32 = new CRC32();
205     buffer.position(position + Integer.BYTES + Integer.BYTES);
206     ByteBuffer slice = buffer.slice();
207     slice.limit(length);
208     crc32.update(slice);
209     final long checksum = crc32.getValue();
210
211     // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
212     buffer.position(position);
213     buffer.putInt(length);
214     buffer.putInt((int) checksum);
215     buffer.position(position + Integer.BYTES + Integer.BYTES + length);
216
217     // Update the last entry with the correct index/term/length.
218     Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
219     this.lastEntry = indexedEntry;
220     this.index.index(index, position);
221     return (Indexed<T>) indexedEntry;
222   }
223
224
225   @Override
226   public void truncate(long index) {
227     // If the index is greater than or equal to the last index, skip the truncate.
228     if (index >= getLastIndex()) {
229       return;
230     }
231
232     // Reset the last entry.
233     lastEntry = null;
234
235     // Truncate the index.
236     this.index.truncate(index);
237
238     if (index < segment.index()) {
239       // Reset the writer to the first entry.
240       buffer.position(JournalSegmentDescriptor.BYTES);
241     } else {
242       // Reset the writer to the given index.
243       reset(index);
244     }
245
246     // Zero the entry header at current buffer position.
247     int position = buffer.position();
248     // Note: we issue a single putLong() instead of two putInt()s.
249     buffer.putLong(0);
250     buffer.position(position);
251   }
252
253   @Override
254   public void flush() {
255     mappedBuffer.force();
256   }
257
258   @Override
259   public void close() {
260     flush();
261     try {
262       BufferCleaner.freeBuffer(mappedBuffer);
263     } catch (IOException e) {
264       throw new StorageException(e);
265     }
266   }
267 }