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 javax.annotation.Nonnull;
25 import javax.annotation.Nullable;
26 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
27 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
28 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
29 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
30 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
31 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
32 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
33 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
34 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
35 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
36 import org.opendaylight.yangtools.concepts.ListenerRegistration;
37 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
45 * SalFacade proxy that invokes keepalive RPCs to prevent session shutdown from remote device
46 * and to detect incorrect session drops (netconf session is inactive, but TCP/SSH connection is still present).
47 * The keepalive RPC is a get-config with empty filter.
49 public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSessionPreferences> {
51 private static final Logger LOG = LoggerFactory.getLogger(KeepaliveSalFacade.class);
53 // 2 minutes keepalive delay by default
54 private static final long DEFAULT_DELAY = TimeUnit.MINUTES.toSeconds(2);
56 // 1 minute transaction timeout by default
57 private static final long DEFAULT_TRANSACTION_TIMEOUT_MILLI = TimeUnit.MILLISECONDS.toMillis(60000);
59 private final RemoteDeviceId id;
60 private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
61 private final ScheduledExecutorService executor;
62 private final long keepaliveDelaySeconds;
63 private final ResetKeepalive resetKeepaliveTask;
64 private final long defaultRequestTimeoutMillis;
66 private volatile NetconfDeviceCommunicator listener;
67 private volatile ScheduledFuture<?> currentKeepalive;
68 private volatile DOMRpcService currentDeviceRpc;
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.
97 * If its already started, let it finish ... not such a big deal.
100 * Then schedule next keepalive.
102 void resetKeepalive() {
103 LOG.trace("{}: Resetting netconf keepalive timer", id);
104 if (currentKeepalive != null) {
105 currentKeepalive.cancel(false);
111 * Cancel current keepalive and also reset current deviceRpc.
113 private void stopKeepalives() {
114 if (currentKeepalive != null) {
115 currentKeepalive.cancel(false);
117 currentDeviceRpc = null;
121 Preconditions.checkState(listener != null, "%s: Unable to reconnect, session listener is missing", id);
123 LOG.info("{}: Reconnecting inactive netconf session", id);
124 listener.disconnect();
128 public void onDeviceConnected(final SchemaContext remoteSchemaContext,
129 final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
130 this.currentDeviceRpc = deviceRpc;
131 final DOMRpcService deviceRpc1 =
132 new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor);
133 salFacade.onDeviceConnected(remoteSchemaContext, netconfSessionPreferences, deviceRpc1);
135 LOG.debug("{}: Netconf session initiated, starting keepalives", id);
139 private void scheduleKeepalive() {
140 Preconditions.checkState(currentDeviceRpc != null);
141 LOG.trace("{}: Scheduling next keepalive in {} {}", id, keepaliveDelaySeconds, TimeUnit.SECONDS);
142 currentKeepalive = executor.schedule(new Keepalive(currentKeepalive), keepaliveDelaySeconds, TimeUnit.SECONDS);
146 public void onDeviceDisconnected() {
148 salFacade.onDeviceDisconnected();
152 public void onDeviceFailed(final Throwable throwable) {
154 salFacade.onDeviceFailed(throwable);
158 public void onNotification(final DOMNotification domNotification) {
160 salFacade.onNotification(domNotification);
164 public void close() {
169 // Keepalive RPC static resources
170 private static final SchemaPath PATH = toPath(NETCONF_GET_CONFIG_QNAME);
171 private static final ContainerNode KEEPALIVE_PAYLOAD = NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME,
172 getSourceNode(NETCONF_RUNNING_QNAME), NetconfMessageTransformUtil.EMPTY_FILTER);
175 * Invoke keepalive RPC and check the response. In case of any received response the keepalive
176 * is considered successful and schedules next keepalive with a fixed delay. If the response is unsuccessful (no
177 * response received, or the rcp could not even be sent) immediate reconnect is triggered as netconf session
178 * is considered inactive/failed.
180 private class Keepalive implements Runnable, FutureCallback<DOMRpcResult> {
182 private final ScheduledFuture<?> previousKeepalive;
184 Keepalive(final ScheduledFuture<?> previousKeepalive) {
185 this.previousKeepalive = previousKeepalive;
190 LOG.trace("{}: Invoking keepalive RPC", id);
193 if (previousKeepalive != null && !previousKeepalive.isDone()) {
194 onFailure(new IllegalStateException("Previous keepalive timed out"));
196 Futures.addCallback(currentDeviceRpc.invokeRpc(PATH, KEEPALIVE_PAYLOAD), this,
197 MoreExecutors.directExecutor());
199 } catch (NullPointerException e) {
200 LOG.debug("{}: Skipping keepalive while reconnecting", id);
201 // Empty catch block intentional
202 // Do nothing. The currentDeviceRpc was null and it means we hit the reconnect window and
203 // attempted to send keepalive while we were reconnecting. Next keepalive will be scheduled
204 // after reconnect so no action necessary here.
208 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE",
209 justification = "Unrecognised NullableDecl")
211 public void onSuccess(final DOMRpcResult result) {
212 // No matter what response we got, rpc-reply or rpc-error,
213 // we got it from device so the netconf session is OK
214 if (result != null && result.getResult() != null) {
215 LOG.debug("{}: Keepalive RPC successful with response: {}", id, result.getResult());
217 } else if (result != null && !result.getErrors().isEmpty()) {
218 LOG.warn("{}: Keepalive RPC failed with error: {}", id, result.getErrors());
221 LOG.warn("{} Keepalive RPC returned null with response. Reconnecting netconf session", id);
227 public void onFailure(@Nonnull final Throwable throwable) {
228 LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, throwable);
234 * Reset keepalive after each RPC response received.
236 private class ResetKeepalive implements FutureCallback<DOMRpcResult> {
238 public void onSuccess(@Nullable final DOMRpcResult result) {
239 // No matter what response we got,
240 // rpc-reply or rpc-error, we got it from device so the netconf session is OK.
245 public void onFailure(@Nonnull final Throwable throwable) {
246 // User/Application RPC failed (The RPC did not reach the remote device or ..
247 // TODO what other reasons could cause this ?)
248 // There is no point in keeping this session. Reconnect.
249 LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, throwable);
255 * Request timeout task is called once the defaultRequestTimeoutMillis is
256 * reached. At this moment, if the request is not yet finished, we cancel
259 private static final class RequestTimeoutTask implements Runnable {
261 private final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture;
263 RequestTimeoutTask(final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture) {
264 this.rpcResultFuture = rpcResultFuture;
269 if (!rpcResultFuture.isDone()) {
270 rpcResultFuture.cancel(true);
276 * DOMRpcService proxy that attaches reset-keepalive-task and schedule
277 * request-timeout-task to each RPC invocation.
279 public static final class KeepaliveDOMRpcService implements DOMRpcService {
281 private final DOMRpcService deviceRpc;
282 private final ResetKeepalive resetKeepaliveTask;
283 private final long defaultRequestTimeoutMillis;
284 private final ScheduledExecutorService executor;
286 KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask,
287 final long defaultRequestTimeoutMillis, final ScheduledExecutorService executor) {
288 this.deviceRpc = deviceRpc;
289 this.resetKeepaliveTask = resetKeepaliveTask;
290 this.defaultRequestTimeoutMillis = defaultRequestTimeoutMillis;
291 this.executor = executor;
294 public DOMRpcService getDeviceRpc() {
300 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
301 final NormalizedNode<?, ?> input) {
302 final CheckedFuture<DOMRpcResult, DOMRpcException> domRpcResultDOMRpcExceptionCheckedFuture =
303 deviceRpc.invokeRpc(type, input);
304 Futures.addCallback(domRpcResultDOMRpcExceptionCheckedFuture, resetKeepaliveTask,
305 MoreExecutors.directExecutor());
307 final RequestTimeoutTask timeoutTask = new RequestTimeoutTask(domRpcResultDOMRpcExceptionCheckedFuture);
308 executor.schedule(timeoutTask, defaultRequestTimeoutMillis, TimeUnit.MILLISECONDS);
310 return domRpcResultDOMRpcExceptionCheckedFuture;
314 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
315 @Nonnull final T listener) {
316 // There is no real communication with the device (yet), no reset here
317 return deviceRpc.registerRpcListener(listener);