|
| 1 | +package connection |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "net" |
| 6 | + "strings" |
| 7 | + "time" |
| 8 | + |
| 9 | + "google.golang.org/grpc" |
| 10 | +) |
| 11 | + |
| 12 | +const ( |
| 13 | + // Default timeout when connecting to CSI driver. I.e. if used in a CSI sidecar container, corresponding CSI driver |
| 14 | + // must be up and running within this time. |
| 15 | + DefaultDriverConnectionTimeout = time.Minute |
| 16 | +) |
| 17 | + |
| 18 | +// Connect opens insecure gRPC connection to a CSI driver. Address must have either '<protocol>://' prefix, or be |
| 19 | +// a path to a socket file. The function tries to connect every second until timeout expires. |
| 20 | +func Connect(address string, timeout time.Duration, dialOptions ...grpc.DialOption) (*grpc.ClientConn, error) { |
| 21 | + dialOptions = append(dialOptions, |
| 22 | + grpc.WithInsecure(), // Don't use TLS, it's usually local Unix domain socket in a container. |
| 23 | + grpc.WithBlock(), // Block until it succeeds (or times out). |
| 24 | + grpc.WithBackoffMaxDelay(time.Second), // Retry every second after failure. |
| 25 | + ) |
| 26 | + if strings.HasPrefix(address, "/") { |
| 27 | + // It looks like filesystem path. |
| 28 | + dialOptions = append(dialOptions, grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) { |
| 29 | + return net.DialTimeout("unix", addr, timeout) |
| 30 | + })) |
| 31 | + } |
| 32 | + ctx, cancel := context.WithTimeout(context.Background(), timeout) |
| 33 | + defer cancel() |
| 34 | + return grpc.DialContext(ctx, address, dialOptions...) |
| 35 | +} |
0 commit comments