image_manager.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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 images
  14. import (
  15. "fmt"
  16. dockerref "github.com/docker/distribution/reference"
  17. v1 "k8s.io/api/core/v1"
  18. "k8s.io/client-go/tools/record"
  19. "k8s.io/client-go/util/flowcontrol"
  20. "k8s.io/klog"
  21. runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
  22. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  23. "k8s.io/kubernetes/pkg/kubelet/events"
  24. "k8s.io/kubernetes/pkg/util/parsers"
  25. )
  26. // imageManager provides the functionalities for image pulling.
  27. type imageManager struct {
  28. recorder record.EventRecorder
  29. imageService kubecontainer.ImageService
  30. backOff *flowcontrol.Backoff
  31. // It will check the presence of the image, and report the 'image pulling', image pulled' events correspondingly.
  32. puller imagePuller
  33. }
  34. var _ ImageManager = &imageManager{}
  35. // NewImageManager instantiates a new ImageManager object.
  36. func NewImageManager(recorder record.EventRecorder, imageService kubecontainer.ImageService, imageBackOff *flowcontrol.Backoff, serialized bool, qps float32, burst int) ImageManager {
  37. imageService = throttleImagePulling(imageService, qps, burst)
  38. var puller imagePuller
  39. if serialized {
  40. puller = newSerialImagePuller(imageService)
  41. } else {
  42. puller = newParallelImagePuller(imageService)
  43. }
  44. return &imageManager{
  45. recorder: recorder,
  46. imageService: imageService,
  47. backOff: imageBackOff,
  48. puller: puller,
  49. }
  50. }
  51. // shouldPullImage returns whether we should pull an image according to
  52. // the presence and pull policy of the image.
  53. func shouldPullImage(container *v1.Container, imagePresent bool) bool {
  54. if container.ImagePullPolicy == v1.PullNever {
  55. return false
  56. }
  57. if container.ImagePullPolicy == v1.PullAlways ||
  58. (container.ImagePullPolicy == v1.PullIfNotPresent && (!imagePresent)) {
  59. return true
  60. }
  61. return false
  62. }
  63. // records an event using ref, event msg. log to glog using prefix, msg, logFn
  64. func (m *imageManager) logIt(ref *v1.ObjectReference, eventtype, event, prefix, msg string, logFn func(args ...interface{})) {
  65. if ref != nil {
  66. m.recorder.Event(ref, eventtype, event, msg)
  67. } else {
  68. logFn(fmt.Sprint(prefix, " ", msg))
  69. }
  70. }
  71. // EnsureImageExists pulls the image for the specified pod and container, and returns
  72. // (imageRef, error message, error).
  73. func (m *imageManager) EnsureImageExists(pod *v1.Pod, container *v1.Container, pullSecrets []v1.Secret, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, string, error) {
  74. logPrefix := fmt.Sprintf("%s/%s", pod.Name, container.Image)
  75. ref, err := kubecontainer.GenerateContainerRef(pod, container)
  76. if err != nil {
  77. klog.Errorf("Couldn't make a ref to pod %v, container %v: '%v'", pod.Name, container.Name, err)
  78. }
  79. // If the image contains no tag or digest, a default tag should be applied.
  80. image, err := applyDefaultImageTag(container.Image)
  81. if err != nil {
  82. msg := fmt.Sprintf("Failed to apply default image tag %q: %v", container.Image, err)
  83. m.logIt(ref, v1.EventTypeWarning, events.FailedToInspectImage, logPrefix, msg, klog.Warning)
  84. return "", msg, ErrInvalidImageName
  85. }
  86. spec := kubecontainer.ImageSpec{Image: image}
  87. imageRef, err := m.imageService.GetImageRef(spec)
  88. if err != nil {
  89. msg := fmt.Sprintf("Failed to inspect image %q: %v", container.Image, err)
  90. m.logIt(ref, v1.EventTypeWarning, events.FailedToInspectImage, logPrefix, msg, klog.Warning)
  91. return "", msg, ErrImageInspect
  92. }
  93. present := imageRef != ""
  94. if !shouldPullImage(container, present) {
  95. if present {
  96. msg := fmt.Sprintf("Container image %q already present on machine", container.Image)
  97. m.logIt(ref, v1.EventTypeNormal, events.PulledImage, logPrefix, msg, klog.Info)
  98. return imageRef, "", nil
  99. }
  100. msg := fmt.Sprintf("Container image %q is not present with pull policy of Never", container.Image)
  101. m.logIt(ref, v1.EventTypeWarning, events.ErrImageNeverPullPolicy, logPrefix, msg, klog.Warning)
  102. return "", msg, ErrImageNeverPull
  103. }
  104. backOffKey := fmt.Sprintf("%s_%s", pod.UID, container.Image)
  105. if m.backOff.IsInBackOffSinceUpdate(backOffKey, m.backOff.Clock.Now()) {
  106. msg := fmt.Sprintf("Back-off pulling image %q", container.Image)
  107. m.logIt(ref, v1.EventTypeNormal, events.BackOffPullImage, logPrefix, msg, klog.Info)
  108. return "", msg, ErrImagePullBackOff
  109. }
  110. m.logIt(ref, v1.EventTypeNormal, events.PullingImage, logPrefix, fmt.Sprintf("Pulling image %q", container.Image), klog.Info)
  111. pullChan := make(chan pullResult)
  112. m.puller.pullImage(spec, pullSecrets, pullChan, podSandboxConfig)
  113. imagePullResult := <-pullChan
  114. if imagePullResult.err != nil {
  115. m.logIt(ref, v1.EventTypeWarning, events.FailedToPullImage, logPrefix, fmt.Sprintf("Failed to pull image %q: %v", container.Image, imagePullResult.err), klog.Warning)
  116. m.backOff.Next(backOffKey, m.backOff.Clock.Now())
  117. if imagePullResult.err == ErrRegistryUnavailable {
  118. msg := fmt.Sprintf("image pull failed for %s because the registry is unavailable.", container.Image)
  119. return "", msg, imagePullResult.err
  120. }
  121. return "", imagePullResult.err.Error(), ErrImagePull
  122. }
  123. m.logIt(ref, v1.EventTypeNormal, events.PulledImage, logPrefix, fmt.Sprintf("Successfully pulled image %q", container.Image), klog.Info)
  124. m.backOff.GC()
  125. return imagePullResult.imageRef, "", nil
  126. }
  127. // applyDefaultImageTag parses a docker image string, if it doesn't contain any tag or digest,
  128. // a default tag will be applied.
  129. func applyDefaultImageTag(image string) (string, error) {
  130. named, err := dockerref.ParseNormalizedNamed(image)
  131. if err != nil {
  132. return "", fmt.Errorf("couldn't parse image reference %q: %v", image, err)
  133. }
  134. _, isTagged := named.(dockerref.Tagged)
  135. _, isDigested := named.(dockerref.Digested)
  136. if !isTagged && !isDigested {
  137. // we just concatenate the image name with the default tag here instead
  138. // of using dockerref.WithTag(named, ...) because that would cause the
  139. // image to be fully qualified as docker.io/$name if it's a short name
  140. // (e.g. just busybox). We don't want that to happen to keep the CRI
  141. // agnostic wrt image names and default hostnames.
  142. image = image + ":" + parsers.DefaultImageTag
  143. }
  144. return image, nil
  145. }