feat(acl): internal acl should support metrics(client.acl.ignore/allow/deny).

This commit is contained in:
zhongwencool 2022-01-19 17:58:49 +08:00
parent 30e07307e9
commit e1274e1117
1 changed files with 26 additions and 4 deletions

View File

@ -38,12 +38,26 @@
-type(acl_rules() :: #{publish => [emqx_access_rule:rule()], -type(acl_rules() :: #{publish => [emqx_access_rule:rule()],
subscribe => [emqx_access_rule:rule()]}). subscribe => [emqx_access_rule:rule()]}).
-record(acl_metrics, {
allow = 'client.acl.allow',
deny = 'client.acl.deny',
ignore = 'client.acl.ignore'
}).
-define(METRICS(Type), tl(tuple_to_list(#Type{}))).
-define(METRICS(Type, K), #Type{}#Type.K).
-define(ACL_METRICS, ?METRICS(acl_metrics)).
-define(ACL_METRICS(K), ?METRICS(acl_metrics, K)).
%%-------------------------------------------------------------------- %%--------------------------------------------------------------------
%% API %% API
%%-------------------------------------------------------------------- %%--------------------------------------------------------------------
load(Env) -> load(Env) ->
Rules = rules_from_file(proplists:get_value(acl_file, Env)), Rules = rules_from_file(proplists:get_value(acl_file, Env)),
register_metrics(),
emqx_hooks:add('client.check_acl', {?MODULE, check_acl, [Rules]}, -1). emqx_hooks:add('client.check_acl', {?MODULE, check_acl, [Rules]}, -1).
unload(_Env) -> unload(_Env) ->
@ -68,9 +82,15 @@ description() ->
-> {ok, allow} | {ok, deny} | ok). -> {ok, allow} | {ok, deny} | ok).
check_acl(Client, PubSub, Topic, _AclResult, Rules) -> check_acl(Client, PubSub, Topic, _AclResult, Rules) ->
case match(Client, Topic, lookup(PubSub, Rules)) of case match(Client, Topic, lookup(PubSub, Rules)) of
{matched, allow} -> {ok, allow}; {matched, allow} ->
{matched, deny} -> {ok, deny}; emqx_metrics:inc(?ACL_METRICS(allow)),
nomatch -> ok {ok, allow};
{matched, deny} ->
emqx_metrics:inc(?ACL_METRICS(deny)),
{ok, deny};
nomatch ->
emqx_metrics:inc(?ACL_METRICS(ignore)),
ok
end. end.
%%-------------------------------------------------------------------- %%--------------------------------------------------------------------
@ -107,6 +127,9 @@ rules_from_file(AclFile) ->
#{} #{}
end. end.
register_metrics() ->
lists:foreach(fun emqx_metrics:ensure/1, ?ACL_METRICS).
filter(_PubSub, {allow, all}) -> filter(_PubSub, {allow, all}) ->
true; true;
filter(_PubSub, {deny, all}) -> filter(_PubSub, {deny, all}) ->
@ -119,4 +142,3 @@ filter(subscribe, {_AllowDeny, _Who, subscribe, _Topics}) ->
true; true;
filter(_PubSub, {_AllowDeny, _Who, _, _Topics}) -> filter(_PubSub, {_AllowDeny, _Who, _, _Topics}) ->
false. false.