_metadata.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. # Copyright 2016 Google LLC
  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. """Provides helper methods for talking to the Compute Engine metadata server.
  15. See https://cloud.google.com/compute/docs/metadata for more details.
  16. """
  17. import datetime
  18. import http.client as http_client
  19. import json
  20. import logging
  21. import os
  22. from urllib.parse import urljoin
  23. from google.auth import _helpers
  24. from google.auth import environment_vars
  25. from google.auth import exceptions
  26. from google.auth import metrics
  27. from google.auth import transport
  28. from google.auth._exponential_backoff import ExponentialBackoff
  29. _LOGGER = logging.getLogger(__name__)
  30. # Environment variable GCE_METADATA_HOST is originally named
  31. # GCE_METADATA_ROOT. For compatibility reasons, here it checks
  32. # the new variable first; if not set, the system falls back
  33. # to the old variable.
  34. _GCE_METADATA_HOST = os.getenv(environment_vars.GCE_METADATA_HOST, None)
  35. if not _GCE_METADATA_HOST:
  36. _GCE_METADATA_HOST = os.getenv(
  37. environment_vars.GCE_METADATA_ROOT, "metadata.google.internal"
  38. )
  39. _METADATA_ROOT = "http://{}/computeMetadata/v1/".format(_GCE_METADATA_HOST)
  40. # This is used to ping the metadata server, it avoids the cost of a DNS
  41. # lookup.
  42. _METADATA_IP_ROOT = "http://{}".format(
  43. os.getenv(environment_vars.GCE_METADATA_IP, "169.254.169.254")
  44. )
  45. _METADATA_FLAVOR_HEADER = "metadata-flavor"
  46. _METADATA_FLAVOR_VALUE = "Google"
  47. _METADATA_HEADERS = {_METADATA_FLAVOR_HEADER: _METADATA_FLAVOR_VALUE}
  48. # Timeout in seconds to wait for the GCE metadata server when detecting the
  49. # GCE environment.
  50. try:
  51. _METADATA_DEFAULT_TIMEOUT = int(os.getenv("GCE_METADATA_TIMEOUT", 3))
  52. except ValueError: # pragma: NO COVER
  53. _METADATA_DEFAULT_TIMEOUT = 3
  54. # Detect GCE Residency
  55. _GOOGLE = "Google"
  56. _GCE_PRODUCT_NAME_FILE = "/sys/class/dmi/id/product_name"
  57. def is_on_gce(request):
  58. """Checks to see if the code runs on Google Compute Engine
  59. Args:
  60. request (google.auth.transport.Request): A callable used to make
  61. HTTP requests.
  62. Returns:
  63. bool: True if the code runs on Google Compute Engine, False otherwise.
  64. """
  65. if ping(request):
  66. return True
  67. if os.name == "nt":
  68. # TODO: implement GCE residency detection on Windows
  69. return False
  70. # Detect GCE residency on Linux
  71. return detect_gce_residency_linux()
  72. def detect_gce_residency_linux():
  73. """Detect Google Compute Engine residency by smbios check on Linux
  74. Returns:
  75. bool: True if the GCE product name file is detected, False otherwise.
  76. """
  77. try:
  78. with open(_GCE_PRODUCT_NAME_FILE, "r") as file_obj:
  79. content = file_obj.read().strip()
  80. except Exception:
  81. return False
  82. return content.startswith(_GOOGLE)
  83. def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT, retry_count=3):
  84. """Checks to see if the metadata server is available.
  85. Args:
  86. request (google.auth.transport.Request): A callable used to make
  87. HTTP requests.
  88. timeout (int): How long to wait for the metadata server to respond.
  89. retry_count (int): How many times to attempt connecting to metadata
  90. server using above timeout.
  91. Returns:
  92. bool: True if the metadata server is reachable, False otherwise.
  93. """
  94. # NOTE: The explicit ``timeout`` is a workaround. The underlying
  95. # issue is that resolving an unknown host on some networks will take
  96. # 20-30 seconds; making this timeout short fixes the issue, but
  97. # could lead to false negatives in the event that we are on GCE, but
  98. # the metadata resolution was particularly slow. The latter case is
  99. # "unlikely".
  100. headers = _METADATA_HEADERS.copy()
  101. headers[metrics.API_CLIENT_HEADER] = metrics.mds_ping()
  102. backoff = ExponentialBackoff(total_attempts=retry_count)
  103. for attempt in backoff:
  104. try:
  105. response = request(
  106. url=_METADATA_IP_ROOT, method="GET", headers=headers, timeout=timeout
  107. )
  108. metadata_flavor = response.headers.get(_METADATA_FLAVOR_HEADER)
  109. return (
  110. response.status == http_client.OK
  111. and metadata_flavor == _METADATA_FLAVOR_VALUE
  112. )
  113. except exceptions.TransportError as e:
  114. _LOGGER.warning(
  115. "Compute Engine Metadata server unavailable on "
  116. "attempt %s of %s. Reason: %s",
  117. attempt,
  118. retry_count,
  119. e,
  120. )
  121. return False
  122. def get(
  123. request,
  124. path,
  125. root=_METADATA_ROOT,
  126. params=None,
  127. recursive=False,
  128. retry_count=5,
  129. headers=None,
  130. return_none_for_not_found_error=False,
  131. ):
  132. """Fetch a resource from the metadata server.
  133. Args:
  134. request (google.auth.transport.Request): A callable used to make
  135. HTTP requests.
  136. path (str): The resource to retrieve. For example,
  137. ``'instance/service-accounts/default'``.
  138. root (str): The full path to the metadata server root.
  139. params (Optional[Mapping[str, str]]): A mapping of query parameter
  140. keys to values.
  141. recursive (bool): Whether to do a recursive query of metadata. See
  142. https://cloud.google.com/compute/docs/metadata#aggcontents for more
  143. details.
  144. retry_count (int): How many times to attempt connecting to metadata
  145. server using above timeout.
  146. headers (Optional[Mapping[str, str]]): Headers for the request.
  147. return_none_for_not_found_error (Optional[bool]): If True, returns None
  148. for 404 error instead of throwing an exception.
  149. Returns:
  150. Union[Mapping, str]: If the metadata server returns JSON, a mapping of
  151. the decoded JSON is returned. Otherwise, the response content is
  152. returned as a string.
  153. Raises:
  154. google.auth.exceptions.TransportError: if an error occurred while
  155. retrieving metadata.
  156. """
  157. base_url = urljoin(root, path)
  158. query_params = {} if params is None else params
  159. headers_to_use = _METADATA_HEADERS.copy()
  160. if headers:
  161. headers_to_use.update(headers)
  162. if recursive:
  163. query_params["recursive"] = "true"
  164. url = _helpers.update_query(base_url, query_params)
  165. backoff = ExponentialBackoff(total_attempts=retry_count)
  166. for attempt in backoff:
  167. try:
  168. response = request(url=url, method="GET", headers=headers_to_use)
  169. if response.status in transport.DEFAULT_RETRYABLE_STATUS_CODES:
  170. _LOGGER.warning(
  171. "Compute Engine Metadata server unavailable on "
  172. "attempt %s of %s. Response status: %s",
  173. attempt,
  174. retry_count,
  175. response.status,
  176. )
  177. continue
  178. else:
  179. break
  180. except exceptions.TransportError as e:
  181. _LOGGER.warning(
  182. "Compute Engine Metadata server unavailable on "
  183. "attempt %s of %s. Reason: %s",
  184. attempt,
  185. retry_count,
  186. e,
  187. )
  188. else:
  189. raise exceptions.TransportError(
  190. "Failed to retrieve {} from the Google Compute Engine "
  191. "metadata service. Compute Engine Metadata server unavailable".format(url)
  192. )
  193. content = _helpers.from_bytes(response.data)
  194. if response.status == http_client.NOT_FOUND and return_none_for_not_found_error:
  195. return None
  196. if response.status == http_client.OK:
  197. if (
  198. _helpers.parse_content_type(response.headers["content-type"])
  199. == "application/json"
  200. ):
  201. try:
  202. return json.loads(content)
  203. except ValueError as caught_exc:
  204. new_exc = exceptions.TransportError(
  205. "Received invalid JSON from the Google Compute Engine "
  206. "metadata service: {:.20}".format(content)
  207. )
  208. raise new_exc from caught_exc
  209. else:
  210. return content
  211. raise exceptions.TransportError(
  212. "Failed to retrieve {} from the Google Compute Engine "
  213. "metadata service. Status: {} Response:\n{}".format(
  214. url, response.status, response.data
  215. ),
  216. response,
  217. )
  218. def get_project_id(request):
  219. """Get the Google Cloud Project ID from the metadata server.
  220. Args:
  221. request (google.auth.transport.Request): A callable used to make
  222. HTTP requests.
  223. Returns:
  224. str: The project ID
  225. Raises:
  226. google.auth.exceptions.TransportError: if an error occurred while
  227. retrieving metadata.
  228. """
  229. return get(request, "project/project-id")
  230. def get_universe_domain(request):
  231. """Get the universe domain value from the metadata server.
  232. Args:
  233. request (google.auth.transport.Request): A callable used to make
  234. HTTP requests.
  235. Returns:
  236. str: The universe domain value. If the universe domain endpoint is not
  237. not found, return the default value, which is googleapis.com
  238. Raises:
  239. google.auth.exceptions.TransportError: if an error other than
  240. 404 occurs while retrieving metadata.
  241. """
  242. universe_domain = get(
  243. request, "universe/universe-domain", return_none_for_not_found_error=True
  244. )
  245. if not universe_domain:
  246. return "googleapis.com"
  247. return universe_domain
  248. def get_service_account_info(request, service_account="default"):
  249. """Get information about a service account from the metadata server.
  250. Args:
  251. request (google.auth.transport.Request): A callable used to make
  252. HTTP requests.
  253. service_account (str): The string 'default' or a service account email
  254. address. The determines which service account for which to acquire
  255. information.
  256. Returns:
  257. Mapping: The service account's information, for example::
  258. {
  259. 'email': '...',
  260. 'scopes': ['scope', ...],
  261. 'aliases': ['default', '...']
  262. }
  263. Raises:
  264. google.auth.exceptions.TransportError: if an error occurred while
  265. retrieving metadata.
  266. """
  267. path = "instance/service-accounts/{0}/".format(service_account)
  268. # See https://cloud.google.com/compute/docs/metadata#aggcontents
  269. # for more on the use of 'recursive'.
  270. return get(request, path, params={"recursive": "true"})
  271. def get_service_account_token(request, service_account="default", scopes=None):
  272. """Get the OAuth 2.0 access token for a service account.
  273. Args:
  274. request (google.auth.transport.Request): A callable used to make
  275. HTTP requests.
  276. service_account (str): The string 'default' or a service account email
  277. address. The determines which service account for which to acquire
  278. an access token.
  279. scopes (Optional[Union[str, List[str]]]): Optional string or list of
  280. strings with auth scopes.
  281. Returns:
  282. Tuple[str, datetime]: The access token and its expiration.
  283. Raises:
  284. google.auth.exceptions.TransportError: if an error occurred while
  285. retrieving metadata.
  286. """
  287. if scopes:
  288. if not isinstance(scopes, str):
  289. scopes = ",".join(scopes)
  290. params = {"scopes": scopes}
  291. else:
  292. params = None
  293. metrics_header = {
  294. metrics.API_CLIENT_HEADER: metrics.token_request_access_token_mds()
  295. }
  296. path = "instance/service-accounts/{0}/token".format(service_account)
  297. token_json = get(request, path, params=params, headers=metrics_header)
  298. token_expiry = _helpers.utcnow() + datetime.timedelta(
  299. seconds=token_json["expires_in"]
  300. )
  301. return token_json["access_token"], token_expiry