Bug 2517: Catch RuntimeExceptions thrown from the DCL in DataChangeListener
[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 org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertFalse;
13 import static org.junit.Assert.fail;
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Matchers.anyString;
16 import static org.mockito.Mockito.doNothing;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19
20 import com.google.common.collect.Lists;
21 import com.google.common.util.concurrent.FutureCallback;
22 import com.google.common.util.concurrent.Futures;
23 import com.google.common.util.concurrent.ListenableFuture;
24 import io.netty.channel.EventLoopGroup;
25 import io.netty.channel.local.LocalAddress;
26 import io.netty.channel.nio.NioEventLoopGroup;
27 import io.netty.util.concurrent.GlobalEventExecutor;
28 import java.io.IOException;
29 import java.net.InetSocketAddress;
30 import java.nio.file.Files;
31 import java.util.List;
32 import java.util.concurrent.ExecutorService;
33 import java.util.concurrent.Executors;
34 import java.util.concurrent.ScheduledExecutorService;
35 import java.util.concurrent.TimeUnit;
36 import java.util.concurrent.TimeoutException;
37 import java.util.concurrent.atomic.AtomicInteger;
38 import org.apache.sshd.server.PasswordAuthenticator;
39 import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
40 import org.apache.sshd.server.session.ServerSession;
41 import org.junit.After;
42 import org.junit.Before;
43 import org.junit.Test;
44 import org.mockito.Mock;
45 import org.mockito.MockitoAnnotations;
46 import org.opendaylight.controller.netconf.api.NetconfMessage;
47 import org.opendaylight.controller.netconf.auth.AuthProvider;
48 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
49 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
50 import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
51 import org.opendaylight.controller.netconf.client.SimpleNetconfClientSessionListener;
52 import org.opendaylight.controller.netconf.client.TestingNetconfClient;
53 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
54 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
55 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
56 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
57 import org.opendaylight.controller.netconf.ssh.SshProxyServer;
58 import org.opendaylight.controller.netconf.ssh.SshProxyServerConfigurationBuilder;
59 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
60 import org.opendaylight.controller.netconf.util.osgi.NetconfConfigUtil;
61 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
62 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
63 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
64 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
65 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionCapabilities;
66 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
67 import org.opendaylight.protocol.framework.NeverReconnectStrategy;
68 import org.opendaylight.yangtools.yang.common.QName;
69 import org.opendaylight.yangtools.yang.common.RpcResult;
70 import org.xml.sax.SAXException;
71
72 public class NetconfITSecureTest extends AbstractNetconfConfigTest {
73
74     public static final int PORT = 12024;
75     private static final InetSocketAddress TLS_ADDRESS = new InetSocketAddress("127.0.0.1", PORT);
76
77     public static final String USERNAME = "user";
78     public static final String PASSWORD = "pwd";
79
80     private SshProxyServer sshProxyServer;
81
82     private ExecutorService nioExec;
83     private EventLoopGroup clientGroup;
84     private ScheduledExecutorService minaTimerEx;
85
86     @Before
87     public void setUp() throws Exception {
88         nioExec = Executors.newFixedThreadPool(1);
89         clientGroup = new NioEventLoopGroup();
90         minaTimerEx = Executors.newScheduledThreadPool(1);
91         sshProxyServer = new SshProxyServer(minaTimerEx, clientGroup, nioExec);
92         sshProxyServer.bind(
93                 new SshProxyServerConfigurationBuilder()
94                         .setBindingAddress(TLS_ADDRESS)
95                         .setLocalAddress(NetconfConfigUtil.getNetconfLocalAddress())
96                         .setAuthenticator(new PasswordAuthenticator() {
97                             @Override
98                             public boolean authenticate(final String username, final String password, final ServerSession session) {
99                                 return true;
100                             }
101                         }
102                     )
103                         .setKeyPairProvider(new PEMGeneratorHostKeyProvider(Files.createTempFile("prefix", "suffix").toAbsolutePath().toString()))
104                         .setIdleTimeout(Integer.MAX_VALUE)
105                         .createSshProxyServerConfiguration());
106     }
107
108     @After
109     public void tearDown() throws Exception {
110         sshProxyServer.close();
111         clientGroup.shutdownGracefully().await();
112         minaTimerEx.shutdownNow();
113         nioExec.shutdownNow();
114     }
115
116     @Test
117     public void testSecure() throws Exception {
118         final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
119         try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration(new SimpleNetconfClientSessionListener()))) {
120             NetconfMessage response = netconfClient.sendMessage(getGetConfig());
121             assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
122                     NetconfMessageUtil.isErrorMessage(response));
123
124             final NetconfMessage gs = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"2\"\n" +
125                     "     xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
126                     "    <get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
127                     "        <identifier>config</identifier>\n" +
128                     "    </get-schema>\n" +
129                     "</rpc>\n"));
130
131             response = netconfClient.sendMessage(gs);
132             assertFalse("Unexpected error message " + XmlUtil.toString(response.getDocument()),
133                     NetconfMessageUtil.isErrorMessage(response));
134         }
135     }
136
137     /**
138      * Test all requests are handled properly and no mismatch occurs in listener
139      */
140     @Test(timeout = 6*60*1000)
141     public void testSecureStress() throws Exception {
142         final int requests = 4000;
143
144         final NetconfClientDispatcher dispatch = new NetconfClientDispatcherImpl(getNettyThreadgroup(), getNettyThreadgroup(), getHashedWheelTimer());
145         final NetconfDeviceCommunicator sessionListener = getSessionListener();
146         try (TestingNetconfClient netconfClient = new TestingNetconfClient("testing-ssh-client", dispatch, getClientConfiguration(sessionListener))) {
147
148             final AtomicInteger responseCounter = new AtomicInteger(0);
149             final List<ListenableFuture<RpcResult<NetconfMessage>>> futures = Lists.newArrayList();
150
151             for (int i = 0; i < requests; i++) {
152                 NetconfMessage getConfig = getGetConfig();
153                 getConfig = changeMessageId(getConfig, i);
154                 final ListenableFuture<RpcResult<NetconfMessage>> netconfMessageFuture = sessionListener.sendRequest(getConfig, QName.create("namespace", "2012-12-12", "get"));
155                 futures.add(netconfMessageFuture);
156                 Futures.addCallback(netconfMessageFuture, new FutureCallback<RpcResult<NetconfMessage>>() {
157                     @Override
158                     public void onSuccess(final RpcResult<NetconfMessage> result) {
159                         responseCounter.incrementAndGet();
160                     }
161
162                     @Override
163                     public void onFailure(final Throwable t) {
164                         throw new RuntimeException(t);
165                     }
166                 });
167             }
168
169             // Wait for every future
170             for (final ListenableFuture<RpcResult<NetconfMessage>> future : futures) {
171                 try {
172                     future.get(3, TimeUnit.MINUTES);
173                 } catch (final TimeoutException e) {
174                     fail("Request " + futures.indexOf(future) + " is not responding");
175                 }
176             }
177
178             // Give future listeners some time to finish counter incrementation
179             Thread.sleep(5000);
180
181             assertEquals(requests, responseCounter.get());
182         }
183     }
184
185     private NetconfMessage changeMessageId(final NetconfMessage getConfig, final int i) throws IOException, SAXException {
186         String s = XmlUtil.toString(getConfig.getDocument(), false);
187         s = s.replace("101", Integer.toString(i));
188         return new NetconfMessage(XmlUtil.readXmlToDocument(s));
189     }
190
191     public NetconfClientConfiguration getClientConfiguration(final NetconfClientSessionListener sessionListener) throws IOException {
192         final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
193         b.withAddress(TLS_ADDRESS);
194         // Using session listener from sal-netconf-connector since stress test cannot be performed with simple listener
195         b.withSessionListener(sessionListener);
196         b.withReconnectStrategy(new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000));
197         b.withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH);
198         b.withConnectionTimeoutMillis(5000);
199         b.withAuthHandler(getAuthHandler());
200         return b.build();
201     }
202
203     @Mock
204     private RemoteDevice<NetconfSessionCapabilities, NetconfMessage> mockedRemoteDevice;
205
206     private NetconfDeviceCommunicator getSessionListener() {
207         MockitoAnnotations.initMocks(this);
208         doNothing().when(mockedRemoteDevice).onRemoteSessionUp(any(NetconfSessionCapabilities.class), any(RemoteDeviceCommunicator.class));
209         doNothing().when(mockedRemoteDevice).onRemoteSessionDown();
210         return new NetconfDeviceCommunicator(new RemoteDeviceId("secure-test"), mockedRemoteDevice);
211     }
212
213     public AuthProvider getAuthProvider() throws Exception {
214         final AuthProvider mockAuth = mock(AuthProvider.class);
215         doReturn("mockedAuth").when(mockAuth).toString();
216         doReturn(true).when(mockAuth).authenticated(anyString(), anyString());
217         return mockAuth;
218     }
219
220     public AuthenticationHandler getAuthHandler() throws IOException {
221         return new LoginPassword(USERNAME, PASSWORD);
222     }
223
224     @Override
225     protected LocalAddress getTcpServerAddress() {
226         return NetconfConfigUtil.getNetconfLocalAddress();
227     }
228 }