Merge "Bug 1593 - Flow Statistics manager is updating store with incorrect key Statis...
[controller.git] / opendaylight / netconf / netconf-it / src / test / java / org / opendaylight / controller / netconf / it / NetconfITSecureTest.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
9 package org.opendaylight.controller.netconf.it;
10
11 import static java.util.Arrays.asList;
12 import static org.junit.Assert.assertTrue;
13 import static org.mockito.Matchers.anyString;
14 import static org.mockito.Mockito.doReturn;
15 import static org.mockito.Mockito.mock;
16
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.lang.management.ManagementFactory;
20 import java.net.InetSocketAddress;
21 import java.util.Collection;
22 import java.util.List;
23 import java.util.concurrent.atomic.AtomicInteger;
24
25 import junit.framework.Assert;
26
27 import org.junit.After;
28 import org.junit.Before;
29 import org.junit.Test;
30 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
31 import org.opendaylight.controller.config.spi.ModuleFactory;
32 import org.opendaylight.controller.netconf.api.NetconfMessage;
33 import org.opendaylight.controller.netconf.auth.AuthProvider;
34 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
35 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
36 import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
37 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
38 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
39 import org.opendaylight.controller.netconf.client.test.TestingNetconfClient;
40 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.NetconfOperationServiceFactoryImpl;
41 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreException;
42 import org.opendaylight.controller.netconf.impl.DefaultCommitNotificationProducer;
43 import org.opendaylight.controller.netconf.impl.NetconfServerDispatcher;
44 import org.opendaylight.controller.netconf.impl.osgi.NetconfOperationServiceFactoryListenerImpl;
45 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
46 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
47 import org.opendaylight.controller.netconf.ssh.NetconfSSHServer;
48 import org.opendaylight.controller.netconf.ssh.authentication.PEMGenerator;
49 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
50 import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
51 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
52 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
53 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
54
55 import com.google.common.collect.Lists;
56
57 import io.netty.channel.ChannelFuture;
58 import io.netty.channel.EventLoopGroup;
59 import io.netty.channel.nio.NioEventLoopGroup;
60 import io.netty.util.concurrent.Future;
61 import io.netty.util.concurrent.GenericFutureListener;
62 import io.netty.util.concurrent.GlobalEventExecutor;
63
64 public class NetconfITSecureTest extends AbstractNetconfConfigTest {
65
66     private static final InetSocketAddress tlsAddress = new InetSocketAddress("127.0.0.1", 12024);
67
68     private DefaultCommitNotificationProducer commitNot;
69     private NetconfSSHServer sshServer;
70     private NetconfMessage getConfig;
71
72     @Before
73     public void setUp() throws Exception {
74         this.getConfig = XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/getConfig.xml");
75
76         super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, getModuleFactories().toArray(
77                 new ModuleFactory[0])));
78
79         final NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
80         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
81
82         commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
83
84
85         final NetconfServerDispatcher dispatchS = createDispatcher(factoriesListener);
86         ChannelFuture s = dispatchS.createLocalServer(NetconfConfigUtil.getNetconfLocalAddress());
87         s.await();
88         EventLoopGroup bossGroup  = new NioEventLoopGroup();
89
90         final char[] pem = PEMGenerator.generate().toCharArray();
91         sshServer = NetconfSSHServer.start(tlsAddress.getPort(), NetconfConfigUtil.getNetconfLocalAddress(), bossGroup, pem);
92         sshServer.setAuthProvider(getAuthProvider());
93     }
94
95     private NetconfServerDispatcher createDispatcher(final NetconfOperationServiceFactoryListenerImpl factoriesListener) {
96         return super.createDispatcher(factoriesListener, NetconfITTest.getNetconfMonitoringListenerService(), commitNot);
97     }
98
99     @After
100     public void tearDown() throws Exception {
101         sshServer.close();
102         commitNot.close();
103         sshServer.join();
104     }
105
106     private HardcodedYangStoreService getYangStore() throws YangStoreException, IOException {
107         final Collection<InputStream> yangDependencies = NetconfITTest.getBasicYangs();
108         return new HardcodedYangStoreService(yangDependencies);
109     }
110
111     protected List<ModuleFactory> getModuleFactories() {
112         return asList(NetconfITTest.FACTORIES);
113     }
114
115     @Test
116     public void testSecure() throws Exception {
117         final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
118         try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration())) {
119             NetconfMessage response = netconfClient.sendMessage(getConfig);
120             Assert.assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
121                     NetconfMessageUtil.isErrorMessage(response));
122
123             final NetconfMessage gs = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"2\"\n" +
124                     "     xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
125                     "    <get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
126                     "        <identifier>config</identifier>\n" +
127                     "    </get-schema>\n" +
128                     "</rpc>\n"));
129
130             response = netconfClient.sendMessage(gs);
131             Assert.assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
132                     NetconfMessageUtil.isErrorMessage(response));
133         }
134     }
135
136     /**
137      * Test all requests are handled properly and no mismatch occurs in listener
138      */
139     @Test(timeout = 3*60*1000)
140     public void testSecureStress() throws Exception {
141         final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
142         try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration())) {
143
144             final AtomicInteger responseCounter = new AtomicInteger(0);
145             final List<Future<?>> futures = Lists.newArrayList();
146
147             final int requests = 1000;
148             for (int i = 0; i < requests; i++) {
149                 final Future<NetconfMessage> netconfMessageFuture = netconfClient.sendRequest(getConfig);
150                 futures.add(netconfMessageFuture);
151                 netconfMessageFuture.addListener(new GenericFutureListener<Future<? super NetconfMessage>>() {
152                     @Override
153                     public void operationComplete(final Future<? super NetconfMessage> future) throws Exception {
154                         assertTrue("Request unsuccessful " + future.cause(), future.isSuccess());
155                         responseCounter.incrementAndGet();
156                     }
157                 });
158             }
159
160             for (final Future<?> future : futures) {
161                 future.await();
162             }
163
164             // Give future listeners some time to finish counter incrementation
165             Thread.sleep(5000);
166
167             org.junit.Assert.assertEquals(requests, responseCounter.get());
168         }
169     }
170
171     public NetconfClientConfiguration getClientConfiguration() throws IOException {
172         final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
173         b.withAddress(tlsAddress);
174         b.withSessionListener(new SimpleNetconfClientSessionListener());
175         b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000));
176         b.withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH);
177         b.withConnectionTimeoutMillis(5000);
178         b.withAuthHandler(getAuthHandler());
179         return b.build();
180     }
181
182     public AuthProvider getAuthProvider() throws Exception {
183         AuthProvider mock = mock(AuthProvider.class);
184         doReturn(true).when(mock).authenticated(anyString(), anyString());
185         return mock;
186     }
187
188     public AuthenticationHandler getAuthHandler() throws IOException {
189         return new LoginPassword("user", "pwd");
190     }
191 }