You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@couchdb.apache.org by ja...@apache.org on 2023/12/12 01:47:06 UTC
(couchdb) 03/03: Remove support for delete markers
This is an automated email from the ASF dual-hosted git repository.
jaydoane pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/couchdb.git
commit 0eca498ed1fa9286746dc9a8667cf7174b15c350
Author: Jay Doane <ja...@apache.org>
AuthorDate: Sun Nov 26 16:12:46 2023 -0800
Remove support for delete markers
Currently, `config:reload()` ignores so-called "delete markers" [1],
denoted by a a key and equal sign, but no value on the right hand
side, e.g.
```ini
key =
```
However, when the `config` application starts, and it parses the
`.ini` files in order, it deletes any existing value from the `ets`
table with that key when it encounters a delete marker. This has the
effect of *overriding* any defaults with `undefined`, which some
people find surprising. [2]
Luckily, the origin of delete markers is not lost to time, and the
original developer has admitted they were essentially a work-around
[3] for not having a proper `.ini` file parser.
This change removes support for delete markers. A persistent call to
`config:delete` no longer writes a delete marker, but instead deletes
the entire line. When parsing `.ini` files, any existing delete
markers are ignored.
Additionally, this change improves consistency after `config:delete`
by loading any values from `.ini` files into the `ets` table
subsequent to the deletion.
[1] https://github.com/apache/couchdb/issues/4892
[2] https://github.com/apache/couchdb/issues/1624
[3] https://couchdb.slack.com/archives/C01TBE2J197/p1701718345541559?thread_ts=1701712487.990349&cid=C01TBE2J197
---
src/chttpd/test/eunit/chttpd_auth_tests.erl | 2 +-
src/config/src/config.erl | 130 +++++++++++++++-------------
src/config/src/config.hrl | 13 +++
src/config/src/config_writer.erl | 15 +++-
src/config/test/config_tests.erl | 82 +++++++++++++++++-
src/docs/src/config/intro.rst | 11 ---
6 files changed, 173 insertions(+), 80 deletions(-)
diff --git a/src/chttpd/test/eunit/chttpd_auth_tests.erl b/src/chttpd/test/eunit/chttpd_auth_tests.erl
index 93ddb8cc6..6745bb31c 100644
--- a/src/chttpd/test/eunit/chttpd_auth_tests.erl
+++ b/src/chttpd/test/eunit/chttpd_auth_tests.erl
@@ -41,11 +41,11 @@ setup_proxy_auth() ->
{{StartCtx, ProxyCfgFile}, HashesShouldWork, HashesShouldFail, SupportedHashAlgorithms}.
teardown_proxy_auth({{Ctx, ProxyCfgFile}, _, _, _}) ->
- ok = file:delete(ProxyCfgFile),
config:delete("chttpd_auth", "hash_algorithms", false),
config:delete("chttpd_auth", "secret", false),
config:delete("chttpd_auth", "proxy_use_secret", false),
config:delete("chttpd", "require_valid_user", false),
+ ok = file:delete(ProxyCfgFile),
test_util:stop_couch(Ctx).
require_valid_user_exception_test_() ->
diff --git a/src/config/src/config.erl b/src/config/src/config.erl
index 6f4255424..417a104c5 100644
--- a/src/config/src/config.erl
+++ b/src/config/src/config.erl
@@ -46,7 +46,8 @@
-define(INVALID_SECTION, <<"Invalid configuration section">>).
-define(INVALID_KEY, <<"Invalid configuration key">>).
-define(INVALID_VALUE, <<"Invalid configuration value">>).
--define(DELETE, delete).
+
+-include("config.hrl").
-record(config, {
ini_files = undefined,
@@ -247,12 +248,11 @@ subscribe_for_changes(Subscription) ->
init(IniFiles) ->
enable_early_features(),
ets:new(?MODULE, [named_table, set, protected, {read_concurrency, true}]),
- lists:map(
- fun(IniFile) ->
- {ok, ParsedIniValues} = parse_ini_file(IniFile),
- ets:insert(?MODULE, ParsedIniValues)
+ maps:foreach(
+ fun(K, V) ->
+ true = ets:insert(?MODULE, {K, V})
end,
- IniFiles
+ ini_map(IniFiles)
),
WriteFile =
case IniFiles of
@@ -311,10 +311,17 @@ handle_call({delete, Sec, Key, Persist, Reason}, _From, Config) ->
{true, undefined} ->
ok;
{true, FileName} ->
- config_writer:save_to_file({{Sec, Key}, ""}, FileName);
+ config_writer:save_to_file({{Sec, Key}, ?DELETE}, FileName);
_ ->
ok
end,
+ IniMap = ini_map(Config#config.ini_files),
+ case maps:find({Sec, Key}, IniMap) of
+ {ok, Val} ->
+ true = ets:insert(?MODULE, {{Sec, Key}, Val});
+ _ ->
+ ok
+ end,
case ConfigDeleteReturn of
ok ->
Event = {config_change, Sec, Key, deleted, Persist},
@@ -324,26 +331,12 @@ handle_call({delete, Sec, Key, Persist, Reason}, _From, Config) ->
{reply, Else, Config}
end;
handle_call(reload, _From, Config) ->
- DiskKVs = lists:foldl(
- fun(IniFile, DiskKVs0) ->
- {ok, ParsedIniValues} = parse_ini_file(IniFile),
- lists:foldl(
- fun({K, V}, DiskKVs1) ->
- dict:store(K, V, DiskKVs1)
- end,
- DiskKVs0,
- ParsedIniValues
- )
- end,
- dict:new(),
- Config#config.ini_files
- ),
- % Update ets with anything we just read
- % from disk
- dict:fold(
- fun({Sec, Key} = K, V, _) ->
+ % Update ets with ini values.
+ IniMap = ini_map(Config#config.ini_files),
+ maps:foreach(
+ fun({Sec, Key} = K, V) ->
VExisting = get(Sec, Key, V),
- ets:insert(?MODULE, {K, V}),
+ true = ets:insert(?MODULE, {K, V}),
case V =:= VExisting of
true ->
ok;
@@ -356,22 +349,21 @@ handle_call(reload, _From, Config) ->
gen_event:sync_notify(config_event, Event)
end
end,
- nil,
- DiskKVs
+ IniMap
),
- % And remove anything in ets that wasn't
- % on disk.
+ % And remove anything in ets that wasn't on disk.
ets:foldl(
- fun({{Sec, Key} = K, _}, _) ->
- case dict:is_key(K, DiskKVs) of
- true ->
- ok;
- false ->
- couch_log:notice("Reload deleting in-memory config ~s.~s", [Sec, Key]),
- ets:delete(?MODULE, K),
- Event = {config_change, Sec, Key, deleted, true},
- gen_event:sync_notify(config_event, Event)
- end
+ fun
+ ({{Sec, Key} = K, _}, _) when not is_map_key(K, IniMap) ->
+ couch_log:notice(
+ "Reload deleting in-memory config ~s.~s",
+ [Sec, Key]
+ ),
+ ets:delete(?MODULE, K),
+ Event = {config_change, Sec, Key, deleted, true},
+ gen_event:sync_notify(config_event, Event);
+ (_, _) ->
+ ok
end,
nil,
?MODULE
@@ -400,10 +392,21 @@ is_sensitive(Section, Key) ->
_ -> false
end.
+ini_map(IniFiles) ->
+ lists:foldl(
+ fun(IniFile, IniMap0) ->
+ {ok, Props} = parse_ini_file(IniFile),
+ IniMap = maps:from_list(Props),
+ maps:merge(IniMap0, IniMap)
+ end,
+ #{},
+ IniFiles
+ ).
+
parse_ini_file(IniFile) ->
IniBin = read_ini_file(IniFile),
ParsedIniValues = parse_ini(IniBin),
- {ok, lists:filter(fun delete_keys/1, ParsedIniValues)}.
+ {ok, ParsedIniValues}.
parse_ini(IniBin) when is_binary(IniBin) ->
Lines0 = re:split(IniBin, "\r\n|\n|\r|\032", [{return, list}]),
@@ -432,10 +435,9 @@ parse_fold(Line, {Section, KVs}) ->
[_] ->
% Failed to split on " = ", so try to split on "=".
% If the line starts with "=" or it's not a KV pair, ignore it.
- % An empty value emit the `delete` atom as a marker.
case string:split(Line, "=") of
["", _] -> {Section, KVs};
- [K, ""] -> {Section, [{{Section, trim(K)}, ?DELETE} | KVs]};
+ [_, ""] -> {Section, KVs};
[K, V] -> {Section, [{{Section, trim(K)}, trim(V)} | KVs]};
[_] -> {Section, KVs}
end
@@ -465,14 +467,6 @@ remove_comments(Line) ->
NoComments
end.
-% Specially handle the ?DELETE marker
-%
-delete_keys({{Section, Key}, ?DELETE}) ->
- ets:delete(?MODULE, {Section, Key}),
- false;
-delete_keys({{_, _}, _}) ->
- true.
-
trim(String) ->
% May look silly but we're using this quite a bit
string:trim(String).
@@ -666,17 +660,17 @@ parse_extra_equal_sign_test() ->
?assertEqual([{{"s", "==k=="}, "v"}], ini("[s]\n==k== = v")).
parse_delete_test() ->
- ?assertEqual([{{"s", "k"}, ?DELETE}], ini("[s]\nk=")),
- ?assertEqual([{{"s", "k"}, ?DELETE}], ini("[s]\nk =")),
- ?assertEqual([{{"s", "k"}, ?DELETE}], ini("[s]\nk = ")),
- ?assertEqual([{{"s", "k"}, ?DELETE}], ini("[s]\nk= ")),
- ?assertEqual([{{"s", "k"}, ?DELETE}], ini("[s]\nk = ")),
- ?assertEqual([{{"s", "k"}, ?DELETE}], ini("[s]\nk = ;")),
- ?assertEqual([{{"s", "k"}, ?DELETE}], ini("[s]\nk =\t;")),
- ?assertEqual([{{"s", "k"}, ?DELETE}], ini("[s]\nk=\n")),
- ?assertEqual([{{"s", "k"}, ?DELETE}], ini("[s]\nk = ; ;")),
- ?assertEqual([{{"s", "k"}, ?DELETE}], ini("[s]\nk = ;v")),
- ?assertEqual([{{"s", "k"}, ?DELETE}], ini("[s]\nk = ;")).
+ ?assertEqual([], ini("[s]\nk=")),
+ ?assertEqual([], ini("[s]\nk =")),
+ ?assertEqual([], ini("[s]\nk = ")),
+ ?assertEqual([], ini("[s]\nk= ")),
+ ?assertEqual([], ini("[s]\nk = ")),
+ ?assertEqual([], ini("[s]\nk = ;")),
+ ?assertEqual([], ini("[s]\nk =\t;")),
+ ?assertEqual([], ini("[s]\nk=\n")),
+ ?assertEqual([], ini("[s]\nk = ; ;")),
+ ?assertEqual([], ini("[s]\nk = ;v")),
+ ?assertEqual([], ini("[s]\nk = ;")).
parse_comments_test() ->
?assertEqual([], ini("[s]\n;k=v")),
@@ -724,4 +718,16 @@ parse_multiple_kvs_test() ->
ini("[s]\nk1=v1\ngarbage\n= more garbage\nk2=v2")
).
+read_non_existent_ini_file_test_() ->
+ {
+ setup,
+ fun() -> meck:expect(couch_log, error, fun(_, _) -> ok end) end,
+ fun(_) -> meck:unload() end,
+ [
+ ?_assertException(
+ throw, {startup_error, _}, read_ini_file("non-existent")
+ )
+ ]
+ }.
+
-endif.
diff --git a/src/config/src/config.hrl b/src/config/src/config.hrl
new file mode 100644
index 000000000..7b7813ae9
--- /dev/null
+++ b/src/config/src/config.hrl
@@ -0,0 +1,13 @@
+% 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.
+
+-define(DELETE, delete).
diff --git a/src/config/src/config_writer.erl b/src/config/src/config_writer.erl
index 2417416c3..98eb54ae9 100644
--- a/src/config/src/config_writer.erl
+++ b/src/config/src/config_writer.erl
@@ -22,6 +22,8 @@
-export([save_to_file/2]).
+-include("config.hrl").
+
%% @spec save_to_file(
%% Config::{{Section::string(), Option::string()}, Value::string()},
%% File::filename()) -> ok
@@ -43,7 +45,7 @@ process_file_lines([Line | Rest], SeenLines, Section, Pattern, Key, Value) ->
process_file_lines(Rest, [Line | SeenLines], Section, Pattern, Key, Value);
process_file_lines([], SeenLines, Section, _Pattern, Key, Value) ->
% Section wasn't found. Append it with the option here.
- [Key ++ " = " ++ Value, Section, "" | strip_empty_lines(SeenLines)].
+ [maybe_kv(Key, Value), Section, "" | strip_empty_lines(SeenLines)].
process_section_lines([Line | Rest], SeenLines, Pattern, Key, Value) ->
case re:run(Line, Pattern, [{capture, all_but_first}]) of
@@ -53,14 +55,14 @@ process_section_lines([Line | Rest], SeenLines, Pattern, Key, Value) ->
% Found another section. Append the option here.
{match, []} ->
lists:reverse(Rest) ++
- [Line, "", Key ++ " = " ++ Value | strip_empty_lines(SeenLines)];
+ [Line, "", maybe_kv(Key, Value) | strip_empty_lines(SeenLines)];
% Found the option itself. Replace it.
{match, _} ->
- lists:reverse(Rest) ++ [Key ++ " = " ++ Value | SeenLines]
+ lists:reverse(Rest) ++ [maybe_kv(Key, Value) | SeenLines]
end;
process_section_lines([], SeenLines, _Pattern, Key, Value) ->
% Found end of file within the section. Append the option here.
- [Key ++ " = " ++ Value | strip_empty_lines(SeenLines)].
+ [maybe_kv(Key, Value) | strip_empty_lines(SeenLines)].
reverse_and_add_newline([Line | Rest], Content) ->
reverse_and_add_newline(Rest, [Line, "\n", Content]);
@@ -71,3 +73,8 @@ strip_empty_lines(["" | Rest]) ->
strip_empty_lines(Rest);
strip_empty_lines(All) ->
All.
+
+maybe_kv(_, ?DELETE) ->
+ "";
+maybe_kv(Key, Value) ->
+ Key ++ " = " ++ Value.
diff --git a/src/config/test/config_tests.erl b/src/config/test/config_tests.erl
index dc83d2c72..8c0f29ec0 100644
--- a/src/config/test/config_tests.erl
+++ b/src/config/test/config_tests.erl
@@ -111,6 +111,35 @@ handle_config_terminate(Self, Reason, {Pid, State}) ->
Pid ! {config_msg, {Self, Reason, State}},
ok.
+setup_ini() ->
+ Chain = [write_ini(F) || F <- ["default.ini", "local.ini"]],
+ {Chain, setup(Chain)}.
+
+teardown_ini({Chain, Apps}) ->
+ lists:foreach(
+ fun(Path) -> ok = file:delete(Path) end,
+ Chain
+ ),
+ teardown(Apps).
+
+write_ini(FileName) ->
+ Path = filename:join([?TEMPDIR, FileName]),
+ Data = io_lib:format("[section]\nfile = ~s\n", [FileName]),
+ ok = file:write_file(Path, Data),
+ Path.
+
+config_delete_reload_restart_test_() ->
+ {
+ "Test consistency after set, delete, reload, and restart",
+ foreach,
+ fun setup_ini/0,
+ fun teardown_ini/1,
+ [
+ fun non_persistent_set_delete_reload_restart/0,
+ fun persistent_set_delete_reload_restart/0
+ ]
+ }.
+
config_get_test_() ->
{
"Config get tests",
@@ -140,7 +169,8 @@ config_set_test_() ->
[
fun should_update_option/0,
fun should_create_new_section/0,
- fun should_fail_to_set_binary_value/0
+ fun should_fail_to_set_binary_value/0,
+ fun should_fail_to_set_invalid_sensitive_key/0
]
}
}.
@@ -386,6 +416,16 @@ should_fail_to_set_binary_value() ->
config:set(<<"a">>, <<"b">>, <<"c">>, false)
).
+should_fail_to_set_invalid_sensitive_key() ->
+ ?assertEqual(
+ {error, <<"Invalid configuration key">>},
+ config:set("admins", "[]", "val")
+ ),
+ ?assertEqual(
+ "'****'",
+ lists:nth(4, meck:capture(first, couch_log, error, ['_', '_'], 2))
+ ).
+
should_return_undefined_atom_after_option_deletion() ->
?assertEqual(ok, config:delete("mock_log", "level", false)),
?assertEqual(undefined, config:get("mock_log", "level")).
@@ -438,7 +478,7 @@ should_write_changes(_, _) ->
?assertEqual(ok, config:set("httpd", "port", "8080")),
?assertEqual("8080", config:get("httpd", "port")),
?assertEqual(ok, config:delete("httpd", "bind_address")),
- ?assertEqual(undefined, config:get("httpd", "bind_address"))
+ ?assertEqual("127.0.0.1", config:get("httpd", "bind_address"))
end).
should_ensure_default_wasnt_modified(_, _) ->
@@ -706,6 +746,44 @@ should_notify_on_config_reload_flush(Subscription, {_Apps, Pid}) ->
end)
}.
+persistent_set_delete_reload_restart() ->
+ Persist = true,
+ ?assertEqual("local.ini", config:get("section", "file")),
+ ?assertEqual(ok, config:set("section", "file", "memory", Persist)),
+ ?assertEqual("memory", config:get("section", "file")),
+ ?assertEqual(ok, config:delete("section", "file", Persist)),
+ ?assertEqual("default.ini", config:get("section", "file")),
+ ?assertEqual(ok, config:reload()),
+ ?assertEqual("default.ini", config:get("section", "file")),
+ with_process_restart(config),
+ % Avoid race with config loading .ini files
+ wait_config_get("section", "file", "default.ini"),
+ ?assertEqual("default.ini", config:get("section", "file")).
+
+non_persistent_set_delete_reload_restart() ->
+ Persist = false,
+ ?assertEqual("local.ini", config:get("section", "file")),
+ ?assertEqual(ok, config:set("section", "file", "memory", Persist)),
+ ?assertEqual("memory", config:get("section", "file")),
+ ?assertEqual(ok, config:delete("section", "file", Persist)),
+ ?assertEqual("local.ini", config:get("section", "file")),
+ ?assertEqual(ok, config:reload()),
+ ?assertEqual("local.ini", config:get("section", "file")),
+ with_process_restart(config),
+ % Avoid race with config loading .ini files
+ wait_config_get("section", "file", "local.ini"),
+ ?assertEqual("local.ini", config:get("section", "file")).
+
+wait_config_get(Sec, Key, Val) ->
+ test_util:wait(
+ fun() ->
+ case config:get(Sec, Key) of
+ V when V =:= Val -> ok;
+ _ -> wait
+ end
+ end
+ ).
+
spawn_config_listener() ->
Self = self(),
Pid = erlang:spawn(fun() ->
diff --git a/src/docs/src/config/intro.rst b/src/docs/src/config/intro.rst
index 10e26b251..64188d491 100644
--- a/src/docs/src/config/intro.rst
+++ b/src/docs/src/config/intro.rst
@@ -125,17 +125,6 @@ the parameter and value are separated `` = ``, i.e. the equal sign is surrounded
by at least one space on each side. This might be useful in the ``[jwt_keys]``
section, where base64 encoded keys may contain some ``=`` characters.
-.. note::
- In case when you'd like to remove some parameter from the `default.ini`
- without modifying that file, you may override in `local.ini`, but without
- any value::
-
- [compactions]
- _default =
-
- This could be read as: "remove the `_default` parameter from the
- `compactions` section if it was ever set before".
-
The semicolon (``;``) signals the start of a comment. Everything after this
character is ignored by CouchDB.