Eliminate LockChangeListener
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / sal / AbstractNetconfDataTreeService.java
1 /*
2  * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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 com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.MoreExecutors;
18 import java.util.Collection;
19 import java.util.List;
20 import java.util.Optional;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
24 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
25 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
26 import org.opendaylight.netconf.api.ModifyAction;
27 import org.opendaylight.netconf.dom.api.NetconfDataTreeService;
28 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceServices.Rpcs;
29 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
30 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps;
31 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfRpcFutureCallback;
32 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
33 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
34 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
35 import org.opendaylight.yangtools.yang.common.RpcError;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 public abstract sealed class AbstractNetconfDataTreeService implements NetconfDataTreeService {
43     private static final class Candidate extends AbstractNetconfDataTreeService {
44         Candidate(final RemoteDeviceId id, final NetconfBaseOps netconfOps, final boolean rollbackSupport,
45                 final boolean lockDatastore) {
46             super(id, netconfOps, rollbackSupport, lockDatastore);
47         }
48
49         /**
50          * This has to be non blocking since it is called from a callback on commit and it is netty threadpool that is
51          * really sensitive to blocking calls.
52          */
53         @Override
54         public ListenableFuture<? extends DOMRpcResult> discardChanges() {
55             return netconfOps.discardChanges(new NetconfRpcFutureCallback("Discard candidate", id));
56         }
57
58         @Override
59         ListenableFuture<? extends DOMRpcResult> lockSingle() {
60             return netconfOps.lockCandidate(new NetconfRpcFutureCallback("Lock candidate", id));
61         }
62
63         @Override
64         List<ListenableFuture<? extends DOMRpcResult>> unlockImpl() {
65             return List.of(netconfOps.unlockCandidate(new NetconfRpcFutureCallback("Unlock candidate", id)));
66         }
67
68         @Override
69         ListenableFuture<? extends DOMRpcResult> editConfig(final DataContainerChild editStructure,
70                 final ModifyAction defaultOperation) {
71             final NetconfRpcFutureCallback callback = new NetconfRpcFutureCallback("Edit candidate", id);
72             return defaultOperation == null ? netconfOps.editConfigCandidate(callback, editStructure, rollbackSupport)
73                 : netconfOps.editConfigCandidate(callback, editStructure, defaultOperation, rollbackSupport);
74         }
75     }
76
77     private static final class Running extends AbstractNetconfDataTreeService {
78         Running(final RemoteDeviceId id, final NetconfBaseOps netconfOps, final boolean rollbackSupport,
79                 final boolean lockDatastore) {
80             super(id, netconfOps, rollbackSupport, lockDatastore);
81         }
82
83         @Override
84         public ListenableFuture<DOMRpcResult> discardChanges() {
85             // Changes cannot be discarded from running
86             return RPC_SUCCESS;
87         }
88
89         @Override
90         public ListenableFuture<DOMRpcResult> commit() {
91             // No candidate, hence we commit immediately
92             return RPC_SUCCESS;
93         }
94
95         @Override
96         ListenableFuture<? extends DOMRpcResult> lockSingle() {
97             return netconfOps.lockRunning(new NetconfRpcFutureCallback("Lock running", id));
98         }
99
100         @Override
101         List<ListenableFuture<? extends DOMRpcResult>> unlockImpl() {
102             return List.of(netconfOps.unlockRunning(new NetconfRpcFutureCallback("Unlock running", id)));
103         }
104
105         @Override
106         ListenableFuture<? extends DOMRpcResult> editConfig(final DataContainerChild editStructure,
107                 final ModifyAction defaultOperation) {
108             final NetconfRpcFutureCallback callback = new NetconfRpcFutureCallback("Edit running", id);
109             return defaultOperation == null ? netconfOps.editConfigRunning(callback, editStructure, rollbackSupport)
110                 : netconfOps.editConfigRunning(callback, editStructure, defaultOperation, rollbackSupport);
111         }
112     }
113
114     private static final class CandidateWithRunning extends AbstractNetconfDataTreeService {
115         private final Candidate candidate;
116         private final Running running;
117
118         CandidateWithRunning(final RemoteDeviceId id, final NetconfBaseOps netconfOps,
119                 final boolean rollbackSupport, final boolean lockDatastore) {
120             super(id, netconfOps, rollbackSupport, lockDatastore);
121             candidate = new Candidate(id, netconfOps, rollbackSupport, lockDatastore);
122             running = new Running(id, netconfOps, rollbackSupport, lockDatastore);
123         }
124
125         @Override
126         public ListenableFuture<? extends DOMRpcResult> discardChanges() {
127             return candidate.discardChanges();
128         }
129
130         @Override
131         ListenableFuture<DOMRpcResult> lockSingle() {
132             throw new UnsupportedOperationException();
133         }
134
135         @Override
136         List<ListenableFuture<? extends DOMRpcResult>> lockImpl() {
137             return List.of(candidate.lockSingle(), running.lockSingle());
138         }
139
140         @Override
141         List<ListenableFuture<? extends DOMRpcResult>> unlockImpl() {
142             return List.of(running.unlock(), candidate.unlock());
143         }
144
145         @Override
146         ListenableFuture<? extends DOMRpcResult> editConfig(final DataContainerChild editStructure,
147                 final ModifyAction defaultOperation) {
148             return candidate.editConfig(editStructure, defaultOperation);
149         }
150     }
151
152     private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfDataTreeService.class);
153     private static final ListenableFuture<DOMRpcResult> RPC_SUCCESS =
154         Futures.immediateFuture(new DefaultDOMRpcResult());
155
156     final @NonNull RemoteDeviceId id;
157     final NetconfBaseOps netconfOps;
158     final boolean rollbackSupport;
159
160     private final boolean lockDatastore;
161
162     AbstractNetconfDataTreeService(final RemoteDeviceId id, final NetconfBaseOps netconfOps,
163             final boolean rollbackSupport, final boolean lockDatastore) {
164         this.id = requireNonNull(id);
165         this.netconfOps = requireNonNull(netconfOps);
166         this.rollbackSupport = rollbackSupport;
167         this.lockDatastore = lockDatastore;
168     }
169
170     public static @NonNull AbstractNetconfDataTreeService of(final RemoteDeviceId id,
171             final MountPointContext mountContext, final Rpcs rpcs,
172             final NetconfSessionPreferences sessionPreferences, final boolean lockDatastore) {
173         final var netconfOps = new NetconfBaseOps(rpcs, mountContext);
174         final boolean rollbackSupport = sessionPreferences.isRollbackSupported();
175
176         // Examine preferences and decide which implementation to use
177         if (sessionPreferences.isCandidateSupported()) {
178             return sessionPreferences.isRunningWritable()
179                 ? new CandidateWithRunning(id, netconfOps, rollbackSupport, lockDatastore)
180                     : new Candidate(id, netconfOps, rollbackSupport, lockDatastore);
181         } else if (sessionPreferences.isRunningWritable()) {
182             return new Running(id, netconfOps, rollbackSupport, lockDatastore);
183         } else {
184             throw new IllegalArgumentException("Device " + id.getName() + " has advertised neither :writable-running "
185                 + "nor :candidate capability. Failed to establish session, as at least one of these must be "
186                 + "advertised.");
187         }
188     }
189
190     @Override
191     public synchronized ListenableFuture<DOMRpcResult> lock() {
192         if (!lockDatastore) {
193             LOG.trace("Lock is not allowed by device configuration, ignoring lock results: {}", id);
194             return RPC_SUCCESS;
195         }
196
197         final ListenableFuture<DOMRpcResult> result = mergeFutures(lockImpl());
198         Futures.addCallback(result, new FutureCallback<>() {
199             @Override
200             public void onSuccess(final DOMRpcResult result) {
201                 final var errors = result.errors();
202                 if (errors.isEmpty()) {
203                     LOG.debug("{}: Lock successful.", id);
204                     return;
205                 }
206                 if (allWarnings(errors)) {
207                     LOG.info("{}: Lock successful with warnings {}", errors, id);
208                     return;
209                 }
210
211                 LOG.warn("{}: Lock failed with errors {}", id, errors);
212             }
213
214             @Override
215             public void onFailure(final Throwable throwable) {
216                 LOG.warn("{}: Lock failed.", id, throwable);
217             }
218         }, MoreExecutors.directExecutor());
219
220         return result;
221     }
222
223     List<ListenableFuture<? extends DOMRpcResult>> lockImpl() {
224         return List.of(lockSingle());
225     }
226
227     abstract ListenableFuture<? extends DOMRpcResult> lockSingle();
228
229     @Override
230     public synchronized ListenableFuture<DOMRpcResult> unlock() {
231         if (!lockDatastore) {
232             LOG.trace("Unlock is not allowed: {}", id);
233             return RPC_SUCCESS;
234         }
235
236         final ListenableFuture<DOMRpcResult> result = mergeFutures(unlockImpl());
237         Futures.addCallback(result, new FutureCallback<>() {
238             @Override
239             public void onSuccess(final DOMRpcResult result) {
240                 final var errors = result.errors();
241                 if (errors.isEmpty()) {
242                     LOG.debug("{}: Unlock successful.", id);
243                     return;
244                 }
245                 if (allWarnings(errors)) {
246                     LOG.info("{}: Unlock successful with warnings {}", errors, id);
247                     return;
248                 }
249
250                 LOG.error("{}: Unlock failed with errors {}", id, errors);
251             }
252
253             @Override
254             public void onFailure(final Throwable throwable) {
255                 LOG.error("{}: Unlock failed.", id, throwable);
256             }
257         }, MoreExecutors.directExecutor());
258         return result;
259     }
260
261     abstract List<ListenableFuture<? extends DOMRpcResult>> unlockImpl();
262
263     @Override
264     public ListenableFuture<Optional<NormalizedNode>> get(final YangInstanceIdentifier path) {
265         return netconfOps.getData(new NetconfRpcFutureCallback("Data read", id), Optional.ofNullable(path));
266     }
267
268     @Override
269     public ListenableFuture<Optional<NormalizedNode>> get(final YangInstanceIdentifier path,
270             final List<YangInstanceIdentifier> fields) {
271         return netconfOps.getData(new NetconfRpcFutureCallback("Data read", id), Optional.ofNullable(path), fields);
272     }
273
274     @Override
275     public ListenableFuture<Optional<NormalizedNode>> getConfig(final YangInstanceIdentifier path) {
276         return netconfOps.getConfigRunningData(new NetconfRpcFutureCallback("Data read", id),
277             Optional.ofNullable(path));
278     }
279
280     @Override
281     public ListenableFuture<Optional<NormalizedNode>> getConfig(final YangInstanceIdentifier path,
282             final List<YangInstanceIdentifier> fields) {
283         return netconfOps.getConfigRunningData(new NetconfRpcFutureCallback("Data read", id),
284             Optional.ofNullable(path), fields);
285     }
286
287     @Override
288     public synchronized ListenableFuture<? extends DOMRpcResult> merge(final LogicalDatastoreType store,
289             final YangInstanceIdentifier path, final NormalizedNode data,
290             final Optional<ModifyAction> defaultOperation) {
291         checkEditable(store);
292         return editConfig(
293             netconfOps.createEditConfigStructure(Optional.ofNullable(data), Optional.of(ModifyAction.MERGE), path),
294             defaultOperation.orElse(null));
295     }
296
297     @Override
298     public synchronized ListenableFuture<? extends DOMRpcResult> replace(final LogicalDatastoreType store,
299             final YangInstanceIdentifier path, final NormalizedNode data,
300             final Optional<ModifyAction> defaultOperation) {
301         checkEditable(store);
302         return editConfig(
303             netconfOps.createEditConfigStructure(Optional.ofNullable(data), Optional.of(ModifyAction.REPLACE), path),
304             defaultOperation.orElse(null));
305     }
306
307     @Override
308     public synchronized ListenableFuture<? extends DOMRpcResult> create(final LogicalDatastoreType store,
309             final YangInstanceIdentifier path, final NormalizedNode data,
310             final Optional<ModifyAction> defaultOperation) {
311         checkEditable(store);
312         return editConfig(
313             netconfOps.createEditConfigStructure(Optional.ofNullable(data), Optional.of(ModifyAction.CREATE), path),
314             defaultOperation.orElse(null));
315     }
316
317     @Override
318     public synchronized ListenableFuture<? extends DOMRpcResult> delete(final LogicalDatastoreType store,
319             final YangInstanceIdentifier path) {
320         return editConfig(netconfOps.createEditConfigStructure(Optional.empty(),
321                 Optional.of(ModifyAction.DELETE), path), null);
322     }
323
324     @Override
325     public synchronized ListenableFuture<? extends DOMRpcResult> remove(final LogicalDatastoreType store,
326             final YangInstanceIdentifier path) {
327         return editConfig(netconfOps.createEditConfigStructure(Optional.empty(),
328                 Optional.of(ModifyAction.REMOVE), path), null);
329     }
330
331     @Override
332     public synchronized ListenableFuture<? extends DOMRpcResult> commit() {
333         return netconfOps.commit(new NetconfRpcFutureCallback("Commit", id));
334     }
335
336     @Override
337     public final Object getDeviceId() {
338         return id;
339     }
340
341     abstract ListenableFuture<? extends DOMRpcResult> editConfig(DataContainerChild editStructure,
342         @Nullable ModifyAction defaultOperation);
343
344     private static void checkEditable(final LogicalDatastoreType store) {
345         checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can only edit configuration data, not %s", store);
346     }
347
348     // Transform list of futures related to RPC operation into a single Future
349     private static ListenableFuture<DOMRpcResult> mergeFutures(
350             final List<ListenableFuture<? extends DOMRpcResult>> futures) {
351         return Futures.whenAllComplete(futures).call(() -> {
352             if (futures.size() == 1) {
353                 // Fast path
354                 return Futures.getDone(futures.get(0));
355             }
356
357             final var builder = ImmutableList.<RpcError>builder();
358             for (ListenableFuture<? extends DOMRpcResult> future : futures) {
359                 builder.addAll(Futures.getDone(future).errors());
360             }
361             return new DefaultDOMRpcResult(null, builder.build());
362         }, MoreExecutors.directExecutor());
363     }
364
365     private static boolean allWarnings(final Collection<? extends @NonNull RpcError> errors) {
366         return errors.stream().allMatch(error -> error.getSeverity() == ErrorSeverity.WARNING);
367     }
368 }