k8s.io/kubernetes@v1.29.3/pkg/kubelet/images/helpers.go (about) 1 /* 2 Copyright 2016 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package images 18 19 import ( 20 "context" 21 "fmt" 22 23 v1 "k8s.io/api/core/v1" 24 "k8s.io/client-go/util/flowcontrol" 25 runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1" 26 kubecontainer "k8s.io/kubernetes/pkg/kubelet/container" 27 ) 28 29 // throttleImagePulling wraps kubecontainer.ImageService to throttle image 30 // pulling based on the given QPS and burst limits. If QPS is zero, defaults 31 // to no throttling. 32 func throttleImagePulling(imageService kubecontainer.ImageService, qps float32, burst int) kubecontainer.ImageService { 33 if qps == 0.0 { 34 return imageService 35 } 36 return &throttledImageService{ 37 ImageService: imageService, 38 limiter: flowcontrol.NewTokenBucketRateLimiter(qps, burst), 39 } 40 } 41 42 type throttledImageService struct { 43 kubecontainer.ImageService 44 limiter flowcontrol.RateLimiter 45 } 46 47 func (ts throttledImageService) PullImage(ctx context.Context, image kubecontainer.ImageSpec, secrets []v1.Secret, podSandboxConfig *runtimeapi.PodSandboxConfig) (string, error) { 48 if ts.limiter.TryAccept() { 49 return ts.ImageService.PullImage(ctx, image, secrets, podSandboxConfig) 50 } 51 return "", fmt.Errorf("pull QPS exceeded") 52 }