@@ -25,6 +25,7 @@ import (
2525 "time"
2626
2727 "google.golang.org/grpc"
28+ "google.golang.org/grpc/connectivity"
2829 grpccredentials "google.golang.org/grpc/credentials"
2930 "google.golang.org/grpc/credentials/insecure"
3031 utilerrors "k8s.io/apimachinery/pkg/util/errors"
@@ -102,11 +103,7 @@ func (s *ServerConfig) NewServer() (*grpc.Server, error) {
102103
103104// DialWithTimeOut will attempt to create a client connection based on the given targets, one at a time, until a client connection is successfully established.
104105func (c * ClientConfig ) DialWithTimeOut (paths []string , timeout time.Duration ) (* grpc.ClientConn , error ) {
105- opts := []grpc.DialOption {
106- // grpc.WithBlock is deprecated. TODO: Perhaps need to reconsider the approach in a future PR
107- //nolint:staticcheck
108- grpc .WithBlock (),
109- }
106+ var opts []grpc.DialOption
110107
111108 var cred grpccredentials.TransportCredentials
112109 if c .ServerAuthCAFile == "" && ! c .InsecureSkipServerVerify {
@@ -136,9 +133,7 @@ func (c *ClientConfig) DialWithTimeOut(paths []string, timeout time.Duration) (*
136133 }
137134 cred = grpccredentials .NewTLS (config )
138135 }
139-
140136 opts = append (opts , grpc .WithTransportCredentials (cred ))
141-
142137 var cc * grpc.ClientConn
143138 var err error
144139 var allErrs []error
@@ -147,7 +142,7 @@ func (c *ClientConfig) DialWithTimeOut(paths []string, timeout time.Duration) (*
147142 if err == nil {
148143 return cc , nil
149144 }
150- allErrs = append (allErrs , err )
145+ allErrs = append (allErrs , fmt . Errorf ( "dial %s error: %v" , path , err ) )
151146 }
152147
153148 return nil , utilerrors .NewAggregate (allErrs )
@@ -157,12 +152,27 @@ func createGRPCConnection(path string, timeout time.Duration, opts ...grpc.DialO
157152 ctx , cancel := context .WithTimeout (context .Background (), timeout )
158153 defer cancel ()
159154
160- // grpc.DialContext is deprecated. TODO: Perhaps need to reconsider the approach in a future PR
161- //nolint:staticcheck
162- cc , err := grpc .DialContext (ctx , path , opts ... )
155+ cc , err := grpc .NewClient (path , opts ... )
163156 if err != nil {
164- return nil , fmt . Errorf ( "dial %s error: %v" , path , err )
157+ return nil , err
165158 }
159+ defer func () {
160+ if err != nil {
161+ cc .Close ()
162+ }
163+ }()
166164
167- return cc , nil
165+ // A blocking dial blocks until the clientConn is ready.
166+ for {
167+ state := cc .GetState ()
168+ if state == connectivity .Idle {
169+ cc .Connect ()
170+ }
171+ if state == connectivity .Ready {
172+ return cc , nil
173+ }
174+ if ! cc .WaitForStateChange (ctx , state ) {
175+ return nil , fmt .Errorf ("timeout waiting for connection to %s, state is %s" , path , state )
176+ }
177+ }
168178}
0 commit comments