001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase;
019
020import java.io.IOException;
021import java.net.BindException;
022import java.net.InetAddress;
023import java.net.InetSocketAddress;
024import java.net.ServerSocket;
025import java.nio.channels.ServerSocketChannel;
026import java.util.Locale;
027import org.apache.hadoop.hbase.testclassification.MiscTests;
028import org.apache.hadoop.hbase.testclassification.SmallTests;
029import org.junit.Assert;
030import org.junit.ClassRule;
031import org.junit.Test;
032import org.junit.experimental.categories.Category;
033import org.slf4j.Logger;
034import org.slf4j.LoggerFactory;
035
036/**
037 * This tests whether ServerSocketChannel works over ipv6, which ZooKeeper
038 * depends on. On Windows Oracle JDK 6, creating a ServerSocketChannel throws
039 * java.net.SocketException: Address family not supported by protocol family
040 * exception. It is a known JVM bug, seems to be only resolved for JDK7:
041 * http://bugs.sun.com/view_bug.do?bug_id=6230761
042 *
043 * For this test, we check that whether we are effected by this bug, and if so
044 * the test ensures that we are running with java.net.preferIPv4Stack=true, so
045 * that ZK will not fail to bind to ipv6 address using ClientCnxnSocketNIO.
046 */
047@Category({MiscTests.class, SmallTests.class})
048public class TestIPv6NIOServerSocketChannel {
049
050  @ClassRule
051  public static final HBaseClassTestRule CLASS_RULE =
052      HBaseClassTestRule.forClass(TestIPv6NIOServerSocketChannel.class);
053
054  private static final Logger LOG = LoggerFactory.getLogger(TestIPv6NIOServerSocketChannel.class);
055
056  /**
057   * Creates and binds a regular ServerSocket.
058   */
059  private void bindServerSocket(InetAddress inetAddr) throws IOException {
060    while(true) {
061      int port = HBaseTestingUtility.randomFreePort();
062      InetSocketAddress addr = new InetSocketAddress(inetAddr, port);
063      ServerSocket serverSocket = null;
064      try {
065        serverSocket = new ServerSocket();
066        serverSocket.bind(addr);
067        break;
068      } catch (BindException ex) {
069        //continue
070        LOG.info("Failed on " + addr + ", inedAddr=" + inetAddr, ex);
071      } finally {
072        if (serverSocket != null) {
073          serverSocket.close();
074        }
075      }
076    }
077  }
078
079  /**
080   * Creates a NIO ServerSocketChannel, and gets the ServerSocket from
081   * there. Then binds the obtained socket.
082   * This fails on Windows with Oracle JDK1.6.0u33, if the passed InetAddress is a
083   * IPv6 address. Works on Oracle JDK 1.7.
084   */
085  private void bindNIOServerSocket(InetAddress inetAddr) throws IOException {
086    while (true) {
087      int port = HBaseTestingUtility.randomFreePort();
088      InetSocketAddress addr = new InetSocketAddress(inetAddr, port);
089      ServerSocketChannel channel = null;
090      ServerSocket serverSocket = null;
091      try {
092        channel = ServerSocketChannel.open();
093        serverSocket = channel.socket();
094        serverSocket.bind(addr); // This does not work
095        break;
096      } catch (BindException ex) {
097        //continue
098      } finally {
099        if (serverSocket != null) {
100          serverSocket.close();
101        }
102        if (channel != null) {
103          channel.close();
104        }
105      }
106    }
107  }
108
109  /**
110   * Checks whether we are effected by the JDK issue on windows, and if so
111   * ensures that we are running with preferIPv4Stack=true.
112   */
113  @Test
114  public void testServerSocket() throws IOException {
115    byte[] addr = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
116    InetAddress inetAddr = InetAddress.getByAddress(addr);
117
118    try {
119      bindServerSocket(inetAddr);
120      bindNIOServerSocket(inetAddr);
121      //if on *nix or windows JDK7, both will pass
122    } catch(java.net.SocketException ex) {
123      //On Windows JDK6, we will get expected exception:
124      //java.net.SocketException: Address family not supported by protocol family
125      //or java.net.SocketException: Protocol family not supported
126      Assert.assertFalse(ex instanceof BindException);
127      Assert.assertTrue(ex.getMessage().toLowerCase(Locale.ROOT).contains("protocol family"));
128      LOG.info("Received expected exception:", ex);
129
130      //if this is the case, ensure that we are running on preferIPv4=true
131      ensurePreferIPv4();
132    }
133  }
134
135  /**
136   * Checks whether we are running with java.net.preferIPv4Stack=true
137   */
138  public void ensurePreferIPv4() throws IOException {
139    InetAddress[] addrs = InetAddress.getAllByName("localhost");
140    for (InetAddress addr : addrs) {
141      LOG.info("resolved localhost as:" + addr);
142      Assert.assertEquals(4, addr.getAddress().length); //ensure 4 byte ipv4 address
143    }
144  }
145
146  /**
147   * Tests whether every InetAddress we obtain by resolving can open a
148   * ServerSocketChannel.
149   */
150  @Test
151  public void testServerSocketFromLocalhostResolution() throws IOException {
152    InetAddress[] addrs = {InetAddress.getLocalHost()};
153    for (InetAddress addr : addrs) {
154      LOG.info("Resolved localhost as: " + addr);
155      bindServerSocket(addr);
156      bindNIOServerSocket(addr);
157    }
158  }
159
160  public static void main(String[] args) throws Exception {
161    TestIPv6NIOServerSocketChannel test = new TestIPv6NIOServerSocketChannel();
162    test.testServerSocket();
163    test.testServerSocketFromLocalhostResolution();
164  }
165}