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 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;
45 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
47 private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
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();
54 private final Queue<Request> requests = new ArrayDeque<>();
55 private NetconfClientSession session;
57 public NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice,
58 final NetconfSessionCapabilities netconfSessionCapabilities) {
59 this(id, remoteDevice, Optional.of(netconfSessionCapabilities));
62 public NetconfDeviceCommunicator(final RemoteDeviceId id,
63 final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice) {
64 this(id, remoteDevice, Optional.<NetconfSessionCapabilities>absent());
67 private NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice,
68 final Optional<NetconfSessionCapabilities> overrideNetconfCapabilities) {
70 this.remoteDevice = remoteDevice;
71 this.overrideNetconfCapabilities = overrideNetconfCapabilities;
75 public void onSessionUp(final NetconfClientSession session) {
78 logger.debug("{}: Session established", id);
79 this.session = session;
81 NetconfSessionCapabilities netconfSessionCapabilities =
82 NetconfSessionCapabilities.fromNetconfSession(session);
83 logger.trace("{}: Session advertised capabilities: {}", id, netconfSessionCapabilities);
85 if(overrideNetconfCapabilities.isPresent()) {
86 netconfSessionCapabilities = netconfSessionCapabilities.replaceModuleCaps(overrideNetconfCapabilities.get());
87 logger.debug("{}: Session capabilities overridden, capabilities that will be used: {}", id, netconfSessionCapabilities);
90 remoteDevice.onRemoteSessionUp(netconfSessionCapabilities, this);
97 public void initializeRemoteConnection(final NetconfClientDispatcher dispatch,
98 final NetconfClientConfiguration config) {
99 if(config instanceof NetconfReconnectingClientConfiguration) {
100 dispatch.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
102 dispatch.createClient(config);
106 private void tearDown( String reason ) {
107 List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
110 if( session != null ) {
114 * Walk all requests, check if they have been executing
115 * or cancelled and remove them from the queue.
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 );
123 } else if (r.future.isCancelled()) {
124 // This just does some house-cleaning
129 remoteDevice.onRemoteSessionDown();
133 sessionLock.unlock();
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() );
142 future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) );
147 private RpcResult<NetconfMessage> createSessionDownRpcResult()
149 return createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
150 String.format( "The netconf session to %1$s is disconnected", id.getName() ) );
153 private RpcResult<NetconfMessage> createErrorRpcResult( RpcError.ErrorType errorType, String message )
155 return RpcResultBuilder.<NetconfMessage>failed()
156 .withError( errorType, NetconfDocumentedException.ErrorTag.operation_failed.getTagValue(),
162 public void onSessionDown(final NetconfClientSession session, final Exception e) {
163 logger.warn("{}: Session went down", id, e);
168 public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
169 logger.warn("{}: Session terminated {}", id, reason);
170 tearDown( reason.getErrorMessage() );
174 public void close() {
175 tearDown( String.format( "The netconf session to %1$s has been closed", id.getName() ) );
179 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
181 * Dispatch between notifications and messages. Messages need to be processed
182 * with lock held, notifications do not.
184 if (isNotification(message)) {
185 processNotification(message);
187 processMessage(message);
191 private void processMessage(final NetconfMessage message) {
192 Request request = null;
195 request = requests.peek();
196 if (request.future.isUncancellable()) {
201 logger.warn("{}: Ignoring unsolicited message {}", id, msgToS(message));
205 sessionLock.unlock();
208 if( request != null ) {
210 logger.debug("{}: Message received {}", id, message);
212 if(logger.isTraceEnabled()) {
213 logger.trace( "{}: Matched request: {} to response: {}", id,
214 msgToS( request.request ), msgToS( message ) );
218 NetconfMessageTransformUtil.checkValidReply( request.request, message );
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 );
224 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
225 .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
230 NetconfMessageTransformUtil.checkSuccessReply(message);
232 catch( NetconfDocumentedException e ) {
233 logger.warn( "{}: Error reply from remote device, request: {}, response: {}", id,
234 msgToS( request.request ), msgToS( message ), e );
236 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
237 .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
241 request.future.set( RpcResultBuilder.success( message ).build() );
245 private static String msgToS(final NetconfMessage msg) {
246 return XmlUtil.toString(msg.getDocument());
250 public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(
251 final NetconfMessage message, final QName rpc) {
254 return sendRequestWithLock( message, rpc );
257 sessionLock.unlock();
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));
267 if (session == null) {
268 logger.warn("{}: Session is disconnected, failing RPC request {}", id, message);
269 return Futures.immediateFuture( createSessionDownRpcResult() );
272 final Request req = new Request( new UncancellableFuture<RpcResult<NetconfMessage>>(true),
276 session.sendMessage(req.request).addListener(new FutureListener<Void>() {
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() );
284 if( future.cause() != null ) {
285 req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
286 future.cause().getLocalizedMessage() ) );
288 req.future.set( createSessionDownRpcResult() ); // assume session is down
290 req.future.setException( future.cause() );
293 logger.trace( "Finished sending request {}", req.request );
301 private void processNotification(final NetconfMessage notification) {
302 logger.debug("{}: Notification received: {}", id, notification);
304 if(logger.isTraceEnabled()) {
305 logger.trace("{}: Notification received: {}", id, msgToS(notification));
308 remoteDevice.onNotification(notification);
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()) ;
316 private static final class Request {
317 final UncancellableFuture<RpcResult<NetconfMessage>> future;
318 final NetconfMessage request;
320 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
321 final NetconfMessage request) {
322 this.future = future;
323 this.request = request;