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