Merge pull request #7613 from radeksimko/cleanup-net-cache

common/net: Cleanup cache of used port after closing
This commit is contained in:
Megan Marsh 2019-05-06 16:44:35 -07:00 committed by GitHub
commit eb80917024
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 9 deletions

View File

@ -6,6 +6,7 @@ import (
"log"
"math/rand"
"net"
"os"
"strconv"
"time"
@ -28,6 +29,7 @@ type Listener struct {
Port int
Address string
lock *filelock.Flock
cleanupFunc func() error
}
func (l *Listener) Close() error {
@ -35,7 +37,18 @@ func (l *Listener) Close() error {
if err != nil {
log.Printf("cannot unlock lockfile %#v: %v", l, err)
}
return l.Listener.Close()
err = l.Listener.Close()
if err != nil {
return err
}
if l.cleanupFunc != nil {
err := l.cleanupFunc()
if err != nil {
log.Printf("cannot cleanup: %#v", err)
}
}
return nil
}
// ListenRangeConfig contains options for listening to a free address [Min,Max)
@ -92,12 +105,17 @@ func (lc ListenRangeConfig) Listen(ctx context.Context) (*Listener, error) {
}
}
cleanupFunc := func() error {
return os.Remove(lockFilePath)
}
log.Printf("Found available port: %d on IP: %s", port, lc.Addr)
listener = &Listener{
Address: lc.Addr,
Port: port,
Listener: l,
lock: lock,
cleanupFunc: cleanupFunc,
}
return nil
})

View File

@ -8,7 +8,6 @@ import (
)
func TestListenRangeConfig_Listen(t *testing.T) {
topCtx, cancel := context.WithCancel(context.Background())
defer cancel()