epgsql_cth.erl 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. -module(epgsql_cth).
  2. -export([
  3. init/2,
  4. terminate/1,
  5. pre_init_per_suite/3,
  6. to_proplist/1
  7. ]).
  8. -include_lib("common_test/include/ct.hrl").
  9. -include("epgsql_tests.hrl").
  10. init(_Id, State) ->
  11. Start = os:timestamp(),
  12. PgConfig = start_postgres(),
  13. ok = create_testdbs(PgConfig),
  14. ct:pal(info, "postgres started in ~p ms\n",
  15. [timer:now_diff(os:timestamp(), Start) / 1000]),
  16. [{pg_config, PgConfig}|State].
  17. pre_init_per_suite(_SuiteName, Config, State) ->
  18. {Config ++ State, State}.
  19. terminate(State) ->
  20. ok = stop_postgres(?config(pg_config, State)).
  21. create_testdbs(Config) ->
  22. PgHost = ?config(host, Config),
  23. PgPort = ?config(port, Config),
  24. PgUser = ?config(user, Config),
  25. Utils = ?config(utils, Config),
  26. Psql = ?config(psql, Utils),
  27. CreateDB = ?config(createdb, Utils),
  28. Opts = lists:concat([" -h ", PgHost, " -p ", PgPort, " "]),
  29. Cmds = [
  30. [CreateDB, Opts, PgUser],
  31. [Psql, Opts, "template1 < ", filename:join(?TEST_DATA_DIR, "test_schema.sql")]
  32. ],
  33. lists:foreach(fun(Cmd) ->
  34. {ok, []} = exec:run(lists:flatten(Cmd), [sync])
  35. end, Cmds).
  36. %% =============================================================================
  37. %% start postgresql
  38. %% =============================================================================
  39. -define(PG_TIMEOUT, 30000).
  40. start_postgres() ->
  41. ok = application:start(erlexec),
  42. pipe([
  43. fun find_utils/1,
  44. fun init_database/1,
  45. fun write_postgresql_config/1,
  46. fun copy_certs/1,
  47. fun write_pg_hba_config/1,
  48. fun start_postgresql/1
  49. ], []).
  50. stop_postgres(Config) ->
  51. PgProc = ?config(proc, Config),
  52. PgProc ! stop,
  53. ok.
  54. find_utils(State) ->
  55. Utils = [initdb, createdb, postgres, psql],
  56. UtilsConfig = lists:foldl(fun(U, Acc) ->
  57. UList = atom_to_list(U),
  58. Path = case os:find_executable(UList) of
  59. false ->
  60. case filelib:wildcard("/usr/lib/postgresql/**/bin/" ++ UList) of
  61. [] ->
  62. ct:pal(error, "~s not found", [U]),
  63. throw({util_no_found, U});
  64. List -> lists:last(lists:sort(List))
  65. end;
  66. P -> P
  67. end,
  68. [{U, Path}|Acc]
  69. end, [], Utils),
  70. [{utils, UtilsConfig}|State].
  71. start_postgresql(Config) ->
  72. PgDataDir = ?config(datadir, Config),
  73. Utils = ?config(utils, Config),
  74. Postgres = ?config(postgres, Utils),
  75. PgHost = "localhost",
  76. PgPort = get_free_port(),
  77. SocketDir = "/tmp",
  78. Command = lists:concat(
  79. [Postgres,
  80. " -k ", SocketDir,
  81. " -D ", PgDataDir,
  82. " -h ", PgHost,
  83. " -p ", PgPort]),
  84. ct:pal(info, ?HI_IMPORTANCE, "Starting Postgresql: `~s`", [Command]),
  85. Pid = proc_lib:spawn(fun() ->
  86. {ok, _, I} = exec:run_link(Command,
  87. [{stderr,
  88. fun(_, _, Msg) ->
  89. ct:pal(info, "postgres: ~s", [Msg])
  90. end}]),
  91. loop(I)
  92. end),
  93. ConfigR = [
  94. {host, PgHost},
  95. {port, PgPort},
  96. {proc, Pid}
  97. | Config
  98. ],
  99. wait_postgresql_ready(SocketDir, ConfigR).
  100. loop(I) ->
  101. receive
  102. stop -> exec:kill(I, 0);
  103. _ -> loop(I)
  104. end.
  105. wait_postgresql_ready(SocketDir, Config) ->
  106. PgPort = ?config(port, Config),
  107. PgFile = lists:concat([".s.PGSQL.", PgPort]),
  108. Path = filename:join(SocketDir, PgFile),
  109. WaitUntil = ts_add(os:timestamp(), ?PG_TIMEOUT),
  110. case wait_(Path, WaitUntil) of
  111. true -> ok;
  112. false -> throw(<<"Postgresql init timeout">>)
  113. end,
  114. Config.
  115. wait_(Path, Until) ->
  116. case file:read_file_info(Path) of
  117. {error, enoent} ->
  118. case os:timestamp() > Until of
  119. true -> false;
  120. _ ->
  121. timer:sleep(300),
  122. wait_(Path, Until)
  123. end;
  124. _ -> true
  125. end.
  126. init_database(Config) ->
  127. Utils = ?config(utils, Config),
  128. Initdb = ?config(initdb, Utils),
  129. {ok, Cwd} = file:get_cwd(),
  130. PgDataDir = filename:append(Cwd, "datadir"),
  131. {ok, _} = exec:run(Initdb ++ " --locale en_US.UTF8 " ++ PgDataDir, [sync,stdout,stderr]),
  132. [{datadir, PgDataDir}|Config].
  133. write_postgresql_config(Config) ->
  134. PgDataDir = ?config(datadir, Config),
  135. PGConfig = [
  136. "ssl = on\n",
  137. "ssl_ca_file = 'root.crt'\n",
  138. "lc_messages = 'en_US.UTF-8'\n",
  139. "wal_level = 'logical'\n",
  140. "max_replication_slots = 15\n",
  141. "max_wal_senders = 15"
  142. ],
  143. FilePath = filename:join(PgDataDir, "postgresql.conf"),
  144. ok = file:write_file(FilePath, PGConfig),
  145. Config.
  146. copy_certs(Config) ->
  147. PgDataDir = ?config(datadir, Config),
  148. Files = [
  149. {"epgsql.crt", "server.crt", 8#00660},
  150. {"epgsql.key", "server.key", 8#00600},
  151. {"root.crt", "root.crt", 8#00660},
  152. {"root.key", "root.key", 8#00660}
  153. ],
  154. lists:foreach(fun({From, To, Mode}) ->
  155. FromPath = filename:join(?TEST_DATA_DIR, From),
  156. ToPath = filename:join(PgDataDir, To),
  157. {ok, _} = file:copy(FromPath, ToPath),
  158. ok = file:change_mode(ToPath, Mode)
  159. end, Files),
  160. Config.
  161. write_pg_hba_config(Config) ->
  162. PgDataDir = ?config(datadir, Config),
  163. User = os:getenv("USER"),
  164. PGConfig = [
  165. "local all ", User, " trust\n",
  166. "host template1 ", User, " 127.0.0.1/32 trust\n",
  167. "host ", User, " ", User, " 127.0.0.1/32 trust\n",
  168. "hostssl postgres ", User, " 127.0.0.1/32 trust\n",
  169. "host epgsql_test_db1 ", User, " 127.0.0.1/32 trust\n",
  170. "host epgsql_test_db1 epgsql_test 127.0.0.1/32 trust\n",
  171. "host epgsql_test_db1 epgsql_test_md5 127.0.0.1/32 md5\n",
  172. "host epgsql_test_db1 epgsql_test_cleartext 127.0.0.1/32 password\n",
  173. "hostssl epgsql_test_db1 epgsql_test_cert 127.0.0.1/32 cert clientcert=1\n",
  174. "host replication epgsql_test_replication 127.0.0.1/32 trust"
  175. ],
  176. FilePath = filename:join(PgDataDir, "pg_hba.conf"),
  177. ok = file:write_file(FilePath, PGConfig),
  178. [{user, User}|Config].
  179. %% =============================================================================
  180. %% Internal functions
  181. %% =============================================================================
  182. get_free_port() ->
  183. {ok, Listen} = gen_tcp:listen(0, []),
  184. {ok, Port} = inet:port(Listen),
  185. ok = gen_tcp:close(Listen),
  186. Port.
  187. pipe(Funs, Config) ->
  188. lists:foldl(fun(F, S) -> F(S) end, Config, Funs).
  189. ts_add({Mega, Sec, Micro}, Timeout) ->
  190. V = (Mega * 1000000 + Sec)*1000000 + Micro + Timeout * 1000,
  191. {V div 1000000000000,
  192. V div 1000000 rem 1000000,
  193. V rem 1000000}.
  194. to_proplist(List) when is_list(List) ->
  195. List;
  196. to_proplist(Map) ->
  197. maps:to_list(Map).