Adopt odlparent-10.0.0/yangtools-8.0.0-SNAPSHOT
[mdsal.git] / replicate / mdsal-replicate-netty / src / main / java / org / opendaylight / mdsal / replicate / netty / SinkRequestHandler.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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.mdsal.replicate.netty;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static com.google.common.base.Verify.verify;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.MoreExecutors;
16 import io.netty.buffer.ByteBuf;
17 import io.netty.buffer.ByteBufInputStream;
18 import io.netty.buffer.Unpooled;
19 import io.netty.channel.Channel;
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.channel.SimpleChannelInboundHandler;
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.List;
25 import org.opendaylight.mdsal.common.api.CommitInfo;
26 import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
27 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
28 import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
29 import org.opendaylight.mdsal.replicate.common.DataTreeCandidateUtils;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.stream.ReusableStreamReceiver;
33 import org.opendaylight.yangtools.yang.data.codec.binfmt.DataTreeCandidateInputOutput;
34 import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeDataInput;
35 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
36 import org.opendaylight.yangtools.yang.data.impl.schema.ReusableImmutableNormalizedNodeStreamWriter;
37 import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 final class SinkRequestHandler extends SimpleChannelInboundHandler<ByteBuf> {
43     private static final Logger LOG = LoggerFactory.getLogger(SinkRequestHandler.class);
44     private static final ContainerNode EMPTY_ROOT = ImmutableNodes.containerNode(SchemaContext.NAME);
45
46     private final ReusableStreamReceiver receiver = ReusableImmutableNormalizedNodeStreamWriter.create();
47     private final List<ByteBuf> chunks = new ArrayList<>();
48     private final DOMDataTreeIdentifier tree;
49     private final DOMTransactionChain chain;
50
51     SinkRequestHandler(final DOMDataTreeIdentifier tree, final DOMTransactionChain chain) {
52         this.tree = requireNonNull(tree);
53         this.chain = requireNonNull(chain);
54     }
55
56     @Override
57     protected void channelRead0(final ChannelHandlerContext ctx, final ByteBuf msg) throws IOException {
58         verify(msg.isReadable(), "Empty message received");
59
60         final short msgType = msg.readUnsignedByte();
61         final Channel channel = ctx.channel();
62         LOG.trace("Channel {} received message type {}", channel, msgType);
63         switch (msgType) {
64             case Constants.MSG_EMPTY_DATA:
65                 handleEmptyData();
66                 break;
67             case Constants.MSG_DTC_CHUNK:
68                 chunks.add(msg.retain());
69                 break;
70             case Constants.MSG_DTC_APPLY:
71                 handleDtcApply();
72                 break;
73             case Constants.MSG_PING:
74                 LOG.trace("Received PING from Source, sending PONG");
75                 ctx.channel().writeAndFlush(Constants.PONG);
76                 break;
77             default:
78                 throw new IllegalStateException("Unexpected message type " + msgType);
79         }
80     }
81
82     private void handleEmptyData() {
83         final DOMDataTreeWriteTransaction tx = chain.newWriteOnlyTransaction();
84
85         if (tree.getRootIdentifier().isEmpty()) {
86             tx.put(tree.getDatastoreType(), YangInstanceIdentifier.empty(), EMPTY_ROOT);
87         } else {
88             tx.delete(tree.getDatastoreType(), tree.getRootIdentifier());
89         }
90         commit(tx);
91     }
92
93     private void handleDtcApply() throws IOException {
94         checkState(!chunks.isEmpty(), "No chunks to apply");
95
96         final ByteBuf bufs = Unpooled.wrappedBuffer(chunks.toArray(new ByteBuf[0]));
97         chunks.clear();
98
99         final DataTreeCandidate candidate;
100         try (ByteBufInputStream stream = new ByteBufInputStream(bufs)) {
101             candidate = DataTreeCandidateInputOutput.readDataTreeCandidate(NormalizedNodeDataInput.newDataInput(stream),
102                 receiver);
103         }
104
105         final DOMDataTreeWriteTransaction tx = chain.newWriteOnlyTransaction();
106         DataTreeCandidateUtils.applyToTransaction(tx, tree.getDatastoreType(), candidate);
107         commit(tx);
108     }
109
110     private static void commit(final DOMDataTreeWriteTransaction tx) {
111         tx.commit().addCallback(new FutureCallback<CommitInfo>() {
112             @Override
113             public void onSuccess(final CommitInfo result) {
114                 LOG.trace("Transaction committed with {}", result);
115             }
116
117             @Override
118             public void onFailure(final Throwable cause) {
119                 // Handled by transaction chain listener
120             }
121         }, MoreExecutors.directExecutor());
122     }
123 }