zuke.tools.prometheus

← Python API reference

@zuke/prometheus 1.1.1: A typed client for the Prometheus HTTP API, for Zuke builds.

Symbols

#

PrometheusAwsSettings

class
class PrometheusAwsSettings(Settings)

Settings for PrometheusConnectionSettings.sigv4(...).

  • region(region: str) -> Self

    The workspace's region, such as us-east-1; defaults to AWS_REGION, then AWS_DEFAULT_REGION.

  • profile(name: str) -> Self

    Read 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) -> Self

    Sign with this access key instead of searching the default chain.

#

PrometheusAzureSettings

class
class PrometheusAzureSettings(Settings)

Settings for PrometheusConnectionSettings.azure(...).

  • scope(scope: str) -> Self

    The scope to request, replacing https://prometheus.monitor.azure.com/.default.

  • tenant_id(id: str) -> Self

    The Microsoft Entra tenant (directory) id; defaults to AZURE_TENANT_ID.

  • client_id(id: str) -> Self

    The application's client id — or, for a user-assigned managed identity, the identity's; defaults to AZURE_CLIENT_ID.

  • authority_host(url: str) -> Self

    The Microsoft Entra authority, such as https://login.microsoftonline.us for Azure Government; defaults to AZURE_AUTHORITY_HOST, then https://login.microsoftonline.com.

  • client_secret(secret: str | None=None) -> Self

    Use a service principal's client secret (the client-credentials grant). The secret defaults to AZURE_CLIENT_SECRET.

  • workload_identity(token_file: str | None=None) -> Self

    Use workload identity federation: the Kubernetes service-account token in tokenFile (default AZURE_FEDERATED_TOKEN_FILE) is the client assertion, read afresh on every token request since it is rotated.

  • managed_identity(client_id: str | None=None) -> Self

    Use 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.

#

PrometheusConnectionSettings

class
class PrometheusConnectionSettings(Settings)

The connection half of every Prometheus call's settings.

  • url(url: str) -> Self

    The 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 be https: unless it is loopback, or ZUKE_ALLOW_INSECURE_URL is set, since a plaintext request hands the credential to anyone on the path. An unauthenticated URL may be plaintext, as an in-cluster http://prometheus.monitoring.svc:9090 usually is.

  • bearer_token(token: str) -> Self

    Authenticate with Authorization: Bearer <token>.

  • basic_auth(username: str, password: str) -> Self

    Authenticate with HTTP basic auth (Authorization: Basic …).

  • header(name: str, value: str) -> Self

    Send a fixed header, such as a tenant id (X-Scope-OrgID). A plain header does not make the call credentialed, so an in-cluster http:// Mimir, Cortex or Thanos with a tenant header keeps working — except Authorization, Proxy-Authorization, Cookie, and a name core's URL redactor treats as credential-bearing (X-API-Key, X-Auth-Token: names containing key, token, secret, auth, pass and 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) -> Self

    Send a fixed header that carries a credential — an API key such as X-API-Key. Like bearerToken, it makes the call credentialed, so the URL must be https: unless it is loopback, and its value is masked in errors.

  • google(configure: Callable[[PrometheusGoogleSettings], PrometheusGoogleSettings] | None=None) -> Self

    Authenticate to Google Cloud Managed Service for Prometheus with an OAuth access token from Application Default Credentials — no gcloud needed. The search order is credentialsFile(...), else the file GOOGLE_APPLICATION_CREDENTIALS names; then gcloud's application_default_credentials.json; then the GCE / GKE metadata server. A file may be a service_account key, an authorized_user gcloud login, or an external_account workload identity federation configuration with a file or url subject-token source. The scope defaults to monitoring.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) -> Self

    Authenticate to Azure Monitor managed service for Prometheus with a Microsoft Entra ID token for https://prometheus.monitor.azure.com/.default — no az needed. 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's IDENTITY_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) -> Self

    Sign every request with AWS Signature Version 4 for Amazon Managed Service for Prometheus (service aps) — no aws CLI needed. The region is region(...), else AWS_REGION / AWS_DEFAULT_REGION. Credentials come from accessKey(...) or profile(...) when set, else the chain: the AWS_ACCESS_KEY_ID environment, 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) -> Self

    How long the call may take, end to end ("10s", or ms; default 30 s). Client-side: the query's own timeout parameter is separate.

  • max_response_bytes(bytes: float) -> Self

    The largest response body to read, in bytes (default 64 MiB). A larger one fails the call rather than being buffered whole.

#

PrometheusExpressionSettings

class
class PrometheusExpressionSettings(PrometheusConnectionSettings)

What an instant and a range query share: the expression and its limits.

  • query(promql: str) -> Self

    The PromQL expression (query).

  • timeout(duration: str | float) -> Self

    The evaluation timeout (timeout), such as "30s" — capped by the server's -query.timeout. The client-side limit is requestTimeout.

  • limit(series: float) -> Self

    The most series to return (limit); 0 means no limit.

  • lookback_delta(duration: str | float) -> Self

    Override the lookback period for this query (lookback_delta).

  • http_method(method: Literal['GET', 'POST']) -> Self

    Send the parameters as a POST form (the default) or in a GET URL.

#

PrometheusGoogleSettings

class
class PrometheusGoogleSettings(Settings)

Settings for PrometheusConnectionSettings.google(...).

  • scopes(*scopes: str) -> Self

    The 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 at gcloud auth application-default login and ignores these.

  • credentials_file(path: str) -> Self

    Read 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) -> Self

    The project charged for the request's quota, sent as x-goog-user-project. Defaults to the credentials file's quota_project_id, which gcloud auth application-default set-quota-project writes.

#

PrometheusLabelsSettings

class
class PrometheusLabelsSettings(PrometheusSelectionSettings)

Settings for listing label names (/api/v1/labels).

  • http_method(method: Literal['GET', 'POST']) -> Self

    Send the parameters as a POST form (the default) or in a GET URL.

#

PrometheusLabelValuesSettings

class
class PrometheusLabelValuesSettings(PrometheusSelectionSettings)

Settings for one label's values (/api/v1/label/<label_name>/values).

  • label_name(name: str) -> Self

    The 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 as http.status_code) is sent in the API's U__ value-encoding escape, so nothing in the name can reach the URL path as a separator.

#

PrometheusMetadataSettings

class
class PrometheusMetadataSettings(PrometheusConnectionSettings)

Settings for metric metadata (/api/v1/metadata).

  • limit(metrics: float) -> Self

    The most metrics to return (limit).

  • limit_per_metric(entries: float) -> Self

    The most metadata entries per metric (limit_per_metric).

  • metric(name: str) -> Self

    Only this metric's metadata (metric).

#

PrometheusQueryRangeSettings

class
class PrometheusQueryRangeSettings(PrometheusExpressionSettings)

Settings for a range query (/api/v1/query_range).

  • start(time: str | float) -> Self

    The inclusive start (start): a Date, Unix seconds, or RFC 3339 text.

  • end(time: str | float) -> Self

    The inclusive end (end): a Date, Unix seconds, or RFC 3339 text.

  • step(duration: str | float) -> Self

    The resolution step (step): "15s", or a number of seconds.

#

PrometheusQuerySettings

class
class PrometheusQuerySettings(PrometheusExpressionSettings)

Settings for an instant query (/api/v1/query).

  • time(time: str | float) -> Self

    The evaluation time (time): a Date, Unix seconds, or RFC 3339 text.

#

PrometheusRulesSettings

class
class PrometheusRulesSettings(PrometheusConnectionSettings)

Settings for the loaded rules (/api/v1/rules).

  • type_(type_: Literal['alert', 'record']) -> Self

    Only alerting ("alert") or only recording ("record") rules (type).

  • rule_name(*names: str) -> Self

    Only rules with these names (rule_name[]).

  • rule_group(*groups: str) -> Self

    Only rules in these groups (rule_group[]).

  • file(*paths: str) -> Self

    Only rules from these files (file[]).

  • match_(*selectors: str) -> Self

    Only rules whose configured labels match these selectors (match[]).

  • exclude_alerts(on: bool | None=None) -> Self

    Leave out each rule's active alerts (exclude_alerts=true).

  • group_limit(groups: float) -> Self

    At most this many rule groups per page (group_limit).

  • group_next_token(token: str) -> Self

    Continue from a previous page's groupNextToken (group_next_token).

#

PrometheusSelectionSettings

class
class PrometheusSelectionSettings(PrometheusConnectionSettings)

What the series, label-name and label-value endpoints share.

  • match_(*selectors: str) -> Self

    Add series selectors (match[]), such as up or {job="api"}.

  • start(time: str | float) -> Self

    The start time (start): a Date, Unix seconds, or RFC 3339 text.

  • end(time: str | float) -> Self

    The end time (end): a Date, Unix seconds, or RFC 3339 text.

  • limit(count: float) -> Self

    The most results to return (limit); 0 means no limit.

#

PrometheusSeriesSettings

class
class PrometheusSeriesSettings(PrometheusSelectionSettings)

Settings for finding series by matchers (/api/v1/series).

  • http_method(method: Literal['GET', 'POST']) -> Self

    Send the parameters as a POST form (the default) or in a GET URL.

#

PrometheusTargetsSettings

class
class PrometheusTargetsSettings(PrometheusConnectionSettings)

Settings for the target overview (/api/v1/targets).

  • state(state: Literal['active', 'dropped', 'any']) -> Self

    Only active or only dropped targets (state); both by default.

#

PrometheusTasks

class
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]) -> object

    Evaluate 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]) -> object

    Evaluate a range query (/api/v1/query_range); the answer is a matrix.

  • static async series(ctx: ServiceContext, configure: Callable[[PrometheusSeriesSettings], PrometheusSeriesSettings]) -> object

    Find the series matching selectors (/api/v1/series).

  • static async labels(ctx: ServiceContext, configure: Callable[[PrometheusLabelsSettings], PrometheusLabelsSettings]) -> object

    List label names (/api/v1/labels).

  • static async label_values(ctx: ServiceContext, configure: Callable[[PrometheusLabelValuesSettings], PrometheusLabelValuesSettings]) -> object

    List one label's values (/api/v1/label/<label_name>/values).

  • static async metadata(ctx: ServiceContext, configure: Callable[[PrometheusMetadataSettings], PrometheusMetadataSettings]) -> object

    Read metric metadata (/api/v1/metadata), keyed by metric name.

  • static async targets(ctx: ServiceContext, configure: Callable[[PrometheusTargetsSettings], PrometheusTargetsSettings]) -> object

    Read target discovery state (/api/v1/targets).

  • static async rules(ctx: ServiceContext, configure: Callable[[PrometheusRulesSettings], PrometheusRulesSettings]) -> object

    Read the loaded alerting and recording rules (/api/v1/rules).

  • static async alerts(ctx: ServiceContext, configure: Callable[[PrometheusConnectionSettings], PrometheusConnectionSettings]) -> object

    Read the active alerts (/api/v1/alerts).

  • static async build_info(ctx: ServiceContext, configure: Callable[[PrometheusConnectionSettings], PrometheusConnectionSettings]) -> object

    Read the server's build information (/api/v1/status/buildinfo).

  • static async healthy(ctx: ServiceContext, configure: Callable[[PrometheusConnectionSettings], PrometheusConnectionSettings]) -> object

    Probe /-/healthy: true on 2xx, false on 503, and a PrometheusApiError on any other status — a 401 is a credential problem, not an unhealthy server.

  • static async ready(ctx: ServiceContext, configure: Callable[[PrometheusConnectionSettings], PrometheusConnectionSettings]) -> object

    Probe /-/ready: true once the server serves queries, false while it answers 503, and a PrometheusApiError on any other status.

  • static async value(ctx: ServiceContext, response: Mapping[str, object]) -> object

    The 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. NaN is returned as NaN, 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]) -> object

    Every 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.