Merge "Fix findbugs violations in netconf"
[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 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;
42
43 /**
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.
47  */
48 public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSessionPreferences> {
49
50     private static final Logger LOG = LoggerFactory.getLogger(KeepaliveSalFacade.class);
51
52     // 2 minutes keepalive delay by default
53     private static final long DEFAULT_DELAY = TimeUnit.MINUTES.toSeconds(2);
54
55     // 1 minute transaction timeout by default
56     private static final long DEFAULT_TRANSACTION_TIMEOUT_MILLI = TimeUnit.MILLISECONDS.toMillis(60000);
57
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;
64
65     private volatile NetconfDeviceCommunicator listener;
66     private volatile ScheduledFuture<?> currentKeepalive;
67     private volatile DOMRpcService currentDeviceRpc;
68
69     public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
70                               final ScheduledExecutorService executor, final long keepaliveDelaySeconds,
71                               final long defaultRequestTimeoutMillis) {
72         this.id = id;
73         this.salFacade = salFacade;
74         this.executor = executor;
75         this.keepaliveDelaySeconds = keepaliveDelaySeconds;
76         this.defaultRequestTimeoutMillis = defaultRequestTimeoutMillis;
77         this.resetKeepaliveTask = new ResetKeepalive();
78     }
79
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);
83     }
84
85     /**
86      * Set the netconf session listener whenever ready.
87      *
88      * @param listener netconf session listener
89      */
90     public void setListener(final NetconfDeviceCommunicator listener) {
91         this.listener = listener;
92     }
93
94     /**
95      * Just cancel current keepalive task.
96      * If its already started, let it finish ... not such a big deal.
97      *
98      * <p>
99      * Then schedule next keepalive.
100      */
101     void resetKeepalive() {
102         LOG.trace("{}: Resetting netconf keepalive timer", id);
103         if (currentKeepalive != null) {
104             currentKeepalive.cancel(false);
105         }
106         scheduleKeepalive();
107     }
108
109     /**
110      * Cancel current keepalive and also reset current deviceRpc.
111      */
112     private void stopKeepalives() {
113         if (currentKeepalive != null) {
114             currentKeepalive.cancel(false);
115         }
116         currentDeviceRpc = null;
117     }
118
119     void reconnect() {
120         Preconditions.checkState(listener != null, "%s: Unable to reconnect, session listener is missing", id);
121         stopKeepalives();
122         LOG.info("{}: Reconnecting inactive netconf session", id);
123         listener.disconnect();
124     }
125
126     @Override
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);
133
134         LOG.debug("{}: Netconf session initiated, starting keepalives", id);
135         scheduleKeepalive();
136     }
137
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);
142     }
143
144     @Override
145     public void onDeviceDisconnected() {
146         stopKeepalives();
147         salFacade.onDeviceDisconnected();
148     }
149
150     @Override
151     public void onDeviceFailed(final Throwable throwable) {
152         stopKeepalives();
153         salFacade.onDeviceFailed(throwable);
154     }
155
156     @Override
157     public void onNotification(final DOMNotification domNotification) {
158         resetKeepalive();
159         salFacade.onNotification(domNotification);
160     }
161
162     @Override
163     public void close() {
164         stopKeepalives();
165         salFacade.close();
166     }
167
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);
172
173     /**
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.
178      */
179     private class Keepalive implements Runnable, FutureCallback<DOMRpcResult> {
180
181         private final ScheduledFuture<?> previousKeepalive;
182
183         Keepalive(final ScheduledFuture<?> previousKeepalive) {
184             this.previousKeepalive = previousKeepalive;
185         }
186
187         @Override
188         public void run() {
189             LOG.trace("{}: Invoking keepalive RPC", id);
190
191             try {
192                 if (previousKeepalive != null && !previousKeepalive.isDone()) {
193                     onFailure(new IllegalStateException("Previous keepalive timed out"));
194                 } else {
195                     Futures.addCallback(currentDeviceRpc.invokeRpc(PATH, KEEPALIVE_PAYLOAD), this,
196                                         MoreExecutors.directExecutor());
197                 }
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.
204             }
205         }
206
207         @Override
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());
213                 scheduleKeepalive();
214             } else if (result != null && !result.getErrors().isEmpty()) {
215                 LOG.warn("{}: Keepalive RPC failed with error: {}", id, result.getErrors());
216                 scheduleKeepalive();
217             } else {
218                 LOG.warn("{} Keepalive RPC returned null with response. Reconnecting netconf session", id);
219                 reconnect();
220             }
221         }
222
223         @Override
224         public void onFailure(@Nonnull final Throwable throwable) {
225             LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, throwable);
226             reconnect();
227         }
228     }
229
230     /**
231      * Reset keepalive after each RPC response received.
232      */
233     private class ResetKeepalive implements FutureCallback<DOMRpcResult> {
234         @Override
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.
238             resetKeepalive();
239         }
240
241         @Override
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);
247             reconnect();
248         }
249     }
250
251     /*
252      * Request timeout task is called once the defaultRequestTimeoutMillis is
253      * reached. At this moment, if the request is not yet finished, we cancel
254      * it.
255      */
256     private static final class RequestTimeoutTask implements Runnable {
257
258         private final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture;
259
260         RequestTimeoutTask(final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture) {
261             this.rpcResultFuture = rpcResultFuture;
262         }
263
264         @Override
265         public void run() {
266             if (!rpcResultFuture.isDone()) {
267                 rpcResultFuture.cancel(true);
268             }
269         }
270     }
271
272     /**
273      * DOMRpcService proxy that attaches reset-keepalive-task and schedule
274      * request-timeout-task to each RPC invocation.
275      */
276     public static final class KeepaliveDOMRpcService implements DOMRpcService {
277
278         private final DOMRpcService deviceRpc;
279         private final ResetKeepalive resetKeepaliveTask;
280         private final long defaultRequestTimeoutMillis;
281         private final ScheduledExecutorService executor;
282
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;
289         }
290
291         public DOMRpcService getDeviceRpc() {
292             return deviceRpc;
293         }
294
295         @Nonnull
296         @Override
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());
303
304             final RequestTimeoutTask timeoutTask = new RequestTimeoutTask(domRpcResultDOMRpcExceptionCheckedFuture);
305             executor.schedule(timeoutTask, defaultRequestTimeoutMillis, TimeUnit.MILLISECONDS);
306
307             return domRpcResultDOMRpcExceptionCheckedFuture;
308         }
309
310         @Override
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);
315         }
316     }
317 }