Merge changes I4ec69712,I8348002a,I7e6abbf1,Idc2294da
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / sal / NetconfDeviceTopologyAdapter.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
9 package org.opendaylight.controller.sal.connect.netconf.sal;
10
11 import com.google.common.base.Function;
12 import com.google.common.collect.FluentIterable;
13 import com.google.common.util.concurrent.CheckedFuture;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import java.util.ArrayList;
17 import java.util.List;
18 import java.util.Map.Entry;
19 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
20 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
21 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
22 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
23 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCapabilities;
24 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
26 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
27 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
28 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeFields.ConnectionStatus;
29 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.fields.AvailableCapabilitiesBuilder;
30 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.fields.UnavailableCapabilities;
31 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.fields.UnavailableCapabilitiesBuilder;
32 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.fields.unavailable.capabilities.UnavailableCapability;
33 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.fields.unavailable.capabilities.UnavailableCapability.FailureReason;
34 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.fields.unavailable.capabilities.UnavailableCapabilityBuilder;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.network.topology.topology.topology.types.TopologyNetconf;
36 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
37 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopologyBuilder;
38 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
39 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
40 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
41 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyBuilder;
42 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
43 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
44 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
45 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
46 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
47 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 final class NetconfDeviceTopologyAdapter implements AutoCloseable {
53
54     public static final Logger logger = LoggerFactory.getLogger(NetconfDeviceTopologyAdapter.class);
55     public static final Function<Entry<QName, FailureReason>, UnavailableCapability> UNAVAILABLE_CAPABILITY_TRANSFORMER = new Function<Entry<QName, FailureReason>, UnavailableCapability>() {
56         @Override
57         public UnavailableCapability apply(final Entry<QName, FailureReason> input) {
58             return new UnavailableCapabilityBuilder()
59                     .setCapability(input.getKey().toString())
60                     .setFailureReason(input.getValue()).build();
61         }
62     };
63     public static final Function<QName, String> AVAILABLE_CAPABILITY_TRANSFORMER = new Function<QName, String>() {
64         @Override
65         public String apply(QName qName) {
66             return qName.toString();
67         }
68     };
69
70     private final RemoteDeviceId id;
71     private final DataBroker dataService;
72
73     private final InstanceIdentifier<NetworkTopology> networkTopologyPath;
74     private final KeyedInstanceIdentifier<Topology, TopologyKey> topologyListPath;
75     private static final String UNKNOWN_REASON = "Unknown reason";
76
77     NetconfDeviceTopologyAdapter(final RemoteDeviceId id, final DataBroker dataService) {
78         this.id = id;
79         this.dataService = dataService;
80
81         this.networkTopologyPath = InstanceIdentifier.builder(NetworkTopology.class).build();
82         this.topologyListPath = networkTopologyPath.child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
83
84         initDeviceData();
85     }
86
87      private void initDeviceData() {
88         final WriteTransaction writeTx = dataService.newWriteOnlyTransaction();
89
90         createNetworkTopologyIfNotPresent(writeTx);
91
92         final InstanceIdentifier<Node> path = id.getTopologyBindingPath();
93         NodeBuilder nodeBuilder = getNodeIdBuilder(id);
94         NetconfNodeBuilder netconfNodeBuilder = new NetconfNodeBuilder();
95         netconfNodeBuilder.setConnectionStatus(ConnectionStatus.Connecting);
96         netconfNodeBuilder.setHost(id.getHost());
97         netconfNodeBuilder.setPort(new PortNumber(id.getAddress().getPort()));
98         nodeBuilder.addAugmentation(NetconfNode.class, netconfNodeBuilder.build());
99         Node node = nodeBuilder.build();
100
101         logger.trace("{}: Init device state transaction {} putting if absent operational data started.", id, writeTx.getIdentifier());
102         writeTx.put(LogicalDatastoreType.OPERATIONAL, path, node);
103         logger.trace("{}: Init device state transaction {} putting operational data ended.", id, writeTx.getIdentifier());
104
105         logger.trace("{}: Init device state transaction {} putting if absent config data started.", id, writeTx.getIdentifier());
106         writeTx.put(LogicalDatastoreType.CONFIGURATION, path, getNodeWithId(id));
107         logger.trace("{}: Init device state transaction {} putting config data ended.", id, writeTx.getIdentifier());
108
109         commitTransaction(writeTx, "init");
110     }
111
112     public void updateDeviceData(boolean up, NetconfDeviceCapabilities capabilities) {
113         final Node data = buildDataForNetconfNode(up, capabilities);
114
115         final WriteTransaction writeTx = dataService.newWriteOnlyTransaction();
116         logger.trace("{}: Update device state transaction {} merging operational data started.", id, writeTx.getIdentifier());
117         writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath(), data);
118         logger.trace("{}: Update device state transaction {} merging operational data ended.", id, writeTx.getIdentifier());
119
120         commitTransaction(writeTx, "update");
121     }
122
123     public void setDeviceAsFailed(Throwable throwable) {
124         String reason = (throwable != null && throwable.getMessage() != null) ? throwable.getMessage() : UNKNOWN_REASON;
125
126         final NetconfNode netconfNode = new NetconfNodeBuilder().setConnectionStatus(ConnectionStatus.UnableToConnect).setConnectedMessage(reason).build();
127         final Node data = getNodeIdBuilder(id).addAugmentation(NetconfNode.class, netconfNode).build();
128
129         final WriteTransaction writeTx = dataService.newWriteOnlyTransaction();
130         logger.trace("{}: Setting device state as failed {} putting operational data started.", id, writeTx.getIdentifier());
131         writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath(), data);
132         logger.trace("{}: Setting device state as failed {} putting operational data ended.", id, writeTx.getIdentifier());
133
134         commitTransaction(writeTx, "update-failed-device");
135     }
136
137     private Node buildDataForNetconfNode(boolean up, NetconfDeviceCapabilities capabilities) {
138         List<String> capabilityList = new ArrayList<>();
139         capabilityList.addAll(capabilities.getNonModuleBasedCapabilities());
140         capabilityList.addAll(FluentIterable.from(capabilities.getResolvedCapabilities()).transform(AVAILABLE_CAPABILITY_TRANSFORMER).toList());
141         final AvailableCapabilitiesBuilder avCapabalitiesBuilder = new AvailableCapabilitiesBuilder();
142         avCapabalitiesBuilder.setAvailableCapability(capabilityList);
143
144         final UnavailableCapabilities unavailableCapabilities =
145                 new UnavailableCapabilitiesBuilder().setUnavailableCapability(FluentIterable.from(capabilities.getUnresolvedCapabilites().entrySet())
146                         .transform(UNAVAILABLE_CAPABILITY_TRANSFORMER).toList()).build();
147
148         final NetconfNodeBuilder netconfNodeBuilder = new NetconfNodeBuilder()
149                 .setHost(id.getHost())
150                 .setPort(new PortNumber(id.getAddress().getPort()))
151                 .setConnectionStatus(up ? ConnectionStatus.Connected : ConnectionStatus.Connecting)
152                 .setAvailableCapabilities(avCapabalitiesBuilder.build())
153                 .setUnavailableCapabilities(unavailableCapabilities);
154
155         final NodeBuilder nodeBuilder = getNodeIdBuilder(id);
156
157         return nodeBuilder.addAugmentation(NetconfNode.class, netconfNodeBuilder.build()).build();
158     }
159
160     public void removeDeviceConfiguration() {
161         final WriteTransaction writeTx = dataService.newWriteOnlyTransaction();
162
163         logger.trace("{}: Close device state transaction {} removing all data started.", id, writeTx.getIdentifier());
164         writeTx.delete(LogicalDatastoreType.CONFIGURATION, id.getTopologyBindingPath());
165         writeTx.delete(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath());
166         logger.trace("{}: Close device state transaction {} removing all data ended.", id, writeTx.getIdentifier());
167
168         commitTransaction(writeTx, "close");
169     }
170
171     private void createNetworkTopologyIfNotPresent(final WriteTransaction writeTx) {
172
173         final NetworkTopology networkTopology = new NetworkTopologyBuilder().build();
174         logger.trace("{}: Merging {} container to ensure its presence", id, networkTopology.QNAME, writeTx.getIdentifier());
175         writeTx.merge(LogicalDatastoreType.CONFIGURATION, networkTopologyPath, networkTopology);
176         writeTx.merge(LogicalDatastoreType.OPERATIONAL, networkTopologyPath, networkTopology);
177
178         final Topology topology = new TopologyBuilder().setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).build();
179         logger.trace("{}: Merging {} container to ensure its presence", id, topology.QNAME, writeTx.getIdentifier());
180         writeTx.merge(LogicalDatastoreType.CONFIGURATION, topologyListPath, topology);
181         writeTx.merge(LogicalDatastoreType.OPERATIONAL, topologyListPath, topology);
182     }
183
184     private void commitTransaction(final WriteTransaction transaction, final String txType) {
185         logger.trace("{}: Committing Transaction {}:{}", id, txType, transaction.getIdentifier());
186         final CheckedFuture<Void, TransactionCommitFailedException> result = transaction.submit();
187
188         Futures.addCallback(result, new FutureCallback<Void>() {
189             @Override
190             public void onSuccess(final Void result) {
191                 logger.trace("{}: Transaction({}) {} SUCCESSFUL", id, txType, transaction.getIdentifier());
192             }
193
194             @Override
195             public void onFailure(final Throwable t) {
196                 logger.error("{}: Transaction({}) {} FAILED!", id, txType, transaction.getIdentifier(), t);
197                 throw new IllegalStateException(id + "  Transaction(" + txType + ") not committed correctly", t);
198             }
199         });
200
201     }
202
203     private static Node getNodeWithId(final RemoteDeviceId id) {
204         final NodeBuilder builder = getNodeIdBuilder(id);
205         return builder.build();
206     }
207
208     private static NodeBuilder getNodeIdBuilder(final RemoteDeviceId id) {
209         final NodeBuilder nodeBuilder = new NodeBuilder();
210         nodeBuilder.setKey(new NodeKey(new NodeId(id.getName())));
211         return nodeBuilder;
212     }
213
214     @Override
215     public void close() throws Exception {
216         removeDeviceConfiguration();
217     }
218 }