diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 46c0276d..99f48ea2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -36,7 +36,7 @@ jobs: - name: Run tests run: | mkdir -p "${RUNNER_TEMP}/test-reports" - gotestsum --junitfile "${RUNNER_TEMP}/test-reports/unit-tests.xml" -- . ./alert_generator/... ./promql/... ./promqle2e/... + gotestsum --junitfile "${RUNNER_TEMP}/test-reports/unit-tests.xml" -- . ./alert_generator/... ./openmetrics/... ./promql/... ./promqle2e/... - name: Upload test results if: always() diff --git a/.github/workflows/compliance-tests.yml b/.github/workflows/compliance-tests.yml index 4c249875..f1d8782e 100644 --- a/.github/workflows/compliance-tests.yml +++ b/.github/workflows/compliance-tests.yml @@ -59,3 +59,18 @@ jobs: go-version: 1.26.x - run: cd promql && make test + + openmetrics: + name: OpenMetrics + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + persist-credentials: false + + - name: Set up Go + uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6.4.0 + with: + go-version: 1.26.x + + - run: cd openmetrics && make test diff --git a/README.md b/README.md index a1141575..bc9d25d6 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ The [alert_generator](alert_generator/README.md) directory contains a shim at th ## OpenMetrics -The [openmetrics](openmetrics/README.md) directory contains a reference to the [OpenMetrics](https://github.com/prometheus/OpenMetrics/blob/v1.0.0/specification/OpenMetrics.md) test suite. +The [openmetrics](openmetrics/README.md) directory contains a programmatic Go compliance test suite for [OpenMetrics 1.0](https://prometheus.io/docs/specs/om/open_metrics_spec/) and [OpenMetrics 2.0](https://prometheus.io/docs/specs/om/open_metrics_2_0_spec/) metric producers (SDKs and `/metrics` endpoints). ## PromQL diff --git a/go.mod b/go.mod index a54678b4..35b4abd3 100644 --- a/go.mod +++ b/go.mod @@ -13,10 +13,10 @@ require ( github.com/oklog/ulid v1.3.1 github.com/pkg/errors v0.9.1 github.com/prometheus/alertmanager v0.28.1 - github.com/prometheus/client_golang v1.23.2 + github.com/prometheus/client_golang v1.24.2-0.20261028105007-0b2f01f00376 github.com/prometheus/client_golang/exp v0.0.0-20261026045710-70c0a469a56a github.com/prometheus/client_model v0.6.3 - github.com/prometheus/common v0.72.0 + github.com/prometheus/common v0.72.2-0.20261027144952-e257672f3db6 github.com/prometheus/common/sigv4 v0.1.0 github.com/prometheus/prometheus v0.307.4-0.20251119130332-1174b0ce4f1f github.com/prometheus/sigv4 v0.3.0 @@ -88,6 +88,7 @@ require ( github.com/hashicorp/go-msgpack/v2 v2.1.1 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-sockaddr v1.0.7 // indirect + github.com/hashicorp/go-uuid v1.0.3 // indirect github.com/hashicorp/golang-lru v0.6.0 // indirect github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect github.com/hashicorp/memberlist v0.5.1 // indirect @@ -106,10 +107,11 @@ require ( github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect + github.com/pandatix/go-abnf v0.5.1 // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/prometheus/exporter-toolkit v0.15.0 // indirect github.com/prometheus/otlptranslator v1.0.0 // indirect - github.com/prometheus/procfs v0.21.0 // indirect + github.com/prometheus/procfs v0.22.0 // indirect github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 // indirect github.com/shurcooL/httpfs v0.0.0-20230704072500-f1e31cf0ba5c // indirect github.com/shurcooL/vfsgen v0.0.0-20230704071429-0000e147ea92 // indirect @@ -121,15 +123,15 @@ require ( go.opentelemetry.io/otel/trace v1.38.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect - golang.org/x/crypto v0.57.0 // indirect + golang.org/x/crypto v0.58.0 // indirect golang.org/x/mod v0.41.0 // indirect - golang.org/x/net v0.59.0 // indirect + golang.org/x/net v0.61.0 // indirect golang.org/x/oauth2 v0.37.0 // indirect - golang.org/x/sync v0.23.0 // indirect - golang.org/x/sys v0.48.0 // indirect - golang.org/x/text v0.42.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect golang.org/x/time v0.13.0 // indirect - golang.org/x/tools v0.49.0 // indirect + golang.org/x/tools v0.51.0 // indirect google.golang.org/api v0.252.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20251002232023-7c0ddcbb5797 // indirect google.golang.org/grpc v1.76.0 // indirect diff --git a/go.sum b/go.sum index 07153bbd..dff616cb 100644 --- a/go.sum +++ b/go.sum @@ -329,8 +329,9 @@ github.com/hashicorp/go-rootcerts v1.0.2 h1:jzhAVGtqPKbwpyCPELlgNWhE1znq+qwJtW5O github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8= github.com/hashicorp/go-sockaddr v1.0.7 h1:G+pTkSO01HpR5qCxg7lxfsFEZaG+C0VssTy/9dbT+Fw= github.com/hashicorp/go-sockaddr v1.0.7/go.mod h1:FZQbEYa1pxkQ7WLpyXJ6cbjpT8q0YgQaK/JakXqGyWw= -github.com/hashicorp/go-uuid v1.0.0 h1:RS8zrF7PhGwyNPOtxSClXXj9HA8feRnJzgnI1RJCSnM= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= +github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.6.0 h1:uL2shRDx7RTrOrTCUZEGP/wJUFiUI8QT6E7z5o8jga4= @@ -434,6 +435,8 @@ github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrB github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= github.com/ovh/go-ovh v1.9.0 h1:6K8VoL3BYjVV3In9tPJUdT7qMx9h0GExN9EXx1r2kKE= github.com/ovh/go-ovh v1.9.0/go.mod h1:cTVDnl94z4tl8pP1uZ/8jlVxntjSIf09bNcQ5TJSC7c= +github.com/pandatix/go-abnf v0.5.1 h1:iyLvSu2Aq12iE0r4n948Qw21BHDuckLq/8WIXAAF+HI= +github.com/pandatix/go-abnf v0.5.1/go.mod h1:VBmbtpFgQNEaQpyAvmi+Ecd9wAYJKzA3TmiB3L93sVg= github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= @@ -454,8 +457,8 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= -github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o= -github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg= +github.com/prometheus/client_golang v1.24.2-0.20261028105007-0b2f01f00376 h1:TH8kcDkZKg9xI7n16Vl198Hb6HFxpl/D0cZz3Pa3v8M= +github.com/prometheus/client_golang v1.24.2-0.20261028105007-0b2f01f00376/go.mod h1:vENYwrbRF5ZOH5/agFOGBpP4GkR0TfPHVTWE9jqwnp8= github.com/prometheus/client_golang/exp v0.0.0-20261026045710-70c0a469a56a h1:OoEy/u/pZ5f40MNac+y1j5kQM0R25ax0WRjm3uxqYTQ= github.com/prometheus/client_golang/exp v0.0.0-20261026045710-70c0a469a56a/go.mod h1:tNd0xTnUQoyfRnpWzS8mCykqNyqGUdoduK0LeEMC1+Y= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= @@ -469,8 +472,8 @@ github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8b github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= github.com/prometheus/common v0.26.0/go.mod h1:M7rCNAaPfAosfx8veZJCuw84e35h3Cfd9VFqTh1DIvc= github.com/prometheus/common v0.29.0/go.mod h1:vu+V0TpY+O6vW9J44gczi3Ap/oXXR10b+M/gUGO4Hls= -github.com/prometheus/common v0.72.0 h1:tAYsE+sPJxIncDAobm4H5aQjmox9ZxEIIqPbiffa8G4= -github.com/prometheus/common v0.72.0/go.mod h1:77NWqAQ2tXT7BIK40qjJdw5Acrsrg1TlHAnsQi3i6mk= +github.com/prometheus/common v0.72.2-0.20261027144952-e257672f3db6 h1:hTmBpcMUwT+Dw+C2NEPK6BLyMF5pE9qWsoSzhI7Iad4= +github.com/prometheus/common v0.72.2-0.20261027144952-e257672f3db6/go.mod h1:Nt+CsVkf/mj4wDAmtSwq1HTPohHSX6fMr6+/f9B5UqM= github.com/prometheus/common/sigv4 v0.1.0 h1:qoVebwtwwEhS85Czm2dSROY5fTo2PAPEVdDeppTwGX4= github.com/prometheus/common/sigv4 v0.1.0/go.mod h1:2Jkxxk9yYvCkE5G1sQT7GuEXm57JrvHu9k5YwTjsNtI= github.com/prometheus/exporter-toolkit v0.15.0 h1:Pcle5sSViwR1x0gdPd0wtYrPQENBieQAM7TmT0qtb2U= @@ -482,8 +485,8 @@ github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsT github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA= -github.com/prometheus/procfs v0.21.0 h1:Qh/e6TlBjZf+XLLqNCqFGmCU6Kj/2Bu7kj3oAc0UnXc= -github.com/prometheus/procfs v0.21.0/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= +github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics= +github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58= github.com/prometheus/prometheus v0.307.4-0.20251119130332-1174b0ce4f1f h1:ERPCnBglv9Z4IjkEBTNbcHmZPlryMldXVWLkk7TeBIY= github.com/prometheus/prometheus v0.307.4-0.20251119130332-1174b0ce4f1f/go.mod h1:7hcXiGf9AXIKW2ehWWzxkvRYJTGmc2StUIJ8mprfxjg= github.com/prometheus/sigv4 v0.3.0 h1:QIG7nTbu0JTnNidGI1Uwl5AGVIChWUACxn2B/BQ1kms= @@ -567,8 +570,8 @@ golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= -golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -634,8 +637,8 @@ golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81R golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues= -golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw= +golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -654,8 +657,8 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -693,19 +696,19 @@ golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= -golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= -golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -753,8 +756,8 @@ golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= -golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= +golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= +golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= golang.org/x/tools/godoc v0.1.0-deprecated h1:o+aZ1BOj6Hsx/GBdJO/s815sqftjSnrZZwyYTHODvtk= golang.org/x/tools/godoc v0.1.0-deprecated/go.mod h1:qM63CriJ961IHWmnWa9CjZnBndniPt4a3CK0PVB9bIg= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= diff --git a/openmetrics/.gitignore b/openmetrics/.gitignore new file mode 100644 index 00000000..0f10fdf5 --- /dev/null +++ b/openmetrics/.gitignore @@ -0,0 +1,3 @@ +bin/ +results.json +index.preloaded.html diff --git a/openmetrics/Makefile b/openmetrics/Makefile new file mode 100644 index 00000000..e4abbc18 --- /dev/null +++ b/openmetrics/Makefile @@ -0,0 +1,17 @@ +ROOT_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST)))) +SUITE_TITLE := OpenMetrics — Test Matrix + +PROMETHEUS_OPENMETRICS_COMPLIANCE_TEST_RE ?= "" +PROMETHEUS_OPENMETRICS_COMPLIANCE_SKIP_TEST_RE ?= "" +RUN_TEST = go test -run $(PROMETHEUS_OPENMETRICS_COMPLIANCE_TEST_RE) -skip $(PROMETHEUS_OPENMETRICS_COMPLIANCE_SKIP_TEST_RE) + +include $(ROOT_DIR)../Makefile.base + +.PHONY: test +test: ## Run OpenMetrics compliance tests suitable for humans and CI. + @$(RUN_TEST) . -v -timeout=$(TIMEOUT) + +.PHONY: test-web +test-web: ## Run OpenMetrics compliance tests with a HTML results view. + @$(RUN_TEST) . -json | tee "$(RESULT_FILE)" + @$(MAKE) results-web diff --git a/openmetrics/README.md b/openmetrics/README.md index dd59078a..3979deb3 100644 --- a/openmetrics/README.md +++ b/openmetrics/README.md @@ -1,7 +1,77 @@ -# OpenMetrics compliance tester +# OpenMetrics Compliance Suite -While [OpenMetrics](https://openmetrics.io/) is an independent CNCF project, Prometheus designated it as the [official specification](https://github.com/prometheus/OpenMetrics/blob/v1.0.0/specification/OpenMetrics.md) for Prometheus exposition. OpenMetrics is, and will remain, closely aligned to Prometheus. +This package provides a programmatic Go compliance test suite for metric producers (client SDKs, instrumentation libraries, and `/metrics` HTTP exporters) implementing the [OpenMetrics 1.0](https://prometheus.io/docs/specs/om/open_metrics_spec/) and [OpenMetrics 2.0](https://prometheus.io/docs/specs/om/open_metrics_2_0_spec/) specifications. -The test suite can be found on [GitHub](https://github.com/OpenObservability/OpenMetrics/tree/main/src/cmd/openmetricstest). Depending on your implementation, the [individual test cases](https://github.com/OpenObservability/OpenMetrics/tree/main/tests/testdata/parsers) might be of direct interest. +Each compliance check is tagged with its RFC 2119 requirement level (`MUST`, `SHOULD`, `MAY`, `RECOMMENDED`) and scrapes an HTTP `/metrics` endpoint with controlled `Accept` and `Accept-Encoding` headers, verifying HTTP negotiation, framing, ABNF syntax, metric metadata, label escaping, sample types, classic and native histograms, and exemplars. -Prometheus considers OpenMetrics compliance part of Prometheus compliance and compatibility. +The test suite shares [`../index.html`](../index.html) to view compliance test results in the browser after a test run completes. + +## Running Tests + +To run the compliance suite against the in-process `prometheus/client_golang` reference target: + +```bash +make test +``` + +To run the tests and open the interactive HTML compliance matrix in your browser: + +```bash +make test-web +``` + +## Programmatic Usage in Go + +You can import `github.com/prometheus/compliance/openmetrics` directly in your own Go test suite to test any `http.Handler` or external `/metrics` process. + +### Testing an `http.Handler` in-process + +```go +package myexporter_test + +import ( + "testing" + + "github.com/prometheus/compliance/openmetrics" +) + +func TestOpenMetricsCompliance(t *testing.T) { + handler := newMetricsHandler() + target := openmetrics.NewHandlerTarget("my-exporter", handler) + openmetrics.RunTests(t, target, openmetrics.ComplianceTests()) +} +``` + +You can also run only a specific specification version: + +- `openmetrics.ComplianceTests()` — runs both OpenMetrics 1.0 and OpenMetrics 2.0 tests. +- `openmetrics.V1ComplianceTests()` — runs only OpenMetrics 1.0 (`1.0.0`) tests. +- `openmetrics.V2ComplianceTests()` — runs only OpenMetrics 2.0 (`2.0.0` / `2.0.0-rc`) tests. + +### Testing an external binary or container + +Implement `openmetrics.Target` (optionally using `openmetrics.RunCommand` to manage the child process lifecycle until `ctx` is canceled): + +```go +type binaryTarget struct{} + +func (binaryTarget) Name() string { return "my-binary" } + +func (binaryTarget) Run(ctx context.Context, opts openmetrics.Options) error { + // Start your binary or container listening on opts.MetricsHostPort and serving opts.MetricsPath: + return openmetrics.RunCommand(ctx, ".", nil, "./my-exporter", "--web.listen-address="+opts.MetricsHostPort, "--web.telemetry-path="+opts.MetricsPath) +} +``` + +## Expected Canonical Metric Set + +While the `protocol` and `syntax` test categories validate any non-empty OpenMetrics exposition, the `metadata`, `escaping`, `samples`, `histograms`, and `exemplars` categories inspect specific canonical metric families when verifying SDK instrumentation features. Reference targets should expose: + +- `app_build_info` (`gauge` with value `1` and labels such as `version` and `sdk`) +- `http_requests_total` (`counter` with no unit, labels `method="GET"` and `status="200"` with value `>= 5`, start timestamp, and an exemplar carrying `trace_id="4bf92f3577b34da6a3ce929d0e0e4736"` and `span_id="00f067aa0ba902b7"`) +- `http_request_size_bytes_total` (`counter` with unit `bytes` and an exemplar carrying `trace_id="4bf92f3577b34da6a3ce929d0e0e4736"`, `span_id="00f067aa0ba902b7"`, and an extended attribute `attr_big` exceeding 128 total UTF-8 runes to exercise OpenMetrics 1.0 128-rune truncation and OpenMetrics 2.0 extended exemplar length) +- `http.server.active_requests` (`gauge` with value `3`, dots in the metric name, and UTF-8 label `service.name="demo-api"` to exercise `escaping=allow-utf-8`, `underscores`, `dots`, and `values`) +- `http_request_duration_seconds` (`histogram` with unit `seconds`, label `method="GET"`, classic buckets `0.01`..`2.5`, native histogram buckets, start timestamp, and an exemplar carrying `trace_id="4bf92f3577b34da6a3ce929d0e0e4736"`) +- `rpc_latency_seconds` (`summary` with unit `seconds` and quantiles `0.5`, `0.9`, `0.99`) + +See [`client_golang_test.go`](client_golang_test.go) for the reference implementation. diff --git a/openmetrics/client_golang_test.go b/openmetrics/client_golang_test.go new file mode 100644 index 00000000..ad1d948d --- /dev/null +++ b/openmetrics/client_golang_test.go @@ -0,0 +1,108 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openmetrics_test + +import ( + "context" + "strings" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/prometheus/common/expfmt" + "github.com/prometheus/compliance/openmetrics" +) + +type clientGolang struct{} + +func (clientGolang) Name() string { return "client_golang" } + +// Run starts an in-process HTTP server instrumented with prometheus/client_golang +// exposing the canonical OpenMetrics 1.0 and 2.0 compliance metric families. +func (clientGolang) Run(ctx context.Context, opts openmetrics.Options) error { + reg := prometheus.NewRegistry() + + buildInfo := prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Name: "app_build_info", + Help: "Application build information.", + }, []string{"version", "sdk"}) + requests := prometheus.NewCounterVec(prometheus.CounterOpts{ + Name: "http_requests_total", + Help: "Total number of HTTP requests handled.", + }, []string{"method", "status"}) + requestBytes := prometheus.NewCounter(prometheus.CounterOpts{ + Name: "http_request_size_bytes_total", + Help: "Total HTTP request bytes received.", + Unit: "bytes", + }) + // Dotted OpenTelemetry-style metric and label names that require UTF-8 quoting + // under allow-utf-8 or translation under underscores/dots/values escaping. + inFlight := prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Name: "http.server.active_requests", + Help: "Current number of in-flight HTTP requests (OTel-style dotted name).", + }, []string{"service.name"}) + // Histogram configured with both classic and native buckets. + requestDuration := prometheus.NewHistogramVec(prometheus.HistogramOpts{ + Name: "http_request_duration_seconds", + Help: "HTTP request duration in seconds.", + Unit: "seconds", + Buckets: []float64{0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5}, + NativeHistogramBucketFactor: 1.1, + }, []string{"method"}) + rpcLatency := prometheus.NewSummary(prometheus.SummaryOpts{ + Name: "rpc_latency_seconds", + Help: "RPC latency summary in seconds.", + Unit: "seconds", + Objectives: map[float64]float64{0.5: 0.01, 0.9: 0.01, 0.99: 0.001}, + }) + + reg.MustRegister(buildInfo, requests, requestBytes, inFlight, requestDuration, rpcLatency) + + exemplar := prometheus.Labels{ + "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", + "span_id": "00f067aa0ba902b7", + } + // Combined exemplar label runes > 128: truncated in OpenMetrics 1.0, preserved in OpenMetrics 2.0. + extendedExemplar := prometheus.Labels{ + "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", + "span_id": "00f067aa0ba902b7", + "attr_big": strings.Repeat("a", 80), + } + + buildInfo.WithLabelValues("1.0.0", "client_golang").Set(1) + requests.WithLabelValues("GET", "200").(prometheus.ExemplarAdder).AddWithExemplar(5, exemplar) + requests.WithLabelValues("POST", "201").Add(2) + requestBytes.(prometheus.ExemplarAdder).AddWithExemplar(4096, extendedExemplar) + inFlight.WithLabelValues("demo-api").Set(3) + requestDuration.WithLabelValues("GET").(prometheus.ExemplarObserver).ObserveWithExemplar(0.042, exemplar) + requestDuration.WithLabelValues("GET").Observe(0.18) + requestDuration.WithLabelValues("GET").Observe(0.73) + rpcLatency.Observe(0.015) + rpcLatency.Observe(0.085) + + handler := promhttp.HandlerFor(reg, promhttp.HandlerOpts{ + EnableOpenMetrics: true, + EnableOpenMetricsTextCreatedSamples: true, + AcceptedFormats: []expfmt.Format{ + expfmt.FmtOpenMetrics_2_0_0, + expfmt.FmtOpenMetrics_2_0_0_rc, + expfmt.FmtOpenMetrics_1_0_0, + expfmt.FmtOpenMetrics_0_0_1, + expfmt.FmtText, + }, + }) + + return openmetrics.NewHandlerTarget("client_golang", handler).Run(ctx, opts) +} + +var _ openmetrics.Target = clientGolang{} diff --git a/openmetrics/compliance.go b/openmetrics/compliance.go new file mode 100644 index 00000000..acbbd5c3 --- /dev/null +++ b/openmetrics/compliance.go @@ -0,0 +1,315 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openmetrics + +import ( + "bytes" + "compress/gzip" + "context" + "errors" + "fmt" + "io" + "mime" + "net/http" + "sync" + "testing" + "time" + + dto "github.com/prometheus/client_model/go" + "github.com/prometheus/common/expfmt" + "github.com/prometheus/common/model" + "github.com/prometheus/compliance" + "github.com/stretchr/testify/require" +) + +// ComplianceTests returns all official OpenMetrics 1.0 and 2.0 compliance tests. +func ComplianceTests() []Test { + ret := make([]Test, 0, 32) + ret = append(ret, V1ComplianceTests()...) + ret = append(ret, V2ComplianceTests()...) + return ret +} + +// V1ComplianceTests returns official OpenMetrics 1.0.0 compliance tests. +// +// See: https://github.com/prometheus/OpenMetrics/blob/v1.0.0/specification/OpenMetrics.md +func V1ComplianceTests() []Test { + return complianceTestsForVersion(Version1_0_0) +} + +// V2ComplianceTests returns official OpenMetrics 2.0.0 compliance tests. +// +// See: https://github.com/prometheus/OpenMetrics/blob/main/specification/OpenMetrics.md +func V2ComplianceTests() []Test { + return complianceTestsForVersion(Version2_0_0) +} + +func complianceTestsForVersion(v Version) []Test { + var ret []Test + ret = append(ret, protocolTests(v)...) + ret = append(ret, syntaxTests(v)...) + ret = append(ret, metadataTests(v)...) + ret = append(ret, escapingTests(v)...) + ret = append(ret, samplesTests(v)...) + ret = append(ret, histogramsTests(v)...) + ret = append(ret, exemplarsTests(v)...) + for i := range ret { + if ret[i].Version == "" { + ret[i].Version = v + } + } + return ret +} + +// ScrapeRequest configures the HTTP request sent to the target's metrics endpoint. +type ScrapeRequest struct { + // Accept overrides the HTTP Accept header. If empty, defaults to Version.AcceptHeader(Escaping). + Accept string + // Escaping specifies the escaping scheme parameter (e.g. "allow-utf-8", "underscores", "dots", "values") + // appended to the default Accept header when Accept is empty. + Escaping string + // AcceptEncoding specifies the HTTP Accept-Encoding header (e.g. "gzip"). + AcceptEncoding string + // Headers specifies additional HTTP request headers. + Headers map[string]string +} + +// ScrapeResult holds the captured HTTP response and decoded OpenMetrics data from a scrape. +type ScrapeResult struct { + // Version is the OpenMetrics specification version configured for this test. + Version Version + // Request is the HTTP scrape request configuration that was sent. + Request ScrapeRequest + // StatusCode is the HTTP status code returned by the target. + StatusCode int + // Headers are the HTTP response headers returned by the target. + Headers http.Header + // ContentType is the raw Content-Type response header. + ContentType string + // MediaType is the parsed media type from Content-Type. + MediaType string + // MediaParams are the parsed parameters from Content-Type (e.g. "version", "charset", "escaping"). + MediaParams map[string]string + // MediaParseErr is any error encountered when parsing Content-Type with mime.ParseMediaType. + MediaParseErr error + // RawBody is the raw HTTP response payload before any decompression. + RawBody []byte + // Body is the uncompressed OpenMetrics text payload. + Body []byte + // DecompressErr is any error encountered when decompressing RawBody. + DecompressErr error + // Families maps metric family name to decoded MetricFamily. + Families map[string]*dto.MetricFamily + // OrderedFamilies contains the decoded MetricFamilies in wire order. + OrderedFamilies []*dto.MetricFamily + // ParseErr is any syntax (ABNF) or semantic error returned by the OpenMetrics decoder. + ParseErr error +} + +// Test defines a compliance test scenario to run against a Target. +type Test struct { + // Name is a unique name for the test case. + Name string + // Description describes the specification requirement being tested. + Description string + // RFCLevel is the requirement level for the test to pass. + RFCLevel compliance.RFCLevel + // Version is the OpenMetrics specification version to test. + Version Version + // Request configures the HTTP scrape request headers. + Request ScrapeRequest + // Validate validates the scrape result in the setup stage. + Validate compliance.ValidateFunc[ScrapeResult] + // ValidateCases configures sub-cases sharing the same scrape result. + ValidateCases []compliance.ValidateCase[ScrapeResult] +} + +// RunTests starts target once, waits for its metrics endpoint to become ready, +// and runs all provided OpenMetrics compliance test cases against it. +func RunTests(t *testing.T, target Target, tcs []Test) { + t.Helper() + + require.NotNil(t, target) + require.NotEmpty(t, tcs) + + hostPort := compliance.FreeLocalHostPort(t) + const metricsPath = "/metrics" + endpointURL := fmt.Sprintf("http://%s%s", hostPort, metricsPath) + + ctx, cancel := context.WithCancel(t.Context()) + var wg sync.WaitGroup + t.Cleanup(func() { + cancel() + wg.Wait() + }) + + errCh := make(chan error, 1) + wg.Add(1) + go func() { + defer wg.Done() + errCh <- target.Run(ctx, Options{ + MetricsHostPort: hostPort, + MetricsPath: metricsPath, + }) + }() + + // Use DisableCompression so tests can inspect raw Content-Encoding headers and wire bytes directly. + client := &http.Client{ + Transport: &http.Transport{ + DisableCompression: true, + }, + Timeout: 10 * time.Second, + } + + readyOk := compliance.SafeRun(t, fmt.Sprintf("%s/_ready", target.Name()), target.Name(), "Wait for target metrics endpoint to become reachable", compliance.MustLevel, func(t *testing.T) { + waitCtx, waitCancel := context.WithTimeout(ctx, 30*time.Second) + defer waitCancel() + if err := compliance.WaitForHTTPReady(waitCtx, endpointURL, errCh, target.Name()); err != nil { + t.Fatalf("target %q failed to become ready at %s: %v", target.Name(), endpointURL, err) + } + }) + + for _, tc := range tcs { + versionShort := tc.Version.shortName() + t.Run(fmt.Sprintf("%s/%s/%s", target.Name(), tc.Name, versionShort), func(t *testing.T) { + t.Parallel() + t.Attr("version", versionShort) + + var res ScrapeResult + setupOk := compliance.SafeRun(t, "_setup", target.Name(), tc.Description, tc.RFCLevel, func(t *testing.T) { + if !readyOk { + t.Fatal("target readiness failed") + } + var err error + res, err = executeScrape(t.Context(), client, endpointURL, tc) + require.NoError(t, err, "HTTP scrape request to %s failed", endpointURL) + + if tc.Validate != nil { + tc.Validate(t, res) + } + }) + + compliance.RunValidateCases(t, target.Name(), setupOk, res, tc.ValidateCases) + }) + } +} + +func executeScrape(ctx context.Context, client *http.Client, endpointURL string, tc Test) (ScrapeResult, error) { + reqCfg := tc.Request + if reqCfg.Accept == "" { + reqCfg.Accept = tc.Version.AcceptHeader(reqCfg.Escaping) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpointURL, nil) + if err != nil { + return ScrapeResult{}, err + } + req.Header.Set("Accept", reqCfg.Accept) + if reqCfg.AcceptEncoding != "" { + req.Header.Set("Accept-Encoding", reqCfg.AcceptEncoding) + } + for k, v := range reqCfg.Headers { + req.Header.Set(k, v) + } + + resp, err := client.Do(req) + if err != nil { + return ScrapeResult{}, err + } + defer resp.Body.Close() + + rawBody, err := io.ReadAll(resp.Body) + if err != nil { + return ScrapeResult{}, fmt.Errorf("failed to read response body: %w", err) + } + + res := ScrapeResult{ + Version: tc.Version, + Request: reqCfg, + StatusCode: resp.StatusCode, + Headers: resp.Header.Clone(), + ContentType: resp.Header.Get("Content-Type"), + RawBody: rawBody, + Body: rawBody, + Families: make(map[string]*dto.MetricFamily), + } + + res.MediaType, res.MediaParams, res.MediaParseErr = mime.ParseMediaType(res.ContentType) + + if resp.Header.Get("Content-Encoding") == "gzip" { + gz, err := gzip.NewReader(bytes.NewReader(rawBody)) + if err != nil { + res.DecompressErr = err + return res, nil + } + decompressed, err := io.ReadAll(gz) + _ = gz.Close() + if err != nil { + res.DecompressErr = err + return res, nil + } + res.Body = decompressed + } + + decodeFormat := buildDecodeFormat(tc.Version, res.MediaParams, reqCfg.Escaping) + dec := expfmt.NewDecoder(bytes.NewReader(res.Body), decodeFormat) + for { + mf := &dto.MetricFamily{} + if err := dec.Decode(mf); err != nil { + if errors.Is(err, io.EOF) { + break + } + res.ParseErr = err + break + } + name := mf.GetName() + if _, dup := res.Families[name]; dup { + res.ParseErr = fmt.Errorf("duplicate metric family %q", name) + break + } + res.Families[name] = mf + res.OrderedFamilies = append(res.OrderedFamilies, mf) + } + + return res, nil +} + +// buildDecodeFormat constructs the expfmt.Format for decoding the scraped payload +// using the ABNF OpenMetrics 1.0 or 2.0 parser for the requested test version +// while honoring any requested or negotiated escaping scheme. +func buildDecodeFormat(v Version, mediaParams map[string]string, reqEscaping string) expfmt.Format { + versionStr := string(v) + if versionStr == "" { + versionStr = expfmt.OpenMetricsVersion_1_0_0 + } + if v == Version2_0_0 && mediaParams["version"] == expfmt.OpenMetricsVersion_2_0_0_rc { + versionStr = expfmt.OpenMetricsVersion_2_0_0_rc + } + + f, err := expfmt.NewOpenMetricsFormat(versionStr) + if err != nil { + f = expfmt.FmtOpenMetrics_1_0_0 + } + + escaping := reqEscaping + if escaping == "" { + escaping = mediaParams[model.EscapingKey] + } + if escaping != "" { + if scheme, err := model.ToEscapingScheme(escaping); err == nil { + f = f.WithEscapingScheme(scheme) + } + } + return f +} diff --git a/openmetrics/compliance_test.go b/openmetrics/compliance_test.go new file mode 100644 index 00000000..4f701c39 --- /dev/null +++ b/openmetrics/compliance_test.go @@ -0,0 +1,25 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openmetrics_test + +import ( + "testing" + + "github.com/prometheus/compliance/openmetrics" +) + +// TestCompliance runs all OpenMetrics 1.0 and 2.0 compliance tests against clientGolang{}. +func TestCompliance(t *testing.T) { + openmetrics.RunTests(t, clientGolang{}, openmetrics.ComplianceTests()) +} diff --git a/openmetrics/escaping.go b/openmetrics/escaping.go new file mode 100644 index 00000000..bd09c40b --- /dev/null +++ b/openmetrics/escaping.go @@ -0,0 +1,209 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openmetrics + +import ( + "fmt" + "regexp" + "testing" + + "github.com/prometheus/common/model" + "github.com/prometheus/compliance" + "github.com/stretchr/testify/require" +) + +var ( + legacyMetricNameRE = regexp.MustCompile(`^[a-zA-Z_:][a-zA-Z0-9_:]*$`) + legacyLabelNameRE = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`) +) + +func escapingTests(v Version) []Test { + utf8Level := compliance.ShouldLevel + if v == Version2_0_0 || v == Version2_0_0RC { + utf8Level = compliance.MustLevel + } + + tests := []Test{ + { + Name: "escaping_allow_utf8", + Description: "Exporters MUST/SHOULD support escaping=allow-utf-8 and preserve UTF-8 metric and label names via quoting", + RFCLevel: utf8Level, + Version: v, + Request: ScrapeRequest{ + Escaping: model.AllowUTF8, + }, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "content_type_escaping_param", + Description: "Content-Type SHOULD echo escaping=allow-utf-8 when negotiated", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.MediaParseErr) + require.Equal(t, model.AllowUTF8, res.MediaParams[model.EscapingKey]) + }, + }, + { + Name: "utf8_metric_and_label_names_preserved", + Description: "UTF-8 dotted metric and label names (http.server.active_requests, service.name) MUST be preserved unescaped after parsing", + RFCLevel: utf8Level, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + mf := requireFamily(t, res, "http.server.active_requests") + m := findMetricWithLabels(mf, map[string]string{"service.name": "demo-api"}) + require.NotNil(t, m, "Expected series http.server.active_requests{service.name=\"demo-api\"}") + require.NotEmpty(t, sampleLinesForFamily(res.Body, "http.server.active_requests"), + "Expected quoted UTF-8 metric name on the wire") + }, + }, + }, + }, + { + Name: "escaping_underscores", + Description: "Exporters SHOULD support escaping=underscores and replace non-legacy characters with underscores", + RFCLevel: compliance.ShouldLevel, + Version: v, + Request: ScrapeRequest{ + Escaping: model.EscapeUnderscores, + }, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "content_type_escaping_param", + Description: "Content-Type SHOULD include escaping=underscores when negotiated", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.MediaParseErr) + require.Equal(t, model.EscapeUnderscores, res.MediaParams[model.EscapingKey]) + }, + }, + { + Name: "all_names_conform_to_legacy_charset", + Description: "Under escaping=underscores, all metric and label names MUST conform to the legacy ASCII character set", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + for _, mf := range res.OrderedFamilies { + require.Truef(t, legacyMetricNameRE.MatchString(mf.GetName()), + "Metric name %q MUST match legacy regex under escaping=underscores", mf.GetName()) + for _, m := range mf.Metric { + for _, lp := range m.Label { + require.Truef(t, legacyLabelNameRE.MatchString(lp.GetName()), + "Label name %q on %q MUST match legacy regex under escaping=underscores", lp.GetName(), mf.GetName()) + } + } + } + }, + }, + { + Name: "dotted_names_translated_to_underscores", + Description: "Dotted metric and label names SHOULD be translated to underscores (http_server_active_requests, service_name)", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + mf := requireFamily(t, res, "http_server_active_requests") + m := findMetricWithLabels(mf, map[string]string{"service_name": "demo-api"}) + require.NotNil(t, m, "Expected series http_server_active_requests{service_name=\"demo-api\"}") + }, + }, + }, + }, + { + Name: "escaping_dots", + Description: "Exporters SHOULD support escaping=dots and encode dots as _dot_", + RFCLevel: compliance.ShouldLevel, + Version: v, + Request: ScrapeRequest{ + Escaping: model.EscapeDots, + }, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "content_type_escaping_param", + Description: "Content-Type SHOULD include escaping=dots when negotiated", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.MediaParseErr) + require.Equal(t, model.EscapeDots, res.MediaParams[model.EscapingKey]) + }, + }, + { + Name: "dotted_names_escaped_as_dot", + Description: "Dotted metric and label names SHOULD be escaped as _dot_ with underscores doubled (http_dot_server_dot_active__requests, service_dot_name)", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + mf := requireFamily(t, res, "http_dot_server_dot_active__requests") + m := findMetricWithLabels(mf, map[string]string{"service_dot_name": "demo-api"}) + require.NotNil(t, m, "Expected series http_dot_server_dot_active__requests{service_dot_name=\"demo-api\"}") + }, + }, + }, + }, + { + Name: "escaping_values", + Description: "Exporters SHOULD support escaping=values and hex-encode non-legacy characters with U__ prefix", + RFCLevel: compliance.ShouldLevel, + Version: v, + Request: ScrapeRequest{ + Escaping: model.EscapeValues, + }, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "content_type_escaping_param", + Description: "Content-Type SHOULD include escaping=values when negotiated", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.MediaParseErr) + require.Equal(t, model.EscapeValues, res.MediaParams[model.EscapingKey]) + }, + }, + { + Name: "dotted_names_hex_encoded", + Description: "Dotted metric and label names SHOULD be hex-encoded with U__ prefix and underscores doubled (U__http_2e_server_2e_active__requests, U__service_2e_name)", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + mf := requireFamily(t, res, "U__http_2e_server_2e_active__requests") + m := findMetricWithLabels(mf, map[string]string{"U__service_2e_name": "demo-api"}) + require.NotNil(t, m, "Expected series U__http_2e_server_2e_active__requests{U__service_2e_name=\"demo-api\"}") + }, + }, + }, + }, + } + + if v == Version2_0_0 || v == Version2_0_0RC { + tests = append(tests, Test{ + Name: "escaping_default_allow_utf8", + Description: fmt.Sprintf("OpenMetrics %s MUST default to allow-utf-8 when no escaping parameter is specified in Accept", v), + RFCLevel: compliance.MustLevel, + Version: v, + Request: ScrapeRequest{ + Accept: fmt.Sprintf("application/openmetrics-text; version=%s", v), + }, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "preserves_utf8_names_by_default", + Description: "Without an explicit escaping parameter in Accept, OpenMetrics 2.0 MUST preserve UTF-8 metric and label names", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + mf := requireFamily(t, res, "http.server.active_requests") + m := findMetricWithLabels(mf, map[string]string{"service.name": "demo-api"}) + require.NotNil(t, m, "Expected UTF-8 series http.server.active_requests{service.name=\"demo-api\"} by default in OpenMetrics 2.0") + }, + }, + }, + }) + } + + return tests +} diff --git a/openmetrics/exemplars.go b/openmetrics/exemplars.go new file mode 100644 index 00000000..3d404307 --- /dev/null +++ b/openmetrics/exemplars.go @@ -0,0 +1,151 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openmetrics + +import ( + "fmt" + "testing" + + dto "github.com/prometheus/client_model/go" + "github.com/prometheus/compliance" + "github.com/stretchr/testify/require" +) + +const om1ExemplarMaxRunes = 128 + +func exemplarsTests(v Version) []Test { + isOM2 := v == Version2_0_0 || v == Version2_0_0RC + + validateCases := []compliance.ValidateCase[ScrapeResult]{ + { + Name: "counter_exemplar_present", + Description: "Counters observed with exemplars SHOULD include a valid exemplar with trace_id label, value, and timestamp", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + mf := requireFamily(t, res, "http_requests_total", "http_requests") + m := findMetricWithLabels(mf, map[string]string{"method": "GET", "status": "200"}) + require.NotNil(t, m) + + ex := m.GetCounter().GetExemplar() + require.NotNil(t, ex, "Expected exemplar on counter series http_requests{method=\"GET\",status=\"200\"}") + lbls := labelMap(ex.Label) + require.Equal(t, "4bf92f3577b34da6a3ce929d0e0e4736", lbls["trace_id"]) + require.Equal(t, "00f067aa0ba902b7", lbls["span_id"]) + require.Positive(t, ex.GetValue()) + require.NotNil(t, ex.GetTimestamp(), "Exemplar SHOULD include a timestamp") + }, + }, + { + Name: "histogram_exemplar_present", + Description: "Histograms observed with exemplars SHOULD include a valid exemplar on a bucket (OM 1.0) or composite sample (OM 2.0)", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + mf := requireFamily(t, res, "http_request_duration_seconds") + require.NotEmpty(t, mf.Metric) + h := mf.Metric[0].GetHistogram() + require.NotNil(t, h) + + var found *dto.Exemplar + if isOM2 { + if len(h.Exemplars) > 0 { + found = h.Exemplars[0] + } + } else { + for _, b := range h.Bucket { + if b.GetExemplar() != nil { + found = b.GetExemplar() + break + } + } + } + require.NotNil(t, found, "Expected exemplar on histogram http_request_duration_seconds") + lbls := labelMap(found.Label) + require.Equal(t, "4bf92f3577b34da6a3ce929d0e0e4736", lbls["trace_id"]) + require.Positive(t, found.GetValue()) + }, + }, + } + + if isOM2 { + validateCases = append(validateCases, compliance.ValidateCase[ScrapeResult]{ + Name: "exemplar_extended_labels_over_128_runes", + Description: "OpenMetrics 2.0 exporters SHOULD preserve exemplar label sets exceeding 128 runes", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + sizeCounter := requireFamily(t, res, "http_request_size_bytes_total", "http_request_size_bytes") + require.NotEmpty(t, sizeCounter.Metric) + ex := sizeCounter.Metric[0].GetCounter().GetExemplar() + require.NotNil(t, ex) + require.Greater(t, exemplarLabelRunes(ex), om1ExemplarMaxRunes, + "Expected OpenMetrics 2.0 exemplar to preserve >128 runes") + lbls := labelMap(ex.Label) + require.NotEmpty(t, lbls["attr_big"], "Expected extended exemplar attribute attr_big to be preserved in OpenMetrics 2.0") + }, + }) + } else { + validateCases = append(validateCases, + compliance.ValidateCase[ScrapeResult]{ + Name: "exemplar_label_runes_within_spec_limit", + Description: "Exemplar label sets MUST NOT exceed 128 UTF-8 runes in OpenMetrics 1.0", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + for _, mf := range res.OrderedFamilies { + for _, m := range mf.Metric { + if ex := m.GetCounter().GetExemplar(); ex != nil { + require.LessOrEqualf(t, exemplarLabelRunes(ex), om1ExemplarMaxRunes, + "Counter %q exemplar label runes MUST be <= %d", mf.GetName(), om1ExemplarMaxRunes) + } + for _, b := range m.GetHistogram().GetBucket() { + if ex := b.GetExemplar(); ex != nil { + require.LessOrEqualf(t, exemplarLabelRunes(ex), om1ExemplarMaxRunes, + "Histogram %q bucket exemplar label runes MUST be <= %d", mf.GetName(), om1ExemplarMaxRunes) + } + } + } + } + }, + }, + compliance.ValidateCase[ScrapeResult]{ + Name: "exemplar_truncated_retains_trace_id", + Description: "OpenMetrics 1.0 exporters SHOULD truncate oversized non-trace exemplar labels to stay within 128 runes while retaining trace_id", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + sizeCounter := requireFamily(t, res, "http_request_size_bytes_total", "http_request_size_bytes") + require.NotEmpty(t, sizeCounter.Metric) + ex := sizeCounter.Metric[0].GetCounter().GetExemplar() + require.NotNil(t, ex, "Expected exemplar on http_request_size_bytes counter") + lbls := labelMap(ex.Label) + require.Equal(t, "4bf92f3577b34da6a3ce929d0e0e4736", lbls["trace_id"], "trace_id SHOULD be retained on exemplar") + require.LessOrEqual(t, exemplarLabelRunes(ex), om1ExemplarMaxRunes) + require.NotContains(t, lbls, "attr_big", "OpenMetrics 1.0 exemplar SHOULD truncate oversized label pairs to stay <= 128 runes") + }, + }, + ) + } + + return []Test{ + { + Name: "exemplars", + Description: fmt.Sprintf("Exporters MUST emit valid exemplars conforming to OpenMetrics %s rune limits and timestamp rules", v), + RFCLevel: compliance.MustLevel, + Version: v, + ValidateCases: validateCases, + }, + } +} diff --git a/openmetrics/helpers.go b/openmetrics/helpers.go new file mode 100644 index 00000000..5e75837c --- /dev/null +++ b/openmetrics/helpers.go @@ -0,0 +1,137 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openmetrics + +import ( + "strings" + "testing" + "unicode/utf8" + + dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" +) + +// findFamily returns the first decoded MetricFamily matching one of the candidate names, or nil. +func findFamily(res ScrapeResult, names ...string) *dto.MetricFamily { + for _, n := range names { + if mf, ok := res.Families[n]; ok { + return mf + } + } + return nil +} + +// requireFamily asserts that at least one of the candidate MetricFamily names exists in res. +func requireFamily(t *testing.T, res ScrapeResult, names ...string) *dto.MetricFamily { + t.Helper() + mf := findFamily(res, names...) + require.NotNilf(t, mf, "expected one of metric families %v in scraped families (found %d families)", names, len(res.Families)) + return mf +} + +// familiesByType returns all decoded MetricFamilies in wire order that have the given MetricType. +func familiesByType(res ScrapeResult, mt dto.MetricType) []*dto.MetricFamily { + var out []*dto.MetricFamily + for _, mf := range res.OrderedFamilies { + if mf.GetType() == mt { + out = append(out, mf) + } + } + return out +} + +// labelMap converts a slice of dto.LabelPair into a map of label name to value. +func labelMap(pairs []*dto.LabelPair) map[string]string { + m := make(map[string]string, len(pairs)) + for _, lp := range pairs { + m[lp.GetName()] = lp.GetValue() + } + return m +} + +// findMetricWithLabels returns the first Metric in mf whose labels match all entries in want. +func findMetricWithLabels(mf *dto.MetricFamily, want map[string]string) *dto.Metric { + if mf == nil { + return nil + } + for _, m := range mf.Metric { + got := labelMap(m.Label) + matched := true + for k, v := range want { + if got[k] != v { + matched = false + break + } + } + if matched { + return m + } + } + return nil +} + +// exemplarLabelRunes returns the total number of UTF-8 runes across all label names and values in e. +func exemplarLabelRunes(e *dto.Exemplar) int { + if e == nil { + return 0 + } + total := 0 + for _, lp := range e.Label { + total += utf8.RuneCountInString(lp.GetName()) + total += utf8.RuneCountInString(lp.GetValue()) + } + return total +} + +var openMetricsSampleSuffixes = []string{ + "_total", + "_created", + "_bucket", + "_sum", + "_count", + "_gsum", + "_gcount", + "_info", +} + +// sampleLinesForFamily returns all sample lines in body belonging to familyName. +func sampleLinesForFamily(body []byte, familyName string) []string { + var out []string + quotedPrefix := `"` + familyName + `"` + braceQuotedPrefix := `{"` + familyName + `"` + for line := range strings.SplitSeq(string(body), "\n") { + if line == "" || strings.HasPrefix(line, "#") { + continue + } + if hasSampleMetricPrefix(line, familyName) || + strings.HasPrefix(line, quotedPrefix) || + strings.HasPrefix(line, braceQuotedPrefix) { + out = append(out, line) + } + } + return out +} + +func hasSampleMetricPrefix(line, familyName string) bool { + if strings.HasPrefix(line, familyName+" ") || strings.HasPrefix(line, familyName+"{") { + return true + } + for _, suf := range openMetricsSampleSuffixes { + withSuf := familyName + suf + if strings.HasPrefix(line, withSuf+" ") || strings.HasPrefix(line, withSuf+"{") { + return true + } + } + return false +} diff --git a/openmetrics/helpers_test.go b/openmetrics/helpers_test.go new file mode 100644 index 00000000..03d7766c --- /dev/null +++ b/openmetrics/helpers_test.go @@ -0,0 +1,65 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openmetrics + +import ( + "testing" + + dto "github.com/prometheus/client_model/go" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/proto" +) + +func TestHelpers(t *testing.T) { + mfCounter := &dto.MetricFamily{ + Name: proto.String("http_requests_total"), + Type: dto.MetricType_COUNTER.Enum(), + Metric: []*dto.Metric{ + { + Label: []*dto.LabelPair{ + {Name: proto.String("method"), Value: proto.String("GET")}, + {Name: proto.String("status"), Value: proto.String("200")}, + }, + Counter: &dto.Counter{Value: proto.Float64(5)}, + }, + }, + } + res := ScrapeResult{ + Families: map[string]*dto.MetricFamily{ + "http_requests_total": mfCounter, + }, + OrderedFamilies: []*dto.MetricFamily{mfCounter}, + } + + require.Equal(t, mfCounter, findFamily(res, "http_requests", "http_requests_total")) + require.Nil(t, findFamily(res, "missing_metric")) + require.Len(t, familiesByType(res, dto.MetricType_COUNTER), 1) + require.Empty(t, familiesByType(res, dto.MetricType_GAUGE)) + + m := findMetricWithLabels(mfCounter, map[string]string{"method": "GET", "status": "200"}) + require.NotNil(t, m) + require.Nil(t, findMetricWithLabels(mfCounter, map[string]string{"method": "POST"})) + + ex := &dto.Exemplar{ + Label: []*dto.LabelPair{ + {Name: proto.String("trace_id"), Value: proto.String("abc")}, + {Name: proto.String("utf8"), Value: proto.String("🚀")}, + }, + } + require.Equal(t, len("trace_id")+len("abc")+len("utf8")+1, exemplarLabelRunes(ex)) + + body := []byte("# TYPE http_requests counter\nhttp_requests_total{method=\"GET\"} 5\nhttp_requests_in_flight 2\n\"http.active\"{\"k\"=\"v\"} 1\n# EOF\n") + require.Equal(t, []string{`http_requests_total{method="GET"} 5`}, sampleLinesForFamily(body, "http_requests")) + require.Equal(t, []string{`"http.active"{"k"="v"} 1`}, sampleLinesForFamily(body, "http.active")) +} diff --git a/openmetrics/histograms.go b/openmetrics/histograms.go new file mode 100644 index 00000000..f63da48e --- /dev/null +++ b/openmetrics/histograms.go @@ -0,0 +1,166 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openmetrics + +import ( + "fmt" + "math" + "testing" + + dto "github.com/prometheus/client_model/go" + "github.com/prometheus/compliance" + "github.com/stretchr/testify/require" +) + +func histogramsTests(v Version) []Test { + isOM2 := v == Version2_0_0 || v == Version2_0_0RC + + tests := []Test{ + { + Name: "histograms", + Description: fmt.Sprintf("Exporters MUST emit valid classic/composite histograms in OpenMetrics %s", v), + RFCLevel: compliance.MustLevel, + Version: v, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "cumulative_buckets_monotonic_and_inf_matches_count", + Description: "Histogram classic buckets MUST have strictly increasing upper bounds, monotonically non-decreasing cumulative counts, and +Inf matching sample_count", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + mf := requireFamily(t, res, "http_request_duration_seconds") + require.Equal(t, dto.MetricType_HISTOGRAM, mf.GetType()) + require.NotEmpty(t, mf.Metric) + + for _, m := range mf.Metric { + h := m.GetHistogram() + require.NotNil(t, h) + require.NotEmpty(t, h.Bucket, "Expected classic histogram buckets on http_request_duration_seconds") + + var prevBound float64 + var prevCount uint64 + for i, b := range h.Bucket { + ub := b.GetUpperBound() + if i > 0 { + require.Greater(t, ub, prevBound, "Bucket upper bounds MUST be strictly increasing") + require.GreaterOrEqual(t, b.GetCumulativeCount(), prevCount, "Cumulative bucket counts MUST be monotonically non-decreasing") + } + prevBound = ub + prevCount = b.GetCumulativeCount() + } + + lastBucket := h.Bucket[len(h.Bucket)-1] + require.True(t, math.IsInf(lastBucket.GetUpperBound(), +1), "Last classic bucket MUST be +Inf") + require.Equal(t, h.GetSampleCount(), lastBucket.GetCumulativeCount(), "+Inf bucket count MUST equal sample_count") + } + }, + }, + { + Name: "histogram_start_timestamp", + Description: "Histogram series SHOULD include a valid start/created timestamp (_created line in OM 1.0, inline st@ in OM 2.0)", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + mf := requireFamily(t, res, "http_request_duration_seconds") + for _, m := range mf.Metric { + ct := m.GetHistogram().GetCreatedTimestamp() + require.NotNil(t, ct, "Histogram series SHOULD include a CreatedTimestamp") + require.NoError(t, ct.CheckValid()) + require.Positive(t, ct.AsTime().UnixNano()) + } + if isOM2 { + lines := sampleLinesForFamily(res.Body, "http_request_duration_seconds") + require.NotEmpty(t, lines) + for _, line := range lines { + require.Contains(t, line, " st@", "OpenMetrics 2.0 histogram SHOULD include inline st@ start timestamp") + } + } + }, + }, + { + Name: "histogram_wire_representation", + Description: "Histograms MUST use multi-line _bucket/_sum/_count in OM 1.0 and single-line composite values in OM 2.0", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + mf := requireFamily(t, res, "http_request_duration_seconds") + lines := sampleLinesForFamily(res.Body, "http_request_duration_seconds") + require.NotEmpty(t, lines) + if isOM2 { + require.Len(t, lines, len(mf.Metric), "OpenMetrics 2.0 histogram MUST emit one composite sample line per series") + for _, line := range lines { + require.Contains(t, line, "{count:", "OpenMetrics 2.0 histogram MUST use composite {count:...,sum:...} format") + require.Contains(t, line, ",sum:") + require.Contains(t, line, ",bucket:[") + } + } else { + require.Greater(t, len(lines), 3*len(mf.Metric), "OpenMetrics 1.0 histogram MUST emit multiple _bucket, _sum, and _count lines") + require.Contains(t, string(res.Body), "http_request_duration_seconds_bucket{") + require.Contains(t, string(res.Body), "http_request_duration_seconds_sum") + require.Contains(t, string(res.Body), "http_request_duration_seconds_count") + } + }, + }, + }, + }, + } + + if isOM2 { + tests = append(tests, Test{ + Name: "native_histograms", + Description: "OpenMetrics 2.0 exporters SHOULD support native histogram spans and bucket deltas in composite histogram values", + RFCLevel: compliance.ShouldLevel, + Version: v, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "native_schema_and_spans_valid", + Description: "Native histograms MUST have schema in [-4, 8], non-negative zero_threshold, and span bucket totals matching sample_count", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + mf := requireFamily(t, res, "http_request_duration_seconds") + require.NotEmpty(t, mf.Metric) + + m := mf.Metric[0] + h := m.GetHistogram() + require.NotNil(t, h.Schema, "Expected native histogram Schema on http_request_duration_seconds in OpenMetrics 2.0") + require.GreaterOrEqual(t, h.GetSchema(), int32(-4), "Native histogram schema MUST be >= -4") + require.LessOrEqual(t, h.GetSchema(), int32(8), "Native histogram schema MUST be <= 8") + require.GreaterOrEqual(t, h.GetZeroThreshold(), 0.0, "Native histogram zero_threshold MUST be >= 0") + require.NotEmpty(t, h.PositiveSpan, "Expected positive native histogram spans") + require.NotEmpty(t, h.PositiveDelta, "Expected positive native histogram bucket deltas") + + var totalBuckets uint64 + var cur int64 + for _, d := range h.PositiveDelta { + cur += d + require.GreaterOrEqual(t, cur, int64(0), "Native histogram bucket count MUST be non-negative") + totalBuckets += uint64(cur) + } + cur = 0 + for _, d := range h.NegativeDelta { + cur += d + require.GreaterOrEqual(t, cur, int64(0), "Native histogram bucket count MUST be non-negative") + totalBuckets += uint64(cur) + } + require.Equal(t, h.GetSampleCount(), h.GetZeroCount()+totalBuckets, + "Native histogram zero_count plus bucket counts MUST equal sample_count") + }, + }, + }, + }) + } + + return tests +} diff --git a/openmetrics/metadata.go b/openmetrics/metadata.go new file mode 100644 index 00000000..f58987c6 --- /dev/null +++ b/openmetrics/metadata.go @@ -0,0 +1,179 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openmetrics + +import ( + "fmt" + "strings" + "testing" + + "github.com/prometheus/compliance" + "github.com/stretchr/testify/require" +) + +func metadataTests(v Version) []Test { + unitSuffixLevel := compliance.MustLevel + if v == Version2_0_0 || v == Version2_0_0RC { + unitSuffixLevel = compliance.ShouldLevel + } + + return []Test{ + { + Name: "metadata", + Description: fmt.Sprintf("Exporters MUST emit valid # TYPE, # HELP, and # UNIT descriptors before samples in OpenMetrics %s", v), + RFCLevel: compliance.MustLevel, + Version: v, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "descriptors_before_samples_and_unique", + Description: "Descriptor lines (# TYPE, # HELP, # UNIT) MUST appear before any samples for a metric family and at most once per family", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr, "ABNF and descriptor ordering validation MUST succeed") + require.NotEmpty(t, res.OrderedFamilies) + + seenType := make(map[string]bool) + seenHelp := make(map[string]bool) + seenUnit := make(map[string]bool) + for line := range strings.SplitSeq(string(res.Body), "\n") { + switch { + case strings.HasPrefix(line, "# TYPE "): + rest := strings.TrimPrefix(line, "# TYPE ") + name, _, ok := cutDescriptorMetricName(rest) + require.True(t, ok, "Malformed # TYPE line: %q", line) + require.False(t, seenType[name], "Duplicate # TYPE line for %q", name) + seenType[name] = true + case strings.HasPrefix(line, "# HELP "): + rest := strings.TrimPrefix(line, "# HELP ") + name, _, ok := cutDescriptorMetricName(rest) + require.True(t, ok, "Malformed # HELP line: %q", line) + require.False(t, seenHelp[name], "Duplicate # HELP line for %q", name) + seenHelp[name] = true + case strings.HasPrefix(line, "# UNIT "): + rest := strings.TrimPrefix(line, "# UNIT ") + name, _, ok := cutDescriptorMetricName(rest) + require.True(t, ok, "Malformed # UNIT line: %q", line) + require.False(t, seenUnit[name], "Duplicate # UNIT line for %q", name) + seenUnit[name] = true + } + } + }, + }, + { + Name: "type_descriptor_present", + Description: "Metric families SHOULD include a # TYPE descriptor", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + require.NotEmpty(t, res.OrderedFamilies) + seenType := make(map[string]bool) + for line := range strings.SplitSeq(string(res.Body), "\n") { + if rest, ok := strings.CutPrefix(line, "# TYPE "); ok { + if name, _, ok := cutDescriptorMetricName(rest); ok { + seenType[name] = true + } + } + } + for _, mf := range res.OrderedFamilies { + name := mf.GetName() + baseName := strings.TrimSuffix(name, "_total") + require.Truef(t, seenType[name] || seenType[baseName], + "MetricFamily %q SHOULD include a # TYPE descriptor", name) + } + }, + }, + { + Name: "help_descriptor_present", + Description: "Metric families SHOULD include a non-empty # HELP descriptor", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + require.NotEmpty(t, res.OrderedFamilies) + for _, mf := range res.OrderedFamilies { + require.NotEmptyf(t, mf.GetHelp(), "MetricFamily %q SHOULD include a non-empty # HELP descriptor", mf.GetName()) + } + }, + }, + { + Name: "unit_descriptor_present", + Description: "Metric families with units SHOULD include a # UNIT descriptor", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + require.NotEmpty(t, res.OrderedFamilies) + foundUnit := false + for _, mf := range res.OrderedFamilies { + if mf.GetUnit() != "" { + foundUnit = true + break + } + } + require.True(t, foundUnit, "Exposition SHOULD include at least one metric family with a # UNIT descriptor") + }, + }, + { + Name: "unit_suffix_matches_unit_descriptor", + Description: "When # UNIT is specified, the metric family name MUST end with _ in OpenMetrics 1.0 (SHOULD in OpenMetrics 2.0)", + RFCLevel: unitSuffixLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + require.NotEmpty(t, res.OrderedFamilies) + for _, mf := range res.OrderedFamilies { + unit := mf.GetUnit() + if unit == "" { + continue + } + baseName := strings.TrimSuffix(mf.GetName(), "_total") + require.Truef(t, strings.HasSuffix(baseName, "_"+unit), + "MetricFamily %q with unit %q must have base name ending with _%s", mf.GetName(), unit, unit) + } + }, + }, + }, + }, + } +} + +// cutDescriptorMetricName extracts the metric family name and remaining text from a +// # TYPE, # HELP, or # UNIT descriptor line after the keyword prefix, supporting both +// unquoted legacy names and quoted UTF-8 metric family names that may contain spaces. +func cutDescriptorMetricName(rest string) (name, tail string, ok bool) { + if !strings.HasPrefix(rest, "\"") { + return strings.Cut(rest, " ") + } + var sb strings.Builder + for i := 1; i < len(rest); i++ { + switch rest[i] { + case '\\': + i++ + if i >= len(rest) { + return "", "", false + } + switch rest[i] { + case 'n': + sb.WriteByte('\n') + default: + sb.WriteByte(rest[i]) + } + case '"': + if i+1 >= len(rest) || rest[i+1] != ' ' { + return "", "", false + } + return sb.String(), rest[i+2:], true + default: + sb.WriteByte(rest[i]) + } + } + return "", "", false +} diff --git a/openmetrics/protocol.go b/openmetrics/protocol.go new file mode 100644 index 00000000..18964cda --- /dev/null +++ b/openmetrics/protocol.go @@ -0,0 +1,169 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openmetrics + +import ( + "bytes" + "fmt" + "net/http" + "strings" + "testing" + + "github.com/prometheus/common/expfmt" + "github.com/prometheus/compliance" + "github.com/stretchr/testify/require" +) + +// gzipMagicHeader is the 2-byte magic number at the start of a gzip stream (RFC 1952). +var gzipMagicHeader = []byte{0x1f, 0x8b} + +func protocolTests(v Version) []Test { + tests := []Test{ + { + Name: "content_negotiation", + Description: fmt.Sprintf("Exporters MUST negotiate OpenMetrics %s when requested via the Accept header", v), + RFCLevel: compliance.MustLevel, + Version: v, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "http_status_ok", + Description: "Exporters MUST respond with HTTP 200 OK to a valid scrape request", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.Equal(t, http.StatusOK, res.StatusCode, "HTTP status code MUST be 200 OK") + }, + }, + { + Name: "content_type_media_type", + Description: "Exporters MUST respond with Content-Type media type application/openmetrics-text", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NotEmpty(t, res.ContentType, "Content-Type header MUST be present") + require.NoError(t, res.MediaParseErr, "Content-Type header MUST be a valid MIME media type") + require.Equal(t, expfmt.OpenMetricsType, res.MediaType, "Media type MUST be application/openmetrics-text") + }, + }, + { + Name: "content_type_version_param", + Description: fmt.Sprintf("Exporters MUST include version=%s in the Content-Type header", v), + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.MediaParseErr) + require.Equal(t, string(v), res.MediaParams["version"], "Content-Type version parameter MUST be %q", v) + }, + }, + { + Name: "content_type_charset_utf8", + Description: "Exporters MUST include charset=utf-8 in the Content-Type header", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.MediaParseErr) + require.Equal(t, "utf-8", strings.ToLower(res.MediaParams["charset"]), "Content-Type charset parameter MUST be utf-8") + }, + }, + }, + }, + { + Name: "negotiation_quality_priority", + Description: "Exporters MUST honor Accept quality values (q=) when selecting the exposition format", + RFCLevel: compliance.MustLevel, + Version: v, + Request: ScrapeRequest{ + Accept: fmt.Sprintf("text/plain;version=0.0.4;q=0.4, application/openmetrics-text;version=%s;q=0.9, */*;q=0.1", v), + }, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "selects_highest_q_openmetrics_version", + Description: fmt.Sprintf("Exporters MUST select OpenMetrics %s when it has a higher q= priority than text/plain", v), + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.Equal(t, http.StatusOK, res.StatusCode) + require.NoError(t, res.MediaParseErr) + require.Equal(t, expfmt.OpenMetricsType, res.MediaType) + require.Equal(t, string(v), res.MediaParams["version"]) + }, + }, + { + Name: "payload_valid_abnf", + Description: "Negotiated response MUST decode without ABNF syntax or semantic errors", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + require.NotEmpty(t, res.OrderedFamilies) + }, + }, + }, + }, + { + Name: "compression_gzip", + Description: "Exporters SHOULD support gzip compression when Accept-Encoding: gzip is sent", + RFCLevel: compliance.ShouldLevel, + Version: v, + Request: ScrapeRequest{ + AcceptEncoding: "gzip", + }, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "content_encoding_gzip", + Description: "Exporters SHOULD return Content-Encoding: gzip and a valid gzip stream when requested", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.Equal(t, http.StatusOK, res.StatusCode) + require.Equal(t, "gzip", res.Headers.Get("Content-Encoding"), "Content-Encoding header SHOULD be gzip") + require.True(t, bytes.HasPrefix(res.RawBody, gzipMagicHeader), "Raw response body MUST start with gzip magic header 0x1f8b") + require.NoError(t, res.DecompressErr, "Response body MUST be a valid gzip stream") + }, + }, + { + Name: "decompressed_payload_valid", + Description: "Decompressed gzip payload MUST be valid OpenMetrics exposition", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.DecompressErr) + require.NoError(t, res.ParseErr) + require.NotEmpty(t, res.OrderedFamilies) + }, + }, + }, + }, + } + + if v == Version2_0_0 { + tests = append(tests, Test{ + Name: "negotiation_rc_version", + Description: "OpenMetrics 2.0 exporters SHOULD also accept version=2.0.0-rc during the release candidate transition", + RFCLevel: compliance.ShouldLevel, + Version: v, + Request: ScrapeRequest{ + Accept: "application/openmetrics-text; version=2.0.0-rc; escaping=allow-utf-8", + }, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "negotiates_2_0_0_rc", + Description: "Exporters SHOULD negotiate version=2.0.0-rc when explicitly requested", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.Equal(t, http.StatusOK, res.StatusCode) + require.NoError(t, res.MediaParseErr) + require.Equal(t, expfmt.OpenMetricsType, res.MediaType) + require.Equal(t, expfmt.OpenMetricsVersion_2_0_0_rc, res.MediaParams["version"]) + require.NoError(t, res.ParseErr) + }, + }, + }, + }) + } + + return tests +} diff --git a/openmetrics/samples.go b/openmetrics/samples.go new file mode 100644 index 00000000..0c431fbd --- /dev/null +++ b/openmetrics/samples.go @@ -0,0 +1,193 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openmetrics + +import ( + "fmt" + "math" + "strings" + "testing" + + dto "github.com/prometheus/client_model/go" + "github.com/prometheus/compliance" + "github.com/stretchr/testify/require" +) + +func samplesTests(v Version) []Test { + isOM2 := v == Version2_0_0 || v == Version2_0_0RC + + return []Test{ + { + Name: "counters", + Description: fmt.Sprintf("Exporters MUST emit valid non-negative counter samples and start timestamps in OpenMetrics %s", v), + RFCLevel: compliance.MustLevel, + Version: v, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "counter_values_non_negative", + Description: "Counter values MUST be non-NaN and non-negative (>= 0)", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + counters := familiesByType(res, dto.MetricType_COUNTER) + require.NotEmpty(t, counters, "Exposition MUST contain at least one counter metric family") + for _, mf := range counters { + for _, m := range mf.Metric { + require.NotNilf(t, m.Counter, "Metric in counter family %q must have Counter field", mf.GetName()) + val := m.GetCounter().GetValue() + require.Falsef(t, math.IsNaN(val), "Counter %q value MUST NOT be NaN", mf.GetName()) + require.GreaterOrEqualf(t, val, 0.0, "Counter %q value MUST be non-negative", mf.GetName()) + } + } + + reqCounter := requireFamily(t, res, "http_requests_total", "http_requests") + mGet := findMetricWithLabels(reqCounter, map[string]string{"method": "GET", "status": "200"}) + require.NotNil(t, mGet, "Expected counter series with method=GET, status=200") + require.GreaterOrEqual(t, mGet.GetCounter().GetValue(), 5.0) + }, + }, + { + Name: "counter_start_timestamp", + Description: "Counter series SHOULD include a valid start/created timestamp (_created line in OM 1.0, inline st@ in OM 2.0)", + RFCLevel: compliance.ShouldLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + reqCounter := requireFamily(t, res, "http_requests_total", "http_requests") + for _, m := range reqCounter.Metric { + ct := m.GetCounter().GetCreatedTimestamp() + require.NotNilf(t, ct, "Counter %q series SHOULD include a CreatedTimestamp", reqCounter.GetName()) + require.NoError(t, ct.CheckValid()) + require.Positive(t, ct.AsTime().UnixNano()) + } + + base := strings.TrimSuffix(reqCounter.GetName(), "_total") + if isOM2 { + lines := sampleLinesForFamily(res.Body, reqCounter.GetName()) + require.NotEmpty(t, lines) + for _, l := range lines { + require.Contains(t, l, " st@", "OpenMetrics 2.0 counter sample line SHOULD contain inline st@ start timestamp") + } + require.NotContains(t, string(res.Body), base+"_created", "OpenMetrics 2.0 MUST NOT emit separate _created lines") + } else { + require.Contains(t, string(res.Body), base+"_created", "OpenMetrics 1.0 counter SHOULD emit _created lines") + } + }, + }, + }, + }, + { + Name: "gauges", + Description: fmt.Sprintf("Exporters MUST emit valid gauge samples in OpenMetrics %s", v), + RFCLevel: compliance.MustLevel, + Version: v, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "gauge_values_valid", + Description: "Gauge metric families MUST contain valid float sample values and expected label sets", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + gauges := familiesByType(res, dto.MetricType_GAUGE) + require.NotEmpty(t, gauges, "Exposition MUST contain at least one gauge metric family") + for _, mf := range gauges { + require.NotEmptyf(t, mf.Metric, "Gauge family %q must contain at least one metric", mf.GetName()) + for _, m := range mf.Metric { + require.NotNilf(t, m.Gauge, "Metric in gauge family %q must have Gauge field", mf.GetName()) + require.NotNilf(t, m.GetGauge().Value, "Gauge %q must have an explicit sample value", mf.GetName()) + } + } + + inFlight := requireFamily(t, res, "http.server.active_requests", "http_server_active_requests") + require.InDelta(t, 3.0, inFlight.Metric[0].GetGauge().GetValue(), 1e-6) + }, + }, + }, + }, + { + Name: "summaries", + Description: fmt.Sprintf("Exporters MUST emit valid summary metrics in OpenMetrics %s", v), + RFCLevel: compliance.MustLevel, + Version: v, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "summary_count_and_sum_non_negative", + Description: "Summary sample_count and sample_sum MUST be non-negative and not NaN", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + mf := requireFamily(t, res, "rpc_latency_seconds") + require.Equal(t, dto.MetricType_SUMMARY, mf.GetType()) + require.NotEmpty(t, mf.Metric) + for _, m := range mf.Metric { + s := m.GetSummary() + require.NotNil(t, s) + require.Positive(t, s.GetSampleCount(), "Summary count should be positive") + require.False(t, math.IsNaN(s.GetSampleSum()), "Summary sum MUST NOT be NaN") + require.GreaterOrEqual(t, s.GetSampleSum(), 0.0, "Summary sum MUST be non-negative") + } + }, + }, + { + Name: "summary_quantiles_valid_and_sorted", + Description: "Summary quantiles MUST be in [0.0, 1.0], sorted in strictly increasing order, with non-negative values", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + mf := requireFamily(t, res, "rpc_latency_seconds") + for _, m := range mf.Metric { + s := m.GetSummary() + require.NotEmpty(t, s.Quantile, "Summary should expose configured quantiles") + prevQ := -1.0 + for _, q := range s.Quantile { + qv := q.GetQuantile() + require.GreaterOrEqual(t, qv, 0.0, "Quantile MUST be >= 0.0") + require.LessOrEqual(t, qv, 1.0, "Quantile MUST be <= 1.0") + require.Greater(t, qv, prevQ, "Quantiles MUST be strictly increasing") + prevQ = qv + + val := q.GetValue() + if !math.IsNaN(val) { + require.GreaterOrEqual(t, val, 0.0, "Summary quantile value MUST NOT be negative") + } + } + } + }, + }, + { + Name: "summary_wire_representation", + Description: "Summaries MUST use multi-line representation in OM 1.0 and single-line composite values in OM 2.0", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr) + mf := requireFamily(t, res, "rpc_latency_seconds") + lines := sampleLinesForFamily(res.Body, "rpc_latency_seconds") + require.NotEmpty(t, lines) + if isOM2 { + require.Len(t, lines, len(mf.Metric), "OpenMetrics 2.0 summary MUST emit one composite sample line per series") + for _, line := range lines { + require.Contains(t, line, "{count:", "OpenMetrics 2.0 summary MUST use composite {count:...,sum:...,quantile:[...]} format") + require.Contains(t, line, ",sum:") + require.Contains(t, line, ",quantile:[") + } + } else { + require.Greater(t, len(lines), len(mf.Metric), "OpenMetrics 1.0 summary MUST use multiple sample lines (_sum, _count, quantile)") + require.Contains(t, string(res.Body), "rpc_latency_seconds_sum") + require.Contains(t, string(res.Body), "rpc_latency_seconds_count") + } + }, + }, + }, + }, + } +} diff --git a/openmetrics/syntax.go b/openmetrics/syntax.go new file mode 100644 index 00000000..5c2a630d --- /dev/null +++ b/openmetrics/syntax.go @@ -0,0 +1,97 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openmetrics + +import ( + "bytes" + "fmt" + "strings" + "testing" + "unicode/utf8" + + "github.com/prometheus/compliance" + "github.com/stretchr/testify/require" +) + +func syntaxTests(v Version) []Test { + return []Test{ + { + Name: "syntax", + Description: fmt.Sprintf("Exporters MUST emit valid UTF-8, LF-delimited OpenMetrics %s text conforming to the ABNF grammar", v), + RFCLevel: compliance.MustLevel, + Version: v, + ValidateCases: []compliance.ValidateCase[ScrapeResult]{ + { + Name: "non_empty_exposition", + Description: "Exposition payload MUST NOT be empty and MUST at least contain # EOF", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NotEmpty(t, res.Body, "Exposition payload MUST NOT be empty") + }, + }, + { + Name: "valid_utf8", + Description: "Exposition payload MUST be valid UTF-8", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.True(t, utf8.Valid(res.Body), "Exposition payload MUST be valid UTF-8") + }, + }, + { + Name: "line_endings_lf_only", + Description: "Lines MUST use LF (\\n) line endings and MUST NOT use CRLF (\\r\\n)", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.False(t, bytes.Contains(res.Body, []byte("\r\n")), "Exposition MUST NOT contain CRLF (\\r\\n) line endings") + }, + }, + { + Name: "no_blank_lines", + Description: "Exposition MUST NOT contain empty lines", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + trimmed := strings.TrimSuffix(string(res.Body), "\n") + for i, line := range strings.Split(trimmed, "\n") { + require.NotEmptyf(t, line, "Line %d MUST NOT be empty", i+1) + } + }, + }, + { + Name: "ends_with_eof", + Description: "Exposition MUST end with # EOF and MUST NOT have trailing data after # EOF", + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + trimmed := strings.TrimSuffix(string(res.Body), "\n") + require.True(t, trimmed == "# EOF" || strings.HasSuffix(trimmed, "\n# EOF"), + "Exposition MUST end with a standalone '# EOF' or '# EOF\\n' line") + lines := strings.Split(trimmed, "\n") + for i, line := range lines[:len(lines)-1] { + require.NotEqualf(t, "# EOF", line, + "Exposition MUST NOT have trailing data after '# EOF' at line %d", i+1) + } + }, + }, + { + Name: "abnf_grammar_and_semantics", + Description: fmt.Sprintf("Exposition MUST conform to the OpenMetrics %s ABNF grammar and semantic rules", v), + RFCLevel: compliance.MustLevel, + Validate: func(t *testing.T, res ScrapeResult) { + require.NoError(t, res.ParseErr, "Exposition MUST parse without ABNF or semantic errors") + require.NotEmpty(t, res.OrderedFamilies, "Exposition SHOULD contain at least one decoded MetricFamily") + }, + }, + }, + }, + } +} diff --git a/openmetrics/test_target.go b/openmetrics/test_target.go new file mode 100644 index 00000000..5b594b49 --- /dev/null +++ b/openmetrics/test_target.go @@ -0,0 +1,124 @@ +// Copyright The Prometheus Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package openmetrics + +import ( + "context" + "errors" + "fmt" + "net" + "net/http" + + "github.com/prometheus/compliance" +) + +// Target represents an OpenMetrics metric producer (SDK test application or exporter) under test. +// Target must expose an HTTP metrics endpoint at http://. +type Target = compliance.Target[Options] + +// Options represents the target configuration for an OpenMetrics compliance test run. +type Options struct { + // MetricsHostPort is the host:port address where the target must listen and serve metrics. + MetricsHostPort string + // MetricsPath is the HTTP path where metrics are served (e.g. "/metrics"). + MetricsPath string +} + +// Version specifies the OpenMetrics specification version under test. +type Version string + +const ( + // Version1_0_0 is the OpenMetrics 1.0.0 specification version. + Version1_0_0 Version = "1.0.0" + // Version2_0_0 is the OpenMetrics 2.0.0 specification version. + Version2_0_0 Version = "2.0.0" + // Version2_0_0RC is the OpenMetrics 2.0.0-rc specification version. + Version2_0_0RC Version = "2.0.0-rc" +) + +func (v Version) shortName() string { + switch v { + case Version1_0_0: + return "om1" + case Version2_0_0: + return "om2" + case Version2_0_0RC: + return "om2-rc" + default: + return string(v) + } +} + +// AcceptHeader returns the canonical OpenMetrics Accept header for this version +// and optional escaping scheme. +func (v Version) AcceptHeader(escaping string) string { + h := fmt.Sprintf("application/openmetrics-text; version=%s", v) + if escaping != "" { + h += fmt.Sprintf("; escaping=%s", escaping) + } + return h +} + +// RunCommand runs the given command with the given args until context is done. +// +// This is useful when starting process-based OpenMetrics exporter or SDK targets. +func RunCommand(ctx context.Context, dir string, extraEnvVars []string, prog string, args ...string) error { + return compliance.RunCommand(ctx, dir, extraEnvVars, prog, args...) +} + +type handlerTarget struct { + name string + handler http.Handler +} + +// NewHandlerTarget wraps an in-process http.Handler as an OpenMetrics compliance Target. +func NewHandlerTarget(name string, handler http.Handler) Target { + return &handlerTarget{ + name: name, + handler: handler, + } +} + +func (h *handlerTarget) Name() string { return h.name } + +func (h *handlerTarget) Run(ctx context.Context, opts Options) error { + mux := http.NewServeMux() + path := opts.MetricsPath + if path == "" { + path = "/metrics" + } + mux.Handle(path, h.handler) + + ln, err := net.Listen("tcp", opts.MetricsHostPort) + if err != nil { + return err + } + srv := &http.Server{Handler: mux} + errCh := make(chan error, 1) + go func() { + if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) { + errCh <- err + return + } + errCh <- nil + }() + + select { + case <-ctx.Done(): + _ = srv.Close() + return <-errCh + case err := <-errCh: + return err + } +} diff --git a/promql/comparer/comparer.go b/promql/comparer/comparer.go index dba83fd9..3c763666 100644 --- a/promql/comparer/comparer.go +++ b/promql/comparer/comparer.go @@ -22,9 +22,9 @@ const ( // PromAPI allows running instant and range queries against a Prometheus-compatible API. type PromAPI interface { // Query performs a query for the given time. - Query(ctx context.Context, query string, ts time.Time, opts ...v1.Option) (model.Value, v1.Warnings, error) + Query(ctx context.Context, query string, ts time.Time, opts ...v1.Option) (model.Value, v1.Warnings, v1.Infos, error) // QueryRange performs a query for the given range. - QueryRange(ctx context.Context, query string, r v1.Range, opts ...v1.Option) (model.Value, v1.Warnings, error) + QueryRange(ctx context.Context, query string, r v1.Range, opts ...v1.Option) (model.Value, v1.Warnings, v1.Infos, error) } // TestCase represents a fully expanded query to be tested. @@ -84,9 +84,9 @@ func (c *Comparer) Compare(tc *TestCase) (*Result, error) { Step: tc.Resolution, } - // TODO: Handle warnings (second, ignored return value). - refResult, _, refErr := c.refAPI.QueryRange(ctx, tc.Query, r) - testResult, _, testErr := c.testAPI.QueryRange(ctx, tc.Query, r) + // TODO: Handle warnings and infos (second and third ignored return values). + refResult, _, _, refErr := c.refAPI.QueryRange(ctx, tc.Query, r) + testResult, _, _, testErr := c.testAPI.QueryRange(ctx, tc.Query, r) if (refErr != nil) != tc.ShouldFail { if refErr != nil { diff --git a/promql/comparer/comparer_test.go b/promql/comparer/comparer_test.go index dd7b4b4a..3fe1c65e 100644 --- a/promql/comparer/comparer_test.go +++ b/promql/comparer/comparer_test.go @@ -31,12 +31,12 @@ type stubPromAPI struct { var _ PromAPI = (*stubPromAPI)(nil) -func (s *stubPromAPI) Query(context.Context, string, time.Time, ...v1.Option) (model.Value, v1.Warnings, error) { - return s.val, nil, s.err +func (s *stubPromAPI) Query(context.Context, string, time.Time, ...v1.Option) (model.Value, v1.Warnings, v1.Infos, error) { + return s.val, nil, nil, s.err } -func (s *stubPromAPI) QueryRange(context.Context, string, v1.Range, ...v1.Option) (model.Value, v1.Warnings, error) { - return s.val, nil, s.err +func (s *stubPromAPI) QueryRange(context.Context, string, v1.Range, ...v1.Option) (model.Value, v1.Warnings, v1.Infos, error) { + return s.val, nil, nil, s.err } func TestCompare_NativeHistograms(t *testing.T) { diff --git a/promql/compliance.go b/promql/compliance.go index 53adf5f0..94609a2d 100644 --- a/promql/compliance.go +++ b/promql/compliance.go @@ -211,7 +211,7 @@ func waitReplayerAndTarget(ctx context.Context, replayer *compliance.ScrapeServe defer ticker.Stop() for { - val, _, err := promAPI.Query(ctx, "count(demo_num_cpus)", end) + val, _, _, err := promAPI.Query(ctx, "count(demo_num_cpus)", end) if err == nil { if vec, ok := val.(model.Vector); ok && len(vec) == 1 && vec[0].Value == 3 { return nil diff --git a/promqle2e/promqle2e.go b/promqle2e/promqle2e.go index 717fe864..6ed252c4 100644 --- a/promqle2e/promqle2e.go +++ b/promqle2e/promqle2e.go @@ -324,7 +324,7 @@ func (t *ScrapeStyleTest) fatalOnUnexpectedPromQLResults(ctx context.Context, tt got model.Matrix ) if err := runutil.RetryWithLog(log.NewJSONLogger(os.Stderr), 10*time.Second, ctx.Done(), func() error { - value, warns, err := b.API().Query(ctx, query, t.maxTime) + value, warns, _, err := b.API().Query(ctx, query, t.maxTime) if err != nil { return fmt.Errorf("instant query %s at %v: %w", query, t.maxTime, err) } diff --git a/target.go b/target.go index e5b730eb..88a79d4a 100644 --- a/target.go +++ b/target.go @@ -148,7 +148,7 @@ var downloadMtx sync.Mutex const ( // TODO(bwplotka): Switch back to DefaultPrometheusDownloadURL once a Prometheus release includes https://github.com/prometheus/prometheus/pull/20098. DefaultPrometheusDownloadURL = "" - DefaultPrometheusGitRef = "6f22682586f217ba0e1172f8111a61db47179798" // https://github.com/prometheus/prometheus/pull/20098 + DefaultPrometheusGitRef = "ad035834ee700af425e9c9c8407defae8242ccc2" // https://github.com/prometheus/prometheus/pull/20098 ) // GetPrometheusBinary downloads or builds the default Prometheus binary (see