<commit_before>%  @copyright 2007-2012 Zuse Institute Berlin

%   Licensed under the Apache License, Version 2.0 (the "License");
%   you may not use this file except in compliance with the License.
%   You may obtain a copy of the License at
%
%       http://www.apache.org/licenses/LICENSE-2.0
%
%   Unless required by applicable law or agreed to in writing, software
%   distributed under the License is distributed on an "AS IS" BASIS,
%   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%   See the License for the specific language governing permissions and
%   limitations under the License.

%% @author <NAME> <<EMAIL>>
%% @doc    Config file parser for scalaris.
%% @end
%% @version $Id$
-module(config).
-author('<EMAIL>').
-vsn('$Id$').
-include("scalaris.hrl").

-export([
         start_link/1, start_link/2, init/2,
         read/1, write/2,
         check_config/0,

         cfg_exists/1, cfg_is_atom/1, cfg_is_bool/1, cfg_is_mypid/1,
         cfg_is_ip/1, cfg_is_ip/2, cfg_is_port/1,
         cfg_is_integer/1, cfg_is_float/1,
         cfg_is_tuple/2, cfg_is_tuple/4, cfg_is_list/1, cfg_is_list/3, cfg_is_string/1,
         cfg_is_in_range/3, cfg_is_greater_than/2, cfg_is_greater_than_equal/2,
         cfg_is_less_than/2, cfg_is_less_than_equal/2, cfg_is_in/2, cfg_is_module/1,
         cfg_test_and_error/3,

         system_continue/3,
         system_code_change/4,
         system_terminate/4,
         loop/0
        ]).

%% public functions

%% @doc Reads a config parameter. If it is not found, the application's
%%      environment is checked or failed is returned. The result will be
%%      cached in the config.
-spec read(Key::atom()) -> any() | failed.
read(Key) ->
    % If an environment variable sets a config parameter that is present in the
    % config, it will override the config (see populate_db/1, process_term/1).
    % We can thus first check the ets table and fall back to the environment
    % check afterwards.
    case ets:info(config_ets) of
        undefined ->
            io:format("config not started yet (trying to read ~p)\n", [Key]),
            failed;
        _ ->
            case ets:lookup(config_ets, Key) of
                [{Key, Value}] -> Value;
                [] -> Value = util:app_get_env(Key, failed),
                      case Value of
                          failed -> ok;
                          _ -> case self() =:= erlang:whereis(config) of
                                   true -> ets:insert(config_ets, {Key, Value});
                                   _    -> write(Key, Value)
                               end
                      end,
                      Value
            end
    end.

%% @doc Writes a config parameter.
-spec write(atom(), any()) -> ok.
write(Key, Value) ->
    comm:send_local(config, {write, self(), Key, Value}),
    receive
        {write_done} -> ok
    end.

%% gen_server setup

%% @doc Starts the config process and determines the config files from
%%      the application's environment. If there is no application,
%%      "scalaris.cfg" and "scalaris.local.cfg" are used. If Options
%%      contains a {config, [{Key1, Value1},...]} tuple, each Key is
%%      set to its Value in the config.
-spec start_link(Options::[tuple()]) -> {ok, pid()}.
start_link(Options) ->
    Files = [util:app_get_env(config, "scalaris.cfg"),
             util:app_get_env(local_config, "scalaris.local.cfg")],
    start_link(Files, Options).

%% @doc Starts the config process. If Options contains a {config,
%%      [{Key1, Value1},...]} tuple, each Key is set to its Value in
%%      the config.
-spec start_link(Filename::[file:name()], Options::[tuple()]) -> {ok, pid()}.
start_link(Files, Options) ->
    case whereis(config) of
        Pid when is_pid(Pid) ->
            %% ct:pal("There is already a Config process:~n"),
            {ok, Pid};
        _ ->
            TheFiles = case util:app_get_env(add_config, []) of
                           []         -> Files;
                           ConfigFile -> lists:append(Files, [ConfigFile])
                       end,
%%             error_logger:info_msg("Config files: ~p~n", [TheFiles]),
            Owner = self(),
            Link = spawn_link(?MODULE, init, [TheFiles, Owner]),
            receive
                done -> ok;
                X    -> error_logger:error_msg("unknown config message  ~p", [X])
            end,
            ConfigParameters = case lists:keyfind(config, 1, Options) of
                                   {config, ConfPars} -> ConfPars;
                                   _ -> []
                               end,
            _ = [write(K, V) || {K, V} <- ConfigParameters],
            {ok, Link}
    end.

%@private
-spec init(Files::[file:name()], Owner::pid()) -> no_return().
init(Files, Owner) ->
    erlang:register(config, self()),
    _ = ets:new(config_ets, [set, protected, named_table]),
    _ = [ populate_db(File) || File <- Files],
    case check_config() of
        true -> ok;
        _    -> % wait so the error output can be written:
            init:stop(1),
            receive nothing -> ok end
    end,
    Owner ! done,
    loop().

-spec loop() -> no_return().
loop() ->
    receive
        {write, Pid, Key, Value} ->
            ets:insert(config_ets, {Key, Value}),
            comm:send_local(Pid, {write_done}),
            loop();
        %% handle sys:suspend messages
        {system, From, Msg} ->
            sys:handle_system_msg(Msg, From, self(), config, [], no_state);
        _ ->
            loop()
    end.
<commit_msg>hardened config:check_config/0 against exceptions (previously check_config/0 did not fail in this case and thus the config process did not shut down the Erlang VM)<commit_after>%  @copyright 2007-2012 Zuse Institute Berlin

%   Licensed under the Apache License, Version 2.0 (the "License");
%   you may not use this file except in compliance with the License.
%   You may obtain a copy of the License at
%
%       http://www.apache.org/licenses/LICENSE-2.0
%
%   Unless required by applicable law or agreed to in writing, software
%   distributed under the License is distributed on an "AS IS" BASIS,
%   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%   See the License for the specific language governing permissions and
%   limitations under the License.

%% @author <NAME> <<EMAIL>>
%% @doc    Config file parser for scalaris.
%% @end
%% @version $Id$
-module(config).
-author('<EMAIL>').
-vsn('$Id$').
-include("scalaris.hrl").

-export([
         start_link/1, start_link/2, init/2,
         read/1, write/2,
         check_config/0,

         cfg_exists/1, cfg_is_atom/1, cfg_is_bool/1, cfg_is_mypid/1,
         cfg_is_ip/1, cfg_is_ip/2, cfg_is_port/1,
         cfg_is_integer/1, cfg_is_float/1,
         cfg_is_tuple/2, cfg_is_tuple/4, cfg_is_list/1, cfg_is_list/3, cfg_is_string/1,
         cfg_is_in_range/3, cfg_is_greater_than/2, cfg_is_greater_than_equal/2,
         cfg_is_less_than/2, cfg_is_less_than_equal/2, cfg_is_in/2, cfg_is_module/1,
         cfg_test_and_error/3,

         system_continue/3,
         system_code_change/4,
         system_terminate/4,
         loop/0
        ]).

%% public functions

%% @doc Reads a config parameter. If it is not found, the application's
%%      environment is checked or failed is returned. The result will be
%%      cached in the config.
-spec read(Key::atom()) -> any() | failed.
read(Key) ->
    % If an environment variable sets a config parameter that is present in the
    % config, it will override the config (see populate_db/1, process_term/1).
    % We can thus first check the ets table and fall back to the environment
    % check afterwards.
    case ets:info(config_ets) of
        undefined ->
            io:format("config not started yet (trying to read ~p)\n", [Key]),
            failed;
        _ ->
            case ets:lookup(config_ets, Key) of
                [{Key, Value}] -> Value;
                [] -> Value = util:app_get_env(Key, failed),
                      case Value of
                          failed -> ok;
                          _ -> case self() =:= erlang:whereis(config) of
                                   true -> ets:insert(config_ets, {Key, Value});
                                   _    -> write(Key, Value)
                               end
                      end,
                      Value
            end
    end.

%% @doc Writes a config parameter.
-spec write(atom(), any()) -> ok.
write(Key, Value) ->
    comm:send_local(config, {write, self(), Key, Value}),
    receive
        {write_done} -> ok
    end.

%% gen_server setup

%% @doc Starts the config process and determines the config files from
%%      the application's environment. If there is no application,
%%      "scalaris.cfg" and "scalaris.local.cfg" are used. If Options
%%      contains a {config, [{Key1, Value1},...]} tuple, each Key is
%%      set to its Value in the config.
-spec start_link(Options::[tuple()]) -> {ok, pid()}.
start_link(Options) ->
    Files = [util:app_get_env(config, "scalaris.cfg"),
             util:app_get_env(local_config, "scalaris.local.cfg")],
    start_link(Files, Options).

%% @doc Starts the config process. If Options contains a {config,
%%      [{Key1, Value1},...]} tuple, each Key is set to its Value in
%%      the config.
-spec start_link(Filename::[file:name()], Options::[tuple()]) -> {ok, pid()}.
start_link(Files, Options) ->
    case whereis(config) of
        Pid when is_pid(Pid) ->
            %% ct:pal("There is already a Config process:~n"),
            {ok, Pid};
        _ ->
            TheFiles = case util:app_get_env(add_config, []) of
                           []         -> Files;
                           ConfigFile -> lists:append(Files, [ConfigFile])
                       end,
%%             error_logger:info_msg("Config files: ~p~n", [TheFiles]),
            Owner = self(),
            Link = spawn_link(?MODULE, init, [TheFiles, Owner]),
            receive
                done -> ok;
                X    -> error_logger:error_msg("unknown config message  ~p", [X])
            end,
            ConfigParameters = case lists:keyfind(config, 1, Options) of
                                   {config, ConfPars} -> ConfPars;
                                   _ -> []
                               end,
            _ = [write(K, V) || {K, V} <- ConfigParameters],
            {ok, Link}
    end.

%@private
-spec init(Files::[file:name()], Owner::pid()) -> no_return().
init(Files, Owner) ->
    erlang:register(config, self()),
    _ = ets:new(config_ets, [set, protected, named_table]),
    _ = [ populate_db(File) || File <- Files],
    try check_config() of
        true -> ok;
        _    -> % wait so the error output can be written:
            init:stop(1),
            receive nothing -> ok end
    catch Err:Reason -> % wait so the error output can be written:
            error_logger:error_msg("check_config/0 crashed with: ~.0p:~.0p~nStacktrace:~p~n",
                                   [Err, Reason, erlang:get_stacktrace()]),
            init:stop(1),
            receive nothing -> ok end
    end,
    Owner ! done,
    loop().

-spec loop() -> no_return().
loop() ->
    receive
        {write, Pid, Key, Value} ->
            ets:insert(config_ets, {Key, Value}),
            comm:send_local(Pid, {write_done}),
            loop();
        %% handle sys:suspend messages
        {system, From, Msg} ->
            sys:handle_system_msg(Msg, From, self(), config, [], no_state);
        _ ->
            loop()
    end.

{'fraction_non_alphanumeric': 0.1250215109275512, 'fraction_numerical': 0.009464808122526243, 'mean_word_length': 2.0010327911179964, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 83, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 15, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2431808', 'n_tokens_mistral': 3523, 'n_tokens_neox': 3440, 'n_words': 1011}