helpers.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. "k8s.io/api/core/v1"
  17. "k8s.io/client-go/util/flowcontrol"
  18. runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
  19. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  20. )
  21. // throttleImagePulling wraps kubecontainer.ImageService to throttle image
  22. // pulling based on the given QPS and burst limits. If QPS is zero, defaults
  23. // to no throttling.
  24. func throttleImagePulling(imageService kubecontainer.ImageService, qps float32, burst int) kubecontainer.ImageService {
  25. if qps == 0.0 {
  26. return imageService
  27. }
  28. return &throttledImageService{
  29. ImageService: imageService,
  30. limiter: flowcontrol.NewTokenBucketRateLimiter(qps, burst),
  31. }
  32. }
  33. type throttledImageService struct {
  34. kubecontainer.ImageService
  35. limiter flowcontrol.RateLimiter
  36. }
  37. func (ts throttledImageService) PullImage(image kubecontainer.ImageSpec, secrets []v1.Secret, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, error) {
  38. if ts.limiter.TryAccept() {
  39. return ts.ImageService.PullImage(image, secrets, podSandboxConfig)
  40. }
  41. return "", fmt.Errorf("pull QPS exceeded")
  42. }