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