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