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.controller.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 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;
46 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
48 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
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();
55 // TODO implement concurrent message limit
56 private final Queue<Request> requests = new ArrayDeque<>();
57 private NetconfClientSession session;
58 private Future<?> initFuture;
60 public NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
61 final NetconfSessionPreferences NetconfSessionPreferences) {
62 this(id, remoteDevice, Optional.of(NetconfSessionPreferences));
65 public NetconfDeviceCommunicator(final RemoteDeviceId id,
66 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice) {
67 this(id, remoteDevice, Optional.<NetconfSessionPreferences>absent());
70 private NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
71 final Optional<NetconfSessionPreferences> overrideNetconfCapabilities) {
73 this.remoteDevice = remoteDevice;
74 this.overrideNetconfCapabilities = overrideNetconfCapabilities;
78 public void onSessionUp(final NetconfClientSession session) {
81 LOG.debug("{}: Session established", id);
82 this.session = session;
84 NetconfSessionPreferences netconfSessionPreferences =
85 NetconfSessionPreferences.fromNetconfSession(session);
86 LOG.trace("{}: Session advertised capabilities: {}", id,
87 netconfSessionPreferences);
89 if(overrideNetconfCapabilities.isPresent()) {
90 netconfSessionPreferences = netconfSessionPreferences.addModuleCaps(overrideNetconfCapabilities.get());
92 "{}: Session capabilities overridden, capabilities that will be used: {}",
93 id, netconfSessionPreferences);
96 remoteDevice.onRemoteSessionUp(netconfSessionPreferences, this);
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);
108 initFuture = dispatcher.createClient(config);
112 initFuture.addListener(new GenericFutureListener<Future<Object>>(){
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());
125 public void disconnect() {
126 if(session != null) {
131 private void tearDown( String reason ) {
132 List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
135 if( session != null ) {
139 * Walk all requests, check if they have been executing
140 * or cancelled and remove them from the queue.
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 );
148 } else if (r.future.isCancelled()) {
149 // This just does some house-cleaning
154 remoteDevice.onRemoteSessionDown();
158 sessionLock.unlock();
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() );
167 future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) );
172 private RpcResult<NetconfMessage> createSessionDownRpcResult() {
173 return createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
174 String.format( "The netconf session to %1$s is disconnected", id.getName() ) );
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();
183 public void onSessionDown(final NetconfClientSession session, final Exception e) {
184 LOG.warn("{}: Session went down", id, e);
189 public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
190 LOG.warn("{}: Session terminated {}", id, reason);
191 tearDown( reason.getErrorMessage() );
195 public void close() {
196 // Cancel reconnect if in progress
197 if(initFuture != null) {
198 initFuture.cancel(false);
200 // Disconnect from device
201 if(session != null) {
203 // tear down not necessary, called indirectly by above close
208 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
210 * Dispatch between notifications and messages. Messages need to be processed
211 * with lock held, notifications do not.
213 if (isNotification(message)) {
214 processNotification(message);
216 processMessage(message);
220 private void processMessage(final NetconfMessage message) {
221 Request request = null;
225 request = requests.peek();
226 if (request != null && request.future.isUncancellable()) {
230 LOG.warn("{}: Ignoring unsolicited message {}", id,
235 sessionLock.unlock();
238 if( request != null ) {
240 LOG.debug("{}: Message received {}", id, message);
242 if(LOG.isTraceEnabled()) {
243 LOG.trace( "{}: Matched request: {} to response: {}", id, msgToS( request.request ), msgToS( message ) );
247 NetconfMessageTransformUtil.checkValidReply( request.request, message );
248 } catch (final NetconfDocumentedException e) {
250 "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
251 id, msgToS(request.request), msgToS(message), e);
253 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
254 .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
256 //recursively processing message to eventually find matching request
257 processMessage(message);
263 NetconfMessageTransformUtil.checkSuccessReply(message);
264 } catch(final NetconfDocumentedException e) {
266 "{}: Error reply from remote device, request: {}, response: {}",
267 id, msgToS(request.request), msgToS(message), e);
269 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
270 .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
274 request.future.set( RpcResultBuilder.success( message ).build() );
278 private static String msgToS(final NetconfMessage msg) {
279 return XmlUtil.toString(msg.getDocument());
283 public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
286 return sendRequestWithLock( message, rpc );
288 sessionLock.unlock();
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));
298 if (session == null) {
299 LOG.warn("{}: Session is disconnected, failing RPC request {}",
301 return Futures.immediateFuture( createSessionDownRpcResult() );
304 final Request req = new Request( new UncancellableFuture<RpcResult<NetconfMessage>>(true),
308 session.sendMessage(req.request).addListener(new FutureListener<Void>() {
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()),
317 if( future.cause() != null ) {
318 req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
319 future.cause().getLocalizedMessage() ) );
321 req.future.set( createSessionDownRpcResult() ); // assume session is down
323 req.future.setException( future.cause() );
326 LOG.trace("Finished sending request {}", req.request);
334 private void processNotification(final NetconfMessage notification) {
335 if(LOG.isTraceEnabled()) {
336 LOG.trace("{}: Notification received: {}", id, notification);
339 remoteDevice.onNotification(notification);
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()) ;
347 private static final class Request {
348 final UncancellableFuture<RpcResult<NetconfMessage>> future;
349 final NetconfMessage request;
351 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
352 final NetconfMessage request) {
353 this.future = future;
354 this.request = request;