This repository has been archived by the owner on May 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 70
/
list.go
392 lines (331 loc) · 10.6 KB
/
list.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
// Copyright (c) 2014,2015,2016,2017 Docker, Inc.
// Copyright (c) 2017 Intel Corporation
//
// 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 (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"syscall"
"text/tabwriter"
"time"
"github.com/urfave/cli"
vc "github.com/kata-containers/runtime/virtcontainers"
oci "github.com/kata-containers/runtime/virtcontainers/pkg/oci"
)
const formatOptions = `table or json`
// containerState represents the platform agnostic pieces relating to a
// running container's status and state
type containerState struct {
// Version is the OCI version for the container
Version string `json:"ociVersion"`
// ID is the container ID
ID string `json:"id"`
// InitProcessPid is the init process id in the parent namespace
InitProcessPid int `json:"pid"`
// Status is the current status of the container, running, paused, ...
Status string `json:"status"`
// Bundle is the path on the filesystem to the bundle
Bundle string `json:"bundle"`
// Rootfs is a path to a directory containing the container's root filesystem.
Rootfs string `json:"rootfs"`
// Created is the unix timestamp for the creation time of the container in UTC
Created time.Time `json:"created"`
// Annotations is the user defined annotations added to the config.
Annotations map[string]string `json:"annotations,omitempty"`
// The owner of the state directory (the owner of the container).
Owner string `json:"owner"`
}
type asset struct {
Path string `json:"path"`
Custom bool `json:"bool"`
}
// hypervisorDetails stores details of the hypervisor used to host
// the container
type hypervisorDetails struct {
HypervisorAsset asset `json:"hypervisorAsset"`
ImageAsset asset `json:"imageAsset"`
KernelAsset asset `json:"kernelAsset"`
}
// fullContainerState specifies the core state plus the hypervisor
// details
type fullContainerState struct {
containerState
CurrentHypervisorDetails hypervisorDetails `json:"currentHypervisor"`
LatestHypervisorDetails hypervisorDetails `json:"latestHypervisor"`
StaleAssets []string
}
type formatState interface {
Write(state []fullContainerState, showAll bool, file *os.File) error
}
type formatJSON struct{}
type formatIDList struct{}
type formatTabular struct{}
var listCLICommand = cli.Command{
Name: "list",
Usage: "lists containers started by " + name + " with the given root",
ArgsUsage: `
Where the given root is specified via the global option "--root"
(default: "` + defaultRootDirectory + `").
EXAMPLE 1:
To list containers created via the default "--root":
# ` + name + ` list
EXAMPLE 2:
To list containers created using a non-default value for "--root":
# ` + name + ` --root value list`,
Flags: []cli.Flag{
cli.StringFlag{
Name: "format, f",
Value: "table",
Usage: `select one of: ` + formatOptions,
},
cli.BoolFlag{
Name: "quiet, q",
Usage: "display only container IDs",
},
cli.BoolFlag{
Name: "cc-all",
Usage: "display all available " + project + " information",
},
},
Action: func(context *cli.Context) error {
s, err := getContainers(context)
if err != nil {
return err
}
file := defaultOutputFile
showAll := context.Bool("cc-all")
var fs formatState = formatIDList{}
if context.Bool("quiet") {
fs = formatIDList{}
} else {
switch context.String("format") {
case "table":
fs = formatTabular{}
case "json":
fs = formatJSON{}
default:
return fmt.Errorf("invalid format option")
}
}
return fs.Write(s, showAll, file)
},
}
// getStaleAssetsreturns compares the two specified hypervisorDetails objects
// and returns a list of strings representing which assets in "old" are not
// current compared to "new". If old and new are identical, the empty string
// will be returned.
//
// Notes:
//
// - This function is trivial because it relies upon the fact that new
// containers are always created with the latest versions of all assets.
//
// - WARNING: Since this function only compares local values, it is unable to
// determine if newer (remote) assets are available.
func getStaleAssets(old, new hypervisorDetails) []string {
var stale []string
if old.KernelAsset.Path != new.KernelAsset.Path {
if old.KernelAsset.Custom {
// The workload kernel asset is a custom one, i.e. it's not coming
// from the runtime configuration file. Thus it does not make sense
// to compare it against the configured kernel asset.
// We assume a custom kernel asset has been updated if the
// corresponding path no longer exists, i.e. it's been replaced by
// a new kernel, e.g. with a new version name.
// Replacing a custom kernel asset binary with exactly the same
// binary name won't allow us to detect if it's staled or not.
if _, err := os.Stat(old.KernelAsset.Path); os.IsNotExist(err) {
stale = append(stale, "kernel")
}
} else {
stale = append(stale, "kernel")
}
}
if old.ImageAsset.Path != new.ImageAsset.Path {
if old.ImageAsset.Custom {
// The workload image asset is a custom one, i.e. it's not coming
// from the runtime configuration file. Thus it does not make sense
// to compare it against the configured image asset.
// We assume a custom image asset has been updated if the
// corresponding path no longer exists, i.e. it's been replaced by
// a new image, e.g. with a new version name.
// Replacing a custom image asset binary with exactly the same
// binary name won't allow us to detect if it's staled or not.
if _, err := os.Stat(old.ImageAsset.Path); os.IsNotExist(err) {
stale = append(stale, "image")
}
} else {
stale = append(stale, "image")
}
}
return stale
}
func (f formatIDList) Write(state []fullContainerState, showAll bool, file *os.File) error {
for _, item := range state {
_, err := fmt.Fprintln(file, item.ID)
if err != nil {
return err
}
}
return nil
}
func (f formatTabular) Write(state []fullContainerState, showAll bool, file *os.File) error {
// values used by runc
flags := uint(0)
minWidth := 12
tabWidth := 1
padding := 3
w := tabwriter.NewWriter(file, minWidth, tabWidth, padding, ' ', flags)
fmt.Fprint(w, "ID\tPID\tSTATUS\tBUNDLE\tCREATED\tOWNER")
if showAll {
fmt.Fprint(w, "\tHYPERVISOR\tKERNEL\tIMAGE\tLATEST-KERNEL\tLATEST-IMAGE\tSTALE\n")
} else {
fmt.Fprintf(w, "\n")
}
for _, item := range state {
fmt.Fprintf(w, "%s\t%d\t%s\t%s\t%s\t%s",
item.ID,
item.InitProcessPid,
item.Status,
item.Bundle,
item.Created.Format(time.RFC3339Nano),
item.Owner)
if showAll {
stale := strings.Join(item.StaleAssets, ",")
if stale == "" {
stale = "-"
}
current := item.CurrentHypervisorDetails
latest := item.LatestHypervisorDetails
all := fmt.Sprintf("\t%s\t%s\t%s",
current.HypervisorAsset.Path,
current.KernelAsset.Path,
current.ImageAsset.Path)
if !current.KernelAsset.Custom {
all += fmt.Sprintf("\t%s", latest.KernelAsset.Path)
} else {
all += fmt.Sprintf("\t%s", current.KernelAsset.Path)
}
if !current.ImageAsset.Custom {
all += fmt.Sprintf("\t%s", latest.ImageAsset.Path)
} else {
all += fmt.Sprintf("\t%s", current.ImageAsset.Path)
}
all += fmt.Sprintf("\t%s\n", stale)
fmt.Fprint(w, all)
} else {
fmt.Fprint(w, "\n")
}
}
return w.Flush()
}
func (f formatJSON) Write(state []fullContainerState, showAll bool, file *os.File) error {
return json.NewEncoder(file).Encode(state)
}
// getDirOwner returns the UID of the specified directory
func getDirOwner(dir string) (uint32, error) {
if dir == "" {
return 0, errors.New("BUG: need directory")
}
st, err := os.Stat(dir)
if err != nil {
return 0, err
}
if !st.IsDir() {
return 0, fmt.Errorf("%q is not a directory", dir)
}
statType, ok := st.Sys().(*syscall.Stat_t)
if !ok {
return 0, fmt.Errorf("cannot convert %+v to stat type for directory %q", st, dir)
}
return statType.Uid, nil
}
func getContainers(context *cli.Context) ([]fullContainerState, error) {
runtimeConfig, ok := context.App.Metadata["runtimeConfig"].(oci.RuntimeConfig)
if !ok {
return nil, errors.New("invalid runtime config")
}
latestHypervisorDetails := getHypervisorDetails(&runtimeConfig.HypervisorConfig)
podList, err := vci.ListPod()
if err != nil {
return nil, err
}
var s []fullContainerState
for _, pod := range podList {
if len(pod.ContainersStatus) == 0 {
// ignore empty pods
continue
}
currentHypervisorDetails := getHypervisorDetails(&pod.HypervisorConfig)
for _, container := range pod.ContainersStatus {
ociState := oci.StatusToOCIState(container)
staleAssets := getStaleAssets(currentHypervisorDetails, latestHypervisorDetails)
uid, err := getDirOwner(container.RootFs)
if err != nil {
return nil, err
}
owner := fmt.Sprintf("#%v", uid)
s = append(s, fullContainerState{
containerState: containerState{
Version: ociState.Version,
ID: ociState.ID,
InitProcessPid: ociState.Pid,
Status: ociState.Status,
Bundle: ociState.Bundle,
Rootfs: container.RootFs,
Created: container.StartTime,
Annotations: ociState.Annotations,
Owner: owner,
},
CurrentHypervisorDetails: currentHypervisorDetails,
LatestHypervisorDetails: latestHypervisorDetails,
StaleAssets: staleAssets,
})
}
}
return s, nil
}
// getHypervisorDetails returns details of the latest version of the
// hypervisor and the associated assets.
func getHypervisorDetails(hypervisorConfig *vc.HypervisorConfig) hypervisorDetails {
hypervisorPath, err := hypervisorConfig.HypervisorAssetPath()
if err != nil {
hypervisorPath = hypervisorConfig.HypervisorPath
}
kernelPath, err := hypervisorConfig.KernelAssetPath()
if err != nil {
kernelPath = hypervisorConfig.KernelPath
}
imagePath, err := hypervisorConfig.ImageAssetPath()
if err != nil {
imagePath = hypervisorConfig.ImagePath
}
return hypervisorDetails{
HypervisorAsset: asset{
Path: hypervisorPath,
Custom: hypervisorConfig.CustomHypervisorAsset(),
},
KernelAsset: asset{
Path: kernelPath,
Custom: hypervisorConfig.CustomKernelAsset(),
},
ImageAsset: asset{
Path: imagePath,
Custom: hypervisorConfig.CustomImageAsset(),
},
}
}