Skip to content
codemowersPublic

About

Grafana for Prometheus native environments

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Anafarg

Declarative Prometheus dashboards for Kubernetes. Administrators install ClusterChart and ClusterDashboard resources that name discovered metric families. Anafarg compiles them to PromQL that is checked and scoped to each viewer. It renders every output with one Go renderer: SVG in the browser, embeddable web components, PNG/MJPEG for old browsers and media players, and a Linux framebuffer helper.

DESIGN.md describes the architecture; Metric visualization and dashboards specifies metric types, rendering and Explore breakdowns. chart/files contains bundled resources; examples contains optional dashboards. /explore is the metric explorer.

Explore metric controls are grouped into Filters, Data and Display. Split charts produces one chart per label value, including independent histogram heatmaps. Splitting happens before aggregation and pooling, keeps the same authorization as the combined chart, and shows up to 24 groups at once. Filter labels to narrow larger selections. Splits and other view choices are recorded in the URL. YAML export produces a ClusterChart for a combined view or a repeated ClusterDashboard for a split view; queries and diagnostics are available below the charts.

The dashboard list keeps every installed dashboard visible. Dashboards whose required jobs are absent from their Prometheus catalog appear gray and sort below available dashboards, with the missing jobs named on the card. Optional overlay sources do not affect availability; discovery failures are reported as unknown availability rather than missing exporters.

The bundled /dashboards/alerts dashboard puts critical alerts first, followed by warnings and other severities. Each section pairs state timelines with horizontal active-duration bars. Namespace, alert, node and Pod selectors narrow the view; opening a chart groups it by alert name and offers label filters and alternative splits. ALERTS_FOR_STATE uses the shared timestamp interval renderer, with full durations inside bars even when activation predates the visible range. Disable the bundled dashboards with provision.dashboards: false.

Path Contents
cmd/anafarg Service: UI, API, display listener
cmd/anafarg-fb Linux framebuffer helper
internal/ Discovery, compiler, engine, renderer, auth, server
ui/ Dependency-free browser UI and the <anafarg-*> embed library
chart/ Helm chart with CRDs and the bundled Kubernetes resource and alert dashboards

Everything is pure Go (CGO_ENABLED=0).

Compared to Grafana and Perses

Grafana and Perses both support dashboards as code. Anafarg focuses on discovered Prometheus metric semantics, Kubernetes namespace authorization and shared rendering across browsers and displays.

Grafana Perses Anafarg
Scope Broad datasource ecosystem for metrics and other data. Datasources Prometheus metrics, Tempo traces, Loki logs and Pyroscope profiles through plugins. Overview Prometheus metrics on Kubernetes.
Chart definition Datasource queries and panel configuration. Panel and query plugins, with PromQL for Prometheus panels. Dashboard model Discovered {job, metric} families with typed refinements; inferred rate, units, histogram, state and information views.
GitOps and state Provisioning imports dashboards into its database; source updates overwrite provisioned UI edits. Provisioning CUE/Go SDKs, validation and CLI workflows; the operator synchronizes dashboard/datasource CRDs to Perses instances. Dashboard as code, operator Watches ClusterChart and ClusterDashboard resources directly; no dashboard database or synchronization operator.
Editing UI editing, with configurable restrictions for provisioned dashboards. Provisioning UI or code. Dashboards Manifest edits; Explore exports chart or repeated-dashboard YAML.
Authorization Organization, team and resource permissions; datasource and label-based controls depend on edition and configuration. Access controls Project/global roles and bindings; optional Kubernetes RBAC for namespaces, dashboard CRDs and datasource CRDs. Authorization Resource access plus per-selector namespace scoping from the viewer's list pods permissions; monitor access additionally gates Explore.
Embedding Panel iframes, subject to deployment and authentication settings. Sharing React/npm components for panels and dashboards. Embedding Dependency-free chart and dashboard web components with host token and variable bindings.
Display rendering Browser dashboard application and panels. Browser panel plugins and embeddable components. One Go renderer for browser SVG, PNG, MJPEG and Linux framebuffer output.

Anafarg deliberately omits logs, traces, other datasource types, plugins and browser editing. To change a dashboard, change its manifest.

Local development

Forward your Prometheus service to a local port, then run without Kubernetes or a login:

kubectl -n monitoring port-forward svc/prometheus-operated 19090:9090
CGO_ENABLED=0 go build -o .build/anafarg ./cmd/anafarg
.build/anafarg -listen 127.0.0.1:8788 -display-listen 127.0.0.1:8789 \
  -auth-mode anonymous -no-kube \
  -resources chart/files \
  -prometheus monitoring/prometheus=http://127.0.0.1:19090
  • Browser UI: open http://127.0.0.1:8788/.
  • Resources: -resources takes comma-separated directories of Anafarg resources and reloads them on change. Unlisted links need metadata.uid and -link-key-file (at least 32 bytes).
  • Kubernetes: instead of -no-kube, pass -context YOUR_CONTEXT to resolve Prometheus resources, read monitor labels and run SubjectAccessReviews with your kubeconfig.
go test ./...
node ui/test_units.mjs   # browser unit formatting matches internal/units
node ui/test_yaml.mjs    # explorer ClusterChart YAML

Useful URLs:

  • /dashboards/namespace-resources?var-namespace=demo&range=6h
  • /api/v1/dashboards/cluster-resources/dashboard.png?width=1280&height=720&theme=dark
  • /api/v1/charts/node-cpu/render.svg
  • /explore?job=monitoring/node-exporter: metric explorer
  • /api/v1/prometheus/monitoring/prometheus/catalog: discovered jobs and families

Embedding

<script type="module" src="https://anafarg.example/embed/anafarg.js"></script>
<anafarg-dashboard src="https://anafarg.example" name="namespace-resources"
                   vars="namespace=shop" range="6h" hide-title></anafarg-dashboard>
<anafarg-chart src="https://anafarg.example" name="node-cpu" height="240"></anafarg-chart>
  • Authentication: set element.getToken = async () => token with an issuer-signed JWT access token for Anafarg's audience. The calling origin must be in allowedOrigins.
  • Variables: those bound in vars are hidden; the others stay selectable.
  • Errors: RBAC denials render inside the panel.

Displays

Dashboards are private; links publish them. A ClusterDashboardLink (administrators, any dashboard, scope: {all: true} or {namespaces: [...]}) or a DashboardLink (namespace admins, dashboards with sharing.namespaced: true, own namespace only) is served at /d/TOKEN/ (unlisted, the default) or /public/NAMESPACE/NAME/ (- for cluster links). Charts that would read series outside a namespace link's boundary render "No access". /links lists the links you administer with their URLs. See docs/sharing.md. The same URL works in modern browsers and, through an ES3 fallback, in Firefox 3.5. …/legacy is plain HTML with a refreshing PNG; add ?stream=mjpeg for a continuous image. display.enabled adds a display-only listener and Service with TLS none, legacy (TLS 1.0 for Windows XP) or modern.

Framebuffer (amd64, arm64, armv7):

CGO_ENABLED=0 GOARCH=arm64 go build -o anafarg-fb ./cmd/anafarg-fb
./anafarg-fb -url https://anafarg.example/d/TOKEN/ -var node=worker-1 -fb /dev/fb0
./anafarg-fb -url https://anafarg.example/public/-/lab-status/ -list-vars
./anafarg-fb -url https://anafarg.example/public/-/lab-status/ -png out.png -width 800 -height 480

-discover finds the links in your kubeconfig with kubectl (all contexts, or -contexts a,b; one query per cluster) and shows them. It also prints the same command line with one -url per link, which then runs on a PC without kubectl or a login:

$ ./anafarg-fb -discover -windowed -slide 2
# production ClusterDashboardLink cluster-resources-wall -> cluster-resources (15/15 charts)
./anafarg-fb \
  -windowed \
  -slide 2 \
  -url https://anafarg.example/d/TOKEN/

Links whose Ready is False are listed as skipped. Contexts that need an interactive login time out after 20 seconds; log in with kubectl first.

Under a Wayland session (WAYLAND_DISPLAY set) the same binary opens a fullscreen window instead; -output wayland|fbdev forces one, and -windowed starts in a borderless window. Drag anywhere to move the window, press F or double-click to toggle fullscreen, Left/Right to switch between rotated dashboards, 1–9 to pick the time range (15m, 1h, 3h, 6h, 12h, 24h, 7d, 30d, 90d), and Esc to quit. It stays pure Go: the Wayland protocol runs over the compositor socket (neurlang/wayland) with shared-memory buffers, no cgo. /dev/fb0 only shows when no desktop owns the screen, i.e. on a console.

./anafarg-fb -url https://anafarg.example/public/-/lab-status/ -windowed
# rotate between dashboards (1 minute each, progress bar at the bottom) and slide charts smoothly
./anafarg-fb -slide 2 \
  -url 'https://anafarg.example/dashboards/cluster-resources' \
  -url 'https://anafarg.example/dashboards/namespace-resources?var-namespace=monitoring'

When Anafarg is unreachable, the helper keeps the last view and marks it offline. The last data is also cached on disk for reboots.

Docker image

docker build -t anafarg:local .

The image is scratch with one static binary, running as UID 65532 on ports 8787 (main) and 8789 (display). Provide CA trust at runtime for HTTPS connections; tzdata is embedded for TIMEZONE.

Kubernetes deployment

These must already exist: the namespace, the Prometheus Operator and a Prometheus resource. Configure an Ingress controller, certificate issuer and CA trust for the installation. Authentication requires an OIDC provider; the default Passmower integration also requires its operator and OIDCClient CRD.

The chart installs:

  • the CRDs (chart/crds)
  • the Deployment, Service, ServiceAccount and Ingress
  • the Passmower OIDCClient when oidc.enabled and oidc.passmower.enabled are true
  • the ServiceAccount's RBAC: create SubjectAccessReviews, watch namespaces and the Anafarg kinds, read Prometheus resources and monitors; the link key Secret is mounted, not read
  • the anafarg-viewer ClusterRole bound to system:authenticated
  • optionally, the bundled dashboards (provision.dashboards), the cluster-resources-wall link (provision.links) and the display Service

For a multi-user installation, configure ingestion labels and admission together with AUTH_MODE=rbac. See Prometheus multitenancy for namespace enforcement, scrape classes, node-exporter and workload labels, admission controls, and authorization checks.

The base configuration is in chart/values.yaml, including resource requests and limits. Keep installation-specific overrides in a local chart/values.CLUSTER.yaml file; these files are ignored by Git. Set image to the complete image reference, preferably by digest. imageRegistry optionally prefixes short image names; imagePullSecrets, env and secretEnv configure registry access and runtime settings.

Tags vX.Y.Z publish ghcr.io/codemowers/anafarg and the chart oci://ghcr.io/codemowers/charts/anafarg at version X.Y.Z, with the image pinned by digest. Use oci://ghcr.io/codemowers/charts/anafarg --version X.Y.Z in place of ./chart below.

Apply CRDs separately on installation and upgrades because Helm does not upgrade resources in crds/:

kubectl --context "$KUBE_CONTEXT" apply --server-side -f chart/crds/
helm upgrade --install anafarg ./chart \
  --kube-context "$KUBE_CONTEXT" \
  --namespace monitoring \
  --reset-values \
  -f chart/values.CLUSTER.yaml \
  --set-string image="$IMAGE_REFERENCE" \
  --wait --timeout 5m

Skaffold reads the target context from skaffold.env (see skaffold.env.example) and installation values from chart/values.local.yaml; both are ignored by Git. SKAFFOLD_DEFAULT_REPO selects the image registry. Builds use Docker/BuildKit with OCI media types and no provenance/SBOM indexes; deployments use the resolved image digest. skaffold dev removes its Helm release on exit.

ingress.host defaults to the release name. Set oidc.uri to the public application URL when hostname expansion or an external Ingress supplies the actual hostname.

OIDC uses provider discovery, Authorization Code with PKCE and a backend cookie session. The provider must support a confidential web client and HTTPS callback at <oidc.uri>/auth/callback. The browser receives no tokens. Bearer embedding requires issuer-signed JWT access tokens with Anafarg's audience; opaque access tokens are not supported.

oidc.passmower.enabled defaults to true: the chart creates a Passmower OIDCClient and reads its generated oidc-client-<release>-owner-secrets Secret. oidc.useIngressRef=true requires Passmower ingress discovery. oidc.displayName, oidc.allowedGroups and oidc.useIngressRef configure this integration.

For another OIDC provider, register the client and store its secret in a Kubernetes Secret in the release namespace, then configure:

oidc:
  enabled: true
  passmower:
    enabled: false
  uri: https://anafarg.example
  issuerURL: https://identity.example
  clientID: anafarg
  existingSecret: anafarg-oidc
  clientSecretKey: client-secret
  scopes:
    - openid
    - profile
    - email

This disables the Passmower resource and generated Secret references. Add provider-specific scopes, such as groups, when required for Kubernetes claim mapping. In rbac mode, configure auth.kubernetes to match kube-apiserver; auth.mode: oidc grants every verified login read access to everything. oidc.enabled: false disables OIDC entirely and requires anonymous mode.

Restart the Deployment after credentials rotate; sessions derived from the previous client secret are invalidated:

kubectl --context "$KUBE_CONTEXT" -n monitoring rollout restart deployment/anafarg

Runtime configuration

Setting Purpose
AUTH_MODE / -auth-mode rbac (default), oidc (any login reads everything) or anonymous
OIDC_ISSUER_URL / OIDC_IDP_URI, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, OIDC_CLIENT_URI, OIDC_AVAILABLE_SCOPES OIDC provider and client; OIDC_IDP_URI takes precedence when both issuer settings are set. The callback is OIDC_CLIENT_URI/auth/callback unless OIDC_REDIRECT_URI is set
ANAFARG_AUDIENCE, ALLOWED_CLIENT_IDS Bearer tokens from embedders: required audience (default: the app URL), accepted clients
ALLOWED_ORIGINS Origins allowed to call the API from browser embedders
KUBERNETES_USERNAME_CLAIM, _USERNAME_PREFIX, _GROUPS_CLAIM, _GROUPS_PREFIX Must match kube-apiserver's OIDC flags; defaults: sub, <issuer># (empty for the email claim), groups, no group prefix
SESSION_KEY Optional session key material; otherwise derived from the client secret
DEFAULT_PROMETHEUS Prometheus for resources without prometheusRef (default monitoring/prometheus)
PROMETHEUS_URLS namespace/name=url overrides, comma-separated
RESOURCES_DIR, KUBECONFIG, KUBE_CONTEXT, KUBERNETES_ENABLED Development: file resources, kubeconfig, or no Kubernetes
LISTEN, DISPLAY_LISTEN, DISPLAY_TLS_MODE, DISPLAY_TLS_CERT, DISPLAY_TLS_KEY Listeners
MAX_SERIES, MAX_POINTS, MAX_RANGE (default 90d), TIMEZONE Query limits and rendering timezone

The optional PROMETHEUS_EXTERNAL_URL environment variable (or -prometheus-external-url) sets the browser-facing URL of the default Prometheus. It enables source and generated-query links in the explorer; query transport still comes from prometheusRef. Links open in a new tab. Unset it to omit them.

Inter 4.1 is shared by the interface, SVG charts and pure-Go raster output; code uses JetBrains Mono 2.304. Fonts are self-hosted, bundled under internal/typeface, and ship with their SIL Open Font Licenses. There are no runtime font/CDN dependencies or frontend build step.

YAML resources and configuration use two-space block style. Run make fmt-yaml to format them and make lint-yaml to check; Skaffold checks before builds and deployments. The native Go formatter retains comments and anchors. Helm templates are excluded because they contain Go-template expressions rather than plain YAML.

The chart resources under chart/files/ are authoritative. Schema changes are breaking: update Git manifests to the current schema and redeploy; Anafarg does not migrate old charts. Series use role for usage/cache/request/limit/capacity and read/write/receive/transmit semantics. make generate-schema updates the structural CRDs and browser capability metadata from Go types; make lint-schema checks them.

Empty charts

An empty chart stays expanded and shows No samples for this window. When a bounded lookup finds an earlier result, the same box shows Last sample: with its timestamp and time ago. The chart keeps the selected time window and does not render older samples. Zero values count as data.

This is automatic and needs no chart-spec setting. The lookup covers the 24h before the selected end time, capped by the installation's maximum range. It uses a sparse wide query and refines around the newest result found. Brief activity between sparse query steps may be missed; an unsuccessful lookup says only that no earlier samples were found within that bound.

The lookup preserves the exact jobs, chart filters, selected variables and namespace permissions. It examines finite chart-query results, including rates and histogram quantiles, rather than raw scrapes. Errors, permission failures and partial responses stay visible as problems and never become absence claims. All-jobs charts show the empty-window message without an earlier-sample lookup.

About

Grafana for Prometheus native environments

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages