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 org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps.getSourceNode;
11 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME;
12 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME;
13 import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
15 import com.google.common.base.Preconditions;
16 import com.google.common.util.concurrent.CheckedFuture;
17 import com.google.common.util.concurrent.FutureCallback;
18 import com.google.common.util.concurrent.Futures;
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 javax.annotation.Nonnull;
26 import javax.annotation.Nullable;
27 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
28 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
29 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
30 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
31 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
32 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
33 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
34 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
35 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
36 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
37 import org.opendaylight.yangtools.concepts.ListenerRegistration;
38 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * SalFacade proxy that invokes keepalive RPCs to prevent session shutdown from remote device
47 * and to detect incorrect session drops (netconf session is inactive, but TCP/SSH connection is still present).
48 * The keepalive RPC is a get-config with empty filter.
50 public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSessionPreferences> {
52 private static final Logger LOG = LoggerFactory.getLogger(KeepaliveSalFacade.class);
54 // 2 minutes keepalive delay by default
55 private static final long DEFAULT_DELAY = TimeUnit.MINUTES.toSeconds(2);
57 // 1 minute transaction timeout by default
58 private static final long DEFAULT_TRANSACTION_TIMEOUT_MILLI = TimeUnit.MILLISECONDS.toMillis(60000);
60 private final RemoteDeviceId id;
61 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
62 private final ScheduledExecutorService executor;
63 private final long keepaliveDelaySeconds;
64 private final ResetKeepalive resetKeepaliveTask;
65 private final long defaultRequestTimeoutMillis;
67 private volatile NetconfDeviceCommunicator listener;
68 private volatile ScheduledFuture<?> currentKeepalive;
69 private volatile DOMRpcService currentDeviceRpc;
70 private final AtomicBoolean lastKeepAliveSucceeded = new AtomicBoolean(false);
72 public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
73 final ScheduledExecutorService executor, final long keepaliveDelaySeconds,
74 final long defaultRequestTimeoutMillis) {
76 this.salFacade = salFacade;
77 this.executor = executor;
78 this.keepaliveDelaySeconds = keepaliveDelaySeconds;
79 this.defaultRequestTimeoutMillis = defaultRequestTimeoutMillis;
80 this.resetKeepaliveTask = new ResetKeepalive();
83 public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
84 final ScheduledExecutorService executor) {
85 this(id, salFacade, executor, DEFAULT_DELAY, DEFAULT_TRANSACTION_TIMEOUT_MILLI);
89 * Set the netconf session listener whenever ready.
91 * @param listener netconf session listener
93 public void setListener(final NetconfDeviceCommunicator listener) {
94 this.listener = listener;
98 * Just cancel current keepalive task.
99 * If its already started, let it finish ... not such a big deal.
102 * Then schedule next keepalive.
104 void resetKeepalive() {
105 LOG.trace("{}: Resetting netconf keepalive timer", id);
106 if (currentKeepalive != null) {
107 currentKeepalive.cancel(false);
109 scheduleKeepalives();
113 * Cancel current keepalive and also reset current deviceRpc.
115 private void stopKeepalives() {
116 if (currentKeepalive != null) {
117 currentKeepalive.cancel(false);
119 currentDeviceRpc = null;
123 Preconditions.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 SchemaContext remoteSchemaContext,
131 final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
132 this.currentDeviceRpc = deviceRpc;
133 final DOMRpcService deviceRpc1 =
134 new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor);
135 salFacade.onDeviceConnected(remoteSchemaContext, netconfSessionPreferences, deviceRpc1);
137 LOG.debug("{}: Netconf session initiated, starting keepalives", id);
138 scheduleKeepalives();
141 private void scheduleKeepalives() {
142 lastKeepAliveSucceeded.set(true);
143 Preconditions.checkState(currentDeviceRpc != null);
144 LOG.trace("{}: Scheduling keepalives every {} {}", id, keepaliveDelaySeconds, TimeUnit.SECONDS);
145 currentKeepalive = executor.scheduleWithFixedDelay(new Keepalive(),
146 keepaliveDelaySeconds, keepaliveDelaySeconds, TimeUnit.SECONDS);
150 public void onDeviceDisconnected() {
152 salFacade.onDeviceDisconnected();
156 public void onDeviceFailed(final Throwable throwable) {
158 salFacade.onDeviceFailed(throwable);
162 public void onNotification(final DOMNotification domNotification) {
164 salFacade.onNotification(domNotification);
168 public void close() {
173 // Keepalive RPC static resources
174 private static final SchemaPath PATH = toPath(NETCONF_GET_CONFIG_QNAME);
175 private static final ContainerNode KEEPALIVE_PAYLOAD = NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME,
176 getSourceNode(NETCONF_RUNNING_QNAME), NetconfMessageTransformUtil.EMPTY_FILTER);
179 * Invoke keepalive RPC and check the response. In case of any received response the keepalive
180 * is considered successful and schedules next keepalive with a fixed delay. If the response is unsuccessful (no
181 * response received, or the rcp could not even be sent) immediate reconnect is triggered as netconf session
182 * is considered inactive/failed.
184 private class Keepalive implements Runnable, FutureCallback<DOMRpcResult> {
188 LOG.trace("{}: Invoking keepalive RPC", id);
191 boolean lastJobSucceeded = lastKeepAliveSucceeded.getAndSet(false);
192 if (!lastJobSucceeded) {
193 onFailure(new IllegalStateException("Previous keepalive timed out"));
195 Futures.addCallback(currentDeviceRpc.invokeRpc(PATH, KEEPALIVE_PAYLOAD), this,
196 MoreExecutors.directExecutor());
198 } catch (NullPointerException e) {
199 LOG.debug("{}: Skipping keepalive while reconnecting", id);
200 // Empty catch block intentional
201 // Do nothing. The currentDeviceRpc was null and it means we hit the reconnect window and
202 // attempted to send keepalive while we were reconnecting. Next keepalive will be scheduled
203 // after reconnect so no action necessary here.
207 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE",
208 justification = "Unrecognised NullableDecl")
210 public void onSuccess(final DOMRpcResult result) {
211 // No matter what response we got, rpc-reply or rpc-error,
212 // we got it from device so the netconf session is OK
213 if (result != null && result.getResult() != null) {
214 lastKeepAliveSucceeded.set(true);
215 } else if (result != null && result.getErrors() != null) {
216 LOG.warn("{}: Keepalive RPC failed with error: {}", id, result.getErrors());
217 lastKeepAliveSucceeded.set(true);
219 LOG.warn("{} Keepalive RPC returned null with response. Reconnecting netconf session", id);
225 public void onFailure(@Nonnull final Throwable throwable) {
226 LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, throwable);
232 * Reset keepalive after each RPC response received.
234 private class ResetKeepalive implements FutureCallback<DOMRpcResult> {
236 public void onSuccess(@Nullable final DOMRpcResult result) {
237 // No matter what response we got,
238 // rpc-reply or rpc-error, we got it from device so the netconf session is OK.
243 public void onFailure(@Nonnull final Throwable throwable) {
244 // User/Application RPC failed (The RPC did not reach the remote device or ..
245 // TODO what other reasons could cause this ?)
246 // There is no point in keeping this session. Reconnect.
247 LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, throwable);
253 * Request timeout task is called once the defaultRequestTimeoutMillis is
254 * reached. At this moment, if the request is not yet finished, we cancel
257 private static final class RequestTimeoutTask implements Runnable {
259 private final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture;
261 RequestTimeoutTask(final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture) {
262 this.rpcResultFuture = rpcResultFuture;
267 if (!rpcResultFuture.isDone()) {
268 rpcResultFuture.cancel(true);
274 * DOMRpcService proxy that attaches reset-keepalive-task and schedule
275 * request-timeout-task to each RPC invocation.
277 public static final class KeepaliveDOMRpcService implements DOMRpcService {
279 private final DOMRpcService deviceRpc;
280 private final ResetKeepalive resetKeepaliveTask;
281 private final long defaultRequestTimeoutMillis;
282 private final ScheduledExecutorService executor;
284 KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask,
285 final long defaultRequestTimeoutMillis, final ScheduledExecutorService executor) {
286 this.deviceRpc = deviceRpc;
287 this.resetKeepaliveTask = resetKeepaliveTask;
288 this.defaultRequestTimeoutMillis = defaultRequestTimeoutMillis;
289 this.executor = executor;
292 public DOMRpcService getDeviceRpc() {
298 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
299 final NormalizedNode<?, ?> input) {
300 final CheckedFuture<DOMRpcResult, DOMRpcException> domRpcResultDOMRpcExceptionCheckedFuture =
301 deviceRpc.invokeRpc(type, input);
302 Futures.addCallback(domRpcResultDOMRpcExceptionCheckedFuture, resetKeepaliveTask,
303 MoreExecutors.directExecutor());
305 final RequestTimeoutTask timeoutTask = new RequestTimeoutTask(domRpcResultDOMRpcExceptionCheckedFuture);
306 executor.schedule(timeoutTask, defaultRequestTimeoutMillis, TimeUnit.MILLISECONDS);
308 return domRpcResultDOMRpcExceptionCheckedFuture;
312 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
313 @Nonnull final T listener) {
314 // There is no real communication with the device (yet), no reset here
315 return deviceRpc.registerRpcListener(listener);