-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
image.go
1853 lines (1673 loc) · 54.2 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
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package image
import (
"context"
"encoding/json"
stderrors "errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"syscall"
"time"
"github.com/containers/common/pkg/retry"
cp "github.com/containers/image/v5/copy"
"github.com/containers/image/v5/directory"
"github.com/containers/image/v5/docker/archive"
dockerarchive "github.com/containers/image/v5/docker/archive"
"github.com/containers/image/v5/docker/reference"
"github.com/containers/image/v5/image"
"github.com/containers/image/v5/manifest"
ociarchive "github.com/containers/image/v5/oci/archive"
"github.com/containers/image/v5/oci/layout"
"github.com/containers/image/v5/pkg/shortnames"
is "github.com/containers/image/v5/storage"
"github.com/containers/image/v5/tarball"
"github.com/containers/image/v5/transports"
"github.com/containers/image/v5/transports/alltransports"
"github.com/containers/image/v5/types"
"github.com/containers/podman/v2/libpod/driver"
"github.com/containers/podman/v2/libpod/events"
"github.com/containers/podman/v2/pkg/inspect"
"github.com/containers/podman/v2/pkg/registries"
"github.com/containers/podman/v2/pkg/util"
"github.com/containers/storage"
digest "github.com/opencontainers/go-digest"
imgspecv1 "github.com/opencontainers/image-spec/specs-go/v1"
ociv1 "github.com/opencontainers/image-spec/specs-go/v1"
opentracing "github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// Image is the primary struct for dealing with images
// It is still very much a work in progress
type Image struct {
// Adding these two structs for now but will cull when we near
// completion of this library.
imgRef types.Image
imgSrcRef types.ImageSource
inspect.ImageData
inspect.ImageResult
inspectInfo *types.ImageInspectInfo
InputName string
image *storage.Image
imageruntime *Runtime
}
// Runtime contains the store
type Runtime struct {
store storage.Store
SignaturePolicyPath string
EventsLogFilePath string
EventsLogger string
Eventer events.Eventer
}
// InfoImage keep information of Image along with all associated layers
type InfoImage struct {
// ID of image
ID string
// Tags of image
Tags []string
// Layers stores all layers of image.
Layers []LayerInfo
}
const maxRetry = 3
// ImageFilter is a function to determine whether a image is included
// in command output. Images to be outputted are tested using the function.
// A true return will include the image, a false return will exclude it.
type ImageFilter func(*Image) bool //nolint
// ErrRepoTagNotFound is the error returned when the image id given doesn't match a rep tag in store
var ErrRepoTagNotFound = stderrors.New("unable to match user input to any specific repotag")
// ErrImageIsBareList is the error returned when the image is just a list or index
var ErrImageIsBareList = stderrors.New("image contains a manifest list or image index, but no runnable image")
// NewImageRuntimeFromStore creates an ImageRuntime based on a provided store
func NewImageRuntimeFromStore(store storage.Store) *Runtime {
return &Runtime{
store: store,
}
}
// NewImageRuntimeFromOptions creates an Image Runtime including the store given
// store options
func NewImageRuntimeFromOptions(options storage.StoreOptions) (*Runtime, error) {
store, err := setStore(options)
if err != nil {
return nil, err
}
return NewImageRuntimeFromStore(store), nil
}
func setStore(options storage.StoreOptions) (storage.Store, error) {
store, err := storage.GetStore(options)
if err != nil {
return nil, err
}
is.Transport.SetStore(store)
return store, nil
}
// newImage creates a new image object given an "input name" and a storage.Image
func (ir *Runtime) newImage(inputName string, img *storage.Image) *Image {
return &Image{
InputName: inputName,
imageruntime: ir,
image: img,
}
}
// newFromStorage creates a new image object from a storage.Image. Its "input name" will be its ID.
func (ir *Runtime) newFromStorage(img *storage.Image) *Image {
return ir.newImage(img.ID, img)
}
// NewFromLocal creates a new image object that is intended
// to only deal with local images already in the store (or
// its aliases)
func (ir *Runtime) NewFromLocal(name string) (*Image, error) {
updatedInputName, localImage, err := ir.getLocalImage(name)
if err != nil {
return nil, err
}
return ir.newImage(updatedInputName, localImage), nil
}
// New creates a new image object where the image could be local
// or remote
func (ir *Runtime) New(ctx context.Context, name, signaturePolicyPath, authfile string, writer io.Writer, dockeroptions *DockerRegistryOptions, signingoptions SigningOptions, label *string, pullType util.PullType) (*Image, error) {
span, _ := opentracing.StartSpanFromContext(ctx, "newImage")
span.SetTag("type", "runtime")
defer span.Finish()
// We don't know if the image is local or not ... check local first
if pullType != util.PullImageAlways {
newImage, err := ir.NewFromLocal(name)
if err == nil {
return newImage, nil
} else if pullType == util.PullImageNever {
return nil, err
}
}
// The image is not local
if signaturePolicyPath == "" {
signaturePolicyPath = ir.SignaturePolicyPath
}
imageName, err := ir.pullImageFromHeuristicSource(ctx, name, writer, authfile, signaturePolicyPath, signingoptions, dockeroptions, &retry.RetryOptions{MaxRetry: maxRetry}, label)
if err != nil {
return nil, err
}
newImage, err := ir.NewFromLocal(imageName[0])
if err != nil {
return nil, errors.Wrapf(err, "error retrieving local image after pulling %s", name)
}
return newImage, nil
}
// SaveImages stores one more images in a multi-image archive.
// Note that only `docker-archive` supports storing multiple
// image.
func (ir *Runtime) SaveImages(ctx context.Context, namesOrIDs []string, format string, outputFile string, quiet, removeSignatures bool) (finalErr error) {
if format != DockerArchive {
return errors.Errorf("multi-image archives are only supported in in the %q format", DockerArchive)
}
sys := GetSystemContext("", "", false)
archWriter, err := archive.NewWriter(sys, outputFile)
if err != nil {
return err
}
defer func() {
err := archWriter.Close()
if err == nil {
return
}
if finalErr == nil {
finalErr = err
return
}
finalErr = errors.Wrap(finalErr, err.Error())
}()
// Decide whether c/image's progress bars should use stderr or stdout.
// Use stderr in case we need to be quiet or if the output is set to
// stdout. If the output is set of stdout, any log message there would
// corrupt the tarfile.
writer := os.Stdout
if quiet {
writer = os.Stderr
}
// extend an image with additional tags
type imageData struct {
*Image
tags []reference.NamedTagged
}
// Look up the images (and their tags) in the local storage.
imageMap := make(map[string]*imageData) // to group tags for an image
imageQueue := []string{} // to preserve relative image order
for _, nameOrID := range namesOrIDs {
// Look up the name or ID in the local image storage.
localImage, err := ir.NewFromLocal(nameOrID)
if err != nil {
return err
}
id := localImage.ID()
iData, exists := imageMap[id]
if !exists {
imageQueue = append(imageQueue, id)
iData = &imageData{Image: localImage}
imageMap[id] = iData
}
// Unless we referred to an ID, add the input as a tag.
if !strings.HasPrefix(id, nameOrID) {
tag, err := NormalizedTag(nameOrID)
if err != nil {
return err
}
refTagged, isTagged := tag.(reference.NamedTagged)
if isTagged {
iData.tags = append(iData.tags, refTagged)
}
}
}
policyContext, err := getPolicyContext(sys)
if err != nil {
return err
}
defer func() {
if err := policyContext.Destroy(); err != nil {
logrus.Errorf("failed to destroy policy context: %q", err)
}
}()
// Now copy the images one-by-one.
for _, id := range imageQueue {
dest, err := archWriter.NewReference(nil)
if err != nil {
return err
}
img := imageMap[id]
copyOptions := getCopyOptions(sys, writer, nil, nil, SigningOptions{RemoveSignatures: removeSignatures}, "", img.tags)
copyOptions.DestinationCtx.SystemRegistriesConfPath = registries.SystemRegistriesConfPath()
// For copying, we need a source reference that we can create
// from the image.
src, err := is.Transport.NewStoreReference(img.imageruntime.store, nil, id)
if err != nil {
return errors.Wrapf(err, "error getting source imageReference for %q", img.InputName)
}
_, err = cp.Image(ctx, policyContext, dest, src, copyOptions)
if err != nil {
return err
}
}
return nil
}
// LoadAllImagesFromDockerArchive loads all images from the docker archive that
// fileName points to.
func (ir *Runtime) LoadAllImagesFromDockerArchive(ctx context.Context, fileName string, signaturePolicyPath string, writer io.Writer) ([]*Image, error) {
if signaturePolicyPath == "" {
signaturePolicyPath = ir.SignaturePolicyPath
}
sc := GetSystemContext(signaturePolicyPath, "", false)
reader, err := archive.NewReader(sc, fileName)
if err != nil {
return nil, err
}
defer func() {
if err := reader.Close(); err != nil {
logrus.Errorf(err.Error())
}
}()
refLists, err := reader.List()
if err != nil {
return nil, err
}
refPairs := []pullRefPair{}
for _, refList := range refLists {
for _, ref := range refList {
pairs, err := ir.getPullRefPairsFromDockerArchiveReference(ctx, reader, ref, sc)
if err != nil {
return nil, err
}
refPairs = append(refPairs, pairs...)
}
}
goal := pullGoal{
pullAllPairs: true,
refPairs: refPairs,
}
defer goal.cleanUp()
imageNames, err := ir.doPullImage(ctx, sc, goal, writer, SigningOptions{}, &DockerRegistryOptions{}, &retry.RetryOptions{}, nil)
if err != nil {
return nil, err
}
newImages := make([]*Image, 0, len(imageNames))
for _, name := range imageNames {
newImage, err := ir.NewFromLocal(name)
if err != nil {
return nil, errors.Wrapf(err, "error retrieving local image after pulling %s", name)
}
newImages = append(newImages, newImage)
}
ir.newImageEvent(events.LoadFromArchive, "")
return newImages, nil
}
// LoadFromArchiveReference creates a new image object for images pulled from a tar archive and the like (podman load)
// This function is needed because it is possible for a tar archive to have multiple tags for one image
func (ir *Runtime) LoadFromArchiveReference(ctx context.Context, srcRef types.ImageReference, signaturePolicyPath string, writer io.Writer) ([]*Image, error) {
if signaturePolicyPath == "" {
signaturePolicyPath = ir.SignaturePolicyPath
}
imageNames, err := ir.pullImageFromReference(ctx, srcRef, writer, "", signaturePolicyPath, SigningOptions{}, &DockerRegistryOptions{}, &retry.RetryOptions{})
if err != nil {
return nil, errors.Wrapf(err, "unable to pull %s", transports.ImageName(srcRef))
}
newImages := make([]*Image, 0, len(imageNames))
for _, name := range imageNames {
newImage, err := ir.NewFromLocal(name)
if err != nil {
return nil, errors.Wrapf(err, "error retrieving local image after pulling %s", name)
}
newImages = append(newImages, newImage)
}
ir.newImageEvent(events.LoadFromArchive, "")
return newImages, nil
}
// Shutdown closes down the storage and require a bool arg as to
// whether it should do so forcibly.
func (ir *Runtime) Shutdown(force bool) error {
_, err := ir.store.Shutdown(force)
return err
}
// GetImagesWithFilters gets images with a series of filters applied
func (ir *Runtime) GetImagesWithFilters(filters []string) ([]*Image, error) {
filterFuncs, err := ir.createFilterFuncs(filters, nil)
if err != nil {
return nil, err
}
images, err := ir.GetImages()
if err != nil {
return nil, err
}
return FilterImages(images, filterFuncs), nil
}
func (i *Image) reloadImage() error {
newImage, err := i.imageruntime.getImage(i.ID())
if err != nil {
return errors.Wrapf(err, "unable to reload image")
}
i.image = newImage
return nil
}
// stringSha256 strips sha256 from user input
func stripSha256(name string) string {
if strings.HasPrefix(name, "sha256:") && len(name) > 7 {
return name[7:]
}
return name
}
// getLocalImage resolves an unknown input describing an image and
// returns an updated input name, and a storage.Image, or an error. It is used by NewFromLocal.
func (ir *Runtime) getLocalImage(inputName string) (string, *storage.Image, error) {
imageError := fmt.Sprintf("unable to find '%s' in local storage", inputName)
if inputName == "" {
return "", nil, errors.Errorf("input name is blank")
}
// Check if the input name has a transport and if so strip it
dest, err := alltransports.ParseImageName(inputName)
if err == nil && dest.DockerReference() != nil {
inputName = dest.DockerReference().String()
}
// Early check for fully-qualified images and (short) IDs.
img, err := ir.store.Image(stripSha256(inputName))
if err == nil {
return inputName, img, nil
}
// Note that it's crucial to first decompose the image and check if
// it's a fully-qualified one or a "short name". The latter requires
// some normalization with search registries and the
// "localhost/prefix".
decomposedImage, err := decompose(inputName)
if err != nil {
// We may have a storage reference. We can't parse it to a
// reference before. Otherwise, we'd normalize "alpine" to
// "docker.io/library/alpine:latest" which would break the
// order in which we should query local images below.
if ref, err := is.Transport.ParseStoreReference(ir.store, inputName); err == nil {
img, err = is.Transport.GetStoreImage(ir.store, ref)
if err == nil {
return inputName, img, nil
}
}
return "", nil, err
}
// The specified image is fully qualified, so it doesn't exist in the
// storage.
if decomposedImage.hasRegistry {
// However ... we may still need to normalize to docker.io:
// `docker.io/foo` -> `docker.io/library/foo`
if ref, err := is.Transport.ParseStoreReference(ir.store, inputName); err == nil {
img, err = is.Transport.GetStoreImage(ir.store, ref)
if err == nil {
return inputName, img, nil
}
}
return "", nil, errors.Wrapf(ErrNoSuchImage, imageError)
}
sys := &types.SystemContext{
SystemRegistriesConfPath: registries.SystemRegistriesConfPath(),
}
candidates, err := shortnames.ResolveLocally(sys, inputName)
if err != nil {
return "", nil, err
}
for _, candidate := range candidates {
img, err := ir.store.Image(candidate.String())
if err == nil {
return candidate.String(), img, nil
}
}
// Backwards compat: normalize to docker.io as some users may very well
// rely on that.
ref, err := is.Transport.ParseStoreReference(ir.store, inputName)
if err == nil {
img, err = is.Transport.GetStoreImage(ir.store, ref)
if err == nil {
return inputName, img, nil
}
}
// Last resort: look at the repotags of all images and try to find a
// match.
images, err := ir.GetImages()
if err != nil {
return "", nil, err
}
decomposedImage, err = decompose(inputName)
if err != nil {
return "", nil, err
}
repoImage, err := findImageInRepotags(decomposedImage, images)
if err == nil {
return inputName, repoImage, nil
}
return "", nil, errors.Wrapf(ErrNoSuchImage, err.Error())
}
// ID returns the image ID as a string
func (i *Image) ID() string {
return i.image.ID
}
// IsReadOnly returns whether the image ID comes from a local store
func (i *Image) IsReadOnly() bool {
return i.image.ReadOnly
}
// Digest returns the image's digest
func (i *Image) Digest() digest.Digest {
return i.image.Digest
}
// Digests returns the image's digests
func (i *Image) Digests() []digest.Digest {
return i.image.Digests
}
// GetManifest returns the image's manifest as a byte array
// and manifest type as a string.
func (i *Image) GetManifest(ctx context.Context, instanceDigest *digest.Digest) ([]byte, string, error) {
imgSrcRef, err := i.toImageSourceRef(ctx)
if err != nil {
return nil, "", err
}
return imgSrcRef.GetManifest(ctx, instanceDigest)
}
// Manifest returns the image's manifest as a byte array
// and manifest type as a string.
func (i *Image) Manifest(ctx context.Context) ([]byte, string, error) {
imgRef, err := i.toImageRef(ctx)
if err != nil {
return nil, "", err
}
return imgRef.Manifest(ctx)
}
// Names returns a string array of names associated with the image, which may be a mixture of tags and digests
func (i *Image) Names() []string {
return i.image.Names
}
// NamesHistory returns a string array of names previously associated with the
// image, which may be a mixture of tags and digests
func (i *Image) NamesHistory() []string {
if len(i.image.Names) > 0 && len(i.image.NamesHistory) > 0 &&
// We compare the latest (time-referenced) tags for equality and skip
// it in the history if they match to not display them twice. We have
// to compare like this, because `i.image.Names` (latest last) gets
// appended on retag, whereas `i.image.NamesHistory` gets prepended
// (latest first)
i.image.Names[len(i.image.Names)-1] == i.image.NamesHistory[0] {
return i.image.NamesHistory[1:]
}
return i.image.NamesHistory
}
// RepoTags returns a string array of repotags associated with the image
func (i *Image) RepoTags() ([]string, error) {
var repoTags []string
for _, name := range i.Names() {
named, err := reference.ParseNormalizedNamed(name)
if err != nil {
return nil, err
}
if tagged, isTagged := named.(reference.NamedTagged); isTagged {
repoTags = append(repoTags, tagged.String())
}
}
return repoTags, nil
}
// RepoDigests returns a string array of repodigests associated with the image
func (i *Image) RepoDigests() ([]string, error) {
var repoDigests []string
added := make(map[string]struct{})
for _, name := range i.Names() {
for _, imageDigest := range append(i.Digests(), i.Digest()) {
if imageDigest == "" {
continue
}
named, err := reference.ParseNormalizedNamed(name)
if err != nil {
return nil, err
}
canonical, err := reference.WithDigest(reference.TrimNamed(named), imageDigest)
if err != nil {
return nil, err
}
if _, alreadyInList := added[canonical.String()]; !alreadyInList {
repoDigests = append(repoDigests, canonical.String())
added[canonical.String()] = struct{}{}
}
}
}
sort.Strings(repoDigests)
return repoDigests, nil
}
// Created returns the time the image was created
func (i *Image) Created() time.Time {
return i.image.Created
}
// TopLayer returns the top layer id as a string
func (i *Image) TopLayer() string {
return i.image.TopLayer
}
// Remove an image; container removal for the image must be done
// outside the context of images
// TODO: the force param does nothing as of now. Need to move container
// handling logic here eventually.
func (i *Image) Remove(ctx context.Context, force bool) error {
parent, err := i.GetParent(ctx)
if err != nil {
return err
}
if _, err := i.imageruntime.store.DeleteImage(i.ID(), true); err != nil {
return err
}
i.newImageEvent(events.Remove)
for parent != nil {
nextParent, err := parent.GetParent(ctx)
if err != nil {
return err
}
children, err := parent.GetChildren(ctx)
if err != nil {
return err
}
// Do not remove if image is a base image and is not untagged, or if
// the image has more children.
if len(children) > 0 || len(parent.Names()) > 0 {
return nil
}
id := parent.ID()
if _, err := i.imageruntime.store.DeleteImage(id, true); err != nil {
logrus.Debugf("unable to remove intermediate image %q: %v", id, err)
} else {
fmt.Println(id)
}
parent = nextParent
}
return nil
}
// getImage retrieves an image matching the given name or hash from system
// storage
// If no matching image can be found, an error is returned
func (ir *Runtime) getImage(image string) (*storage.Image, error) {
var img *storage.Image
ref, err := is.Transport.ParseStoreReference(ir.store, image)
if err == nil {
img, err = is.Transport.GetStoreImage(ir.store, ref)
}
if err != nil {
img2, err2 := ir.store.Image(image)
if err2 != nil {
if ref == nil {
return nil, errors.Wrapf(err, "error parsing reference to image %q", image)
}
return nil, errors.Wrapf(err, "unable to locate image %q", image)
}
img = img2
}
return img, nil
}
func (ir *Runtime) ImageNames(id string) ([]string, error) {
myImage, err := ir.getImage(id)
if err != nil {
return nil, errors.Wrapf(err, "error getting image %s ", id)
}
return myImage.Names, nil
}
// GetImages retrieves all images present in storage
func (ir *Runtime) GetImages() ([]*Image, error) {
return ir.getImages(false)
}
// GetRWImages retrieves all read/write images present in storage
func (ir *Runtime) GetRWImages() ([]*Image, error) {
return ir.getImages(true)
}
// getImages retrieves all images present in storage
func (ir *Runtime) getImages(rwOnly bool) ([]*Image, error) {
images, err := ir.store.Images()
if err != nil {
return nil, err
}
newImages := []*Image{}
for _, i := range images {
if rwOnly && i.ReadOnly {
continue
}
// iterating over these, be careful to not iterate on the literal
// pointer.
image := i
img := ir.newFromStorage(&image)
newImages = append(newImages, img)
}
return newImages, nil
}
// getImageDigest creates an image object and uses the hex value of the digest as the image ID
// for parsing the store reference
func getImageDigest(ctx context.Context, src types.ImageReference, sc *types.SystemContext) (string, error) {
newImg, err := src.NewImage(ctx, sc)
if err != nil {
return "", err
}
defer func() {
if err := newImg.Close(); err != nil {
logrus.Errorf("failed to close image: %q", err)
}
}()
imageDigest := newImg.ConfigInfo().Digest
if err = imageDigest.Validate(); err != nil {
return "", errors.Wrapf(err, "error getting config info")
}
return "@" + imageDigest.Hex(), nil
}
// NormalizedTag returns the canonical version of tag for use in Image.Names()
func NormalizedTag(tag string) (reference.Named, error) {
decomposedTag, err := decompose(tag)
if err != nil {
return nil, err
}
// If the input doesn't specify a registry, set the registry to localhost
var ref reference.Named
if !decomposedTag.hasRegistry {
ref, err = decomposedTag.referenceWithRegistry(DefaultLocalRegistry)
if err != nil {
return nil, err
}
} else {
ref, err = decomposedTag.normalizedReference()
if err != nil {
return nil, err
}
}
// If the input does not have a tag, we need to add one (latest)
ref = reference.TagNameOnly(ref)
return ref, nil
}
// TagImage adds a tag to the given image
func (i *Image) TagImage(tag string) error {
if err := i.reloadImage(); err != nil {
return err
}
ref, err := NormalizedTag(tag)
if err != nil {
return err
}
tags := i.Names()
if util.StringInSlice(ref.String(), tags) {
return nil
}
tags = append(tags, ref.String())
if err := i.imageruntime.store.SetNames(i.ID(), tags); err != nil {
return err
}
if err := i.reloadImage(); err != nil {
return err
}
i.newImageEvent(events.Tag)
return nil
}
// UntagImage removes the specified tag from the image.
// If the tag does not exist, ErrNoSuchTag is returned.
func (i *Image) UntagImage(tag string) error {
if err := i.reloadImage(); err != nil {
return err
}
// Normalize the tag as we do with TagImage.
ref, err := NormalizedTag(tag)
if err != nil {
return err
}
tag = ref.String()
var newTags []string
tags := i.Names()
if !util.StringInSlice(tag, tags) {
return errors.Wrapf(ErrNoSuchTag, "%q", tag)
}
for _, t := range tags {
if tag != t {
newTags = append(newTags, t)
}
}
if err := i.imageruntime.store.SetNames(i.ID(), newTags); err != nil {
return err
}
if err := i.reloadImage(); err != nil {
return err
}
i.newImageEvent(events.Untag)
return nil
}
// PushImageToHeuristicDestination pushes the given image to "destination", which is heuristically parsed.
// Use PushImageToReference if the destination is known precisely.
func (i *Image) PushImageToHeuristicDestination(ctx context.Context, destination, manifestMIMEType, authFile, digestFile, signaturePolicyPath string, writer io.Writer, forceCompress bool, signingOptions SigningOptions, dockerRegistryOptions *DockerRegistryOptions, additionalDockerArchiveTags []reference.NamedTagged) error {
if destination == "" {
return errors.Wrapf(syscall.EINVAL, "destination image name must be specified")
}
// Get the destination Image Reference
dest, err := alltransports.ParseImageName(destination)
if err != nil {
if hasTransport(destination) {
return errors.Wrapf(err, "error getting destination imageReference for %q", destination)
}
// Try adding the images default transport
destination2 := DefaultTransport + destination
dest, err = alltransports.ParseImageName(destination2)
if err != nil {
return err
}
}
return i.PushImageToReference(ctx, dest, manifestMIMEType, authFile, digestFile, signaturePolicyPath, writer, forceCompress, signingOptions, dockerRegistryOptions, additionalDockerArchiveTags)
}
// PushImageToReference pushes the given image to a location described by the given path
func (i *Image) PushImageToReference(ctx context.Context, dest types.ImageReference, manifestMIMEType, authFile, digestFile, signaturePolicyPath string, writer io.Writer, forceCompress bool, signingOptions SigningOptions, dockerRegistryOptions *DockerRegistryOptions, additionalDockerArchiveTags []reference.NamedTagged) error {
sc := GetSystemContext(signaturePolicyPath, authFile, forceCompress)
sc.BlobInfoCacheDir = filepath.Join(i.imageruntime.store.GraphRoot(), "cache")
policyContext, err := getPolicyContext(sc)
if err != nil {
return err
}
defer func() {
if err := policyContext.Destroy(); err != nil {
logrus.Errorf("failed to destroy policy context: %q", err)
}
}()
// Look up the source image, expecting it to be in local storage
src, err := is.Transport.ParseStoreReference(i.imageruntime.store, i.ID())
if err != nil {
return errors.Wrapf(err, "error getting source imageReference for %q", i.InputName)
}
copyOptions := getCopyOptions(sc, writer, nil, dockerRegistryOptions, signingOptions, manifestMIMEType, additionalDockerArchiveTags)
copyOptions.DestinationCtx.SystemRegistriesConfPath = registries.SystemRegistriesConfPath() // FIXME: Set this more globally. Probably no reason not to have it in every types.SystemContext, and to compute the value just once in one place.
// Copy the image to the remote destination
manifestBytes, err := cp.Image(ctx, policyContext, dest, src, copyOptions)
if err != nil {
return errors.Wrapf(err, "error copying image to the remote destination")
}
digest, err := manifest.Digest(manifestBytes)
if err != nil {
return errors.Wrapf(err, "error computing digest of manifest of new image %q", transports.ImageName(dest))
}
logrus.Debugf("Successfully pushed %s with digest %s", transports.ImageName(dest), digest.String())
if digestFile != "" {
if err = ioutil.WriteFile(digestFile, []byte(digest.String()), 0644); err != nil {
return errors.Wrapf(err, "failed to write digest to file %q", digestFile)
}
}
i.newImageEvent(events.Push)
return nil
}
// MatchesID returns a bool based on if the input id
// matches the image's id
// TODO: This isn't used anywhere, so remove it
func (i *Image) MatchesID(id string) bool {
return strings.HasPrefix(i.ID(), id)
}
// ToImageRef returns an image reference type from an image
// TODO: Hopefully we can remove this exported function for mheon
func (i *Image) ToImageRef(ctx context.Context) (types.Image, error) {
return i.toImageRef(ctx)
}
// toImageSourceRef returns an ImageSource Reference type from an image
func (i *Image) toImageSourceRef(ctx context.Context) (types.ImageSource, error) {
if i == nil {
return nil, errors.Errorf("cannot convert nil image to image source reference")
}
if i.imgSrcRef == nil {
ref, err := is.Transport.ParseStoreReference(i.imageruntime.store, "@"+i.ID())
if err != nil {
return nil, errors.Wrapf(err, "error parsing reference to image %q", i.ID())
}
imgSrcRef, err := ref.NewImageSource(ctx, nil)
if err != nil {
return nil, errors.Wrapf(err, "error reading image %q as image source", i.ID())
}
i.imgSrcRef = imgSrcRef
}
return i.imgSrcRef, nil
}
//Size returns the size of the image
func (i *Image) Size(ctx context.Context) (*uint64, error) {
sum, err := i.imageruntime.store.ImageSize(i.ID())
if err == nil && sum >= 0 {
usum := uint64(sum)
return &usum, nil
}
return nil, errors.Wrap(err, "unable to determine size")
}
// toImageRef returns an Image Reference type from an image
func (i *Image) toImageRef(ctx context.Context) (types.Image, error) {
if i == nil {
return nil, errors.Errorf("cannot convert nil image to image reference")
}
imgSrcRef, err := i.toImageSourceRef(ctx)
if err != nil {
return nil, err
}
if i.imgRef == nil {
systemContext := &types.SystemContext{}
unparsedDefaultInstance := image.UnparsedInstance(imgSrcRef, nil)
imgRef, err := image.FromUnparsedImage(ctx, systemContext, unparsedDefaultInstance)
if err != nil {
// check for a "tried-to-treat-a-bare-list-like-a-runnable-image" problem, else
// return info about the not-a-bare-list runnable image part of this storage.Image
if manifestBytes, manifestType, err2 := imgSrcRef.GetManifest(ctx, nil); err2 == nil {
if manifest.MIMETypeIsMultiImage(manifestType) {
if list, err3 := manifest.ListFromBlob(manifestBytes, manifestType); err3 == nil {
switch manifestType {
case ociv1.MediaTypeImageIndex:
err = errors.Wrapf(ErrImageIsBareList, "%q is an image index", i.InputName)
case manifest.DockerV2ListMediaType:
err = errors.Wrapf(ErrImageIsBareList, "%q is a manifest list", i.InputName)
default:
err = errors.Wrapf(ErrImageIsBareList, "%q", i.InputName)
}
for _, instanceDigest := range list.Instances() {
instance := instanceDigest
unparsedInstance := image.UnparsedInstance(imgSrcRef, &instance)
if imgRef2, err4 := image.FromUnparsedImage(ctx, systemContext, unparsedInstance); err4 == nil {
imgRef = imgRef2
err = nil
break
}
}
}
}
}
if err != nil {
return nil, errors.Wrapf(err, "error reading image %q as image", i.ID())
}
}
i.imgRef = imgRef
}
return i.imgRef, nil
}
// DriverData gets the driver data from the store on a layer
func (i *Image) DriverData() (*driver.Data, error) {
return driver.GetDriverData(i.imageruntime.store, i.TopLayer())
}
// Layer returns the image's top layer
func (i *Image) Layer() (*storage.Layer, error) {
return i.imageruntime.store.Layer(i.image.TopLayer)
}
// History contains the history information of an image
type History struct {
ID string `json:"id"`
Created *time.Time `json:"created"`
CreatedBy string `json:"createdBy"`
Size int64 `json:"size"`
Comment string `json:"comment"`
Tags []string `json:"tags"`
}
// History gets the history of an image and the IDs of images that are part of
// its history
func (i *Image) History(ctx context.Context) ([]*History, error) {
img, err := i.toImageRef(ctx)
if err != nil {
if errors.Cause(err) == ErrImageIsBareList {
return nil, nil