Skip to content

Commit

Permalink
Avoid deadlock in etcd.Close when stopping during bootstrapping
Browse files Browse the repository at this point in the history
Signed-off-by: Joshua Zhang <[email protected]>
  • Loading branch information
joshuazh-x committed Jan 10, 2025
1 parent 0c31a4c commit b1802ac
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 3 deletions.
2 changes: 1 addition & 1 deletion embed/etcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func StartEtcd(inCfg *Config) (e *Etcd, err error) {
if !serving {
// errored before starting gRPC server for serveCtx.serversC
for _, sctx := range e.sctxs {
close(sctx.serversC)
sctx.close()
}
}
e.Close()
Expand Down
13 changes: 11 additions & 2 deletions embed/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"net"
"net/http"
"strings"
"sync"

"go.etcd.io/etcd/etcdserver"
"go.etcd.io/etcd/etcdserver/api/v3client"
Expand Down Expand Up @@ -64,6 +65,7 @@ type serveCtx struct {
userHandlers map[string]http.Handler
serviceRegister func(*grpc.Server)
serversC chan *servers
closeOnce sync.Once
}

type servers struct {
Expand Down Expand Up @@ -96,6 +98,9 @@ func (sctx *serveCtx) serve(
gopts ...grpc.ServerOption) (err error) {
logger := defaultLog.New(ioutil.Discard, "etcdhttp", 0)

// Make sure serversC is closed even if we prematurely exit the function.
defer sctx.close()

select {
case <-s.StoppingNotify():
return errors.New("server is stopping")
Expand All @@ -119,8 +124,6 @@ func (sctx *serveCtx) serve(
servElection := v3election.NewElectionServer(v3c)
servLock := v3lock.NewLockServer(v3c)

// Make sure serversC is closed even if we prematurely exit the function.
defer close(sctx.serversC)
var gwmux *gw.ServeMux
if s.Cfg.EnableGRPCGateway {
// GRPC gateway connects to grpc server via connection provided by grpc dial.
Expand Down Expand Up @@ -555,3 +558,9 @@ func (sctx *serveCtx) registerTrace() {
evf := func(w http.ResponseWriter, r *http.Request) { trace.RenderEvents(w, r, true) }
sctx.registerUserHandler("/debug/events", http.HandlerFunc(evf))
}

func (sctx *serveCtx) close() {
sctx.closeOnce.Do(func() {
close(sctx.serversC)
})
}
1 change: 1 addition & 0 deletions etcdserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2167,6 +2167,7 @@ func (s *EtcdServer) publish(timeout time.Duration) {
Val: string(b),
}

// gofail: var beforePublishing struct{}
for {
ctx, cancel := context.WithTimeout(s.ctx, timeout)
_, err := s.Do(ctx, req)
Expand Down
55 changes: 55 additions & 0 deletions integration/embed_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@ import (
"testing"
"time"

"github.com/stretchr/testify/require"
"go.etcd.io/etcd/clientv3"
"go.etcd.io/etcd/embed"
gofail "go.etcd.io/gofail/runtime"
)

func TestEmbedEtcd(t *testing.T) {
Expand Down Expand Up @@ -196,3 +198,56 @@ func setupEmbedCfg(cfg *embed.Config, curls []url.URL, purls []url.URL) {
}
cfg.InitialCluster = cfg.InitialCluster[1:]
}

func TestEmbedEtcdStopDuringBootstrapping(t *testing.T) {
if len(gofail.List()) == 0 {
t.Skip("please run 'make gofail-enable' before running the test")
}

fpName := "beforePublishing"
require.NoError(t, gofail.Enable(fpName, `sleep("2s")`))
t.Cleanup(func() {
terr := gofail.Disable(fpName)
if terr != nil && terr != gofail.ErrDisabled {
t.Fatalf("failed to disable %s: %v", fpName, terr)
}
})

done := make(chan struct{})
go func() {
defer close(done)

cfg := embed.NewConfig()
urls := newEmbedURLs(false, 2)
setupEmbedCfg(cfg, []url.URL{urls[0]}, []url.URL{urls[1]})
cfg.Dir = filepath.Join(t.TempDir(), "embed-etcd")

e, err := embed.StartEtcd(cfg)
if err != nil {
t.Errorf("Failed to start etcd, got error %v", err)
}
defer e.Close()

go func() {
time.Sleep(time.Second)
e.Server.Stop()
t.Log("Stopped server during bootstrapping")
}()

select {
case <-e.Server.ReadyNotify():
t.Log("Server is ready!")
case <-e.Server.StopNotify():
t.Log("Server is stopped")
case <-time.After(20 * time.Second):
e.Server.Stop() // trigger a shutdown
t.Error("Server took too long to start!")
}
}()

select {
case <-done:
case <-time.After(10 * time.Second):
t.Error("timeout in bootstrapping etcd")
}
}

0 comments on commit b1802ac

Please sign in to comment.