Skip to content

Generic API Plugin

The Generic API plugin (generic_api.py) queries HTTP/HTTPS JSON endpoints—such as Prometheus, CheckMK, and Argos—extracts and transforms metrics via configuration-driven paths, regular expressions, and aggregations, and writes LML files for LLview's dbupdate action.

It typically runs periodically via cronjob on LLview Server (or it can also run on LLview Remote if the network access to the target APIs is only available there).


Command-Line Interface

python3 generic_api.py --config config.yml [OPTIONS]
Flag Required Default Description
--config <file> Yes — Path to the YAML configuration file.
--loglevel <level> No INFO Logging verbosity (DEBUG, INFO, WARNING, ERROR).
--singleLML <file> No — Merge all sections into a single LML output file instead of one file per section.
--outfolder <dir> No — Base output directory prepended to all generated LML paths (normalized with os.path.normpath).

Processing Pipeline

Each top-level server block and its files sections are processed in the following order:

  • Static Value & Cache Check:
    • If value is set on a metric, HTTP querying is skipped (written immediately if target_id is set, or injected into all instances during finalization).
    • If the metric name already exists in cached_queries, cached data is reused without re-querying.
  • URL Construction & Parameter Expansion:
    • Builds the target URL from hostname (automatically prepending https:// if absent) and either query (PromQL) or endpoint (REST).
    • URL-encodes parameters and expands relative start/end offsets (e.g., -5m, 0s) into Unix epoch timestamps.
  • HTTP Request & Path Extraction:
    • Performs an HTTP GET request using token headers or Basic Auth credentials, honoring configured proxies and TLS verification ((10, 20) second timeout).
    • Traverses the JSON response using path (defaulting to 'data.result'), expanding {name} and wildcard * keys into {target_id: value} dictionaries, and stores the result if cache: true.
  • Normalization & Transformation:
    • Prometheus responses (list of objects containing 'metric'): applies replace placeholders and regex to pid, formats GPU (device) and per-core CPU (cpu) entries, applies factor/min/max, and attaches extra labels.
    • Generic / REST responses (wildcard dictionaries or scalar values): filters None entries from [ts, value] lists, applies aggregate (or selects the first valid point), runs regex, and applies factor/min/max when numeric.
  • Finalization & LML Output:
    • Attaches __prefix, __type, static value entries, and default fallbacks to every record.
    • Normalizes the destination path, creates missing parent directories, and writes the LML XML file via to_LML.

Configuration Reference

Server Options (<server_name>)

Each top-level YAML entry defines an API server and the LML files generated from it.

Key Type Default Description
hostname string — API server host or base URL (supports environment variables such as ${PROMETHEUS_SERVER}).
credentials string / dict Interactive / none Authentication configuration: 'none', 'module' (imports get_user_pass from credentials in PYTHONPATH), or {username: ..., password: ...} (supports envvars).
token string — Authorization token sent in request headers (Authorization: <token>); takes precedence over Basic Auth when set.
proxies dict — HTTP/HTTPS proxy mapping passed to requests.get.
verify bool / string True Enables/disables TLS certificate verification or specifies a CA bundle path.
files dict — Dictionary of output file sections (<section_name>).

File Section Options (files.<section_name>)

Each section under files corresponds to a single LML output file.

Key Type Default Description
LML string — Output LML XML file path (required).
type string "" Entity type written to __type (e.g., 'cpuinfo', 'coreinfo', 'sysstat', 'ndpwrinfo').
prefix string "" Prefix written to __prefix and prepended to the section timestamp key (<prefix>_ts).
index string — Key name used for indexing LML entries (e.g., 'id').
mapping dict — Map of source_field: lml_field defining fields kept in the LML output.
metrics dict — Dictionary of metric definitions (<metric_name>) to query or inject.

Metric Options (metrics.<metric_name>)

Key Type Default Description
query string — PromQL query appended to /api/v1/query?query=....
endpoint string — REST endpoint path appended to hostname (used when query is omitted).
parameters dict — URL query parameters; start and end support relative time strings.
value any — Static value exported without making an HTTP request (uses target_id if given, otherwise applied to all instances in the section).
cache bool false Caches extracted data in memory under the metric name for reuse within the same run.
path string 'data.result' Dot-separated JSON traversal path; supports {name} and * wildcards.
target_id string — Target instance ID for scalar responses (required when path does not use * and data is not a Prometheus list).
id string 'instance' Prometheus label key used to extract the base instance identifier (pid).
aggregate string First valid Aggregation for [ts, val] arrays: min, max, avg, sum, count, or concatenate.
regex string — Regular expression applied to Prometheus pid or REST string values (returns capture group 1 if present, else the full match).
replace dict — Prometheus map of raw_pid: template supporting {label} placeholders from the metric's label dictionary.
factor float 1.0 Multiplier applied to parsed numeric values.
min float — Lower clamp bound applied after factor.
max float — Upper clamp bound applied after factor.
default any — Fallback value assigned to any instance in the section missing this metric.

Path Traversal, Time Expansion & Aggregations

Dynamic JSON path Syntax

Pattern Behavior Example
key1.key2 Traverses nested dictionaries to extract a list or scalar value. 'extensions.plugin_output'
* Iterates over dictionary keys at that level and assigns each key as target_id. 'out.*.power'
{name} Substitutes the YAML metric key name into the path before traversal. 'out.*.{name}'

Relative Time Parameters (start and end)

When parameters contains start or end, strings matching ^([+-]?\d+)([smhdw])$ are converted to Unix epoch timestamps relative to int(time.time()). Absolute timestamps and all other parameters (e.g., step: "60") are left unchanged.

Unit Seconds Example Resolved Value
s 1 0s, -30s Current time, or 30 seconds ago
m 60 -1m, -5m 1 minute ago, or 5 minutes ago
h 3600 -2h 2 hours ago
d 86400 -1d 1 day ago
w 604800 -1w 1 week ago

Built-in aggregate Functions

Used on REST responses returning lists of [timestamp, value] pairs. Points where value is None are ignored before evaluation.

Method Output Type Behavior
(omitted) Original Selects the first non-None point and its timestamp.
min float Minimum of all valid float values; records the latest valid timestamp.
max float Maximum of all valid float values; records the latest valid timestamp.
avg float Arithmetic mean of all valid float values; records the latest valid timestamp.
sum float Sum of all valid float values; records the latest valid timestamp.
count int Count of non-None data points (supports numeric and string values).
concatenate string Comma-separated string of all valid values; records the latest valid timestamp.

Prometheus Label & Value Handling

  • Special Metric Types:
    • GPU metrics (when label device is present): strips 'nvidia', formats id as <pid>_<gpu:02d>, and sets feature: GPU<gpu>.
    • CPU metrics (when label cpu is present): nests values per core under id_data[name][int(cpu)] = value.
    • General metrics: stores id_data[name] = value and copies all additional non-instance labels onto the record.
  • Placeholder & Regex Processing:
    • replace runs before regex on Prometheus pid values, substituting {label} placeholders with values from the metric's label dictionary.
    • On REST/scalar metrics, regex runs on the extracted string before attempting float() conversion; non-numeric matches (such as units) are preserved as strings.

Example Configurations

A reference Prometheus configuration is maintained in the LLview configuration repository:

CheckMK & Argos Examples

checkmk:
  hostname: ${CHECKMK_SERVER}
  token: ${CHECKMK_TOKEN}
  files:
    environment:
      LML: './sysstat_LML.xml'
      type: 'sysstat'
      prefix: 'syst'
      metrics:
        # Static metadata injected without an HTTP query
        sysname:
          value: 'SYSTEM'
        # Extract numeric value and unit from the same cached endpoint
        power:
          endpoint: '/site/check_mk/api/1.0/objects/host/host01/actions/show_service/invoke'
          parameters:
            service_description: System_Power
            columns: plugin_output
          path: 'extensions.plugin_output'
          target_id: 'sysstat'
          regex: '^(\d+\.?\d+)'
          default: 0
          cache: true
        power_unit:
          endpoint: '/site/check_mk/api/1.0/objects/host/host01/actions/show_service/invoke'
          parameters:
            service_description: System_Power
            columns: plugin_output
          path: 'extensions.plugin_output'
          target_id: 'sysstat'
          regex: '^\d+\.?\d+([^\s]+)'
          default: ''
          cache: true

argos:
  hostname: ${ARGOS_SERVER}
  credentials:
    username: ${ARGOS_USER}
    password: ${ARGOS_PASS}
  files:
    nodepower:
      LML: './nodepower_LML.xml'
      type: 'ndpwrinfo'
      prefix: 'ndpwr'
      index: 'id'
      metrics:
        power:
          endpoint: '/api/v1/metrics/power'
          # Wildcard captures node names as target IDs
          path: 'data.*.{name}'
          aggregate: 'avg'
          parameters:
            components: node-[001-010]
            step: "60"
            start: "-5m"
            end: "0s"
          default: 0