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<UserPreferences> 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 UserPreferences 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.<UserPreferences>absent());
73 private NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
74 final Optional<UserPreferences> 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 = overrideNetconfCapabilities.get().isOverride() ?
95 netconfSessionPreferences.replaceModuleCaps(overrideNetconfCapabilities.get().getSessionPreferences()) :
96 netconfSessionPreferences.addModuleCaps(overrideNetconfCapabilities.get().getSessionPreferences());
98 "{}: Session capabilities overridden, capabilities that will be used: {}",
99 id, netconfSessionPreferences);
103 remoteDevice.onRemoteSessionUp(netconfSessionPreferences, this);
104 if (!firstConnectionFuture.isDone()) {
105 firstConnectionFuture.set(netconfSessionPreferences.getNetconfDeviceCapabilities());
109 sessionLock.unlock();
117 * @return future that returns succes on first succesfull connection and failure when the underlying
118 * reconnecting strategy runs out of reconnection attempts
120 public ListenableFuture<NetconfDeviceCapabilities> initializeRemoteConnection(final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) {
121 if(config instanceof NetconfReconnectingClientConfiguration) {
122 initFuture = dispatcher.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
124 initFuture = dispatcher.createClient(config);
128 initFuture.addListener(new GenericFutureListener<Future<Object>>(){
131 public void operationComplete(Future<Object> future) throws Exception {
132 if (!future.isSuccess() && !future.isCancelled()) {
133 LOG.debug("{}: Connection failed", id, future.cause());
134 NetconfDeviceCommunicator.this.remoteDevice.onRemoteSessionFailed(future.cause());
135 if (firstConnectionFuture.isDone()) {
136 firstConnectionFuture.setException(future.cause());
141 return firstConnectionFuture;
144 public void disconnect() {
145 if(session != null) {
150 private void tearDown( String reason ) {
151 LOG.debug("Tearing down {}", reason);
152 List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
155 if( session != null ) {
159 * Walk all requests, check if they have been executing
160 * or cancelled and remove them from the queue.
162 final Iterator<Request> it = requests.iterator();
163 while (it.hasNext()) {
164 final Request r = it.next();
165 if (r.future.isUncancellable()) {
166 futuresToCancel.add( r.future );
168 } else if (r.future.isCancelled()) {
169 // This just does some house-cleaning
174 remoteDevice.onRemoteSessionDown();
178 sessionLock.unlock();
181 // Notify pending request futures outside of the sessionLock to avoid unnecessarily
182 // blocking the caller.
183 for( UncancellableFuture<RpcResult<NetconfMessage>> future: futuresToCancel ) {
184 if( Strings.isNullOrEmpty( reason ) ) {
185 future.set( createSessionDownRpcResult() );
187 future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) );
192 private RpcResult<NetconfMessage> createSessionDownRpcResult() {
193 return createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
194 String.format( "The netconf session to %1$s is disconnected", id.getName() ) );
197 private RpcResult<NetconfMessage> createErrorRpcResult( RpcError.ErrorType errorType, String message ) {
198 return RpcResultBuilder.<NetconfMessage>failed()
199 .withError(errorType, NetconfDocumentedException.ErrorTag.operation_failed.getTagValue(), message).build();
203 public void onSessionDown(final NetconfClientSession session, final Exception e) {
204 LOG.warn("{}: Session went down", id, e);
209 public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
210 LOG.warn("{}: Session terminated {}", id, reason);
211 tearDown( reason.getErrorMessage() );
215 public void close() {
216 // Cancel reconnect if in progress
217 if(initFuture != null) {
218 initFuture.cancel(false);
220 // Disconnect from device
221 if(session != null) {
223 // tear down not necessary, called indirectly by above close
228 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
230 * Dispatch between notifications and messages. Messages need to be processed
231 * with lock held, notifications do not.
233 if (isNotification(message)) {
234 processNotification(message);
236 processMessage(message);
240 private void processMessage(final NetconfMessage message) {
241 Request request = null;
245 request = requests.peek();
246 if (request != null && request.future.isUncancellable()) {
250 LOG.warn("{}: Ignoring unsolicited message {}", id,
255 sessionLock.unlock();
258 if( request != null ) {
260 LOG.debug("{}: Message received {}", id, message);
262 if(LOG.isTraceEnabled()) {
263 LOG.trace( "{}: Matched request: {} to response: {}", id, msgToS( request.request ), msgToS( message ) );
267 NetconfMessageTransformUtil.checkValidReply( request.request, message );
268 } catch (final NetconfDocumentedException e) {
270 "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
271 id, msgToS(request.request), msgToS(message), e);
273 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
274 .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
276 //recursively processing message to eventually find matching request
277 processMessage(message);
283 NetconfMessageTransformUtil.checkSuccessReply(message);
284 } catch(final NetconfDocumentedException e) {
286 "{}: Error reply from remote device, request: {}, response: {}",
287 id, msgToS(request.request), msgToS(message), e);
289 request.future.set( RpcResultBuilder.<NetconfMessage>failed()
290 .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
294 request.future.set( RpcResultBuilder.success( message ).build() );
298 private static String msgToS(final NetconfMessage msg) {
299 return XmlUtil.toString(msg.getDocument());
303 public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
306 return sendRequestWithLock( message, rpc );
308 sessionLock.unlock();
312 private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(
313 final NetconfMessage message, final QName rpc) {
314 if(LOG.isTraceEnabled()) {
315 LOG.trace("{}: Sending message {}", id, msgToS(message));
318 if (session == null) {
319 LOG.warn("{}: Session is disconnected, failing RPC request {}",
321 return Futures.immediateFuture( createSessionDownRpcResult() );
324 final Request req = new Request( new UncancellableFuture<RpcResult<NetconfMessage>>(true),
328 session.sendMessage(req.request).addListener(new FutureListener<Void>() {
330 public void operationComplete(final Future<Void> future) throws Exception {
331 if( !future.isSuccess() ) {
332 // We expect that a session down will occur at this point
333 LOG.debug("{}: Failed to send request {}", id,
334 XmlUtil.toString(req.request.getDocument()),
337 if( future.cause() != null ) {
338 req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
339 future.cause().getLocalizedMessage() ) );
341 req.future.set( createSessionDownRpcResult() ); // assume session is down
343 req.future.setException( future.cause() );
346 LOG.trace("Finished sending request {}", req.request);
354 private void processNotification(final NetconfMessage notification) {
355 if(LOG.isTraceEnabled()) {
356 LOG.trace("{}: Notification received: {}", id, notification);
359 remoteDevice.onNotification(notification);
362 private static boolean isNotification(final NetconfMessage message) {
363 final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
364 return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
367 private static final class Request {
368 final UncancellableFuture<RpcResult<NetconfMessage>> future;
369 final NetconfMessage request;
371 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
372 final NetconfMessage request) {
373 this.future = future;
374 this.request = request;