|
| 1 | +""" |
| 2 | +Lambda Metadata Service client |
| 3 | +
|
| 4 | +Fetches execution environment metadata from the Lambda Metadata Endpoint, |
| 5 | +with caching for the sandbox lifetime. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import logging |
| 11 | +import os |
| 12 | +import urllib.request |
| 13 | +from dataclasses import dataclass, field |
| 14 | +from json import JSONDecodeError |
| 15 | +from json import loads as json_loads |
| 16 | +from typing import Any |
| 17 | + |
| 18 | +from aws_lambda_powertools.shared.constants import ( |
| 19 | + LAMBDA_INITIALIZATION_TYPE, |
| 20 | + LAMBDA_METADATA_API_ENV, |
| 21 | + LAMBDA_METADATA_TOKEN_ENV, |
| 22 | + METADATA_API_VERSION, |
| 23 | + METADATA_DEFAULT_TIMEOUT_SECS, |
| 24 | + METADATA_PATH, |
| 25 | + POWERTOOLS_DEV_ENV, |
| 26 | +) |
| 27 | +from aws_lambda_powertools.utilities.metadata.exceptions import LambdaMetadataError |
| 28 | + |
| 29 | +logger = logging.getLogger(__name__) |
| 30 | + |
| 31 | +_cache: dict[str, Any] = {} |
| 32 | + |
| 33 | + |
| 34 | +@dataclass(frozen=True) |
| 35 | +class LambdaMetadata: |
| 36 | + """Lambda execution environment metadata returned by the metadata endpoint.""" |
| 37 | + |
| 38 | + availability_zone_id: str | None = None |
| 39 | + """The Availability Zone ID where the function is executing (e.g. ``use1-az1``).""" |
| 40 | + |
| 41 | + _raw: dict[str, Any] = field(default_factory=dict, repr=False) |
| 42 | + """Full raw response for forward-compatibility with future fields.""" |
| 43 | + |
| 44 | + |
| 45 | +def _is_lambda_environment() -> bool: |
| 46 | + """Check whether we are running inside a Lambda execution environment.""" |
| 47 | + return os.environ.get(LAMBDA_INITIALIZATION_TYPE, "") != "" |
| 48 | + |
| 49 | + |
| 50 | +def _is_dev_mode() -> bool: |
| 51 | + """Check whether POWERTOOLS_DEV is enabled.""" |
| 52 | + return os.environ.get(POWERTOOLS_DEV_ENV, "false").strip().lower() in ("true", "1") |
| 53 | + |
| 54 | + |
| 55 | +def _build_metadata(data: dict[str, Any]) -> LambdaMetadata: |
| 56 | + """Build a LambdaMetadata dataclass from the raw endpoint response.""" |
| 57 | + return LambdaMetadata( |
| 58 | + availability_zone_id=data.get("AvailabilityZoneID"), |
| 59 | + _raw=data, |
| 60 | + ) |
| 61 | + |
| 62 | + |
| 63 | +def _fetch_metadata(timeout: float = METADATA_DEFAULT_TIMEOUT_SECS) -> dict[str, Any]: |
| 64 | + """ |
| 65 | + Fetch metadata from the Lambda Metadata Endpoint via HTTP. |
| 66 | +
|
| 67 | + Parameters |
| 68 | + ---------- |
| 69 | + timeout : float |
| 70 | + Request timeout in seconds. |
| 71 | +
|
| 72 | + Returns |
| 73 | + ------- |
| 74 | + dict[str, Any] |
| 75 | + Parsed JSON response from the metadata endpoint. |
| 76 | +
|
| 77 | + Raises |
| 78 | + ------ |
| 79 | + LambdaMetadataError |
| 80 | + If required environment variables are missing, the endpoint returns |
| 81 | + a non-200 status, or the response cannot be parsed. |
| 82 | + """ |
| 83 | + api = os.environ.get(LAMBDA_METADATA_API_ENV) |
| 84 | + token = os.environ.get(LAMBDA_METADATA_TOKEN_ENV) |
| 85 | + |
| 86 | + if not api: |
| 87 | + raise LambdaMetadataError( |
| 88 | + f"Environment variable {LAMBDA_METADATA_API_ENV} is not set. Ensure {LAMBDA_METADATA_API_ENV} is set.", |
| 89 | + ) |
| 90 | + if not token: |
| 91 | + raise LambdaMetadataError( |
| 92 | + f"Environment variable {LAMBDA_METADATA_TOKEN_ENV} is not set. Ensure {LAMBDA_METADATA_TOKEN_ENV} is set.", |
| 93 | + ) |
| 94 | + |
| 95 | + url = f"http://{api}/{METADATA_API_VERSION}{METADATA_PATH}" |
| 96 | + logger.debug("Fetching Lambda metadata from: %s", url) |
| 97 | + |
| 98 | + req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"}) |
| 99 | + |
| 100 | + try: |
| 101 | + with urllib.request.urlopen(req, timeout=timeout) as resp: # nosec B310 |
| 102 | + status = resp.status |
| 103 | + body = resp.read().decode("utf-8") |
| 104 | + except urllib.error.HTTPError as exc: |
| 105 | + raise LambdaMetadataError( |
| 106 | + f"Metadata request failed with status {exc.code}", |
| 107 | + status_code=exc.code, |
| 108 | + ) from exc |
| 109 | + except Exception as exc: |
| 110 | + raise LambdaMetadataError(f"Failed to fetch Lambda metadata: {exc}") from exc |
| 111 | + |
| 112 | + if status != 200: |
| 113 | + raise LambdaMetadataError( |
| 114 | + f"Metadata request failed with status {status}", |
| 115 | + status_code=status, |
| 116 | + ) |
| 117 | + |
| 118 | + try: |
| 119 | + data: dict[str, Any] = json_loads(body) |
| 120 | + except (JSONDecodeError, TypeError) as exc: |
| 121 | + raise LambdaMetadataError(f"Failed to parse metadata response: {exc}") from exc |
| 122 | + |
| 123 | + logger.debug("Lambda metadata response: %s", data) |
| 124 | + return data |
| 125 | + |
| 126 | + |
| 127 | +def get_lambda_metadata(*, timeout: float = METADATA_DEFAULT_TIMEOUT_SECS) -> LambdaMetadata: |
| 128 | + """ |
| 129 | + Retrieve Lambda execution environment metadata. |
| 130 | +
|
| 131 | + Returns cached metadata on subsequent calls. When not running in a Lambda |
| 132 | + environment (local dev, tests) or when ``POWERTOOLS_DEV`` is enabled, |
| 133 | + returns an empty ``LambdaMetadata``. |
| 134 | +
|
| 135 | + Parameters |
| 136 | + ---------- |
| 137 | + timeout : float |
| 138 | + HTTP request timeout in seconds (default 1.0). |
| 139 | +
|
| 140 | + Returns |
| 141 | + ------- |
| 142 | + LambdaMetadata |
| 143 | + Metadata about the current execution environment. |
| 144 | +
|
| 145 | + Raises |
| 146 | + ------ |
| 147 | + LambdaMetadataError |
| 148 | + If the metadata endpoint is unavailable or returns an error. |
| 149 | +
|
| 150 | + Example |
| 151 | + ------- |
| 152 | + >>> from aws_lambda_powertools.utilities.metadata import get_lambda_metadata |
| 153 | + >>> metadata = get_lambda_metadata() |
| 154 | + >>> metadata.availability_zone_id # e.g. "use1-az1" |
| 155 | + """ |
| 156 | + if _is_dev_mode() or not _is_lambda_environment(): |
| 157 | + return LambdaMetadata() |
| 158 | + |
| 159 | + if _cache: |
| 160 | + return _build_metadata(_cache) |
| 161 | + |
| 162 | + data = _fetch_metadata(timeout=timeout) |
| 163 | + _cache.update(data) |
| 164 | + return _build_metadata(_cache) |
| 165 | + |
| 166 | + |
| 167 | +def clear_metadata_cache() -> None: |
| 168 | + """ |
| 169 | + Clear the cached metadata. |
| 170 | +
|
| 171 | + Useful for testing or when you need to force a fresh fetch |
| 172 | + (e.g. after SnapStart restore). |
| 173 | + """ |
| 174 | + _cache.clear() |
0 commit comments