e78f2b32df0cbc338bad5b28ac1d5063084b9b96
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / listener / NetconfDeviceCommunicator.java
1 /*
2  * Copyright (c) 2014 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.sal.connect.netconf.listener;
9
10 import java.util.ArrayDeque;
11 import java.util.Collections;
12 import java.util.Iterator;
13 import java.util.Queue;
14
15 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
16 import org.opendaylight.controller.netconf.api.NetconfMessage;
17 import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
18 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
19 import org.opendaylight.controller.netconf.client.NetconfClientSession;
20 import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
21 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
22 import org.opendaylight.controller.netconf.util.xml.XmlElement;
23 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
24 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
25 import org.opendaylight.controller.sal.common.util.RpcErrors;
26 import org.opendaylight.controller.sal.common.util.Rpcs;
27 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
28 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
29 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
30 import org.opendaylight.controller.sal.connect.util.FailedRpcResult;
31 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.RpcError;
34 import org.opendaylight.yangtools.yang.common.RpcResult;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 import com.google.common.util.concurrent.Futures;
39 import com.google.common.util.concurrent.ListenableFuture;
40
41 import io.netty.util.concurrent.Future;
42 import io.netty.util.concurrent.FutureListener;
43
44 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
45
46     private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
47
48     private static final RpcResult<NetconfMessage> FAILED_RPC_RESULT = new FailedRpcResult<>(RpcErrors.getRpcError(
49             null, null, null, RpcError.ErrorSeverity.ERROR, "Netconf session disconnected",
50             RpcError.ErrorType.PROTOCOL, null));
51
52     private final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice;
53     private final RemoteDeviceId id;
54
55     public NetconfDeviceCommunicator(final RemoteDeviceId id,
56             final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice) {
57         this.id = id;
58         this.remoteDevice = remoteDevice;
59     }
60
61     private final Queue<Request> requests = new ArrayDeque<>();
62     private NetconfClientSession session;
63
64     @Override
65     public synchronized void onSessionUp(final NetconfClientSession session) {
66         logger.debug("{}: Session established", id);
67         this.session = session;
68
69         final NetconfSessionCapabilities netconfSessionCapabilities = NetconfSessionCapabilities.fromNetconfSession(session);
70         logger.trace("{}: Session advertised capabilities: {}", id, netconfSessionCapabilities);
71
72         remoteDevice.onRemoteSessionUp(netconfSessionCapabilities, this);
73     }
74
75     public void initializeRemoteConnection(final NetconfClientDispatcher dispatch,
76                                            final NetconfReconnectingClientConfiguration config) {
77         dispatch.createReconnectingClient(config);
78     }
79
80     private synchronized void tearDown(final Exception e) {
81         remoteDevice.onRemoteSessionDown();
82         session = null;
83
84         /*
85          * Walk all requests, check if they have been executing
86          * or cancelled and remove them from the queue.
87          */
88         final Iterator<Request> it = requests.iterator();
89         while (it.hasNext()) {
90             final Request r = it.next();
91             if (r.future.isUncancellable()) {
92                 r.future.setException(e);
93                 it.remove();
94             } else if (r.future.isCancelled()) {
95                 // This just does some house-cleaning
96                 it.remove();
97             }
98         }
99     }
100
101     @Override
102     public void onSessionDown(final NetconfClientSession session, final Exception e) {
103         logger.warn("{}: Session went down", id, e);
104         tearDown(e);
105     }
106
107     @Override
108     public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
109         logger.warn("{}: Session terminated {}", id, reason);
110         tearDown(new RuntimeException(reason.getErrorMessage()));
111     }
112
113     @Override
114     public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
115         /*
116          * Dispatch between notifications and messages. Messages need to be processed
117          * with lock held, notifications do not.
118          */
119         if (isNotification(message)) {
120             processNotification(message);
121         } else {
122             processMessage(message);
123         }
124     }
125
126     private synchronized void processMessage(final NetconfMessage message) {
127         final Request r = requests.peek();
128         if (r.future.isUncancellable()) {
129             requests.poll();
130
131             logger.debug("{}: Message received {}", id, message);
132
133             if(logger.isTraceEnabled()) {
134                 logger.trace("{}: Matched request: {} to response: {}", id, msgToS(r.request), msgToS(message));
135             }
136
137             try {
138                 NetconfMessageTransformUtil.checkValidReply(r.request, message);
139             } catch (final IllegalStateException e) {
140                 logger.warn("{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}", id,
141                         msgToS(r.request), msgToS(message), e);
142                 r.future.setException(e);
143                 return;
144             }
145
146             try {
147                 NetconfMessageTransformUtil.checkSuccessReply(message);
148             } catch (NetconfDocumentedException | IllegalStateException e) {
149                 logger.warn("{}: Error reply from remote device, request: {}, response: {}", id,
150                         msgToS(r.request), msgToS(message), e);
151                 r.future.setException(e);
152                 return;
153             }
154
155             r.future.set(Rpcs.getRpcResult(true, message, Collections.<RpcError>emptySet()));
156         } else {
157             logger.warn("{}: Ignoring unsolicited message {}", id, msgToS(message));
158         }
159     }
160
161     @Override
162     public void close() {
163         tearDown(new RuntimeException("Closed"));
164     }
165
166     private static String msgToS(final NetconfMessage msg) {
167         return XmlUtil.toString(msg.getDocument());
168     }
169
170     @Override
171     public synchronized ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
172         if(logger.isTraceEnabled()) {
173             logger.trace("{}: Sending message {}", id, msgToS(message));
174         }
175
176         if (session == null) {
177             logger.warn("{}: Session is disconnected, failing RPC request {}", id, message);
178             return Futures.immediateFuture(FAILED_RPC_RESULT);
179         }
180
181         final Request req = new Request(new UncancellableFuture<RpcResult<NetconfMessage>>(true), message, rpc);
182         requests.add(req);
183
184         session.sendMessage(req.request).addListener(new FutureListener<Void>() {
185             @Override
186             public void operationComplete(final Future<Void> future) throws Exception {
187                 if (!future.isSuccess()) {
188                     // We expect that a session down will occur at this point
189                     logger.debug("{}: Failed to send request {}", id, XmlUtil.toString(req.request.getDocument()), future.cause());
190                     req.future.setException(future.cause());
191                 } else {
192                     logger.trace("{}: Finished sending request {}", id, req.request);
193                 }
194             }
195         });
196
197         return req.future;
198     }
199
200     private void processNotification(final NetconfMessage notification) {
201         logger.debug("{}: Notification received: {}", id, notification);
202
203         if(logger.isTraceEnabled()) {
204             logger.trace("{}: Notification received: {}", id, msgToS(notification));
205         }
206
207         remoteDevice.onNotification(notification);
208     }
209
210     private static boolean isNotification(final NetconfMessage message) {
211         final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
212         return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
213     }
214
215     private static final class Request {
216         final UncancellableFuture<RpcResult<NetconfMessage>> future;
217         final NetconfMessage request;
218         final QName rpc;
219
220         private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future, final NetconfMessage request, final QName rpc) {
221             this.future = future;
222             this.request = request;
223             this.rpc = rpc;
224         }
225     }
226 }