Allow rpc definition for RuntimeMXBeans to come from groupings
[controller.git] / opendaylight / netconf / netconf-it / src / test / java / org / opendaylight / controller / netconf / it / AbstractNetconfConfigTest.java
1 /*
2  * Copyright (c) 2013 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.netconf.it;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.mockito.Matchers.any;
13 import static org.mockito.Matchers.anySetOf;
14 import static org.mockito.Matchers.anyString;
15 import static org.mockito.Mockito.doNothing;
16 import static org.mockito.Mockito.doReturn;
17 import static org.mockito.Mockito.mock;
18
19 import io.netty.channel.Channel;
20 import io.netty.channel.ChannelFuture;
21 import io.netty.channel.EventLoopGroup;
22 import io.netty.channel.local.LocalAddress;
23 import io.netty.channel.nio.NioEventLoopGroup;
24 import io.netty.util.HashedWheelTimer;
25 import io.netty.util.concurrent.GlobalEventExecutor;
26 import java.io.ByteArrayInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.net.InetSocketAddress;
30 import java.net.SocketAddress;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Collection;
34 import java.util.Collections;
35 import java.util.HashSet;
36 import java.util.List;
37 import org.apache.commons.io.IOUtils;
38 import org.junit.After;
39 import org.junit.Before;
40 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
41 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
42 import org.opendaylight.controller.config.spi.ModuleFactory;
43 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
44 import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
45 import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleFactory;
46 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
47 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
48 import org.opendaylight.controller.netconf.api.NetconfMessage;
49 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
50 import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
51 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
52 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
53 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
54 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException;
55 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreService;
56 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreServiceImpl;
57 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
58 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
59 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
60 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
61 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
62 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
63 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
64 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceSnapshotImpl;
65 import org.opendaylight.controller.netconf.impl.osgi.SessionMonitoringService;
66 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationProvider;
67 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationService;
68 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
69 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
70 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
73 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
74 import org.w3c.dom.Element;
75
76 public abstract class AbstractNetconfConfigTest extends AbstractConfigTest {
77
78     public static final String LOOPBACK_ADDRESS = "127.0.0.1";
79     public static final int SERVER_CONNECTION_TIMEOUT_MILLIS = 5000;
80
81     static ModuleFactory[] FACTORIES = {new TestImplModuleFactory(),
82                                         new DepTestImplModuleFactory(),
83                                         new NetconfTestImplModuleFactory(),
84                                         new IdentityTestModuleFactory(),
85                                         new MultipleDependenciesModuleFactory() };
86
87     private EventLoopGroup nettyThreadgroup;
88     private HashedWheelTimer hashedWheelTimer;
89
90     private NetconfClientDispatcherImpl clientDispatcher;
91     private Channel serverTcpChannel;
92
93     private NetconfMessage getConfig;
94     private NetconfMessage get;
95
96     /**
97      * @Before in subclasses is called after this method.
98      */
99     @Before
100     public void setUpAbstractNetconfConfigTest() throws Exception {
101         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, FACTORIES));
102
103         nettyThreadgroup = new NioEventLoopGroup();
104         hashedWheelTimer = new HashedWheelTimer();
105
106         loadMessages();
107
108         setUpTestInitial();
109
110         final NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
111         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
112
113         for (final NetconfOperationServiceFactory netconfOperationServiceFactory : getAdditionalServiceFactories()) {
114             factoriesListener.onAddNetconfOperationServiceFactory(netconfOperationServiceFactory);
115         }
116
117         serverTcpChannel = startNetconfTcpServer(factoriesListener);
118         clientDispatcher = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
119     }
120
121     /**
122      * Called before setUp method is executed, so test classes can set up resources before setUpAbstractNetconfConfigTest method is called.
123      */
124     protected void setUpTestInitial() throws Exception {}
125
126     private void loadMessages() throws Exception {
127         this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
128         this.get = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/get.xml");
129     }
130
131     public NetconfMessage getGetConfig() {
132         return getConfig;
133     }
134
135     public NetconfMessage getGet() {
136         return get;
137     }
138
139     private Channel startNetconfTcpServer(final NetconfOperationServiceFactoryListenerImpl factoriesListener) throws Exception {
140         final NetconfServerDispatcher dispatch = createDispatcher(factoriesListener, getNetconfMonitoringService(), getNotificationProducer());
141
142         final ChannelFuture s;
143         if(getTcpServerAddress() instanceof LocalAddress) {
144             s = dispatch.createLocalServer(((LocalAddress) getTcpServerAddress()));
145         } else {
146             s = dispatch.createServer(((InetSocketAddress) getTcpServerAddress()));
147         }
148         s.await();
149         return s.channel();
150     }
151
152     protected DefaultCommitNotificationProducer getNotificationProducer() {
153         final DefaultCommitNotificationProducer notificationProducer = mock(DefaultCommitNotificationProducer.class);
154         doNothing().when(notificationProducer).close();
155         doNothing().when(notificationProducer).sendCommitNotification(anyString(), any(Element.class), anySetOf(String.class));
156         return notificationProducer;
157     }
158
159     protected Iterable<NetconfOperationServiceFactory> getAdditionalServiceFactories() {
160         return Collections.emptySet();
161     }
162
163     protected SessionMonitoringService getNetconfMonitoringService() throws Exception {
164         final NetconfOperationProvider netconfOperationProvider = mock(NetconfOperationProvider.class);
165         final NetconfOperationServiceSnapshotImpl snap = mock(NetconfOperationServiceSnapshotImpl.class);
166         doReturn(Collections.<NetconfOperationService>emptySet()).when(snap).getServices();
167         doReturn(snap).when(netconfOperationProvider).openSnapshot(anyString());
168         return new NetconfMonitoringServiceImpl(netconfOperationProvider);
169     }
170
171     protected abstract SocketAddress getTcpServerAddress();
172
173     public NetconfClientDispatcherImpl getClientDispatcher() {
174         return clientDispatcher;
175     }
176
177     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
178         final Collection<InputStream> yangDependencies = getBasicYangs();
179         return new HardcodedYangStoreService(yangDependencies);
180     }
181
182     static Collection<InputStream> getBasicYangs() throws IOException {
183
184         final List<String> paths = Arrays.asList(
185                 "/META-INF/yang/config.yang",
186                 "/META-INF/yang/rpc-context.yang",
187                 "/META-INF/yang/config-test.yang",
188                 "/META-INF/yang/config-test-impl.yang",
189                 "/META-INF/yang/test-types.yang",
190                 "/META-INF/yang/test-groups.yang",
191                 "/META-INF/yang/ietf-inet-types.yang");
192
193         final Collection<InputStream> yangDependencies = new ArrayList<>();
194         final List<String> failedToFind = new ArrayList<>();
195         for (final String path : paths) {
196             final InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
197             if (resourceAsStream == null) {
198                 failedToFind.add(path);
199             } else {
200                 yangDependencies.add(resourceAsStream);
201             }
202         }
203         assertEquals("Some yang files were not found", Collections.<String>emptyList(), failedToFind);
204         return yangDependencies;
205     }
206
207     protected NetconfServerDispatcher createDispatcher(
208             final NetconfOperationServiceFactoryListenerImpl factoriesListener, final SessionMonitoringService sessionMonitoringService,
209             final DefaultCommitNotificationProducer commitNotifier) {
210         final SessionIdProvider idProvider = new SessionIdProvider();
211
212         final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
213                 hashedWheelTimer, factoriesListener, idProvider, SERVER_CONNECTION_TIMEOUT_MILLIS, commitNotifier, sessionMonitoringService);
214
215         final NetconfServerDispatcher.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcher.ServerChannelInitializer(
216                 serverNegotiatorFactory);
217         return new NetconfServerDispatcher(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
218     }
219
220     protected HashedWheelTimer getHashedWheelTimer() {
221         return hashedWheelTimer;
222     }
223
224     protected EventLoopGroup getNettyThreadgroup() {
225         return nettyThreadgroup;
226     }
227
228     /**
229      * @After in subclasses is be called before this.
230      */
231     @After
232     public void cleanUpNetconf() throws Exception {
233         serverTcpChannel.close().await();
234         hashedWheelTimer.stop();
235         nettyThreadgroup.shutdownGracefully().await();
236     }
237
238     public NetconfClientConfiguration getClientConfiguration(final InetSocketAddress tcpAddress, final int timeout) {
239         final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
240         b.withAddress(tcpAddress);
241         b.withSessionListener(new SimpleNetconfClientSessionListener());
242         b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, timeout));
243         b.withConnectionTimeoutMillis(timeout);
244         return b.build();
245     }
246
247     public static final class HardcodedYangStoreService implements YangStoreService {
248
249         private final List<InputStream> byteArrayInputStreams;
250
251         public HardcodedYangStoreService(final Collection<? extends InputStream> inputStreams) throws YangStoreException, IOException {
252             byteArrayInputStreams = new ArrayList<>();
253             for (final InputStream inputStream : inputStreams) {
254                 assertNotNull(inputStream);
255                 final byte[] content = IOUtils.toByteArray(inputStream);
256                 final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content);
257                 byteArrayInputStreams.add(byteArrayInputStream);
258             }
259         }
260
261         @Override
262         public YangStoreSnapshot getYangStoreSnapshot() throws YangStoreException {
263             for (final InputStream inputStream : byteArrayInputStreams) {
264                 try {
265                     inputStream.reset();
266                 } catch (final IOException e) {
267                     throw new RuntimeException(e);
268                 }
269             }
270
271             final YangParserImpl yangParser = new YangParserImpl();
272             final SchemaContext schemaContext = yangParser.resolveSchemaContext(new HashSet<>(yangParser.parseYangModelsFromStreamsMapped(byteArrayInputStreams).values()));
273             final YangStoreServiceImpl yangStoreService = new YangStoreServiceImpl(new SchemaContextProvider() {
274                 @Override
275                 public SchemaContext getSchemaContext() {
276                     return schemaContext ;
277                 }
278             });
279             return yangStoreService.getYangStoreSnapshot();
280         }
281     }
282 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.