2 * Copyright (c) 2015 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.sal;
10 import static com.google.common.base.Preconditions.checkState;
11 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps.getSourceNode;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_CONFIG_NODEID;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME;
14 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import com.google.common.util.concurrent.MoreExecutors;
20 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
21 import java.util.concurrent.ScheduledExecutorService;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
24 import java.util.concurrent.atomic.AtomicBoolean;
25 import org.opendaylight.mdsal.dom.api.DOMActionService;
26 import org.opendaylight.mdsal.dom.api.DOMNotification;
27 import org.opendaylight.mdsal.dom.api.DOMRpcAvailabilityListener;
28 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
29 import org.opendaylight.mdsal.dom.api.DOMRpcService;
30 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
31 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
32 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
33 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
34 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
35 import org.opendaylight.yangtools.concepts.ListenerRegistration;
36 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 * SalFacade proxy that invokes keepalive RPCs to prevent session shutdown from remote device
45 * and to detect incorrect session drops (netconf session is inactive, but TCP/SSH connection is still present).
46 * The keepalive RPC is a get-config with empty filter.
48 public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSessionPreferences> {
50 private static final Logger LOG = LoggerFactory.getLogger(KeepaliveSalFacade.class);
52 // 2 minutes keepalive delay by default
53 private static final long DEFAULT_DELAY = TimeUnit.MINUTES.toSeconds(2);
55 // 1 minute transaction timeout by default
56 private static final long DEFAULT_TRANSACTION_TIMEOUT_MILLI = TimeUnit.MILLISECONDS.toMillis(60000);
58 private final RemoteDeviceId id;
59 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
60 private final ScheduledExecutorService executor;
61 private final long keepaliveDelaySeconds;
62 private final ResetKeepalive resetKeepaliveTask;
63 private final long defaultRequestTimeoutMillis;
65 private volatile NetconfDeviceCommunicator listener;
66 private volatile ScheduledFuture<?> currentKeepalive;
67 private volatile DOMRpcService currentDeviceRpc;
68 private final AtomicBoolean lastKeepAliveSucceeded = new AtomicBoolean(false);
70 public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
71 final ScheduledExecutorService executor, final long keepaliveDelaySeconds,
72 final long defaultRequestTimeoutMillis) {
74 this.salFacade = salFacade;
75 this.executor = executor;
76 this.keepaliveDelaySeconds = keepaliveDelaySeconds;
77 this.defaultRequestTimeoutMillis = defaultRequestTimeoutMillis;
78 this.resetKeepaliveTask = new ResetKeepalive();
81 public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
82 final ScheduledExecutorService executor) {
83 this(id, salFacade, executor, DEFAULT_DELAY, DEFAULT_TRANSACTION_TIMEOUT_MILLI);
87 * Set the netconf session listener whenever ready.
89 * @param listener netconf session listener
91 public void setListener(final NetconfDeviceCommunicator listener) {
92 this.listener = listener;
96 * Just cancel current keepalive task if exists.
97 * If its already started, let it finish ... not such a big deal.
100 * Then schedule next keepalive.
102 synchronized void resetKeepalive() {
103 LOG.trace("{}: Resetting netconf keepalive timer", id);
104 if (currentKeepalive != null) {
105 currentKeepalive.cancel(false);
107 LOG.trace("{}: Keepalive does not exist", id);
109 scheduleKeepalives();
113 * Cancel current keepalive and also reset current deviceRpc.
115 private synchronized void stopKeepalives() {
116 if (currentKeepalive != null) {
117 currentKeepalive.cancel(false);
119 currentDeviceRpc = null;
123 checkState(listener != null, "%s: Unable to reconnect, session listener is missing", id);
125 LOG.info("{}: Reconnecting inactive netconf session", id);
126 listener.disconnect();
130 public void onDeviceConnected(final MountPointContext remoteSchemaContext,
131 final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
132 onDeviceConnected(remoteSchemaContext, netconfSessionPreferences, deviceRpc, null);
136 public void onDeviceConnected(final MountPointContext remoteSchemaContext,
137 final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc,
138 final DOMActionService deviceAction) {
139 this.currentDeviceRpc = deviceRpc;
140 final DOMRpcService deviceRpc1 =
141 new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor,
142 new ResponseWaitingScheduler());
144 salFacade.onDeviceConnected(remoteSchemaContext, netconfSessionPreferences, deviceRpc1, deviceAction);
146 LOG.debug("{}: Netconf session initiated, starting keepalives", id);
150 private void scheduleKeepalives() {
151 lastKeepAliveSucceeded.set(true);
152 checkState(currentDeviceRpc != null);
153 LOG.trace("{}: Scheduling keepalives every {} {}", id, keepaliveDelaySeconds, TimeUnit.SECONDS);
154 currentKeepalive = executor.scheduleWithFixedDelay(new Keepalive(),
155 keepaliveDelaySeconds, keepaliveDelaySeconds, TimeUnit.SECONDS);
159 public void onDeviceDisconnected() {
161 salFacade.onDeviceDisconnected();
165 public void onDeviceFailed(final Throwable throwable) {
167 salFacade.onDeviceFailed(throwable);
171 public void onNotification(final DOMNotification domNotification) {
173 salFacade.onNotification(domNotification);
177 public void close() {
182 // Keepalive RPC static resources
183 private static final ContainerNode KEEPALIVE_PAYLOAD = NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_NODEID,
184 getSourceNode(NETCONF_RUNNING_QNAME), NetconfMessageTransformUtil.EMPTY_FILTER);
187 * Invoke keepalive RPC and check the response. In case of any received response the keepalive
188 * is considered successful and schedules next keepalive with a fixed delay. If the response is unsuccessful (no
189 * response received, or the rcp could not even be sent) immediate reconnect is triggered as netconf session
190 * is considered inactive/failed.
192 private class Keepalive implements Runnable, FutureCallback<DOMRpcResult> {
196 LOG.trace("{}: Invoking keepalive RPC", id);
199 final boolean lastJobSucceeded = lastKeepAliveSucceeded.getAndSet(false);
200 if (!lastJobSucceeded) {
201 onFailure(new IllegalStateException("Previous keepalive timed out"));
203 Futures.addCallback(currentDeviceRpc.invokeRpc(NETCONF_GET_CONFIG_QNAME, KEEPALIVE_PAYLOAD), this,
204 MoreExecutors.directExecutor());
206 } catch (final NullPointerException e) {
207 LOG.debug("{}: Skipping keepalive while reconnecting", id);
208 // Empty catch block intentional
209 // Do nothing. The currentDeviceRpc was null and it means we hit the reconnect window and
210 // attempted to send keepalive while we were reconnecting. Next keepalive will be scheduled
211 // after reconnect so no action necessary here.
215 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE",
216 justification = "Unrecognised NullableDecl")
218 public void onSuccess(final DOMRpcResult result) {
219 // No matter what response we got, rpc-reply or rpc-error,
220 // we got it from device so the netconf session is OK
221 if (result == null) {
222 LOG.warn("{} Keepalive RPC returned null with response. Reconnecting netconf session", id);
227 if (result.getResult() != null) {
228 lastKeepAliveSucceeded.set(true);
229 } else if (result.getErrors() != null) {
230 LOG.warn("{}: Keepalive RPC failed with error: {}", id, result.getErrors());
231 lastKeepAliveSucceeded.set(true);
233 LOG.warn("{} Keepalive RPC returned null with response. Reconnecting netconf session", id);
239 public void onFailure(final Throwable throwable) {
240 LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, throwable);
246 * Reset keepalive after each RPC response received.
248 private class ResetKeepalive implements FutureCallback<DOMRpcResult> {
250 public void onSuccess(final DOMRpcResult result) {
251 // No matter what response we got,
252 // rpc-reply or rpc-error, we got it from device so the netconf session is OK.
257 public void onFailure(final Throwable throwable) {
258 // User/Application RPC failed (The RPC did not reach the remote device or ..
259 // TODO what other reasons could cause this ?)
260 // There is no point in keeping this session. Reconnect.
261 LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, throwable);
266 private final class ResponseWaitingScheduler {
268 private ScheduledFuture<?> schedule;
270 public void initScheduler(final Runnable runnable) {
272 //Listening on the result should be done before the keepalive rpc will be send
273 final long delay = keepaliveDelaySeconds * 1000 - 500;
274 schedule = executor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
277 public void stopScheduler() {
278 if (schedule != null) {
279 schedule.cancel(true);
281 LOG.trace("Scheduler does not exist.");
286 private static final class ResponseWaiting implements Runnable {
288 private final ListenableFuture<? extends DOMRpcResult> rpcResultFuture;
289 private final ResponseWaitingScheduler responseWaitingScheduler;
291 ResponseWaiting(final ResponseWaitingScheduler responseWaitingScheduler,
292 final ListenableFuture<? extends DOMRpcResult> rpcResultFuture) {
293 this.responseWaitingScheduler = responseWaitingScheduler;
294 this.rpcResultFuture = rpcResultFuture;
297 public void start() {
298 LOG.trace("Start to waiting for result.");
299 responseWaitingScheduler.initScheduler(this);
303 LOG.info("Stop to waiting for result.");
304 responseWaitingScheduler.stopScheduler();
309 if (!rpcResultFuture.isCancelled() && !rpcResultFuture.isDone()) {
310 LOG.trace("Waiting for result");
311 responseWaitingScheduler.initScheduler(this);
313 LOG.trace("Result has been cancelled or done.");
319 * Request timeout task is called once the defaultRequestTimeoutMillis is
320 * reached. At this moment, if the request is not yet finished, we cancel
323 private static final class RequestTimeoutTask implements Runnable {
324 private final ListenableFuture<? extends DOMRpcResult> rpcResultFuture;
325 private final ResponseWaiting responseWaiting;
327 RequestTimeoutTask(final ListenableFuture<? extends DOMRpcResult> rpcResultFuture,
328 final ResponseWaiting responseWaiting) {
329 this.rpcResultFuture = rpcResultFuture;
330 this.responseWaiting = responseWaiting;
335 if (!rpcResultFuture.isDone()) {
336 rpcResultFuture.cancel(true);
338 if (responseWaiting != null) {
339 responseWaiting.stop();
345 * DOMRpcService proxy that attaches reset-keepalive-task and schedule
346 * request-timeout-task to each RPC invocation.
348 public static final class KeepaliveDOMRpcService implements DOMRpcService {
349 private final DOMRpcService deviceRpc;
350 private final ResetKeepalive resetKeepaliveTask;
351 private final long defaultRequestTimeoutMillis;
352 private final ScheduledExecutorService executor;
353 private final ResponseWaitingScheduler responseWaitingScheduler;
355 KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask,
356 final long defaultRequestTimeoutMillis, final ScheduledExecutorService executor,
357 final ResponseWaitingScheduler responseWaitingScheduler) {
358 this.deviceRpc = deviceRpc;
359 this.resetKeepaliveTask = resetKeepaliveTask;
360 this.defaultRequestTimeoutMillis = defaultRequestTimeoutMillis;
361 this.executor = executor;
362 this.responseWaitingScheduler = responseWaitingScheduler;
365 public DOMRpcService getDeviceRpc() {
370 public ListenableFuture<? extends DOMRpcResult> invokeRpc(final QName type, final NormalizedNode<?, ?> input) {
371 final ListenableFuture<? extends DOMRpcResult> rpcResultFuture = deviceRpc.invokeRpc(type, input);
372 final ResponseWaiting responseWaiting = new ResponseWaiting(responseWaitingScheduler, rpcResultFuture);
373 responseWaiting.start();
374 Futures.addCallback(rpcResultFuture, resetKeepaliveTask, MoreExecutors.directExecutor());
376 final RequestTimeoutTask timeoutTask = new RequestTimeoutTask(rpcResultFuture, responseWaiting);
377 executor.schedule(timeoutTask, defaultRequestTimeoutMillis, TimeUnit.MILLISECONDS);
379 return rpcResultFuture;
383 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(final T listener) {
384 // There is no real communication with the device (yet), no reset here
385 return deviceRpc.registerRpcListener(listener);