1 /* Copyright 2018 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/compute_engine_metadata_client.h"
17
18 #include <utility>
19 #include "tensorflow/core/platform/cloud/curl_http_request.h"
20
21 namespace tensorflow {
22
23 namespace {
24
25 // The URL to retrieve metadata when running in Google Compute Engine.
26 constexpr char kGceMetadataBaseUrl[] = "http://metadata/computeMetadata/v1/";
27
28 } // namespace
29
ComputeEngineMetadataClient(std::shared_ptr<HttpRequest::Factory> http_request_factory,const RetryConfig & config)30 ComputeEngineMetadataClient::ComputeEngineMetadataClient(
31 std::shared_ptr<HttpRequest::Factory> http_request_factory,
32 const RetryConfig& config)
33 : http_request_factory_(std::move(http_request_factory)),
34 retry_config_(config) {}
35
GetMetadata(const string & path,std::vector<char> * response_buffer)36 Status ComputeEngineMetadataClient::GetMetadata(
37 const string& path, std::vector<char>* response_buffer) {
38 const auto get_metadata_from_gce = [path, response_buffer, this]() {
39 std::unique_ptr<HttpRequest> request(http_request_factory_->Create());
40 request->SetUri(kGceMetadataBaseUrl + path);
41 request->AddHeader("Metadata-Flavor", "Google");
42 request->SetResultBuffer(response_buffer);
43 TF_RETURN_IF_ERROR(request->Send());
44 return Status::OK();
45 };
46
47 return RetryingUtils::CallWithRetries(get_metadata_from_gce, retry_config_);
48 }
49
50 } // namespace tensorflow
51