docker_image.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 nil, err
  58. }
  59. imageInspect, err = ds.client.InspectImageByID(image.Image)
  60. if err != nil {
  61. if libdocker.IsImageNotFoundError(err) {
  62. return &runtimeapi.ImageStatusResponse{}, nil
  63. }
  64. return nil, err
  65. }
  66. }
  67. imageStatus, err := imageInspectToRuntimeAPIImage(imageInspect)
  68. if err != nil {
  69. return nil, err
  70. }
  71. res := runtimeapi.ImageStatusResponse{Image: imageStatus}
  72. if r.GetVerbose() {
  73. res.Info = imageInspect.Config.Labels
  74. }
  75. return &res, nil
  76. }
  77. // PullImage pulls an image with authentication config.
  78. func (ds *dockerService) PullImage(_ context.Context, r *runtimeapi.PullImageRequest) (*runtimeapi.PullImageResponse, error) {
  79. image := r.GetImage()
  80. auth := r.GetAuth()
  81. authConfig := dockertypes.AuthConfig{}
  82. if auth != nil {
  83. authConfig.Username = auth.Username
  84. authConfig.Password = auth.Password
  85. authConfig.ServerAddress = auth.ServerAddress
  86. authConfig.IdentityToken = auth.IdentityToken
  87. authConfig.RegistryToken = auth.RegistryToken
  88. }
  89. err := ds.client.PullImage(image.Image,
  90. authConfig,
  91. dockertypes.ImagePullOptions{},
  92. )
  93. if err != nil {
  94. return nil, filterHTTPError(err, image.Image)
  95. }
  96. imageRef, err := getImageRef(ds.client, image.Image)
  97. if err != nil {
  98. return nil, err
  99. }
  100. return &runtimeapi.PullImageResponse{ImageRef: imageRef}, nil
  101. }
  102. // RemoveImage removes the image.
  103. func (ds *dockerService) RemoveImage(_ context.Context, r *runtimeapi.RemoveImageRequest) (*runtimeapi.RemoveImageResponse, error) {
  104. image := r.GetImage()
  105. // If the image has multiple tags, we need to remove all the tags
  106. // TODO: We assume image.Image is image ID here, which is true in the current implementation
  107. // of kubelet, but we should still clarify this in CRI.
  108. imageInspect, err := ds.client.InspectImageByID(image.Image)
  109. // dockerclient.InspectImageByID doesn't work with digest and repoTags,
  110. // it is safe to continue removing it since there is another check below.
  111. if err != nil && !libdocker.IsImageNotFoundError(err) {
  112. return nil, err
  113. }
  114. if imageInspect == nil {
  115. // image is nil, assuming it doesn't exist.
  116. return &runtimeapi.RemoveImageResponse{}, nil
  117. }
  118. // An image can have different numbers of RepoTags and RepoDigests.
  119. // Iterating over both of them plus the image ID ensures the image really got removed.
  120. // It also prevents images from being deleted, which actually are deletable using this approach.
  121. var images []string
  122. images = append(images, imageInspect.RepoTags...)
  123. images = append(images, imageInspect.RepoDigests...)
  124. images = append(images, image.Image)
  125. for _, image := range images {
  126. if _, err := ds.client.RemoveImage(image, dockertypes.ImageRemoveOptions{PruneChildren: true}); err != nil && !libdocker.IsImageNotFoundError(err) {
  127. return nil, err
  128. }
  129. }
  130. return &runtimeapi.RemoveImageResponse{}, nil
  131. }
  132. // getImageRef returns the image digest if exists, or else returns the image ID.
  133. func getImageRef(client libdocker.Interface, image string) (string, error) {
  134. img, err := client.InspectImageByRef(image)
  135. if err != nil {
  136. return "", err
  137. }
  138. if img == nil {
  139. return "", fmt.Errorf("unable to inspect image %s", image)
  140. }
  141. // Returns the digest if it exist.
  142. if len(img.RepoDigests) > 0 {
  143. return img.RepoDigests[0], nil
  144. }
  145. return img.ID, nil
  146. }
  147. func filterHTTPError(err error, image string) error {
  148. // docker/docker/pull/11314 prints detailed error info for docker pull.
  149. // When it hits 502, it returns a verbose html output including an inline svg,
  150. // which makes the output of kubectl get pods much harder to parse.
  151. // Here converts such verbose output to a concise one.
  152. jerr, ok := err.(*jsonmessage.JSONError)
  153. if ok && (jerr.Code == http.StatusBadGateway ||
  154. jerr.Code == http.StatusServiceUnavailable ||
  155. jerr.Code == http.StatusGatewayTimeout) {
  156. return fmt.Errorf("RegistryUnavailable: %v", err)
  157. }
  158. return err
  159. }