Skip to content

Commit

Permalink
chore: add func to get open port to start covenant emulator
Browse files Browse the repository at this point in the history
  • Loading branch information
RafilxTenfen committed Jan 15, 2025
1 parent 0ee1947 commit c80f479
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 2 deletions.
6 changes: 5 additions & 1 deletion itest/test_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package e2etest

import (
"context"
"fmt"
"math/rand"
"os"
"sync"
Expand Down Expand Up @@ -107,13 +108,16 @@ func StartManager(t *testing.T) *TestManager {
parsedConfig, err := signerConfig.Parse()
require.NoError(t, err)

remoteSignerPort, url := AllocateUniquePort(t)
parsedConfig.ServerConfig.Port = remoteSignerPort
covenantConfig.RemoteSigner.URL = fmt.Sprintf("http://%s", url)

server, err := signerService.New(
context.Background(),
parsedConfig,
app,
met,
)

require.NoError(t, err)

signer := remotesigner.NewRemoteSigner(covenantConfig.RemoteSigner)
Expand Down
63 changes: 62 additions & 1 deletion itest/utils.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,67 @@
package e2etest

import "os"
import (
"fmt"
mrand "math/rand/v2"
"net"
"os"
"sync"
"testing"
)

// Track allocated ports, protected by a mutex
var (
allocatedPorts = make(map[int]struct{})
portMutex sync.Mutex
)

// AllocateUniquePort tries to find an available TCP port on the localhost
// by testing multiple random ports within a specified range.
func AllocateUniquePort(t *testing.T) (int, string) {
randPort := func(base, spread int) int {
return base + mrand.IntN(spread)
}

// Base port and spread range for port selection
const (
basePort = 40000
portRange = 50000
)

var url string
// Try up to 10 times to find an available port
for i := 0; i < 30; i++ {
port := randPort(basePort, portRange)

// Lock the mutex to check and modify the shared map
portMutex.Lock()
if _, exists := allocatedPorts[port]; exists {
// Port already allocated, try another one
portMutex.Unlock()
continue
}

url = fmt.Sprintf("127.0.0.1:%d", port)
listener, err := net.Listen("tcp", url)
if err != nil {
portMutex.Unlock()
continue
}

allocatedPorts[port] = struct{}{}
portMutex.Unlock()

if err := listener.Close(); err != nil {
continue
}

return port, url
}

// If no available port was found, fail the test
t.Fatalf("failed to find an available port in range %d-%d", basePort, basePort+portRange)
return 0, ""
}

func baseDir(pattern string) (string, error) {
tempPath := os.TempDir()
Expand Down

0 comments on commit c80f479

Please sign in to comment.