Merge "Implement basic ShardTransactionChain#CloseTransactionChain"
[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.List;
14 import java.util.Queue;
15 import java.util.concurrent.locks.Lock;
16 import java.util.concurrent.locks.ReentrantLock;
17
18 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
19 import org.opendaylight.controller.netconf.api.NetconfMessage;
20 import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
21 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
22 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
23 import org.opendaylight.controller.netconf.client.NetconfClientSession;
24 import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
25 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
26 import org.opendaylight.controller.netconf.util.xml.XmlElement;
27 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
28 import org.opendaylight.controller.sal.common.util.RpcErrors;
29 import org.opendaylight.controller.sal.common.util.Rpcs;
30 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
31 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
32 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
33 import org.opendaylight.controller.sal.connect.util.FailedRpcResult;
34 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.common.RpcError;
37 import org.opendaylight.yangtools.yang.common.RpcResult;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 import com.google.common.base.Strings;
42 import com.google.common.collect.Lists;
43 import com.google.common.util.concurrent.Futures;
44 import com.google.common.util.concurrent.ListenableFuture;
45
46 import io.netty.util.concurrent.Future;
47 import io.netty.util.concurrent.FutureListener;
48
49 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
50
51     private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
52
53     private final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice;
54     private final RemoteDeviceId id;
55     private final Lock sessionLock = new ReentrantLock();
56
57     public NetconfDeviceCommunicator(final RemoteDeviceId id,
58             final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice) {
59         this.id = id;
60         this.remoteDevice = remoteDevice;
61     }
62
63     private final Queue<Request> requests = new ArrayDeque<>();
64     private NetconfClientSession session;
65
66     @Override
67     public void onSessionUp(final NetconfClientSession session) {
68         sessionLock.lock();
69         try {
70             logger.debug("{}: Session established", id);
71             this.session = session;
72
73             final NetconfSessionCapabilities netconfSessionCapabilities =
74                                              NetconfSessionCapabilities.fromNetconfSession(session);
75             logger.trace("{}: Session advertised capabilities: {}", id, netconfSessionCapabilities);
76
77             remoteDevice.onRemoteSessionUp(netconfSessionCapabilities, this);
78         }
79         finally {
80             sessionLock.unlock();
81         }
82     }
83
84     public void initializeRemoteConnection(final NetconfClientDispatcher dispatch,
85                                            final NetconfReconnectingClientConfiguration config) {
86         dispatch.createReconnectingClient(config);
87     }
88
89     private void tearDown( String reason ) {
90         List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
91         sessionLock.lock();
92         try {
93             if( session != null ) {
94                 session = null;
95
96                 /*
97                  * Walk all requests, check if they have been executing
98                  * or cancelled and remove them from the queue.
99                  */
100                 final Iterator<Request> it = requests.iterator();
101                 while (it.hasNext()) {
102                     final Request r = it.next();
103                     if (r.future.isUncancellable()) {
104                         futuresToCancel.add( r.future );
105                         it.remove();
106                     } else if (r.future.isCancelled()) {
107                         // This just does some house-cleaning
108                         it.remove();
109                     }
110                 }
111
112                 remoteDevice.onRemoteSessionDown();
113             }
114         }
115         finally {
116             sessionLock.unlock();
117         }
118
119         // Notify pending request futures outside of the sessionLock to avoid unnecessarily
120         // blocking the caller.
121         for( UncancellableFuture<RpcResult<NetconfMessage>> future: futuresToCancel ) {
122             if( Strings.isNullOrEmpty( reason ) ) {
123                 future.set( createSessionDownRpcResult() );
124             } else {
125                 future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) );
126             }
127         }
128     }
129
130     private RpcResult<NetconfMessage> createSessionDownRpcResult()
131     {
132         return createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
133                              String.format( "The netconf session to %1$s is disconnected", id.getName() ) );
134     }
135
136     private RpcResult<NetconfMessage> createErrorRpcResult( RpcError.ErrorType errorType, String message )
137     {
138         return new FailedRpcResult<NetconfMessage>( RpcErrors.getRpcError( null,
139                 NetconfDocumentedException.ErrorTag.operation_failed.getTagValue(),
140                 null, RpcError.ErrorSeverity.ERROR, message, errorType, null ) );
141     }
142
143     @Override
144     public void onSessionDown(final NetconfClientSession session, final Exception e) {
145         logger.warn("{}: Session went down", id, e);
146         tearDown( null );
147     }
148
149     @Override
150     public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
151         logger.warn("{}: Session terminated {}", id, reason);
152         tearDown( reason.getErrorMessage() );
153     }
154
155     @Override
156     public void close() {
157         tearDown( String.format( "The netconf session to %1$s has been closed", id.getName() ) );
158     }
159
160     @Override
161     public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
162         /*
163          * Dispatch between notifications and messages. Messages need to be processed
164          * with lock held, notifications do not.
165          */
166         if (isNotification(message)) {
167             processNotification(message);
168         } else {
169             processMessage(message);
170         }
171     }
172
173     private void processMessage(final NetconfMessage message) {
174         Request request = null;
175         sessionLock.lock();
176         try {
177             request = requests.peek();
178             if (request.future.isUncancellable()) {
179                 requests.poll();
180             }
181             else {
182                 request = null;
183                 logger.warn("{}: Ignoring unsolicited message {}", id, msgToS(message));
184             }
185         }
186         finally {
187             sessionLock.unlock();
188         }
189
190         if( request != null ) {
191
192             logger.debug("{}: Message received {}", id, message);
193
194             if(logger.isTraceEnabled()) {
195                 logger.trace( "{}: Matched request: {} to response: {}", id,
196                               msgToS( request.request ), msgToS( message ) );
197             }
198
199             try {
200                 NetconfMessageTransformUtil.checkValidReply( request.request, message );
201             }
202             catch (final NetconfDocumentedException e) {
203                 logger.warn( "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
204                              id, msgToS( request.request ), msgToS( message ), e );
205
206                 request.future.set( new FailedRpcResult<NetconfMessage>(
207                                                            NetconfMessageTransformUtil.toRpcError( e ) ) );
208                 return;
209             }
210
211             try {
212                 NetconfMessageTransformUtil.checkSuccessReply(message);
213             }
214             catch( NetconfDocumentedException e ) {
215                 logger.warn( "{}: Error reply from remote device, request: {}, response: {}", id,
216                              msgToS( request.request ), msgToS( message ), e );
217
218                 request.future.set( new FailedRpcResult<NetconfMessage>(
219                                                           NetconfMessageTransformUtil.toRpcError( e ) ) );
220                 return;
221             }
222
223             request.future.set(Rpcs.getRpcResult( true, message, Collections.<RpcError>emptySet() ) );
224         }
225     }
226
227     private static String msgToS(final NetconfMessage msg) {
228         return XmlUtil.toString(msg.getDocument());
229     }
230
231     @Override
232     public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(
233                                                final NetconfMessage message, final QName rpc) {
234         sessionLock.lock();
235         try {
236             return sendRequestWithLock( message, rpc );
237         }
238         finally {
239             sessionLock.unlock();
240         }
241     }
242
243     private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(
244                                                final NetconfMessage message, final QName rpc) {
245         if(logger.isTraceEnabled()) {
246             logger.trace("{}: Sending message {}", id, msgToS(message));
247         }
248
249         if (session == null) {
250             logger.warn("{}: Session is disconnected, failing RPC request {}", id, message);
251             return Futures.immediateFuture( createSessionDownRpcResult() );
252         }
253
254         final Request req = new Request( new UncancellableFuture<RpcResult<NetconfMessage>>(true),
255                                          message );
256         requests.add(req);
257
258         session.sendMessage(req.request).addListener(new FutureListener<Void>() {
259             @Override
260             public void operationComplete(final Future<Void> future) throws Exception {
261                 if( !future.isSuccess() ) {
262                     // We expect that a session down will occur at this point
263                     logger.debug( "{}: Failed to send request {}", id,
264                                   XmlUtil.toString(req.request.getDocument()), future.cause() );
265
266                     if( future.cause() != null ) {
267                         req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
268                                                               future.cause().getLocalizedMessage() ) );
269                     } else {
270                         req.future.set( createSessionDownRpcResult() ); // assume session is down
271                     }
272                     req.future.setException( future.cause() );
273                 }
274                 else {
275                     logger.trace( "Finished sending request {}", req.request );
276                 }
277             }
278         });
279
280         return req.future;
281     }
282
283     private void processNotification(final NetconfMessage notification) {
284         logger.debug("{}: Notification received: {}", id, notification);
285
286         if(logger.isTraceEnabled()) {
287             logger.trace("{}: Notification received: {}", id, msgToS(notification));
288         }
289
290         remoteDevice.onNotification(notification);
291     }
292
293     private static boolean isNotification(final NetconfMessage message) {
294         final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
295         return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
296     }
297
298     private static final class Request {
299         final UncancellableFuture<RpcResult<NetconfMessage>> future;
300         final NetconfMessage request;
301
302         private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
303                         final NetconfMessage request) {
304             this.future = future;
305             this.request = request;
306         }
307     }
308 }