epgsql_cth.erl 6.8 KB

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