-
Notifications
You must be signed in to change notification settings - Fork 684
/
comm.go
194 lines (157 loc) · 3.89 KB
/
comm.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package agent
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/url"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"github.com/datawire/ambassador/v2/pkg/api/agent"
"github.com/datawire/dlib/dlog"
)
const APIKeyMetadataKey = "x-ambassador-api-key"
type RPCComm struct {
conn io.Closer
client agent.DirectorClient
rptWake chan struct{}
retCancel context.CancelFunc
agentID *agent.Identity
directives chan *agent.Directive
}
const (
defaultHostname = "app.getambassador.io"
defaultPort = "443"
)
type ConnInfo struct {
hostname string
port string
secure bool
}
func connInfoFromAddress(address string) (*ConnInfo, error) {
endpoint, err := url.Parse(address)
if err != nil {
return nil, err
}
hostname := endpoint.Hostname()
if hostname == "" {
hostname = defaultHostname
}
port := endpoint.Port()
if port == "" {
port = defaultPort
}
secure := true
if endpoint.Scheme == "http" {
secure = false
}
return &ConnInfo{hostname, port, secure}, nil
}
func NewComm(ctx context.Context, connInfo *ConnInfo, agentID *agent.Identity, apiKey string) (*RPCComm, error) {
ctx = dlog.WithField(ctx, "agent", "comm")
opts := make([]grpc.DialOption, 0, 1)
address := connInfo.hostname + ":" + connInfo.port
if connInfo.secure {
config := &tls.Config{ServerName: connInfo.hostname}
creds := credentials.NewTLS(config)
opts = append(opts, grpc.WithTransportCredentials(creds))
} else {
opts = append(opts, grpc.WithInsecure())
}
dlog.Debugf(ctx, "Dialing server at %s (secure=%t)", address, connInfo.secure)
conn, err := grpc.Dial(address, opts...)
if err != nil {
return nil, err
}
client := agent.NewDirectorClient(conn)
retCtx, retCancel := context.WithCancel(ctx)
c := &RPCComm{
conn: conn,
client: client,
retCancel: retCancel,
agentID: agentID,
directives: make(chan *agent.Directive, 1),
rptWake: make(chan struct{}, 1),
}
retCtx = metadata.AppendToOutgoingContext(retCtx, APIKeyMetadataKey, apiKey)
go c.retrieveLoop(retCtx)
return c, nil
}
func (c *RPCComm) retrieveLoop(ctx context.Context) {
ctx = dlog.WithField(ctx, "agent", "retriever")
for {
if err := c.retrieve(ctx); err != nil {
dlog.Debugf(ctx, "exited: %+v", err)
}
select {
case <-c.rptWake:
dlog.Debug(ctx, "restarting")
case <-ctx.Done():
return
}
}
}
func (c *RPCComm) retrieve(ctx context.Context) error {
stream, err := c.client.Retrieve(ctx, c.agentID)
if err != nil {
return err
}
for {
directive, err := stream.Recv()
if err != nil {
return err
}
select {
case c.directives <- directive:
case <-ctx.Done():
return nil
}
}
}
func (c *RPCComm) Close() error {
c.retCancel()
return c.conn.Close()
}
func (c *RPCComm) Report(ctx context.Context, report *agent.Snapshot, apiKey string) error {
select {
case c.rptWake <- struct{}{}:
default:
}
ctx = metadata.AppendToOutgoingContext(ctx, APIKeyMetadataKey, apiKey)
// marshal snapshot
data, err := json.Marshal(report)
if err != nil {
return fmt.Errorf("json.Marshal: %w", err)
}
const CHUNKSIZE = (64 * 1024) - 4 // 64KiB-4B; gRPC adds 4 bytes of overhead
dlog.Debugf(ctx, "Report is %dB; will take %d chunks",
len(data),
(len(data)+CHUNKSIZE-1)/CHUNKSIZE)
// make stream
stream, err := c.client.ReportStream(ctx)
if err != nil {
return fmt.Errorf("ReportStream.Open: %w", err)
}
// send chunks
msg := &agent.RawSnapshotChunk{}
for i := 0; i < len(data); i += CHUNKSIZE {
j := i + CHUNKSIZE
if j < len(data) {
msg.Chunk = data[i:j]
} else {
msg.Chunk = data[i:]
}
if err := stream.Send(msg); err != nil {
return fmt.Errorf("ReportStream.Send: %w", err)
}
}
if _, err = stream.CloseAndRecv(); err != nil {
return fmt.Errorf("ReportStream.Close: %w", err)
}
return nil
}
func (c *RPCComm) Directives() <-chan *agent.Directive {
return c.directives
}