emqx_plugin_kafka_util.erl 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. -module(emqx_plugin_kafka_util).
  2. -include_lib("emqx/include/logger.hrl").
  3. -export([
  4. resource_id/0
  5. , channel_id/1
  6. , check_config/2
  7. ]).
  8. -export([
  9. check_crc32cer_nif/0
  10. ]).
  11. resource_id() ->
  12. <<"emqx_plugin:kafka_producer">>.
  13. client_id(ClientId) ->
  14. <<"emqx_plugin:kafka_client:", (bin(ClientId))/binary>>.
  15. channel_id(Endpoint) ->
  16. <<"emqx_plugin:kafka_producer:connector:", (bin(Endpoint))/binary>>.
  17. bin(Bin) when is_binary(Bin) -> Bin;
  18. bin(Str) when is_list(Str) -> list_to_binary(Str);
  19. bin(Atom) when is_atom(Atom) -> atom_to_binary(Atom, utf8).
  20. check_config(Key, Config) when is_map_key(Key, Config) ->
  21. tr_config(Key, maps:get(Key, Config));
  22. check_config(Key, _Config) ->
  23. throw(#{
  24. reason => missing_required_config,
  25. missing_config => Key
  26. }).
  27. tr_config(bootstrap_hosts, Hosts) ->
  28. hosts(Hosts);
  29. tr_config(client_id, ClientId) ->
  30. client_id(ClientId);
  31. tr_config(sasl, Sasl) ->
  32. sasl(Sasl);
  33. tr_config(ssl, Ssl) ->
  34. ssl(Ssl);
  35. tr_config(_Key, Value) ->
  36. Value.
  37. %% Parse comma separated host:port list into a [{Host,Port}] list
  38. hosts(Hosts) when is_binary(Hosts) ->
  39. hosts(binary_to_list(Hosts));
  40. hosts([#{hostname := _, port := _} | _] = Servers) ->
  41. [{Hostname, Port} || #{hostname := Hostname, port := Port} <- Servers];
  42. hosts(Hosts) when is_list(Hosts) ->
  43. kpro:parse_endpoints(Hosts).
  44. sasl(#{mechanism := Mechanism, username := Username, password := Secret}) ->
  45. {Mechanism, Username, Secret};
  46. sasl(_) ->
  47. undefined.
  48. ssl(#{enable := true} = SSL) ->
  49. emqx_tls_lib:to_client_opts(SSL);
  50. ssl(_) ->
  51. false.
  52. check_crc32cer_nif() ->
  53. try
  54. crc32cer:nif("1")
  55. catch
  56. error:{crc32cer_nif_not_loaded, _}:_ ->
  57. load_crc32cer_nif()
  58. end.
  59. load_crc32cer_nif() ->
  60. code:purge(crc32cer),
  61. code:load_file(crc32cer).