meta/test/support/ldap_test_environment.ex

73 lines
2.0 KiB
Elixir

defmodule RecycledCloud.LDAPTestEnvironment do
alias RecycledCloud.LDAP
require Logger
@image "code.ungleich.ch:5050/fnux/e-durable-oci-images/openldap-playground:latest"
defp container_name, do: "ldap-playground-#{System.unique_integer()}"
defp get_runtime_tuple(args) do
runtime = System.find_executable("podman") || System.find_executable("docker")
case System.get_env("CALL_CONTAINER_RUNTIME_AS_ROOT") do
nil -> {runtime, args}
_ -> {System.find_executable("sudo"), [runtime | args]}
end
end
defp wait_for_ldap(poll_every \\ 1000, max \\ 10, current \\ 0) do
case LDAP.connect() do
%{status: :ok, conn: conn} ->
conn |> LDAP.close()
:ok
%{status: :error, conn: _} ->
unless current >= max do
Process.sleep(poll_every)
wait_for_ldap(poll_every, max, current + 1)
else
:timeout
end
end
end
def start() do
container = container_name()
runtime_tuple = get_runtime_tuple([
"run", "--rm", "--name", container, "-p", "3089:389", @image
])
case runtime_tuple do
{nil, _} ->
Logger.error("Could not find a container runtime (required for LDAP environment). Exiting.")
:error
{binary, args} ->
Logger.info("Starting LDAP environment.")
port = Port.open(
{:spawn_executable, binary},
[:binary, args: args]
)
max_loop_count = case System.get_env("LDAP_WAIT_LOOPS") do
nil -> 10
str -> str |> String.to_integer
end
case wait_for_ldap(1000, max_loop_count) do
:ok ->
# Wait for LDAP server to be populated.
# FIXME: poll state instead of taking a nap!
Process.sleep(2000)
{:ok, port, container}
:timeout -> {:error, :timeout}
end
end
end
def stop(name) do
Logger.info "Terminating LDAP Test Environment."
{binary, args} = get_runtime_tuple(["stop", name])
System.cmd(binary, args)
end
end