EcsMetadataFetcher.cc 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright 2009-2017 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 <sstream>
  18. #include <memory>
  19. #include <alibabacloud/core/Url.h>
  20. #include "CurlHttpClient.h"
  21. using namespace AlibabaCloud;
  22. namespace
  23. {
  24. const int DEFAULT_TIMEOUT_IN_MILLISECONDS = 5000;
  25. const char* const METADATA_SERVICE_HOST = "100.100.100.200";
  26. const char* const URL_IN_ECS_METADATA = "/latest/meta-data/ram/security-credentials/";
  27. }
  28. EcsMetadataFetcher::EcsMetadataFetcher()
  29. {
  30. }
  31. EcsMetadataFetcher::~EcsMetadataFetcher()
  32. {
  33. }
  34. std::string EcsMetadataFetcher::roleName()const
  35. {
  36. return roleName_;
  37. }
  38. void EcsMetadataFetcher::setRoleName(const std::string & roleName)
  39. {
  40. roleName_ = roleName;
  41. }
  42. std::string EcsMetadataFetcher::getMetadata()
  43. {
  44. std::stringstream path;
  45. path << URL_IN_ECS_METADATA << roleName_;
  46. Url credentialUrl;
  47. credentialUrl.setHost(METADATA_SERVICE_HOST);
  48. credentialUrl.setPath(path.str());
  49. auto client = std::make_shared<CurlHttpClient>();
  50. HttpRequest request;
  51. request.setUrl(credentialUrl);
  52. auto outcome = client->makeRequest(request);
  53. if (outcome.isSuccess())
  54. return std::string(outcome.result().body(), outcome.result().bodySize());
  55. else
  56. return outcome.error().errorCode();
  57. }