Merge "Startup archetype: remove 'Impl' from config subsystem Module name."
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / sal / tx / ReadOnlyTx.java
1 /*
2  * Copyright (c) 2014 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.controller.sal.connect.netconf.sal.tx;
9
10 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DATA_QNAME;
11
12 import com.google.common.base.Function;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.util.concurrent.CheckedFuture;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import com.google.common.util.concurrent.ListenableFuture;
19 import java.util.concurrent.ExecutionException;
20 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
21 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
22 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
23 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
24 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
25 import org.opendaylight.controller.sal.connect.netconf.util.NetconfBaseOps;
26 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
27 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
28 import org.opendaylight.yangtools.util.concurrent.MappingCheckedFuture;
29 import org.opendaylight.yangtools.yang.common.RpcResult;
30 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36
37 public final class ReadOnlyTx implements DOMDataReadOnlyTransaction {
38
39     private static final Logger LOG  = LoggerFactory.getLogger(ReadOnlyTx.class);
40
41     private final NetconfBaseOps netconfOps;
42     private final DataNormalizer normalizer;
43     private final RemoteDeviceId id;
44     private final FutureCallback<RpcResult<CompositeNode>> loggingCallback;
45
46     public ReadOnlyTx(final NetconfBaseOps netconfOps, final DataNormalizer normalizer, final RemoteDeviceId id) {
47         this.netconfOps = netconfOps;
48         this.normalizer = normalizer;
49         this.id = id;
50         // Simple logging callback to log result of read operation
51         loggingCallback = new FutureCallback<RpcResult<CompositeNode>>() {
52             @Override
53             public void onSuccess(final RpcResult<CompositeNode> result) {
54                 if(result.isSuccessful()) {
55                     LOG.trace("{}: Reading data successful", id);
56                 } else {
57                     LOG.warn("{}: Reading data unsuccessful: {}", id, result.getErrors());
58                 }
59
60             }
61
62             @Override
63             public void onFailure(final Throwable t) {
64                 LOG.warn("{}: Reading data failed", id, t);
65             }
66         };
67     }
68
69     private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readConfigurationData(
70             final YangInstanceIdentifier path) {
71         final ListenableFuture<RpcResult<CompositeNode>> configRunning = netconfOps.getConfigRunning(loggingCallback, Optional.fromNullable(path));
72         // Find data node and normalize its content
73         final ListenableFuture<Optional<NormalizedNode<?, ?>>> transformedFuture = Futures.transform(configRunning, new Function<RpcResult<CompositeNode>, Optional<NormalizedNode<?, ?>>>() {
74             @Override
75             public Optional<NormalizedNode<?, ?>> apply(final RpcResult<CompositeNode> result) {
76                 checkReadSuccess(result, path);
77
78                 final CompositeNode data = result.getResult().getFirstCompositeByName(NETCONF_DATA_QNAME);
79                 final CompositeNode node = (CompositeNode) NetconfMessageTransformUtil.findNode(data, path);
80
81                 return data == null ?
82                         Optional.<NormalizedNode<?, ?>>absent() :
83                         transform(path, node);
84             }
85         });
86
87         return MappingCheckedFuture.create(transformedFuture, ReadFailedException.MAPPER);
88     }
89
90     private void checkReadSuccess(final RpcResult<CompositeNode> result, final YangInstanceIdentifier path) {
91         try {
92             Preconditions.checkArgument(result.isSuccessful(), "%s: Unable to read data: %s, errors: %s", id, path, result.getErrors());
93         } catch (final IllegalArgumentException e) {
94             LOG.warn("{}: Unable to read data: {}, errors: {}", id, path, result.getErrors());
95             throw e;
96         }
97     }
98
99     private Optional<NormalizedNode<?, ?>> transform(final YangInstanceIdentifier path, final CompositeNode node) {
100         if(node == null) {
101             return Optional.absent();
102         }
103         try {
104             return Optional.<NormalizedNode<?, ?>>of(normalizer.toNormalized(path, node).getValue());
105         } catch (final Exception e) {
106             LOG.error("{}: Unable to normalize data for {}, data: {}", id, path, node, e);
107             throw e;
108         }
109     }
110
111     private CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readOperationalData(
112             final YangInstanceIdentifier path) {
113         final ListenableFuture<RpcResult<CompositeNode>> configCandidate = netconfOps.get(loggingCallback, Optional.fromNullable(path));
114
115         // Find data node and normalize its content
116         final ListenableFuture<Optional<NormalizedNode<?, ?>>> transformedFuture = Futures.transform(configCandidate, new Function<RpcResult<CompositeNode>, Optional<NormalizedNode<?, ?>>>() {
117             @Override
118             public Optional<NormalizedNode<?, ?>> apply(final RpcResult<CompositeNode> result) {
119                 checkReadSuccess(result, path);
120
121                 final CompositeNode data = result.getResult().getFirstCompositeByName(NETCONF_DATA_QNAME);
122                 final CompositeNode node = (CompositeNode) NetconfMessageTransformUtil.findNode(data, path);
123
124                 return data == null ?
125                         Optional.<NormalizedNode<?, ?>>absent() :
126                         transform(path, node);
127             }
128         });
129
130         return MappingCheckedFuture.create(transformedFuture, ReadFailedException.MAPPER);
131     }
132
133     @Override
134     public void close() {
135         // NOOP
136     }
137
138     @Override
139     public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(
140             final LogicalDatastoreType store, final YangInstanceIdentifier path) {
141         final YangInstanceIdentifier legacyPath = toLegacyPath(normalizer, path, id);
142
143         switch (store) {
144             case CONFIGURATION : {
145                 return readConfigurationData(legacyPath);
146             }
147             case OPERATIONAL : {
148                 return readOperationalData(legacyPath);
149             }
150         }
151
152         throw new IllegalArgumentException(String.format("%s, Cannot read data %s for %s datastore, unknown datastore type", id, path, store));
153     }
154
155     @Override
156     public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
157         final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException>
158             data = read(store, path);
159
160         try {
161             return Futures.immediateCheckedFuture(data.get().isPresent());
162         } catch (InterruptedException | ExecutionException e) {
163             return Futures.immediateFailedCheckedFuture(new ReadFailedException("Exists failed",e));
164         }
165     }
166
167     static YangInstanceIdentifier toLegacyPath(final DataNormalizer normalizer, final YangInstanceIdentifier path, final RemoteDeviceId id) {
168         try {
169             return normalizer.toLegacy(path);
170         } catch (final DataNormalizationException e) {
171             throw new IllegalArgumentException(id + ": Cannot normalize path " + path, e);
172         }
173     }
174
175     @Override
176     public Object getIdentifier() {
177         return this;
178     }
179 }