Make Payload Serializable
[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.eclipse.jdt.annotation.NonNull;
31 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
32 import org.opendaylight.controller.cluster.datastore.persisted.DataTreeCandidateInputOutput.DataTreeCandidateWithVersion;
33 import org.opendaylight.controller.cluster.io.ChunkedByteArray;
34 import org.opendaylight.controller.cluster.io.ChunkedOutputStream;
35 import org.opendaylight.controller.cluster.raft.messages.IdentifiablePayload;
36 import org.opendaylight.yangtools.concepts.Either;
37 import org.opendaylight.yangtools.yang.data.api.schema.stream.ReusableStreamReceiver;
38 import org.opendaylight.yangtools.yang.data.impl.schema.ReusableImmutableNormalizedNodeStreamWriter;
39 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 /**
44  * Payload persisted when a transaction commits. It contains the transaction identifier and the
45  * {@link DataTreeCandidate}
46  *
47  * @author Robert Varga
48  */
49 @Beta
50 public abstract class CommitTransactionPayload extends IdentifiablePayload<TransactionIdentifier>
51         implements Serializable {
52     private static final Logger LOG = LoggerFactory.getLogger(CommitTransactionPayload.class);
53     private static final long serialVersionUID = 1L;
54
55     private static final int MAX_ARRAY_SIZE = ceilingPowerOfTwo(Integer.getInteger(
56         "org.opendaylight.controller.cluster.datastore.persisted.max-array-size", 256 * 1024));
57
58     private volatile Entry<TransactionIdentifier, DataTreeCandidateWithVersion> candidate = null;
59
60     CommitTransactionPayload() {
61         // hidden on purpose
62     }
63
64     public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
65             final DataTreeCandidate candidate, final PayloadVersion version, final int initialSerializedBufferCapacity)
66                     throws IOException {
67         final ChunkedOutputStream cos = new ChunkedOutputStream(initialSerializedBufferCapacity, MAX_ARRAY_SIZE);
68         try (DataOutputStream dos = new DataOutputStream(cos)) {
69             transactionId.writeTo(dos);
70             DataTreeCandidateInputOutput.writeDataTreeCandidate(dos, version, candidate);
71         }
72
73         final Either<byte[], ChunkedByteArray> source = cos.toVariant();
74         LOG.debug("Initial buffer capacity {}, actual serialized size {}", initialSerializedBufferCapacity, cos.size());
75         return source.isFirst() ? new Simple(source.getFirst()) : new Chunked(source.getSecond());
76     }
77
78     @VisibleForTesting
79     public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
80             final DataTreeCandidate candidate, final PayloadVersion version) throws IOException {
81         return create(transactionId, candidate, version, 512);
82     }
83
84     @VisibleForTesting
85     public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
86             final DataTreeCandidate candidate) throws IOException {
87         return create(transactionId, candidate, PayloadVersion.current());
88     }
89
90     public @NonNull Entry<TransactionIdentifier, DataTreeCandidateWithVersion> getCandidate() throws IOException {
91         Entry<TransactionIdentifier, DataTreeCandidateWithVersion> localCandidate = candidate;
92         if (localCandidate == null) {
93             synchronized (this) {
94                 localCandidate = candidate;
95                 if (localCandidate == null) {
96                     candidate = localCandidate = getCandidate(ReusableImmutableNormalizedNodeStreamWriter.create());
97                 }
98             }
99         }
100         return localCandidate;
101     }
102
103     public final @NonNull Entry<TransactionIdentifier, DataTreeCandidateWithVersion> getCandidate(
104             final ReusableStreamReceiver receiver) throws IOException {
105         final DataInput in = newDataInput();
106         return new SimpleImmutableEntry<>(TransactionIdentifier.readFrom(in),
107                 DataTreeCandidateInputOutput.readDataTreeCandidate(in, receiver));
108     }
109
110     @Override
111     public TransactionIdentifier getIdentifier() {
112         try  {
113             return getCandidate().getKey();
114         } catch (IOException e) {
115             throw new IllegalStateException("Candidate deserialization failed.", e);
116         }
117     }
118
119     /**
120      * The cached candidate needs to be cleared after it is done applying to the DataTree, otherwise it would be keeping
121      * deserialized in memory which are not needed anymore leading to wasted memory. This lets the payload know that
122      * this was the last time the candidate was needed ant it is safe to be cleared.
123      */
124     public Entry<TransactionIdentifier, DataTreeCandidateWithVersion> acquireCandidate() throws IOException {
125         final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> localCandidate = getCandidate();
126         candidate = null;
127         return localCandidate;
128     }
129
130     @Override
131     public final String toString() {
132         final var helper = MoreObjects.toStringHelper(this);
133         final var localCandidate = candidate;
134         if (localCandidate != null) {
135             helper.add("identifier", candidate.getKey());
136         }
137         return helper.add("size", size()).toString();
138     }
139
140     abstract void writeBytes(ObjectOutput out) throws IOException;
141
142     abstract DataInput newDataInput();
143
144     @Override
145     protected final Object writeReplace() {
146         return new Proxy(this);
147     }
148
149     private static final class Simple extends CommitTransactionPayload {
150         private static final long serialVersionUID = 1L;
151
152         private final byte[] serialized;
153
154         Simple(final byte[] serialized) {
155             this.serialized = requireNonNull(serialized);
156         }
157
158         @Override
159         public int size() {
160             return serialized.length;
161         }
162
163         @Override
164         DataInput newDataInput() {
165             return ByteStreams.newDataInput(serialized);
166         }
167
168         @Override
169         void writeBytes(final ObjectOutput out) throws IOException {
170             out.write(serialized);
171         }
172     }
173
174     private static final class Chunked extends CommitTransactionPayload {
175         private static final long serialVersionUID = 1L;
176
177         @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "Handled via serialization proxy")
178         private final ChunkedByteArray source;
179
180         Chunked(final ChunkedByteArray source) {
181             this.source = requireNonNull(source);
182         }
183
184         @Override
185         void writeBytes(final ObjectOutput out) throws IOException {
186             source.copyTo(out);
187         }
188
189         @Override
190         public int size() {
191             return source.size();
192         }
193
194         @Override
195         DataInput newDataInput() {
196             return new DataInputStream(source.openStream());
197         }
198     }
199
200     private static final class Proxy implements Externalizable {
201         private static final long serialVersionUID = 1L;
202
203         private CommitTransactionPayload payload;
204
205         // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
206         // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
207         @SuppressWarnings("checkstyle:RedundantModifier")
208         public Proxy() {
209             // For Externalizable
210         }
211
212         Proxy(final CommitTransactionPayload payload) {
213             this.payload = requireNonNull(payload);
214         }
215
216         @Override
217         public void writeExternal(final ObjectOutput out) throws IOException {
218             out.writeInt(payload.size());
219             payload.writeBytes(out);
220         }
221
222         @Override
223         public void readExternal(final ObjectInput in) throws IOException {
224             final int length = in.readInt();
225             if (length < 0) {
226                 throw new StreamCorruptedException("Invalid payload length " + length);
227             } else if (length < MAX_ARRAY_SIZE) {
228                 final byte[] serialized = new byte[length];
229                 in.readFully(serialized);
230                 payload = new Simple(serialized);
231             } else {
232                 payload = new Chunked(ChunkedByteArray.readFrom(in, length, MAX_ARRAY_SIZE));
233             }
234         }
235
236         private Object readResolve() {
237             return verifyNotNull(payload);
238         }
239     }
240 }