summaryrefslogtreecommitdiff
path: root/statusserver/src/statusserver.erl
blob: 81fcd7ac7153388dda0ce0fd78cf945579dd7eeb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
%%% Copyright (c) 2017, NORDUnet A/S.
%%% See LICENSE for licensing information.

-module(statusserver).
-export([init_module/0]).
%% API (URL)
-export([request/4]).

-define(APPURL_PLOP_STATUS, "plop/v1/status").

request(post, ?APPURL_PLOP_STATUS, Service, Input) ->
    case (catch mochijson2:decode(Input)) of
        {error, E} ->
            html("bad input:", E);
        Entries when is_list(Entries) ->
            lists:foreach(fun ({struct, PropList}) ->
                                  Target = proplists:get_value(<<"target">>, PropList),
                                  Source = proplists:get_value(<<"source">>, PropList),
                                  Variable = proplists:get_value(<<"key">>, PropList),
                                  Status = proplists:get_value(<<"value">>, PropList),
                                  set_status(Service, Source, Target, Variable, Status)
                          end, Entries)
    end,
    success({[{result, <<"ok">>}]});
request(get, "", "status", Input) ->
    Now = plop_compat:monotonic_time(millisecond),
    Variables = [{struct, [
                           {service, list_to_binary(Service)},
                           {source, Source},
                           {target, Target},
                           {variable, Variable},
                           {status, Status},
                           {age, (Now - Timestamp) / 1000}
                          ]}  || {{Service, Source, Target, Variable}, Status, Timestamp} <- get_status()],
    success({[{result, Variables}]}).


success(Data) ->
    {200, [{"Content-Type", "text/json"}, {"Access-Control-Allow-Origin", "*"}], mochijson2:encode(Data)}.

html(Text, Input) ->
    {400, [{"Content-Type", "text/html"}],
     io_lib:format(
       "<html><body><p>~n" ++
           "~s~n" ++
           "~p~n" ++
           "</body></html>~n", [Text, Input])}.

-define(STATUSDB_TABLE, statusserver_statusdb).

init_module() ->
    create_statusdb().

create_statusdb() ->
    case ets:info(?STATUSDB_TABLE) of
	undefined ->
	    ok;
	_ ->
	    ets:delete(?STATUSDB_TABLE)
    end,
    ets:new(?STATUSDB_TABLE, [set, public, named_table]).

get_status() ->
    [E || [E] <- ets:match(?STATUSDB_TABLE, '$1')].

set_status(Service, Source, Target, Variable, Status) ->
    lager:info("status: ~p ~p ~p ~p ~p", [Service, Source, Target, Variable, Status]),
    Timestamp = plop_compat:monotonic_time(millisecond),
    true = ets:insert(?STATUSDB_TABLE,
                      {{Service, Source, Target, Variable}, Status, Timestamp}),
    ok.