Allow LIVEBOOK_PORT to be set to 0 for a random port (#906)

This commit is contained in:
José Valim 2022-01-21 09:18:02 +01:00 committed by GitHub
parent 526499dfa5
commit bd3363acde
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 39 additions and 12 deletions

View file

@ -169,7 +169,8 @@ The following environment variables configure Livebook:
* LIVEBOOK_PORT - sets the port Livebook runs on. If you want to run multiple
instances on the same domain with the same credentials but on different ports,
you also need to set LIVEBOOK_SECRET_KEY_BASE. Defaults to 8080.
you also need to set LIVEBOOK_SECRET_KEY_BASE. Defaults to 8080. If set to 0,
a random port will be picked.
* LIVEBOOK_ROOT_PATH - sets the root path to use for file selection. This does
not restrict access to upper directories unless the operating system user is

View file

@ -5,8 +5,8 @@ config :livebook, LivebookWeb.Endpoint,
http: [ip: {127, 0, 0, 1}, port: 8080],
server: true
# Start log-level in notice by default to reduce output
config :logger, level: :notice
# Set log level to warning by default to reduce output
config :logger, level: :warning
# ## SSL Support
#

View file

@ -27,7 +27,8 @@ defmodule Livebook.Application do
# Start the unique task dependencies
Livebook.UniqueTask,
# Start the Endpoint (http/https)
LivebookWeb.Endpoint
# We skip the access url as we do our own logging below
{LivebookWeb.Endpoint, log_access_url: false}
] ++ app_specs()
opts = [strategy: :one_for_one, name: Livebook.Supervisor]

View file

@ -78,10 +78,8 @@ if Mix.target() == :app do
end
defp import_livebook(url) do
%{
URI.parse(LivebookWeb.Endpoint.access_url())
| path: "/import"
}
LivebookWeb.Endpoint.access_struct_url()
|> Map.replace!(:path, "/import")
|> append_query("url=#{URI.encode_www_form(url)}")
|> URI.to_string()
|> Livebook.Utils.browser_open()

View file

@ -78,14 +78,41 @@ defmodule LivebookWeb.Endpoint do
plug LivebookWeb.Router
def access_url() do
root_url = url()
def access_struct_url() do
base =
case struct_url() do
%URI{scheme: "https", port: 0} = uri ->
%{uri | port: get_port(__MODULE__.HTTPS, 433)}
%URI{scheme: "http", port: 0} = uri ->
%{uri | port: get_port(__MODULE__.HTTP, 80)}
%URI{} = uri ->
uri
end
base = update_in(base.path, &(&1 || "/"))
if Livebook.Config.auth_mode() == :token do
token = Application.fetch_env!(:livebook, :token)
root_url <> "/?token=" <> token
%{base | query: "token=" <> token}
else
root_url
base
end
end
def access_url do
URI.to_string(access_struct_url())
end
defp get_port(ref, default) do
try do
:ranch.get_addr(ref)
rescue
_ -> default
else
{_, port} when is_integer(port) -> port
_ -> default
end
end
end