• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2 
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 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #include "tensorflow/core/platform/cloud/gcs_throttle.h"
17 
18 #include <algorithm>
19 
20 namespace tensorflow {
21 
22 namespace {
get_default_env_time()23 EnvTime* get_default_env_time() {
24   static EnvTime* default_env_time = new EnvTime;
25   return default_env_time;
26 }
27 }  // namespace
28 
GcsThrottle(EnvTime * env_time)29 GcsThrottle::GcsThrottle(EnvTime* env_time)
30     : last_updated_secs_(env_time ? env_time->GetOverridableNowSeconds()
31                                   : EnvTime::NowSeconds()),
32       available_tokens_(0),
33       env_time_(env_time ? env_time : get_default_env_time()) {}
34 
AdmitRequest()35 bool GcsThrottle::AdmitRequest() {
36   mutex_lock l(mu_);
37   UpdateState();
38   if (available_tokens_ < config_.tokens_per_request) {
39     return false || !config_.enabled;
40   }
41   available_tokens_ -= config_.tokens_per_request;
42   return true;
43 }
44 
RecordResponse(size_t num_bytes)45 void GcsThrottle::RecordResponse(size_t num_bytes) {
46   mutex_lock l(mu_);
47   UpdateState();
48   available_tokens_ -= request_bytes_to_tokens(num_bytes);
49 }
50 
SetConfig(GcsThrottleConfig config)51 void GcsThrottle::SetConfig(GcsThrottleConfig config) {
52   mutex_lock l(mu_);
53   config_ = config;
54   available_tokens_ = config.initial_tokens;
55   last_updated_secs_ = env_time_->GetOverridableNowSeconds();
56 }
57 
UpdateState()58 void GcsThrottle::UpdateState() {
59   // TODO(b/72643279): Switch to a monotonic clock.
60   int64 now = env_time_->GetOverridableNowSeconds();
61   uint64 delta_secs =
62       std::max(int64{0}, now - static_cast<int64>(last_updated_secs_));
63   available_tokens_ += delta_secs * config_.token_rate;
64   available_tokens_ = std::min(available_tokens_, config_.bucket_size);
65   last_updated_secs_ = now;
66 }
67 
68 }  // namespace tensorflow
69