/
util.go
360 lines (306 loc) · 10.4 KB
/
util.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*
Copyright 2020 The OpenYurt 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 util
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"github.com/alibaba/openyurt/pkg/yurthub/kubernetes/serializer"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apiserver/pkg/endpoints/handlers/negotiation"
"k8s.io/apiserver/pkg/endpoints/handlers/responsewriters"
apirequest "k8s.io/apiserver/pkg/endpoints/request"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
certutil "k8s.io/client-go/util/cert"
"k8s.io/klog"
)
// ProxyKeyType represents the key in proxy request context
type ProxyKeyType int
const (
// ProxyReqContentType represents request content type context key
ProxyReqContentType ProxyKeyType = iota
// ProxyRespContentType represents response content type context key
ProxyRespContentType
// ProxyClientComponent represents client component context key
ProxyClientComponent
// ProxyReqCanCache represents request can cache context key
ProxyReqCanCache
)
// WithValue returns a copy of parent in which the value associated with key is val.
func WithValue(parent context.Context, key interface{}, val interface{}) context.Context {
return context.WithValue(parent, key, val)
}
// WithReqContentType returns a copy of parent in which the response content type value is set
func WithReqContentType(parent context.Context, contentType string) context.Context {
return WithValue(parent, ProxyReqContentType, contentType)
}
// ReqContentTypeFrom returns the value of the request content type key on the ctx
func ReqContentTypeFrom(ctx context.Context) (string, bool) {
info, ok := ctx.Value(ProxyReqContentType).(string)
return info, ok
}
// WithRespContentType returns a copy of parent in which the request content type value is set
func WithRespContentType(parent context.Context, contentType string) context.Context {
return WithValue(parent, ProxyRespContentType, contentType)
}
// RespContentTypeFrom returns the value of the response content type key on the ctx
func RespContentTypeFrom(ctx context.Context) (string, bool) {
info, ok := ctx.Value(ProxyRespContentType).(string)
return info, ok
}
// WithClientComponent returns a copy of parent in which the client component value is set
func WithClientComponent(parent context.Context, component string) context.Context {
return WithValue(parent, ProxyClientComponent, component)
}
// ClientComponentFrom returns the value of the client component key on the ctx
func ClientComponentFrom(ctx context.Context) (string, bool) {
info, ok := ctx.Value(ProxyClientComponent).(string)
return info, ok
}
// WithReqCanCache returns a copy of parent in which the request can cache value is set
func WithReqCanCache(parent context.Context, canCache bool) context.Context {
return WithValue(parent, ProxyReqCanCache, canCache)
}
// ReqCanCacheFrom returns the value of the request can cache key on the ctx
func ReqCanCacheFrom(ctx context.Context) (bool, bool) {
info, ok := ctx.Value(ProxyReqCanCache).(bool)
return info, ok
}
// ReqString formats a string for request
func ReqString(req *http.Request) string {
ctx := req.Context()
comp, _ := ClientComponentFrom(ctx)
if info, ok := apirequest.RequestInfoFrom(ctx); ok {
return fmt.Sprintf("%v %s %s: %s", comp, info.Verb, info.Resource, req.URL.String())
}
return fmt.Sprintf("%s of %s", comp, req.URL.String())
}
// ReqInfoString formats a string for request info
func ReqInfoString(info *apirequest.RequestInfo) string {
if info == nil {
return ""
}
return fmt.Sprintf("%s %s for %s", info.Verb, info.Resource, info.Path)
}
// WriteObject write object to response writer
func WriteObject(statusCode int, obj runtime.Object, w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
gv := schema.GroupVersion{
Group: "",
Version: runtime.APIVersionInternal,
}
if info, ok := apirequest.RequestInfoFrom(ctx); ok {
gv.Group = info.APIGroup
gv.Version = info.APIVersion
}
responsewriters.WriteObjectNegotiated(serializer.YurtHubSerializer.NegotiatedSerializer, negotiation.DefaultEndpointRestrictions, gv, w, req, statusCode, obj)
}
// Err write err to response writer
func Err(err error, w http.ResponseWriter, req *http.Request) {
ctx := req.Context()
gv := schema.GroupVersion{
Group: "",
Version: runtime.APIVersionInternal,
}
if info, ok := apirequest.RequestInfoFrom(ctx); ok {
gv.Group = info.APIGroup
gv.Version = info.APIVersion
}
responsewriters.ErrorNegotiated(err, serializer.YurtHubSerializer.NegotiatedSerializer, gv, w, req)
}
// NewDualReadCloser create an dualReadCloser object
func NewDualReadCloser(rc io.ReadCloser, isRespBody bool) (io.ReadCloser, io.ReadCloser) {
pr, pw := io.Pipe()
dr := &dualReadCloser{
rc: rc,
pw: pw,
isRespBody: isRespBody,
}
return dr, pr
}
type dualReadCloser struct {
rc io.ReadCloser
pw *io.PipeWriter
// isRespBody shows rc(is.ReadCloser) is a response.Body
// or not(maybe a request.Body). if it is true(it's a response.Body),
// we should close the response body in Close func, else not,
// it(request body) will be closed by http request caller
isRespBody bool
}
// Read read data into p and write into pipe
func (dr *dualReadCloser) Read(p []byte) (n int, err error) {
n, err = dr.rc.Read(p)
if n > 0 {
if n, err := dr.pw.Write(p[:n]); err != nil {
klog.Errorf("dualReader: failed to write %v", err)
return n, err
}
}
return
}
// Close close two readers
func (dr *dualReadCloser) Close() error {
errs := make([]error, 0)
if dr.isRespBody {
if err := dr.rc.Close(); err != nil {
errs = append(errs, err)
}
}
if err := dr.pw.Close(); err != nil {
errs = append(errs, err)
}
if len(errs) != 0 {
return fmt.Errorf("failed to close dualReader, %v", errs)
}
return nil
}
// KeyFunc combine comp resource ns name into a key
func KeyFunc(comp, resource, ns, name string) (string, error) {
if comp == "" || resource == "" {
return "", fmt.Errorf("createKey: comp, resource can not be empty")
}
return filepath.Join(comp, resource, ns, name), nil
}
// SplitKey split key into comp, resource, ns, name
func SplitKey(key string) (comp, resource, ns, name string) {
if len(key) == 0 {
return
}
parts := strings.Split(key, "/")
switch len(parts) {
case 1:
comp = parts[0]
case 2:
comp = parts[0]
resource = parts[1]
case 3:
comp = parts[0]
resource = parts[1]
name = parts[2]
case 4:
comp = parts[0]
resource = parts[1]
ns = parts[2]
name = parts[3]
}
return
}
// IsSupportedLBMode check lb mode is supported or not
func IsSupportedLBMode(lbMode string) bool {
switch lbMode {
case "rr", "priority":
return true
}
return false
}
// IsSupportedCertMode check cert mode is supported or not
func IsSupportedCertMode(certMode string) bool {
switch certMode {
case "kubelet", "hubself":
return true
}
return false
}
// FileExists checks if specified file exists.
func FileExists(filename string) (bool, error) {
if _, err := os.Stat(filename); os.IsNotExist(err) {
return false, nil
} else if err != nil {
return false, err
}
return true, nil
}
// LoadKubeletRestClientConfig load *rest.Config for accessing healthyServer
func LoadKubeletRestClientConfig(healthyServer *url.URL) (*rest.Config, error) {
const (
pairFile = "/var/lib/kubelet/pki/kubelet-client-current.pem"
rootCAFile = "/etc/kubernetes/pki/ca.crt"
)
tlsClientConfig := rest.TLSClientConfig{}
if _, err := certutil.NewPool(rootCAFile); err != nil {
klog.Errorf("Expected to load root CA config from %s, but got err: %v", rootCAFile, err)
} else {
tlsClientConfig.CAFile = rootCAFile
}
if can, _ := certutil.CanReadCertAndKey(pairFile, pairFile); !can {
return nil, fmt.Errorf("error reading %s, certificate and key must be supplied as a pair", pairFile)
}
tlsClientConfig.KeyFile = pairFile
tlsClientConfig.CertFile = pairFile
return &rest.Config{
Host: healthyServer.String(),
TLSClientConfig: tlsClientConfig,
}, nil
}
func LoadRESTClientConfig(kubeconfig string) (*rest.Config, error) {
// Load structured kubeconfig data from the given path.
loader := &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}
loadedConfig, err := loader.Load()
if err != nil {
return nil, err
}
// Flatten the loaded data to a particular restclient.Config based on the current context.
return clientcmd.NewNonInteractiveClientConfig(
*loadedConfig,
loadedConfig.CurrentContext,
&clientcmd.ConfigOverrides{},
loader,
).ClientConfig()
}
func LoadKubeConfig(kubeconfig string) (*clientcmdapi.Config, error) {
loader := &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfig}
loadedConfig, err := loader.Load()
if err != nil {
return nil, err
}
return loadedConfig, nil
}
func CreateKubeConfigFile(kubeClientConfig *rest.Config, kubeconfigPath string) error {
// Get the CA data from the bootstrap client config.
caFile, caData := kubeClientConfig.CAFile, []byte{}
if len(caFile) == 0 {
caData = kubeClientConfig.CAData
}
// Build resulting kubeconfig.
kubeconfigData := clientcmdapi.Config{
// Define a cluster stanza based on the bootstrap kubeconfig.
Clusters: map[string]*clientcmdapi.Cluster{"default-cluster": {
Server: kubeClientConfig.Host,
InsecureSkipTLSVerify: kubeClientConfig.Insecure,
CertificateAuthority: caFile,
CertificateAuthorityData: caData,
}},
// Define auth based on the obtained client cert.
AuthInfos: map[string]*clientcmdapi.AuthInfo{"default-auth": {
ClientCertificate: kubeClientConfig.CertFile,
ClientKey: kubeClientConfig.KeyFile,
}},
// Define a context that connects the auth info and cluster, and set it as the default
Contexts: map[string]*clientcmdapi.Context{"default-context": {
Cluster: "default-cluster",
AuthInfo: "default-auth",
Namespace: "default",
}},
CurrentContext: "default-context",
}
// Marshal to disk
return clientcmd.WriteToFile(kubeconfigData, kubeconfigPath)
}