Add the shared state to the global scope to get previous data (#8447)
This commit is contained in:
parent
6be3bd8c9c
commit
01fc69da47
|
|
@ -192,6 +192,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.
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
Loading…
Reference in New Issue