Merge "Add lispflowmapping specific configuration options"
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / test / java / org / opendaylight / controller / sal / binding / test / util / BindingTestContext.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.binding.test.util;
9
10 import static com.google.common.base.Preconditions.checkState;
11
12 import java.io.InputStream;
13 import java.util.ArrayList;
14 import java.util.List;
15 import java.util.Set;
16 import java.util.concurrent.Future;
17
18 import javassist.ClassPool;
19
20 import org.opendaylight.controller.md.sal.binding.impl.ForwardedBackwardsCompatibleDataBroker;
21 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
22 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
23 import org.opendaylight.controller.md.sal.dom.broker.impl.DOMDataBrokerImpl;
24 import org.opendaylight.controller.md.sal.dom.broker.impl.compat.BackwardsCompatibleDataBroker;
25 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
26 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
27 import org.opendaylight.controller.sal.binding.api.data.DataProviderService;
28 import org.opendaylight.controller.sal.binding.api.mount.MountProviderService;
29 import org.opendaylight.controller.sal.binding.impl.DataBrokerImpl;
30 import org.opendaylight.controller.sal.binding.impl.NotificationBrokerImpl;
31 import org.opendaylight.controller.sal.binding.impl.RpcProviderRegistryImpl;
32 import org.opendaylight.controller.sal.binding.impl.connect.dom.BindingDomConnectorDeployer;
33 import org.opendaylight.controller.sal.binding.impl.connect.dom.BindingIndependentConnector;
34 import org.opendaylight.controller.sal.binding.impl.forward.DomForwardedBindingBrokerImpl;
35 import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
36 import org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration;
37 import org.opendaylight.controller.sal.core.api.Broker.RpcRegistration;
38 import org.opendaylight.controller.sal.core.api.BrokerService;
39 import org.opendaylight.controller.sal.core.api.RpcImplementation;
40 import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
41 import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
42 import org.opendaylight.controller.sal.core.api.data.DataStore;
43 import org.opendaylight.controller.sal.core.api.mount.MountProvisionService;
44 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
45 import org.opendaylight.controller.sal.dom.broker.BrokerImpl;
46 import org.opendaylight.controller.sal.dom.broker.MountPointManagerImpl;
47 import org.opendaylight.controller.sal.dom.broker.impl.DataStoreStatsWrapper;
48 import org.opendaylight.controller.sal.dom.broker.impl.HashMapDataStore;
49 import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareDataStoreAdapter;
50 import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareRpcBroker;
51 import org.opendaylight.controller.sal.dom.broker.impl.SchemaContextProvider;
52 import org.opendaylight.yangtools.concepts.ListenerRegistration;
53 import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.common.RpcResult;
56 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
57 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
58 import org.opendaylight.yangtools.yang.model.api.Module;
59 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
61 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
62 import org.reflections.Reflections;
63 import org.reflections.scanners.ResourcesScanner;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 import com.google.common.base.Predicate;
68 import com.google.common.collect.ClassToInstanceMap;
69 import com.google.common.collect.ImmutableClassToInstanceMap;
70 import com.google.common.collect.ImmutableMap;
71 import com.google.common.util.concurrent.ListeningExecutorService;
72
73 public class BindingTestContext implements AutoCloseable, SchemaContextProvider {
74
75     public static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier TREE_ROOT = org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
76             .builder().toInstance();
77
78     private static final Logger LOG = LoggerFactory.getLogger(BindingTestContext.class);
79
80     private RuntimeGeneratedMappingServiceImpl mappingServiceImpl;
81
82     private DomForwardedBindingBrokerImpl baBrokerImpl;
83     private DataBrokerImpl baDataImpl;
84     private NotificationBrokerImpl baNotifyImpl;
85     private BindingIndependentConnector baConnectImpl;
86
87     private org.opendaylight.controller.sal.dom.broker.DataBrokerImpl biDataImpl;
88     private org.opendaylight.controller.sal.core.api.data.DataProviderService biDataLegacyBroker;
89     private BrokerImpl biBrokerImpl;
90     private HashMapDataStore rawDataStore;
91     private SchemaAwareDataStoreAdapter schemaAwareDataStore;
92     private DataStoreStatsWrapper dataStoreStats;
93     private DataStore dataStore;
94
95     private final boolean dataStoreStatisticsEnabled = false;
96
97     private final ListeningExecutorService executor;
98     private final ClassPool classPool;
99
100     private final boolean startWithSchema;
101
102     private MountPointManagerImpl biMountImpl;
103
104     private SchemaContext schemaContext;
105
106     private ImmutableMap<LogicalDatastoreType, DOMStore> newDatastores;
107
108     private BackwardsCompatibleDataBroker biCompatibleBroker;
109
110     private final List<SchemaContextListener> schemaListeners = new ArrayList<>();
111
112     private DataProviderService baData;
113
114     private DOMDataBroker newDOMDataBroker;
115
116     @Override
117     public SchemaContext getSchemaContext() {
118         return schemaContext;
119     }
120
121     public DOMDataBroker getDomAsyncDataBroker() {
122         return newDOMDataBroker;
123     }
124
125     protected BindingTestContext(final ListeningExecutorService executor, final ClassPool classPool, final boolean startWithSchema) {
126         this.executor = executor;
127         this.classPool = classPool;
128         this.startWithSchema = startWithSchema;
129     }
130
131     public void startDomDataStore() {
132         checkState(dataStore == null, "DataStore already started.");
133         checkState(biDataImpl != null, "Dom Data Broker not present");
134         rawDataStore = new HashMapDataStore();
135         schemaAwareDataStore = new SchemaAwareDataStoreAdapter();
136         schemaAwareDataStore.changeDelegate(rawDataStore);
137         if (dataStoreStatisticsEnabled) {
138             dataStoreStats = new DataStoreStatsWrapper(schemaAwareDataStore);
139             dataStore = dataStoreStats;
140         } else {
141             dataStore = schemaAwareDataStore;
142         }
143
144         biDataImpl.registerConfigurationReader(TREE_ROOT, dataStore);
145         biDataImpl.registerOperationalReader(TREE_ROOT, dataStore);
146         biDataImpl.registerCommitHandler(TREE_ROOT, dataStore);
147     }
148
149     public void startDomDataBroker() {
150         checkState(executor != null, "Executor needs to be set");
151         biDataImpl = new org.opendaylight.controller.sal.dom.broker.DataBrokerImpl();
152         biDataImpl.setExecutor(executor);
153         biDataLegacyBroker = biDataImpl;
154     }
155
156     public void startNewDomDataBroker() {
157         checkState(executor != null, "Executor needs to be set");
158         InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", executor);
159         InMemoryDOMDataStore configStore = new InMemoryDOMDataStore("CFG", executor);
160         newDatastores = ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
161                 .put(LogicalDatastoreType.OPERATIONAL, operStore)
162                 .put(LogicalDatastoreType.CONFIGURATION, configStore)
163                 .build();
164
165         newDOMDataBroker = new DOMDataBrokerImpl(newDatastores, executor);
166
167         biCompatibleBroker = new BackwardsCompatibleDataBroker(newDOMDataBroker);
168
169         schemaListeners.add(configStore);
170         schemaListeners.add(operStore);
171         schemaListeners.add(biCompatibleBroker);
172         biDataLegacyBroker = biCompatibleBroker;
173     }
174
175     public void startBindingDataBroker() {
176         checkState(executor != null, "Executor needs to be set");
177         baDataImpl = new DataBrokerImpl();
178         baDataImpl.setExecutor(executor);
179         baData = baDataImpl;
180     }
181
182     public void startBindingBroker() {
183         checkState(executor != null, "Executor needs to be set");
184         checkState(baData != null, "Binding Data Broker must be started");
185         checkState(baNotifyImpl != null, "Notification Service must be started");
186         baBrokerImpl = new DomForwardedBindingBrokerImpl("test");
187
188         baBrokerImpl.getMountManager().setDataCommitExecutor(executor);
189         baBrokerImpl.getMountManager().setNotificationExecutor(executor);
190         baBrokerImpl.setRpcBroker(new RpcProviderRegistryImpl("test"));
191         baBrokerImpl.setDataBroker(baData);
192         baBrokerImpl.setNotificationBroker(baNotifyImpl);
193         baBrokerImpl.start();
194     }
195
196     public void startForwarding() {
197         checkState(baData != null, "Binding Data Broker needs to be started");
198         checkState(biDataLegacyBroker != null, "DOM Data Broker needs to be started.");
199         checkState(mappingServiceImpl != null, "DOM Mapping Service needs to be started.");
200
201         baConnectImpl = BindingDomConnectorDeployer.createConnector(getBindingToDomMappingService());
202         baConnectImpl.setDomRpcRegistry(getDomRpcRegistry());
203         baBrokerImpl.setConnector(baConnectImpl);
204         baBrokerImpl.setDomProviderContext(createMockContext());
205         baBrokerImpl.startForwarding();
206     }
207
208     private ProviderSession createMockContext() {
209
210         final ClassToInstanceMap<BrokerService> domBrokerServices = ImmutableClassToInstanceMap
211                 .<BrokerService> builder()
212                 //
213                 .put(org.opendaylight.controller.sal.core.api.data.DataProviderService.class, biDataLegacyBroker) //
214                 .put(RpcProvisionRegistry.class, biBrokerImpl.getRouter()) //
215                 .put(MountProvisionService.class, biMountImpl) //
216                 .build();
217
218         return new ProviderSession() {
219
220             @Override
221             public Future<RpcResult<CompositeNode>> rpc(final QName rpc, final CompositeNode input) {
222                 throw new UnsupportedOperationException();
223             }
224
225             @Override
226             public <T extends BrokerService> T getService(final Class<T> service) {
227                 return domBrokerServices.getInstance(service);
228             }
229
230             @Override
231             public boolean isClosed() {
232                 return false;
233             }
234
235             @Override
236             public Set<QName> getSupportedRpcs() {
237                 return null;
238             }
239
240             @Override
241             public void close() {
242             }
243
244             @Override
245             public ListenerRegistration<RpcRegistrationListener> addRpcRegistrationListener(
246                     final RpcRegistrationListener listener) {
247                 return null;
248             }
249
250             @Override
251             public RpcRegistration addRpcImplementation(final QName rpcType, final RpcImplementation implementation)
252                     throws IllegalArgumentException {
253                 return null;
254             }
255
256             @Override
257             public RoutedRpcRegistration addRoutedRpcImplementation(final QName rpcType, final RpcImplementation implementation) {
258                 return null;
259             }
260
261             @Override
262             public RoutedRpcRegistration addMountedRpcImplementation(final QName rpcType, final RpcImplementation implementation) {
263                 return null;
264             }
265         };
266     }
267
268     public void startBindingToDomMappingService() {
269         checkState(classPool != null, "ClassPool needs to be present");
270         mappingServiceImpl = new RuntimeGeneratedMappingServiceImpl(classPool);
271     }
272
273     public void updateYangSchema(final String[] files) {
274         schemaContext = getContext(files);
275
276         if (schemaAwareDataStore != null) {
277             schemaAwareDataStore.onGlobalContextUpdated(schemaContext);
278         }
279         if (mappingServiceImpl != null) {
280             mappingServiceImpl.onGlobalContextUpdated(schemaContext);
281         }
282         for(SchemaContextListener listener : schemaListeners) {
283             listener.onGlobalContextUpdated(schemaContext);
284         }
285     }
286
287     public static String[] getAllYangFilesOnClasspath() {
288         Predicate<String> predicate = new Predicate<String>() {
289             @Override
290             public boolean apply(final String input) {
291                 return input.endsWith(".yang");
292             }
293         };
294         Reflections reflection = new Reflections("META-INF.yang", new ResourcesScanner());
295         Set<String> result = reflection.getResources(predicate);
296         return result.toArray(new String[result.size()]);
297     }
298
299     private static SchemaContext getContext(final String[] yangFiles) {
300         ClassLoader loader = BindingTestContext.class.getClassLoader();
301         List<InputStream> streams = new ArrayList<>();
302         for (String string : yangFiles) {
303             InputStream stream = loader.getResourceAsStream(string);
304             streams.add(stream);
305         }
306         YangParserImpl parser = new YangParserImpl();
307         Set<Module> modules = parser.parseYangModelsFromStreams(streams);
308         return parser.resolveSchemaContext(modules);
309     }
310
311     public void startLegacy() {
312         startBindingDataBroker();
313         startBindingNotificationBroker();
314         startBindingBroker();
315         startDomDataBroker();
316         startDomDataStore();
317         startDomBroker();
318         startDomMountPoint();
319         startBindingToDomMappingService();
320         startForwarding();
321         if (startWithSchema) {
322             loadYangSchemaFromClasspath();
323         }
324     }
325
326     public void start() {
327         startNewDomDataBroker();
328         startDomBroker();
329         startDomMountPoint();
330         startBindingToDomMappingService();
331         startNewBindingDataBroker();
332
333         startBindingNotificationBroker();
334         startBindingBroker();
335
336         startForwarding();
337         if (startWithSchema) {
338             loadYangSchemaFromClasspath();
339         }
340     }
341
342     public void startNewBindingDataBroker() {
343         ForwardedBackwardsCompatibleDataBroker forwarded = new ForwardedBackwardsCompatibleDataBroker(newDOMDataBroker, mappingServiceImpl, executor);
344         schemaListeners.add(forwarded);
345         baData = forwarded;
346     }
347
348     private void startDomMountPoint() {
349         biMountImpl = new MountPointManagerImpl();
350         biMountImpl.setDataBroker(getDomDataBroker());
351     }
352
353     private void startDomBroker() {
354         checkState(executor != null);
355         biBrokerImpl = new BrokerImpl();
356         biBrokerImpl.setRouter(new SchemaAwareRpcBroker("/", this));
357
358     }
359
360     public void startBindingNotificationBroker() {
361         checkState(executor != null);
362         baNotifyImpl = new NotificationBrokerImpl(executor);
363
364     }
365
366     public void loadYangSchemaFromClasspath() {
367         String[] files = getAllYangFilesOnClasspath();
368         updateYangSchema(files);
369     }
370
371     public DataProviderService getBindingDataBroker() {
372         return baData;
373     }
374
375     public org.opendaylight.controller.sal.core.api.data.DataProviderService getDomDataBroker() {
376         return biDataLegacyBroker;
377     }
378
379     public DataStore getDomDataStore() {
380         return dataStore;
381     }
382
383     public BindingIndependentMappingService getBindingToDomMappingService() {
384         return mappingServiceImpl;
385     }
386
387     public void logDataStoreStatistics() {
388         if (dataStoreStats == null) {
389             return;
390         }
391
392         LOG.info("BIDataStore Statistics: Configuration Read Count: {} TotalTime: {} ms AverageTime (ns): {} ms",
393                 dataStoreStats.getConfigurationReadCount(), dataStoreStats.getConfigurationReadTotalTime(),
394                 dataStoreStats.getConfigurationReadAverageTime());
395
396         LOG.info("BIDataStore Statistics: Operational Read Count: {} TotalTime: {} ms AverageTime (ns): {} ms",
397                 dataStoreStats.getOperationalReadCount(), dataStoreStats.getOperationalReadTotalTime(),
398                 dataStoreStats.getOperationalReadAverageTime());
399
400         LOG.info("BIDataStore Statistics: Request Commit Count: {} TotalTime: {} ms AverageTime (ns): {} ms",
401                 dataStoreStats.getRequestCommitCount(), dataStoreStats.getRequestCommitTotalTime(),
402                 dataStoreStats.getRequestCommitAverageTime());
403     }
404
405     public RpcProviderRegistry getBindingRpcRegistry() {
406         return baBrokerImpl.getRoot();
407     }
408
409     public RpcProvisionRegistry getDomRpcRegistry() {
410         if (biBrokerImpl == null) {
411             return null;
412         }
413         return biBrokerImpl.getRouter();
414     }
415
416     public RpcImplementation getDomRpcInvoker() {
417         return biBrokerImpl.getRouter();
418     }
419
420     @Override
421     public void close() throws Exception {
422
423     }
424
425     public MountProviderService getBindingMountProviderService() {
426         return baBrokerImpl.getMountManager();
427     }
428
429     public MountProvisionService getDomMountProviderService() {
430         return biMountImpl;
431     }
432 }