Skip to content

Commit

Permalink
Add the shared state to the global scope to get previous data (influx…
Browse files Browse the repository at this point in the history
  • Loading branch information
essobedo authored Nov 30, 2020
1 parent ec8a22f commit 1be33f8
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
1 change: 1 addition & 0 deletions plugins/processors/starlark/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
3 changes: 3 additions & 0 deletions plugins/processors/starlark/starlark.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 25 additions & 0 deletions plugins/processors/starlark/testdata/compare_metrics.star
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 1be33f8

Please sign in to comment.