cloud-metadata 1.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cloud_metadata/__init__.py +176 -0
- cloud_metadata/_http.py +103 -0
- cloud_metadata/cli.py +192 -0
- cloud_metadata/detect.py +187 -0
- cloud_metadata/engine.py +333 -0
- cloud_metadata/errors.py +65 -0
- cloud_metadata/functions.py +211 -0
- cloud_metadata/providers/__init__.py +20 -0
- cloud_metadata/providers/_loader.py +260 -0
- cloud_metadata/providers/_spec.py +194 -0
- cloud_metadata/providers/data/alibaba.json +113 -0
- cloud_metadata/providers/data/amazon.json +97 -0
- cloud_metadata/providers/data/google.json +78 -0
- cloud_metadata/providers/data/index.json +9 -0
- cloud_metadata/providers/data/microsoft.json +77 -0
- cloud_metadata/providers/data/oracle.json +73 -0
- cloud_metadata/py.typed +0 -0
- cloud_metadata/registry.py +125 -0
- cloud_metadata-1.1.0.dist-info/METADATA +379 -0
- cloud_metadata-1.1.0.dist-info/RECORD +23 -0
- cloud_metadata-1.1.0.dist-info/WHEEL +4 -0
- cloud_metadata-1.1.0.dist-info/entry_points.txt +3 -0
- cloud_metadata-1.1.0.dist-info/licenses/LICENSE +618 -0
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
# Copyright (c) 2026 SUSE LLC. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# This file is part of cloud-metadata. cloud-metadata provides one command
|
|
4
|
+
# and one Python API that return the same standard instance metadata on every
|
|
5
|
+
# supported public cloud.
|
|
6
|
+
#
|
|
7
|
+
# This program is free software: you can redistribute it and/or modify
|
|
8
|
+
# it under the terms of the GNU General Public License as published by
|
|
9
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
10
|
+
# (at your option) any later version.
|
|
11
|
+
#
|
|
12
|
+
# This program is distributed in the hope that it will be useful,
|
|
13
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
+
# GNU General Public License for more details.
|
|
16
|
+
#
|
|
17
|
+
# You should have received a copy of the GNU General Public License
|
|
18
|
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
19
|
+
|
|
20
|
+
"""One metadata command and API for every public cloud.
|
|
21
|
+
|
|
22
|
+
Example:
|
|
23
|
+
>>> import cloud_metadata as cm
|
|
24
|
+
>>> cm.detect_provider() # doctest: +SKIP
|
|
25
|
+
'amazon'
|
|
26
|
+
>>> cm.get("instance-id") # doctest: +SKIP
|
|
27
|
+
'i-0123456789abcdef0'
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
from cloud_metadata import _http, detect, engine, registry
|
|
31
|
+
from cloud_metadata.errors import (
|
|
32
|
+
CloudMetadataError,
|
|
33
|
+
DocumentNotFound,
|
|
34
|
+
InvalidExpression,
|
|
35
|
+
KeyNotAvailable,
|
|
36
|
+
MetadataUnavailable,
|
|
37
|
+
ProviderNotDetected,
|
|
38
|
+
)
|
|
39
|
+
from cloud_metadata.providers._spec import (
|
|
40
|
+
STANDARD_KEYS,
|
|
41
|
+
Auth,
|
|
42
|
+
Document,
|
|
43
|
+
Probe,
|
|
44
|
+
ProviderSpec,
|
|
45
|
+
)
|
|
46
|
+
from cloud_metadata.registry import register, unregister
|
|
47
|
+
|
|
48
|
+
__version__ = "1.1.0"
|
|
49
|
+
|
|
50
|
+
__all__ = [
|
|
51
|
+
"STANDARD_KEYS",
|
|
52
|
+
"Auth",
|
|
53
|
+
"CloudMetadataError",
|
|
54
|
+
"Document",
|
|
55
|
+
"DocumentNotFound",
|
|
56
|
+
"InvalidExpression",
|
|
57
|
+
"KeyNotAvailable",
|
|
58
|
+
"MetadataUnavailable",
|
|
59
|
+
"Probe",
|
|
60
|
+
"ProviderNotDetected",
|
|
61
|
+
"ProviderSpec",
|
|
62
|
+
"clear_cache",
|
|
63
|
+
"detect_provider",
|
|
64
|
+
"get",
|
|
65
|
+
"keys",
|
|
66
|
+
"providers",
|
|
67
|
+
"query",
|
|
68
|
+
"raw",
|
|
69
|
+
"register",
|
|
70
|
+
"unregister",
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _timeout(timeout: float | None) -> float:
|
|
75
|
+
return _http.DEFAULT_TIMEOUT if timeout is None else timeout
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _spec(provider: str | None, timeout: float | None) -> ProviderSpec:
|
|
79
|
+
"""Return the named provider, or the detected one if ``provider`` is None."""
|
|
80
|
+
if provider is None:
|
|
81
|
+
provider = detect.detect_provider(timeout=_timeout(timeout))
|
|
82
|
+
return registry.get_spec(provider)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def detect_provider(*, timeout: float | None = None) -> str:
|
|
86
|
+
"""Return the name of the cloud provider this process runs on.
|
|
87
|
+
|
|
88
|
+
Raises:
|
|
89
|
+
ProviderNotDetected: If no registered provider matches.
|
|
90
|
+
"""
|
|
91
|
+
return detect.detect_provider(timeout=_timeout(timeout))
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def get(key: str, *, provider: str | None = None, timeout: float | None = None) -> str:
|
|
95
|
+
"""Return the value of a standard key, for example ``"private-ipv4"``.
|
|
96
|
+
|
|
97
|
+
Args:
|
|
98
|
+
key: One of :data:`STANDARD_KEYS`.
|
|
99
|
+
provider: Provider name. Detected automatically if ``None``.
|
|
100
|
+
timeout: Seconds to wait for each request. Defaults to 2.
|
|
101
|
+
|
|
102
|
+
Raises:
|
|
103
|
+
ProviderNotDetected: If the provider is unknown or not detected.
|
|
104
|
+
KeyNotAvailable: If the provider has no value for the key.
|
|
105
|
+
MetadataUnavailable: If the metadata service cannot be reached.
|
|
106
|
+
"""
|
|
107
|
+
spec = _spec(provider, timeout)
|
|
108
|
+
return engine.resolve(spec, key, timeout=_timeout(timeout))
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def query(
|
|
112
|
+
expression: str,
|
|
113
|
+
*,
|
|
114
|
+
document: str | None = None,
|
|
115
|
+
provider: str | None = None,
|
|
116
|
+
timeout: float | None = None,
|
|
117
|
+
) -> object:
|
|
118
|
+
"""Evaluate a JMESPath expression against one of the provider's documents.
|
|
119
|
+
|
|
120
|
+
The document defaults to the provider's primary (first) document. The
|
|
121
|
+
helpers ``basename`` and ``strip_zone_suffix`` are available.
|
|
122
|
+
|
|
123
|
+
Raises:
|
|
124
|
+
ProviderNotDetected: If the provider is unknown or not detected.
|
|
125
|
+
DocumentNotFound: If the provider has no document with that name. It is
|
|
126
|
+
also a ``KeyError``.
|
|
127
|
+
InvalidExpression: If the expression is not valid JMESPath. It is also
|
|
128
|
+
a ``ValueError``.
|
|
129
|
+
MetadataUnavailable: If the metadata service cannot be reached.
|
|
130
|
+
"""
|
|
131
|
+
spec = _spec(provider, timeout)
|
|
132
|
+
return engine.evaluate(spec, expression, document, timeout=_timeout(timeout))
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def raw(
|
|
136
|
+
*,
|
|
137
|
+
document: str | None = None,
|
|
138
|
+
provider: str | None = None,
|
|
139
|
+
timeout: float | None = None,
|
|
140
|
+
) -> object:
|
|
141
|
+
"""Return one of the provider's documents as the provider sends it.
|
|
142
|
+
|
|
143
|
+
A JSON document is returned parsed and a text document as a string. The
|
|
144
|
+
document defaults to the provider's primary (first) document.
|
|
145
|
+
"""
|
|
146
|
+
spec = _spec(provider, timeout)
|
|
147
|
+
return engine.evaluate(spec, None, document, timeout=_timeout(timeout))
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def keys(
|
|
151
|
+
*, provider: str | None = None, timeout: float | None = None
|
|
152
|
+
) -> tuple[str, ...]:
|
|
153
|
+
"""Return the standard keys the provider supports.
|
|
154
|
+
|
|
155
|
+
Standard keys come first, in :data:`STANDARD_KEYS` order, followed by any
|
|
156
|
+
other keys the provider defines. This does not contact the metadata
|
|
157
|
+
service when ``provider`` is given.
|
|
158
|
+
"""
|
|
159
|
+
mapped = _spec(provider, timeout).keys
|
|
160
|
+
standard = tuple(key for key in STANDARD_KEYS if key in mapped)
|
|
161
|
+
return standard + tuple(key for key in mapped if key not in STANDARD_KEYS)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def clear_cache() -> None:
|
|
165
|
+
"""Forget the cached documents, tokens and the detected provider.
|
|
166
|
+
|
|
167
|
+
The next call contacts the metadata service again. Providers that are
|
|
168
|
+
registered or removed clear the caches on their own.
|
|
169
|
+
"""
|
|
170
|
+
engine.clear_cache()
|
|
171
|
+
detect.clear_cache()
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def providers() -> tuple[str, ...]:
|
|
175
|
+
"""Return the names of the registered providers, in registry order."""
|
|
176
|
+
return registry.names()
|
cloud_metadata/_http.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
# Copyright (c) 2026 SUSE LLC. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# This file is part of cloud-metadata. cloud-metadata provides one command
|
|
4
|
+
# and one Python API that return the same standard instance metadata on every
|
|
5
|
+
# supported public cloud.
|
|
6
|
+
#
|
|
7
|
+
# This program is free software: you can redistribute it and/or modify
|
|
8
|
+
# it under the terms of the GNU General Public License as published by
|
|
9
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
10
|
+
# (at your option) any later version.
|
|
11
|
+
#
|
|
12
|
+
# This program is distributed in the hope that it will be useful,
|
|
13
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
+
# GNU General Public License for more details.
|
|
16
|
+
#
|
|
17
|
+
# You should have received a copy of the GNU General Public License
|
|
18
|
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
19
|
+
|
|
20
|
+
"""Small HTTP helper for talking to instance metadata services.
|
|
21
|
+
|
|
22
|
+
Only the ``http`` scheme is used. Metadata services are link-local and do not
|
|
23
|
+
speak TLS.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
import http.client
|
|
27
|
+
import urllib.error
|
|
28
|
+
import urllib.request
|
|
29
|
+
from collections.abc import Mapping
|
|
30
|
+
from typing import NamedTuple
|
|
31
|
+
from urllib.parse import urlsplit
|
|
32
|
+
|
|
33
|
+
from cloud_metadata.errors import MetadataUnavailable
|
|
34
|
+
|
|
35
|
+
DEFAULT_TIMEOUT = 2.0
|
|
36
|
+
|
|
37
|
+
# Metadata services are link-local, so a proxy from the environment
|
|
38
|
+
# (``http_proxy`` and friends) must never be used.
|
|
39
|
+
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Response(NamedTuple):
|
|
43
|
+
"""A successful (2xx) response."""
|
|
44
|
+
|
|
45
|
+
status: int
|
|
46
|
+
body: str
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def check_scheme(url: str) -> None:
|
|
50
|
+
"""Raise ``ValueError`` unless ``url`` is an ``http`` URL."""
|
|
51
|
+
scheme = urlsplit(url).scheme
|
|
52
|
+
if scheme != "http":
|
|
53
|
+
msg = f"only http URLs are allowed, got {url!r}"
|
|
54
|
+
raise ValueError(msg)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def join_url(base_url: str, path: str) -> str:
|
|
58
|
+
"""Join an IMDS base URL and an absolute path.
|
|
59
|
+
|
|
60
|
+
The base URL can use an IPv4 address, an IPv6 address in brackets, or a
|
|
61
|
+
DNS name. A trailing ``/`` on the base URL is ignored.
|
|
62
|
+
"""
|
|
63
|
+
check_scheme(base_url)
|
|
64
|
+
if not path.startswith("/"):
|
|
65
|
+
msg = f"path must start with '/', got {path!r}"
|
|
66
|
+
raise ValueError(msg)
|
|
67
|
+
return base_url.rstrip("/") + path
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def request(
|
|
71
|
+
method: str,
|
|
72
|
+
url: str,
|
|
73
|
+
headers: Mapping[str, str] | None = None,
|
|
74
|
+
timeout: float = DEFAULT_TIMEOUT,
|
|
75
|
+
) -> Response:
|
|
76
|
+
"""Send one request and return the response.
|
|
77
|
+
|
|
78
|
+
Raises:
|
|
79
|
+
ValueError: If ``url`` is not an ``http`` URL.
|
|
80
|
+
MetadataUnavailable: If the service is unreachable, times out, sends an
|
|
81
|
+
undecodable body or answers with an HTTP error. For an HTTP error
|
|
82
|
+
the exception has the status code in ``status``.
|
|
83
|
+
"""
|
|
84
|
+
check_scheme(url)
|
|
85
|
+
# The scheme was checked above, so S310 does not apply.
|
|
86
|
+
req = urllib.request.Request( # noqa: S310
|
|
87
|
+
url, headers=dict(headers or {}), method=method
|
|
88
|
+
)
|
|
89
|
+
try:
|
|
90
|
+
with _OPENER.open(req, timeout=timeout) as resp:
|
|
91
|
+
status = resp.status
|
|
92
|
+
body = resp.read().decode("utf-8")
|
|
93
|
+
except urllib.error.HTTPError as err:
|
|
94
|
+
err.close()
|
|
95
|
+
msg = f"{method} {url} returned HTTP {err.code}"
|
|
96
|
+
raise MetadataUnavailable(msg, status=err.code) from err
|
|
97
|
+
except (urllib.error.URLError, OSError, http.client.HTTPException) as err:
|
|
98
|
+
msg = f"{method} {url} failed: {err}"
|
|
99
|
+
raise MetadataUnavailable(msg) from err
|
|
100
|
+
except UnicodeDecodeError as err:
|
|
101
|
+
msg = f"{method} {url} returned a body that is not UTF-8"
|
|
102
|
+
raise MetadataUnavailable(msg) from err
|
|
103
|
+
return Response(status, body)
|
cloud_metadata/cli.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
# Copyright (c) 2026 SUSE LLC. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# This file is part of cloud-metadata. cloud-metadata provides one command
|
|
4
|
+
# and one Python API that return the same standard instance metadata on every
|
|
5
|
+
# supported public cloud.
|
|
6
|
+
#
|
|
7
|
+
# This program is free software: you can redistribute it and/or modify
|
|
8
|
+
# it under the terms of the GNU General Public License as published by
|
|
9
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
10
|
+
# (at your option) any later version.
|
|
11
|
+
#
|
|
12
|
+
# This program is distributed in the hope that it will be useful,
|
|
13
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
+
# GNU General Public License for more details.
|
|
16
|
+
#
|
|
17
|
+
# You should have received a copy of the GNU General Public License
|
|
18
|
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
19
|
+
|
|
20
|
+
"""The ``cloud-metadata`` command line tool.
|
|
21
|
+
|
|
22
|
+
Values are written to stdout on their own, so the output works in shell
|
|
23
|
+
substitution. Messages go to stderr.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
import argparse
|
|
27
|
+
import json
|
|
28
|
+
import sys
|
|
29
|
+
from collections.abc import Callable, Sequence
|
|
30
|
+
|
|
31
|
+
import cloud_metadata as cm
|
|
32
|
+
from cloud_metadata.errors import (
|
|
33
|
+
CloudMetadataError,
|
|
34
|
+
DocumentNotFound,
|
|
35
|
+
InvalidExpression,
|
|
36
|
+
KeyNotAvailable,
|
|
37
|
+
MetadataUnavailable,
|
|
38
|
+
ProviderNotDetected,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
PROG = "cloud-metadata"
|
|
42
|
+
|
|
43
|
+
EXIT_OK = 0
|
|
44
|
+
EXIT_ERROR = 1
|
|
45
|
+
EXIT_PROVIDER = 2
|
|
46
|
+
EXIT_KEY = 3
|
|
47
|
+
EXIT_IMDS = 4
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def exit_code(error: BaseException) -> int:
|
|
51
|
+
"""Map an exception to the process exit code."""
|
|
52
|
+
# An unknown document and a bad expression are usage errors.
|
|
53
|
+
if isinstance(error, ProviderNotDetected | DocumentNotFound | InvalidExpression):
|
|
54
|
+
return EXIT_PROVIDER
|
|
55
|
+
if isinstance(error, KeyNotAvailable):
|
|
56
|
+
return EXIT_KEY
|
|
57
|
+
if isinstance(error, MetadataUnavailable):
|
|
58
|
+
return EXIT_IMDS
|
|
59
|
+
return EXIT_ERROR
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _provider(args: argparse.Namespace) -> int:
|
|
63
|
+
print(cm.detect_provider(timeout=args.timeout))
|
|
64
|
+
return EXIT_OK
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _keys(args: argparse.Namespace) -> int:
|
|
68
|
+
for key in cm.keys(provider=args.provider, timeout=args.timeout):
|
|
69
|
+
print(key)
|
|
70
|
+
return EXIT_OK
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _get(args: argparse.Namespace) -> int:
|
|
74
|
+
print(cm.get(args.key, provider=args.provider, timeout=args.timeout))
|
|
75
|
+
return EXIT_OK
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _print_value(value: object) -> None:
|
|
79
|
+
"""Print a string as it is and any other value as JSON."""
|
|
80
|
+
if isinstance(value, str):
|
|
81
|
+
print(value)
|
|
82
|
+
else:
|
|
83
|
+
print(json.dumps(value, indent=2))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _query(args: argparse.Namespace) -> int:
|
|
87
|
+
value = cm.query(
|
|
88
|
+
args.expression,
|
|
89
|
+
document=args.document,
|
|
90
|
+
provider=args.provider,
|
|
91
|
+
timeout=args.timeout,
|
|
92
|
+
)
|
|
93
|
+
_print_value(value)
|
|
94
|
+
return EXIT_OK
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _raw(args: argparse.Namespace) -> int:
|
|
98
|
+
value = cm.raw(document=args.document, provider=args.provider, timeout=args.timeout)
|
|
99
|
+
_print_value(value)
|
|
100
|
+
return EXIT_OK
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _positive_float(text: str) -> float:
|
|
104
|
+
try:
|
|
105
|
+
value = float(text)
|
|
106
|
+
except ValueError:
|
|
107
|
+
value = 0.0
|
|
108
|
+
if not value > 0:
|
|
109
|
+
msg = f"expected a number of seconds greater than 0, got {text!r}"
|
|
110
|
+
raise argparse.ArgumentTypeError(msg)
|
|
111
|
+
return value
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _option_parents() -> tuple[argparse.ArgumentParser, argparse.ArgumentParser]:
|
|
115
|
+
"""Return the parsers with only ``--timeout`` and with both options."""
|
|
116
|
+
timeout = argparse.ArgumentParser(add_help=False)
|
|
117
|
+
timeout.add_argument(
|
|
118
|
+
"--timeout",
|
|
119
|
+
type=_positive_float,
|
|
120
|
+
metavar="N",
|
|
121
|
+
help="seconds to wait for each request (default: 2)",
|
|
122
|
+
)
|
|
123
|
+
both = argparse.ArgumentParser(add_help=False, parents=[timeout])
|
|
124
|
+
both.add_argument(
|
|
125
|
+
"--provider",
|
|
126
|
+
metavar="P",
|
|
127
|
+
help="provider name, instead of detecting it (default: detect)",
|
|
128
|
+
)
|
|
129
|
+
return timeout, both
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
133
|
+
"""Build the argument parser."""
|
|
134
|
+
parser = argparse.ArgumentParser(
|
|
135
|
+
prog=PROG,
|
|
136
|
+
description="Print instance metadata in the same way on every public cloud.",
|
|
137
|
+
)
|
|
138
|
+
parser.add_argument(
|
|
139
|
+
"--version",
|
|
140
|
+
action="version",
|
|
141
|
+
version=f"{PROG} {cm.__version__}",
|
|
142
|
+
)
|
|
143
|
+
commands = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
|
|
144
|
+
handlers: dict[str, Callable[[argparse.Namespace], int]] = {
|
|
145
|
+
"get": _get,
|
|
146
|
+
"provider": _provider,
|
|
147
|
+
"keys": _keys,
|
|
148
|
+
"query": _query,
|
|
149
|
+
"raw": _raw,
|
|
150
|
+
}
|
|
151
|
+
helps = {
|
|
152
|
+
"get": "print the value of a standard key, for example private-ipv4",
|
|
153
|
+
"provider": "print the detected cloud provider",
|
|
154
|
+
"keys": "print the standard keys the provider supports",
|
|
155
|
+
"query": "evaluate a JMESPath expression against a metadata document",
|
|
156
|
+
"raw": "print a metadata document without evaluating anything",
|
|
157
|
+
}
|
|
158
|
+
timeout_only, both = _option_parents()
|
|
159
|
+
for name, handler in handlers.items():
|
|
160
|
+
sub = commands.add_parser(
|
|
161
|
+
name,
|
|
162
|
+
help=helps[name],
|
|
163
|
+
description=helps[name],
|
|
164
|
+
parents=[timeout_only if name == "provider" else both],
|
|
165
|
+
)
|
|
166
|
+
sub.set_defaults(handler=handler)
|
|
167
|
+
if name == "get":
|
|
168
|
+
sub.add_argument("key", help="standard key, see the keys command")
|
|
169
|
+
if name == "query":
|
|
170
|
+
sub.add_argument("expression", help="JMESPath expression")
|
|
171
|
+
if name in ("query", "raw"):
|
|
172
|
+
sub.add_argument(
|
|
173
|
+
"--document",
|
|
174
|
+
metavar="NAME",
|
|
175
|
+
help="document to use (default: the provider's primary document)",
|
|
176
|
+
)
|
|
177
|
+
return parser
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
181
|
+
"""Run the command line tool and return the exit code."""
|
|
182
|
+
args = build_parser().parse_args(argv)
|
|
183
|
+
try:
|
|
184
|
+
handler: Callable[[argparse.Namespace], int] = args.handler
|
|
185
|
+
return handler(args)
|
|
186
|
+
except CloudMetadataError as err:
|
|
187
|
+
print(f"{PROG}: error: {err}", file=sys.stderr)
|
|
188
|
+
return exit_code(err)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
if __name__ == "__main__": # pragma: no cover
|
|
192
|
+
sys.exit(main())
|
cloud_metadata/detect.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# Copyright (c) 2026 SUSE LLC. All rights reserved.
|
|
2
|
+
#
|
|
3
|
+
# This file is part of cloud-metadata. cloud-metadata provides one command
|
|
4
|
+
# and one Python API that return the same standard instance metadata on every
|
|
5
|
+
# supported public cloud.
|
|
6
|
+
#
|
|
7
|
+
# This program is free software: you can redistribute it and/or modify
|
|
8
|
+
# it under the terms of the GNU General Public License as published by
|
|
9
|
+
# the Free Software Foundation, either version 3 of the License, or
|
|
10
|
+
# (at your option) any later version.
|
|
11
|
+
#
|
|
12
|
+
# This program is distributed in the hope that it will be useful,
|
|
13
|
+
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
+
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
+
# GNU General Public License for more details.
|
|
16
|
+
#
|
|
17
|
+
# You should have received a copy of the GNU General Public License
|
|
18
|
+
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
19
|
+
|
|
20
|
+
"""Detect which cloud provider the process is running on.
|
|
21
|
+
|
|
22
|
+
The DMI and ``dmidecode`` checks are ported from ``provider.py`` in
|
|
23
|
+
cloud-registration-engine (https://github.com/SUSE-Enceladus/cloud-registration-engine,
|
|
24
|
+
commit 84815e24604012832bcafee155cc1a560ebf11e0), which is
|
|
25
|
+
Copyright (c) 2026 SUSE LLC and licensed GPL-3.0-or-later.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import logging
|
|
29
|
+
import os
|
|
30
|
+
import subprocess
|
|
31
|
+
from collections.abc import Iterable
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
from cloud_metadata import _http, engine, registry
|
|
35
|
+
from cloud_metadata.errors import MetadataUnavailable, ProviderNotDetected
|
|
36
|
+
from cloud_metadata.providers._spec import ProviderSpec
|
|
37
|
+
|
|
38
|
+
logger = logging.getLogger(__name__)
|
|
39
|
+
|
|
40
|
+
DEFAULT_DMI_DIR = "/sys/class/dmi/id"
|
|
41
|
+
DMI_FILES = ("sys_vendor", "product_name", "chassis_asset_tag")
|
|
42
|
+
PROVIDER_ENV = "CLOUD_METADATA_PROVIDER"
|
|
43
|
+
DMIDECODE_TIMEOUT = 5
|
|
44
|
+
|
|
45
|
+
# The provider found in this process, once detection has succeeded.
|
|
46
|
+
_detected: str | None = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def clear_cache() -> None:
|
|
50
|
+
"""Forget the detected provider."""
|
|
51
|
+
global _detected # noqa: PLW0603
|
|
52
|
+
_detected = None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
registry.add_change_callback(clear_cache)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def match_dmi_text(text: str, specs: Iterable[ProviderSpec]) -> str | None:
|
|
59
|
+
"""Return the first provider whose ``dmi_match`` occurs in ``text``.
|
|
60
|
+
|
|
61
|
+
The comparison is case-insensitive. Providers are tried in the order given.
|
|
62
|
+
"""
|
|
63
|
+
lowered = text.strip().lower()
|
|
64
|
+
for spec in specs:
|
|
65
|
+
if any(fragment in lowered for fragment in spec.dmi_match):
|
|
66
|
+
return spec.name
|
|
67
|
+
return None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def check_dmi_files(specs: Iterable[ProviderSpec] | None = None) -> str | None:
|
|
71
|
+
"""Look for a provider in the DMI files.
|
|
72
|
+
|
|
73
|
+
The directory is ``/sys/class/dmi/id`` unless ``DMI_DIR_PATH`` is set.
|
|
74
|
+
Files that are missing or unreadable are skipped.
|
|
75
|
+
|
|
76
|
+
Returns:
|
|
77
|
+
The provider name, or ``None`` if nothing matches.
|
|
78
|
+
"""
|
|
79
|
+
candidates = tuple(registry.specs() if specs is None else specs)
|
|
80
|
+
base_dir = Path(os.environ.get("DMI_DIR_PATH", DEFAULT_DMI_DIR))
|
|
81
|
+
for file_name in DMI_FILES:
|
|
82
|
+
try:
|
|
83
|
+
content = (base_dir / file_name).read_text(encoding="utf-8")
|
|
84
|
+
except (OSError, UnicodeDecodeError):
|
|
85
|
+
continue
|
|
86
|
+
name = match_dmi_text(content, candidates)
|
|
87
|
+
if name is not None:
|
|
88
|
+
return name
|
|
89
|
+
return None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def check_imds(spec: ProviderSpec, *, timeout: float = _http.DEFAULT_TIMEOUT) -> bool:
|
|
93
|
+
"""Return True if the provider's metadata service answers a probe.
|
|
94
|
+
|
|
95
|
+
Each probe path is requested through :func:`cloud_metadata.engine.request`,
|
|
96
|
+
so it uses the provider's headers, token flow and every base URL. Any
|
|
97
|
+
successful response counts. A provider without probes never matches.
|
|
98
|
+
"""
|
|
99
|
+
for probe in spec.probes:
|
|
100
|
+
try:
|
|
101
|
+
engine.request(spec, probe.path, timeout=timeout)
|
|
102
|
+
except MetadataUnavailable as err:
|
|
103
|
+
logger.debug("%s: probe %s failed: %s", spec.name, probe.path, err)
|
|
104
|
+
continue
|
|
105
|
+
return True
|
|
106
|
+
return False
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def check_dmidecode(specs: Iterable[ProviderSpec] | None = None) -> str | None:
|
|
110
|
+
"""Look for a provider in the output of ``dmidecode``.
|
|
111
|
+
|
|
112
|
+
Returns:
|
|
113
|
+
The provider name, or ``None`` if nothing matches, ``dmidecode`` is not
|
|
114
|
+
installed, fails, or times out.
|
|
115
|
+
"""
|
|
116
|
+
candidates = tuple(registry.specs() if specs is None else specs)
|
|
117
|
+
try:
|
|
118
|
+
result = subprocess.run(
|
|
119
|
+
["dmidecode", "-s", "system-manufacturer"], # noqa: S607
|
|
120
|
+
stdout=subprocess.PIPE,
|
|
121
|
+
stderr=subprocess.DEVNULL,
|
|
122
|
+
timeout=DMIDECODE_TIMEOUT,
|
|
123
|
+
check=False,
|
|
124
|
+
)
|
|
125
|
+
except (OSError, subprocess.SubprocessError):
|
|
126
|
+
# dmidecode is not installed, not permitted, or timed out.
|
|
127
|
+
return None
|
|
128
|
+
if result.returncode != 0:
|
|
129
|
+
return None
|
|
130
|
+
return match_dmi_text(result.stdout.decode("utf-8", errors="replace"), candidates)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def detect_provider(*, timeout: float = _http.DEFAULT_TIMEOUT) -> str:
|
|
134
|
+
"""Return the name of the provider this process is running on.
|
|
135
|
+
|
|
136
|
+
Order:
|
|
137
|
+
|
|
138
|
+
1. ``CLOUD_METADATA_PROVIDER``, which must name a registered provider.
|
|
139
|
+
2. DMI files. A match is confirmed with that provider's metadata probes. If
|
|
140
|
+
the probes fail, DMI is trusted and a warning is logged.
|
|
141
|
+
3. If DMI is inconclusive, every provider's probes in registry order.
|
|
142
|
+
4. ``dmidecode``.
|
|
143
|
+
|
|
144
|
+
The result is cached until a provider is registered or removed. The
|
|
145
|
+
override is not cached.
|
|
146
|
+
|
|
147
|
+
Raises:
|
|
148
|
+
ProviderNotDetected: If nothing matches or the override names an
|
|
149
|
+
unknown provider.
|
|
150
|
+
"""
|
|
151
|
+
global _detected # noqa: PLW0603
|
|
152
|
+
override = os.environ.get(PROVIDER_ENV)
|
|
153
|
+
if override:
|
|
154
|
+
return registry.get_spec(override).name
|
|
155
|
+
if _detected is not None:
|
|
156
|
+
return _detected
|
|
157
|
+
name = _detect(timeout)
|
|
158
|
+
_detected = name
|
|
159
|
+
return name
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _detect(timeout: float) -> str:
|
|
163
|
+
name = check_dmi_files()
|
|
164
|
+
if name is not None:
|
|
165
|
+
if check_imds(registry.get_spec(name), timeout=timeout):
|
|
166
|
+
logger.info("Detected %s via DMI and metadata service", name)
|
|
167
|
+
else:
|
|
168
|
+
logger.warning(
|
|
169
|
+
"DMI identifies %s but its metadata service did not answer; "
|
|
170
|
+
"trusting DMI",
|
|
171
|
+
name,
|
|
172
|
+
)
|
|
173
|
+
return name
|
|
174
|
+
for spec in registry.specs():
|
|
175
|
+
if check_imds(spec, timeout=timeout):
|
|
176
|
+
logger.info("Detected %s via metadata service", spec.name)
|
|
177
|
+
return spec.name
|
|
178
|
+
name = check_dmidecode()
|
|
179
|
+
if name is not None:
|
|
180
|
+
logger.info("Detected %s via dmidecode", name)
|
|
181
|
+
return name
|
|
182
|
+
msg = (
|
|
183
|
+
"could not detect a cloud provider (registered: "
|
|
184
|
+
f"{', '.join(registry.names()) or 'none'}); "
|
|
185
|
+
f"set {PROVIDER_ENV} to override"
|
|
186
|
+
)
|
|
187
|
+
raise ProviderNotDetected(msg)
|