-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathclient.go
More file actions
65 lines (51 loc) · 1.39 KB
/
client.go
File metadata and controls
65 lines (51 loc) · 1.39 KB
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
package cmd
import (
"context"
"time"
"github.com/raystack/salt/config"
stencilv1beta1 "github.com/raystack/stencil/proto/raystack/stencil/v1beta1"
"github.com/spf13/cobra"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type ClientConfig struct {
Host string `yaml:"host" cmdx:"host"`
}
func createConnection(ctx context.Context, host string) (*grpc.ClientConn, error) {
opts := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
}
return grpc.DialContext(ctx, host, opts...)
}
func createClient(cmd *cobra.Command, cdk *CDK) (stencilv1beta1.StencilServiceClient, func(), error) {
c, err := loadClientConfig(cmd, cdk.Config)
if err != nil {
return nil, nil, err
}
host := c.Host
if host == "" {
return nil, nil, ErrClientConfigHostNotFound
}
dialTimeoutCtx, dialCancel := context.WithTimeout(cmd.Context(), time.Second*2)
conn, err := createConnection(dialTimeoutCtx, host)
if err != nil {
dialCancel()
return nil, nil, err
}
cancel := func() {
dialCancel()
conn.Close()
}
client := stencilv1beta1.NewStencilServiceClient(conn)
return client, cancel, nil
}
func loadClientConfig(cmd *cobra.Command, cmdxConfig *config.Loader) (*ClientConfig, error) {
var clientConfig ClientConfig
if err := cmdxConfig.Load(
&clientConfig,
); err != nil {
return nil, err
}
return &clientConfig, nil
}