common/net: Cleanup cache of used port after closing
This commit is contained in:
parent
69009472b4
commit
8519da6ce9
|
@ -6,6 +6,7 @@ import (
|
||||||
"log"
|
"log"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"net"
|
"net"
|
||||||
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
@ -25,9 +26,10 @@ type Listener struct {
|
||||||
// Listener can be closed but Port will be file locked by packer until
|
// Listener can be closed but Port will be file locked by packer until
|
||||||
// Close is called.
|
// Close is called.
|
||||||
net.Listener
|
net.Listener
|
||||||
Port int
|
Port int
|
||||||
Address string
|
Address string
|
||||||
lock *filelock.Flock
|
lock *filelock.Flock
|
||||||
|
cleanupFunc func() error
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l *Listener) Close() error {
|
func (l *Listener) Close() error {
|
||||||
|
@ -35,7 +37,18 @@ func (l *Listener) Close() error {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("cannot unlock lockfile %#v: %v", l, err)
|
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)
|
// 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)
|
log.Printf("Found available port: %d on IP: %s", port, lc.Addr)
|
||||||
listener = &Listener{
|
listener = &Listener{
|
||||||
Address: lc.Addr,
|
Address: lc.Addr,
|
||||||
Port: port,
|
Port: port,
|
||||||
Listener: l,
|
Listener: l,
|
||||||
lock: lock,
|
lock: lock,
|
||||||
|
cleanupFunc: cleanupFunc,
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
|
@ -8,7 +8,6 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestListenRangeConfig_Listen(t *testing.T) {
|
func TestListenRangeConfig_Listen(t *testing.T) {
|
||||||
|
|
||||||
topCtx, cancel := context.WithCancel(context.Background())
|
topCtx, cancel := context.WithCancel(context.Background())
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue