• 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 
GcsThrottle(EnvTime * env_time)22 GcsThrottle::GcsThrottle(EnvTime* env_time)
23     : last_updated_secs_(env_time->NowSeconds()),
24       available_tokens_(0),
25       env_time_(env_time) {}
26 
AdmitRequest()27 bool GcsThrottle::AdmitRequest() {
28   mutex_lock l(mu_);
29   UpdateState();
30   if (available_tokens_ < config_.tokens_per_request) {
31     return false || !config_.enabled;
32   }
33   available_tokens_ -= config_.tokens_per_request;
34   return true;
35 }
36 
RecordResponse(size_t num_bytes)37 void GcsThrottle::RecordResponse(size_t num_bytes) {
38   mutex_lock l(mu_);
39   UpdateState();
40   available_tokens_ -= request_bytes_to_tokens(num_bytes);
41 }
42 
SetConfig(GcsThrottleConfig config)43 void GcsThrottle::SetConfig(GcsThrottleConfig config) {
44   mutex_lock l(mu_);
45   config_ = config;
46   available_tokens_ = config.initial_tokens;
47   last_updated_secs_ = env_time_->NowSeconds();
48 }
49 
UpdateState()50 void GcsThrottle::UpdateState() {
51   // TODO(b/72643279): Switch to a monotonic clock.
52   int64 now = env_time_->NowSeconds();
53   uint64 delta_secs =
54       std::max(int64{0}, now - static_cast<int64>(last_updated_secs_));
55   available_tokens_ += delta_secs * config_.token_rate;
56   available_tokens_ = std::min(available_tokens_, config_.bucket_size);
57   last_updated_secs_ = now;
58 }
59 
60 }  // namespace tensorflow
61