From bbfeab054a229725a1ec5119b179b1e1bd521870 Mon Sep 17 00:00:00 2001 From: Michael Neale Date: Fri, 25 Oct 2024 13:42:22 +1100 Subject: [PATCH] fix: check for port use (#3190) Actually done by goose but hand holding for now fix for: https://github.com/TBD54566975/ftl/issues/3169 Prompt was something like "can you take a look at https://github.com/TBD54566975/ftl/issues/3169 and come up with a fix" --- frontend/cli/cmd_serve.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/frontend/cli/cmd_serve.go b/frontend/cli/cmd_serve.go index 0a416b8955..439cb2a833 100644 --- a/frontend/cli/cmd_serve.go +++ b/frontend/cli/cmd_serve.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "net" "net/url" "os" osExec "os/exec" //nolint:depguard @@ -64,8 +65,18 @@ func (s *serveCmd) Run(ctx context.Context, projConfig projectconfig.Config) err } //nolint:maintidx +func isPortAvailable(host string, port string) bool { + ln, err := net.Listen("tcp", net.JoinHostPort(host, port)) + if err != nil { + return false + } + ln.Close() + return true +} + func (s *serveCmd) run(ctx context.Context, projConfig projectconfig.Config, initialised optional.Option[chan bool], devMode bool, bindAllocator *bind.BindAllocator) error { logger := log.FromContext(ctx) + controllerClient := rpc.ClientFromContext[ftlv1connect.ControllerServiceClient](ctx) provisionerClient := rpc.ClientFromContext[provisionerconnect.ProvisionerServiceClient](ctx) @@ -75,6 +86,13 @@ func (s *serveCmd) run(ctx context.Context, projConfig projectconfig.Config, ini _ = KillBackgroundServe(logger) //nolint:errcheck // ignore error here if the process is not running } + // Check port availability before starting in background + host := s.Bind.Hostname() + port := s.Bind.Port() + if !isPortAvailable(host, port) { + return fmt.Errorf("port %s is already in use on %s", port, host) + } + if err := runInBackground(logger); err != nil { return err }