HADOOP-12259. Utility to Dynamic port allocation (brahmareddy via rkanter)

(cherry picked from commit ee233ec95ce8cfc8309d3adc072d926cd85eba08)
(cherry picked from commit 731ed9cad81f91e9da18148f0c4757a38ca406f6)
This commit is contained in:
Robert Kanter 2015-07-24 09:41:53 -07:00 committed by Zhe Zhang
parent d053d1c3ff
commit bd16763591
2 changed files with 64 additions and 0 deletions

View File

@ -7,6 +7,7 @@ Release 2.7.4 - UNRELEASED
NEW FEATURES
IMPROVEMENTS
HADOOP-12259. Utility to Dynamic port allocation (brahmareddy via rkanter)
OPTIMIZATIONS

View File

@ -0,0 +1,63 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.net;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ServerSocketUtil {
private static final Log LOG = LogFactory.getLog(ServerSocketUtil.class);
/**
* Port scan & allocate is how most other apps find ports
*
* @param port given port
* @param retries number of retires
* @return
* @throws IOException
*/
public static int getPort(int port, int retries) throws IOException {
Random rand = new Random();
int tryPort = port;
int tries = 0;
while (true) {
if (tries > 0) {
tryPort = port + rand.nextInt(65535 - port);
}
LOG.info("Using port " + tryPort);
try (ServerSocket s = new ServerSocket(tryPort)) {
return tryPort;
} catch (IOException e) {
tries++;
if (tries >= retries) {
LOG.info("Port is already in use; giving up");
throw e;
} else {
LOG.info("Port is already in use; trying again");
}
}
}
}
}