Skip to content

Commit

Permalink
Fix the race condition
Browse files Browse the repository at this point in the history
Signed-off-by: David Gageot <[email protected]>
  • Loading branch information
dgageot committed Mar 21, 2019
1 parent 8a20078 commit 8e3d233
Showing 1 changed file with 4 additions and 13 deletions.
17 changes: 4 additions & 13 deletions pkg/skaffold/util/port.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import (
// See https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt,
func GetAvailablePort(port int, forwardedPorts *sync.Map) int {
if isPortAvailable(port, forwardedPorts) {
forwardedPorts.Store(port, true)
return port
}

Expand All @@ -41,14 +40,12 @@ func GetAvailablePort(port int, forwardedPorts *sync.Map) int {
port++
if isPortAvailable(port, forwardedPorts) {
logrus.Debugf("found open port: %d", port)
forwardedPorts.Store(port, true)
return port
}
}

for port = 4503; port <= 4533; port++ {
if isPortAvailable(port, forwardedPorts) {
forwardedPorts.Store(port, true)
return port
}
}
Expand All @@ -58,18 +55,16 @@ func GetAvailablePort(port int, forwardedPorts *sync.Map) int {
return -1
}

l.Close()
// Here, we introduce a race condition by closing before we
// update the `forwardedPorts` map.
// Another go routine could try the same port and succeed.

p := l.Addr().(*net.TCPAddr).Port

forwardedPorts.Store(p, true)
l.Close()
return p
}

func isPortAvailable(p int, forwardedPorts *sync.Map) bool {
if _, ok := forwardedPorts.Load(p); ok {
alreadyUsed, loaded := forwardedPorts.LoadOrStore(p, true)
if loaded && alreadyUsed.(bool) {
return false
}

Expand All @@ -79,9 +74,5 @@ func isPortAvailable(p int, forwardedPorts *sync.Map) bool {
}

l.Close()
// Here, we introduce a race condition by closing before we
// update the `forwardedPorts` map.
// Another go routine could try the same port and succeed.

return true
}

0 comments on commit 8e3d233

Please sign in to comment.