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.Strings;
11 import com.google.common.util.concurrent.ListenableFuture;
12 import com.google.common.util.concurrent.SettableFuture;
13 import io.netty.util.concurrent.Future;
14 import java.io.EOFException;
15 import java.util.ArrayDeque;
16 import java.util.ArrayList;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Optional;
20 import java.util.Queue;
21 import java.util.concurrent.Semaphore;
22 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
23 import java.util.concurrent.locks.Lock;
24 import java.util.concurrent.locks.ReentrantLock;
25 import org.opendaylight.netconf.api.FailedNetconfMessage;
26 import org.opendaylight.netconf.api.NetconfDocumentedException;
27 import org.opendaylight.netconf.api.NetconfMessage;
28 import org.opendaylight.netconf.api.NetconfTerminationReason;
29 import org.opendaylight.netconf.api.xml.XmlElement;
30 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
31 import org.opendaylight.netconf.api.xml.XmlUtil;
32 import org.opendaylight.netconf.client.NetconfClientDispatcher;
33 import org.opendaylight.netconf.client.NetconfClientSession;
34 import org.opendaylight.netconf.client.NetconfClientSessionListener;
35 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
36 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
37 import org.opendaylight.netconf.sal.connect.api.RemoteDevice;
38 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceCommunicator;
39 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
40 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
41 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
42 import org.opendaylight.yangtools.yang.common.ErrorTag;
43 import org.opendaylight.yangtools.yang.common.QName;
44 import org.opendaylight.yangtools.yang.common.RpcError;
45 import org.opendaylight.yangtools.yang.common.RpcResult;
46 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
50 public class NetconfDeviceCommunicator
51 implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
53 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
55 protected final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice;
56 private final Optional<UserPreferences> overrideNetconfCapabilities;
57 protected final RemoteDeviceId id;
58 private final Lock sessionLock = new ReentrantLock();
60 private final Semaphore semaphore;
61 private final int concurentRpcMsgs;
63 private final Queue<Request> requests = new ArrayDeque<>();
64 private NetconfClientSession currentSession;
66 private final SettableFuture<NetconfDeviceCapabilities> firstConnectionFuture;
67 private Future<?> initFuture;
69 // isSessionClosing indicates a close operation on the session is issued and
70 // tearDown will surely be called later to finish the close.
71 // Used to allow only one thread to enter tearDown and other threads should
72 // NOT enter it simultaneously and should end its close operation without
73 // calling tearDown to release the locks they hold to avoid deadlock.
74 private static final AtomicIntegerFieldUpdater<NetconfDeviceCommunicator> CLOSING_UPDATER =
75 AtomicIntegerFieldUpdater.newUpdater(NetconfDeviceCommunicator.class, "closing");
76 private volatile int closing;
78 public boolean isSessionClosing() {
82 public NetconfDeviceCommunicator(
83 final RemoteDeviceId id,
84 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
85 final UserPreferences netconfSessionPreferences, final int rpcMessageLimit) {
86 this(id, remoteDevice, Optional.of(netconfSessionPreferences), rpcMessageLimit);
89 public NetconfDeviceCommunicator(
90 final RemoteDeviceId id,
91 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
92 final int rpcMessageLimit) {
93 this(id, remoteDevice, Optional.empty(), rpcMessageLimit);
96 private NetconfDeviceCommunicator(
97 final RemoteDeviceId id,
98 final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
99 final Optional<UserPreferences> overrideNetconfCapabilities, final int rpcMessageLimit) {
100 this.concurentRpcMsgs = rpcMessageLimit;
102 this.remoteDevice = remoteDevice;
103 this.overrideNetconfCapabilities = overrideNetconfCapabilities;
104 this.firstConnectionFuture = SettableFuture.create();
105 this.semaphore = rpcMessageLimit > 0 ? new Semaphore(rpcMessageLimit) : null;
109 public void onSessionUp(final NetconfClientSession session) {
112 LOG.debug("{}: Session established", id);
113 currentSession = session;
115 NetconfSessionPreferences netconfSessionPreferences =
116 NetconfSessionPreferences.fromNetconfSession(session);
117 LOG.trace("{}: Session advertised capabilities: {}", id,
118 netconfSessionPreferences);
120 if (overrideNetconfCapabilities.isPresent()) {
121 final NetconfSessionPreferences sessionPreferences = overrideNetconfCapabilities
122 .get().getSessionPreferences();
123 netconfSessionPreferences = overrideNetconfCapabilities.get().moduleBasedCapsOverrided()
124 ? netconfSessionPreferences.replaceModuleCaps(sessionPreferences)
125 : netconfSessionPreferences.addModuleCaps(sessionPreferences);
127 netconfSessionPreferences = overrideNetconfCapabilities.get().nonModuleBasedCapsOverrided()
128 ? netconfSessionPreferences.replaceNonModuleCaps(sessionPreferences)
129 : netconfSessionPreferences.addNonModuleCaps(sessionPreferences);
130 LOG.debug("{}: Session capabilities overridden, capabilities that will be used: {}", id,
131 netconfSessionPreferences);
134 remoteDevice.onRemoteSessionUp(netconfSessionPreferences, this);
135 if (!firstConnectionFuture.isDone()) {
136 firstConnectionFuture.set(netconfSessionPreferences.getNetconfDeviceCapabilities());
139 sessionLock.unlock();
144 * Initialize remote connection.
146 * @param dispatcher {@code NetconfCLientDispatcher}
147 * @param config {@code NetconfClientConfiguration}
148 * @return future that returns succes on first succesfull connection and failure when the underlying
149 * reconnecting strategy runs out of reconnection attempts
151 public ListenableFuture<NetconfDeviceCapabilities> initializeRemoteConnection(
152 final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) {
153 if (config instanceof NetconfReconnectingClientConfiguration) {
154 initFuture = dispatcher.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
156 initFuture = dispatcher.createClient(config);
160 initFuture.addListener(future -> {
161 if (!future.isSuccess() && !future.isCancelled()) {
162 LOG.debug("{}: Connection failed", id, future.cause());
163 NetconfDeviceCommunicator.this.remoteDevice.onRemoteSessionFailed(future.cause());
164 if (firstConnectionFuture.isDone()) {
165 firstConnectionFuture.setException(future.cause());
169 return firstConnectionFuture;
172 public void disconnect() {
173 // If session is already in closing, no need to close it again
174 if (currentSession != null && startClosing() && currentSession.isUp()) {
175 currentSession.close();
179 private void tearDown(final String reason) {
180 if (!isSessionClosing()) {
181 LOG.warn("It's curious that no one to close the session but tearDown is called!");
183 LOG.debug("Tearing down {}", reason);
184 final List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = new ArrayList<>();
187 if (currentSession != null) {
188 currentSession = null;
190 * Walk all requests, check if they have been executing
191 * or cancelled and remove them from the queue.
193 final Iterator<Request> it = requests.iterator();
194 while (it.hasNext()) {
195 final Request r = it.next();
196 if (r.future.isUncancellable()) {
197 futuresToCancel.add(r.future);
199 } else if (r.future.isCancelled()) {
200 // This just does some house-cleaning
205 remoteDevice.onRemoteSessionDown();
208 sessionLock.unlock();
211 // Notify pending request futures outside of the sessionLock to avoid unnecessarily
212 // blocking the caller.
213 for (final UncancellableFuture<RpcResult<NetconfMessage>> future : futuresToCancel) {
214 if (Strings.isNullOrEmpty(reason)) {
215 future.set(createSessionDownRpcResult());
217 future.set(createErrorRpcResult(RpcError.ErrorType.TRANSPORT, reason));
224 private RpcResult<NetconfMessage> createSessionDownRpcResult() {
225 return createErrorRpcResult(RpcError.ErrorType.TRANSPORT,
226 String.format("The netconf session to %1$s is disconnected", id.getName()));
229 private static RpcResult<NetconfMessage> createErrorRpcResult(final RpcError.ErrorType errorType,
230 final String message) {
231 return RpcResultBuilder.<NetconfMessage>failed()
232 .withError(errorType, ErrorTag.OPERATION_FAILED.elementBody(), message).build();
236 public void onSessionDown(final NetconfClientSession session, final Exception exception) {
237 // If session is already in closing, no need to call tearDown again.
238 if (startClosing()) {
239 if (exception instanceof EOFException) {
240 LOG.info("{}: Session went down: {}", id, exception.getMessage());
242 LOG.warn("{}: Session went down", id, exception);
249 public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
250 // onSessionTerminated is called directly by disconnect, no need to compare and set isSessionClosing.
251 LOG.warn("{}: Session terminated {}", id, reason);
252 tearDown(reason.getErrorMessage());
256 public void close() {
257 // Cancel reconnect if in progress
258 if (initFuture != null) {
259 initFuture.cancel(false);
261 // Disconnect from device
262 // tear down not necessary, called indirectly by the close in disconnect()
267 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
269 * Dispatch between notifications and messages. Messages need to be processed
270 * with lock held, notifications do not.
272 if (isNotification(message)) {
273 processNotification(message);
275 processMessage(message);
279 private void processMessage(final NetconfMessage message) {
280 Request request = null;
284 request = requests.peek();
285 if (request != null && request.future.isUncancellable()) {
286 request = requests.poll();
287 // we have just removed one request from the queue
288 // we can also release one permit
289 if (semaphore != null) {
294 LOG.warn("{}: Ignoring unsolicited message {}", id,
298 sessionLock.unlock();
301 if (request != null) {
303 if (FailedNetconfMessage.class.isInstance(message)) {
304 request.future.set(NetconfMessageTransformUtil.toRpcResult((FailedNetconfMessage) message));
308 LOG.debug("{}: Message received {}", id, message);
310 if (LOG.isTraceEnabled()) {
311 LOG.trace("{}: Matched request: {} to response: {}", id, msgToS(request.request), msgToS(message));
315 NetconfMessageTransformUtil.checkValidReply(request.request, message);
316 } catch (final NetconfDocumentedException e) {
318 "{}: Invalid request-reply match,"
319 + "reply message contains different message-id, request: {}, response: {}",
320 id, msgToS(request.request), msgToS(message), e);
322 request.future.set(RpcResultBuilder.<NetconfMessage>failed()
323 .withRpcError(NetconfMessageTransformUtil.toRpcError(e)).build());
325 //recursively processing message to eventually find matching request
326 processMessage(message);
332 NetconfMessageTransformUtil.checkSuccessReply(message);
333 } catch (final NetconfDocumentedException e) {
335 "{}: Error reply from remote device, request: {}, response: {}",
336 id, msgToS(request.request), msgToS(message), e);
338 request.future.set(RpcResultBuilder.<NetconfMessage>failed()
339 .withRpcError(NetconfMessageTransformUtil.toRpcError(e)).build());
343 request.future.set(RpcResultBuilder.success(message).build());
347 private static String msgToS(final NetconfMessage msg) {
348 return XmlUtil.toString(msg.getDocument());
352 public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
355 if (semaphore != null && !semaphore.tryAcquire()) {
356 LOG.warn("Limit of concurrent rpc messages was reached (limit: {}). Rpc reply message is needed. "
357 + "Discarding request of Netconf device with id: {}", concurentRpcMsgs, id.getName());
358 return FluentFutures.immediateFailedFluentFuture(new NetconfDocumentedException(
359 "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs
360 + ") waiting for emptying the queue of Netconf device with id: " + id.getName()));
363 return sendRequestWithLock(message, rpc);
365 sessionLock.unlock();
369 private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(final NetconfMessage message,
371 if (LOG.isTraceEnabled()) {
372 LOG.trace("{}: Sending message {}", id, msgToS(message));
375 if (currentSession == null) {
376 LOG.warn("{}: Session is disconnected, failing RPC request {}",
378 return FluentFutures.immediateFluentFuture(createSessionDownRpcResult());
381 final Request req = new Request(new UncancellableFuture<>(true), message);
384 currentSession.sendMessage(req.request).addListener(future -> {
385 if (!future.isSuccess()) {
386 // We expect that a session down will occur at this point
387 LOG.debug("{}: Failed to send request {}", id,
388 XmlUtil.toString(req.request.getDocument()),
391 if (future.cause() != null) {
392 req.future.set(createErrorRpcResult(RpcError.ErrorType.TRANSPORT,
393 future.cause().getLocalizedMessage()));
395 req.future.set(createSessionDownRpcResult()); // assume session is down
397 req.future.setException(future.cause());
399 LOG.trace("Finished sending request {}", req.request);
406 private void processNotification(final NetconfMessage notification) {
407 if (LOG.isTraceEnabled()) {
408 LOG.trace("{}: Notification received: {}", id, notification);
411 remoteDevice.onNotification(notification);
414 private static boolean isNotification(final NetconfMessage message) {
415 if (message.getDocument() == null) {
416 // We have no message, which mean we have a FailedNetconfMessage
419 final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
420 return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
423 private static final class Request {
424 final UncancellableFuture<RpcResult<NetconfMessage>> future;
425 final NetconfMessage request;
427 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
428 final NetconfMessage request) {
429 this.future = future;
430 this.request = request;
434 private boolean startClosing() {
435 return CLOSING_UPDATER.compareAndSet(this, 0, 1);