@Test
public void testConnectivityFailover() throws Exception {
String serviceName = "WEBHDFS";
HaDescriptor descriptor = HaDescriptorFactory.createDescriptor();
descriptor.addServiceConfig(HaDescriptorFactory.createServiceConfig(serviceName, "true", "1", "1000", "2", "1000"));
HaProvider provider = new DefaultHaProvider(descriptor);
URI uri1 = new URI( "http://unreachable-host" );
URI uri2 = new URI( "http://reachable-host" );
ArrayList<String> urlList = new ArrayList<String>();
urlList.add(uri1.toString());
urlList.add(uri2.toString());
provider.addHaService(serviceName, urlList);
FilterConfig filterConfig = EasyMock.createNiceMock(FilterConfig.class);
ServletContext servletContext = EasyMock.createNiceMock(ServletContext.class);
EasyMock.expect(filterConfig.getInitParameter(WebHdfsHaHttpClientDispatch.RESOURCE_ROLE_ATTRIBUTE)).andReturn(serviceName).anyTimes();
EasyMock.expect(filterConfig.getServletContext()).andReturn(servletContext).anyTimes();
EasyMock.expect(servletContext.getAttribute(HaServletContextListener.PROVIDER_ATTRIBUTE_NAME)).andReturn(provider).anyTimes();
BasicHttpParams params = new BasicHttpParams();
HttpUriRequest outboundRequest = EasyMock.createNiceMock(HttpRequestBase.class);
EasyMock.expect(outboundRequest.getMethod()).andReturn( "GET" ).anyTimes();
EasyMock.expect(outboundRequest.getURI()).andReturn( uri1 ).anyTimes();
EasyMock.expect(outboundRequest.getParams()).andReturn( params ).anyTimes();
HttpServletRequest inboundRequest = EasyMock.createNiceMock(HttpServletRequest.class);
EasyMock.expect(inboundRequest.getRequestURL()).andReturn( new StringBuffer(uri2.toString()) ).once();
EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(0)).once();
EasyMock.expect(inboundRequest.getAttribute("dispatch.ha.failover.counter")).andReturn(new AtomicInteger(1)).once();
HttpServletResponse outboundResponse = EasyMock.createNiceMock(HttpServletResponse.class);
EasyMock.expect(outboundResponse.getOutputStream()).andAnswer( new IAnswer<ServletOutputStream>() {
@Override
public ServletOutputStream answer() throws Throwable {
return new ServletOutputStream() {
@Override
public void write( int b ) throws IOException {
throw new IOException( "unreachable-host" );
}
};
}
}).once();
EasyMock.replay(filterConfig, servletContext, outboundRequest, inboundRequest, outboundResponse);
Assert.assertEquals(uri1.toString(), provider.getActiveURL(serviceName));
WebHdfsHaHttpClientDispatch dispatch = new WebHdfsHaHttpClientDispatch();
dispatch.init(filterConfig);
long startTime = System.currentTimeMillis();
try {
dispatch.executeRequest(outboundRequest, inboundRequest, outboundResponse);
} catch (IOException e) {
//this is expected after the failover limit is reached
}
long elapsedTime = System.currentTimeMillis() - startTime;
Assert.assertEquals(uri2.toString(), provider.getActiveURL(serviceName));
//test to make sure the sleep took place
Assert.assertTrue(elapsedTime > 1000);
}