-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
probe.go
290 lines (246 loc) · 8.84 KB
/
probe.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/*
Copyright 2019 The Knative 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 health
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"syscall"
"time"
"golang.org/x/sys/unix"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
grpchealth "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
corev1 "k8s.io/api/core/v1"
netheader "knative.dev/networking/pkg/http/header"
pkgnet "knative.dev/pkg/network"
"knative.dev/pkg/ptr"
)
// HTTPProbeConfigOptions holds the HTTP probe config options
type HTTPProbeConfigOptions struct {
Timeout time.Duration
*corev1.HTTPGetAction
KubeMajor string
KubeMinor string
MaxProtoMajor int
}
// TCPProbeConfigOptions holds the TCP probe config options
type TCPProbeConfigOptions struct {
SocketTimeout time.Duration
Address string
}
// GRPCProbeConfigOptions holds the gRPC probe config options
type GRPCProbeConfigOptions struct {
Timeout time.Duration
*corev1.GRPCAction
KubeMajor string
KubeMinor string
}
// TCPProbe checks that a TCP socket to the address can be opened.
// Did not reuse k8s.io/kubernetes/pkg/probe/tcp to not create a dependency
// on klog.
func TCPProbe(config TCPProbeConfigOptions) error {
conn, err := net.DialTimeout("tcp", config.Address, config.SocketTimeout)
if err != nil {
return err
}
conn.Close()
return nil
}
// Returns a transport that uses HTTP/2 if it's known to be supported, and otherwise
// spoofs the request & response versions to HTTP/1.1.
func autoDowngradingTransport(opt HTTPProbeConfigOptions) http.RoundTripper {
t := pkgnet.NewProberTransport()
return pkgnet.RoundTripperFunc(func(r *http.Request) (*http.Response, error) {
// If the user-container can handle HTTP2, we pass through the request as-is.
// We have to set r.ProtoMajor to 2, since auto transport relies solely on it
// to decide whether to use h2c or http1.1.
if opt.MaxProtoMajor == 2 {
r.ProtoMajor = 2
return t.RoundTrip(r)
}
// Otherwise, save the request HTTP version and downgrade it
// to HTTP1 before sending.
version := r.ProtoMajor
r.ProtoMajor = 1
resp, err := t.RoundTrip(r)
// Restore the request & response HTTP version before sending back.
r.ProtoMajor = version
if resp != nil {
resp.ProtoMajor = version
}
return resp, err
})
}
var transport = func() *http.Transport {
t := http.DefaultTransport.(*http.Transport).Clone()
//nolint:gosec // We explicitly don't need to check certs here.
t.TLSClientConfig.InsecureSkipVerify = true
return t
}()
func getURL(config HTTPProbeConfigOptions) (*url.URL, error) {
return url.Parse(string(config.Scheme) + "://" + net.JoinHostPort(config.Host, config.Port.String()) + config.Path)
}
// http2UpgradeProbe checks that an HTTP with HTTP2 upgrade request
// connection can be understood by the address.
// Returns: the highest known proto version supported (0 if not ready or error)
func http2UpgradeProbe(config HTTPProbeConfigOptions) (int, error) {
httpClient := &http.Client{
Transport: transport,
Timeout: config.Timeout,
}
url, err := getURL(config)
if err != nil {
return 0, fmt.Errorf("error constructing probe url %w", err)
}
req, err := http.NewRequest(http.MethodOptions, url.String(), nil)
if err != nil {
return 0, fmt.Errorf("error constructing probe request %w", err)
}
// An upgrade will need to have at least these 3 headers.
// This is documented at https://tools.ietf.org/html/rfc7540#section-3.2
req.Header.Add("Connection", "Upgrade, HTTP2-Settings")
req.Header.Add("Upgrade", "h2c")
req.Header.Add("HTTP2-Settings", "")
req.Header.Add(netheader.UserAgentKey, netheader.KubeProbeUAPrefix+config.KubeMajor+"/"+config.KubeMinor)
res, err := httpClient.Do(req)
if err != nil {
return 0, err
}
defer res.Body.Close()
maxProto := 0
if isHTTPProbeUpgradingToH2C(res) {
maxProto = 2
} else if isHTTPProbeReady(res) {
maxProto = 1
} else {
return maxProto, fmt.Errorf("HTTP probe did not respond Ready, got status code: %d", res.StatusCode)
}
return maxProto, nil
}
// HTTPProbe checks that HTTP connection can be established to the address.
func HTTPProbe(config HTTPProbeConfigOptions) error {
if config.MaxProtoMajor == 0 {
// If we don't know if the connection supports HTTP2, we will try it.
// Once we get a non-error response, we won't try again.
// If maxProto is 0, container is not ready, so we don't know whether http2 is supported.
// If maxProto is 1, we know we're ready, but we also can't upgrade, so just return.
// If maxProto is 2, we know we can upgrade to http2
maxProto, err := http2UpgradeProbe(config)
if err != nil {
return fmt.Errorf("failed to run HTTP2 upgrade probe with error: %w", err)
}
config.MaxProtoMajor = maxProto
if config.MaxProtoMajor == 1 {
return nil
}
}
httpClient := &http.Client{
Transport: autoDowngradingTransport(config),
Timeout: config.Timeout,
}
url, err := getURL(config)
if err != nil {
return fmt.Errorf("error constructing probe url %w", err)
}
req, err := http.NewRequest(http.MethodGet, url.String(), nil)
if err != nil {
return fmt.Errorf("error constructing probe request %w", err)
}
req.Header.Add(netheader.UserAgentKey, netheader.KubeProbeUAPrefix+config.KubeMajor+"/"+config.KubeMinor)
for _, header := range config.HTTPHeaders {
req.Header.Add(header.Name, header.Value)
}
res, err := httpClient.Do(req)
if err != nil {
return err
}
defer func() {
// Ensure body is both read _and_ closed so it can be reused for keep-alive.
// No point handling errors, connection just won't be reused.
io.Copy(io.Discard, res.Body)
res.Body.Close()
}()
if !isHTTPProbeReady(res) {
return fmt.Errorf("HTTP probe did not respond Ready, got status code: %d", res.StatusCode)
}
return nil
}
// isHTTPProbeUpgradingToH2C checks whether the server indicates it's switching to h2c protocol.
func isHTTPProbeUpgradingToH2C(res *http.Response) bool {
return res.StatusCode == http.StatusSwitchingProtocols && res.Header.Get("Upgrade") == "h2c"
}
// isHTTPProbeReady checks whether we received a successful Response
func isHTTPProbeReady(res *http.Response) bool {
// response status code between 200-399 indicates success
return res.StatusCode >= 200 && res.StatusCode < 400
}
// GRPCProbe checks that gRPC connection can be established to the address.
func GRPCProbe(config GRPCProbeConfigOptions) error {
// Use k8s.io/kubernetes/pkg/probe/dialer_others.go to correspond to OSs other than Windows
dialer := &net.Dialer{
Control: func(network, address string, c syscall.RawConn) error {
return c.Control(func(fd uintptr) {
unix.SetsockoptLinger(int(fd), syscall.SOL_SOCKET, syscall.SO_LINGER, &unix.Linger{Onoff: 1, Linger: 1})
})
},
}
opts := []grpc.DialOption{
grpc.WithUserAgent(netheader.KubeProbeUAPrefix + config.KubeMajor + "/" + config.KubeMinor),
grpc.WithBlock(),
grpc.WithTransportCredentials(insecure.NewCredentials()), // credentials are currently not supported
grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
return dialer.DialContext(ctx, "tcp", addr)
}),
}
ctx, cancel := context.WithTimeout(context.Background(), config.Timeout)
defer cancel()
addr := net.JoinHostPort("127.0.0.1", fmt.Sprintf("%d", config.Port))
conn, err := grpc.DialContext(ctx, addr, opts...)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return fmt.Errorf("failed to connect service %q within %v: %w", addr, config.Timeout, err)
}
return fmt.Errorf("failed to connect service at %q: %w", addr, err)
}
defer func() {
_ = conn.Close()
}()
client := grpchealth.NewHealthClient(conn)
resp, err := client.Check(metadata.NewOutgoingContext(ctx, make(metadata.MD)), &grpchealth.HealthCheckRequest{
Service: ptr.StringValue(config.Service),
})
if err != nil {
stat, ok := status.FromError(err)
if ok {
switch stat.Code() {
case codes.Unimplemented:
return fmt.Errorf("this server does not implement the grpc health protocol (grpc.health.v1.Health) %w", err)
case codes.DeadlineExceeded:
return fmt.Errorf("health rpc did not complete within %v: %w", config.Timeout, err)
}
}
return fmt.Errorf("health rpc probe failed: %w", err)
}
if resp.GetStatus() != grpchealth.HealthCheckResponse_SERVING {
return fmt.Errorf("service unhealthy (responded with %q)", resp.GetStatus().String())
}
return nil
}