forked from kubernetes-sigs/cri-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
451 lines (405 loc) · 10.3 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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*
Copyright 2017 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 main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"os"
"os/signal"
"reflect"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/golang/protobuf/jsonpb" //nolint:staticcheck
"github.com/golang/protobuf/proto" //nolint:staticcheck
utilyaml "k8s.io/apimachinery/pkg/util/yaml"
internalapi "k8s.io/cri-api/pkg/apis"
pb "k8s.io/cri-api/pkg/apis/runtime/v1"
"sigs.k8s.io/yaml"
)
const (
// truncatedImageIDLen is the truncated length of imageID
truncatedIDLen = 13
)
var (
// The global stopCh for monitoring Interrupt signal.
// DO NOT use it directly. Use SetupInterruptSignalHandler() to get it.
signalIntStopCh chan struct{}
// only setup stopCh once
signalIntSetupOnce = &sync.Once{}
)
// SetupInterruptSignalHandler setup a global signal handler monitoring Interrupt signal. e.g: Ctrl+C.
// The returned read-only channel will be closed on receiving Interrupt signals.
// It will directly call os.Exit(1) on receiving Interrupt signal twice.
func SetupInterruptSignalHandler() <-chan struct{} {
signalIntSetupOnce.Do(func() {
signalIntStopCh = make(chan struct{})
c := make(chan os.Signal, 2)
signal.Notify(c, shutdownSignals...)
go func() {
<-c
close(signalIntStopCh)
<-c
os.Exit(1) // Exit immediately on second signal
}()
})
return signalIntStopCh
}
type listOptions struct {
// id of container or sandbox
id string
// podID of container
podID string
// Regular expression pattern to match pod or container
nameRegexp string
// Regular expression pattern to match the pod namespace
podNamespaceRegexp string
// state of the sandbox
state string
// show verbose info for the sandbox
verbose bool
// labels are selectors for the sandbox
labels map[string]string
// quiet is for listing just container/sandbox/image IDs
quiet bool
// output format
output string
// all containers
all bool
// latest container
latest bool
// last n containers
last int
// out with truncating the id
noTrunc bool
// image used by the container
image string
// resolve image path
resolveImagePath bool
}
type execOptions struct {
// id of container
id string
// timeout to stop command
timeout int64
// Whether to exec a command in a tty
tty bool
// Whether to stream stdin
stdin bool
// Command to exec
cmd []string
// transport to be used
transport string
}
type attachOptions struct {
// id of container
id string
// Whether the stdin is TTY
tty bool
// Whether pass Stdin to container
stdin bool
// transport to be used
transport string
}
type portforwardOptions struct {
// id of sandbox
id string
// ports to forward
ports []string
}
func getSortedKeys(m map[string]string) []string {
keys := make([]string, 0, len(m))
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
func loadContainerConfig(path string) (*pb.ContainerConfig, error) {
f, err := openFile(path)
if err != nil {
return nil, err
}
defer f.Close()
var config pb.ContainerConfig
if err := utilyaml.NewYAMLOrJSONDecoder(f, 4096).Decode(&config); err != nil {
return nil, err
}
if config.Metadata == nil {
return nil, errors.New("metadata is not set")
}
if config.Metadata.Name == "" {
return nil, fmt.Errorf("name is not in metadata %q", config.Metadata)
}
return &config, nil
}
func loadPodSandboxConfig(path string) (*pb.PodSandboxConfig, error) {
f, err := openFile(path)
if err != nil {
return nil, err
}
defer f.Close()
var config pb.PodSandboxConfig
if err := utilyaml.NewYAMLOrJSONDecoder(f, 4096).Decode(&config); err != nil {
return nil, err
}
if config.Metadata == nil {
return nil, errors.New("metadata is not set")
}
if config.Metadata.Name == "" || config.Metadata.Namespace == "" || config.Metadata.Uid == "" {
return nil, fmt.Errorf("name, namespace or uid is not in metadata %q", config.Metadata)
}
return &config, nil
}
func openFile(path string) (*os.File, error) {
f, err := os.Open(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("config at %s not found", path)
}
return nil, err
}
return f, nil
}
func protobufObjectToJSON(obj proto.Message) (string, error) {
jsonpbMarshaler := jsonpb.Marshaler{EmitDefaults: true, Indent: " "}
marshaledJSON, err := jsonpbMarshaler.MarshalToString(obj)
if err != nil {
return "", err
}
return marshaledJSON, nil
}
func outputProtobufObjAsJSON(obj proto.Message) error {
marshaledJSON, err := protobufObjectToJSON(obj)
if err != nil {
return err
}
fmt.Println(marshaledJSON)
return nil
}
func outputProtobufObjAsYAML(obj proto.Message) error {
marshaledJSON, err := protobufObjectToJSON(obj)
if err != nil {
return err
}
marshaledYAML, err := yaml.JSONToYAML([]byte(marshaledJSON))
if err != nil {
return err
}
fmt.Println(string(marshaledYAML))
return nil
}
func outputStatusInfo(status, handlers string, info map[string]string, format string, tmplStr string) error {
// Sort all keys
keys := []string{}
for k := range info {
keys = append(keys, k)
}
sort.Strings(keys)
jsonInfo := "{" + "\"status\":" + status + ","
if handlers != "" {
jsonInfo += "\"runtimeHandlers\":" + handlers + ","
}
for _, k := range keys {
var res interface{}
// We attempt to convert key into JSON if possible else use it directly
if err := json.Unmarshal([]byte(info[k]), &res); err != nil {
jsonInfo += "\"" + k + "\"" + ":" + "\"" + info[k] + "\","
} else {
jsonInfo += "\"" + k + "\"" + ":" + info[k] + ","
}
}
jsonInfo = jsonInfo[:len(jsonInfo)-1]
jsonInfo += "}"
switch format {
case "yaml":
yamlInfo, err := yaml.JSONToYAML([]byte(jsonInfo))
if err != nil {
return err
}
fmt.Println(string(yamlInfo))
case "json":
var output bytes.Buffer
if err := json.Indent(&output, []byte(jsonInfo), "", " "); err != nil {
return err
}
fmt.Println(output.String())
case "go-template":
output, err := tmplExecuteRawJSON(tmplStr, jsonInfo)
if err != nil {
return err
}
fmt.Println(output)
default:
fmt.Printf("Don't support %q format\n", format)
}
return nil
}
func outputEvent(event proto.Message, format string, tmplStr string) error {
switch format {
case "yaml":
err := outputProtobufObjAsYAML(event)
if err != nil {
return err
}
case "json":
err := outputProtobufObjAsJSON(event)
if err != nil {
return err
}
case "go-template":
jsonEvent, err := protobufObjectToJSON(event)
if err != nil {
return err
}
output, err := tmplExecuteRawJSON(tmplStr, jsonEvent)
if err != nil {
return err
}
fmt.Println(output)
default:
fmt.Printf("Don't support %q format\n", format)
}
return nil
}
func parseLabelStringSlice(ss []string) (map[string]string, error) {
labels := make(map[string]string)
for _, s := range ss {
pair := strings.Split(s, "=")
if len(pair) != 2 {
return nil, fmt.Errorf("incorrectly specified label: %v", s)
}
labels[pair[0]] = pair[1]
}
return labels, nil
}
// marshalMapInOrder marshalls a map into json in the order of the original
// data structure.
func marshalMapInOrder(m map[string]interface{}, t interface{}) (string, error) {
s := "{"
v := reflect.ValueOf(t)
for i := 0; i < v.Type().NumField(); i++ {
field := jsonFieldFromTag(v.Type().Field(i).Tag)
if field == "" || field == "-" {
continue
}
value, err := json.Marshal(m[field])
if err != nil {
return "", err
}
s += fmt.Sprintf("%q:%s,", field, value)
}
s = s[:len(s)-1]
s += "}"
var buf bytes.Buffer
if err := json.Indent(&buf, []byte(s), "", " "); err != nil {
return "", err
}
return buf.String(), nil
}
// jsonFieldFromTag gets json field name from field tag.
func jsonFieldFromTag(tag reflect.StructTag) string {
field := strings.Split(tag.Get("json"), ",")[0]
for _, f := range strings.Split(tag.Get("protobuf"), ",") {
if !strings.HasPrefix(f, "json=") {
continue
}
field = strings.TrimPrefix(f, "json=")
}
return field
}
func getTruncatedID(id, prefix string) string {
id = strings.TrimPrefix(id, prefix)
if len(id) > truncatedIDLen {
id = id[:truncatedIDLen]
}
return id
}
func matchesRegex(pattern, target string) bool {
if pattern == "" {
return true
}
matched, err := regexp.MatchString(pattern, target)
if err != nil {
// Assume it's not a match if an error occurs.
return false
}
return matched
}
func matchesImage(imageClient internalapi.ImageManagerService, image string, containerImage string) (bool, error) {
if image == "" {
return true, nil
}
r1, err := ImageStatus(imageClient, image, false)
if err != nil {
return false, err
}
r2, err := ImageStatus(imageClient, containerImage, false)
if err != nil {
return false, err
}
if r1.Image == nil || r2.Image == nil {
// Always return not match if the image doesn't exist.
return false, nil
}
return r1.Image.Id == r2.Image.Id, nil
}
func getRepoImage(imageClient internalapi.ImageManagerService, image string) (string, error) {
r, err := ImageStatus(imageClient, image, false)
if err != nil {
return "", err
}
if len(r.Image.RepoTags) > 0 {
return r.Image.RepoTags[0], nil
}
return image, nil
}
func handleDisplay(
ctx context.Context,
client internalapi.RuntimeService,
watch bool,
displayFunc func(context.Context, internalapi.RuntimeService) error,
) error {
if !watch {
return displayFunc(ctx, client)
}
displayErrCh := make(chan error, 1)
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
watchCtx, cancelFn := context.WithCancel(ctx)
defer cancelFn()
// Put the displayPodMetrics in another goroutine, because it might be
// time consuming with lots of pods and we want to cancel it
// ASAP when user hit CtrlC
go func() {
for range ticker.C {
if err := displayFunc(watchCtx, client); err != nil {
displayErrCh <- err
break
}
}
}()
// listen for CtrlC or error
select {
case <-SetupInterruptSignalHandler():
cancelFn()
return nil
case err := <-displayErrCh:
return err
}
}