Commit Graph

27 Commits

Author SHA1 Message Date
Anders Eknert e43ef0a979 Use any in place of interface{} (#7566)
Earlier this evening I tried to run the Go
[modernize](https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/modernize)
analyzer on OPA. That didn't go as planned:

- https://github.com/golang/go/issues/73661
- https://github.com/golang/go/issues/73663

While we wait for that to be fixed, I figured an old-fashioned
search-and-replace across the repo may work for at least the
`interface{}` to `any` conversion. That should help make it easier
to see the other fixes as applied by the modernize tool once it has
had those issues resolved.

Signed-off-by: Anders Eknert <anders@styra.com>
2025-05-12 13:57:48 +02:00
Johan Fylling a179a24c48 v1 API
All packages, except for `cmd` and `internal`, have been moved into a new `v1` root package.

Old packages are kept for backwards-compatibility reasons. All contained code is replaced with simple type aliases and proxy functions to `v1` implementations.

Old packages default to the Rego v0 syntax, new `v1` packages default to the Rego v1 syntax.

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-12-12 15:27:34 +01:00
Johan Fylling 7bb6dbe36b Preparing for v1 API
Moving (most) source to v1 root package to prepare for v0/v1 API separation.

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-12-12 15:09:03 +01:00
Stephan Renatus 9afdad7919 Status API: use jsonpb for json marshalling of prometheus metrics (#4324)
* Wrap the prometheus portion of our metrics in such a way that they use jsonpb for
   encoding to JSON, as prescribed by the protobuf library.

   Note: We're using jsonpb, not protojson, because there is no protobuf V2 version of
   github.com/prometheus/client_golang

* build(deps): bump github.com/prometheus/client_golang (#4307)

 This reverts commit 2f298db68c.

* CHANGELOG.md: add note re: JSON encoding of Status API payloads

Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
2022-02-22 09:25:19 +01:00
Torin Sandall a1dae2f79e download: Add timer to HTTP request
Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2021-12-08 17:06:53 -08:00
Stephan Renatus ef716a3142 opa eval: add '--count=#' flag (#3655)
`opa eval --count=# --profile` will now evaluate the query # times,
and display aggregated results for metrics and the expression-time
profile.

Before, `opa eval --profile` would yield output like this (JSON):

    "metrics": {
      "timer_rego_external_resolve_ns": 233,
      "timer_rego_load_files_ns": 138866,
      "timer_rego_module_compile_ns": 432654,
      "timer_rego_module_parse_ns": 81454,
      "timer_rego_query_compile_ns": 54892,
      "timer_rego_query_eval_ns": 135624,
      "timer_rego_query_parse_ns": 3886
    },
    "profile": [
      {
        "total_time_ns": 75705,
        "num_eval": 4,
        "num_redo": 2,
        "location": {
          "file": "t.rego",
          "row": 8,
          "col": 2
        }
      },

Now, both of these are replaced by "aggragated_" variants that
include some statistics:

    "aggregated_metrics": {
      "timer_rego_external_resolve_ns": {
        "75%": 1618.5,
        "90%": 1933.8000000000002,
        "95%": 1954,
        "99%": 1954,
        "99.9%": 1954,
        "99.99%": 1954,
        "count": 10,
        "max": 1954,
        "mean": 1137.1,
        "median": 1140,
        "min": 311,
        "stddev": 514.9278493148337
      },

and

    "aggregated_profile": [
      {
        "total_time_ns_stats": {
          "75%": 63369.75,
          "90%": 69523.5,
          "95%": 69691,
          "99%": 69691,
          "99.9%": 69691,
          "99.99%": 69691,
          "count": 10,
          "max": 69691,
          "mean": 39030.9,
          "median": 53758.5,
          "min": 3390,
          "stddev": 27635.790954666016
        },
        "num_eval": 1,
        "num_redo": 1,
        "location": {
          "file": "t.rego",
          "row": 9,
          "col": 2
        }
      }

The table format has been adjusted as well, and only displays a subset of
the statistics gathered:
Especially the 99.9 and 99.99 percentiles hardly matter for the sample
sizes I'd expect to be used here: they will almost certainly match "max".

The output is less unwieldy now:

    +------------------------------+---------+----------+---------------+----------------+---------------+
    |            METRIC            |   MIN   |   MAX    |     MEAN      |      90%       |      99%      |
    +------------------------------+---------+----------+---------------+----------------+---------------+
    | timer_rego_load_files_ns     | 349969  | 2549399  | 1.4760619e+06 | 2.5312689e+06  | 2.549399e+06  |
    | timer_rego_module_compile_ns | 1087507 | 24537496 | 1.120074e+07  | 2.41699473e+07 | 2.4537496e+07 |
    | timer_rego_module_parse_ns   | 275531  | 1915263  | 1.126406e+06  | 1.9016968e+06  | 1.915263e+06  |
    | timer_rego_query_compile_ns  | 61663   | 64395    | 63062.5       | 64374.1        | 64395         |
    | timer_rego_query_eval_ns     | 161812  | 1198092  | 637754        | 1.1846622e+06  | 1.198092e+06  |
    | timer_rego_query_parse_ns    | 6078    | 6078     | 6078          | 6078           | 6078          |
    +------------------------------+---------+----------+---------------+----------------+---------------+
    +----------+-------------+-------------+-------------+-------------+----------+----------+-----------------+
    |   MIN    |     MAX     |    MEAN     |     90%     |     99%     | NUM EVAL | NUM REDO |    LOCATION     |
    +----------+-------------+-------------+-------------+-------------+----------+----------+-----------------+
    | 43.875µs | 26.135469ms | 11.494512ms | 25.746215ms | 26.135469ms | 1        | 1        | data.rbac.allow |
    | 21.478µs | 211.461µs   | 98.102µs    | 205.72µs    | 211.461µs   | 1        | 1        | rbac.rego:13    |
    | 19.652µs | 123.537µs   | 73.161µs    | 122.75µs    | 123.537µs   | 1        | 1        | rbac.rego:40    |
    | 12.303µs | 117.277µs   | 61.59µs     | 116.733µs   | 117.277µs   | 2        | 1        | rbac.rego:50    |
    | 12.224µs | 93.214µs    | 51.289µs    | 92.217µs    | 93.214µs    | 1        | 1        | rbac.rego:44    |
    | 5.561µs  | 84.121µs    | 43.002µs    | 83.469µs    | 84.121µs    | 1        | 1        | rbac.rego:51    |
    | 5.56µs   | 71.712µs    | 36.545µs    | 71.158µs    | 71.712µs    | 1        | 0        | rbac.rego:45    |
    | 4.958µs  | 66.04µs     | 33.161µs    | 65.636µs    | 66.04µs     | 1        | 2        | rbac.rego:49    |
    | 4.326µs  | 65.836µs    | 30.461µs    | 65.083µs    | 65.836µs    | 1        | 1        | rbac.rego:6     |
    | 3.948µs  | 43.399µs    | 24.167µs    | 43.055µs    | 43.399µs    | 1        | 2        | rbac.rego:55    |
    +----------+-------------+-------------+-------------+-------------+----------+----------+-----------------+

Fixes #3651.

Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
2021-07-21 21:32:01 +02:00
Will Beason 3be1d08b87 Change check-lint to use golangci-lint (#3465)
golint is deprecated. The author of the code no longer supports the
codebase. golangci-lint is faster than golint, and is in use by other
opa repositories (e.g. Gatekeeper).

This commit changes tools.go to reference golangci (so it ends up in
vendor) and modifies check-lint to use golangci instead.

Breaking API Changes:

- plugins/rest/rest.go: Fix typo "AllowInsureTLS" -> "AllowInsecureTLS"
- storage/errors.go: Removed unused IndexingNotSupportedErr

Signed-off-by: Will Beason <willbeason@google.com>
2021-05-19 07:52:02 +02:00
Torin Sandall 34ff7c738b sdk: Add new SDK package for embedding OPA
This commit adds a new top-level package for integration with OPA. The
SDK defines a simple interface for OPA integrations that require the
management APIs. The APIs allow callers to instantiate an instance of
OPA by specifying the OPA configuration as a file or byte slice. The
SDK implements basic lifecycle management so that callers can control
whether startup blocks the calling thread (or not). Also, callers can
control the log level of debug and console logs emitted by the OPA. In
the future, other options could be exposed but for now we choose to
keep the API as simple as possible (as we will be aiming for
consistency across multiple languages eventually, we want to keep the
surface area small as possible.)

For policy queries, users can supply wallclock time, the decision
name, and the value of the input document. The SDK ensures the
wallclock time is consistent across time.now_ns() and the decision log
record (for replay purposes). The SDK incldues a dedicated
"sdk_decision_eval" metric that records the total decision latency for
monitoring purposes. The SDK ensures the input document is not
processed more than necessary (i.e., it parses into an AST value which
is reused for decision log masking.) Finally, the SDK includes a UUID
in the result which can be used for correlation with the decision log.

Co-authored-by: Torin Sandall <torinsandall@gmail.com>
Co-authored-by: Anders Eknert <anders@eknert.com>

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
Signed-off-by: Anders Eknert <anders@eknert.com>
2021-05-10 11:34:14 -04:00
Patrick East 197c8387f7 wasm: Add metrics for wasm resolver evaluations
This plumbs through metrics to the wasm evaluation, adding several
new timers. They will show up when using a Wasm bundle with any of the
usual evaluation mechanisms (eg opa eval, bench, server requests etc)

Signed-off-by: Patrick East <east.patrick@gmail.com>
2020-11-06 15:12:38 -05:00
Torin Sandall 525afe9d52 metrics: Include Add(uint64) on Counter object
This change is not backwards compatible but it is only a minor
inconvenience for anyone who has re-implemented metrics.Metrics (which
feels highly unlikely anyway.)

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2020-04-14 09:50:28 -04:00
Patrick East feaf745da9 server: Cache PreparedEvalQuery's for data requests
This adds in caching of prepared queries for versioned and unversioned
data queries (POST/GET to `/`, `/data`, and `/v1/data`).

The cache has a max size of 100 and just starts acting as a circular
buffer for queries (FIFO, no smarts for LRU caching or anything). It
seems like it would be unlikely for these API's to hit the cache max
size. Most OPA use-cases have a single query that is re-used over
and over with different inputs.

There is a new metric `counter_server_query_cache_hit` which will
show whether or not a request used the query cache or not. It is there
primarily to help explain away why sometimes a handful of the other
metrics aren't there (the query parse/compile/etc).

In the future this could be added to the query API's too. This change
does not touch anything other than the "data" API's.

Closes: #1567
Signed-off-by: Patrick East <east.patrick@gmail.com>
2019-12-18 11:07:14 -08:00
Patrick East 9c85dfc6fc Plumb metrics through loader and bundle helpers
This corrects the missing time in rego_module_parse timers as we now
have metrics collecting info as we parse *.rego files from file
loaders and from bundles as they are unpacked.

It also adds in a timer for the data files that are loaded through
similar mechanisms.

Signed-off-by: Patrick East <east.patrick@gmail.com>
2019-12-12 10:31:22 -08:00
Patrick East 650512a6af rego: Support loading bundles and files w/ Rego API
There are three new APIs to load files, bundle files/dirs, or to
just give a bundle directly.

This requires re-shuffling some of the transaction handling for
a couple of reasons. First off, the bundle loading process requires
a write txn for placing any bundle manifets or data loaded into
the store. The second is that for auto-created txns we cant just
abort anymore, we need to commit after the prepare step.

So, we now conditionally create a write transaction and when we did
auto-create one we will commit it on success.

Signed-off-by: Patrick East <east.patrick@gmail.com>
2019-09-04 13:39:52 -06:00
Torin Sandall b0523466c1 Refactor metric provider implementation
* Remove metric provider config to avoid introducing new public
  interfaces. Since there is only one provider (prometheus) and it
  doesn't have any configurable settings, remove the configuration
  changes for now. We can always add these in the future.

* Remove dummy metric provider implementation. This isn't needed now
  that we're using the metrics.Metrics interface instead of
  metrics.GlobalMetrics.

* Remove metrics.GlobalMetrics in favour of metrics.Metrics. Move the
  HTTP handler instrumentation interfaces into the server package to
  avoid coupling the metrics package to the net/http package.

* Refactor the prometheus provider to implement the metrics.Metrics
  interface. Since the prometheus registry can error on Gather()
  calls, the provider has been updated to accept a logger and use ti
  when the Gather() call fails. This doesn't affect any public
  interfaces so it can be revisited in future if needed. Alteratnively
  we could add a Gather() interface onto metrics.Metrics which could
  return the error.

* Refactor status plugin to include metrics in status update by
  default. Users implementing the status API are likely to need
  performance metrics to gauge the OPA's health. Moreover if they are
  implementing the status API it's unlikely they will want to poll the
  /metrics endpoint on the OPA HTTP API (which may not even be
  exposed.)

* Move the prometheus endpoint test case into the e2e package so the
  server package has no dependencies on prometheus anymore.

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2019-08-15 15:08:38 -04:00
Torin Sandall f8442c1345 metrics: Make metrics object thread-safe
This let's the metrics object be shared across goroutines which will
be valuable for maintaining global metrics within an OPA instance.

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2019-08-15 15:08:38 -04:00
Stan Lagun 69fbaacfde Add Prometheus metrics to the status updates
Prometheus metrics can give much of insight into OPA's health.
Run-time metrics are a natural part of the application state
so having them in status update seems like a right change
that can help server understand what's going in with the OPA
instance.

The commit also encapsulates all prometheus-related code in one package
and abstracts it with generic interface so that it would be possible
to add other metrics providers

Addresses #1606

Signed-off-by: Stan Lagun <stan@styra.com>
2019-08-15 15:08:38 -04:00
Patrick East dea3b489b4 Decouple Rego input and query options
The process to decouple the input and query compilation had already been
started. Aside from custom compilation stages which might live out of the tree
there are no usages of the input in the current QueryCompiler implementation,
all had been removed previously. This change removes the connection between
the two and more formally breaks the two apart.

The benefit here is that we can compile and cache queries independent from
the input.

Signed-off-by: Patrick East <east.patrick@gmail.com>
2019-04-23 22:38:04 -07:00
Torin Sandall 503b8c0645 Add metrics timer for server handler
These changes add a new metric into the server that calculates the
time taken from when the handler is invoked to the point where the
decison log is emitted. Hopefully this will prevent us from missing
important periods in the request path.

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2019-01-16 12:45:47 -08:00
repenno d85a3e15ca Add query metrics to decision logs
Fixes #1033

Signed-off-by: repenno <rapenno@gmail.com>
2019-01-16 12:45:47 -08:00
Torin Sandall ab4d7faa2e Add Stringer implementation on metrics object
Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2018-11-16 14:07:44 -08:00
Torin Sandall f59aade0f8 Add marshalling to the metrics.Metrics package
This makes it easier for callers to serialize structs that contain
metrics. Callers do not have to convert the metrics to
map[string]interface{}.

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2018-07-26 13:31:40 -07:00
Stephan Renatus 2f1526c672 fix misspell
Signed-off-by: Stephan Renatus <srenatus@chef.io>
2018-06-05 09:50:13 -07:00
Torin Sandall 744316dbaa Add basic query performance instrumentation
Previously OPA only tracked query performance a high level (e.g., parse,
compile, eval latencies.) In some cases, it's necessary to instrument
lower level evaluation operations to understand performance. These
changes update the eval implementation to support instrumentation:

* Eval has been instrumented to record time taken for various core
operations like term plugging, reading from the store, rule lookup,
cache hits, etc.

* Rego package has been updated to support a simple rego.Instrument
operation that enables query instrumentation.

* REPL and server have been updated to expose simple interfaces to turn
on instrumentation.

* Diagnostic policy config "all" will enable instrumentation.

Instrumentation can be expensive (because it requires timing frequently
executed operations) so it should be treated as a debugging tool and not
enabled all of the time.
2018-02-09 09:30:27 -08:00
Torin Sandall ae9ae105f4 Update topdown to record partial eval latency 2018-01-18 14:11:47 -08:00
Torin Sandall c45bdf9e8d Refactor Policy API responses
These changes update the Policy API responses to:

- Return empty objects for PUT/DELETE with optional support for ?metrics
- Return AST and raw/source for GET

Support for the ?source param has been removed as the raw/source version
is now included by default.
2017-08-24 11:29:26 -07:00
Matthew Mussomele a147de388f Augment the metrics interface to support clearing 2017-08-10 08:06:22 -07:00
Torin Sandall 0e5a841b9a Add basic performance metric collection 2017-05-12 09:55:14 -07:00