c8639bbebbf9ab77db2ce445411fee4b53a9e5e5
[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.math.IntMath.ceilingPowerOfTwo;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.base.MoreObjects;
16 import com.google.common.io.ByteStreams;
17 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
18 import java.io.DataInput;
19 import java.io.DataInputStream;
20 import java.io.DataOutputStream;
21 import java.io.IOException;
22 import java.io.ObjectOutput;
23 import java.io.Serializable;
24 import java.util.AbstractMap.SimpleImmutableEntry;
25 import java.util.Map.Entry;
26 import org.apache.commons.lang3.SerializationUtils;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
29 import org.opendaylight.controller.cluster.datastore.persisted.DataTreeCandidateInputOutput.DataTreeCandidateWithVersion;
30 import org.opendaylight.controller.cluster.io.ChunkedByteArray;
31 import org.opendaylight.controller.cluster.io.ChunkedOutputStream;
32 import org.opendaylight.controller.cluster.raft.messages.IdentifiablePayload;
33 import org.opendaylight.yangtools.concepts.Either;
34 import org.opendaylight.yangtools.yang.data.api.schema.stream.ReusableStreamReceiver;
35 import org.opendaylight.yangtools.yang.data.impl.schema.ReusableImmutableNormalizedNodeStreamWriter;
36 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  * Payload persisted when a transaction commits. It contains the transaction identifier and the
42  * {@link DataTreeCandidate}
43  *
44  * @author Robert Varga
45  */
46 @Beta
47 public abstract sealed class CommitTransactionPayload extends IdentifiablePayload<TransactionIdentifier>
48         implements Serializable {
49     private static final Logger LOG = LoggerFactory.getLogger(CommitTransactionPayload.class);
50     private static final long serialVersionUID = 1L;
51
52     static final int MAX_ARRAY_SIZE = ceilingPowerOfTwo(Integer.getInteger(
53         "org.opendaylight.controller.cluster.datastore.persisted.max-array-size", 256 * 1024));
54
55     private volatile Entry<TransactionIdentifier, DataTreeCandidateWithVersion> candidate = null;
56
57     CommitTransactionPayload() {
58         // hidden on purpose
59     }
60
61     public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
62             final DataTreeCandidate candidate, final PayloadVersion version, final int initialSerializedBufferCapacity)
63                     throws IOException {
64         final ChunkedOutputStream cos = new ChunkedOutputStream(initialSerializedBufferCapacity, MAX_ARRAY_SIZE);
65         try (DataOutputStream dos = new DataOutputStream(cos)) {
66             transactionId.writeTo(dos);
67             DataTreeCandidateInputOutput.writeDataTreeCandidate(dos, version, candidate);
68         }
69
70         final Either<byte[], ChunkedByteArray> source = cos.toVariant();
71         LOG.debug("Initial buffer capacity {}, actual serialized size {}", initialSerializedBufferCapacity, cos.size());
72         return source.isFirst() ? new Simple(source.getFirst()) : new Chunked(source.getSecond());
73     }
74
75     @VisibleForTesting
76     public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
77             final DataTreeCandidate candidate, final PayloadVersion version) throws IOException {
78         return create(transactionId, candidate, version, 512);
79     }
80
81     @VisibleForTesting
82     public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
83             final DataTreeCandidate candidate) throws IOException {
84         return create(transactionId, candidate, PayloadVersion.current());
85     }
86
87     public @NonNull Entry<TransactionIdentifier, DataTreeCandidateWithVersion> getCandidate() throws IOException {
88         Entry<TransactionIdentifier, DataTreeCandidateWithVersion> localCandidate = candidate;
89         if (localCandidate == null) {
90             synchronized (this) {
91                 localCandidate = candidate;
92                 if (localCandidate == null) {
93                     candidate = localCandidate = getCandidate(ReusableImmutableNormalizedNodeStreamWriter.create());
94                 }
95             }
96         }
97         return localCandidate;
98     }
99
100     public final @NonNull Entry<TransactionIdentifier, DataTreeCandidateWithVersion> getCandidate(
101             final ReusableStreamReceiver receiver) throws IOException {
102         final DataInput in = newDataInput();
103         return new SimpleImmutableEntry<>(TransactionIdentifier.readFrom(in),
104                 DataTreeCandidateInputOutput.readDataTreeCandidate(in, receiver));
105     }
106
107     @Override
108     public TransactionIdentifier getIdentifier() {
109         try  {
110             return getCandidate().getKey();
111         } catch (IOException e) {
112             throw new IllegalStateException("Candidate deserialization failed.", e);
113         }
114     }
115
116     @Override
117     public final int serializedSize() {
118         // TODO: this is not entirely accurate as the the byte[] can be chunked by the serialization stream
119         return ProxySizeHolder.PROXY_SIZE + size();
120     }
121
122     /**
123      * The cached candidate needs to be cleared after it is done applying to the DataTree, otherwise it would be keeping
124      * deserialized in memory which are not needed anymore leading to wasted memory. This lets the payload know that
125      * this was the last time the candidate was needed ant it is safe to be cleared.
126      */
127     public Entry<TransactionIdentifier, DataTreeCandidateWithVersion> acquireCandidate() throws IOException {
128         final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> localCandidate = getCandidate();
129         candidate = null;
130         return localCandidate;
131     }
132
133     @Override
134     public final String toString() {
135         final var helper = MoreObjects.toStringHelper(this);
136         final var localCandidate = candidate;
137         if (localCandidate != null) {
138             helper.add("identifier", candidate.getKey());
139         }
140         return helper.add("size", size()).toString();
141     }
142
143     abstract void writeBytes(ObjectOutput out) throws IOException;
144
145     abstract DataInput newDataInput();
146
147     @Override
148     public final Object writeReplace() {
149         return new CT(this);
150     }
151
152     static final class Simple extends CommitTransactionPayload {
153         @java.io.Serial
154         private static final long serialVersionUID = 1L;
155
156         private final byte[] serialized;
157
158         Simple(final byte[] serialized) {
159             this.serialized = requireNonNull(serialized);
160         }
161
162         @Override
163         public int size() {
164             return serialized.length;
165         }
166
167         @Override
168         DataInput newDataInput() {
169             return ByteStreams.newDataInput(serialized);
170         }
171
172         @Override
173         void writeBytes(final ObjectOutput out) throws IOException {
174             out.write(serialized);
175         }
176     }
177
178     static final class Chunked extends CommitTransactionPayload {
179         @java.io.Serial
180         private static final long serialVersionUID = 1L;
181
182         @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "Handled via serialization proxy")
183         private final ChunkedByteArray source;
184
185         Chunked(final ChunkedByteArray source) {
186             this.source = requireNonNull(source);
187         }
188
189         @Override
190         void writeBytes(final ObjectOutput out) throws IOException {
191             source.copyTo(out);
192         }
193
194         @Override
195         public int size() {
196             return source.size();
197         }
198
199         @Override
200         DataInput newDataInput() {
201             return new DataInputStream(source.openStream());
202         }
203     }
204
205     // Exists to break initialization dependency between CommitTransactionPayload/Simple/Proxy
206     private static final class ProxySizeHolder {
207         static final int PROXY_SIZE = SerializationUtils.serialize(new CT(new Simple(new byte[0]))).length;
208
209         private ProxySizeHolder() {
210             // Hidden on purpose
211         }
212     }
213 }