zuke.tools.prometheus
@zuke/prometheus 1.1.1: A typed client for the Prometheus HTTP API, for Zuke builds.
zuke on PyPI ↗ 15 symbols
Symbols
class PrometheusAwsSettings(Settings) Settings for PrometheusConnectionSettings.sigv4(...).
-
region(region: str) -> SelfThe workspace's region, such as
us-east-1; defaults toAWS_REGION, thenAWS_DEFAULT_REGION. -
profile(name: str) -> SelfRead static keys from this profile of the shared credentials and config files (
~/.aws/credentials,~/.aws/config) instead of searching the default chain. -
access_key(access_key_id: str, secret_access_key: str, session_token: str | None=None) -> SelfSign with this access key instead of searching the default chain.
class PrometheusAzureSettings(Settings) Settings for PrometheusConnectionSettings.azure(...).
-
scope(scope: str) -> SelfThe scope to request, replacing
https://prometheus.monitor.azure.com/.default. -
tenant_id(id: str) -> SelfThe Microsoft Entra tenant (directory) id; defaults to
AZURE_TENANT_ID. -
client_id(id: str) -> SelfThe application's client id — or, for a user-assigned managed identity, the identity's; defaults to
AZURE_CLIENT_ID. -
authority_host(url: str) -> SelfThe Microsoft Entra authority, such as
https://login.microsoftonline.usfor Azure Government; defaults toAZURE_AUTHORITY_HOST, thenhttps://login.microsoftonline.com. -
client_secret(secret: str | None=None) -> SelfUse a service principal's client secret (the client-credentials grant). The secret defaults to
AZURE_CLIENT_SECRET. -
workload_identity(token_file: str | None=None) -> SelfUse workload identity federation: the Kubernetes service-account token in
tokenFile(defaultAZURE_FEDERATED_TOKEN_FILE) is the client assertion, read afresh on every token request since it is rotated. -
managed_identity(client_id: str | None=None) -> SelfUse the managed identity of the VM, App Service or Functions app the build runs on. Pass a user-assigned identity's client id, or leave it out for
clientId(...)/AZURE_CLIENT_ID, and failing those the system-assigned identity.
class PrometheusConnectionSettings(Settings) The connection half of every Prometheus call's settings.
-
url(url: str) -> SelfThe Prometheus base URL, such as
https://prometheus.internal. A path or query string it carries — a proxy prefix, a tenant parameter — is kept, and the endpoint path is appended. Userinfo in the URL (https://user:pass@host) is taken off the URL and sent as basic auth. When the call carries any credential — a configured source, or that userinfo — the URL must behttps:unless it is loopback, orZUKE_ALLOW_INSECURE_URLis set, since a plaintext request hands the credential to anyone on the path. An unauthenticated URL may be plaintext, as an in-clusterhttp://prometheus.monitoring.svc:9090usually is. -
bearer_token(token: str) -> SelfAuthenticate with
Authorization: Bearer <token>. -
basic_auth(username: str, password: str) -> SelfAuthenticate with HTTP basic auth (
Authorization: Basic …). -
header(name: str, value: str) -> SelfSend a fixed header, such as a tenant id (
X-Scope-OrgID). A plain header does not make the call credentialed, so an in-clusterhttp://Mimir, Cortex or Thanos with a tenant header keeps working — exceptAuthorization,Proxy-Authorization,Cookie, and a name core's URL redactor treats as credential-bearing (X-API-Key,X-Auth-Token: names containingkey,token,secret,auth,passand the like), which count as credentials. For an API key under any other name use secretHeader. The value is masked in errors either way (when eight or more characters long). -
secret_header(name: str, value: str) -> SelfSend a fixed header that carries a credential — an API key such as
X-API-Key. LikebearerToken, it makes the call credentialed, so the URL must behttps:unless it is loopback, and its value is masked in errors. -
google(configure: Callable[[PrometheusGoogleSettings], PrometheusGoogleSettings] | None=None) -> SelfAuthenticate to Google Cloud Managed Service for Prometheus with an OAuth access token from Application Default Credentials — no
gcloudneeded. The search order iscredentialsFile(...), else the fileGOOGLE_APPLICATION_CREDENTIALSnames; then gcloud'sapplication_default_credentials.json; then the GCE / GKE metadata server. A file may be aservice_accountkey, anauthorized_usergcloud login, or anexternal_accountworkload identity federation configuration with afileorurlsubject-token source. The scope defaults tomonitoring.read; the token is cached until shortly before it expires. `ts s.url("https://monitoring.googleapis.com/v1/projects/my-project/location/global/prometheus") .google()` -
azure(configure: Callable[[PrometheusAzureSettings], PrometheusAzureSettings] | None=None) -> SelfAuthenticate to Azure Monitor managed service for Prometheus with a Microsoft Entra ID token for
https://prometheus.monitor.azure.com/.default— noazneeded. Unless a credential is chosen, the first the environment configures is used: client secret (AZURE_TENANT_ID,AZURE_CLIENT_ID,AZURE_CLIENT_SECRET), then workload identity (AZURE_TENANT_ID,AZURE_CLIENT_ID,AZURE_FEDERATED_TOKEN_FILE), then managed identity (App Service'sIDENTITY_ENDPOINT, else the VM's IMDS). The token is cached until shortly before it expires. `ts s.url("https://my-amw.eastus.prometheus.monitor.azure.com") .azure((a) => a.managedIdentity(clientId))` -
sigv4(configure: Callable[[PrometheusAwsSettings], PrometheusAwsSettings] | None=None) -> SelfSign every request with AWS Signature Version 4 for Amazon Managed Service for Prometheus (service
aps) — noawsCLI needed. The region isregion(...), elseAWS_REGION/AWS_DEFAULT_REGION. Credentials come fromaccessKey(...)orprofile(...)when set, else the chain: theAWS_ACCESS_KEY_IDenvironment, the shared files' profile, web identity (AWS_WEB_IDENTITY_TOKEN_FILE+AWS_ROLE_ARN), the ECS / EKS Pod Identity container endpoint, then EC2 IMDSv2. Configure it after any other source, so it signs the headers they add. `ts s.url("https://aps-workspaces.us-east-1.amazonaws.com/workspaces/ws-1234") .sigv4((a) => a.region("us-east-1"))` -
request_timeout(duration: str | float) -> SelfHow long the call may take, end to end (
"10s", or ms; default 30 s). Client-side: the query's owntimeoutparameter is separate. -
max_response_bytes(bytes: float) -> SelfThe largest response body to read, in bytes (default 64 MiB). A larger one fails the call rather than being buffered whole.
class PrometheusExpressionSettings(PrometheusConnectionSettings) What an instant and a range query share: the expression and its limits.
-
query(promql: str) -> SelfThe PromQL expression (
query). -
timeout(duration: str | float) -> SelfThe evaluation timeout (
timeout), such as"30s"— capped by the server's-query.timeout. The client-side limit isrequestTimeout. -
limit(series: float) -> SelfThe most series to return (
limit);0means no limit. -
lookback_delta(duration: str | float) -> SelfOverride the lookback period for this query (
lookback_delta). -
http_method(method: Literal['GET', 'POST']) -> SelfSend the parameters as a
POSTform (the default) or in aGETURL.
class PrometheusGoogleSettings(Settings) Settings for PrometheusConnectionSettings.google(...).
-
scopes(*scopes: str) -> SelfThe OAuth scopes to request, replacing the default
https://www.googleapis.com/auth/monitoring.read. A gcloud user credential (authorized_user) carries the scopes it was granted atgcloud auth application-default loginand ignores these. -
credentials_file(path: str) -> SelfRead this credentials file — a service-account key, a gcloud user credential, or a workload identity federation configuration — instead of searching Application Default Credentials.
-
quota_project(project: str) -> SelfThe project charged for the request's quota, sent as
x-goog-user-project. Defaults to the credentials file'squota_project_id, whichgcloud auth application-default set-quota-projectwrites.
class PrometheusLabelsSettings(PrometheusSelectionSettings) Settings for listing label names (/api/v1/labels).
-
http_method(method: Literal['GET', 'POST']) -> SelfSend the parameters as a
POSTform (the default) or in aGETURL.
class PrometheusLabelValuesSettings(PrometheusSelectionSettings) Settings for one label's values (/api/v1/label/<label_name>/values).
-
label_name(name: str) -> SelfThe label whose values to list. Any name is accepted: one outside the classic
[a-zA-Z_:][a-zA-Z0-9_:]*form (a UTF-8 name such ashttp.status_code) is sent in the API'sU__value-encoding escape, so nothing in the name can reach the URL path as a separator.
class PrometheusMetadataSettings(PrometheusConnectionSettings) Settings for metric metadata (/api/v1/metadata).
-
limit(metrics: float) -> SelfThe most metrics to return (
limit). -
limit_per_metric(entries: float) -> SelfThe most metadata entries per metric (
limit_per_metric). -
metric(name: str) -> SelfOnly this metric's metadata (
metric).
class PrometheusQueryRangeSettings(PrometheusExpressionSettings) Settings for a range query (/api/v1/query_range).
-
start(time: str | float) -> SelfThe inclusive start (
start): aDate, Unix seconds, or RFC 3339 text. -
end(time: str | float) -> SelfThe inclusive end (
end): aDate, Unix seconds, or RFC 3339 text. -
step(duration: str | float) -> SelfThe resolution step (
step):"15s", or a number of seconds.
class PrometheusQuerySettings(PrometheusExpressionSettings) Settings for an instant query (/api/v1/query).
-
time(time: str | float) -> SelfThe evaluation time (
time): aDate, Unix seconds, or RFC 3339 text.
class PrometheusRulesSettings(PrometheusConnectionSettings) Settings for the loaded rules (/api/v1/rules).
-
type_(type_: Literal['alert', 'record']) -> SelfOnly alerting (
"alert") or only recording ("record") rules (type). -
rule_name(*names: str) -> SelfOnly rules with these names (
rule_name[]). -
rule_group(*groups: str) -> SelfOnly rules in these groups (
rule_group[]). -
file(*paths: str) -> SelfOnly rules from these files (
file[]). -
match_(*selectors: str) -> SelfOnly rules whose configured labels match these selectors (
match[]). -
exclude_alerts(on: bool | None=None) -> SelfLeave out each rule's active alerts (
exclude_alerts=true). -
group_limit(groups: float) -> SelfAt most this many rule groups per page (
group_limit). -
group_next_token(token: str) -> SelfContinue from a previous page's
groupNextToken(group_next_token).
class PrometheusSelectionSettings(PrometheusConnectionSettings) What the series, label-name and label-value endpoints share.
-
match_(*selectors: str) -> SelfAdd series selectors (
match[]), such asupor{job="api"}. -
start(time: str | float) -> SelfThe start time (
start): aDate, Unix seconds, or RFC 3339 text. -
end(time: str | float) -> SelfThe end time (
end): aDate, Unix seconds, or RFC 3339 text. -
limit(count: float) -> SelfThe most results to return (
limit);0means no limit.
class PrometheusSeriesSettings(PrometheusSelectionSettings) Settings for finding series by matchers (/api/v1/series).
-
http_method(method: Literal['GET', 'POST']) -> SelfSend the parameters as a
POSTform (the default) or in aGETURL.
class PrometheusTargetsSettings(PrometheusConnectionSettings) Settings for the target overview (/api/v1/targets).
-
state(state: Literal['active', 'dropped', 'any']) -> SelfOnly active or only dropped targets (
state); both by default.
class PrometheusTasks The Prometheus HTTP API as tasks (<https://prometheus.io/docs/prometheus/latest/querying/api/>).
-
static async query(ctx: ServiceContext, configure: Callable[[PrometheusQuerySettings], PrometheusQuerySettings]) -> objectEvaluate an instant query (
/api/v1/query). `ts const result = await PrometheusTasks.query((s) => s.url("https://prometheus.internal").bearerToken(token) .query('sum(rate(http_requests_total{code=~"5.."}[5m]))') );` -
static async query_range(ctx: ServiceContext, configure: Callable[[PrometheusQueryRangeSettings], PrometheusQueryRangeSettings]) -> objectEvaluate a range query (
/api/v1/query_range); the answer is a matrix. -
static async series(ctx: ServiceContext, configure: Callable[[PrometheusSeriesSettings], PrometheusSeriesSettings]) -> objectFind the series matching selectors (
/api/v1/series). -
static async labels(ctx: ServiceContext, configure: Callable[[PrometheusLabelsSettings], PrometheusLabelsSettings]) -> objectList label names (
/api/v1/labels). -
static async label_values(ctx: ServiceContext, configure: Callable[[PrometheusLabelValuesSettings], PrometheusLabelValuesSettings]) -> objectList one label's values (
/api/v1/label/<label_name>/values). -
static async metadata(ctx: ServiceContext, configure: Callable[[PrometheusMetadataSettings], PrometheusMetadataSettings]) -> objectRead metric metadata (
/api/v1/metadata), keyed by metric name. -
static async targets(ctx: ServiceContext, configure: Callable[[PrometheusTargetsSettings], PrometheusTargetsSettings]) -> objectRead target discovery state (
/api/v1/targets). -
static async rules(ctx: ServiceContext, configure: Callable[[PrometheusRulesSettings], PrometheusRulesSettings]) -> objectRead the loaded alerting and recording rules (
/api/v1/rules). -
static async alerts(ctx: ServiceContext, configure: Callable[[PrometheusConnectionSettings], PrometheusConnectionSettings]) -> objectRead the active alerts (
/api/v1/alerts). -
static async build_info(ctx: ServiceContext, configure: Callable[[PrometheusConnectionSettings], PrometheusConnectionSettings]) -> objectRead the server's build information (
/api/v1/status/buildinfo). -
static async healthy(ctx: ServiceContext, configure: Callable[[PrometheusConnectionSettings], PrometheusConnectionSettings]) -> objectProbe
/-/healthy:trueon 2xx,falseon 503, and aPrometheusApiErroron any other status — a 401 is a credential problem, not an unhealthy server. -
static async ready(ctx: ServiceContext, configure: Callable[[PrometheusConnectionSettings], PrometheusConnectionSettings]) -> objectProbe
/-/ready:trueonce the server serves queries,falsewhile it answers 503, and aPrometheusApiErroron any other status. -
static async value(ctx: ServiceContext, response: Mapping[str, object]) -> objectThe single number an instant query returned — a scalar, or a vector of exactly one float sample — failing clearly on an empty or multi-sample vector, a matrix, a string or a native histogram.
NaNis returned asNaN, which compares false both ways — gate with!(v <= max). `ts const ratio = PrometheusTasks.value(await PrometheusTasks.query((s) => …));` -
static async samples(ctx: ServiceContext, response: Mapping[str, object]) -> objectEvery float sample of an instant query, with its labels: a vector's elements, or a scalar as one unlabelled sample. An empty vector is an empty list; a matrix, string or native histogram fails.