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