f4c7ec52c3c53f7d739eff7fa30da1945010f8d1
[controller.git] / atomix-storage / src / main / java / io / atomix / storage / journal / FileChannelJournalSegmentWriter.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
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 FileChannelJournalSegmentWriter<E> extends JournalSegmentWriter<E> {
46   private static final ByteBuffer ZERO_ENTRY_HEADER = ByteBuffer.wrap(new byte[ENTRY_HEADER_BYTES]);
47
48   private final ByteBuffer memory;
49   private Indexed<E> lastEntry;
50   private long currentPosition;
51
52   FileChannelJournalSegmentWriter(
53       FileChannel channel,
54       JournalSegment<E> segment,
55       int maxEntrySize,
56       JournalIndex index,
57       JournalSerdes namespace) {
58     super(channel, segment, maxEntrySize, index, namespace);
59     memory = allocMemory(maxEntrySize);
60     reset(0);
61   }
62
63   FileChannelJournalSegmentWriter(JournalSegmentWriter<E> previous, int position) {
64     super(previous);
65     memory = allocMemory(maxEntrySize);
66     lastEntry = previous.getLastEntry();
67     currentPosition = position;
68   }
69
70   private static ByteBuffer allocMemory(int maxEntrySize) {
71     final var buf = ByteBuffer.allocate((maxEntrySize + ENTRY_HEADER_BYTES) * 2);
72     buf.limit(0);
73     return buf;
74   }
75
76   @Override
77   MappedByteBuffer buffer() {
78     return null;
79   }
80
81   @Override
82   MappedJournalSegmentWriter<E> toMapped() {
83     return new MappedJournalSegmentWriter<>(this, (int) currentPosition);
84   }
85
86   @Override
87   FileChannelJournalSegmentWriter<E> toFileChannel() {
88     return this;
89   }
90
91   @Override
92   void reset(long index) {
93     long nextIndex = firstIndex;
94
95     // Clear the buffer indexes.
96     currentPosition = JournalSegmentDescriptor.BYTES;
97
98     try {
99       // Clear memory buffer and read fist chunk
100       channel.read(memory.clear(), JournalSegmentDescriptor.BYTES);
101       memory.flip();
102
103       // Read the entry length.
104       int length = memory.getInt();
105
106       // If the length is non-zero, read the entry.
107       while (0 < length && length <= maxEntrySize && (index == 0 || nextIndex <= index)) {
108
109         // Read the checksum of the entry.
110         final long checksum = memory.getInt() & 0xFFFFFFFFL;
111
112         // Slice off the entry's bytes
113         final ByteBuffer entryBytes = memory.slice();
114         entryBytes.limit(length);
115
116         // Compute the checksum for the entry bytes.
117         final CRC32 crc32 = new CRC32();
118         crc32.update(entryBytes);
119
120         // If the stored checksum does not equal the computed checksum, do not proceed further
121         if (checksum != crc32.getValue()) {
122           break;
123         }
124
125         entryBytes.rewind();
126         final E entry = namespace.deserialize(entryBytes);
127         lastEntry = new Indexed<>(nextIndex, entry, length);
128         this.index.index(nextIndex, (int) currentPosition);
129         nextIndex++;
130
131         // Update the current position for indexing.
132         currentPosition = currentPosition + ENTRY_HEADER_BYTES + length;
133         memory.position(memory.position() + length);
134
135         // Read more bytes from the segment if necessary.
136         if (memory.remaining() < maxEntrySize) {
137           channel.read(memory.compact());
138           memory.flip();
139         }
140
141         length = memory.getInt();
142       }
143     } catch (BufferUnderflowException e) {
144       // No-op, position is only updated on success
145     } catch (IOException e) {
146       throw new StorageException(e);
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     try {
163       namespace.serialize(entry, memory.clear().position(ENTRY_HEADER_BYTES));
164     } catch (KryoException e) {
165       throw new StorageException.TooLarge("Entry size exceeds maximum allowed bytes (" + maxEntrySize + ")");
166     }
167     memory.flip();
168
169     final int length = memory.limit() - ENTRY_HEADER_BYTES;
170
171     // Ensure there's enough space left in the buffer to store the entry.
172     if (maxSegmentSize - currentPosition < length + ENTRY_HEADER_BYTES) {
173       throw new BufferOverflowException();
174     }
175
176     // If the entry length exceeds the maximum entry size then throw an exception.
177     if (length > maxEntrySize) {
178       throw new StorageException.TooLarge("Entry size " + length + " exceeds maximum allowed bytes (" + maxEntrySize + ")");
179     }
180
181     // Compute the checksum for the entry.
182     final CRC32 crc32 = new CRC32();
183     crc32.update(memory.array(), ENTRY_HEADER_BYTES, memory.limit() - ENTRY_HEADER_BYTES);
184     final long checksum = crc32.getValue();
185
186     // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
187     memory.putInt(0, length).putInt(Integer.BYTES, (int) checksum);
188     try {
189       channel.write(memory, currentPosition);
190     } catch (IOException e) {
191       throw new StorageException(e);
192     }
193
194     // Update the last entry with the correct index/term/length.
195     Indexed<E> indexedEntry = new Indexed<>(index, entry, length);
196     this.lastEntry = indexedEntry;
197     this.index.index(index, (int) currentPosition);
198
199     currentPosition = currentPosition + ENTRY_HEADER_BYTES + length;
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     try {
217       if (index < firstIndex) {
218         // Reset the writer to the first entry.
219         currentPosition = JournalSegmentDescriptor.BYTES;
220       } else {
221         // Reset the writer to the given index.
222         reset(index);
223       }
224
225       // Zero the entry header at current channel position.
226       channel.write(ZERO_ENTRY_HEADER.asReadOnlyBuffer(), currentPosition);
227     } catch (IOException e) {
228       throw new StorageException(e);
229     }
230   }
231
232   @Override
233   void flush() {
234     try {
235       if (channel.isOpen()) {
236         channel.force(true);
237       }
238     } catch (IOException e) {
239       throw new StorageException(e);
240     }
241   }
242
243   @Override
244   void close() {
245     flush();
246   }
247 }