Skip to content

Commit

Permalink
Add task for generating randomized device metrics (#1564)
Browse files Browse the repository at this point in the history
  • Loading branch information
elinol authored Sep 30, 2024
1 parent 9ff1b2d commit 0046d1d
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
59 changes: 59 additions & 0 deletions lib/mix/tasks/fake.metrics.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
if Mix.env() == :dev do
defmodule Mix.Tasks.Fake.Metrics do
use Mix.Task

alias NervesHub.Repo
alias NervesHub.Devices
alias NervesHub.Devices.DeviceMetric

@shortdoc "Create randomized metrics for device"
@requirements ["app.start"]

@impl Mix.Task
def run([device_identifier | _]) do
{:ok, %{id: device_id}} = Devices.get_by_identifier(device_identifier)
now = DateTime.now!("Etc/UTC") |> DateTime.truncate(:millisecond)
a_week_ago = DateTime.add(now, -7, :day) |> DateTime.truncate(:millisecond)

add_metrics(device_id, now, a_week_ago)
end

@doc """
Runs recursively until current timestamp is less than or equal to ending timestamp
"""
def add_metrics(device_id, current_timestamp, ending_timestamp)
when current_timestamp <= ending_timestamp,
do: save_metrics(device_id, current_timestamp)

def add_metrics(device_id, current_timestamp, ending_timestamp) do
save_metrics(device_id, current_timestamp)

new_timestamp = DateTime.add(current_timestamp, -20, :minute)
add_metrics(device_id, new_timestamp, ending_timestamp)
end

def save_metrics(device_id, current_timestamp) do
metrics = %{
"cpu_temp" => Enum.random(1..100),
"load_15min" => :rand.uniform() |> Float.ceil(2),
"load_1min" => :rand.uniform() |> Float.ceil(2),
"load_5min" => :rand.uniform() |> Float.ceil(2),
"size_mb" => 7892,
"used_mb" => Enum.random(0..7892),
"used_percent" => Enum.random(0..100)
}

Repo.transaction(fn ->
Enum.map(metrics, fn {key, val} ->
DeviceMetric.save_with_timestamp(%{
device_id: device_id,
key: key,
value: val,
inserted_at: current_timestamp
})
|> Repo.insert()
end)
end)
end
end
end
10 changes: 10 additions & 0 deletions lib/nerves_hub/devices/device_metric.ex
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,16 @@ defmodule NervesHub.Devices.DeviceMetric do
|> format_field(:key)
end

@doc """
To use when creating fake metrics with manipulated timestamps
"""
def save_with_timestamp(params) do
%__MODULE__{}
|> cast(params, @required_params ++ [:inserted_at])
|> validate_required(@required_params)
|> format_field(:key)
end

defp format_field(%Changeset{changes: %{key: key}} = cs, :key) do
# Just remove spaces for now.
formatted_key = String.replace(key, " ", "")
Expand Down

0 comments on commit 0046d1d

Please sign in to comment.