f442e475d50397eccfb9539c4cb0a61a392fff0a
[netconf.git] / netconf / sal-netconf-connector / src / test / java / org / opendaylight / netconf / sal / connect / netconf / sal / NetconfDeviceTopologyAdapterTest.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.junit.Assert.assertEquals;
11 import static org.mockito.Matchers.any;
12 import static org.mockito.Mockito.doNothing;
13 import static org.mockito.Mockito.doReturn;
14 import static org.mockito.Mockito.times;
15 import static org.mockito.Mockito.verify;
16 import static org.opendaylight.mdsal.common.api.CommitInfo.emptyFluentFuture;
17
18 import com.google.common.base.Optional;
19 import com.google.common.collect.ClassToInstanceMap;
20 import com.google.common.collect.ImmutableClassToInstanceMap;
21 import com.google.common.util.concurrent.MoreExecutors;
22 import java.net.InetSocketAddress;
23 import java.util.EnumMap;
24 import java.util.concurrent.TimeUnit;
25 import javassist.ClassPool;
26 import org.junit.Before;
27 import org.junit.Test;
28 import org.mockito.Mock;
29 import org.mockito.MockitoAnnotations;
30 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
31 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
32 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
33 import org.opendaylight.controller.md.sal.binding.impl.BindingDOMDataBrokerAdapter;
34 import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
35 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
36 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
37 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
38 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
39 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
40 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
41 import org.opendaylight.controller.md.sal.dom.broker.impl.SerializedDOMDataBroker;
42 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStoreFactory;
43 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
44 import org.opendaylight.mdsal.binding.dom.codec.gen.impl.DataObjectSerializerGenerator;
45 import org.opendaylight.mdsal.binding.dom.codec.gen.impl.StreamWriterGenerator;
46 import org.opendaylight.mdsal.binding.dom.codec.impl.BindingNormalizedNodeCodecRegistry;
47 import org.opendaylight.mdsal.binding.generator.impl.GeneratedClassLoadingStrategy;
48 import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
49 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
50 import org.opendaylight.mdsal.binding.generator.util.JavassistUtils;
51 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
52 import org.opendaylight.mdsal.dom.api.DOMSchemaServiceExtension;
53 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
54 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeConnectionStatus;
57 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
58 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
59 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
60 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
61 import org.opendaylight.yangtools.concepts.ListenerRegistration;
62 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
63 import org.opendaylight.yangtools.yang.common.QName;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
66 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
67 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
69 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
70
71 public class NetconfDeviceTopologyAdapterTest {
72
73     private final RemoteDeviceId id = new RemoteDeviceId("test", new InetSocketAddress("localhost", 22));
74
75     @Mock
76     private DataBroker broker;
77     @Mock
78     private WriteTransaction writeTx;
79     @Mock
80     private BindingTransactionChain txChain;
81     @Mock
82     private NetconfNode data;
83
84     private final String txIdent = "test transaction";
85
86     private SchemaContext schemaContext = null;
87     private final String sessionIdForReporting = "netconf-test-session1";
88
89     private BindingTransactionChain transactionChain;
90
91     private DataBroker dataBroker;
92
93     private DOMDataBroker domDataBroker;
94
95     @Before
96     public void setUp() throws Exception {
97         MockitoAnnotations.initMocks(this);
98         doReturn(txChain).when(broker).createTransactionChain(any(TransactionChainListener.class));
99         doReturn(writeTx).when(txChain).newWriteOnlyTransaction();
100         doNothing().when(writeTx)
101                 .put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
102         doNothing().when(writeTx)
103                 .merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
104
105         doReturn(txIdent).when(writeTx).getIdentifier();
106
107         this.schemaContext = YangParserTestUtils.parseYangResources(NetconfDeviceTopologyAdapterTest.class,
108             "/schemas/network-topology@2013-10-21.yang", "/schemas/ietf-inet-types@2013-07-15.yang",
109             "/schemas/yang-ext.yang", "/schemas/netconf-node-topology.yang",
110             "/schemas/network-topology-augment-test@2016-08-08.yang");
111         schemaContext.getModules();
112         final DOMSchemaService schemaService = createSchemaService();
113
114         final DOMStore operStore = InMemoryDOMDataStoreFactory.create("DOM-OPER", schemaService);
115         final DOMStore configStore = InMemoryDOMDataStoreFactory.create("DOM-CFG", schemaService);
116
117         final EnumMap<LogicalDatastoreType, DOMStore> datastores = new EnumMap<>(LogicalDatastoreType.class);
118         datastores.put(LogicalDatastoreType.CONFIGURATION, configStore);
119         datastores.put(LogicalDatastoreType.OPERATIONAL, operStore);
120
121         domDataBroker = new SerializedDOMDataBroker(datastores, MoreExecutors.newDirectExecutorService());
122
123         final ClassPool pool = ClassPool.getDefault();
124         final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool));
125         final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
126         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
127         codecRegistry.onBindingRuntimeContextUpdated(
128                 BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
129
130         final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
131         final BindingToNormalizedNodeCodec bindingToNormalized =
132                 new BindingToNormalizedNodeCodec(loading, codecRegistry);
133         bindingToNormalized.onGlobalContextUpdated(schemaContext);
134         dataBroker = new BindingDOMDataBrokerAdapter(domDataBroker, bindingToNormalized);
135
136         transactionChain = dataBroker.createTransactionChain(new TransactionChainListener() {
137             @Override
138             public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
139                     final AsyncTransaction<?, ?> transaction, final Throwable cause) {
140
141             }
142
143             @Override
144             public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
145
146             }
147         });
148
149     }
150
151     @Test
152     public void testFailedDevice() throws Exception {
153
154         doReturn(emptyFluentFuture()).when(writeTx).commit();
155         NetconfDeviceTopologyAdapter adapter = new NetconfDeviceTopologyAdapter(id, txChain);
156         adapter.setDeviceAsFailed(null);
157
158         verify(txChain, times(2)).newWriteOnlyTransaction();
159         verify(writeTx, times(1))
160                 .put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
161         adapter.close();
162
163         adapter = new NetconfDeviceTopologyAdapter(id, transactionChain); //not a mock
164         adapter.setDeviceAsFailed(null);
165
166         Optional<NetconfNode> netconfNode = dataBroker.newReadWriteTransaction().read(LogicalDatastoreType.OPERATIONAL,
167                 id.getTopologyBindingPath().augmentation(NetconfNode.class)).checkedGet(5, TimeUnit.SECONDS);
168
169         assertEquals("Netconf node should be presented.", true, netconfNode.isPresent());
170         assertEquals("Connection status should be failed.",
171                 NetconfNodeConnectionStatus.ConnectionStatus.UnableToConnect.getName(),
172                 netconfNode.get().getConnectionStatus().getName());
173
174     }
175
176     @Test
177     public void testDeviceUpdate() throws Exception {
178         doReturn(emptyFluentFuture()).when(writeTx).commit();
179
180         NetconfDeviceTopologyAdapter adapter = new NetconfDeviceTopologyAdapter(id, txChain);
181         adapter.updateDeviceData(true, new NetconfDeviceCapabilities());
182
183         verify(txChain, times(2)).newWriteOnlyTransaction();
184         verify(writeTx, times(1))
185                 .put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
186         verify(writeTx, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class));
187
188     }
189
190     @Test
191     public void testDeviceAugmentedNodePresence() throws Exception {
192
193         Integer dataTestId = 474747;
194
195         NetconfDeviceTopologyAdapter adapter = new NetconfDeviceTopologyAdapter(id, transactionChain);
196
197         QName netconfTestLeafQname = QName.create(
198                 "urn:TBD:params:xml:ns:yang:network-topology-augment-test", "2016-08-08", "test-id").intern();
199
200         YangInstanceIdentifier pathToAugmentedLeaf = YangInstanceIdentifier.builder().node(NetworkTopology.QNAME)
201                 .node(Topology.QNAME)
202                 .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), "topology-netconf")
203                 .node(Node.QNAME)
204                 .nodeWithKey(Node.QNAME, QName.create(Node.QNAME, "node-id"), "test")
205                 .node(netconfTestLeafQname).build();
206
207         NormalizedNode<?, ?> augmentNode = ImmutableLeafNodeBuilder.create().withValue(dataTestId)
208                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(netconfTestLeafQname)).build();
209
210         DOMDataWriteTransaction wtx =  domDataBroker.newWriteOnlyTransaction();
211         wtx.put(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf, augmentNode);
212         wtx.commit().get(5, TimeUnit.SECONDS);
213
214         adapter.updateDeviceData(true, new NetconfDeviceCapabilities());
215         Optional<NormalizedNode<?, ?>> testNode = domDataBroker.newReadOnlyTransaction()
216                 .read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).get(2, TimeUnit.SECONDS);
217
218         assertEquals("Augmented node data should be still present after device update.", true, testNode.isPresent());
219         assertEquals("Augmented data should be the same as before update node.", dataTestId, testNode.get().getValue());
220
221         adapter.setDeviceAsFailed(null);
222         testNode = domDataBroker.newReadOnlyTransaction()
223                 .read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).get(2, TimeUnit.SECONDS);
224
225         assertEquals("Augmented node data should be still present after device failed.", true, testNode.isPresent());
226         assertEquals("Augmented data should be the same as before failed device.",
227                 dataTestId, testNode.get().getValue());
228     }
229
230     private DOMSchemaService createSchemaService() {
231         return new DOMSchemaService() {
232
233             @Override
234             public SchemaContext getSessionContext() {
235                 return schemaContext;
236             }
237
238             @Override
239             public SchemaContext getGlobalContext() {
240                 return schemaContext;
241             }
242
243             @Override
244             public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
245                     final SchemaContextListener listener) {
246                 listener.onGlobalContextUpdated(getGlobalContext());
247                 return new AbstractListenerRegistration<SchemaContextListener>(listener) {
248                     @Override
249                     protected void removeRegistration() {
250                         // No-op
251                     }
252                 };
253             }
254
255             @Override
256             public ClassToInstanceMap<DOMSchemaServiceExtension> getExtensions() {
257                 return ImmutableClassToInstanceMap.of();
258             }
259         };
260     }
261
262     @Test
263     public void testRemoveDeviceConfiguration() throws Exception {
264         doReturn(emptyFluentFuture()).when(writeTx).commit();
265
266         NetconfDeviceTopologyAdapter adapter = new NetconfDeviceTopologyAdapter(id, txChain);
267         adapter.close();
268
269         verify(txChain, times(2)).newWriteOnlyTransaction();
270         verify(writeTx).delete(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath());
271         verify(writeTx, times(2)).commit();
272     }
273
274 }