This repository has been archived by the owner on Feb 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 887
/
image_list.go
268 lines (242 loc) · 7.72 KB
/
image_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
// Copyright 2015 The rkt 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"
"encoding/json"
"fmt"
"strings"
rktflag "github.com/coreos/rkt/rkt/flag"
"github.com/coreos/rkt/store"
"github.com/appc/spec/schema"
"github.com/appc/spec/schema/lastditch"
"github.com/dustin/go-humanize"
"github.com/spf13/cobra"
)
const (
defaultTimeLayout = "2006-01-02 15:04:05.999 -0700 MST"
id = "id"
name = "name"
importTime = "import time"
lastUsed = "last used"
size = "size"
latest = "latest"
)
// Convenience methods for formatting fields
func l(s string) string {
return strings.ToLower(strings.Replace(s, " ", "", -1))
}
func u(s string) string {
return strings.ToUpper(s)
}
var (
// map of valid fields and related header name
ImagesFieldHeaderMap = map[string]string{
l(id): u(id),
l(name): u(name),
l(importTime): u(importTime),
l(lastUsed): u(lastUsed),
l(latest): u(latest),
l(size): u(size),
}
// map of valid sort fields containing the mapping between the provided field name
// and the related aciinfo's field name.
ImagesFieldAciInfoMap = map[string]string{
l(id): "blobkey",
l(name): l(name),
l(importTime): l(importTime),
l(lastUsed): l(lastUsed),
l(latest): l(latest),
l(size): l(size),
}
ImagesSortableFields = map[string]struct{}{
l(name): struct{}{},
l(importTime): struct{}{},
l(lastUsed): struct{}{},
l(size): struct{}{},
}
)
type ImagesSortAsc bool
func (isa *ImagesSortAsc) Set(s string) error {
switch strings.ToLower(s) {
case "asc":
*isa = true
case "desc":
*isa = false
default:
return fmt.Errorf("wrong sort order")
}
return nil
}
func (isa *ImagesSortAsc) String() string {
if *isa {
return "asc"
}
return "desc"
}
func (isa *ImagesSortAsc) Type() string {
return "imagesSortAsc"
}
var (
cmdImageList = &cobra.Command{
Use: "list",
Short: "List images in the local store",
Long: `Optionally, allows the user to specify the fields and sort order.`,
Run: runWrapper(runImages),
}
flagImagesFields *rktflag.OptionList
flagImagesSortFields *rktflag.OptionList
flagImagesSortAsc ImagesSortAsc
)
func init() {
sortFields := []string{l(name), l(importTime), l(lastUsed), l(size)}
fields := append([]string{l(id)}, append(sortFields, l(latest))...)
// Set defaults
var err error
flagImagesFields, err = rktflag.NewOptionList(fields, strings.Join(fields, ","))
if err != nil {
stderr.FatalE("", err)
}
flagImagesSortFields, err = rktflag.NewOptionList(sortFields, l(importTime))
if err != nil {
stderr.FatalE("", err)
}
flagImagesSortAsc = true
cmdImage.AddCommand(cmdImageList)
cmdImageList.Flags().Var(flagImagesFields, "fields", fmt.Sprintf(`comma-separated list of fields to display. Accepted values: %s`,
flagImagesFields.PermissibleString()))
cmdImageList.Flags().Var(flagImagesSortFields, "sort", fmt.Sprintf(`sort the output according to the provided comma-separated list of fields. Accepted values: %s`,
flagImagesSortFields.PermissibleString()))
cmdImageList.Flags().Var(&flagImagesSortAsc, "order", `choose the sorting order if at least one sort field is provided (--sort). Accepted values: "asc", "desc"`)
cmdImageList.Flags().BoolVar(&flagNoLegend, "no-legend", false, "suppress a legend with the list")
cmdImageList.Flags().BoolVar(&flagFullOutput, "full", false, "use long output format")
}
func runImages(cmd *cobra.Command, args []string) int {
var errors []error
tabBuffer := new(bytes.Buffer)
tabOut := getTabOutWithWriter(tabBuffer)
if !flagNoLegend {
var headerFields []string
for _, f := range flagImagesFields.Options {
headerFields = append(headerFields, ImagesFieldHeaderMap[f])
}
fmt.Fprintf(tabOut, "%s\n", strings.Join(headerFields, "\t"))
}
s, err := store.NewStore(getDataDir())
if err != nil {
stderr.PrintE("cannot open store", err)
return 1
}
var sortAciinfoFields []string
for _, f := range flagImagesSortFields.Options {
sortAciinfoFields = append(sortAciinfoFields, ImagesFieldAciInfoMap[f])
}
aciInfos, err := s.GetAllACIInfos(sortAciinfoFields, bool(flagImagesSortAsc))
if err != nil {
stderr.PrintE("unable to get aci infos", err)
return 1
}
for _, aciInfo := range aciInfos {
imj, err := s.GetImageManifestJSON(aciInfo.BlobKey)
if err != nil {
// ignore aciInfo with missing image manifest as it can be deleted in the meantime
continue
}
var im *schema.ImageManifest
if err = json.Unmarshal(imj, &im); err != nil {
errors = append(errors, newImgListLoadError(err, imj, aciInfo.BlobKey))
continue
}
version, ok := im.Labels.Get("version")
var fieldValues []string
for _, f := range flagImagesFields.Options {
fieldValue := ""
switch f {
case l(id):
hashKey := aciInfo.BlobKey
if !flagFullOutput {
// The short hash form is [HASH_ALGO]-[FIRST 12 CHAR]
// For example, sha512-123456789012
pos := strings.Index(hashKey, "-")
trimLength := pos + 13
if pos > 0 && trimLength < len(hashKey) {
hashKey = hashKey[:trimLength]
}
}
fieldValue = hashKey
case l(name):
fieldValue = aciInfo.Name
if ok {
fieldValue = fmt.Sprintf("%s:%s", fieldValue, version)
}
case l(importTime):
if flagFullOutput {
fieldValue = aciInfo.ImportTime.Format(defaultTimeLayout)
} else {
fieldValue = humanize.Time(aciInfo.ImportTime)
}
case l(lastUsed):
if flagFullOutput {
fieldValue = aciInfo.LastUsed.Format(defaultTimeLayout)
} else {
fieldValue = humanize.Time(aciInfo.LastUsed)
}
case l(size):
totalSize := aciInfo.Size + aciInfo.TreeStoreSize
if flagFullOutput {
fieldValue = fmt.Sprintf("%d", totalSize)
} else {
fieldValue = humanize.IBytes(uint64(totalSize))
}
case l(latest):
fieldValue = fmt.Sprintf("%t", aciInfo.Latest)
}
fieldValues = append(fieldValues, fieldValue)
}
fmt.Fprintf(tabOut, "%s\n", strings.Join(fieldValues, "\t"))
}
if len(errors) > 0 {
sep := "----------------------------------------"
stderr.Printf("%d error(s) encountered when listing images:", len(errors))
stderr.Print(sep)
for _, err := range errors {
stderr.Error(err)
stderr.Print(sep)
}
stderr.Print("misc:")
stderr.Printf(" rkt's appc version: %s", schema.AppContainerVersion)
// make a visible break between errors and the listing
stderr.Print("")
}
tabOut.Flush()
stdout.Print(tabBuffer.String())
return 0
}
func newImgListLoadError(err error, imj []byte, blobKey string) error {
var lines []string
im := lastditch.ImageManifest{}
imErr := im.UnmarshalJSON(imj)
if imErr == nil {
lines = append(lines, fmt.Sprintf("Unable to load manifest of image %s (spec version %s) because it is invalid:", im.Name, im.ACVersion))
lines = append(lines, fmt.Sprintf(" %v", err))
} else {
lines = append(lines, "Unable to load manifest of an image because it is invalid:")
lines = append(lines, fmt.Sprintf(" %v", err))
lines = append(lines, " Also, failed to get any information about invalid image manifest:")
lines = append(lines, fmt.Sprintf(" %v", imErr))
}
lines = append(lines, "ID of the invalid image:")
lines = append(lines, fmt.Sprintf(" %s", blobKey))
return fmt.Errorf("%s", strings.Join(lines, "\n"))
}