This repository has been archived by the owner on Oct 26, 2023. It is now read-only.
/
image.go
305 lines (288 loc) · 8.33 KB
/
image.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
// Copyright © 2017 Max Goltzsche
//
// 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 cmd
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/containers/image/transports"
humanize "github.com/dustin/go-humanize"
"github.com/mgoltzsche/ctnr/image"
"github.com/mgoltzsche/ctnr/image/builder"
"github.com/opencontainers/go-digest"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
var (
imageCmd = &cobra.Command{
Use: "image",
Short: "Manages images",
Long: `Provides subcommands to manage images in the local store.`,
}
imageListCmd = &cobra.Command{
Use: "list",
Short: "Lists all images",
Long: `Lists all images available in the local store.`,
Run: wrapRun(runImageList),
}
imageTagCmd = &cobra.Command{
Use: "tag IMAGE...",
Short: "Tags one or many images",
Long: `Tags one or many images in the local store.`,
Run: wrapRun(runImageTag),
}
imageUntagCmd = &cobra.Command{
Use: "untag IMAGE...",
Short: "Untags one or many images",
Long: `Untags one or many images in the local store.`,
Run: wrapRun(runImageUntag),
}
imageRmCmd = &cobra.Command{
Use: "rm IMAGEID",
Short: "Removes the image from the store",
Long: `Removes the image as well as all tags referencing it from the store.`,
Run: wrapRun(runImageRm),
}
imageGcCmd = &cobra.Command{
Use: "gc",
Short: "Garbage collects image blobs",
Long: `Garbage collects all image blobs in the local store that are not referenced.`,
Run: wrapRun(runImageGc),
}
imageImportCmd = &cobra.Command{
Use: "import IMAGE",
Short: "Imports an image",
Long: `Fetches an image either from a local or remote source and
imports it into the local store.`,
Run: wrapRun(runImageImport),
}
imageExportCmd = &cobra.Command{
Use: "export IMAGEREF DEST",
Short: "Exports an image",
Long: `Exports an image from the local store
to a local or remote destination.`,
Run: func(cmd *cobra.Command, args []string) {
panic("TODO: export image")
},
}
imageCatConfigCmd = &cobra.Command{
Use: "cat-config IMAGE",
Short: "Prints an image's configuration",
Long: `Prints an image's configuration.`,
Run: wrapRun(runImageCatConfig),
}
imageBuildCmd = &cobra.Command{
Use: "build",
Short: "Builds a new image from the provided options",
Long: `Builds a new image from the provided options.`,
Run: wrapRun(runImageBuildRun),
}
flagImageTTL time.Duration
flagImageRefTTL time.Duration
flagImageMaxPerRepo int
defaultImageTTL = time.Duration(1000 * 1000 * 1000 * 60 * 60 * 24 * 7 /*7 days*/)
)
func init() {
transportsHelp := "\n\nSupported transports:\n " +
strings.Join(transports.ListNames(), "\n ") +
"\n\nExample image refs:\n docker://alpine:latest\n oci:mydir:latest"
imageExportCmd.Long += transportsHelp
imageImportCmd.Long += transportsHelp
initImageBuildFlags(imageBuildCmd.Flags())
imageCmd.AddCommand(imageListCmd)
imageCmd.AddCommand(imageTagCmd)
imageCmd.AddCommand(imageUntagCmd)
imageCmd.AddCommand(imageRmCmd)
imageCmd.AddCommand(imageGcCmd)
imageCmd.AddCommand(imageImportCmd)
imageCmd.AddCommand(imageExportCmd)
imageCmd.AddCommand(imageCatConfigCmd)
imageCmd.AddCommand(imageBuildCmd)
imageGcCmd.Flags().DurationVarP(&flagImageTTL, "ttl", "t", defaultImageTTL, "image lifetime before it gets garbage collected")
imageGcCmd.Flags().DurationVarP(&flagImageRefTTL, "ref-ttl", "r", 0, "tagged image lifetime before it gets garbage collected")
imageGcCmd.Flags().IntVarP(&flagImageMaxPerRepo, "max", "m", 0, "max entries per repo (default 0 == unlimited)")
}
func runImageList(cmd *cobra.Command, args []string) (err error) {
imgs, err := store.Images()
if err != nil {
return
}
sort.Slice(imgs, func(i, j int) bool {
return imgs[i].LastUsed.Before(imgs[j].LastUsed)
})
f := "%-35s %-15s %-71s %-15s %8s\n"
fmt.Printf(f, "REPO", "REF", "ID", "CREATED", "SIZE")
for _, img := range imgs {
repo := ""
ref := ""
if img.Tag != nil {
repo = img.Tag.Repo
ref = img.Tag.Ref
}
fmt.Printf(f, repo, ref, img.ID(), humanize.Time(img.Created), humanize.Bytes(img.Size()))
}
return
}
func runImageGc(cmd *cobra.Command, args []string) error {
if len(args) != 0 {
return usageError("No argument expected: " + args[0])
}
return store.ImageGC(flagImageTTL, flagImageRefTTL, flagImageMaxPerRepo)
}
func runImageRm(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
return usageError("No IMAGEID provided")
}
ids := make([]digest.Digest, len(args))
for i, a := range args {
if d, e := digest.Parse(a); e == nil && d.Validate() == nil {
ids[i] = d
} else {
return errors.Errorf("invalid IMAGEID %q provided", a)
}
}
return store.DelImage(ids...)
}
func runImageImport(cmd *cobra.Command, args []string) (err error) {
if len(args) != 1 {
return usageError("No image provided")
}
lockedStore, err := openImageStore()
if err != nil {
return
}
img, err := lockedStore.ImportImage(args[0])
if err == nil {
fmt.Fprintln(os.Stdout, img.ID())
}
return
}
func runImageTag(cmd *cobra.Command, args []string) (err error) {
if len(args) < 2 {
return usageError("ImageID and tag arguments required")
}
lockedStore, err := openImageStore()
if err != nil {
return
}
imageId, err := digest.Parse(args[0])
if err != nil {
return
}
for _, tag := range args[1:] {
if _, err = lockedStore.TagImage(imageId, tag); err != nil {
return
}
}
return
}
func runImageUntag(cmd *cobra.Command, args []string) (err error) {
if len(args) == 0 {
return usageError("No image tag argument provided")
}
lockedStore, err := openImageStore()
if err != nil {
return
}
for _, tag := range args {
e := lockedStore.UntagImage(tag)
if e != nil {
loggers.Error.Println(e)
err = e
}
}
if err != nil {
err = errors.New("Failed to untag all images")
}
return
}
func runImageCatConfig(cmd *cobra.Command, args []string) (err error) {
if len(args) != 1 {
return usageError("No IMAGE argument provided")
}
lockedStore, err := openImageStore()
if err != nil {
return
}
img, err := image.GetLocalImage(lockedStore, args[0])
if err != nil {
return
}
b, err := json.MarshalIndent(&img.Config, "", " ")
if err != nil {
return
}
fmt.Println(string(b))
return
}
func runImageBuildRun(cmd *cobra.Command, args []string) (err error) {
if len(args) > 0 {
flagImageBuildOps.dockerfileDir = args[0]
} else if flagImageBuildOps.dockerfileDir, err = os.Getwd(); err != nil {
return
}
if flagImageBuildOps.dockerfileDir, err = filepath.Abs(flagImageBuildOps.dockerfileDir); err != nil {
return
}
if len(args) > 1 {
return usageError(fmt.Sprintf("Only one context path supported as argument but provided: %v", args[1:]))
}
lockedStore, err := openImageStore()
if err != nil {
return
}
cache := builder.NewNoOpCache()
if !flagNoCache {
cache = builder.NewImageBuildCache(filepath.Join(flagStoreDir, "image-build-cache"), loggers.Warn)
}
proot := ""
if flagProot {
proot = flagPRootPath
if proot == "" {
return usageError("proot enabled but no --proot-path provided")
}
}
tmpDir := filepath.Join(flagStoreDir, "tmp")
imageBuilder := builder.NewImageBuilder(builder.ImageBuildConfig{
Images: lockedStore,
Bundles: store.BundleStore,
Cache: cache,
Tempfs: tmpDir,
RunRoot: flagStateDir,
Rootless: flagRootless,
PRoot: proot,
RemoveSucceededBundles: flagRm || flagAll,
RemoveFailedBundle: flagAll,
Loggers: loggers,
})
defer func() {
if e := imageBuilder.Close(); e != nil {
loggers.Error.Println(e)
}
}()
if len(flagImageBuildOps.ops) == 0 {
return errors.New("no build operations provided")
}
for _, op := range flagImageBuildOps.ops {
if err = op(imageBuilder); err != nil {
return
}
}
fmt.Fprintln(os.Stdout, imageBuilder.Image())
return
}