2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.datastore.persisted;
10 import static com.google.common.base.Verify.verifyNotNull;
11 import static com.google.common.math.IntMath.ceilingPowerOfTwo;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.annotations.Beta;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.MoreObjects;
17 import com.google.common.io.ByteStreams;
18 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
19 import java.io.DataInput;
20 import java.io.DataInputStream;
21 import java.io.DataOutputStream;
22 import java.io.Externalizable;
23 import java.io.IOException;
24 import java.io.ObjectInput;
25 import java.io.ObjectOutput;
26 import java.io.Serializable;
27 import java.io.StreamCorruptedException;
28 import java.util.AbstractMap.SimpleImmutableEntry;
29 import java.util.Map.Entry;
30 import org.apache.commons.lang3.SerializationUtils;
31 import org.eclipse.jdt.annotation.NonNull;
32 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
33 import org.opendaylight.controller.cluster.datastore.persisted.DataTreeCandidateInputOutput.DataTreeCandidateWithVersion;
34 import org.opendaylight.controller.cluster.io.ChunkedByteArray;
35 import org.opendaylight.controller.cluster.io.ChunkedOutputStream;
36 import org.opendaylight.controller.cluster.raft.messages.IdentifiablePayload;
37 import org.opendaylight.controller.cluster.raft.persisted.LegacySerializable;
38 import org.opendaylight.yangtools.concepts.Either;
39 import org.opendaylight.yangtools.yang.data.api.schema.stream.ReusableStreamReceiver;
40 import org.opendaylight.yangtools.yang.data.impl.schema.ReusableImmutableNormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * Payload persisted when a transaction commits. It contains the transaction identifier and the
47 * {@link DataTreeCandidate}
49 * @author Robert Varga
52 public abstract sealed class CommitTransactionPayload extends IdentifiablePayload<TransactionIdentifier>
53 implements Serializable {
54 private static final Logger LOG = LoggerFactory.getLogger(CommitTransactionPayload.class);
55 private static final long serialVersionUID = 1L;
57 static final int MAX_ARRAY_SIZE = ceilingPowerOfTwo(Integer.getInteger(
58 "org.opendaylight.controller.cluster.datastore.persisted.max-array-size", 256 * 1024));
60 private volatile Entry<TransactionIdentifier, DataTreeCandidateWithVersion> candidate = null;
62 CommitTransactionPayload() {
66 public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
67 final DataTreeCandidate candidate, final PayloadVersion version, final int initialSerializedBufferCapacity)
69 final ChunkedOutputStream cos = new ChunkedOutputStream(initialSerializedBufferCapacity, MAX_ARRAY_SIZE);
70 try (DataOutputStream dos = new DataOutputStream(cos)) {
71 transactionId.writeTo(dos);
72 DataTreeCandidateInputOutput.writeDataTreeCandidate(dos, version, candidate);
75 final Either<byte[], ChunkedByteArray> source = cos.toVariant();
76 LOG.debug("Initial buffer capacity {}, actual serialized size {}", initialSerializedBufferCapacity, cos.size());
77 return source.isFirst() ? new Simple(source.getFirst()) : new Chunked(source.getSecond());
81 public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
82 final DataTreeCandidate candidate, final PayloadVersion version) throws IOException {
83 return create(transactionId, candidate, version, 512);
87 public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
88 final DataTreeCandidate candidate) throws IOException {
89 return create(transactionId, candidate, PayloadVersion.current());
92 public @NonNull Entry<TransactionIdentifier, DataTreeCandidateWithVersion> getCandidate() throws IOException {
93 Entry<TransactionIdentifier, DataTreeCandidateWithVersion> localCandidate = candidate;
94 if (localCandidate == null) {
96 localCandidate = candidate;
97 if (localCandidate == null) {
98 candidate = localCandidate = getCandidate(ReusableImmutableNormalizedNodeStreamWriter.create());
102 return localCandidate;
105 public final @NonNull Entry<TransactionIdentifier, DataTreeCandidateWithVersion> getCandidate(
106 final ReusableStreamReceiver receiver) throws IOException {
107 final DataInput in = newDataInput();
108 return new SimpleImmutableEntry<>(TransactionIdentifier.readFrom(in),
109 DataTreeCandidateInputOutput.readDataTreeCandidate(in, receiver));
113 public TransactionIdentifier getIdentifier() {
115 return getCandidate().getKey();
116 } catch (IOException e) {
117 throw new IllegalStateException("Candidate deserialization failed.", e);
122 public final int serializedSize() {
123 // TODO: this is not entirely accurate as the the byte[] can be chunked by the serialization stream
124 return ProxySizeHolder.PROXY_SIZE + size();
128 * The cached candidate needs to be cleared after it is done applying to the DataTree, otherwise it would be keeping
129 * deserialized in memory which are not needed anymore leading to wasted memory. This lets the payload know that
130 * this was the last time the candidate was needed ant it is safe to be cleared.
132 public Entry<TransactionIdentifier, DataTreeCandidateWithVersion> acquireCandidate() throws IOException {
133 final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> localCandidate = getCandidate();
135 return localCandidate;
139 public final String toString() {
140 final var helper = MoreObjects.toStringHelper(this);
141 final var localCandidate = candidate;
142 if (localCandidate != null) {
143 helper.add("identifier", candidate.getKey());
145 return helper.add("size", size()).toString();
148 abstract void writeBytes(ObjectOutput out) throws IOException;
150 abstract DataInput newDataInput();
153 public final Object writeReplace() {
157 static sealed class Simple extends CommitTransactionPayload {
159 private static final long serialVersionUID = 1L;
161 private final byte[] serialized;
163 Simple(final byte[] serialized) {
164 this.serialized = requireNonNull(serialized);
169 return serialized.length;
173 DataInput newDataInput() {
174 return ByteStreams.newDataInput(serialized);
178 void writeBytes(final ObjectOutput out) throws IOException {
179 out.write(serialized);
183 static sealed class Chunked extends CommitTransactionPayload {
185 private static final long serialVersionUID = 1L;
187 @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "Handled via serialization proxy")
188 private final ChunkedByteArray source;
190 Chunked(final ChunkedByteArray source) {
191 this.source = requireNonNull(source);
195 void writeBytes(final ObjectOutput out) throws IOException {
201 return source.size();
205 DataInput newDataInput() {
206 return new DataInputStream(source.openStream());
210 // Exists to break initialization dependency between CommitTransactionPayload/Simple/Proxy
211 private static final class ProxySizeHolder {
212 static final int PROXY_SIZE = SerializationUtils.serialize(new CT(new Simple(new byte[0]))).length;
214 private ProxySizeHolder() {
219 @Deprecated(since = "7.0.0", forRemoval = true)
220 private static final class SimpleMagnesium extends Simple implements LegacySerializable {
222 private static final long serialVersionUID = 1L;
224 SimpleMagnesium(final byte[] serialized) {
229 @Deprecated(since = "7.0.0", forRemoval = true)
230 private static final class ChunkedMagnesium extends Chunked implements LegacySerializable {
232 private static final long serialVersionUID = 1L;
234 ChunkedMagnesium(final ChunkedByteArray source) {
239 @Deprecated(since = "7.0.0", forRemoval = true)
240 private static final class Proxy implements Externalizable {
242 private static final long serialVersionUID = 1L;
244 private CommitTransactionPayload payload;
246 // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
247 // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
248 @SuppressWarnings("checkstyle:RedundantModifier")
250 // For Externalizable
254 public void writeExternal(final ObjectOutput out) {
255 throw new UnsupportedOperationException();
259 public void readExternal(final ObjectInput in) throws IOException {
260 final int length = in.readInt();
262 throw new StreamCorruptedException("Invalid payload length " + length);
263 } else if (length < MAX_ARRAY_SIZE) {
264 final byte[] serialized = new byte[length];
265 in.readFully(serialized);
266 payload = new SimpleMagnesium(serialized);
268 payload = new ChunkedMagnesium(ChunkedByteArray.readFrom(in, length, MAX_ARRAY_SIZE));
273 private Object readResolve() {
274 return verifyNotNull(payload);