2023-04-10 15:36:59 +00:00
|
|
|
// Copyright (c) HashiCorp, Inc.
|
|
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
|
2018-01-12 21:58:44 +00:00
|
|
|
package pool
|
2018-01-11 01:21:28 +00:00
|
|
|
|
|
|
|
import (
|
2018-01-12 21:58:44 +00:00
|
|
|
"fmt"
|
|
|
|
"net"
|
2018-01-11 01:21:28 +00:00
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
2023-01-03 17:25:20 +00:00
|
|
|
"github.com/hashicorp/nomad/ci"
|
2018-01-11 01:21:28 +00:00
|
|
|
"github.com/hashicorp/nomad/helper/testlog"
|
2023-01-03 17:25:20 +00:00
|
|
|
"github.com/shoenig/test/must"
|
2018-01-11 01:21:28 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func newTestPool(t *testing.T) *ConnPool {
|
2018-09-17 21:22:40 +00:00
|
|
|
l := testlog.HCLogger(t)
|
|
|
|
p := NewPool(l, 1*time.Minute, 10, nil)
|
2018-01-11 01:21:28 +00:00
|
|
|
return p
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestConnPool_ConnListener(t *testing.T) {
|
2023-01-03 17:25:20 +00:00
|
|
|
ports := ci.PortAllocator.Grab(1)
|
2018-01-12 21:58:44 +00:00
|
|
|
addrStr := fmt.Sprintf("127.0.0.1:%d", ports[0])
|
|
|
|
addr, err := net.ResolveTCPAddr("tcp", addrStr)
|
2023-01-03 17:25:20 +00:00
|
|
|
must.NoError(t, err)
|
2018-01-12 21:58:44 +00:00
|
|
|
|
|
|
|
exitCh := make(chan struct{})
|
|
|
|
defer close(exitCh)
|
|
|
|
go func() {
|
2023-01-03 17:25:20 +00:00
|
|
|
ln, listenErr := net.Listen("tcp", addrStr)
|
|
|
|
must.NoError(t, listenErr)
|
|
|
|
defer func() { _ = ln.Close() }()
|
2018-01-12 21:58:44 +00:00
|
|
|
conn, _ := ln.Accept()
|
2023-01-03 17:25:20 +00:00
|
|
|
defer func() { _ = conn.Close() }()
|
2018-01-12 21:58:44 +00:00
|
|
|
<-exitCh
|
|
|
|
}()
|
|
|
|
|
|
|
|
time.Sleep(100 * time.Millisecond)
|
|
|
|
|
|
|
|
// Create a test pool
|
2018-01-11 01:21:28 +00:00
|
|
|
pool := newTestPool(t)
|
|
|
|
|
|
|
|
// Setup a listener
|
2021-06-07 14:22:37 +00:00
|
|
|
c := make(chan *Conn, 1)
|
2018-01-11 01:21:28 +00:00
|
|
|
pool.SetConnListener(c)
|
|
|
|
|
|
|
|
// Make an RPC
|
2021-12-01 22:36:02 +00:00
|
|
|
_, err = pool.acquire("test", addr)
|
2023-01-03 17:25:20 +00:00
|
|
|
must.NoError(t, err)
|
2018-01-11 01:21:28 +00:00
|
|
|
|
|
|
|
// Assert we get a connection.
|
|
|
|
select {
|
|
|
|
case <-c:
|
|
|
|
case <-time.After(100 * time.Millisecond):
|
|
|
|
t.Fatalf("timeout")
|
|
|
|
}
|
|
|
|
|
|
|
|
// Test that the channel is closed when the pool shuts down.
|
2023-01-03 17:25:20 +00:00
|
|
|
err = pool.Shutdown()
|
|
|
|
must.NoError(t, err)
|
|
|
|
|
2018-01-11 01:21:28 +00:00
|
|
|
_, ok := <-c
|
2023-01-03 17:25:20 +00:00
|
|
|
must.False(t, ok)
|
2018-01-11 01:21:28 +00:00
|
|
|
}
|