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