/
core.go
105 lines (85 loc) · 2.46 KB
/
core.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package grpshuffle_client
import (
"context"
"crypto/tls"
"fmt"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"log"
"time"
"github.com/korosuke613/grpshuffle/go/grpshuffle"
"google.golang.org/grpc"
health "google.golang.org/grpc/health/grpc_health_v1" // here
"google.golang.org/grpc/keepalive"
)
func makeDialOpts(noTls bool) []grpc.DialOption {
// see https://pkg.go.dev/google.golang.org/grpc/keepalive#ClientParameters
kp := keepalive.ClientParameters{
Time: 60 * time.Second,
}
var dialOpts []grpc.DialOption
dialOpts = append(dialOpts, grpc.WithKeepaliveParams(kp))
if noTls {
dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
} else {
tlsConfig := tls.Config{
InsecureSkipVerify: true,
}
dialOpts = append(dialOpts, grpc.WithTransportCredentials(credentials.NewTLS(&tlsConfig)))
}
return dialOpts
}
// Connect is create grpc.ClientConn
func Connect(host string, port int, noTls bool) (conn *grpc.ClientConn, err error) {
addr := fmt.Sprintf("%v:%v", host, port)
dialOpts := makeDialOpts(noTls)
conn, err = grpc.Dial(addr, dialOpts...)
if err != nil {
return nil, err
}
return conn, nil
}
// CloseConnect is close grpc.ClientConn
func CloseConnect(conn *grpc.ClientConn) {
err := conn.Close()
if err != nil {
log.Fatal(fmt.Errorf("close failed for healthHandler()"))
return
}
}
// Shuffle is request to grpshuffle.ComputeClient
func Shuffle(cc *grpshuffle.ComputeClient, divide uint64, targets []string) ([]*grpshuffle.Combination, error) {
ctx, cancel := context.WithCancel(context.Background())
go func(cancel func()) {
time.Sleep(2500 * time.Millisecond)
cancel()
}(cancel)
res, err := (*cc).Shuffle(ctx, &grpshuffle.ShuffleRequest{
Targets: targets,
Divide: divide,
})
if err != nil {
return nil, err
}
return res.Combinations, nil
}
// HealthCheckResponse is response HealthCheck
type HealthCheckResponse struct {
Status string `json:"status"`
}
// HealthCheck is request to grpc_health_v1.HealthClient
func HealthCheck(hc *health.HealthClient) (*HealthCheckResponse, error) {
ctx, cancel := context.WithCancel(context.Background())
go func(cancel func()) {
time.Sleep(2500 * time.Millisecond)
cancel()
}(cancel)
res, err := (*hc).Check(ctx, &health.HealthCheckRequest{})
if err != nil {
return nil, err
}
result := &HealthCheckResponse{
Status: health.HealthCheckResponse_ServingStatus_name[int32(res.Status)],
}
return result, nil
}