Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

experimenting with docker api #133

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/elixir.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ jobs:
restore-keys: ${{ runner.os }}-mix-
- name: Install dependencies
run: mix deps.get
- name: Run formatter
run: mix format --check-formatted
- name: Run tests
run: mix test --exclude flaky --cover
- name: Verify version
Expand Down
17 changes: 11 additions & 6 deletions lib/container.ex
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,10 @@ defmodule Testcontainers.Container do
when is_binary(check_image) or is_struct(check_image, Regex)

@os_type (case :os.type() do
{:win32, _} -> :windows
{:unix, :darwin} -> :macos
{:unix, _} -> :linux
end)
{:win32, _} -> :windows
{:unix, :darwin} -> :macos
{:unix, _} -> :linux
end)

@doc guard: true
defguard is_os(name)
Expand Down Expand Up @@ -163,6 +163,7 @@ defmodule Testcontainers.Container do
if config.auto_remove do
raise ArgumentError, "Cannot reuse a container that is set to auto-remove"
end

%__MODULE__{config | reuse: reuse}
end

Expand Down Expand Up @@ -198,12 +199,16 @@ defmodule Testcontainers.Container do
@doc """
Sets a network mode to apply to the container object in docker.
"""
def with_network_mode(%__MODULE__{} = config, mode) when is_binary(mode) and not is_os(:linux) do
def with_network_mode(%__MODULE__{} = config, mode)
when is_binary(mode) and not is_os(:linux) do
with mode <- String.downcase(mode) do
if mode == "host" do
Testcontainers.Logger.log("To use host network mode on non-linux hosts, please see https://docs.docker.com/network/drivers/host")
Testcontainers.Logger.log(
"To use host network mode on non-linux hosts, please see https://docs.docker.com/network/drivers/host"
)
end
end

%__MODULE__{config | network_mode: mode}
end

Expand Down
1 change: 1 addition & 0 deletions lib/container/protocols/container_builder_helper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ defmodule Testcontainers.ContainerBuilderHelper do

if config.reuse && "true" == Map.get(state.properties, "testcontainers.reuse.enable", "false") do
hash = Hash.struct_to_hash(config)

config
|> Container.with_label(container_reuse(), "true")
|> Container.with_label(container_reuse_hash_label(), hash)
Expand Down
13 changes: 8 additions & 5 deletions lib/docker/api.ex
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ defmodule Testcontainers.Docker.Api do

def get_container(container_id, conn)
when is_binary(container_id) do
case Api.Container.container_inspect(conn, container_id) do
case Testcontainers.Docker.Impl.container_inspect(conn, container_id) do
{:error, %Tesla.Env{status: other}} ->
{:error, {:http_error, other}}

Expand All @@ -22,9 +22,12 @@ defmodule Testcontainers.Docker.Api do
end

def get_container_by_hash(hash, conn) do
filters_json = %{
"label" => ["#{Testcontainers.Constants.container_reuse_hash_label}=#{hash}"]
} |> Jason.encode!()
filters_json =
%{
"label" => ["#{Testcontainers.Constants.container_reuse_hash_label()}=#{hash}"]
}
|> Jason.encode!()

case Api.Container.container_list(conn, filters: filters_json) do
{:ok, containers} when is_list(containers) ->
case containers do
Expand Down Expand Up @@ -162,7 +165,7 @@ defmodule Testcontainers.Docker.Api do
end

def get_bridge_gateway(conn) do
case Api.Network.network_inspect(conn, "bridge") do
case Testcontainers.Docker.Impl.network_inspect(conn, "bridge") do
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is the current experimentation

{:ok, %DockerEngineAPI.Model.Network{IPAM: %DockerEngineAPI.Model.Ipam{Config: config}}} ->
with_gateway =
config
Expand Down
199 changes: 199 additions & 0 deletions lib/docker/builder.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
# NOTE: This file is auto generated by OpenAPI Generator 7.0.1 (https://openapi-generator.tech).
# Do not edit this file manually.

defmodule Testcontainers.Docker.RequestBuilder do
@moduledoc """
Helper functions for building Tesla requests
"""

@doc """
Specify the request `method` when building a request.

Does not override the `method` if one has already been specified.

### Parameters

- `request` (Map) - Collected request options
- `method` (atom) - Request method

### Returns

Map
"""
@spec method(map(), atom()) :: map()
def method(request, method) do
Map.put_new(request, :method, method)
end

@doc """
Specify the request URL when building a request.

Does not override the `url` if one has already been specified.

### Parameters

- `request` (Map) - Collected request options
- `url` (String) - Request URL

### Returns

Map
"""
@spec url(map(), String.t()) :: map()
def url(request, url) do
Map.put_new(request, :url, url)
end

@doc """
Add optional parameters to the request.

### Parameters

- `request` (Map) - Collected request options
- `definitions` (Map) - Map of parameter name to parameter location.
- `options` (KeywordList) - The provided optional parameters

### Returns

Map
"""
@spec add_optional_params(map(), %{optional(atom) => atom()}, keyword()) :: map()
def add_optional_params(request, _, []), do: request

def add_optional_params(request, definitions, [{key, value} | tail]) do
case definitions do
%{^key => location} ->
request
|> add_param(location, key, value)
|> add_optional_params(definitions, tail)

_ ->
add_optional_params(request, definitions, tail)
end
end

@doc """
Add non-optional parameters to the request.

### Parameters

- `request` (Map) - Collected request options
- `location` (atom) - Where to put the parameter
- `key` (atom) - The name of the parameter
- `value` (any) - The value of the parameter

### Returns

Map
"""
@spec add_param(map(), atom(), atom(), any()) :: map()
def add_param(request, :body, :body, value), do: Map.put(request, :body, value)

def add_param(request, :body, key, value) do
request
|> Map.put_new_lazy(:body, &Tesla.Multipart.new/0)
|> Map.update!(:body, fn multipart ->
Tesla.Multipart.add_field(
multipart,
key,
Jason.encode!(value),
headers: [{:"Content-Type", "application/json"}]
)
end)
end

def add_param(request, :headers, key, value) do
headers =
request
|> Map.get(:headers, [])
|> List.keystore(key, 0, {key, value})

Map.put(request, :headers, headers)
end

def add_param(request, :file, name, path) do
request
|> Map.put_new_lazy(:body, &Tesla.Multipart.new/0)
|> Map.update!(:body, &Tesla.Multipart.add_file(&1, path, name: name))
end

def add_param(request, :form, name, value) do
Map.update(request, :body, %{name => value}, &Map.put(&1, name, value))
end

def add_param(request, location, key, value) do
Map.update(request, location, [{key, value}], &(&1 ++ [{key, value}]))
end

@doc """
This function ensures that the `body` parameter is always set.

When using Tesla with the `httpc` adapter (the default adapter), there is a
bug where POST, PATCH and PUT requests will fail if the body is empty.

### Parameters

- `request` (Map) - Collected request options

### Returns

Map
"""
@spec ensure_body(map()) :: map()
def ensure_body(%{body: nil} = request) do
%{request | body: ""}
end

def ensure_body(request) do
Map.put_new(request, :body, "")
end

@type status_code :: :default | 100..599
@type response_mapping :: [{status_code, false | %{} | module()}]

@doc """
Evaluate the response from a Tesla request.
Decode the response for a Tesla request.

### Parameters

- `result` (Tesla.Env.result()): The response from Tesla.request/2.
- `mapping` ([{http_status, struct}]): The mapping for status to struct for decoding.

### Returns

- `{:ok, struct}` or `{:ok, Tesla.Env.t()}` on success
- `{:error, term}` on failure
"""
@spec evaluate_response(Tesla.Env.result(), response_mapping) ::
{:ok, struct()} | Tesla.Env.result()
def evaluate_response({:ok, %Tesla.Env{} = env}, mapping) do
resolve_mapping(env, mapping, nil)
end

def evaluate_response({:error, _} = error, _), do: error

defp resolve_mapping(%Tesla.Env{status: status} = env, [{mapping_status, struct} | _], _)
when status == mapping_status do
decode(env, struct)
end

defp resolve_mapping(env, [{:default, struct} | tail], _),
do: resolve_mapping(env, tail, struct)

defp resolve_mapping(env, [_ | tail], struct), do: resolve_mapping(env, tail, struct)

defp resolve_mapping(env, [], nil), do: {:error, env}

defp resolve_mapping(env, [], struct), do: decode(env, struct)

defp decode(%Tesla.Env{} = env, false), do: {:ok, env}

defp decode(%Tesla.Env{body: body}, %{}) do
DockerEngineAPI.Deserializer.jason_decode(body)
end

defp decode(%Tesla.Env{body: body}, module) do
DockerEngineAPI.Deserializer.jason_decode(body, module)
end
end
99 changes: 99 additions & 0 deletions lib/docker/connection.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# NOTE: This file is auto generated by OpenAPI Generator 7.0.1 (https://openapi-generator.tech).
# Do not edit this file manually.

defmodule Testcontainers.Docker.Connection do
@moduledoc """
Handle Tesla connections for DockerEngineAPI.
"""

@default_options [
base_url: "http://localhost/v1.43",
adapter: Tesla.Adapter.Hackney
]

@typedoc """
The list of options that can be passed to new/1.

- `base_url`: Overrides the base URL on a per-client basis.
- `user_agent`: Overrides the User-Agent header.
"""
@type options :: [
{:base_url, String.t()},
{:user_agent, String.t()}
]

@doc "Forward requests to Tesla."
@spec request(Tesla.Client.t(), [Tesla.option()]) :: Tesla.Env.result()
defdelegate request(client, options), to: Tesla

@doc """
Configure a client that may have authentication.

### Parameters

- `options`: a keyword list of OpenAPIPetstore.Connection.options.

### Returns

Tesla.Env.client
"""
@spec new(options) :: Tesla.Env.client()

def new(options \\ []) when is_list(options) do
options = @default_options |> Keyword.merge(options)

options
|> Keyword.merge(options)
|> middleware()
|> Tesla.client(adapter(options))
end

@doc """
Returns fully configured middleware for passing to Tesla.client/2.
"""
@spec middleware(options) :: [Tesla.Client.middleware()]
def middleware(options \\ []) do
base_url = Keyword.get(options, :base_url)

tesla_options = get_tesla_options()
middleware = Keyword.get(tesla_options, :middleware, [])
json_engine = Keyword.get(tesla_options, :json, Jason)

user_agent =
Keyword.get(
options,
:user_agent,
Keyword.get(
tesla_options,
:user_agent,
"openapi-generator - DockerEngineAPI 1.43 - elixir"
)
)

[
{Tesla.Middleware.BaseUrl, base_url},
{Tesla.Middleware.Headers, [{"user-agent", user_agent}]},
{Tesla.Middleware.EncodeJson, engine: json_engine}
| middleware
]
end

def get_tesla_options, do: Application.get_env(:tesla, __MODULE__, [])

@doc """
Returns the default adapter for this API.
"""
def adapter(options \\ []) do
case Keyword.get(
options,
:adapter,
Keyword.get(get_tesla_options(), :adapter, nil)
) do
Tesla.Adapter.Hackney ->
{Tesla.Adapter.Hackney, [recv_timeout: Keyword.get(options, :recv_timeout, 1_000)]}

other ->
other
end
end
end
Loading
Loading