Merge "Bug 8071 - Do not fail on modules with invalid revision during ...
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / sal / KeepaliveSalFacade.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.netconf.sal.connect.netconf.sal;
9
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;
14
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 java.util.concurrent.ScheduledExecutorService;
20 import java.util.concurrent.ScheduledFuture;
21 import java.util.concurrent.TimeUnit;
22 import javax.annotation.Nonnull;
23 import javax.annotation.Nullable;
24 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
25 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
26 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
27 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
28 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
29 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
30 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
31 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
32 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
33 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
34 import org.opendaylight.yangtools.concepts.ListenerRegistration;
35 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
38 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 /**
43  * SalFacade proxy that invokes keepalive RPCs to prevent session shutdown from remote device
44  * and to detect incorrect session drops (netconf session is inactive, but TCP/SSH connection is still present).
45  * The keepalive RPC is a get-config with empty filter.
46  */
47 public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSessionPreferences> {
48
49     private static final Logger LOG = LoggerFactory.getLogger(KeepaliveSalFacade.class);
50
51     // 2 minutes keepalive delay by default
52     private static final long DEFAULT_DELAY = TimeUnit.MINUTES.toSeconds(2);
53
54     // 1 minute transaction timeout by default
55     private static final long DEFAULT_TRANSACTION_TIMEOUT_MILLI = TimeUnit.MILLISECONDS.toMillis(60000);
56
57     private final RemoteDeviceId id;
58     private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
59     private final ScheduledExecutorService executor;
60     private final long keepaliveDelaySeconds;
61     private final ResetKeepalive resetKeepaliveTask;
62     private final long defaultRequestTimeoutMillis;
63
64     private volatile NetconfDeviceCommunicator listener;
65     private volatile ScheduledFuture<?> currentKeepalive;
66     private volatile DOMRpcService currentDeviceRpc;
67
68     public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
69                               final ScheduledExecutorService executor, final long keepaliveDelaySeconds,
70                               final long defaultRequestTimeoutMillis) {
71         this.id = id;
72         this.salFacade = salFacade;
73         this.executor = executor;
74         this.keepaliveDelaySeconds = keepaliveDelaySeconds;
75         this.defaultRequestTimeoutMillis = defaultRequestTimeoutMillis;
76         this.resetKeepaliveTask = new ResetKeepalive();
77     }
78
79     public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
80                               final ScheduledExecutorService executor) {
81         this(id, salFacade, executor, DEFAULT_DELAY, DEFAULT_TRANSACTION_TIMEOUT_MILLI);
82     }
83
84     /**
85      * Set the netconf session listener whenever ready.
86      *
87      * @param listener netconf session listener
88      */
89     public void setListener(final NetconfDeviceCommunicator listener) {
90         this.listener = listener;
91     }
92
93     /**
94      * Just cancel current keepalive task.
95      * If its already started, let it finish ... not such a big deal.
96      *
97      * <p>
98      * Then schedule next keepalive.
99      */
100     void resetKeepalive() {
101         LOG.trace("{}: Resetting netconf keepalive timer", id);
102         if (currentKeepalive != null) {
103             currentKeepalive.cancel(false);
104         }
105         scheduleKeepalive();
106     }
107
108     /**
109      * Cancel current keepalive and also reset current deviceRpc.
110      */
111     private void stopKeepalives() {
112         if (currentKeepalive != null) {
113             currentKeepalive.cancel(false);
114         }
115         currentDeviceRpc = null;
116     }
117
118     void reconnect() {
119         Preconditions.checkState(listener != null, "%s: Unable to reconnect, session listener is missing", id);
120         stopKeepalives();
121         LOG.info("{}: Reconnecting inactive netconf session", id);
122         listener.disconnect();
123     }
124
125     @Override
126     public void onDeviceConnected(final SchemaContext remoteSchemaContext,
127                           final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
128         this.currentDeviceRpc = deviceRpc;
129         final DOMRpcService deviceRpc1 =
130                 new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor);
131         salFacade.onDeviceConnected(remoteSchemaContext, netconfSessionPreferences, deviceRpc1);
132
133         LOG.debug("{}: Netconf session initiated, starting keepalives", id);
134         scheduleKeepalive();
135     }
136
137     private void scheduleKeepalive() {
138         Preconditions.checkState(currentDeviceRpc != null);
139         LOG.trace("{}: Scheduling next keepalive in {} {}", id, keepaliveDelaySeconds, TimeUnit.SECONDS);
140         currentKeepalive = executor.schedule(new Keepalive(currentKeepalive), keepaliveDelaySeconds, TimeUnit.SECONDS);
141     }
142
143     @Override
144     public void onDeviceDisconnected() {
145         stopKeepalives();
146         salFacade.onDeviceDisconnected();
147     }
148
149     @Override
150     public void onDeviceFailed(final Throwable throwable) {
151         stopKeepalives();
152         salFacade.onDeviceFailed(throwable);
153     }
154
155     @Override
156     public void onNotification(final DOMNotification domNotification) {
157         resetKeepalive();
158         salFacade.onNotification(domNotification);
159     }
160
161     @Override
162     public void close() {
163         stopKeepalives();
164         salFacade.close();
165     }
166
167     // Keepalive RPC static resources
168     private static final SchemaPath PATH = toPath(NETCONF_GET_CONFIG_QNAME);
169     private static final ContainerNode KEEPALIVE_PAYLOAD = NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME,
170             getSourceNode(NETCONF_RUNNING_QNAME), NetconfMessageTransformUtil.EMPTY_FILTER);
171
172     /**
173      * Invoke keepalive RPC and check the response. In case of any received response the keepalive
174      * is considered successful and schedules next keepalive with a fixed delay. If the response is unsuccessful (no
175      * response received, or the rcp could not even be sent) immediate reconnect is triggered as netconf session
176      * is considered inactive/failed.
177      */
178     private class Keepalive implements Runnable, FutureCallback<DOMRpcResult> {
179
180         private final ScheduledFuture<?> previousKeepalive;
181
182         Keepalive(final ScheduledFuture<?> previousKeepalive) {
183             this.previousKeepalive = previousKeepalive;
184         }
185
186         @Override
187         public void run() {
188             LOG.trace("{}: Invoking keepalive RPC", id);
189
190             try {
191                 if (previousKeepalive != null && !previousKeepalive.isDone()) {
192                     onFailure(new IllegalStateException("Previous keepalive timed out"));
193                 } else {
194                     Futures.addCallback(currentDeviceRpc.invokeRpc(PATH, KEEPALIVE_PAYLOAD), this);
195                 }
196             } catch (NullPointerException e) {
197                 LOG.debug("{}: Skipping keepalive while reconnecting", id);
198                 // Empty catch block intentional
199                 // Do nothing. The currentDeviceRpc was null and it means we hit the reconnect window and
200                 // attempted to send keepalive while we were reconnecting. Next keepalive will be scheduled
201                 // after reconnect so no action necessary here.
202             }
203         }
204
205         @Override
206         public void onSuccess(final DOMRpcResult result) {
207             if (result != null && result.getResult() != null) {
208                 LOG.debug("{}: Keepalive RPC successful with response: {}", id, result.getResult());
209                 scheduleKeepalive();
210             } else {
211                 LOG.warn("{} Keepalive RPC returned null with response: {}. Reconnecting netconf session", id, result);
212                 reconnect();
213             }
214         }
215
216         @Override
217         public void onFailure(@Nonnull final Throwable throwable) {
218             LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, throwable);
219             reconnect();
220         }
221     }
222
223     /**
224      * Reset keepalive after each RPC response received.
225      */
226     private class ResetKeepalive implements FutureCallback<DOMRpcResult> {
227         @Override
228         public void onSuccess(@Nullable final DOMRpcResult result) {
229             // No matter what response we got,
230             // rpc-reply or rpc-error, we got it from device so the netconf session is OK.
231             resetKeepalive();
232         }
233
234         @Override
235         public void onFailure(@Nonnull final Throwable throwable) {
236             // User/Application RPC failed (The RPC did not reach the remote device or ..
237             // TODO what other reasons could cause this ?)
238             // There is no point in keeping this session. Reconnect.
239             LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, throwable);
240             reconnect();
241         }
242     }
243
244     /*
245      * Request timeout task is called once the defaultRequestTimeoutMillis is
246      * reached. At this moment, if the request is not yet finished, we cancel
247      * it.
248      */
249     private static final class RequestTimeoutTask implements Runnable {
250
251         private final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture;
252
253         RequestTimeoutTask(final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture) {
254             this.rpcResultFuture = rpcResultFuture;
255         }
256
257         @Override
258         public void run() {
259             if (!rpcResultFuture.isDone()) {
260                 rpcResultFuture.cancel(true);
261             }
262         }
263     }
264
265     /**
266      * DOMRpcService proxy that attaches reset-keepalive-task and schedule
267      * request-timeout-task to each RPC invocation.
268      */
269     public static final class KeepaliveDOMRpcService implements DOMRpcService {
270
271         private final DOMRpcService deviceRpc;
272         private ResetKeepalive resetKeepaliveTask;
273         private final long defaultRequestTimeoutMillis;
274         private final ScheduledExecutorService executor;
275
276         KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask,
277                 final long defaultRequestTimeoutMillis, final ScheduledExecutorService executor) {
278             this.deviceRpc = deviceRpc;
279             this.resetKeepaliveTask = resetKeepaliveTask;
280             this.defaultRequestTimeoutMillis = defaultRequestTimeoutMillis;
281             this.executor = executor;
282         }
283
284         public DOMRpcService getDeviceRpc() {
285             return deviceRpc;
286         }
287
288         @Nonnull
289         @Override
290         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
291                                                                       final NormalizedNode<?, ?> input) {
292             final CheckedFuture<DOMRpcResult, DOMRpcException> domRpcResultDOMRpcExceptionCheckedFuture =
293                     deviceRpc.invokeRpc(type, input);
294             Futures.addCallback(domRpcResultDOMRpcExceptionCheckedFuture, resetKeepaliveTask);
295
296             final RequestTimeoutTask timeoutTask = new RequestTimeoutTask(domRpcResultDOMRpcExceptionCheckedFuture);
297             executor.schedule(timeoutTask, defaultRequestTimeoutMillis, TimeUnit.MILLISECONDS);
298
299             return domRpcResultDOMRpcExceptionCheckedFuture;
300         }
301
302         @Override
303         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
304                 @Nonnull final T listener) {
305             // There is no real communication with the device (yet), no reset here
306             return deviceRpc.registerRpcListener(listener);
307         }
308     }
309 }