forked from poseidon/matchbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
85 lines (74 loc) · 1.87 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package client
import (
"crypto/tls"
"errors"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"github.com/coreos/matchbox/matchbox/rpc/rpcpb"
)
var (
errNoEndpoints = errors.New("client: No endpoints provided")
errNoTLSConfig = errors.New("client: No TLS Config provided")
)
// Config configures a Client.
type Config struct {
// List of endpoint URLs
Endpoints []string
// DialTimeout is the timeout for dialing a client connection
DialTimeout time.Duration
// Client TLS credentials
TLS *tls.Config
}
// Client provides a matchbox client RPC session.
type Client struct {
Groups rpcpb.GroupsClient
Profiles rpcpb.ProfilesClient
Ignition rpcpb.IgnitionClient
conn *grpc.ClientConn
}
// New creates a new Client from the given Config.
func New(config *Config) (*Client, error) {
if len(config.Endpoints) == 0 {
return nil, errNoEndpoints
}
return newClient(config)
}
// Close closes the client's connections.
func (c *Client) Close() error {
return c.conn.Close()
}
func newClient(config *Config) (*Client, error) {
conn, err := dialEndpoints(config)
if err != nil {
return nil, err
}
client := &Client{
conn: conn,
Groups: rpcpb.NewGroupsClient(conn),
Profiles: rpcpb.NewProfilesClient(conn),
Ignition: rpcpb.NewIgnitionClient(conn),
}
return client, nil
}
// dialEndpoints attemps to Dial each endpoint in order to establish a
// connection.
func dialEndpoints(config *Config) (conn *grpc.ClientConn, err error) {
opts := []grpc.DialOption{
grpc.WithBlock(),
grpc.WithTimeout(config.DialTimeout),
}
if config.TLS != nil {
creds := credentials.NewTLS(config.TLS)
opts = append(opts, grpc.WithTransportCredentials(creds))
} else {
return nil, errNoTLSConfig
}
for _, endpoint := range config.Endpoints {
conn, err = grpc.Dial(endpoint, opts...)
if err == nil {
return conn, nil
}
}
return nil, err
}