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