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 #ifndef TENSORFLOW_CORE_PLATFORM_CLOUD_GCS_DNS_CACHE_H_ 17 #define TENSORFLOW_CORE_PLATFORM_CLOUD_GCS_DNS_CACHE_H_ 18 19 #include <random> 20 21 #include "tensorflow/core/platform/cloud/http_request.h" 22 #include "tensorflow/core/platform/env.h" 23 24 namespace tensorflow { 25 const int64 kDefaultRefreshRateSecs = 60; 26 27 // DnsCache is a userspace DNS cache specialized for the GCS filesystem. 28 // 29 // Some environments have unreliable DNS resolvers. DnsCache ameliorates the 30 // situation by radically reducing the number of DNS requests by performing 31 // 2 DNS queries per minute (by default) on a background thread. Updated cache 32 // entries are used to override curl's DNS resolution processes. 33 class GcsDnsCache { 34 public: 35 // Default no-argument constructor. GcsDnsCache()36 GcsDnsCache() : GcsDnsCache(kDefaultRefreshRateSecs) {} 37 38 // Constructs a GcsDnsCache with the specified refresh rate. GcsDnsCache(int64 refresh_rate_secs)39 GcsDnsCache(int64 refresh_rate_secs) 40 : GcsDnsCache(Env::Default(), refresh_rate_secs) {} 41 42 GcsDnsCache(Env* env, int64 refresh_rate_secs); 43 ~GcsDnsCache()44 ~GcsDnsCache() { 45 mutex_lock l(mu_); 46 cancelled_ = true; 47 cond_var_.notify_one(); 48 } 49 50 // Annotate the given HttpRequest with resolve overrides from the cache. 51 void AnnotateRequest(HttpRequest* request); 52 53 private: 54 static std::vector<string> ResolveName(const string& name); 55 static std::vector<std::vector<string>> ResolveNames( 56 const std::vector<string>& names); 57 void WorkerThread(); 58 59 // Define a friend class for testing. 60 friend class GcsDnsCacheTest; 61 62 mutex mu_; 63 Env* env_; 64 condition_variable cond_var_; 65 std::default_random_engine random_ GUARDED_BY(mu_); 66 bool started_ GUARDED_BY(mu_) = false; 67 bool cancelled_ GUARDED_BY(mu_) = false; 68 std::unique_ptr<Thread> worker_ GUARDED_BY(mu_); // After mutable vars. 69 const int64 refresh_rate_secs_; 70 71 // Entries in this vector correspond to entries in kCachedDomainNames. 72 std::vector<std::vector<string>> addresses_ GUARDED_BY(mu_); 73 }; 74 75 } // namespace tensorflow 76 77 #endif // TENSORFLOW_CORE_PLATFORM_CLOUD_GCS_DNS_CACHE_H_ 78