Files
test-script/test_script.py
T

57 lines
1.5 KiB
Python

from i7lib.client import run
from i7lib.timeutils import now, to_datetime
ID_LOAD_INDEX = 49
ID_JOB_HEARTBEAT = 50
ID_HIGH_CPU_PULSE = 51
ID_HIGH_CPU_ALARM = 52
THRESHOLD_SIGNAL = "deb13kde-high-cpu-threshold"
prev_over_threshold = None
def log(msg):
dt = to_datetime(now()).strftime("%Y-%m-%d %H:%M:%S")
print(f"[{dt}] {msg}")
def logic(plant):
global prev_over_threshold
cpu = plant.state.get("deb13kde-cpu", 0.0)
ram = plant.state.get("deb13kde-ram", 0.0)
load_index = (cpu * 3.0 + ram) / 4.0
batch = plant.new_write_batch()
batch.add(ID_LOAD_INDEX, load_index, "deb13kde-load-index")
batch.add(ID_JOB_HEARTBEAT, now(), "deb13kde-job-heartbeat")
if THRESHOLD_SIGNAL not in plant.state:
log(f"WARNING: {THRESHOLD_SIGNAL} not present in plant.state - skipping alarm evaluation")
plant.send(batch)
return
threshold = plant.state[THRESHOLD_SIGNAL]
over_threshold = cpu > threshold
batch.add(ID_HIGH_CPU_ALARM, 1.0 if over_threshold else 0.0, "deb13kde-high-cpu-alarm")
if prev_over_threshold is not None and over_threshold and not prev_over_threshold:
log(f"CPU {cpu:.1f}% crossed threshold {threshold:.1f}% - firing pulse")
batch.add(ID_HIGH_CPU_PULSE, 1.0, "deb13kde-high-cpu-pulse")
plant.send(batch)
if prev_over_threshold is None:
log(f"first tick: cpu={cpu:.1f} ram={ram:.1f} threshold={threshold:.1f}")
prev_over_threshold = over_threshold
if __name__ == "__main__":
run(logic, interval_ms=1000, offset_ms=200)