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.client.mdsal;
10 import com.google.common.base.Strings;
11 import com.google.common.collect.ImmutableMap;
12 import com.google.common.util.concurrent.Futures;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import com.google.common.util.concurrent.SettableFuture;
15 import io.netty.util.concurrent.Future;
16 import java.io.EOFException;
17 import java.util.ArrayDeque;
18 import java.util.ArrayList;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.Queue;
22 import java.util.concurrent.Semaphore;
23 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
24 import java.util.concurrent.locks.Lock;
25 import java.util.concurrent.locks.ReentrantLock;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.netconf.api.DocumentedException;
28 import org.opendaylight.netconf.api.NetconfMessage;
29 import org.opendaylight.netconf.api.NetconfTerminationReason;
30 import org.opendaylight.netconf.api.xml.XmlElement;
31 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
32 import org.opendaylight.netconf.api.xml.XmlUtil;
33 import org.opendaylight.netconf.client.NetconfClientDispatcher;
34 import org.opendaylight.netconf.client.NetconfClientSession;
35 import org.opendaylight.netconf.client.NetconfClientSessionListener;
36 import org.opendaylight.netconf.client.NetconfMessageUtil;
37 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
38 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
39 import org.opendaylight.netconf.client.mdsal.api.NetconfSessionPreferences;
40 import org.opendaylight.netconf.client.mdsal.api.RemoteDevice;
41 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceCommunicator;
42 import org.opendaylight.netconf.client.mdsal.api.RemoteDeviceId;
43 import org.opendaylight.yangtools.yang.common.Empty;
44 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
45 import org.opendaylight.yangtools.yang.common.ErrorTag;
46 import org.opendaylight.yangtools.yang.common.ErrorType;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.common.RpcError;
49 import org.opendaylight.yangtools.yang.common.RpcResult;
50 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator {
55 private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
57 protected final RemoteDevice<NetconfDeviceCommunicator> remoteDevice;
58 private final @Nullable UserPreferences overrideNetconfCapabilities;
59 protected final RemoteDeviceId id;
60 private final Lock sessionLock = new ReentrantLock();
62 private final Semaphore semaphore;
63 private final int concurentRpcMsgs;
65 private final Queue<Request> requests = new ArrayDeque<>();
66 private NetconfClientSession currentSession;
68 private final SettableFuture<Empty> firstConnectionFuture = SettableFuture.create();
69 private Future<?> taskFuture;
71 // isSessionClosing indicates a close operation on the session is issued and
72 // tearDown will surely be called later to finish the close.
73 // Used to allow only one thread to enter tearDown and other threads should
74 // NOT enter it simultaneously and should end its close operation without
75 // calling tearDown to release the locks they hold to avoid deadlock.
76 private static final AtomicIntegerFieldUpdater<NetconfDeviceCommunicator> CLOSING_UPDATER =
77 AtomicIntegerFieldUpdater.newUpdater(NetconfDeviceCommunicator.class, "closing");
78 private volatile int closing;
80 public boolean isSessionClosing() {
84 public NetconfDeviceCommunicator(final RemoteDeviceId id,
85 final RemoteDevice<NetconfDeviceCommunicator> remoteDevice, final int rpcMessageLimit) {
86 this(id, remoteDevice, rpcMessageLimit, null);
89 public NetconfDeviceCommunicator(final RemoteDeviceId id,
90 final RemoteDevice<NetconfDeviceCommunicator> remoteDevice, final int rpcMessageLimit,
91 final @Nullable UserPreferences overrideNetconfCapabilities) {
92 concurentRpcMsgs = rpcMessageLimit;
94 this.remoteDevice = remoteDevice;
95 this.overrideNetconfCapabilities = overrideNetconfCapabilities;
96 semaphore = rpcMessageLimit > 0 ? new Semaphore(rpcMessageLimit) : null;
100 public void onSessionUp(final NetconfClientSession session) {
103 LOG.debug("{}: Session established", id);
104 currentSession = session;
106 var netconfSessionPreferences = NetconfSessionPreferences.fromNetconfSession(session);
107 LOG.trace("{}: Session advertised capabilities: {}", id, netconfSessionPreferences);
109 final var localOverride = overrideNetconfCapabilities;
110 if (localOverride != null) {
111 final var sessionPreferences = localOverride.sessionPreferences();
112 netconfSessionPreferences = localOverride.overrideModuleCapabilities()
113 ? netconfSessionPreferences.replaceModuleCaps(sessionPreferences)
114 : netconfSessionPreferences.addModuleCaps(sessionPreferences);
116 netconfSessionPreferences = localOverride.overrideNonModuleCapabilities()
117 ? netconfSessionPreferences.replaceNonModuleCaps(sessionPreferences)
118 : netconfSessionPreferences.addNonModuleCaps(sessionPreferences);
119 LOG.debug("{}: Session capabilities overridden, capabilities that will be used: {}", id,
120 netconfSessionPreferences);
123 remoteDevice.onRemoteSessionUp(netconfSessionPreferences, this);
125 sessionLock.unlock();
128 // FIXME: right, except ... this does not include the device schema setup, so is it really useful?
129 if (!firstConnectionFuture.set(Empty.value())) {
130 LOG.trace("{}: First connection already completed", id);
135 * Initialize remote connection.
137 * @param dispatcher {@code NetconfCLientDispatcher}
138 * @param config {@code NetconfClientConfiguration}
139 * @return a ListenableFuture that returns success on first successful connection and failure when the underlying
140 * reconnecting strategy runs out of reconnection attempts
142 public ListenableFuture<Empty> initializeRemoteConnection(final NetconfClientDispatcher dispatcher,
143 final NetconfClientConfiguration config) {
145 final Future<?> connectFuture;
146 if (config instanceof NetconfReconnectingClientConfiguration) {
147 // FIXME: This is weird. If I understand it correctly we want to know about the first connection so as to
148 // forward error state. Analyze the call graph to understand what is going on here. We really want
149 // to move reconnection away from the socket layer, so that it can properly interface with sessions
150 // and generally has some event-driven state (as all good network glue does). There is a second story
151 // which is we want to avoid duplicate code, so it depends on other users as well.
152 final var future = dispatcher.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
154 connectFuture = future.firstSessionFuture();
156 taskFuture = connectFuture = dispatcher.createClient(config);
159 connectFuture.addListener(future -> {
160 if (!future.isSuccess() && !future.isCancelled()) {
161 LOG.debug("{}: Connection failed", id, future.cause());
162 remoteDevice.onRemoteSessionFailed(future.cause());
163 if (!firstConnectionFuture.isDone()) {
164 firstConnectionFuture.setException(future.cause());
168 return firstConnectionFuture;
171 public void disconnect() {
172 // If session is already in closing, no need to close it again
173 if (currentSession != null && startClosing() && currentSession.isUp()) {
174 currentSession.close();
178 private void tearDown(final String reason) {
179 if (!isSessionClosing()) {
180 LOG.warn("It's curious that no one to close the session but tearDown is called!");
182 LOG.debug("Tearing down {}", reason);
183 final List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = new ArrayList<>();
186 if (currentSession != null) {
187 currentSession = null;
189 * Walk all requests, check if they have been executing
190 * or cancelled and remove them from the queue.
192 final Iterator<Request> it = requests.iterator();
193 while (it.hasNext()) {
194 final Request r = it.next();
195 if (r.future.isUncancellable()) {
196 futuresToCancel.add(r.future);
198 } else if (r.future.isCancelled()) {
199 // This just does some house-cleaning
204 remoteDevice.onRemoteSessionDown();
207 sessionLock.unlock();
210 // Notify pending request futures outside of the sessionLock to avoid unnecessarily
211 // blocking the caller.
212 for (final UncancellableFuture<RpcResult<NetconfMessage>> future : futuresToCancel) {
213 if (Strings.isNullOrEmpty(reason)) {
214 future.set(createSessionDownRpcResult());
216 future.set(createErrorRpcResult(ErrorType.TRANSPORT, reason));
223 private RpcResult<NetconfMessage> createSessionDownRpcResult() {
224 return createErrorRpcResult(ErrorType.TRANSPORT,
225 String.format("The netconf session to %1$s is disconnected", id.name()));
228 private static RpcResult<NetconfMessage> createErrorRpcResult(final ErrorType errorType, final String message) {
229 return RpcResultBuilder.<NetconfMessage>failed()
230 .withError(errorType, ErrorTag.OPERATION_FAILED, message).build();
234 public void onSessionDown(final NetconfClientSession session, final Exception exception) {
235 // If session is already in closing, no need to call tearDown again.
236 if (startClosing()) {
237 if (exception instanceof EOFException) {
238 LOG.info("{}: Session went down: {}", id, exception.getMessage());
240 LOG.warn("{}: Session went down", id, exception);
247 public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
248 // onSessionTerminated is called directly by disconnect, no need to compare and set isSessionClosing.
249 LOG.warn("{}: Session terminated {}", id, reason);
250 tearDown(reason.getErrorMessage());
254 public void close() {
255 // Cancel reconnect if in progress
256 if (taskFuture != null) {
257 taskFuture.cancel(false);
259 // Disconnect from device
260 // tear down not necessary, called indirectly by the close in disconnect()
265 public void onMessage(final NetconfClientSession session, final NetconfMessage message) {
267 * Dispatch between notifications and messages. Messages need to be processed
268 * with lock held, notifications do not.
270 if (isNotification(message)) {
271 processNotification(message);
273 processMessage(message);
278 public void onError(final NetconfClientSession session, final Exception failure) {
279 final Request request = pollRequest();
280 if (request != null) {
281 request.future.set(RpcResultBuilder.<NetconfMessage>failed()
282 .withRpcError(toRpcError(new DocumentedException(failure.getMessage(),
283 ErrorType.APPLICATION, ErrorTag.MALFORMED_MESSAGE, ErrorSeverity.ERROR)))
286 LOG.warn("{}: Ignoring unsolicited failure {}", id, failure.toString());
290 private @Nullable Request pollRequest() {
295 request = requests.peek();
296 if (request != null && request.future.isUncancellable()) {
297 request = requests.poll();
298 // we have just removed one request from the queue
299 // we can also release one permit
300 if (semaphore != null) {
307 sessionLock.unlock();
312 private void processMessage(final NetconfMessage message) {
313 final Request request = pollRequest();
314 if (request == null) {
315 // No matching request, bail out
316 LOG.warn("{}: Ignoring unsolicited message {}", id, msgToS(message));
320 LOG.debug("{}: Message received {}", id, message);
322 if (LOG.isTraceEnabled()) {
323 LOG.trace("{}: Matched request: {} to response: {}", id, msgToS(request.request), msgToS(message));
326 final String inputMsgId = request.request.getDocument().getDocumentElement()
327 .getAttribute(XmlNetconfConstants.MESSAGE_ID);
328 final String outputMsgId = message.getDocument().getDocumentElement()
329 .getAttribute(XmlNetconfConstants.MESSAGE_ID);
330 if (!inputMsgId.equals(outputMsgId)) {
331 // FIXME: we should be able to transform directly to RpcError without an intermediate exception
332 final var ex = new DocumentedException("Response message contained unknown \"message-id\"", null,
333 ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, ErrorSeverity.ERROR,
334 ImmutableMap.of("actual-message-id", outputMsgId, "expected-message-id", inputMsgId));
335 LOG.warn("{}: Invalid request-reply match, reply message contains different message-id, "
336 + "request: {}, response: {}", id, msgToS(request.request), msgToS(message));
338 request.future.set(RpcResultBuilder.<NetconfMessage>failed().withRpcError(toRpcError(ex)).build());
340 // recursively processing message to eventually find matching request
341 processMessage(message);
345 if (NetconfMessageUtil.isErrorMessage(message)) {
346 // FIXME: we should be able to transform directly to RpcError without an intermediate exception
347 final var ex = DocumentedException.fromXMLDocument(message.getDocument());
348 LOG.warn("{}: Error reply from remote device, request: {}, response: {}",
349 id, msgToS(request.request), msgToS(message));
350 request.future.set(RpcResultBuilder.<NetconfMessage>failed().withRpcError(toRpcError(ex)).build());
354 request.future.set(RpcResultBuilder.success(message).build());
357 private static String msgToS(final NetconfMessage msg) {
358 return XmlUtil.toString(msg.getDocument());
361 private static RpcError toRpcError(final DocumentedException ex) {
362 final var errorInfo = ex.getErrorInfo();
363 final String infoString;
364 if (errorInfo != null) {
365 final var sb = new StringBuilder();
366 for (var e : errorInfo.entrySet()) {
367 final var tag = e.getKey();
368 sb.append('<').append(tag).append('>').append(e.getValue()).append("</").append(tag).append('>');
370 infoString = sb.toString();
375 return ex.getErrorSeverity() == ErrorSeverity.ERROR
376 ? RpcResultBuilder.newError(ex.getErrorType(), ex.getErrorTag(), ex.getLocalizedMessage(), null,
377 infoString, ex.getCause())
378 : RpcResultBuilder.newWarning(ex.getErrorType(), ex.getErrorTag(), ex.getLocalizedMessage(), null,
379 infoString, ex.getCause());
383 public ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final NetconfMessage message, final QName rpc) {
386 if (semaphore != null && !semaphore.tryAcquire()) {
387 LOG.warn("Limit of concurrent rpc messages was reached (limit: {}). Rpc reply message is needed. "
388 + "Discarding request of Netconf device with id: {}", concurentRpcMsgs, id.name());
389 return Futures.immediateFailedFuture(new DocumentedException(
390 "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs
391 + ") waiting for emptying the queue of Netconf device with id: " + id.name()));
394 return sendRequestWithLock(message, rpc);
396 sessionLock.unlock();
400 private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(final NetconfMessage message,
402 if (LOG.isTraceEnabled()) {
403 LOG.trace("{}: Sending message {}", id, msgToS(message));
406 if (currentSession == null) {
407 LOG.warn("{}: Session is disconnected, failing RPC request {}",
409 return Futures.immediateFuture(createSessionDownRpcResult());
412 final Request req = new Request(new UncancellableFuture<>(true), message);
415 currentSession.sendMessage(req.request).addListener(future -> {
416 if (!future.isSuccess()) {
417 // We expect that a session down will occur at this point
418 LOG.debug("{}: Failed to send request {}", id,
419 XmlUtil.toString(req.request.getDocument()),
422 if (future.cause() != null) {
423 req.future.set(createErrorRpcResult(ErrorType.TRANSPORT, future.cause().getLocalizedMessage()));
425 req.future.set(createSessionDownRpcResult()); // assume session is down
427 req.future.setException(future.cause());
429 LOG.trace("Finished sending request {}", req.request);
436 private void processNotification(final NetconfMessage notification) {
437 if (LOG.isTraceEnabled()) {
438 LOG.trace("{}: Notification received: {}", id, notification);
441 remoteDevice.onNotification(notification);
444 private static boolean isNotification(final NetconfMessage message) {
445 if (message.getDocument() == null) {
446 // We have no message, which mean we have a FailedNetconfMessage
449 final XmlElement xmle = XmlElement.fromDomDocument(message.getDocument());
450 return XmlNetconfConstants.NOTIFICATION_ELEMENT_NAME.equals(xmle.getName()) ;
453 private static final class Request {
454 final UncancellableFuture<RpcResult<NetconfMessage>> future;
455 final NetconfMessage request;
457 private Request(final UncancellableFuture<RpcResult<NetconfMessage>> future,
458 final NetconfMessage request) {
459 this.future = future;
460 this.request = request;
464 private boolean startClosing() {
465 return CLOSING_UPDATER.compareAndSet(this, 0, 1);