github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/throttle.go (about)

     1  /*
     2  Copyright 2014 The Kubernetes Authors All rights reserved.
     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 util
    18  
    19  import "github.com/juju/ratelimit"
    20  
    21  type RateLimiter interface {
    22  	// CanAccept returns true if the rate is below the limit, false otherwise
    23  	CanAccept() bool
    24  	// Accept returns once a token becomes available.
    25  	Accept()
    26  	// Stop stops the rate limiter, subsequent calls to CanAccept will return false
    27  	Stop()
    28  }
    29  
    30  type tickRateLimiter struct {
    31  	limiter *ratelimit.Bucket
    32  }
    33  
    34  // NewTokenBucketRateLimiter creates a rate limiter which implements a token bucket approach.
    35  // The rate limiter allows bursts of up to 'burst' to exceed the QPS, while still maintaining a
    36  // smoothed qps rate of 'qps'.
    37  // The bucket is initially filled with 'burst' tokens, and refills at a rate of 'qps'.
    38  // The maximum number of tokens in the bucket is capped at 'burst'.
    39  func NewTokenBucketRateLimiter(qps float32, burst int) RateLimiter {
    40  	limiter := ratelimit.NewBucketWithRate(float64(qps), int64(burst))
    41  	return &tickRateLimiter{limiter}
    42  }
    43  
    44  type fakeRateLimiter struct{}
    45  
    46  func NewFakeRateLimiter() RateLimiter {
    47  	return &fakeRateLimiter{}
    48  }
    49  
    50  func (t *tickRateLimiter) CanAccept() bool {
    51  	return t.limiter.TakeAvailable(1) == 1
    52  }
    53  
    54  // Accept will block until a token becomes available
    55  func (t *tickRateLimiter) Accept() {
    56  	t.limiter.Wait(1)
    57  }
    58  
    59  func (t *tickRateLimiter) Stop() {
    60  }
    61  
    62  func (t *fakeRateLimiter) CanAccept() bool {
    63  	return true
    64  }
    65  
    66  func (t *fakeRateLimiter) Stop() {}
    67  
    68  func (t *fakeRateLimiter) Accept() {}