Leader should always apply modifications as local
[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 java.util.Objects.requireNonNull;
12 import static org.opendaylight.controller.cluster.datastore.persisted.ChunkedOutputStream.MAX_ARRAY_SIZE;
13
14 import com.google.common.annotations.Beta;
15 import com.google.common.annotations.VisibleForTesting;
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.Externalizable;
22 import java.io.IOException;
23 import java.io.ObjectInput;
24 import java.io.ObjectOutput;
25 import java.io.Serializable;
26 import java.io.StreamCorruptedException;
27 import java.util.AbstractMap.SimpleImmutableEntry;
28 import java.util.Map.Entry;
29 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
30 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.IdentifiablePayload;
31 import org.opendaylight.yangtools.concepts.Variant;
32 import org.opendaylight.yangtools.yang.data.api.schema.stream.ReusableStreamReceiver;
33 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
34 import org.opendaylight.yangtools.yang.data.impl.schema.ReusableImmutableNormalizedNodeStreamWriter;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * Payload persisted when a transaction commits. It contains the transaction identifier and the
40  * {@link DataTreeCandidate}
41  *
42  * @author Robert Varga
43  */
44 @Beta
45 public abstract class CommitTransactionPayload extends IdentifiablePayload<TransactionIdentifier>
46         implements Serializable {
47     private static final Logger LOG = LoggerFactory.getLogger(CommitTransactionPayload.class);
48     private static final long serialVersionUID = 1L;
49
50     private volatile Entry<TransactionIdentifier, DataTreeCandidate> candidate = null;
51
52     CommitTransactionPayload() {
53
54     }
55
56     public static CommitTransactionPayload create(final TransactionIdentifier transactionId,
57             final DataTreeCandidate candidate, final int initialSerializedBufferCapacity) throws IOException {
58
59         final ChunkedOutputStream cos = new ChunkedOutputStream(initialSerializedBufferCapacity);
60         try (DataOutputStream dos = new DataOutputStream(cos)) {
61             transactionId.writeTo(dos);
62             DataTreeCandidateInputOutput.writeDataTreeCandidate(dos, candidate);
63         }
64
65         final Variant<byte[], ChunkedByteArray> source = cos.toVariant();
66         LOG.debug("Initial buffer capacity {}, actual serialized size {}", initialSerializedBufferCapacity, cos.size());
67         return source.isFirst() ? new Simple(source.getFirst()) : new Chunked(source.getSecond());
68     }
69
70     @VisibleForTesting
71     public static CommitTransactionPayload create(final TransactionIdentifier transactionId,
72             final DataTreeCandidate candidate) throws IOException {
73         return create(transactionId, candidate, 512);
74     }
75
76     public Entry<TransactionIdentifier, DataTreeCandidate> getCandidate() throws IOException {
77         Entry<TransactionIdentifier, DataTreeCandidate> localCandidate = candidate;
78         if (localCandidate == null) {
79             synchronized (this) {
80                 localCandidate = candidate;
81                 if (localCandidate == null) {
82                     candidate = localCandidate = getCandidate(ReusableImmutableNormalizedNodeStreamWriter.create());
83                 }
84             }
85         }
86         return localCandidate;
87     }
88
89     public final Entry<TransactionIdentifier, DataTreeCandidate> getCandidate(
90             final ReusableStreamReceiver receiver) throws IOException {
91         final DataInput in = newDataInput();
92         return new SimpleImmutableEntry<>(TransactionIdentifier.readFrom(in),
93                 DataTreeCandidateInputOutput.readDataTreeCandidate(in, receiver));
94     }
95
96     public TransactionIdentifier getIdentifier() {
97         try  {
98             return getCandidate().getKey();
99         } catch (IOException e) {
100             throw new IllegalStateException("Candidate deserialization failed.", e);
101         }
102     }
103
104     abstract void writeBytes(ObjectOutput out) throws IOException;
105
106     abstract DataInput newDataInput();
107
108     final Object writeReplace() {
109         return new Proxy(this);
110     }
111
112     private static final class Simple extends CommitTransactionPayload {
113         private static final long serialVersionUID = 1L;
114
115         private final byte[] serialized;
116
117         Simple(final byte[] serialized) {
118             this.serialized = requireNonNull(serialized);
119         }
120
121         @Override
122         public int size() {
123             return serialized.length;
124         }
125
126         @Override
127         DataInput newDataInput() {
128             return ByteStreams.newDataInput(serialized);
129         }
130
131         @Override
132         void writeBytes(final ObjectOutput out) throws IOException {
133             out.write(serialized);
134         }
135     }
136
137     private static final class Chunked extends CommitTransactionPayload {
138         private static final long serialVersionUID = 1L;
139
140         @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "Handled via serialization proxy")
141         private final ChunkedByteArray source;
142
143         Chunked(final ChunkedByteArray source) {
144             this.source = requireNonNull(source);
145         }
146
147         @Override
148         void writeBytes(final ObjectOutput out) throws IOException {
149             source.copyTo(out);
150         }
151
152         @Override
153         public int size() {
154             return source.size();
155         }
156
157         @Override
158         DataInput newDataInput() {
159             return new DataInputStream(source.openStream());
160         }
161     }
162
163     private static final class Proxy implements Externalizable {
164         private static final long serialVersionUID = 1L;
165
166         private CommitTransactionPayload payload;
167
168         // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
169         // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
170         @SuppressWarnings("checkstyle:RedundantModifier")
171         public Proxy() {
172             // For Externalizable
173         }
174
175         Proxy(final CommitTransactionPayload payload) {
176             this.payload = requireNonNull(payload);
177         }
178
179         @Override
180         public void writeExternal(final ObjectOutput out) throws IOException {
181             out.writeInt(payload.size());
182             payload.writeBytes(out);
183         }
184
185         @Override
186         public void readExternal(final ObjectInput in) throws IOException {
187             final int length = in.readInt();
188             if (length < 0) {
189                 throw new StreamCorruptedException("Invalid payload length " + length);
190             } else if (length < MAX_ARRAY_SIZE) {
191                 final byte[] serialized = new byte[length];
192                 in.readFully(serialized);
193                 payload = new Simple(serialized);
194             } else {
195                 payload = new Chunked(ChunkedByteArray.readFrom(in, length, MAX_ARRAY_SIZE));
196             }
197         }
198
199         private Object readResolve() {
200             return verifyNotNull(payload);
201         }
202     }
203 }