Merge "Add support for notification subtree filter"
[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     private final RemoteDeviceId id;
55     private final RemoteDeviceHandler<NetconfSessionPreferences> salFacade;
56     private final ScheduledExecutorService executor;
57     private final long keepaliveDelaySeconds;
58     private final ResetKeepalive resetKeepaliveTask;
59
60     private volatile NetconfDeviceCommunicator listener;
61     private volatile ScheduledFuture<?> currentKeepalive;
62     private volatile DOMRpcService currentDeviceRpc;
63
64     public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
65                               final ScheduledExecutorService executor, final long keepaliveDelaySeconds) {
66         this.id = id;
67         this.salFacade = salFacade;
68         this.executor = executor;
69         this.keepaliveDelaySeconds = keepaliveDelaySeconds;
70         this.resetKeepaliveTask = new ResetKeepalive();
71     }
72
73     public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
74                               final ScheduledExecutorService executor) {
75         this(id, salFacade, executor, DEFAULT_DELAY);
76     }
77
78     /**
79      * Set the netconf session listener whenever ready
80      *
81      * @param listener netconf session listener
82      */
83     public void setListener(final NetconfDeviceCommunicator listener) {
84         this.listener = listener;
85     }
86
87     /**
88      * Just cancel current keepalive task.
89      * If its already started, let it finish ... not such a big deal.
90      *
91      * Then schedule next keepalive.
92      */
93     private void resetKeepalive() {
94         LOG.trace("{}: Resetting netconf keepalive timer", id);
95         if(currentKeepalive != null) {
96             currentKeepalive.cancel(false);
97         }
98         scheduleKeepalive();
99     }
100
101     /**
102      * Cancel current keepalive and also reset current deviceRpc
103      */
104     private void stopKeepalives() {
105         if(currentKeepalive != null) {
106             currentKeepalive.cancel(false);
107         }
108         currentDeviceRpc = null;
109     }
110
111     private void reconnect() {
112         Preconditions.checkState(listener != null, "%s: Unable to reconnect, session listener is missing", id);
113         stopKeepalives();
114         LOG.info("{}: Reconnecting inactive netconf session", id);
115         listener.disconnect();
116     }
117
118     @Override
119     public void onDeviceConnected(final SchemaContext remoteSchemaContext, final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
120         this.currentDeviceRpc = deviceRpc;
121         final DOMRpcService deviceRpc1 = new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask);
122         salFacade.onDeviceConnected(remoteSchemaContext, netconfSessionPreferences, deviceRpc1);
123
124         LOG.debug("{}: Netconf session initiated, starting keepalives", id);
125         scheduleKeepalive();
126     }
127
128     private void scheduleKeepalive() {
129         Preconditions.checkState(currentDeviceRpc != null);
130         LOG.trace("{}: Scheduling next keepalive in {} {}", id, keepaliveDelaySeconds, TimeUnit.SECONDS);
131         currentKeepalive = executor.schedule(new Keepalive(currentKeepalive), keepaliveDelaySeconds, TimeUnit.SECONDS);
132     }
133
134     @Override
135     public void onDeviceDisconnected() {
136         stopKeepalives();
137         salFacade.onDeviceDisconnected();
138     }
139
140     @Override
141     public void onDeviceFailed(final Throwable throwable) {
142         stopKeepalives();
143         salFacade.onDeviceFailed(throwable);
144     }
145
146     @Override
147     public void onNotification(final DOMNotification domNotification) {
148         resetKeepalive();
149         salFacade.onNotification(domNotification);
150     }
151
152     @Override
153     public void close() {
154         stopKeepalives();
155         salFacade.close();
156     }
157
158     // Keepalive RPC static resources
159     private static final SchemaPath PATH = toPath(NETCONF_GET_CONFIG_QNAME);
160     private static final ContainerNode KEEPALIVE_PAYLOAD =
161             NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME, getSourceNode(NETCONF_RUNNING_QNAME), NetconfMessageTransformUtil.EMPTY_FILTER);
162
163     /**
164      * Invoke keepalive RPC and check the response. In case of any received response the keepalive
165      * is considered successful and schedules next keepalive with a fixed delay. If the response is unsuccessful (no
166      * response received, or the rcp could not even be sent) immediate reconnect is triggered as netconf session
167      * is considered inactive/failed.
168      */
169     private class Keepalive implements Runnable, FutureCallback<DOMRpcResult> {
170
171         private final ScheduledFuture<?> previousKeepalive;
172
173         public Keepalive(final ScheduledFuture<?> previousKeepalive) {
174             this.previousKeepalive = previousKeepalive;
175         }
176
177         @Override
178         public void run() {
179             LOG.trace("{}: Invoking keepalive RPC", id);
180
181             try {
182                 if(previousKeepalive != null && !previousKeepalive.isDone()) {
183                     onFailure(new IllegalStateException("Previous keepalive timed out"));
184                 } else {
185                     Futures.addCallback(currentDeviceRpc.invokeRpc(PATH, KEEPALIVE_PAYLOAD), this);
186                 }
187             } catch (NullPointerException e) {
188                 LOG.debug("{}: Skipping keepalive while reconnecting", id);
189                 // Empty catch block intentional
190                 // Do nothing. The currentDeviceRpc was null and it means we hit the reconnect window and
191                 // attempted to send keepalive while we were reconnecting. Next keepalive will be scheduled
192                 // after reconnect so no action necessary here.
193             }
194         }
195
196         @Override
197         public void onSuccess(final DOMRpcResult result) {
198             if (result != null && result.getResult() != null) {
199                 LOG.debug("{}: Keepalive RPC successful with response: {}", id, result.getResult());
200                 scheduleKeepalive();
201             } else {
202                 LOG.warn("{} Keepalive RPC returned null with response: {}. Reconnecting netconf session", id, result);
203                 reconnect();
204             }
205         }
206
207         @Override
208         public void onFailure(@Nonnull final Throwable t) {
209             LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, t);
210             reconnect();
211         }
212     }
213
214     /**
215      * Reset keepalive after each RPC response received
216      */
217     private class ResetKeepalive implements com.google.common.util.concurrent.FutureCallback<DOMRpcResult> {
218         @Override
219         public void onSuccess(@Nullable final DOMRpcResult result) {
220             // No matter what response we got, rpc-reply or rpc-error, we got it from device so the netconf session is OK
221             resetKeepalive();
222         }
223
224         @Override
225         public void onFailure(@Nonnull final Throwable t) {
226             // User/Application RPC failed (The RPC did not reach the remote device.
227             // There is no point in keeping this session. Reconnect.
228             LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, t);
229             reconnect();
230         }
231     }
232
233     /**
234      * DOMRpcService proxy that attaches reset-keepalive-task to each RPC invocation.
235      */
236     private static final class KeepaliveDOMRpcService implements DOMRpcService {
237
238         private final DOMRpcService deviceRpc;
239         private ResetKeepalive resetKeepaliveTask;
240
241         public KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask) {
242             this.deviceRpc = deviceRpc;
243             this.resetKeepaliveTask = resetKeepaliveTask;
244         }
245
246         @Nonnull
247         @Override
248         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, final NormalizedNode<?, ?> input) {
249             final CheckedFuture<DOMRpcResult, DOMRpcException> domRpcResultDOMRpcExceptionCheckedFuture = deviceRpc.invokeRpc(type, input);
250             Futures.addCallback(domRpcResultDOMRpcExceptionCheckedFuture, resetKeepaliveTask);
251             return domRpcResultDOMRpcExceptionCheckedFuture;
252         }
253
254         @Override
255         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
256             // There is no real communication with the device (yet), no reset here
257             return deviceRpc.registerRpcListener(listener);
258         }
259     }
260 }