forked from kubernetes-retired/kpng
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
242 lines (189 loc) · 5.17 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
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package client
import (
"context"
"os"
"os/signal"
"syscall"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
// allow multi gRPC URLs
//_ "github.com/Jille/grpc-multi-resolver"
"k8s.io/klog/v2"
"sigs.k8s.io/kpng/api/localv1"
"sigs.k8s.io/kpng/client/localsink"
"sigs.k8s.io/kpng/client/localsink/fullstate"
"sigs.k8s.io/kpng/client/tlsflags"
)
type ServiceEndpoints = fullstate.ServiceEndpoints
type FlagSet = tlsflags.FlagSet
// New returns a new LocalClient with values bound to the given flag-set for command-line tools.
// Other needs can use `&LocalClient{...}` directly.
func New(flags FlagSet) (lc *LocalClient) {
lc = &LocalClient{
TLS: &tlsflags.Flags{},
}
lc.ctx, lc.cancel = context.WithCancel(context.Background())
lc.DefaultFlags(flags)
return
}
// LocalClient is a simple client to kube-proxy's Endpoints API.
type LocalClient struct {
// Target is the gRPC dial target
Target string
TLS *tlsflags.Flags
// ErrorDelay is the delay before retrying after an error.
ErrorDelay time.Duration
// GRPCBuffer is the max size of a gRPC message
MaxMsgSize int
Sink localsink.Sink
conn *grpc.ClientConn
watch localv1.Sets_WatchClient
watchReq *localv1.WatchReq
ctx context.Context
cancel func()
}
// DefaultFlags registers this client's values to the standard flags.
func (lc *LocalClient) DefaultFlags(flags FlagSet) {
flags.StringVar(&lc.Target, "api", "127.0.0.1:12090", "API to reach (can use multi:///1.0.0.1:1234,1.0.0.2:1234)")
flags.DurationVar(&lc.ErrorDelay, "error-delay", 1*time.Second, "duration to wait before retrying after errors")
flags.IntVar(&lc.MaxMsgSize, "max-msg-size", 4<<20, "max gRPC message size")
lc.TLS.Bind(flags, "")
}
// Next sends the next diff to the sink, waiting for a new revision as needed.
// It's designed to never fail, unless canceled.
func (lc *LocalClient) Next() (canceled bool) {
if lc.watch == nil {
lc.dial()
}
retry:
if lc.ctx.Err() != nil {
canceled = true
return
}
// say we're ready
nodeName, err := lc.Sink.WaitRequest()
if err != nil { // errors are considered as cancel
canceled = true
return
}
err = lc.watch.Send(&localv1.WatchReq{
NodeName: nodeName,
})
if err != nil {
lc.postError()
goto retry
}
for {
op, err := lc.watch.Recv()
if err != nil {
// klog.Error("watch recv failed: ", err)
lc.postError()
goto retry
}
// pass the op to the sync
lc.Sink.Send(op)
// break on sync
switch v := op.Op; v.(type) {
case *localv1.OpItem_Sync:
return
}
}
}
// Cancel will cancel this client, quickly closing any call to Next.
func (lc *LocalClient) Cancel() {
lc.cancel()
}
// CancelOnSignals make the default termination signals to cancel this client.
func (lc *LocalClient) CancelOnSignals() {
lc.CancelOn(os.Interrupt, os.Kill, syscall.SIGTERM)
}
// CancelOn make the given signals to cancel this client.
func (lc *LocalClient) CancelOn(signals ...os.Signal) {
go func() {
c := make(chan os.Signal)
signal.Notify(c, signals...)
sig := <-c
klog.Info("got signal ", sig, ", stopping")
lc.Cancel()
sig = <-c
klog.Info("got signal ", sig, " again, forcing exit")
os.Exit(1)
}()
}
func (lc *LocalClient) Context() context.Context {
return lc.ctx
}
func (lc *LocalClient) DialContext(ctx context.Context) (conn *grpc.ClientConn, err error) {
klog.Info("connecting to ", lc.Target)
opts := append(
make([]grpc.DialOption, 0),
grpc.WithMaxMsgSize(lc.MaxMsgSize),
)
tlsCfg := lc.TLS.Config()
if tlsCfg == nil {
opts = append(opts, grpc.WithInsecure())
} else {
opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(tlsCfg)))
}
return grpc.DialContext(lc.ctx, lc.Target, opts...)
}
func (lc *LocalClient) Dial() (conn *grpc.ClientConn, err error) {
if ctxErr := lc.ctx.Err(); ctxErr == context.Canceled {
err = ctxErr
return
}
return lc.DialContext(lc.ctx)
}
func (lc *LocalClient) dial() (canceled bool) {
retry:
conn, err := lc.Dial()
if err == context.Canceled {
return true
} else if err != nil {
//klog.Info("failed to connect: ", err)
lc.errorSleep()
goto retry
}
lc.conn = conn
lc.watch, err = localv1.NewSetsClient(lc.conn).Watch(lc.ctx)
if err != nil {
conn.Close()
//klog.Info("failed to start watch: ", err)
lc.errorSleep()
goto retry
}
lc.Sink.Reset()
//klog.V(1).Info("connected")
return false
}
func (lc *LocalClient) errorSleep() {
time.Sleep(lc.ErrorDelay)
}
func (lc *LocalClient) postError() {
if lc.watch != nil {
lc.watch.CloseSend()
lc.watch = nil
}
if lc.conn != nil {
lc.conn.Close()
lc.conn = nil
}
if err := lc.ctx.Err(); err != nil {
return
}
lc.errorSleep()
lc.dial()
}