32 Commits

Author SHA1 Message Date
Anders Eknert d3f34a3387 Modernize analyzer fixes (#7965)
Have done this some time in the past, but there was a few
new issues this would highlight now that we're on Go 1.24.

Mostly:
- Use `b.Loop()` in benchmarks
- Use `strings.SplitSeq` where possible
- Remove `omitempty` tag for types that can't be empty

Signed-off-by: Anders Eknert <anders@eknert.com>
2025-10-10 17:51:02 +02:00
Jacob Hochstetler 2cc948d872 TLM: Upgrade to v1 tablewriter (#7937)
- Updated test fixtures and various test fixes.

Signed-off-by: Jacob Hochstetler <jacob.hochstetler@gmail.com>
2025-10-01 10:44:42 +02:00
Sebastian Spaink d102e453e5 fix: print eval errors to stderr (#7880)
updated the presentation package print functions to accept a parameter to print to stderr.

Signed-off-by: Sebastian Spaink <sebastianspaink@gmail.com>
2025-09-11 16:13:15 -05:00
kevinstyra 94a953150a cmd: allow branding
This change allows users that build their own executable or "spin" of
OPA to give it a name, and have it reference itself properly in help
texts.

It's a vanity thing, but I think some people would appreciate it, hat
tip to the international association of pedants.

Signed-off-by: Stephan Renatus <stephan@styra.com>
Co-authored-by: kevinstyra <83973046+kevinstyra@users.noreply.github.com>
2025-07-24 11:33:23 +02:00
kevinstyra 36bae2aac6 cmd: use command.RunE to return errors and perform orderly shutdown of OPA
`os.Exit` immediately exits the program and doesn't run defer functions.
This can be problematic as any command.OnFinalize routines and any logic
after the command.Execute won't be run.

Also suppress all RunE cobra error and usage messages. These would be
printed twice otherwise.

Signed-off-by: Stephan Renatus <stephan@styra.com>
Co-authored-by: Kevin St. Pierre <kevin@styra.com>
2025-07-23 17:17:50 +02:00
Johan Fylling 817b6635a8 ast,format: Allowing keywords in Rego references (#7709)
Updating the parser and formatter to allow keywords in refs.

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2025-06-25 15:19:21 +02:00
Anders Eknert d2a415e25d opa check --bundle report virtual/base doc conflicts (#7701)
A tiny first step to have more tooling correctly report
virtual and base document conflicts, as detailed in #7694.

This PR fixes the `opa check` command to report conflicts
of this type when the `-b`/`--bundle` flag is provided. The
bundle flag is required as without that, `opa check` should
only verify policies and not load data at all.

While I was in the `cmd` directory, I got annoyed with how
many of these commands store the same constants for their
`--format` flag, so I decided to fix that too, even if it
wasn't related to what I originally planned to do. I hope
it's not too distracting.

Signed-off-by: Anders Eknert <anders@styra.com>
2025-06-16 12:24:42 +02:00
Anders Eknert 3810973ab1 perf: improve "baseline" metrics of opa bench for trivial queries (#7580)
It's been irritating me for long how `opa bench` has such a high baseline
metric for even the most trivial queries, as in order to know the cost of
"your" Rego you'll need to first subtract the number OPA adds for just
getting eval set up. This improves this somewhat by not initiating some
caches until they're needed. We don't need to cache comprehensions to eval
the value '1', or a functionMockStack, and so on. In fact, we may never
need one. The gain here is miniscule for real policy evaluation, but helps
some with making `opa bench` approach a more reasonable baseline.

We *can* have 10 allocs more removed if we initialize and reuse a base
cache and a virtual cache across all runs. This works as the query is
the same for all runs. However, since those are normally initialized
per "run" (query), perhaps that's going too far?

```
opa bench 1
```

**Before**
```
+-------------------------------------------+------------+
| samples                                   |     398083 |
| ns/op                                     |       2978 |
| B/op                                      |       3200 |
| allocs/op                                 |         49 |
+-------------------------------------------+------------+
```

**After**
```
+-------------------------------------------+------------+
| samples                                   |     432841 |
| ns/op                                     |       2825 |
| B/op                                      |       2968 |
| allocs/op                                 |         40 |
+-------------------------------------------+------------+
```

This change also fixes a panic which happened when the `--metrics` flag
was set to `false`.

Signed-off-by: Anders Eknert <anders@styra.com>
2025-05-15 15:34:44 +02:00
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
Anders Eknert bd5ceb5142 Enable unused-receiver linter (revive) (#7448)
Signed-off-by: Anders Eknert <anders@styra.com>
2025-03-14 11:41:25 +01:00
Anders Eknert 55e87e79ae Add perfsprint linter (#7334)
And update code to conform to the rule.

- Replace unnecessary fmt.Sprintf with string concatenation
- Replace fmt.Sprint with more efficient strconv.Itoa
- Replace static fmt.Errorf calls with more efficient errors.New

Thanks @srenatus for pushing me down this rabbit hole!

Signed-off-by: Anders Eknert <anders@styra.com>
2025-01-31 20:24:05 +01:00
Anders Eknert b942136a4a Use Go 1.22+ int ranges (#7328)
With "some" help from `golangci-lint run --fix ./...`

Signed-off-by: Anders Eknert <anders@styra.com>
2025-01-30 09:57:27 +01:00
Anders Eknert b584ce1d28 opa bench: don't generate JSON from result (#7295)
The numbers reported by `opa bench` would often be misleading, as they
would include the cost of generating "JSON" (interface{}) values from
the result.

**Before**
```
> opa bench 'numbers.range(1, 500)'
+-------------------------------------------+------------+
| samples                                   |      19736 |
| ns/op                                     |      61062 |
| B/op                                      |      65905 |
| allocs/op                                 |       1086 |
+-------------------------------------------+------------+
```

**After**
```
> opa bench 'numbers.range(1, 500)'
+-------------------------------------------+------------+
| samples                                   |      53263 |
| ns/op                                     |      21836 |
| B/op                                      |      12057 |
| allocs/op                                 |         63 |
+-------------------------------------------+------------+
```

Fixes #7291

Signed-off-by: Anders Eknert <anders@styra.com>
2025-01-22 14:20:40 +01:00
Anders Eknert 622434d113 Add util.Keys and util.KeysSorted (#7285)
And use them to reduce imperative boilerplate throughout
the codebase.

Additionally, replace use of sort.Slice with slices.SortFunc
which is more efficient since it is generic and as such avoids
allocations related to `interface{}` casts.

Also a few performance-related minor fixes, but not the main
theme of this PR.

```
BenchmarkRegalLintingItself-10 before / after
1832684458 ns/op    3453470360 B/op    66125422 allocs/op
1826601250 ns/op    3449619024 B/op    65999164 allocs/op
````

Signed-off-by: Anders Eknert <anders@styra.com>
2025-01-21 08:30:19 +01:00
Johan Fylling 563321d26b Rego v1 capabilities and keywords update (#7216)
* Separating v0- and v1 keywords
* Adding `rego_v1` capability feature

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-12-17 11:50:11 +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
Johan Fylling 6af5e79bd9 storage: Optimized read mode for default data storage
A new optimized read mode has been added to the default in-memory store, where data written to the store is eagerly converted to AST values (the data format used during evaluation). This pre-converted data is faster to read, and won’t cause memory spikes during load; but comes with slower data writes (affects startup and bundle load/update time) and a larger lowest overall memory footprint for OPA. Can be enabled for `opa run`, `opa eval`, and `opa bench` by setting the `—optimize-store-for-read-speed`. See http://localhost:8888/docs/edge/policy-performance/#storage-optimization.

Implements: #4147

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
Co-authored-by: Ashutosh Narkar <anarkar4387@gmail.com>
2024-10-30 12:12:21 +01:00
Johan Fylling 5521453d87 cmd: Adding --v0-compatible flag (#7065)
To make OPA behave as v0.x post v1.0 release.
If used simultaneously with `--v1-compatible` flag, the `--v0-compatible` flag takes precedence.

Also, future-proofing `cmd` package tests for 1.0.

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-09-26 00:45:51 +02:00
Colin J Lacy 4bfae4e64e cmd: add env var backups to command flags (#6508)
Signed-off-by: Colin Lacy <colinjlacy@gmail.com>
2024-01-29 15:15:35 +01:00
Johan Fylling b36151d992 Adding --v1-compatible flag to all previously unsupported command line commands (#6521)
In addition to those commands already supported:

* build
* check
* eval
* fmt
* test

support has been added to the following commands:

* `bench`
* `deps`
* `exec`
* `inspect`
* `parse`
* `run` (command `server` and `REPL`)

Fixes: #6520

Signed-off-by: Johan Fylling <johan.dev@fylling.se>
2024-01-24 15:42:32 +01:00
Ashutosh Narkar 88cf5a100b cmd: Extend e2e benchmarking mode to include OPA config (#5335)
Currently the e2e bench mode doesn't support providing an
OPA configuration to enable features like decision logging
that can have an impact on the server overhead. This change
adds a new flag to the bench cmd to specify the OPA configuration.

Fixes: #4899

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2022-11-02 09:18:49 +01:00
Anders Eknert 9a597feb2e chore: don't use the deprecated ioutil functions (#5319)
Another annoyance removed :P

Signed-off-by: Anders Eknert <anders@eknert.com>
2022-10-27 14:30:26 +02:00
Philip Conrad 2572e3206e cmd/bench: Fix port collision in utility function. (#5036)
We're now using port 0 to have the OS select an open port for us,
and wait in a loop (with exponential backoff) until the runtime returns
an address, so we can go on.

Signed-off-by: Philip Conrad <philipaconrad@gmail.com>
2022-08-25 11:43:11 +02:00
Ashutosh Narkar 93e4557c75 Add e2e mode for opa bench
This commit adds a new flag to the opa bench command which
allows users to run benchmarks against a running OPA server.
This mode can be used to evaluate the additional overhead the
server is going to introduce.

Co-authored-by: Anders Eknert anders@eknert.com
Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2022-06-22 11:29:47 -07:00
Stephan Renatus 0efa2f0bad add allow_net to capabilities, use it to disable fetching remote schemas (#3748)
This adds a new top-level key to the capabilities structure, `allow_net`.
It currently is only used for restricting the typechecker's ability to fetch
remote refs in JSON schemas, but could be used more widely in the future.

It works like this:

- If it's not present, any host can be contacted
- If it's present, the items will be the hosts or IP addresses that may be
   contacted; anything not in the list is prohibited.
- As a consequence, If it's present and empty (`[]`), no host can be contacted

Introducing a package-level var to gojsonschema isn't the prettiest solution,
but since we want this in an all-or-nothing way right now anyways, it does
the trick. And it's more ergonomic than adding extra parameters all over the
place.

Fixes #3746.

Also:

* move some profiling-related default params into newEvalCommandParams
* replace some errors.Wrap by fmt.Errorf in loader pkg
* remove some != nil handling where it didn't make a difference when
  working on the schema set
* reduces indentation in code examples in `opa eval -h` and `opa check -h`
  by replacing tabs by four spaces.
* ast: allow testing with remote refs without networking

It would be nice to ensure that the remote refs feature actually works,
without introducing a network dependency into our tests.

This commit adds the kube 1.14 definitions into ast/testdata, and uses
that from a httptest.Server instance in the unit tests.

Signed-off-by: Stephan Renatus <stephan.renatus@gmail.com>
2021-08-24 21:54:01 +02: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
Torin Sandall 7be82daa7f cmd: Do not print nil errors in bench subcommand
Fixes #3530

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2021-06-07 10:20:27 -04: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
Ashutosh Narkar 2b2d73ebbf Add target flag to OPA subcommands
This commit adds a target flag to the
bench, eval, test and run (repl) commands
which allows users to exercise the wasm
rumtime.

Fixes #2878

Signed-off-by: Ashutosh Narkar <anarkar4387@gmail.com>
2021-02-05 10:16:22 -08:00
Ansu Varghese cc1cecf567 opa eval: support rego validation using input JSON schema (#3060)
New support to input a JSON schema file via "opa eval --schema" that
helps improve static type checking and returns precise error reports as
you develop Rego code.

Also, uses modified version of https://github.com/xeipuuv/gojsonschema
from internal/ to help set Rego types, using gojsonschema's Compiler
results. See README docs for more details on the feature.

Co-authored-by: Mandana Vaziri <mvaziri@us.ibm.com>
Co-authored-by: Ansu Varghese <avarghese@us.ibm.com>
Signed-off-by: Ansu Varghese <avarghese@us.ibm.com>
2021-01-27 13:32:59 +01:00
Torin Sandall 740b33bd13 cmd: Add support for benchmarking partial evaluation queries
This change allows users to get an accurate estimate of partial eval
performance on their policies.

Signed-off-by: Torin Sandall <torinsandall@gmail.com>
2021-01-08 10:39:56 -05:00
Patrick East e6727cbdf2 Add opa bench and opa test --bench
This adds in a new CLI sub command `opa bench` which will load
and evaluate similar to `opa eval` but will perform benchmark testing
of the query.

There is also a new `--bench` option for `opa test` which will
similarly perform benchmarking, except on the unit tests.

Both use the golang testing frameworks benchmark tooling, and the
output format is compliant with the go benchmark standard when using
the newly added `gobench` output format option.

They both support specifying a `--count` to run the benchmark a
number of times and a `--benchmem` option to report memory statistics.

To help enable using the `opa test` command better with the benchmark
option there is now a `--run`/`-r` option that can be provided to
specify a regex for what test cases should be run. The regex supports
anything that is supported by re2:

https://github.com/google/re2/wiki/Syntax

These changes required updating to Go 1.13 to get the ability to
report custom metrics with the benchmark results
https://golang.org/pkg/testing/#B.ReportMetric To get Netlify on board
we needed to add a `.go-version` file to the root of the repo. This is
now the single source of truth for the OPA golang version.

Fixes: #1424
Signed-off-by: Patrick East <east.patrick@gmail.com>
2020-02-24 14:03:42 -08:00