From d4793aea4dfbf1862bf6ca8eb5cf4279a41b36a4 Mon Sep 17 00:00:00 2001 From: Magnus Ahltorp Date: Fri, 27 Jan 2017 02:02:39 +0100 Subject: Separate erlang config file for reloadable parameters --- src/plopconfig.erl | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/plopconfig.erl (limited to 'src/plopconfig.erl') diff --git a/src/plopconfig.erl b/src/plopconfig.erl new file mode 100644 index 0000000..00b29df --- /dev/null +++ b/src/plopconfig.erl @@ -0,0 +1,57 @@ +%%% Copyright (c) 2017, NORDUnet A/S. +%%% See LICENSE for licensing information. + +-module(plopconfig). +-export([get_env/1, get_env/2, init_table/0, load_config/0]). + +-define(PLOPCONFIG_TABLE, plopconfig). + +init_table() -> + case ets:info(?PLOPCONFIG_TABLE) of + undefined -> + ok; + _ -> + ets:delete(?PLOPCONFIG_TABLE) + end, + ets:new(?PLOPCONFIG_TABLE, [set, public, named_table]), + load_config(). + +keys() -> + KeyList = lists:map(fun ({Key, _Value}) -> Key end, + ets:tab2list(?PLOPCONFIG_TABLE)), + sets:from_list(KeyList). + +load_config() -> + {ok, Filename} = application:get_env(plop, plopconfig), + {ok, File} = file:consult(Filename), + OldKeys = keys(), + lists:foreach( + fun ({Key, Value}) -> + true = ets:insert(?PLOPCONFIG_TABLE, {Key, Value}) + end, hd(File)), + NewKeys = keys(), + RemovedKeys = sets:subtract(OldKeys, NewKeys), + lists:foreach(fun (Key) -> + ets:delete(?PLOPCONFIG_TABLE, Key) + end, sets:to_list(RemovedKeys)), + lager:info("loaded config: new keys ~p old keys ~p removed keys ~p", + [sets:to_list(NewKeys), + sets:to_list(OldKeys), + sets:to_list(RemovedKeys)]), + ok. + +get_env(Key, DefaultValue) -> + case get_env(Key) of + {ok, Value} -> + Value; + _ -> + DefaultValue + end. + +get_env(Key) -> + case ets:lookup(?PLOPCONFIG_TABLE, Key) of + [{_, Value}] -> + {ok, Value}; + [] -> + undefined + end. -- cgit v1.1