Rework NETCONF client reconnection
[netconf.git] / netconf / tools / netconf-testtool / src / test / java / org / opendaylight / netconf / test / tool / TestToolTest.java
1 /*
2  * Copyright (C) 2019 Ericsson Software Technology AB. 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.netconf.test.tool;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNotNull;
13 import static org.xmlunit.assertj.XmlAssert.assertThat;
14
15 import com.google.common.collect.ImmutableMap;
16 import io.netty.channel.nio.NioEventLoopGroup;
17 import io.netty.util.HashedWheelTimer;
18 import io.netty.util.concurrent.DefaultThreadFactory;
19 import java.io.File;
20 import java.net.InetSocketAddress;
21 import java.util.Map;
22 import java.util.Set;
23 import java.util.concurrent.ConcurrentHashMap;
24 import java.util.concurrent.TimeUnit;
25 import java.util.regex.Pattern;
26 import org.junit.AfterClass;
27 import org.junit.BeforeClass;
28 import org.junit.Rule;
29 import org.junit.Test;
30 import org.opendaylight.netconf.api.NetconfMessage;
31 import org.opendaylight.netconf.api.xml.XmlUtil;
32 import org.opendaylight.netconf.auth.AuthProvider;
33 import org.opendaylight.netconf.client.NetconfClientDispatcher;
34 import org.opendaylight.netconf.client.NetconfClientDispatcherImpl;
35 import org.opendaylight.netconf.client.NetconfClientSession;
36 import org.opendaylight.netconf.client.NetconfClientSessionListener;
37 import org.opendaylight.netconf.client.SimpleNetconfClientSessionListener;
38 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
39 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration.NetconfClientProtocol;
40 import org.opendaylight.netconf.client.conf.NetconfClientConfigurationBuilder;
41 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.LoginPasswordHandler;
42 import org.opendaylight.netconf.test.tool.config.Configuration;
43 import org.opendaylight.netconf.test.tool.config.ConfigurationBuilder;
44 import org.opendaylight.netconf.test.tool.config.YangResource;
45 import org.w3c.dom.Document;
46
47 @SuppressWarnings("SameParameterValue")
48 public class TestToolTest {
49
50     private static final long RECEIVE_TIMEOUT_MS = 5_000;
51     private static final int RANDOM_PORT = 0;
52
53     private static final User ADMIN_USER = new User("admin", "admin");
54     private static final File CUSTOM_RPC_CONFIG = new File("src/test/resources/customrpc.xml");
55     private static final Configuration SSH_SIMULATOR_CONFIG = getSimulatorConfig(NetconfClientProtocol.SSH,
56         ADMIN_USER);
57     private static final Configuration TCP_SIMULATOR_CONFIG = getSimulatorConfig(NetconfClientProtocol.SSH,
58         ADMIN_USER);
59
60     private static NioEventLoopGroup nettyGroup;
61     private static NetconfClientDispatcherImpl dispatcher;
62
63
64     @Rule
65     public LogPropertyCatcher logPropertyCatcher =
66         new LogPropertyCatcher(Pattern.compile("(start\\(\\) listen on auto-allocated port="
67             + "|Simulated TCP device started on (/0:0:0:0:0:0:0:0|/0.0.0.0):)(\\d+)"));
68
69     private static final String XML_REQUEST_RFC7950_SECTION_4_2_9 = "<rpc message-id=\"101\"\n"
70         + "          xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
71         + "       <activate-software-image xmlns=\"http://example.com/system\">\n"
72         + "         <image-name>example-fw-2.3</image-name>\n"
73         + "       </activate-software-image>\n"
74         + "     </rpc>";
75     private static final String EXPECTED_XML_RESPONSE_RFC7950_SECTION_4_2_9 = "<rpc-reply message-id=\"101\"\n"
76         + "                xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
77         + "       <status xmlns=\"http://example.com/system\">\n"
78         + "         The image example-fw-2.3 is being installed.\n"
79         + "       </status>\n"
80         + "     </rpc-reply>";
81     private static final String XML_REQUEST_RFC7950_SECTION_7_15_3 = "<rpc message-id=\"101\"\n"
82         + "          xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
83         + "       <action xmlns=\"urn:ietf:params:xml:ns:yang:1\">\n"
84         + "         <server xmlns=\"urn:example:server-farm\">\n"
85         + "           <name>apache-1</name>\n"
86         + "           <reset>\n"
87         + "             <reset-at>2014-07-29T13:42:00Z</reset-at>\n"
88         + "           </reset>\n"
89         + "         </server>\n"
90         + "       </action>\n"
91         + "     </rpc>";
92     private static final String EXPECTED_XML_RESPONSE_RFC7950_SECTION_7_15_3 = "<rpc-reply message-id=\"101\"\n"
93         + "           xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
94         + "  <reset-finished-at xmlns=\"urn:example:server-farm\">\n"
95         + "    2014-07-29T13:42:12Z\n"
96         + "  </reset-finished-at>\n"
97         + "</rpc-reply>";
98     private static final Map<String, String> PREFIX_2_URI = ImmutableMap.of(
99         "base10", "urn:ietf:params:xml:ns:netconf:base:1.0",
100         "ncmon", "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring"
101     );
102
103     @BeforeClass
104     public static void setUpClass() {
105         HashedWheelTimer hashedWheelTimer = new HashedWheelTimer();
106         nettyGroup = new NioEventLoopGroup(1, new DefaultThreadFactory(NetconfClientDispatcher.class));
107         dispatcher = new NetconfClientDispatcherImpl(nettyGroup, nettyGroup, hashedWheelTimer);
108     }
109
110     @AfterClass
111     public static void cleanUpClass()
112         throws InterruptedException {
113         nettyGroup.shutdownGracefully().sync();
114     }
115
116     @Test
117     public void customRpcOverSsh()
118         throws Exception {
119         Document docResponse = invokeRpc(SSH_SIMULATOR_CONFIG, XML_REQUEST_RFC7950_SECTION_7_15_3);
120         assertThat(docResponse)
121             .and(EXPECTED_XML_RESPONSE_RFC7950_SECTION_7_15_3)
122             .ignoreWhitespace()
123             .areIdentical();
124     }
125
126     @Test
127     public void customRpcOverTcp()
128         throws Exception {
129         Document docResponse = invokeRpc(TCP_SIMULATOR_CONFIG, XML_REQUEST_RFC7950_SECTION_4_2_9);
130         assertThat(docResponse)
131             .and(EXPECTED_XML_RESPONSE_RFC7950_SECTION_4_2_9)
132             .ignoreWhitespace()
133             .areIdentical();
134     }
135
136     @Test
137     public void shouldSupportGetSchema()
138         throws Exception {
139         String getSchema = "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"m-0\">\n"
140             + "  <get>\n"
141             + "    <filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\">\n"
142             + "      <netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
143             + "        <schemas/>\n"
144             + "      </netconf-state>\n"
145             + "    </filter>\n"
146             + "  </get>\n"
147             + "</rpc>";
148         Document docResponse = invokeRpc(TCP_SIMULATOR_CONFIG, getSchema);
149         Set<YangResource> expectedYangResources = Configuration.DEFAULT_YANG_RESOURCES;
150         assertEquals(4, expectedYangResources.size());
151         assertThat(docResponse)
152             .withNamespaceContext(PREFIX_2_URI)
153             .valueByXPath("count(//base10:rpc-reply/base10:data/ncmon:netconf-state/ncmon:schemas/ncmon:schema)")
154             .isEqualTo(expectedYangResources.size());
155     }
156
157     private Document invokeRpc(final Configuration simulatorConfig, final String xmlRequest)
158         throws Exception {
159         // GIVEN
160         int localPort = launchSimulator(simulatorConfig);
161         SimpleNetconfClientSessionListener sessionListener = new SimpleNetconfClientSessionListener();
162         NetconfClientConfiguration clientConfig = getClientConfig("localhost", localPort,
163             simulatorConfig, sessionListener);
164         Document docRequest = XmlUtil.readXmlToDocument(xmlRequest);
165         NetconfMessage request = new NetconfMessage(docRequest);
166
167         // WHEN
168         NetconfMessage response;
169         try (NetconfClientSession ignored = dispatcher.createClient(clientConfig).get()) {
170             response = sessionListener.sendRequest(request)
171                 .get(RECEIVE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
172         }
173
174         // THEN
175         assertNotNull(response);
176         return response.getDocument();
177     }
178
179     private static final ConcurrentHashMap<Configuration, Integer> CACHED_SIMULATORS = new ConcurrentHashMap<>();
180
181     /**
182      * Retrieves a previously launched simulator or launches a new one using the given configuration.
183      *
184      * @param configuration The simulator configuration.
185      * @return The TCP port number to access the launched simulator.
186      */
187     private int launchSimulator(final Configuration configuration) {
188         return CACHED_SIMULATORS.computeIfAbsent(configuration, cfg -> {
189             NetconfDeviceSimulator simulator = new NetconfDeviceSimulator(cfg);
190             simulator.start();
191             return logPropertyCatcher.getLastValue()
192                 .map(Integer::parseInt)
193                 .orElseThrow(() -> new IllegalArgumentException("Unable to capture auto-allocated port from log"));
194         });
195     }
196
197     @SuppressWarnings("deprecation")
198     private static Configuration getSimulatorConfig(final NetconfClientProtocol protocol, final User user) {
199         return new ConfigurationBuilder()
200             .setStartingPort(RANDOM_PORT)
201             .setRpcConfigFile(CUSTOM_RPC_CONFIG)
202             .setSsh(protocol == NetconfClientProtocol.SSH)
203             .setAuthProvider(new InMemoryAuthenticationProvider(user))
204             .build();
205     }
206
207     private static NetconfClientConfiguration getClientConfig(final String host, final int port,
208                                                               final Configuration simulatorConfig,
209                                                               final NetconfClientSessionListener sessionListener) {
210         User user = ((InMemoryAuthenticationProvider) simulatorConfig.getAuthProvider()).user;
211         return NetconfClientConfigurationBuilder.create()
212             .withAddress(new InetSocketAddress(host, port))
213             .withSessionListener(sessionListener)
214             .withProtocol(simulatorConfig.isSsh() ? NetconfClientProtocol.SSH : NetconfClientProtocol.TCP)
215             .withAuthHandler(new LoginPasswordHandler(user.username, user.password))
216             .build();
217     }
218
219     private static final class User {
220         private final String username;
221         private final String password;
222
223         private User(final String username, final String password) {
224             this.username = username;
225             this.password = password;
226         }
227     }
228
229     private static final class InMemoryAuthenticationProvider implements AuthProvider {
230
231         private final User user;
232
233         private InMemoryAuthenticationProvider(final User user) {
234             this.user = user;
235         }
236
237         @Override
238         public boolean authenticated(final String username, final String password) {
239             return user.username.equals(username) && user.password.equals(password);
240         }
241     }
242 }