Skip to content

envtest: added retry for 'addr in use' bind error #173

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions pkg/envtest/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@ package envtest

import (
"fmt"
"net"
"os"
"path/filepath"
"strings"
"time"

apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
Expand Down Expand Up @@ -138,8 +140,7 @@ func (te *Environment) Start() (*rest.Config, error) {
te.ControlPlane.APIServer.StartTimeout = te.ControlPlaneStartTimeout
te.ControlPlane.APIServer.StopTimeout = te.ControlPlaneStopTimeout

// Start the control plane - retry if it fails
if err := te.ControlPlane.Start(); err != nil {
if err := te.startControlPlane(); err != nil {
return nil, err
}

Expand All @@ -156,6 +157,32 @@ func (te *Environment) Start() (*rest.Config, error) {
return te.Config, err
}

func (te *Environment) startControlPlane() error {
numTries, maxRetries := 0, 5
for ; numTries < maxRetries; numTries++ {
// Start the control plane - retry if it fails
err := te.ControlPlane.Start()
if err == nil {
break
}
// code snippet copied from following answer on stackoverflow
// https://stackoverflow.com/questions/51151973/catching-bind-address-already-in-use-in-golang
if opErr, ok := err.(*net.OpError); ok {
if opErr.Op == "listen" && strings.Contains(opErr.Error(), "address already in use") {
if stopErr := te.ControlPlane.Stop(); stopErr != nil {
return fmt.Errorf("failed to stop controlplane in response to bind error 'address already in use'")
}
}
} else {
return err
}
}
if numTries == maxRetries {
return fmt.Errorf("failed to start the controlplane. retried %d times", numTries)
}
return nil
}

func (te *Environment) defaultTimeouts() error {
var err error
if te.ControlPlaneStartTimeout == 0 {
Expand Down