7cdcb1bd28b916716f5f7b50ce4955605e56a3f0
[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.mock;
17 import com.google.common.io.ByteStreams;
18 import io.netty.channel.Channel;
19 import io.netty.channel.ChannelFuture;
20 import io.netty.channel.EventLoopGroup;
21 import io.netty.channel.local.LocalAddress;
22 import io.netty.channel.nio.NioEventLoopGroup;
23 import io.netty.util.HashedWheelTimer;
24 import io.netty.util.concurrent.GlobalEventExecutor;
25 import java.io.ByteArrayInputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.net.InetSocketAddress;
29 import java.net.SocketAddress;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.Collection;
33 import java.util.Collections;
34 import java.util.HashSet;
35 import java.util.List;
36 import java.util.concurrent.TimeUnit;
37 import org.junit.After;
38 import org.junit.Before;
39 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
40 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
41 import org.opendaylight.controller.config.spi.ModuleFactory;
42 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
43 import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
44 import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleFactory;
45 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
46 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
47 import org.opendaylight.controller.netconf.api.NetconfMessage;
48 import org.opendaylight.controller.netconf.api.monitoring.NetconfMonitoringService;
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.YangStoreService;
55 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
56 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcherImpl;
57 import org.opendaylight.controller.netconf.impl.NetconfServerSessionNegotiatorFactory;
58 import org.opendaylight.controller.netconf.impl.SessionIdProvider;
59 import org.opendaylight.controller.netconf.impl.osgi.AggregatedNetconfOperationServiceFactory;
60 import org.opendaylight.controller.netconf.impl.osgi.NetconfMonitoringServiceImpl;
61 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationServiceFactory;
62 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringActivator;
63 import org.opendaylight.controller.netconf.monitoring.osgi.NetconfMonitoringOperationService;
64 import org.opendaylight.controller.netconf.notifications.BaseNetconfNotificationListener;
65 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
66 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
67 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
70 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
71 import org.w3c.dom.Element;
72
73 public abstract class AbstractNetconfConfigTest extends AbstractConfigTest {
74
75     public static final String LOOPBACK_ADDRESS = "127.0.0.1";
76     public static final int SERVER_CONNECTION_TIMEOUT_MILLIS = 5000;
77     private static final int RESOURCE_TIMEOUT_MINUTES = 2;
78
79     static ModuleFactory[] FACTORIES = {new TestImplModuleFactory(),
80                                         new DepTestImplModuleFactory(),
81                                         new NetconfTestImplModuleFactory(),
82                                         new IdentityTestModuleFactory(),
83                                         new MultipleDependenciesModuleFactory() };
84
85     private EventLoopGroup nettyThreadgroup;
86     private HashedWheelTimer hashedWheelTimer;
87
88     private NetconfClientDispatcherImpl clientDispatcher;
89     private Channel serverTcpChannel;
90
91     private NetconfMessage getConfig;
92     private NetconfMessage get;
93
94     /**
95      * @Before in subclasses is called after this method.
96      */
97     @Before
98     public void setUpAbstractNetconfConfigTest() throws Exception {
99         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, FACTORIES));
100
101         nettyThreadgroup = new NioEventLoopGroup();
102         hashedWheelTimer = new HashedWheelTimer();
103
104         loadMessages();
105
106         setUpTestInitial();
107
108         final AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
109         final NetconfMonitoringService netconfMonitoringService = getNetconfMonitoringService(factoriesListener);
110         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
111         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfMonitoringActivator.NetconfMonitoringOperationServiceFactory(new NetconfMonitoringOperationService(netconfMonitoringService)));
112
113         for (final NetconfOperationServiceFactory netconfOperationServiceFactory : getAdditionalServiceFactories(factoriesListener)) {
114             factoriesListener.onAddNetconfOperationServiceFactory(netconfOperationServiceFactory);
115         }
116
117         serverTcpChannel = startNetconfTcpServer(factoriesListener, netconfMonitoringService);
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 AggregatedNetconfOperationServiceFactory listener, final NetconfMonitoringService monitoring) throws Exception {
140         final NetconfServerDispatcherImpl dispatch = createDispatcher(listener, monitoring, 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(RESOURCE_TIMEOUT_MINUTES, TimeUnit.MINUTES);
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(final AggregatedNetconfOperationServiceFactory factoriesListener) throws Exception {
160         return Collections.emptySet();
161     }
162
163     protected NetconfMonitoringService getNetconfMonitoringService(final AggregatedNetconfOperationServiceFactory factoriesListener) throws Exception {
164         return new NetconfMonitoringServiceImpl(factoriesListener);
165     }
166
167     protected abstract SocketAddress getTcpServerAddress();
168
169     public NetconfClientDispatcherImpl getClientDispatcher() {
170         return clientDispatcher;
171     }
172
173     private HardcodedYangStoreService getYangStore() throws IOException {
174         final Collection<InputStream> yangDependencies = getBasicYangs();
175         return new HardcodedYangStoreService(yangDependencies);
176     }
177
178     static Collection<InputStream> getBasicYangs() throws IOException {
179
180         final List<String> paths = Arrays.asList(
181                 "/META-INF/yang/config.yang",
182                 "/META-INF/yang/rpc-context.yang",
183                 "/META-INF/yang/config-test.yang",
184                 "/META-INF/yang/config-test-impl.yang",
185                 "/META-INF/yang/test-types.yang",
186                 "/META-INF/yang/test-groups.yang",
187                 "/META-INF/yang/ietf-inet-types.yang");
188
189         final Collection<InputStream> yangDependencies = new ArrayList<>();
190         final List<String> failedToFind = new ArrayList<>();
191         for (final String path : paths) {
192             final InputStream resourceAsStream = NetconfITTest.class.getResourceAsStream(path);
193             if (resourceAsStream == null) {
194                 failedToFind.add(path);
195             } else {
196                 yangDependencies.add(resourceAsStream);
197             }
198         }
199         assertEquals("Some yang files were not found", Collections.<String>emptyList(), failedToFind);
200         return yangDependencies;
201     }
202
203     protected NetconfServerDispatcherImpl createDispatcher(
204             final AggregatedNetconfOperationServiceFactory factoriesListener, final NetconfMonitoringService sessionMonitoringService,
205             final DefaultCommitNotificationProducer commitNotifier) {
206         final SessionIdProvider idProvider = new SessionIdProvider();
207
208         final NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactory(
209                 hashedWheelTimer, factoriesListener, idProvider, SERVER_CONNECTION_TIMEOUT_MILLIS, commitNotifier, sessionMonitoringService);
210
211         final NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(
212                 serverNegotiatorFactory);
213         return new NetconfServerDispatcherImpl(serverChannelInitializer, nettyThreadgroup, nettyThreadgroup);
214     }
215
216     protected HashedWheelTimer getHashedWheelTimer() {
217         return hashedWheelTimer;
218     }
219
220     protected EventLoopGroup getNettyThreadgroup() {
221         return nettyThreadgroup;
222     }
223
224     /**
225      * @After in subclasses is be called before this.
226      */
227     @After
228     public void cleanUpNetconf() throws Exception {
229         serverTcpChannel.close().await(RESOURCE_TIMEOUT_MINUTES, TimeUnit.MINUTES);
230         hashedWheelTimer.stop();
231         nettyThreadgroup.shutdownGracefully().await(RESOURCE_TIMEOUT_MINUTES, TimeUnit.MINUTES);
232     }
233
234     public NetconfClientConfiguration getClientConfiguration(final InetSocketAddress tcpAddress, final int timeout) {
235         final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
236         b.withAddress(tcpAddress);
237         b.withSessionListener(new SimpleNetconfClientSessionListener());
238         b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, timeout));
239         b.withConnectionTimeoutMillis(timeout);
240         return b.build();
241     }
242
243     public static final class HardcodedYangStoreService extends YangStoreService {
244         public HardcodedYangStoreService(final Collection<? extends InputStream> inputStreams) throws IOException {
245             super(new SchemaContextProvider() {
246                 @Override
247                 public SchemaContext getSchemaContext() {
248                     return getSchema(inputStreams);
249                 }
250             }, new BaseNetconfNotificationListener() {
251                 @Override
252                 public void onCapabilityChanged(final NetconfCapabilityChange capabilityChange) {
253                     // NOOP
254                 }
255             });
256         }
257
258         private static SchemaContext getSchema(final Collection<? extends InputStream> inputStreams) {
259             final ArrayList<InputStream> byteArrayInputStreams = new ArrayList<>();
260             for (final InputStream inputStream : inputStreams) {
261                 assertNotNull(inputStream);
262                 final byte[] content;
263                 try {
264                     content = ByteStreams.toByteArray(inputStream);
265                 } catch (IOException e) {
266                     throw new IllegalStateException("Cannot read " + inputStream, e);
267                 }
268                 final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content);
269                 byteArrayInputStreams.add(byteArrayInputStream);
270             }
271
272             for (final InputStream inputStream : byteArrayInputStreams) {
273                 try {
274                     inputStream.reset();
275                 } catch (final IOException e) {
276                     throw new RuntimeException(e);
277                 }
278             }
279
280             final YangParserImpl yangParser = new YangParserImpl();
281             return yangParser.resolveSchemaContext(new HashSet<>(yangParser.parseYangModelsFromStreamsMapped(byteArrayInputStreams).values()));
282         }
283     }
284 }