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 java.util.concurrent.ScheduledExecutorService;
21 import java.util.concurrent.ScheduledFuture;
22 import java.util.concurrent.TimeUnit;
23 import javax.annotation.Nonnull;
24 import javax.annotation.Nullable;
25 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
26 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
27 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
28 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
29 import org.opendaylight.controller.md.sal.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.yang.data.api.schema.ContainerNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
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;
69 public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
70 final ScheduledExecutorService executor, final long keepaliveDelaySeconds,
71 final long defaultRequestTimeoutMillis) {
73 this.salFacade = salFacade;
74 this.executor = executor;
75 this.keepaliveDelaySeconds = keepaliveDelaySeconds;
76 this.defaultRequestTimeoutMillis = defaultRequestTimeoutMillis;
77 this.resetKeepaliveTask = new ResetKeepalive();
80 public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
81 final ScheduledExecutorService executor) {
82 this(id, salFacade, executor, DEFAULT_DELAY, DEFAULT_TRANSACTION_TIMEOUT_MILLI);
86 * Set the netconf session listener whenever ready.
88 * @param listener netconf session listener
90 public void setListener(final NetconfDeviceCommunicator listener) {
91 this.listener = listener;
95 * Just cancel current keepalive task.
96 * If its already started, let it finish ... not such a big deal.
99 * Then schedule next keepalive.
101 void resetKeepalive() {
102 LOG.trace("{}: Resetting netconf keepalive timer", id);
103 if (currentKeepalive != null) {
104 currentKeepalive.cancel(false);
110 * Cancel current keepalive and also reset current deviceRpc.
112 private void stopKeepalives() {
113 if (currentKeepalive != null) {
114 currentKeepalive.cancel(false);
116 currentDeviceRpc = null;
120 Preconditions.checkState(listener != null, "%s: Unable to reconnect, session listener is missing", id);
122 LOG.info("{}: Reconnecting inactive netconf session", id);
123 listener.disconnect();
127 public void onDeviceConnected(final SchemaContext remoteSchemaContext,
128 final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
129 this.currentDeviceRpc = deviceRpc;
130 final DOMRpcService deviceRpc1 =
131 new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor);
132 salFacade.onDeviceConnected(remoteSchemaContext, netconfSessionPreferences, deviceRpc1);
134 LOG.debug("{}: Netconf session initiated, starting keepalives", id);
138 private void scheduleKeepalive() {
139 Preconditions.checkState(currentDeviceRpc != null);
140 LOG.trace("{}: Scheduling next keepalive in {} {}", id, keepaliveDelaySeconds, TimeUnit.SECONDS);
141 currentKeepalive = executor.schedule(new Keepalive(currentKeepalive), keepaliveDelaySeconds, TimeUnit.SECONDS);
145 public void onDeviceDisconnected() {
147 salFacade.onDeviceDisconnected();
151 public void onDeviceFailed(final Throwable throwable) {
153 salFacade.onDeviceFailed(throwable);
157 public void onNotification(final DOMNotification domNotification) {
159 salFacade.onNotification(domNotification);
163 public void close() {
168 // Keepalive RPC static resources
169 private static final SchemaPath PATH = toPath(NETCONF_GET_CONFIG_QNAME);
170 private static final ContainerNode KEEPALIVE_PAYLOAD = NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME,
171 getSourceNode(NETCONF_RUNNING_QNAME), NetconfMessageTransformUtil.EMPTY_FILTER);
174 * Invoke keepalive RPC and check the response. In case of any received response the keepalive
175 * is considered successful and schedules next keepalive with a fixed delay. If the response is unsuccessful (no
176 * response received, or the rcp could not even be sent) immediate reconnect is triggered as netconf session
177 * is considered inactive/failed.
179 private class Keepalive implements Runnable, FutureCallback<DOMRpcResult> {
181 private final ScheduledFuture<?> previousKeepalive;
183 Keepalive(final ScheduledFuture<?> previousKeepalive) {
184 this.previousKeepalive = previousKeepalive;
189 LOG.trace("{}: Invoking keepalive RPC", id);
192 if (previousKeepalive != null && !previousKeepalive.isDone()) {
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.
208 public void onSuccess(final DOMRpcResult result) {
209 // No matter what response we got, rpc-reply or rpc-error,
210 // we got it from device so the netconf session is OK
211 if (result != null && result.getResult() != null) {
212 LOG.debug("{}: Keepalive RPC successful with response: {}", id, result.getResult());
214 } else if (result != null && result.getErrors() != null) {
215 LOG.warn("{}: Keepalive RPC failed with error: {}", id, result.getErrors());
218 LOG.warn("{} Keepalive RPC returned null with response: {}. Reconnecting netconf session", id, result);
224 public void onFailure(@Nonnull final Throwable throwable) {
225 LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, throwable);
231 * Reset keepalive after each RPC response received.
233 private class ResetKeepalive implements FutureCallback<DOMRpcResult> {
235 public void onSuccess(@Nullable final DOMRpcResult result) {
236 // No matter what response we got,
237 // rpc-reply or rpc-error, we got it from device so the netconf session is OK.
242 public void onFailure(@Nonnull final Throwable throwable) {
243 // User/Application RPC failed (The RPC did not reach the remote device or ..
244 // TODO what other reasons could cause this ?)
245 // There is no point in keeping this session. Reconnect.
246 LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, throwable);
252 * Request timeout task is called once the defaultRequestTimeoutMillis is
253 * reached. At this moment, if the request is not yet finished, we cancel
256 private static final class RequestTimeoutTask implements Runnable {
258 private final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture;
260 RequestTimeoutTask(final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture) {
261 this.rpcResultFuture = rpcResultFuture;
266 if (!rpcResultFuture.isDone()) {
267 rpcResultFuture.cancel(true);
273 * DOMRpcService proxy that attaches reset-keepalive-task and schedule
274 * request-timeout-task to each RPC invocation.
276 public static final class KeepaliveDOMRpcService implements DOMRpcService {
278 private final DOMRpcService deviceRpc;
279 private ResetKeepalive resetKeepaliveTask;
280 private final long defaultRequestTimeoutMillis;
281 private final ScheduledExecutorService executor;
283 KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask,
284 final long defaultRequestTimeoutMillis, final ScheduledExecutorService executor) {
285 this.deviceRpc = deviceRpc;
286 this.resetKeepaliveTask = resetKeepaliveTask;
287 this.defaultRequestTimeoutMillis = defaultRequestTimeoutMillis;
288 this.executor = executor;
291 public DOMRpcService getDeviceRpc() {
297 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
298 final NormalizedNode<?, ?> input) {
299 final CheckedFuture<DOMRpcResult, DOMRpcException> domRpcResultDOMRpcExceptionCheckedFuture =
300 deviceRpc.invokeRpc(type, input);
301 Futures.addCallback(domRpcResultDOMRpcExceptionCheckedFuture, resetKeepaliveTask,
302 MoreExecutors.directExecutor());
304 final RequestTimeoutTask timeoutTask = new RequestTimeoutTask(domRpcResultDOMRpcExceptionCheckedFuture);
305 executor.schedule(timeoutTask, defaultRequestTimeoutMillis, TimeUnit.MILLISECONDS);
307 return domRpcResultDOMRpcExceptionCheckedFuture;
311 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
312 @Nonnull final T listener) {
313 // There is no real communication with the device (yet), no reset here
314 return deviceRpc.registerRpcListener(listener);