Skip to content

Commit

Permalink
Add Connect function
Browse files Browse the repository at this point in the history
  • Loading branch information
jsafrane committed Jan 18, 2019
1 parent 6bb407d commit 1ed39ab
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions connection/connection.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package connection

import (
"context"
"net"
"strings"
"time"

"google.golang.org/grpc"
)

const (
// Default timeout when connecting to CSI driver. I.e. if used in a CSI sidecar container, corresponding CSI driver
// must be up and running within this time.
DefaultDriverConnectionTimeout = time.Minute
)

// Connect opens insecure gRPC connection to a CSI driver. Address must have either '<protocol>://' prefix, or be
// a path to a socket file. The function tries to connect every second until timeout expires.
func Connect(address string, timeout time.Duration, dialOptions ...grpc.DialOption) (*grpc.ClientConn, error) {
dialOptions = append(dialOptions,
grpc.WithInsecure(), // Don't use TLS, it's usually local Unix domain socket in a container.
grpc.WithBlock(), // Block until it succeeds (or times out).
grpc.WithBackoffMaxDelay(time.Second), // Retry every second after failure.
)
if strings.HasPrefix(address, "/") {
// It looks like filesystem path.
dialOptions = append(dialOptions, grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
return net.DialTimeout("unix", addr, timeout)
}))
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return grpc.DialContext(ctx, address, dialOptions...)
}

0 comments on commit 1ed39ab

Please sign in to comment.