|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.spark.network |
| 19 | + |
| 20 | +import java.net.InetSocketAddress |
| 21 | + |
| 22 | +import org.apache.spark.{Logging, SparkException} |
| 23 | +import org.eclipse.jetty.server.Server |
| 24 | + |
| 25 | +private[spark] object PortManager extends Logging |
| 26 | +{ |
| 27 | + |
| 28 | + /** |
| 29 | + * Start service on given port, or attempt to fall back to the n+1 port for a certain number of |
| 30 | + * retries |
| 31 | + * |
| 32 | + * @param startPort |
| 33 | + * @param maxRetries Maximum number of retries to attempt. A value of e.g. 3 will cause 4 |
| 34 | + * total attempts, on ports n, n+1, n+2, and n+3 |
| 35 | + * @param startService Function to start service on a given port. Expected to throw a java.net |
| 36 | + * .BindException if the port is already in use |
| 37 | + * @tparam T |
| 38 | + * @throws SparkException When unable to start service in the given number of attempts |
| 39 | + * @return |
| 40 | + */ |
| 41 | + def startWithIncrements[T](startPort: Int, maxRetries: Int, startService: Int => T): |
| 42 | + (T, Int) = { |
| 43 | + for( offset <- 0 to maxRetries) { |
| 44 | + val tryPort = startPort + offset |
| 45 | + try { |
| 46 | + val service: T = startService(tryPort) |
| 47 | + return (service, tryPort) |
| 48 | + } catch { |
| 49 | + case e: java.net.BindException => { |
| 50 | + if (!e.getMessage.contains("Address already in use") || |
| 51 | + offset == (maxRetries-1)) { |
| 52 | + throw e |
| 53 | + } |
| 54 | + logInfo("Could not bind on port: " + tryPort + ". Attempting port " + (tryPort+1)) |
| 55 | + } |
| 56 | + case e: Exception => throw e |
| 57 | + } |
| 58 | + } |
| 59 | + throw new SparkException(s"Couldn't start service on port $startPort") |
| 60 | + } |
| 61 | +} |
0 commit comments