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

Forwarding random port with upnpc #700 #810

1 change: 1 addition & 0 deletions config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ config :archethic, Archethic.Networking.IPLookup.NATDiscovery,
config :archethic, Archethic.Networking.IPLookup.RemoteDiscovery,
provider: Archethic.Networking.IPLookup.RemoteDiscovery.IPIFY

config :archethic, Archethic.Networking.PortForwarding, port_range: 49_152..65_535
# -----End-of-Networking-configs ------

config :archethic_web,
Expand Down
1 change: 0 additions & 1 deletion config/test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ config :archethic, Archethic.Networking.IPLookup.NATDiscovery, provider: MockNAT
# Regardless of default IPIFY use MockRemoteDiscovery
config :archethic, Archethic.Networking.IPLookup.RemoteDiscovery, provider: MockRemoteDiscovery

config :archethic, Archethic.Networking.PortForwarding, MockPortForwarding
config :archethic, Archethic.Networking.Scheduler, enabled: false

# -----End-of-Networking-tests-configs ------
Expand Down
26 changes: 18 additions & 8 deletions lib/archethic/networking/port_forwarding.ex
Original file line number Diff line number Diff line change
Expand Up @@ -40,24 +40,34 @@ defmodule Archethic.Networking.PortForwarding do

defp do_try_open_port(port), do: NATDiscovery.open_port(port)

defp fallback(port, _force? = true) do
case do_try_open_port(0) do
defp fallback(port, force?, retries \\ 10)

defp fallback(_, _force? = true, 0) do
Logger.error(
"Port from configuration is used but requires a manuel port forwarding setting on the router"
)

:error
end

@random_ports_range Application.compile_env!(:archethic, [__MODULE__, :port_range])
defp fallback(port, _force? = true, retries) do
# // If the port is not open, try to open a random port
Logger.info("Trying to open a random port")

case do_try_open_port(Enum.random(@random_ports_range)) do
{:ok, port} ->
Logger.info("Use the random port #{port} as fallback")
{:ok, port}

:error ->
Logger.error("Cannot publish the a random port #{port}")

Logger.error(
"Port from configuration is used but requires a manuel port forwarding setting on the router"
)

:error
fallback(port, _force? = true, retries - 1)
end
end

defp fallback(port, _force? = false) do
defp fallback(port, _force? = false, _) do
Logger.warning("No fallback provided for the port #{port}")

Logger.warning(
Expand Down