InfluxDB: Flux - Custom Function stateChangesOnly() (on Hostname)

Aus Wiki-WebPerfect
Wechseln zu: Navigation, Suche

Because the built-in function stateChangesOnly() only works for alerts and the field "_level", you cannot use the function for other UseCases! (More Information's: https://github.com/influxdata/flux/issues/4179)
That's why I created a custom function based on the function "stateChangesOnly()" for my own UseCase.

UseCase description: I monitor VMs with Telegraf and I want to know when a VM was live migrated and to which host.

My Custom Function of stateChangesOnly

Because the function only works with numeric values, you have to remove the non-numeric characters and change the the data type of the field to an integer.
In my example the Hostname starts always with the prefix "FPPW".

string_to_trim = "FPPW"

custom_stateChangesOnly = (tables=<-) => {
  return tables
    |> map(fn: (r) => ({r with
      host_value:
        int(v: strings.trimPrefix(v: r.host, prefix: string_to_trim))
    }))
    |> duplicate(column: "host", as: "____temp_host____")
    |> drop(columns: ["host"])
    |> rename(columns: {"____temp_host____": "host"})
    |> sort(columns: ["_source_timestamp", "host"], desc: true)
    |> difference(columns: ["host_value"])
    |> filter(fn: (r) => r.host_value != 0)
    |> drop(columns: ["host_value"])
    |> experimental.group(mode: "extend", columns: ["host"])
}

Using the Custom Function

from(bucket: "<YOUR_BUCKET>")
  |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
  |> filter(fn: (r) => 
    r._measurement == "<YOUR_MEASUREMENT>" and
    r._field == "<YOUR_FIELD>" and
    r.VMName == "<YOUR_VMNAME>"
  )
  '''|> custom_stateChangesOnly()'''
  |> group()


The source function stateChangesOnly() is defined here: https://github.com/influxdata/flux/blob/master/stdlib/influxdata/influxdb/monitor/monitor.flux#L253-L277