private int getFreePort(bool firstToAccess, string path, IContainerActions containerActions, ref bool unknownState) { int portToUse; portToUse = Utils.MinPort; try { if (!unknownState && File.Exists(path) && firstToAccess) { try { var portsRemoved = this.recycleUnusedPorts(path); if (portsRemoved.Any(p => !portAvailable(p))) { // We can't wait too long cos we are in the middle of a mutex. If we timeout // and next time it attempts to use these ports then it will just fail and skip them Task.WaitAny(containerActions.KillZombieContainersBoundToPorts(portsRemoved), Task.Delay((int)timeout.TotalMilliseconds / 2)); } } catch (IOException) { } } } catch (Exception ex) { Console.Error.WriteLine(ex.Message); unknownState = true; } if (unknownState) { // Something has gone wrong - pick a diff range of ports far away from the others without reserving do { portToUse += new Random().Next(1, 100) + 100; } while (!portAvailable(portToUse)); return(portToUse); } do { try { portToUse = this.reserveLowestFreePort(path); } catch (IOException) { } // If portAvailable is false then this can result in us reserving multiple ports. // This is fine thos because there is something using them so they should be excluded. } while (!portAvailable(portToUse)); return(portToUse); }
public UniquePortProvider(IContainerActions containerActions) { this.containerActions = containerActions; }