Skip to content

Commit 45eaef2

Browse files
janosgbalint
authored andcommitted
cmd/swarm: solve rare cases of using the same random port in tests (#17352)
1 parent 3bcb501 commit 45eaef2

2 files changed

Lines changed: 131 additions & 19 deletions

File tree

‎cmd/swarm/config_test.go‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"fmt"
2121
"io"
2222
"io/ioutil"
23+
"net"
2324
"os"
2425
"os/exec"
2526
"testing"
@@ -559,3 +560,16 @@ func TestValidateConfig(t *testing.T) {
559560
}
560561
}
561562
}
563+
564+
func assignTCPPort() (string, error) {
565+
l, err := net.Listen("tcp", "127.0.0.1:0")
566+
if err != nil {
567+
return "", err
568+
}
569+
l.Close()
570+
_, port, err := net.SplitHostPort(l.Addr().String())
571+
if err != nil {
572+
return "", err
573+
}
574+
return port, nil
575+
}

‎cmd/swarm/run_test.go‎

Lines changed: 117 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,15 @@
1717
package main
1818

1919
import (
20+
"context"
2021
"fmt"
2122
"io/ioutil"
2223
"net"
2324
"os"
2425
"path/filepath"
2526
"runtime"
27+
"sync"
28+
"syscall"
2629
"testing"
2730
"time"
2831

@@ -218,14 +221,12 @@ func existingTestNode(t *testing.T, dir string, bzzaccount string) *testNode {
218221
}
219222

220223
// assign ports
221-
httpPort, err := assignTCPPort()
222-
if err != nil {
223-
t.Fatal(err)
224-
}
225-
p2pPort, err := assignTCPPort()
224+
ports, err := getAvailableTCPPorts(2)
226225
if err != nil {
227226
t.Fatal(err)
228227
}
228+
p2pPort := ports[0]
229+
httpPort := ports[1]
229230

230231
// start the node
231232
node.Cmd = runSwarm(t,
@@ -246,6 +247,17 @@ func existingTestNode(t *testing.T, dir string, bzzaccount string) *testNode {
246247
}
247248
}()
248249

250+
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
251+
defer cancel()
252+
253+
// ensure that all ports have active listeners
254+
// so that the next node will not get the same
255+
// when calling getAvailableTCPPorts
256+
err = waitTCPPorts(ctx, ports...)
257+
if err != nil {
258+
t.Fatal(err)
259+
}
260+
249261
// wait for the node to start
250262
for start := time.Now(); time.Since(start) < 10*time.Second; time.Sleep(50 * time.Millisecond) {
251263
node.Client, err = rpc.Dial(conf.IPCEndpoint())
@@ -280,14 +292,12 @@ func newTestNode(t *testing.T, dir string) *testNode {
280292
node := &testNode{Dir: dir}
281293

282294
// assign ports
283-
httpPort, err := assignTCPPort()
284-
if err != nil {
285-
t.Fatal(err)
286-
}
287-
p2pPort, err := assignTCPPort()
295+
ports, err := getAvailableTCPPorts(2)
288296
if err != nil {
289297
t.Fatal(err)
290298
}
299+
p2pPort := ports[0]
300+
httpPort := ports[1]
291301

292302
// start the node
293303
node.Cmd = runSwarm(t,
@@ -308,6 +318,17 @@ func newTestNode(t *testing.T, dir string) *testNode {
308318
}
309319
}()
310320

321+
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
322+
defer cancel()
323+
324+
// ensure that all ports have active listeners
325+
// so that the next node will not get the same
326+
// when calling getAvailableTCPPorts
327+
err = waitTCPPorts(ctx, ports...)
328+
if err != nil {
329+
t.Fatal(err)
330+
}
331+
311332
// wait for the node to start
312333
for start := time.Now(); time.Since(start) < 10*time.Second; time.Sleep(50 * time.Millisecond) {
313334
node.Client, err = rpc.Dial(conf.IPCEndpoint())
@@ -343,15 +364,92 @@ func (n *testNode) Shutdown() {
343364
}
344365
}
345366

346-
func assignTCPPort() (string, error) {
347-
l, err := net.Listen("tcp", "127.0.0.1:0")
348-
if err != nil {
349-
return "", err
367+
// getAvailableTCPPorts returns a set of ports that
368+
// nothing is listening on at the time.
369+
//
370+
// Function assignTCPPort cannot be called in sequence
371+
// and guardantee that the same port will be returned in
372+
// different calls as the listener is closed within the function,
373+
// not after all listeners are started and selected unique
374+
// available ports.
375+
func getAvailableTCPPorts(count int) (ports []string, err error) {
376+
for i := 0; i < count; i++ {
377+
l, err := net.Listen("tcp", "127.0.0.1:0")
378+
if err != nil {
379+
return nil, err
380+
}
381+
// defer close in the loop to be sure the same port will not
382+
// be selected in the next iteration
383+
defer l.Close()
384+
385+
_, port, err := net.SplitHostPort(l.Addr().String())
386+
if err != nil {
387+
return nil, err
388+
}
389+
ports = append(ports, port)
350390
}
351-
l.Close()
352-
_, port, err := net.SplitHostPort(l.Addr().String())
353-
if err != nil {
354-
return "", err
391+
return ports, nil
392+
}
393+
394+
// waitTCPPorts blocks until tcp connections can be
395+
// established on all provided ports. It runs all
396+
// ports dialers in parallel, and returns the first
397+
// encountered error.
398+
// See waitTCPPort also.
399+
func waitTCPPorts(ctx context.Context, ports ...string) error {
400+
var err error
401+
// mu locks err variable that is assigned in
402+
// other goroutines
403+
var mu sync.Mutex
404+
405+
// cancel is canceling all goroutines
406+
// when the firs error is returned
407+
// to prevent unnecessary waiting
408+
ctx, cancel := context.WithCancel(ctx)
409+
defer cancel()
410+
411+
var wg sync.WaitGroup
412+
for _, port := range ports {
413+
wg.Add(1)
414+
go func(port string) {
415+
defer wg.Done()
416+
417+
e := waitTCPPort(ctx, port)
418+
419+
mu.Lock()
420+
defer mu.Unlock()
421+
if e != nil && err == nil {
422+
err = e
423+
cancel()
424+
}
425+
}(port)
426+
}
427+
wg.Wait()
428+
429+
return err
430+
}
431+
432+
// waitTCPPort blocks until tcp connection can be established
433+
// ona provided port. It has a 3 minute timeout as maximum,
434+
// to prevent long waiting, but it can be shortened with
435+
// a provided context instance. Dialer has a 10 second timeout
436+
// in every iteration, and connection refused error will be
437+
// retried in 100 milliseconds periods.
438+
func waitTCPPort(ctx context.Context, port string) error {
439+
ctx, cancel := context.WithTimeout(ctx, 3*time.Minute)
440+
defer cancel()
441+
442+
for {
443+
c, err := (&net.Dialer{Timeout: 10 * time.Second}).DialContext(ctx, "tcp", "127.0.0.1:"+port)
444+
if err != nil {
445+
if operr, ok := err.(*net.OpError); ok {
446+
if syserr, ok := operr.Err.(*os.SyscallError); ok && syserr.Err == syscall.ECONNREFUSED {
447+
time.Sleep(100 * time.Millisecond)
448+
continue
449+
}
450+
}
451+
return err
452+
}
453+
return c.Close()
355454
}
356-
return port, nil
357455
}

0 commit comments

Comments
 (0)