diff --git a/plugins/processors/starlark/README.md b/plugins/processors/starlark/README.md index 1194845ea1ad8..7afd9507a7b80 100644 --- a/plugins/processors/starlark/README.md +++ b/plugins/processors/starlark/README.md @@ -190,6 +190,7 @@ def failing(metric): - [multiple metrics](/plugins/processors/starlark/testdata/multiple_metrics.star) - Return multiple metrics by using [a list](https://docs.bazel.build/versions/master/skylark/lib/list.html) of metrics. - [multiple metrics from json array](/plugins/processors/starlark/testdata/multiple_metrics_with_json.star) - Builds a new metric from each element of a json array then returns all the created metrics. - [custom error](/plugins/processors/starlark/testdata/fail.star) - Return a custom error with [fail](https://docs.bazel.build/versions/master/skylark/lib/globals.html#fail). +- [compare with previous metric](/plugins/processors/starlark/testdata/compare_metrics.star) - Compare the current metric with the previous one using the shared state. [All examples](/plugins/processors/starlark/testdata) are in the testdata folder. diff --git a/plugins/processors/starlark/starlark.go b/plugins/processors/starlark/starlark.go index 4835f06dee5a4..9a055ce56db6f 100644 --- a/plugins/processors/starlark/starlark.go +++ b/plugins/processors/starlark/starlark.go @@ -73,6 +73,9 @@ func (s *Starlark) Init() error { return err } + // Make available a shared state to the apply function + globals["state"] = starlark.NewDict(0) + // Freeze the global state. This prevents modifications to the processor // state and prevents scripts from containing errors storing tracking // metrics. Tasks that require global state will not be possible due to diff --git a/plugins/processors/starlark/testdata/compare_metrics.star b/plugins/processors/starlark/testdata/compare_metrics.star new file mode 100644 index 0000000000000..79555729d1814 --- /dev/null +++ b/plugins/processors/starlark/testdata/compare_metrics.star @@ -0,0 +1,25 @@ +# Example showing how to keep the last metric in order to compare it with the new one. +# +# Example Input: +# cpu value=10i 1465839830100400201 +# cpu value=8i 1465839830100400301 +# +# Example Output: +# cpu_diff value=2i 1465839830100400301 + +state = { + "last": None +} + +def apply(metric): + # Load from the shared state the metric assigned to the key "last" + last = state["last"] + # Store the deepcopy of the new metric into the shared state and assign it to the key "last" + # NB: To store a metric into the shared state you have to deep copy it + state["last"] = deepcopy(metric) + if last != None: + # Create a new metric named "cpu_diff" + result = Metric("cpu_diff") + # Set the field "value" to the difference between the value of the last metric and the current one + result.fields["value"] = last.fields["value"] - metric.fields["value"] + return result