k8s.io/kubernetes@v1.29.3/pkg/kubelet/apis/grpc/ratelimit.go (about) 1 /* 2 Copyright 2023 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 grpc 18 19 import ( 20 "context" 21 22 gotimerate "golang.org/x/time/rate" 23 "k8s.io/klog/v2" 24 25 "google.golang.org/grpc" 26 "google.golang.org/grpc/codes" 27 "google.golang.org/grpc/status" 28 ) 29 30 var ( 31 ErrorLimitExceeded = status.Error(codes.ResourceExhausted, "rejected by rate limit") 32 ) 33 34 // Limiter defines the interface to perform request rate limiting, 35 // based on the interface exposed by https://pkg.go.dev/golang.org/x/time/rate#Limiter 36 type Limiter interface { 37 // Allow reports whether an event may happen now. 38 Allow() bool 39 } 40 41 // LimiterUnaryServerInterceptor returns a new unary server interceptors that performs request rate limiting. 42 func LimiterUnaryServerInterceptor(limiter Limiter) grpc.UnaryServerInterceptor { 43 return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { 44 if !limiter.Allow() { 45 return nil, ErrorLimitExceeded 46 } 47 return handler(ctx, req) 48 } 49 } 50 51 // WithRateLimiter creates new rate limiter with unary interceptor. 52 func WithRateLimiter(serviceName string, qps, burstTokens int32) grpc.ServerOption { 53 qpsVal := gotimerate.Limit(qps) 54 burstVal := int(burstTokens) 55 klog.InfoS("Setting rate limiting for endpoint", "service", serviceName, "qps", qpsVal, "burstTokens", burstVal) 56 return grpc.UnaryInterceptor(LimiterUnaryServerInterceptor(gotimerate.NewLimiter(qpsVal, burstVal))) 57 }