EcsMetadataFetcher.cc 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright 1999-2019 Alibaba Cloud 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. #include "EcsMetadataFetcher.h"
  17. #include "CurlHttpClient.h"
  18. #include <alibabacloud/core/Url.h>
  19. #include <memory>
  20. #include <sstream>
  21. namespace AlibabaCloud {
  22. EcsMetadataFetcher::EcsMetadataFetcher() {}
  23. EcsMetadataFetcher::~EcsMetadataFetcher() {}
  24. std::string EcsMetadataFetcher::roleName() const { return roleName_; }
  25. void EcsMetadataFetcher::setRoleName(const std::string &roleName) {
  26. roleName_ = roleName;
  27. }
  28. std::string EcsMetadataFetcher::getMetadata() {
  29. return getMetadata(METADATA_SERVICE_HOST, URL_IN_ECS_METADATA);
  30. }
  31. std::string EcsMetadataFetcher::getMetadata(const std::string host,
  32. const std::string in_path) {
  33. std::stringstream path;
  34. path << in_path << roleName_;
  35. Url credentialUrl;
  36. credentialUrl.setHost(host);
  37. credentialUrl.setPath(path.str());
  38. auto client = std::make_shared<CurlHttpClient>();
  39. HttpRequest request;
  40. request.setUrl(credentialUrl);
  41. auto outcome = client->makeRequest(request);
  42. if (outcome.isSuccess())
  43. return std::string(outcome.result().body(), outcome.result().bodySize());
  44. else
  45. return outcome.error().errorCode();
  46. }
  47. } // namespace AlibabaCloud