Revert "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.eclipse.jdt.annotation.NonNull;
30 import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
31 import org.opendaylight.controller.cluster.datastore.persisted.DataTreeCandidateInputOutput.DataTreeCandidateWithVersion;
32 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
33 import org.opendaylight.yangtools.concepts.Variant;
34 import org.opendaylight.yangtools.yang.data.api.schema.stream.ReusableStreamReceiver;
35 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
36 import org.opendaylight.yangtools.yang.data.impl.schema.ReusableImmutableNormalizedNodeStreamWriter;
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 class CommitTransactionPayload extends Payload implements Serializable {
48     private static final Logger LOG = LoggerFactory.getLogger(CommitTransactionPayload.class);
49     private static final long serialVersionUID = 1L;
50
51     CommitTransactionPayload() {
52
53     }
54
55     public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
56             final DataTreeCandidate candidate, final PayloadVersion version, final int initialSerializedBufferCapacity)
57                     throws IOException {
58         final ChunkedOutputStream cos = new ChunkedOutputStream(initialSerializedBufferCapacity);
59         try (DataOutputStream dos = new DataOutputStream(cos)) {
60             transactionId.writeTo(dos);
61             DataTreeCandidateInputOutput.writeDataTreeCandidate(dos, version, candidate);
62         }
63
64         final Variant<byte[], ChunkedByteArray> source = cos.toVariant();
65         LOG.debug("Initial buffer capacity {}, actual serialized size {}", initialSerializedBufferCapacity, cos.size());
66         return source.isFirst() ? new Simple(source.getFirst()) : new Chunked(source.getSecond());
67     }
68
69     @VisibleForTesting
70     public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
71             final DataTreeCandidate candidate, final PayloadVersion version) throws IOException {
72         return create(transactionId, candidate, version, 512);
73     }
74
75     @VisibleForTesting
76     public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
77             final DataTreeCandidate candidate) throws IOException {
78         return create(transactionId, candidate, PayloadVersion.current());
79     }
80
81     public @NonNull Entry<TransactionIdentifier, DataTreeCandidateWithVersion> getCandidate() throws IOException {
82         return getCandidate(ReusableImmutableNormalizedNodeStreamWriter.create());
83     }
84
85     public final @NonNull Entry<TransactionIdentifier, DataTreeCandidateWithVersion> getCandidate(
86             final ReusableStreamReceiver receiver) throws IOException {
87         final DataInput in = newDataInput();
88         return new SimpleImmutableEntry<>(TransactionIdentifier.readFrom(in),
89                 DataTreeCandidateInputOutput.readDataTreeCandidate(in, receiver));
90     }
91
92     abstract void writeBytes(ObjectOutput out) throws IOException;
93
94     abstract DataInput newDataInput();
95
96     final Object writeReplace() {
97         return new Proxy(this);
98     }
99
100     private static final class Simple extends CommitTransactionPayload {
101         private static final long serialVersionUID = 1L;
102
103         private final byte[] serialized;
104
105         Simple(final byte[] serialized) {
106             this.serialized = requireNonNull(serialized);
107         }
108
109         @Override
110         public int size() {
111             return serialized.length;
112         }
113
114         @Override
115         DataInput newDataInput() {
116             return ByteStreams.newDataInput(serialized);
117         }
118
119         @Override
120         void writeBytes(final ObjectOutput out) throws IOException {
121             out.write(serialized);
122         }
123     }
124
125     private static final class Chunked extends CommitTransactionPayload {
126         private static final long serialVersionUID = 1L;
127
128         @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "Handled via serialization proxy")
129         private final ChunkedByteArray source;
130
131         Chunked(final ChunkedByteArray source) {
132             this.source = requireNonNull(source);
133         }
134
135         @Override
136         void writeBytes(final ObjectOutput out) throws IOException {
137             source.copyTo(out);
138         }
139
140         @Override
141         public int size() {
142             return source.size();
143         }
144
145         @Override
146         DataInput newDataInput() {
147             return new DataInputStream(source.openStream());
148         }
149     }
150
151     private static final class Proxy implements Externalizable {
152         private static final long serialVersionUID = 1L;
153
154         private CommitTransactionPayload payload;
155
156         // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
157         // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
158         @SuppressWarnings("checkstyle:RedundantModifier")
159         public Proxy() {
160             // For Externalizable
161         }
162
163         Proxy(final CommitTransactionPayload payload) {
164             this.payload = requireNonNull(payload);
165         }
166
167         @Override
168         public void writeExternal(final ObjectOutput out) throws IOException {
169             out.writeInt(payload.size());
170             payload.writeBytes(out);
171         }
172
173         @Override
174         public void readExternal(final ObjectInput in) throws IOException {
175             final int length = in.readInt();
176             if (length < 0) {
177                 throw new StreamCorruptedException("Invalid payload length " + length);
178             } else if (length < MAX_ARRAY_SIZE) {
179                 final byte[] serialized = new byte[length];
180                 in.readFully(serialized);
181                 payload = new Simple(serialized);
182             } else {
183                 payload = new Chunked(ChunkedByteArray.readFrom(in, length, MAX_ARRAY_SIZE));
184             }
185         }
186
187         private Object readResolve() {
188             return verifyNotNull(payload);
189         }
190     }
191 }