2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.connect.netconf.listener;
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 com.google.common.util.concurrent.SettableFuture;
16 import io.netty.util.concurrent.Future;
17 import io.netty.util.concurrent.FutureListener;
18 import io.netty.util.concurrent.GenericFutureListener;
19 import java.util.ArrayDeque;
20 import java.util.Iterator;
21 import java.util.List;
22 import java.util.Queue;
23 import java.util.concurrent.locks.Lock;
24 import java.util.concurrent.locks.ReentrantLock;
25 import org.opendaylight.controller.config.util.xml.XmlElement;
26 import org.opendaylight.controller.config.util.xml.XmlUtil;
27 import org.opendaylight.netconf.api.NetconfDocumentedException;
28 import org.opendaylight.netconf.api.NetconfMessage;
29 import org.opendaylight.netconf.api.NetconfTerminationReason;
30 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
31 import org.opendaylight.netconf.client.NetconfClientDispatcher;
32 import org.opendaylight.netconf.client.NetconfClientSession;
33 import org.opendaylight.netconf.client.NetconfClientSessionListener;
34 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
35 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
36 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
37 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
38 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
39 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
40 import org.opendaylight.yangtools.yang.common.QName;
41 import org.opendaylight.yangtools.yang.common.RpcError;
42 import org.opendaylight.yangtools.yang.common.RpcResult;
43 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
49 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
51 protected final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice;
52 private final Optional<NetconfSessionPreferences> overrideNetconfCapabilities;
53 protected final RemoteDeviceId id;
54 private final Lock sessionLock = new ReentrantLock();
56 // TODO implement concurrent message limit
57 private final Queue<Request> requests = new ArrayDeque<>();
58 private NetconfClientSession session;
60 private Future<?> initFuture;
61 private SettableFuture<NetconfDeviceCapabilities> firstConnectionFuture;
63 public NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
64 final NetconfSessionPreferences NetconfSessionPreferences) {
65 this(id, remoteDevice, Optional.of(NetconfSessionPreferences));
68 public NetconfDeviceCommunicator(final RemoteDeviceId id,
69 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice) {
70 this(id, remoteDevice, Optional.<NetconfSessionPreferences>absent());
73 private NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
74 final Optional<NetconfSessionPreferences> overrideNetconfCapabilities) {
76 this.remoteDevice = remoteDevice;
77 this.overrideNetconfCapabilities = overrideNetconfCapabilities;
78 this.firstConnectionFuture = SettableFuture.create();
82 public void onSessionUp(final NetconfClientSession session) {
85 LOG.debug("{}: Session established", id);
86 this.session = session;
88 NetconfSessionPreferences netconfSessionPreferences =
89 NetconfSessionPreferences.fromNetconfSession(session);
90 LOG.trace("{}: Session advertised capabilities: {}", id,
91 netconfSessionPreferences);
93 if(overrideNetconfCapabilities.isPresent()) {
94 netconfSessionPreferences = netconfSessionPreferences.addModuleCaps(overrideNetconfCapabilities.get());
96 "{}: Session capabilities overridden, capabilities that will be used: {}",
97 id, netconfSessionPreferences);
101 remoteDevice.onRemoteSessionUp(netconfSessionPreferences, this);
102 if (!firstConnectionFuture.isDone()) {
103 firstConnectionFuture.set(netconfSessionPreferences.getNetconfDeviceCapabilities());
107 sessionLock.unlock();
115 * @return future that returns succes on first succesfull connection and failure when the underlying
116 * reconnecting strategy runs out of reconnection attempts
118 public ListenableFuture<NetconfDeviceCapabilities> initializeRemoteConnection(final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) {
119 // TODO 2313 extract listener from configuration
120 if(config instanceof NetconfReconnectingClientConfiguration) {
121 initFuture = dispatcher.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
123 initFuture = dispatcher.createClient(config);
127 initFuture.addListener(new GenericFutureListener<Future<Object>>(){
130 public void operationComplete(Future<Object> future) throws Exception {
131 if (!future.isSuccess() && !future.isCancelled()) {
132 LOG.debug("{}: Connection failed", id, future.cause());
133 NetconfDeviceCommunicator.this.remoteDevice.onRemoteSessionFailed(future.cause());
134 if (firstConnectionFuture.isDone()) {
135 firstConnectionFuture.setException(future.cause());
140 return firstConnectionFuture;
143 public void disconnect() {
144 if(session != null) {
149 private void tearDown( String reason ) {
150 LOG.debug("Tearing down {}", reason);
151 List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
154 if( session != null ) {
158 * Walk all requests, check if they have been executing
159 * or cancelled and remove them from the queue.
161 final Iterator<Request> it = requests.iterator();
162 while (it.hasNext()) {
163 final Request r = it.next();
164 if (r.future.isUncancellable()) {
165 futuresToCancel.add( r.future );
167 } else if (r.future.isCancelled()) {
168 // This just does some house-cleaning
173 remoteDevice.onRemoteSessionDown();
177 sessionLock.unlock();
180 // Notify pending request futures outside of the sessionLock to avoid unnecessarily
181 // blocking the caller.
182 for( UncancellableFuture<RpcResult<NetconfMessage>> future: futuresToCancel ) {
183 if( Strings.isNullOrEmpty( reason ) ) {
184 future.set( createSessionDownRpcResult() );
186 future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) );
191 private RpcResult<NetconfMessage> createSessionDownRpcResult() {
192 return createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
193 String.format( "The netconf session to %1$s is disconnected", id.getName() ) );
196 private RpcResult<NetconfMessage> createErrorRpcResult( RpcError.ErrorType errorType, String message ) {
197 return RpcResultBuilder.<NetconfMessage>failed()
198 .withError(errorType, NetconfDocumentedException.ErrorTag.operation_failed.getTagValue(), message).build();
202 public void onSessionDown(final NetconfClientSession session, final Exception e) {
203 LOG.warn("{}: Session went down", id, e);
208 public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
209 LOG.warn("{}: Session terminated {}", id, reason);
210 tearDown( reason.getErrorMessage() );
214 public void close() {
215 // Cancel reconnect if in progress
216 if(initFuture != null) {
217 initFuture.cancel(false);
219 // Disconnect from device
220 if(session != null) {
222 // tear down not necessary, called indirectly by above close
227 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
229 * Dispatch between notifications and messages. Messages need to be processed
230 * with lock held, notifications do not.
232 if (isNotification(message)) {
233 processNotification(message);
235 processMessage(message);
239 private void processMessage(final NetconfMessage message) {
240 Request request = null;
244 request = requests.peek();
245 if (request != null && request.future.isUncancellable()) {
249 LOG.warn("{}: Ignoring unsolicited message {}", id,
254 sessionLock.unlock();
257 if( request != null ) {
259 LOG.debug("{}: Message received {}", id, message);
261 if(LOG.isTraceEnabled()) {
262 LOG.trace( "{}: Matched request: {} to response: {}", id, msgToS( request.request ), msgToS( message ) );
266 NetconfMessageTransformUtil.checkValidReply( request.request, message );
267 } catch (final NetconfDocumentedException e) {
269 "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
270 id, msgToS(request.request), msgToS(message), e);
272 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
273 .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
275 //recursively processing message to eventually find matching request
276 processMessage(message);
282 NetconfMessageTransformUtil.checkSuccessReply(message);
283 } catch(final NetconfDocumentedException e) {
285 "{}: Error reply from remote device, request: {}, response: {}",
286 id, msgToS(request.request), msgToS(message), e);
288 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
289 .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
293 request.future.set( RpcResultBuilder.success( message ).build() );
297 private static String msgToS(final NetconfMessage msg) {
298 return XmlUtil.toString(msg.getDocument());
302 public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
305 return sendRequestWithLock( message, rpc );
307 sessionLock.unlock();
311 private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(
312 final NetconfMessage message, final QName rpc) {
313 if(LOG.isTraceEnabled()) {
314 LOG.trace("{}: Sending message {}", id, msgToS(message));
317 if (session == null) {
318 LOG.warn("{}: Session is disconnected, failing RPC request {}",
320 return Futures.immediateFuture( createSessionDownRpcResult() );
323 final Request req = new Request( new UncancellableFuture<RpcResult<NetconfMessage>>(true),
327 session.sendMessage(req.request).addListener(new FutureListener<Void>() {
329 public void operationComplete(final Future<Void> future) throws Exception {
330 if( !future.isSuccess() ) {
331 // We expect that a session down will occur at this point
332 LOG.debug("{}: Failed to send request {}", id,
333 XmlUtil.toString(req.request.getDocument()),
336 if( future.cause() != null ) {
337 req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
338 future.cause().getLocalizedMessage() ) );
340 req.future.set( createSessionDownRpcResult() ); // assume session is down
342 req.future.setException( future.cause() );
345 LOG.trace("Finished sending request {}", req.request);
353 private void processNotification(final NetconfMessage notification) {
354 if(LOG.isTraceEnabled()) {
355 LOG.trace("{}: Notification received: {}", id, notification);
358 remoteDevice.onNotification(notification);
361 private static boolean isNotification(final NetconfMessage message) {
362 final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
363 return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
366 private static final class Request {
367 final UncancellableFuture<RpcResult<NetconfMessage>> future;
368 final NetconfMessage request;
370 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
371 final NetconfMessage request) {
372 this.future = future;
373 this.request = request;