diff --git a/.gitignore b/.gitignore index 45e6da1..009971c 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,4 @@ erl_crash.dump elstat-*.tar *.db +config/config.exs \ No newline at end of file diff --git a/lib/api.ex b/lib/api.ex index e01c07e..836087e 100644 --- a/lib/api.ex +++ b/lib/api.ex @@ -1,4 +1,4 @@ -defmodule Elstat.API.Status do +defmodule Elstat.API.CurrentStatus do require Logger def init(req0, state) do @@ -13,3 +13,21 @@ defmodule Elstat.API.Status do {:ok, req, state} end end + +defmodule Elstat.API.Status do + def init(req0, state) do + status = Elstat.Manager.get_current_state() + graph = Elstat.Manager.get_graph_state() + + req = :cowboy_req.reply(200, + %{"content-type" => "text/json"}, + Poison.encode!(%{ + status: status, + graph: graph, + }), + req0 + ) + + {:ok, req, state} + end +end diff --git a/lib/cowboy.ex b/lib/cowboy.ex index 38d8b8e..0e4b649 100644 --- a/lib/cowboy.ex +++ b/lib/cowboy.ex @@ -32,7 +32,8 @@ defmodule Elstat.Cowboy do {:_, [ {"/", :cowboy_static, {:file, "static/index.html"}}, {"/hewwo", Elstat.Cowboy.DefaultHandler, []}, - {"/api/current_status", Elstat.API.Status, []}, + {"/api/current_status", Elstat.API.CurrentStatus, []}, + {"/api/status", Elstat.API.Status, []} ]} ]) diff --git a/lib/manager.ex b/lib/manager.ex index 574f47f..92c808d 100644 --- a/lib/manager.ex +++ b/lib/manager.ex @@ -67,6 +67,10 @@ defmodule Elstat.Manager do GenServer.call(man_pid, {:get_current}) end + def get_graph_state() do + man_pid = :global.whereis_name Elstat.Manager + GenServer.call(man_pid, {:get_graph}) + end # server callbacks @@ -151,6 +155,43 @@ defmodule Elstat.Manager do {:reply, reply, state} end + def handle_call({:get_graph}, _from, state) do + graph_reply = state.serv_state + |> Map.keys + |> Enum.map(fn key -> + spec = state.services[key].adapter.adapter_spec + + if Enum.member?(spec.db_columns, :latency) do + {:ok, result} = Sqlitex.with_db('elstat.db', fn db -> + query = """ + SELECT timestamp, latency FROM #{Atom.to_string key} + ORDER BY timestamp DESC + LIMIT 50 + """ + + Logger.debug "query for latency: #{query}" + + Sqlitex.query(db, query) + end) + + act = result + |> Enum.map(fn field -> + [Keyword.get(field, :timestamp), Keyword.get(field, :latency)] + end) + + {key, act} + else + nil + end + end) + |> Enum.filter(fn d -> d != nil end) + |> Map.new + + Logger.debug "graph reply: #{inspect graph_reply}" + + {:reply, graph_reply, state} + end + def build_insert_query(service_id, state) do services = state.services service = services[service_id]