docker_image.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package dockershim
  14. import (
  15. "context"
  16. "fmt"
  17. "net/http"
  18. dockertypes "github.com/docker/docker/api/types"
  19. dockerfilters "github.com/docker/docker/api/types/filters"
  20. "github.com/docker/docker/pkg/jsonmessage"
  21. runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
  22. "k8s.io/klog"
  23. "k8s.io/kubernetes/pkg/kubelet/dockershim/libdocker"
  24. )
  25. // This file implements methods in ImageManagerService.
  26. // ListImages lists existing images.
  27. func (ds *dockerService) ListImages(_ context.Context, r *runtimeapi.ListImagesRequest) (*runtimeapi.ListImagesResponse, error) {
  28. filter := r.GetFilter()
  29. opts := dockertypes.ImageListOptions{}
  30. if filter != nil {
  31. if filter.GetImage().GetImage() != "" {
  32. opts.Filters = dockerfilters.NewArgs()
  33. opts.Filters.Add("reference", filter.GetImage().GetImage())
  34. }
  35. }
  36. images, err := ds.client.ListImages(opts)
  37. if err != nil {
  38. return nil, err
  39. }
  40. result := make([]*runtimeapi.Image, 0, len(images))
  41. for _, i := range images {
  42. apiImage, err := imageToRuntimeAPIImage(&i)
  43. if err != nil {
  44. klog.V(5).Infof("Failed to convert docker API image %+v to runtime API image: %v", i, err)
  45. continue
  46. }
  47. result = append(result, apiImage)
  48. }
  49. return &runtimeapi.ListImagesResponse{Images: result}, nil
  50. }
  51. // ImageStatus returns the status of the image, returns nil if the image doesn't present.
  52. func (ds *dockerService) ImageStatus(_ context.Context, r *runtimeapi.ImageStatusRequest) (*runtimeapi.ImageStatusResponse, error) {
  53. image := r.GetImage()
  54. imageInspect, err := ds.client.InspectImageByRef(image.Image)
  55. if err != nil {
  56. if libdocker.IsImageNotFoundError(err) {
  57. return &runtimeapi.ImageStatusResponse{}, nil
  58. }
  59. return nil, err
  60. }
  61. imageStatus, err := imageInspectToRuntimeAPIImage(imageInspect)
  62. if err != nil {
  63. return nil, err
  64. }
  65. res := runtimeapi.ImageStatusResponse{Image: imageStatus}
  66. if r.GetVerbose() {
  67. res.Info = imageInspect.Config.Labels
  68. }
  69. return &res, nil
  70. }
  71. // PullImage pulls an image with authentication config.
  72. func (ds *dockerService) PullImage(_ context.Context, r *runtimeapi.PullImageRequest) (*runtimeapi.PullImageResponse, error) {
  73. image := r.GetImage()
  74. auth := r.GetAuth()
  75. authConfig := dockertypes.AuthConfig{}
  76. if auth != nil {
  77. authConfig.Username = auth.Username
  78. authConfig.Password = auth.Password
  79. authConfig.ServerAddress = auth.ServerAddress
  80. authConfig.IdentityToken = auth.IdentityToken
  81. authConfig.RegistryToken = auth.RegistryToken
  82. }
  83. err := ds.client.PullImage(image.Image,
  84. authConfig,
  85. dockertypes.ImagePullOptions{},
  86. )
  87. if err != nil {
  88. return nil, filterHTTPError(err, image.Image)
  89. }
  90. imageRef, err := getImageRef(ds.client, image.Image)
  91. if err != nil {
  92. return nil, err
  93. }
  94. return &runtimeapi.PullImageResponse{ImageRef: imageRef}, nil
  95. }
  96. // RemoveImage removes the image.
  97. func (ds *dockerService) RemoveImage(_ context.Context, r *runtimeapi.RemoveImageRequest) (*runtimeapi.RemoveImageResponse, error) {
  98. image := r.GetImage()
  99. // If the image has multiple tags, we need to remove all the tags
  100. // TODO: We assume image.Image is image ID here, which is true in the current implementation
  101. // of kubelet, but we should still clarify this in CRI.
  102. imageInspect, err := ds.client.InspectImageByID(image.Image)
  103. // dockerclient.InspectImageByID doesn't work with digest and repoTags,
  104. // it is safe to continue removing it since there is another check below.
  105. if err != nil && !libdocker.IsImageNotFoundError(err) {
  106. return nil, err
  107. }
  108. if imageInspect == nil {
  109. // image is nil, assuming it doesn't exist.
  110. return &runtimeapi.RemoveImageResponse{}, nil
  111. }
  112. // An image can have different numbers of RepoTags and RepoDigests.
  113. // Iterating over both of them plus the image ID ensures the image really got removed.
  114. // It also prevents images from being deleted, which actually are deletable using this approach.
  115. var images []string
  116. images = append(images, imageInspect.RepoTags...)
  117. images = append(images, imageInspect.RepoDigests...)
  118. images = append(images, image.Image)
  119. for _, image := range images {
  120. if _, err := ds.client.RemoveImage(image, dockertypes.ImageRemoveOptions{PruneChildren: true}); err != nil && !libdocker.IsImageNotFoundError(err) {
  121. return nil, err
  122. }
  123. }
  124. return &runtimeapi.RemoveImageResponse{}, nil
  125. }
  126. // getImageRef returns the image digest if exists, or else returns the image ID.
  127. func getImageRef(client libdocker.Interface, image string) (string, error) {
  128. img, err := client.InspectImageByRef(image)
  129. if err != nil {
  130. return "", err
  131. }
  132. if img == nil {
  133. return "", fmt.Errorf("unable to inspect image %s", image)
  134. }
  135. // Returns the digest if it exist.
  136. if len(img.RepoDigests) > 0 {
  137. return img.RepoDigests[0], nil
  138. }
  139. return img.ID, nil
  140. }
  141. func filterHTTPError(err error, image string) error {
  142. // docker/docker/pull/11314 prints detailed error info for docker pull.
  143. // When it hits 502, it returns a verbose html output including an inline svg,
  144. // which makes the output of kubectl get pods much harder to parse.
  145. // Here converts such verbose output to a concise one.
  146. jerr, ok := err.(*jsonmessage.JSONError)
  147. if ok && (jerr.Code == http.StatusBadGateway ||
  148. jerr.Code == http.StatusServiceUnavailable ||
  149. jerr.Code == http.StatusGatewayTimeout) {
  150. return fmt.Errorf("RegistryUnavailable: %v", err)
  151. }
  152. return err
  153. }