View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase;
20  
21  import java.io.IOException;
22  import java.net.BindException;
23  import java.net.InetAddress;
24  import java.net.InetSocketAddress;
25  import java.net.ServerSocket;
26  import java.nio.channels.ServerSocketChannel;
27  import java.util.Locale;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.hbase.testclassification.SmallTests;
32  import org.junit.Assert;
33  import org.junit.Rule;
34  import org.junit.Test;
35  import org.junit.experimental.categories.Category;
36  import org.junit.rules.TestRule;
37  
38  /**
39   * This tests whether ServerSocketChannel works over ipv6, which Zookeeper
40   * depends on. On Windows Oracle JDK 6, creating a ServerSocketChannel throws
41   * java.net.SocketException: Address family not supported by protocol family
42   * exception. It is a known JVM bug, seems to be only resolved for JDK7:
43   * http://bugs.sun.com/view_bug.do?bug_id=6230761
44   *
45   * For this test, we check that whether we are effected by this bug, and if so
46   * the test ensures that we are running with java.net.preferIPv4Stack=true, so
47   * that ZK will not fail to bind to ipv6 address using ClientCnxnSocketNIO.
48   */
49  @Category(SmallTests.class)
50  public class TestIPv6NIOServerSocketChannel {
51    private static final Log LOG = LogFactory.getLog(TestIPv6NIOServerSocketChannel.class);
52  
53    @Rule
54    public final TestRule timeout = CategoryBasedTimeout.builder().
55      withTimeout(this.getClass()).withLookingForStuckThread(true).build();
56    /**
57     * Creates and binds a regular ServerSocket.
58     */
59    private void bindServerSocket(InetAddress inetAddr) throws IOException {
60      while(true) {
61        int port = HBaseTestingUtility.randomFreePort();
62        InetSocketAddress addr = new InetSocketAddress(inetAddr, port);
63        ServerSocket serverSocket = null;
64        try {
65          serverSocket = new ServerSocket();
66          serverSocket.bind(addr);
67          break;
68        } catch (BindException ex) {
69          //continue
70          LOG.info("Failed on " + addr + ", inedAddr=" + inetAddr, ex);
71        } finally {
72          if (serverSocket != null) {
73            serverSocket.close();
74          }
75        }
76      }
77    }
78  
79    /**
80     * Creates a NIO ServerSocketChannel, and gets the ServerSocket from
81     * there. Then binds the obtained socket.
82     * This fails on Windows with Oracle JDK1.6.0u33, if the passed InetAddress is a
83     * IPv6 address. Works on Oracle JDK 1.7.
84     */
85    private void bindNIOServerSocket(InetAddress inetAddr) throws IOException {
86      while (true) {
87        int port = HBaseTestingUtility.randomFreePort();
88        InetSocketAddress addr = new InetSocketAddress(inetAddr, port);
89        ServerSocketChannel channel = null;
90        ServerSocket serverSocket = null;
91        try {
92          channel = ServerSocketChannel.open();
93          serverSocket = channel.socket();
94          serverSocket.bind(addr); // This does not work
95          break;
96        } catch (BindException ex) {
97          //continue
98        } finally {
99          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:");
129       LOG.info(ex);
130 
131       //if this is the case, ensure that we are running on preferIPv4=true
132       ensurePreferIPv4();
133     }
134   }
135 
136   /**
137    * Checks whether we are running with java.net.preferIPv4Stack=true
138    */
139   public void ensurePreferIPv4() throws IOException {
140     InetAddress[] addrs = InetAddress.getAllByName("localhost");
141     for (InetAddress addr : addrs) {
142       LOG.info("resolved localhost as:" + addr);
143       Assert.assertEquals(4, addr.getAddress().length); //ensure 4 byte ipv4 address
144     }
145   }
146 
147   /**
148    * Tests whether every InetAddress we obtain by resolving can open a
149    * ServerSocketChannel.
150    */
151   @Test
152   public void testServerSocketFromLocalhostResolution() throws IOException {
153     InetAddress[] addrs = {InetAddress.getLocalHost()};
154     for (InetAddress addr : addrs) {
155       LOG.info("Resolved localhost as: " + addr);
156       bindServerSocket(addr);
157       bindNIOServerSocket(addr);
158     }
159   }
160 
161   public static void main(String[] args) throws Exception {
162     TestIPv6NIOServerSocketChannel test = new TestIPv6NIOServerSocketChannel();
163     test.testServerSocket();
164     test.testServerSocketFromLocalhostResolution();
165   }
166 }