epgsql_cth.erl 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 get_version/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. {env, [{"LANGUAGE", "en"}]}]),
  92. loop(I)
  93. end),
  94. ConfigR = [
  95. {host, PgHost},
  96. {port, PgPort},
  97. {proc, Pid}
  98. | Config
  99. ],
  100. wait_postgresql_ready(SocketDir, ConfigR).
  101. loop(I) ->
  102. receive
  103. stop -> exec:kill(I, 0);
  104. _ -> loop(I)
  105. end.
  106. wait_postgresql_ready(SocketDir, Config) ->
  107. PgPort = ?config(port, Config),
  108. PgFile = lists:concat([".s.PGSQL.", PgPort]),
  109. Path = filename:join(SocketDir, PgFile),
  110. WaitUntil = ts_add(os:timestamp(), ?PG_TIMEOUT),
  111. case wait_(Path, WaitUntil) of
  112. true -> ok;
  113. false -> throw(<<"Postgresql init timeout">>)
  114. end,
  115. Config.
  116. wait_(Path, Until) ->
  117. case file:read_file_info(Path) of
  118. {error, enoent} ->
  119. case os:timestamp() > Until of
  120. true -> false;
  121. _ ->
  122. timer:sleep(300),
  123. wait_(Path, Until)
  124. end;
  125. _ -> true
  126. end.
  127. init_database(Config) ->
  128. Utils = ?config(utils, Config),
  129. Initdb = ?config(initdb, Utils),
  130. {ok, Cwd} = file:get_cwd(),
  131. PgDataDir = filename:append(Cwd, "datadir"),
  132. {ok, _} = exec:run(Initdb ++ " --locale en_US.UTF8 " ++ PgDataDir, [sync,stdout,stderr]),
  133. [{datadir, PgDataDir}|Config].
  134. get_version(Config) ->
  135. Datadir = ?config(datadir, Config),
  136. VersionFile = filename:join(Datadir, "PG_VERSION"),
  137. {ok, VersionFileData} = file:read_file(VersionFile),
  138. VersionBin = list_to_binary(string:strip(binary_to_list(VersionFileData), both, $\n)),
  139. Version = lists:map(fun erlang:binary_to_integer/1,
  140. binary:split(VersionBin, <<".">>, [global])),
  141. [{version, Version} | Config].
  142. write_postgresql_config(Config) ->
  143. PgDataDir = ?config(datadir, Config),
  144. PGConfig = [
  145. "ssl = on\n",
  146. "ssl_ca_file = 'root.crt'\n",
  147. "lc_messages = 'en_US.UTF-8'\n",
  148. "fsync = off\n",
  149. "wal_level = 'logical'\n",
  150. "max_replication_slots = 15\n",
  151. "max_wal_senders = 15"
  152. ],
  153. FilePath = filename:join(PgDataDir, "postgresql.conf"),
  154. ok = file:write_file(FilePath, PGConfig),
  155. Config.
  156. copy_certs(Config) ->
  157. PgDataDir = ?config(datadir, Config),
  158. Files = [
  159. {"server.crt", "server.crt", 8#00660},
  160. {"server.key", "server.key", 8#00600},
  161. {"root.crt", "root.crt", 8#00660},
  162. {"root.key", "root.key", 8#00660}
  163. ],
  164. lists:foreach(fun({From, To, Mode}) ->
  165. FromPath = filename:join(?TEST_DATA_DIR, From),
  166. ToPath = filename:join(PgDataDir, To),
  167. {ok, _} = file:copy(FromPath, ToPath),
  168. ok = file:change_mode(ToPath, Mode)
  169. end, Files),
  170. Config.
  171. write_pg_hba_config(Config) ->
  172. PgDataDir = ?config(datadir, Config),
  173. Version = ?config(version, Config),
  174. User = os:getenv("USER"),
  175. PGConfig = [
  176. "local all ", User, " trust\n",
  177. "host template1 ", User, " 127.0.0.1/32 trust\n",
  178. "host ", User, " ", User, " 127.0.0.1/32 trust\n",
  179. "hostssl postgres ", User, " 127.0.0.1/32 trust\n",
  180. "host epgsql_test_db1 ", User, " 127.0.0.1/32 trust\n",
  181. "host epgsql_test_db1 epgsql_test 127.0.0.1/32 trust\n",
  182. "host epgsql_test_db1 epgsql_test_md5 127.0.0.1/32 md5\n",
  183. "host epgsql_test_db1 epgsql_test_cleartext 127.0.0.1/32 password\n",
  184. "hostssl epgsql_test_db1 epgsql_test_cert 127.0.0.1/32 cert clientcert=1\n",
  185. "host template1 ", User, " ::1/128 trust\n",
  186. "host ", User, " ", User, " ::1/128 trust\n",
  187. "hostssl postgres ", User, " ::1/128 trust\n",
  188. "host epgsql_test_db1 ", User, " ::1/128 trust\n",
  189. "host epgsql_test_db1 epgsql_test ::1/128 trust\n",
  190. "host epgsql_test_db1 epgsql_test_md5 ::1/128 md5\n",
  191. "host epgsql_test_db1 epgsql_test_cleartext ::1/128 password\n",
  192. "hostssl epgsql_test_db1 epgsql_test_cert ::1/128 cert clientcert=1\n" |
  193. case Version >= [10] of
  194. true ->
  195. %% See
  196. %% https://www.postgresql.org/docs/10/static/release-10.html
  197. %% "Change how logical replication uses pg_hba.conf"
  198. ["host epgsql_test_db1 epgsql_test_replication 127.0.0.1/32 trust\n",
  199. %% scram auth method only available on PG >= 10
  200. "host epgsql_test_db1 epgsql_test_scram 127.0.0.1/32 scram-sha-256\n"];
  201. false ->
  202. ["host replication epgsql_test_replication 127.0.0.1/32 trust\n"]
  203. end
  204. ],
  205. FilePath = filename:join(PgDataDir, "pg_hba.conf"),
  206. ok = file:write_file(FilePath, PGConfig),
  207. [{user, User}|Config].
  208. %% =============================================================================
  209. %% Internal functions
  210. %% =============================================================================
  211. get_free_port() ->
  212. {ok, Listen} = gen_tcp:listen(0, []),
  213. {ok, Port} = inet:port(Listen),
  214. ok = gen_tcp:close(Listen),
  215. Port.
  216. pipe(Funs, Config) ->
  217. lists:foldl(fun(F, S) -> F(S) end, Config, Funs).
  218. ts_add({Mega, Sec, Micro}, Timeout) ->
  219. V = (Mega * 1000000 + Sec)*1000000 + Micro + Timeout * 1000,
  220. {V div 1000000000000,
  221. V div 1000000 rem 1000000,
  222. V rem 1000000}.