4cbe151a6d8337f6f607ce26e3f6d087d2912148
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / persisted / CommitTransactionPayload.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.datastore.persisted;
9
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;
13
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;
44
45 /**
46  * Payload persisted when a transaction commits. It contains the transaction identifier and the
47  * {@link DataTreeCandidate}
48  *
49  * @author Robert Varga
50  */
51 @Beta
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;
56
57     static final int MAX_ARRAY_SIZE = ceilingPowerOfTwo(Integer.getInteger(
58         "org.opendaylight.controller.cluster.datastore.persisted.max-array-size", 256 * 1024));
59
60     private volatile Entry<TransactionIdentifier, DataTreeCandidateWithVersion> candidate = null;
61
62     CommitTransactionPayload() {
63         // hidden on purpose
64     }
65
66     public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
67             final DataTreeCandidate candidate, final PayloadVersion version, final int initialSerializedBufferCapacity)
68                     throws IOException {
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);
73         }
74
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());
78     }
79
80     @VisibleForTesting
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);
84     }
85
86     @VisibleForTesting
87     public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
88             final DataTreeCandidate candidate) throws IOException {
89         return create(transactionId, candidate, PayloadVersion.current());
90     }
91
92     public @NonNull Entry<TransactionIdentifier, DataTreeCandidateWithVersion> getCandidate() throws IOException {
93         Entry<TransactionIdentifier, DataTreeCandidateWithVersion> localCandidate = candidate;
94         if (localCandidate == null) {
95             synchronized (this) {
96                 localCandidate = candidate;
97                 if (localCandidate == null) {
98                     candidate = localCandidate = getCandidate(ReusableImmutableNormalizedNodeStreamWriter.create());
99                 }
100             }
101         }
102         return localCandidate;
103     }
104
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));
110     }
111
112     @Override
113     public TransactionIdentifier getIdentifier() {
114         try  {
115             return getCandidate().getKey();
116         } catch (IOException e) {
117             throw new IllegalStateException("Candidate deserialization failed.", e);
118         }
119     }
120
121     @Override
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();
125     }
126
127     /**
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.
131      */
132     public Entry<TransactionIdentifier, DataTreeCandidateWithVersion> acquireCandidate() throws IOException {
133         final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> localCandidate = getCandidate();
134         candidate = null;
135         return localCandidate;
136     }
137
138     @Override
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());
144         }
145         return helper.add("size", size()).toString();
146     }
147
148     abstract void writeBytes(ObjectOutput out) throws IOException;
149
150     abstract DataInput newDataInput();
151
152     @Override
153     public final Object writeReplace() {
154         return new CT(this);
155     }
156
157     static sealed class Simple extends CommitTransactionPayload {
158         @java.io.Serial
159         private static final long serialVersionUID = 1L;
160
161         private final byte[] serialized;
162
163         Simple(final byte[] serialized) {
164             this.serialized = requireNonNull(serialized);
165         }
166
167         @Override
168         public int size() {
169             return serialized.length;
170         }
171
172         @Override
173         DataInput newDataInput() {
174             return ByteStreams.newDataInput(serialized);
175         }
176
177         @Override
178         void writeBytes(final ObjectOutput out) throws IOException {
179             out.write(serialized);
180         }
181     }
182
183     static sealed class Chunked extends CommitTransactionPayload {
184         @java.io.Serial
185         private static final long serialVersionUID = 1L;
186
187         @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "Handled via serialization proxy")
188         private final ChunkedByteArray source;
189
190         Chunked(final ChunkedByteArray source) {
191             this.source = requireNonNull(source);
192         }
193
194         @Override
195         void writeBytes(final ObjectOutput out) throws IOException {
196             source.copyTo(out);
197         }
198
199         @Override
200         public int size() {
201             return source.size();
202         }
203
204         @Override
205         DataInput newDataInput() {
206             return new DataInputStream(source.openStream());
207         }
208     }
209
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;
213
214         private ProxySizeHolder() {
215             // Hidden on purpose
216         }
217     }
218
219     @Deprecated(since = "7.0.0", forRemoval = true)
220     private static final class SimpleMagnesium extends Simple implements LegacySerializable {
221         @java.io.Serial
222         private static final long serialVersionUID = 1L;
223
224         SimpleMagnesium(final byte[] serialized) {
225             super(serialized);
226         }
227     }
228
229     @Deprecated(since = "7.0.0", forRemoval = true)
230     private static final class ChunkedMagnesium extends Chunked implements LegacySerializable {
231         @java.io.Serial
232         private static final long serialVersionUID = 1L;
233
234         ChunkedMagnesium(final ChunkedByteArray source) {
235             super(source);
236         }
237     }
238
239     @Deprecated(since = "7.0.0", forRemoval = true)
240     private static final class Proxy implements Externalizable {
241         @java.io.Serial
242         private static final long serialVersionUID = 1L;
243
244         private CommitTransactionPayload payload;
245
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")
249         public Proxy() {
250             // For Externalizable
251         }
252
253         Proxy(final CommitTransactionPayload payload) {
254             this.payload = requireNonNull(payload);
255         }
256
257         @Override
258         public void writeExternal(final ObjectOutput out) throws IOException {
259             out.writeInt(payload.size());
260             payload.writeBytes(out);
261         }
262
263         @Override
264         public void readExternal(final ObjectInput in) throws IOException {
265             final int length = in.readInt();
266             if (length < 0) {
267                 throw new StreamCorruptedException("Invalid payload length " + length);
268             } else if (length < MAX_ARRAY_SIZE) {
269                 final byte[] serialized = new byte[length];
270                 in.readFully(serialized);
271                 payload = new SimpleMagnesium(serialized);
272             } else {
273                 payload = new ChunkedMagnesium(ChunkedByteArray.readFrom(in, length, MAX_ARRAY_SIZE));
274             }
275         }
276
277         @java.io.Serial
278         private Object readResolve() {
279             return verifyNotNull(payload);
280         }
281     }
282 }