diff --git a/clientconn.go b/clientconn.go index a1e1a98006a7..bad91069f8af 100644 --- a/clientconn.go +++ b/clientconn.go @@ -134,6 +134,18 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * opt.apply(&cc.dopts) } + defer func() { + select { + case <-ctx.Done(): + conn, err = nil, ctx.Err() + default: + } + + if err != nil { + cc.Close() + } + }() + if channelz.IsOn() { if cc.dopts.channelzParentID != 0 { cc.channelzID = channelz.RegisterChannel(&channelzChannel{cc}, cc.dopts.channelzParentID, target) @@ -196,18 +208,6 @@ func DialContext(ctx context.Context, target string, opts ...DialOption) (conn * defer cancel() } - defer func() { - select { - case <-ctx.Done(): - conn, err = nil, ctx.Err() - default: - } - - if err != nil { - cc.Close() - } - }() - scSet := false if cc.dopts.scChan != nil { // Try to get an initial service config. @@ -820,7 +820,7 @@ func (cc *ClientConn) Close() error { } channelz.AddTraceEvent(cc.channelzID, ted) // TraceEvent needs to be called before RemoveEntry, as TraceEvent may add trace reference to - // the entity beng deleted, and thus prevent it from being deleted right away. + // the entity being deleted, and thus prevent it from being deleted right away. channelz.RemoveEntry(cc.channelzID) } return nil diff --git a/test/channelz_test.go b/test/channelz_test.go index c5dcff39f703..4d8c0cc3e0b6 100644 --- a/test/channelz_test.go +++ b/test/channelz_test.go @@ -190,6 +190,18 @@ func (s) TestCZTopChannelRegistrationAndDeletion(t *testing.T) { } } +func (s) TestCZTopChannelRegistrationAndDeletionWhenDialFail(t *testing.T) { + channelz.NewChannelzStorage() + // Make dial fails (due to no transport security specified) + _, err := grpc.Dial("fake.addr") + if err == nil { + t.Fatal("expecting dial to fail") + } + if tcs, end := channelz.GetTopChannels(0, 0); tcs != nil || !end { + t.Fatalf("GetTopChannels(0, 0) = %v, %v, want , true", tcs, end) + } +} + func (s) TestCZNestedChannelRegistrationAndDeletion(t *testing.T) { channelz.NewChannelzStorage() e := tcpClearRREnv