-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathcontainer.go
318 lines (291 loc) · 8.11 KB
/
container.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
package cri
import (
"bytes"
"context"
"encoding/json"
"fmt"
"reflect"
"regexp"
"sort"
"strings"
"time"
"github.com/ddosify/alaz/log"
"github.com/gogo/protobuf/jsonpb"
"github.com/golang/protobuf/proto" //nolint:staticcheck
internalapi "k8s.io/cri-api/pkg/apis"
pb "k8s.io/cri-api/pkg/apis/runtime/v1"
)
func getContainersList(containersList []*pb.Container, opts listOptions) []*pb.Container {
filtered := []*pb.Container{}
for _, c := range containersList {
// Filter by pod name/namespace regular expressions.
if matchesRegex(opts.nameRegexp, c.Metadata.Name) {
filtered = append(filtered, c)
}
}
sort.Sort(containerByCreated(filtered))
n := len(filtered)
if opts.latest {
n = 1
}
if opts.last > 0 {
n = opts.last
}
n = func(a, b int) int {
if a < b {
return a
}
return b
}(n, len(filtered))
return filtered[:n]
}
func ListContainers(runtimeClient internalapi.RuntimeService, opts listOptions) error {
filter := &pb.ContainerFilter{}
if opts.id != "" {
filter.Id = opts.id
}
if opts.podID != "" {
filter.PodSandboxId = opts.podID
}
st := &pb.ContainerStateValue{}
if !opts.all && opts.state == "" {
st.State = pb.ContainerState_CONTAINER_RUNNING
filter.State = st
}
if opts.state != "" {
st.State = pb.ContainerState_CONTAINER_UNKNOWN
switch strings.ToLower(opts.state) {
case "created":
st.State = pb.ContainerState_CONTAINER_CREATED
filter.State = st
case "running":
st.State = pb.ContainerState_CONTAINER_RUNNING
filter.State = st
case "exited":
st.State = pb.ContainerState_CONTAINER_EXITED
filter.State = st
case "unknown":
st.State = pb.ContainerState_CONTAINER_UNKNOWN
filter.State = st
default:
log.Logger.Fatal().Msgf("--state should be one of created, running, exited or unknown")
}
}
if opts.latest || opts.last > 0 {
// Do not filter by state if latest/last is specified.
filter.State = nil
}
if opts.labels != nil {
filter.LabelSelector = opts.labels
}
r, err := runtimeClient.ListContainers(context.TODO(), filter)
// logrus.Debugf("ListContainerResponse: %v", r)
if err != nil {
return err
}
r = getContainersList(r, opts)
switch opts.output {
case "json":
return outputProtobufObjAsJSON(&pb.ListContainersResponse{Containers: r})
case "table":
// continue; output will be generated after the switch block ends.
default:
return fmt.Errorf("unsupported output format %q", opts.output)
}
return nil
}
// ContainerStatus sends a ContainerStatusRequest to the server, and parses
// the returned ContainerStatusResponse.
func ContainerStatus(client internalapi.RuntimeService, id, output string, tmplStr string, quiet bool) error {
verbose := !(quiet)
if output == "" { // default to json output
output = "json"
}
if id == "" {
return fmt.Errorf("ID cannot be empty")
}
// request := &pb.ContainerStatusRequest{
// ContainerId: id,
// Verbose: verbose,
// }
// logrus.Debugf("ContainerStatusRequest: %v", request)
r, err := client.ContainerStatus(context.TODO(), id, verbose)
// logrus.Debugf("ContainerStatusResponse: %v", r)
if err != nil {
return err
}
status, err := marshalContainerStatus(r.Status)
if err != nil {
return err
}
switch output {
case "json", "go-template":
return outputStatusInfo(status, r.Info, output, tmplStr)
// case "table": // table output is after this switch block
default:
return fmt.Errorf("output option cannot be %s", output)
}
return nil
}
// marshalContainerStatus converts container status into string and converts
// the timestamps into readable format.
func marshalContainerStatus(cs *pb.ContainerStatus) (string, error) {
statusStr, err := protobufObjectToJSON(cs)
if err != nil {
return "", err
}
jsonMap := make(map[string]interface{})
err = json.Unmarshal([]byte(statusStr), &jsonMap)
if err != nil {
return "", err
}
jsonMap["createdAt"] = time.Unix(0, cs.CreatedAt).Format(time.RFC3339Nano)
var startedAt, finishedAt time.Time
if cs.State != pb.ContainerState_CONTAINER_CREATED {
// If container is not in the created state, we have tried and
// started the container. Set the startedAt.
startedAt = time.Unix(0, cs.StartedAt)
}
if cs.State == pb.ContainerState_CONTAINER_EXITED ||
(cs.State == pb.ContainerState_CONTAINER_UNKNOWN && cs.FinishedAt > 0) {
// If container is in the exit state, set the finishedAt.
// Or if container is in the unknown state and FinishedAt > 0, set the finishedAt
finishedAt = time.Unix(0, cs.FinishedAt)
}
jsonMap["startedAt"] = startedAt.Format(time.RFC3339Nano)
jsonMap["finishedAt"] = finishedAt.Format(time.RFC3339Nano)
return marshalMapInOrder(jsonMap, *cs)
}
func outputStatusInfo(status 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 + ","
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 "json":
var output bytes.Buffer
if err := json.Indent(&output, []byte(jsonInfo), "", " "); err != nil {
return err
}
fmt.Println(output.String())
default:
fmt.Printf("Don't support %q format\n", format)
}
return 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
}
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 containerByCreated []*pb.Container
func (a containerByCreated) Len() int { return len(a) }
func (a containerByCreated) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a containerByCreated) Less(i, j int) bool {
return a[i].CreatedAt > a[j].CreatedAt
}
func outputProtobufObjAsJSON(obj proto.Message) error {
marshaledJSON, err := protobufObjectToJSON(obj)
if err != nil {
fmt.Println(err)
return err
}
fmt.Println("here")
fmt.Println(marshaledJSON)
return 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 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
}