Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(rexctl): fast backups and multi-instance voice ports (#3655)

Hampusa27e5f0d325b
diff --git a/fluxer_docs/src/content/docs/operator/running.mdx b/fluxer_docs/src/content/docs/operator/running.mdx
index 5de0b7336..45c0ec616 100644
--- a/fluxer_docs/src/content/docs/operator/running.mdx
+++ b/fluxer_docs/src/content/docs/operator/running.mdx
@@ -56,6 +56,16 @@ curl -fsSL https://fluxer.dev/install.sh | sh -s -- restore fluxer-chat.example.
Then change your domain's `A` record to the new machine's address.
+## Run more than one instance on a host
+
+You can run more than one instance on the same machine. Each one needs three things of its own: a project name with `--project`, an instance directory with `--dir`, and an edge binding that doesn't clash with the others. Run the extra instances behind your own reverse proxy with `--behind-proxy` and a distinct `--bind`.
+
+```sh
+rexctl install --dir /path/to/second-instance --project blue --behind-proxy --bind 127.0.0.1:8081
+```
+
+rexctl chooses free voice and video ports for each instance and prints the ones it picked. `rexctl doctor` shows which instance uses which ports.
+
## Manage people
Create an invite link that 10 people can use within a week.
diff --git a/fluxer_rexctl/cmd/backup.go b/fluxer_rexctl/cmd/backup.go
index de3cef603..c6956bbbb 100644
--- a/fluxer_rexctl/cmd/backup.go
+++ b/fluxer_rexctl/cmd/backup.go
@@ -167,6 +167,8 @@ func backupStageTitle(stage string) string {
return "Copying uploads and search data while Fluxer is paused"
case backup.StageStarting:
return "Starting Fluxer again"
+ case backup.StageCompressing:
+ return "Compressing the backup while Fluxer runs"
}
return ""
}
@@ -186,9 +188,12 @@ func backupCreateErr(err error) error {
var missing *backup.MissingDataError
var dump *backup.DumpError
var stopped *backup.InterruptedError
+ var compress *backup.CompressError
switch {
case errors.As(err, &stopped) && stopped.Restarted:
return &ui.ExitError{Code: ui.ExitInterrupted, Msg: "Cancelled the backup. Fluxer is running again.", Err: err}
+ case errors.As(err, &compress):
+ return ui.Wrap(err, "Couldn't finish the backup while compressing it. Fluxer is running again.", "Free up some space or check the backup folder, then run rexctl backup again.")
case errors.As(err, &ee), errors.Is(err, context.Canceled):
return err
case errors.Is(err, backup.ErrNeverStarted):
diff --git a/fluxer_rexctl/cmd/backup_test.go b/fluxer_rexctl/cmd/backup_test.go
new file mode 100644
index 000000000..ecebeca9d
--- /dev/null
+++ b/fluxer_rexctl/cmd/backup_test.go
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package cmd
+
+import (
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/backup"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
+)
+
+func TestBackupCompressErrorKeepsInstanceUp(t *testing.T) {
+ err := backupCreateErr(&backup.CompressError{Err: errors.New("no space left on device")})
+ var ee *ui.ExitError
+ if !errors.As(err, &ee) {
+ t.Fatalf("backupCreateErr returned %T, want a ui.ExitError", err)
+ }
+ if ee.Code == ui.ExitInterrupted {
+ t.Fatal("a compression failure is not a cancellation")
+ }
+ if !strings.Contains(ee.Msg, "running again") {
+ t.Fatalf("message = %q, want it to say Fluxer is running again", ee.Msg)
+ }
+}
+
+func TestBackupCompressingStageHasTitle(t *testing.T) {
+ if backupStageTitle(backup.StageCompressing) == "" {
+ t.Fatal("the compressing stage has no progress title")
+ }
+}
diff --git a/fluxer_rexctl/cmd/install.go b/fluxer_rexctl/cmd/install.go
index 63217051c..0642488b1 100644
--- a/fluxer_rexctl/cmd/install.go
+++ b/fluxer_rexctl/cmd/install.go
@@ -104,11 +104,9 @@ func newInstallCmd(app *App) *cobra.Command {
fl.BoolVar(&f.TakeOver, "take-over", false, "take over Fluxer data found on this machine")
fl.BoolVar(&f.DeleteOld, "delete-old-data", false, "delete Fluxer data found on this machine and start fresh")
fl.StringVar(&f.Project, "project", defaultProject, "name for this instance's containers and volumes")
- fl.IntVar(&f.VoiceTCPPort, "voice-tcp-port", 0, "the TCP port for voice and video")
- fl.IntVar(&f.VoiceUDPPort, "voice-udp-port", 0, "the UDP port for voice and video")
- for _, name := range []string{"project", "voice-tcp-port", "voice-udp-port"} {
- _ = fl.MarkHidden(name)
- }
+ fl.IntVar(&f.VoiceTCPPort, "voice-tcp-port", 0, "TCP port for voice and video, for running more than one instance on a host")
+ fl.IntVar(&f.VoiceUDPPort, "voice-udp-port", 0, "UDP port for voice and video, for running more than one instance on a host")
+ _ = fl.MarkHidden("project")
confirmFlag(c, &f.Confirm)
f.Setup.bind(c)
f.Storage.bind(c)
@@ -189,6 +187,7 @@ func runInstall(ctx context.Context, app *App, c *cobra.Command, f *installFlags
return err
}
f.Domain = normaliseDomain(f.Domain)
+ in.resolveVoicePorts(ctx)
if in.runChecks(ctx, checks.Preinstall) {
return notReady()
}
@@ -749,6 +748,84 @@ func (in *installer) settings() map[string]string {
return out
}
+func (in *installer) resolveVoicePorts(ctx context.Context) {
+ tcpSet := in.f.VoiceTCPPort > 0
+ udpSet := in.f.VoiceUDPPort > 0
+ if tcpSet && udpSet {
+ return
+ }
+ pub := in.publishedPorts(ctx)
+ free := func(number int, proto string) bool {
+ if number < 1 || number > 65535 {
+ return false
+ }
+ used, _, err := host.PortInUse(proto, number)
+ if err != nil || used {
+ return false
+ }
+ return !pub[host.Port{Number: number, Proto: proto}]
+ }
+ switch {
+ case !tcpSet && !udpSet:
+ tcp, udp := pickVoicePair(free)
+ if tcp == 0 || tcp == 7881 {
+ return
+ }
+ in.f.VoiceTCPPort, in.f.VoiceUDPPort = tcp, udp
+ in.announceVoicePorts(tcp, udp)
+ case !tcpSet:
+ for tcp := 7881; tcp <= 65535; tcp += 2 {
+ if tcp != in.f.VoiceUDPPort && free(tcp, "tcp") {
+ in.f.VoiceTCPPort = tcp
+ return
+ }
+ }
+ case !udpSet:
+ for udp := 7882; udp <= 65535; udp += 2 {
+ if udp != in.f.VoiceTCPPort && free(udp, "udp") {
+ in.f.VoiceUDPPort = udp
+ return
+ }
+ }
+ }
+}
+
+func pickVoicePair(free func(number int, proto string) bool) (int, int) {
+ for tcp, udp := 7881, 7882; tcp <= 65533 && udp <= 65534; tcp, udp = tcp+2, udp+2 {
+ if free(tcp, "tcp") && free(udp, "udp") {
+ return tcp, udp
+ }
+ }
+ return 0, 0
+}
+
+func (in *installer) announceVoicePorts(tcp, udp int) {
+ msg := fmt.Sprintf("Ports 7881 and 7882 are already in use, so this instance will use %d and %d for voice and video.", tcp, udp)
+ in.plan = append(in.plan, msg)
+ if !in.f.DryRun {
+ in.app.UI.Info("%s", msg)
+ }
+}
+
+func (in *installer) publishedPorts(ctx context.Context) map[host.Port]bool {
+ out := map[host.Port]bool{}
+ e := in.engine
+ if e == nil {
+ e = in.found
+ }
+ if e == nil {
+ return out
+ }
+ owners, err := e.PublishedHostPorts(ctx)
+ if err != nil {
+ return out
+ }
+ for _, o := range owners {
+ out[host.Port{Number: o.Number, Proto: o.Proto}] = true
+ }
+ return out
+}
+
func (in *installer) firewallPorts() []host.Port {
var out []host.Port
for _, p := range stack.Ports(in.settings()) {
diff --git a/fluxer_rexctl/cmd/install_voice_test.go b/fluxer_rexctl/cmd/install_voice_test.go
new file mode 100644
index 000000000..e943452da
--- /dev/null
+++ b/fluxer_rexctl/cmd/install_voice_test.go
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package cmd
+
+import "testing"
+
+func TestPickVoicePairDefaultFree(t *testing.T) {
+ tcp, udp := pickVoicePair(func(int, string) bool { return true })
+ if tcp != 7881 || udp != 7882 {
+ t.Errorf("all free = %d/%d, want 7881/7882", tcp, udp)
+ }
+}
+
+func TestPickVoicePairStepsByTwo(t *testing.T) {
+ busy := map[int]bool{7881: true, 7882: true}
+ tcp, udp := pickVoicePair(func(n int, _ string) bool { return !busy[n] })
+ if tcp != 7883 || udp != 7884 {
+ t.Errorf("default pair busy = %d/%d, want 7883/7884", tcp, udp)
+ }
+ busy[7883], busy[7884] = true, true
+ tcp, udp = pickVoicePair(func(n int, _ string) bool { return !busy[n] })
+ if tcp != 7885 || udp != 7886 {
+ t.Errorf("two pairs busy = %d/%d, want 7885/7886", tcp, udp)
+ }
+}
+
+func TestPickVoicePairNeedsBothSides(t *testing.T) {
+ tcp, udp := pickVoicePair(func(n int, proto string) bool {
+ if proto == "udp" && n == 7882 {
+ return false
+ }
+ return true
+ })
+ if tcp != 7883 || udp != 7884 {
+ t.Errorf("udp side of default busy = %d/%d, want 7883/7884", tcp, udp)
+ }
+}
diff --git a/fluxer_rexctl/internal/backup/archive.go b/fluxer_rexctl/internal/backup/archive.go
index c44950753..c0862e93a 100644
--- a/fluxer_rexctl/internal/backup/archive.go
+++ b/fluxer_rexctl/internal/backup/archive.go
@@ -115,6 +115,59 @@ func (w *archiveWriter) finish(m *Manifest) error {
return w.f.Close()
}
+type volumeSpool struct {
+ f *os.File
+ tw *tar.Writer
+}
+
+func createSpool(path string) (*volumeSpool, error) {
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
+ if err != nil {
+ return nil, err
+ }
+ return &volumeSpool{f: f, tw: tar.NewWriter(f)}, nil
+}
+
+func (s *volumeSpool) add(hdr *tar.Header, r io.Reader) error {
+ if err := checkName(hdr.Name); err != nil {
+ return err
+ }
+ hdr.Format = tar.FormatPAX
+ if hdr.ModTime.IsZero() {
+ hdr.ModTime = time.Now()
+ }
+ if err := s.tw.WriteHeader(hdr); err != nil {
+ return err
+ }
+ if hdr.Typeflag != tar.TypeReg {
+ return nil
+ }
+ n, err := io.Copy(s.tw, r)
+ if err != nil {
+ return err
+ }
+ if n != hdr.Size {
+ return fmt.Errorf("backup: %s changed size while it was copied", hdr.Name)
+ }
+ return nil
+}
+
+func (s *volumeSpool) finish() error {
+ if err := s.tw.Close(); err != nil {
+ return err
+ }
+ if err := s.f.Sync(); err != nil {
+ return err
+ }
+ return s.f.Close()
+}
+
+func (s *volumeSpool) abort() {
+ s.tw.Close()
+ s.f.Close()
+ os.Remove(s.f.Name())
+}
+
func sums(entries []Entry) []byte {
var b bytes.Buffer
for _, e := range entries {
diff --git a/fluxer_rexctl/internal/backup/backup.go b/fluxer_rexctl/internal/backup/backup.go
index 625b22af2..c2f1361a6 100644
--- a/fluxer_rexctl/internal/backup/backup.go
+++ b/fluxer_rexctl/internal/backup/backup.go
@@ -25,14 +25,15 @@ const (
)
const (
- StageFiles = "files"
- StageDatabase = "database"
- StageStopping = "stopping"
- StageVolumes = "volumes"
- StageStarting = "starting"
- StageVerifying = "verifying"
- StageClearing = "clearing"
- StagePulling = "pulling"
+ StageFiles = "files"
+ StageDatabase = "database"
+ StageStopping = "stopping"
+ StageVolumes = "volumes"
+ StageStarting = "starting"
+ StageCompressing = "compressing"
+ StageVerifying = "verifying"
+ StageClearing = "clearing"
+ StagePulling = "pulling"
)
const (
diff --git a/fluxer_rexctl/internal/backup/create.go b/fluxer_rexctl/internal/backup/create.go
index 2ce9052d3..a47419bd7 100644
--- a/fluxer_rexctl/internal/backup/create.go
+++ b/fluxer_rexctl/internal/backup/create.go
@@ -172,7 +172,8 @@ func Create(ctx context.Context, inst *instance.Instance, p *engine.Project, opt
}
if len(volumes) > 0 {
- if err := copyVolumes(ctx, w, p, image, volumes, running, progress, opts.OnEvent); err != nil {
+ spool := final + ".vol" + PartialSuffix
+ if err := copyVolumes(ctx, w, p, image, volumes, running, spool, progress, opts.OnEvent); err != nil {
return nil, err
}
for _, v := range volumes {
@@ -413,18 +414,23 @@ func checkDisk(ctx context.Context, p *engine.Project, image, dir string, volume
}
func diskNeed(ctx context.Context, p *engine.Project, image string, volumes []volumeRef, bundledDB bool) (uint64, error) {
- var total uint64
+ var db uint64
if bundledDB {
- total = databaseSize(ctx, p)
+ db = databaseSize(ctx, p)
}
+ var vol uint64
if len(volumes) > 0 {
kb, err := volumesSize(ctx, p, image, volumes)
if err != nil {
return 0, err
}
- total += kb * 1024
+ vol = kb * 1024
}
- return total * diskHeadroomPct / 100, nil
+ return backupDiskNeed(db, vol), nil
+}
+
+func backupDiskNeed(db, vol uint64) uint64 {
+ return (db + vol*2) * diskHeadroomPct / 100
}
func volumesSize(ctx context.Context, p *engine.Project, image string, volumes []volumeRef) (uint64, error) {
@@ -629,8 +635,32 @@ func restartServices(ctx context.Context, p *engine.Project, running []string, o
return nil
}
-func copyVolumes(ctx context.Context, w *archiveWriter, p *engine.Project, image string, volumes []volumeRef, running []string, progress func(string), onEvent func(engine.Event)) (err error) {
+type CompressError struct {
+ Err error
+}
+
+func (e *CompressError) Error() string { return "backup: compressing the backup: " + e.Err.Error() }
+
+func (e *CompressError) Unwrap() error { return e.Err }
+
+func copyVolumes(ctx context.Context, w *archiveWriter, p *engine.Project, image string, volumes []volumeRef, running []string, spool string, progress func(string), onEvent func(engine.Event)) error {
+ if err := spoolVolumes(ctx, spool, p, image, volumes, running, progress, onEvent); err != nil {
+ return err
+ }
+ defer os.Remove(spool)
+ if err := ctx.Err(); err != nil {
+ return &InterruptedError{Restarted: true, Err: err}
+ }
+ progress(StageCompressing)
+ return compressSpool(ctx, w, spool)
+}
+
+func spoolVolumes(ctx context.Context, spoolPath string, p *engine.Project, image string, volumes []volumeRef, running []string, progress func(string), onEvent func(engine.Event)) (err error) {
progress(StageStopping)
+ spool, serr := createSpool(spoolPath)
+ if serr != nil {
+ return serr
+ }
defer func() {
if len(running) == 0 {
return
@@ -647,25 +677,56 @@ func copyVolumes(ctx context.Context, w *archiveWriter, p *engine.Project, image
}
}()
if err := p.Stop(context.WithoutCancel(ctx)); err != nil {
+ spool.abort()
return err
}
if err := ctx.Err(); err != nil {
+ spool.abort()
return err
}
progress(StageVolumes)
for _, v := range volumes {
- if err := copyVolume(ctx, w, p, image, v); err != nil {
+ if err := copyVolume(ctx, spool, p, image, v); err != nil {
+ spool.abort()
return err
}
}
+ if err := spool.finish(); err != nil {
+ spool.abort()
+ return err
+ }
return nil
}
+func compressSpool(ctx context.Context, w *archiveWriter, spoolPath string) error {
+ f, err := os.Open(spoolPath)
+ if err != nil {
+ return &CompressError{Err: err}
+ }
+ defer f.Close()
+ tr := tar.NewReader(bufio.NewReaderSize(f, 1<<20))
+ for {
+ if err := ctx.Err(); err != nil {
+ return &InterruptedError{Restarted: true, Err: err}
+ }
+ hdr, err := tr.Next()
+ if errors.Is(err, io.EOF) {
+ return nil
+ }
+ if err != nil {
+ return &CompressError{Err: err}
+ }
+ if err := w.add(hdr, tr); err != nil {
+ return &CompressError{Err: err}
+ }
+ }
+}
+
const volumeTarScript = `b=$(find /data -type f -exec stat -c '%i %s' {} + | awk '!seen[$1]++ { t += $2 } END { print t + 0 }') || exit 1
tar -cf - -C /data . || exit 1
echo "rexctl-bytes $b" >&2`
-func copyVolume(ctx context.Context, w *archiveWriter, p *engine.Project, image string, v volumeRef) error {
+func copyVolume(ctx context.Context, spool *volumeSpool, p *engine.Project, image string, v volumeRef) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
pr, pw := io.Pipe()
@@ -683,7 +744,7 @@ func copyVolume(ctx context.Context, w *archiveWriter, p *engine.Project, image
pw.CloseWithError(err)
done <- err
}()
- copied, werr := relayVolume(w, v.short, tar.NewReader(pr))
+ copied, werr := relayVolume(spool, v.short, tar.NewReader(pr))
if werr != nil {
cancel()
pr.CloseWithError(werr)
@@ -723,7 +784,7 @@ func measuredBytes(stderr string) (int64, bool) {
return 0, false
}
-func relayVolume(w *archiveWriter, short string, tr *tar.Reader) (int64, error) {
+func relayVolume(spool *volumeSpool, short string, tr *tar.Reader) (int64, error) {
var copied int64
for {
hdr, err := tr.Next()
@@ -766,7 +827,7 @@ func relayVolume(w *archiveWriter, short string, tr *tar.Reader) (int64, error)
default:
continue
}
- if err := w.add(out, tr); err != nil {
+ if err := spool.add(out, tr); err != nil {
return copied, err
}
}
diff --git a/fluxer_rexctl/internal/backup/fastbackup_test.go b/fluxer_rexctl/internal/backup/fastbackup_test.go
new file mode 100644
index 000000000..82d629a2a
--- /dev/null
+++ b/fluxer_rexctl/internal/backup/fastbackup_test.go
@@ -0,0 +1,215 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package backup
+
+import (
+ "archive/tar"
+ "bytes"
+ "context"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+type spoolEntry struct {
+ name string
+ typ byte
+ data []byte
+}
+
+func writeSpool(t *testing.T, path string, entries []spoolEntry) {
+ t.Helper()
+ s, err := createSpool(path)
+ if err != nil {
+ t.Fatalf("create spool: %v", err)
+ }
+ for _, e := range entries {
+ hdr := &tar.Header{Name: e.name, Mode: 0o644, Typeflag: e.typ, ModTime: time.Unix(1700000000, 0)}
+ if e.typ == tar.TypeReg {
+ hdr.Size = int64(len(e.data))
+ }
+ if err := s.add(hdr, bytes.NewReader(e.data)); err != nil {
+ s.abort()
+ t.Fatalf("spool add %s: %v", e.name, err)
+ }
+ }
+ if err := s.finish(); err != nil {
+ s.abort()
+ t.Fatalf("finish spool: %v", err)
+ }
+}
+
+func TestVolumeSpoolStaysUncompressed(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "spool")
+ writeSpool(t, path, []spoolEntry{
+ {name: VolumesPrefix + "seaweedfs-data/", typ: tar.TypeDir},
+ {name: VolumesPrefix + "seaweedfs-data/a.bin", typ: tar.TypeReg, data: []byte("hello volume")},
+ })
+ raw, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(raw) >= 4 && raw[0] == 0x28 && raw[1] == 0xb5 && raw[2] == 0x2f && raw[3] == 0xfd {
+ t.Fatal("the offline spool is a zstd stream; compression still runs while Fluxer is stopped")
+ }
+ tr := tar.NewReader(bytes.NewReader(raw))
+ hdr, err := tr.Next()
+ for err == nil && hdr.Typeflag == tar.TypeDir {
+ hdr, err = tr.Next()
+ }
+ if err != nil {
+ t.Fatalf("the spool is not a plain readable tar: %v", err)
+ }
+ body, _ := io.ReadAll(tr)
+ if hdr.Name != VolumesPrefix+"seaweedfs-data/a.bin" || string(body) != "hello volume" {
+ t.Fatalf("spool content = %q %q", hdr.Name, body)
+ }
+}
+
+func TestFastBackupArchiveRoundTrip(t *testing.T) {
+ dir := t.TempDir()
+ spool := filepath.Join(dir, "spool")
+ big := bytes.Repeat([]byte{0x7f, 0x11, 0x42, 0xa0}, 2048)
+ entries := []spoolEntry{
+ {name: VolumesPrefix + "seaweedfs-data/", typ: tar.TypeDir},
+ {name: VolumesPrefix + "seaweedfs-data/a.bin", typ: tar.TypeReg, data: big},
+ {name: VolumesPrefix + "seaweedfs-data/sub/b.txt", typ: tar.TypeReg, data: []byte("second file")},
+ {name: VolumesPrefix + "valkey-data/dump.rdb", typ: tar.TypeReg, data: []byte("valkey state")},
+ }
+ writeSpool(t, spool, entries)
+
+ final := filepath.Join(dir, "backup"+Extension)
+ partial := final + PartialSuffix
+ w, err := createArchive(partial)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := w.addBytes(FilesPrefix+"compose.yaml", 0o644, []byte("services: {}")); err != nil {
+ t.Fatal(err)
+ }
+ if err := w.addBytes(DumpName, 0o600, []byte("PGDMP fake dump")); err != nil {
+ t.Fatal(err)
+ }
+ if err := compressSpool(context.Background(), w, spool); err != nil {
+ t.Fatalf("compressSpool: %v", err)
+ }
+ m := &Manifest{
+ Project: "fluxer",
+ Domain: "chat.example.com",
+ CreatedAt: time.Now().UTC().Truncate(time.Second),
+ Database: DumpName,
+ Volumes: []string{"seaweedfs-data", "valkey-data"},
+ }
+ if err := w.finish(m); err != nil {
+ t.Fatalf("finish: %v", err)
+ }
+ if err := os.Rename(partial, final); err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := Verify(final); err != nil {
+ t.Fatalf("Verify rejected the recompressed archive: %v", err)
+ }
+
+ got := map[string]string{}
+ err = walkArchive(final, func(hdr *tar.Header, r io.Reader) error {
+ if hdr.Typeflag != tar.TypeReg {
+ return nil
+ }
+ b, err := io.ReadAll(r)
+ if err != nil {
+ return err
+ }
+ got[hdr.Name] = string(b)
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("walkArchive: %v", err)
+ }
+ want := map[string]string{
+ FilesPrefix + "compose.yaml": "services: {}",
+ DumpName: "PGDMP fake dump",
+ VolumesPrefix + "seaweedfs-data/a.bin": string(big),
+ VolumesPrefix + "seaweedfs-data/sub/b.txt": "second file",
+ VolumesPrefix + "valkey-data/dump.rdb": "valkey state",
+ }
+ for name, body := range want {
+ if got[name] != body {
+ t.Fatalf("%s round-tripped to %d bytes, want %d", name, len(got[name]), len(body))
+ }
+ }
+ if _, ok := got[ManifestName]; !ok {
+ t.Fatal("the archive has no manifest")
+ }
+}
+
+func TestCompressSpoolCancelKeepsInstanceUp(t *testing.T) {
+ dir := t.TempDir()
+ spool := filepath.Join(dir, "spool")
+ writeSpool(t, spool, []spoolEntry{{name: VolumesPrefix + "valkey-data/x", typ: tar.TypeReg, data: []byte("x")}})
+ w, err := createArchive(filepath.Join(dir, "out"+PartialSuffix))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer w.abort()
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ err = compressSpool(ctx, w, spool)
+ var ie *InterruptedError
+ if !errors.As(err, &ie) || !ie.Restarted {
+ t.Fatalf("a cancelled online compression returned %v, want an interrupted error flagged as restarted", err)
+ }
+}
+
+func TestCompressSpoolCorruptReportsCompressError(t *testing.T) {
+ dir := t.TempDir()
+ spool := filepath.Join(dir, "spool")
+ if err := os.WriteFile(spool, bytes.Repeat([]byte{0xff}, 1024), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ w, err := createArchive(filepath.Join(dir, "out"+PartialSuffix))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer w.abort()
+ err = compressSpool(context.Background(), w, spool)
+ var ce *CompressError
+ if !errors.As(err, &ce) {
+ t.Fatalf("a broken spool returned %v, want a CompressError", err)
+ }
+ var ie *InterruptedError
+ if errors.As(err, &ie) {
+ t.Fatal("a broken spool must not look like an interruption")
+ }
+}
+
+func TestBackupDiskNeedCountsRawIntermediate(t *testing.T) {
+ const db = uint64(1 << 30)
+ const vol = uint64(10 << 30)
+ got := backupDiskNeed(db, vol)
+ want := (db + vol*2) * diskHeadroomPct / 100
+ if got != want {
+ t.Fatalf("backupDiskNeed = %d, want %d", got, want)
+ }
+ single := (db + vol) * diskHeadroomPct / 100
+ if got <= single {
+ t.Fatalf("backupDiskNeed = %d does not reserve room for the raw intermediate (a single copy needs %d)", got, single)
+ }
+ if backupDiskNeed(db, 0) != db*diskHeadroomPct/100 {
+ t.Fatal("with no volumes the need should not double anything")
+ }
+}
+
+func TestCompressErrorMessageNamesCompression(t *testing.T) {
+ e := &CompressError{Err: errors.New("no space left on device")}
+ if !strings.Contains(e.Error(), "compressing") {
+ t.Fatalf("CompressError message = %q", e.Error())
+ }
+ if !errors.Is(e, e.Err) {
+ t.Fatal("CompressError should unwrap to its cause")
+ }
+}
diff --git a/fluxer_rexctl/internal/checks/checks.go b/fluxer_rexctl/internal/checks/checks.go
index 91b93ff74..24aaef15d 100644
--- a/fluxer_rexctl/internal/checks/checks.go
+++ b/fluxer_rexctl/internal/checks/checks.go
@@ -69,6 +69,9 @@ type Env struct {
ps []engine.Container
psErr error
psDone bool
+ pub map[host.Port]string
+ pubErr error
+ pubDone bool
}
type Check struct {
diff --git a/fluxer_rexctl/internal/checks/env.go b/fluxer_rexctl/internal/checks/env.go
index 627a7487d..50809a4e6 100644
--- a/fluxer_rexctl/internal/checks/env.go
+++ b/fluxer_rexctl/internal/checks/env.go
@@ -13,6 +13,7 @@ import (
"os"
"os/exec"
"runtime"
+ "strconv"
"strings"
"time"
@@ -83,6 +84,42 @@ func (e *Env) SetEngine(en *engine.Engine, err error) {
func (e *Env) reset() {
e.ps, e.psErr, e.psDone = nil, nil, false
+ e.pub, e.pubErr, e.pubDone = nil, nil, false
+}
+
+func (e *Env) published(ctx context.Context) (map[host.Port]string, bool) {
+ if e.pubDone {
+ return e.pub, e.pubErr == nil
+ }
+ e.pubDone = true
+ if e.Engine == nil {
+ e.pubErr = errNoProject
+ return nil, false
+ }
+ owners, err := e.Engine.PublishedHostPorts(ctx)
+ if err != nil {
+ e.pubErr = err
+ return nil, false
+ }
+ e.pub = map[host.Port]string{}
+ for _, o := range owners {
+ key := host.Port{Number: o.Number, Proto: o.Proto}
+ if _, ok := e.pub[key]; !ok {
+ e.pub[key] = o.Project
+ }
+ }
+ return e.pub, true
+}
+
+func (e *Env) voicePorts() (tcp, udp int) {
+ tcp, udp = 7881, 7882
+ if n, err := strconv.Atoi(e.value(stack.VoiceTCPPortKey)); err == nil && n > 0 && n <= 65535 {
+ tcp = n
+ }
+ if n, err := strconv.Atoi(e.value(stack.VoiceUDPPortKey)); err == nil && n > 0 && n <= 65535 {
+ udp = n
+ }
+ return tcp, udp
}
func (e *Env) state() *instance.State {
diff --git a/fluxer_rexctl/internal/checks/ports.go b/fluxer_rexctl/internal/checks/ports.go
index 3b72b9228..31bb92b5c 100644
--- a/fluxer_rexctl/internal/checks/ports.go
+++ b/fluxer_rexctl/internal/checks/ports.go
@@ -16,7 +16,7 @@ import (
)
func init() {
- Register(Check{ID: "ports", Phases: Preinstall, Run: runPorts})
+ Register(Check{ID: "ports", Phases: Preinstall | Installed, Run: runPorts})
}
var containerOwners = map[string]bool{
@@ -36,13 +36,21 @@ func ContainerOwner(name string) bool {
}
func runPorts(ctx context.Context, e *Env) Result {
+ if e.installed() {
+ return e.portOwners(ctx)
+ }
wanted := e.wantedPorts()
+ pub, _ := e.published(ctx)
var numbers, busy []string
var first *stack.Port
firstOwner := ""
+ firstContainer := false
sameOwner := true
+ allVoice := true
+ allContainer := true
seen := map[int]bool{}
for _, p := range wanted {
+ p := p
if seen[p.Number] {
continue
}
@@ -52,12 +60,24 @@ func runPorts(ctx context.Context, e *Env) Result {
}
seen[p.Number] = true
numbers = append(numbers, strconv.Itoa(p.Number))
+ container := containerOwners[owner]
+ if !used {
+ if proj, ok := pub[host.Port{Number: p.Number, Proto: p.Proto}]; ok {
+ used, owner, container = true, proj, true
+ }
+ }
if !used {
continue
}
busy = append(busy, strconv.Itoa(p.Number))
+ if !e.isVoicePort(p) {
+ allVoice = false
+ }
+ if !container {
+ allContainer = false
+ }
if first == nil {
- first, firstOwner = &p, owner
+ first, firstOwner, firstContainer = &p, owner, container
} else if owner != firstOwner {
sameOwner = false
}
@@ -66,12 +86,17 @@ func runPorts(ctx context.Context, e *Env) Result {
case first == nil:
return pass(fmt.Sprintf("Ports %s are free.", ui.JoinAnd(numbers)))
case len(busy) == 1:
- return e.portBusy(*first, firstOwner)
+ return e.portBusy(ctx, *first, firstOwner, firstContainer)
+ }
+ if allVoice && allContainer {
+ if fix := e.voiceRemedy(ctx); fix != "" {
+ return fail(fmt.Sprintf("Ports %s are already used by another instance on this machine.", ui.JoinAnd(busy)), fix)
+ }
}
msg := fmt.Sprintf("Ports %s are already in use.", ui.JoinAnd(busy))
fix := "Stop the programs that use them, then run rexctl doctor."
switch {
- case sameOwner && containerOwners[firstOwner]:
+ case sameOwner && firstContainer:
msg = fmt.Sprintf("Ports %s are already in use by containers.", ui.JoinAnd(busy))
fix = "Stop the containers that use them, then run rexctl doctor."
case sameOwner && firstOwner != "":
@@ -79,11 +104,81 @@ func runPorts(ctx context.Context, e *Env) Result {
fix = fmt.Sprintf("Stop %s, then run rexctl doctor.", firstOwner)
}
if e.mode() == modeBundled && !slices.ContainsFunc(busy, func(n string) bool { return n != "80" && n != "443" }) {
- fix = e.portFix(*first)
+ fix = e.portFix(ctx, *first, firstContainer)
}
return fail(msg, fix)
}
+func (e *Env) portOwners(ctx context.Context) Result {
+ pub, ok := e.published(ctx)
+ if !ok || len(pub) == 0 {
+ return skip("")
+ }
+ byProject := map[string][]int{}
+ for port, proj := range pub {
+ if proj == "" {
+ continue
+ }
+ if !slices.Contains(byProject[proj], port.Number) {
+ byProject[proj] = append(byProject[proj], port.Number)
+ }
+ }
+ if len(byProject) == 0 {
+ return skip("")
+ }
+ projects := make([]string, 0, len(byProject))
+ for proj := range byProject {
+ projects = append(projects, proj)
+ }
+ slices.Sort(projects)
+ var parts []string
+ for _, proj := range projects {
+ nums := byProject[proj]
+ slices.Sort(nums)
+ strs := make([]string, len(nums))
+ for i, n := range nums {
+ strs[i] = strconv.Itoa(n)
+ }
+ parts = append(parts, fmt.Sprintf("%s uses %s", proj, ui.JoinAnd(strs)))
+ }
+ return pass(strings.Join(parts, ", ") + ".")
+}
+
+func (e *Env) isVoicePort(p stack.Port) bool {
+ tcp, udp := e.voicePorts()
+ return (p.Proto == "tcp" && p.Number == tcp) || (p.Proto == "udp" && p.Number == udp)
+}
+
+func (e *Env) voiceRemedy(ctx context.Context) string {
+ tcp, udp := e.voicePorts()
+ ftcp, fudp := e.nextFreeVoicePair(ctx, tcp, udp)
+ if ftcp == 0 || fudp == 0 {
+ return ""
+ }
+ return fmt.Sprintf("Run rexctl install --project NAME --voice-tcp-port %d --voice-udp-port %d to run a second instance alongside it.", ftcp, fudp)
+}
+
+func (e *Env) nextFreeVoicePair(ctx context.Context, tcp, udp int) (int, int) {
+ pub, _ := e.published(ctx)
+ free := func(number int, proto string) bool {
+ if number < 1 || number > 65535 {
+ return false
+ }
+ used, _, err := host.PortInUse(proto, number)
+ if err != nil || used {
+ return false
+ }
+ _, taken := pub[host.Port{Number: number, Proto: proto}]
+ return !taken
+ }
+ for t, u := tcp+2, udp+2; t <= 65533 && u <= 65534; t, u = t+2, u+2 {
+ if free(t, "tcp") && free(u, "udp") {
+ return t, u
+ }
+ }
+ return 0, 0
+}
+
func (e *Env) wantedPorts() []stack.Port {
var out []stack.Port
ports := e.ports()
@@ -116,20 +211,20 @@ func bindPort(bind string) int {
return n
}
-func (e *Env) portBusy(p stack.Port, owner string) Result {
+func (e *Env) portBusy(ctx context.Context, p stack.Port, owner string, container bool) Result {
msg := fmt.Sprintf("Port %d is already in use.", p.Number)
switch {
- case containerOwners[owner]:
+ case container:
msg = fmt.Sprintf("Port %d is already in use by a container.", p.Number)
case owner != "":
msg = fmt.Sprintf("Port %d is already in use by %s.", p.Number, owner)
}
- if fix := e.portFix(p); fix != "" {
+ if fix := e.portFix(ctx, p, container); fix != "" {
return fail(msg, fix)
}
what := "the program that uses it"
switch {
- case containerOwners[owner]:
+ case container:
what = "the container that uses it"
case owner != "":
what = owner
@@ -137,7 +232,7 @@ func (e *Env) portBusy(p stack.Port, owner string) Result {
return fail(msg, fmt.Sprintf("Stop %s, then run rexctl doctor.", what))
}
-func (e *Env) portFix(p stack.Port) string {
+func (e *Env) portFix(ctx context.Context, p stack.Port, container bool) string {
if e.mode() == modeBundled && (p.Number == 80 || p.Number == 443) {
return "Run rexctl install --behind-proxy to use your own proxy."
}
@@ -150,6 +245,11 @@ func (e *Env) portFix(p stack.Port) string {
return fmt.Sprintf("Run rexctl install --behind-proxy --bind %s to use another port.", net.JoinHostPort(host, strconv.Itoa(free)))
}
}
+ if container && e.isVoicePort(p) {
+ if fix := e.voiceRemedy(ctx); fix != "" {
+ return fix
+ }
+ }
return ""
}
diff --git a/fluxer_rexctl/internal/deploy/ports.go b/fluxer_rexctl/internal/deploy/ports.go
index 0cdb82a63..5e505bf5f 100644
--- a/fluxer_rexctl/internal/deploy/ports.go
+++ b/fluxer_rexctl/internal/deploy/ports.go
@@ -3,14 +3,17 @@
package deploy
import (
+ "context"
"fmt"
"maps"
"slices"
"strconv"
"strings"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
"github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
)
@@ -27,6 +30,16 @@ var portVars = []portVar{
{"FLUXER_LIVEKIT_UDP_PORT", 7882, []string{"udp"}},
}
+func portKeyChanged(changed []string) bool {
+ for _, name := range changed {
+ switch name {
+ case settings.EdgeHTTPPort, settings.EdgeHTTPSPort, settings.VoiceTCPPort, settings.VoiceUDPPort:
+ return true
+ }
+ }
+ return false
+}
+
func portOf(env map[string]string, v portVar) int {
if n, err := strconv.Atoi(strings.TrimSpace(env[v.name])); err == nil && n > 0 && n <= 65535 {
return n
@@ -73,7 +86,21 @@ func PortChanges(inst *instance.Instance, changes map[string]*string) (opened, c
return opened, closed, nil
}
-func checkPortsFree(ports []host.Port) error {
+func checkPortsFree(ctx context.Context, e *engine.Engine, self string, ports []host.Port) error {
+ published := map[host.Port]string{}
+ if e != nil {
+ if owners, err := e.PublishedHostPorts(ctx); err == nil {
+ for _, o := range owners {
+ if o.Project == self {
+ continue
+ }
+ key := host.Port{Number: o.Number, Proto: o.Proto}
+ if _, ok := published[key]; !ok {
+ published[key] = o.Project
+ }
+ }
+ }
+ }
seen := map[host.Port]bool{}
for _, p := range ports {
if seen[p] {
@@ -81,7 +108,15 @@ func checkPortsFree(ports []host.Port) error {
}
seen[p] = true
busy, owner, err := host.PortInUse(p.Proto, p.Number)
- if err != nil || !busy {
+ if err != nil {
+ continue
+ }
+ if !busy {
+ if proj, ok := published[p]; ok {
+ busy, owner = true, proj
+ }
+ }
+ if !busy {
continue
}
msg := fmt.Sprintf("Port %d is already in use on this machine.", p.Number)
@@ -93,6 +128,46 @@ func checkPortsFree(ports []host.Port) error {
return nil
}
+type portRole struct {
+ host.Port
+ subject string
+ noun string
+ setting string
+}
+
+func effectivePorts(env map[string]string, mode string) []portRole {
+ var out []portRole
+ if mode != settings.EdgeProxy && mode != settings.EdgeTunnel {
+ http := portOf(env, portVars[0])
+ https := portOf(env, portVars[1])
+ out = append(out,
+ portRole{Port: host.Port{Number: http, Proto: "tcp"}, subject: "The web address", noun: "the web address", setting: settings.EdgeHTTPPort},
+ portRole{Port: host.Port{Number: https, Proto: "tcp"}, subject: "The web address", noun: "the web address", setting: settings.EdgeHTTPSPort},
+ portRole{Port: host.Port{Number: https, Proto: "udp"}, subject: "The web address", noun: "the web address", setting: settings.EdgeHTTPSPort},
+ )
+ }
+ tcp := portOf(env, portVars[2])
+ udp := portOf(env, portVars[3])
+ out = append(out,
+ portRole{Port: host.Port{Number: tcp, Proto: "tcp"}, subject: "Voice", noun: "voice (TCP)", setting: settings.VoiceTCPPort},
+ portRole{Port: host.Port{Number: udp, Proto: "udp"}, subject: "Voice", noun: "voice (UDP)", setting: settings.VoiceUDPPort},
+ )
+ return out
+}
+
+func checkPortsDistinct(ports []portRole) error {
+ byPort := map[host.Port]portRole{}
+ for _, p := range ports {
+ if prev, ok := byPort[p.Port]; ok && prev.noun != p.noun {
+ return ui.Refused(
+ fmt.Sprintf("%s would use port %d, which Fluxer already uses for %s.", p.subject, p.Number, prev.noun),
+ fmt.Sprintf("Pick a different port with %s.", p.setting))
+ }
+ byPort[p.Port] = p
+ }
+ return nil
+}
+
func PortList(ports []host.Port) string {
var nums []int
for _, p := range ports {
diff --git a/fluxer_rexctl/internal/deploy/ports_test.go b/fluxer_rexctl/internal/deploy/ports_test.go
new file mode 100644
index 000000000..d7ae6dd63
--- /dev/null
+++ b/fluxer_rexctl/internal/deploy/ports_test.go
@@ -0,0 +1,102 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package deploy
+
+import (
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/host"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/settings"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
+)
+
+func TestPortOfDefaults(t *testing.T) {
+ for _, v := range portVars {
+ if got := portOf(nil, v); got != v.def {
+ t.Errorf("portOf(%s) = %d, want default %d", v.name, got, v.def)
+ }
+ for _, bad := range []string{"", "0", "-5", "70000", "x"} {
+ if got := portOf(map[string]string{v.name: bad}, v); got != v.def {
+ t.Errorf("portOf(%s=%q) = %d, want default %d", v.name, bad, got, v.def)
+ }
+ }
+ if got := portOf(map[string]string{v.name: "7999"}, v); got != 7999 {
+ t.Errorf("portOf(%s=7999) = %d, want 7999", v.name, got)
+ }
+ }
+}
+
+func TestPortDiffVoiceOnly(t *testing.T) {
+ old := map[string]string{}
+ next := map[string]string{"FLUXER_LIVEKIT_TCP_PORT": "7883", "FLUXER_LIVEKIT_UDP_PORT": "7884"}
+ added, removed := portDiff(old, next)
+ wantAdded := []host.Port{{Number: 7883, Proto: "tcp"}, {Number: 7884, Proto: "udp"}}
+ wantRemoved := []host.Port{{Number: 7881, Proto: "tcp"}, {Number: 7882, Proto: "udp"}}
+ if !samePorts(added, wantAdded) || !samePorts(removed, wantRemoved) {
+ t.Errorf("portDiff = added %v removed %v, want added %v removed %v", added, removed, wantAdded, wantRemoved)
+ }
+ if a, _ := portDiff(next, next); len(a) != 0 {
+ t.Errorf("portDiff of equal envs added %v, want none", a)
+ }
+}
+
+func TestPortKeyChanged(t *testing.T) {
+ cases := map[bool][]string{
+ true: {settings.VoiceTCPPort},
+ false: {settings.Domain, settings.MemoryProfile},
+ }
+ for want, changed := range cases {
+ if got := portKeyChanged(changed); got != want {
+ t.Errorf("portKeyChanged(%v) = %v, want %v", changed, got, want)
+ }
+ }
+ for _, k := range []string{settings.EdgeHTTPPort, settings.EdgeHTTPSPort, settings.VoiceTCPPort, settings.VoiceUDPPort} {
+ if !portKeyChanged([]string{settings.Domain, k}) {
+ t.Errorf("portKeyChanged should be true for %s", k)
+ }
+ }
+}
+
+func TestCheckPortsDistinctDefaults(t *testing.T) {
+ for _, mode := range []string{settings.EdgeBundled, settings.EdgeProxy, settings.EdgeTunnel} {
+ if err := checkPortsDistinct(effectivePorts(nil, mode)); err != nil {
+ t.Errorf("default %s install should have distinct ports, got %v", mode, err)
+ }
+ }
+}
+
+func TestCheckPortsDistinctVoiceHitsWeb(t *testing.T) {
+ env := map[string]string{"FLUXER_LIVEKIT_TCP_PORT": "443"}
+ err := checkPortsDistinct(effectivePorts(env, settings.EdgeBundled))
+ if err == nil {
+ t.Fatal("voice.tcp_port 443 in bundled mode should be refused")
+ }
+ if !strings.Contains(err.Error(), "the web address") || !strings.Contains(err.Error(), "443") {
+ t.Errorf("message should name the web address and the port, got %q", err.Error())
+ }
+ var ee *ui.ExitError
+ if errors.As(err, &ee) && !strings.Contains(ee.Fix, settings.VoiceTCPPort) {
+ t.Errorf("fix should point at %s, got %q", settings.VoiceTCPPort, ee.Fix)
+ }
+}
+
+func TestCheckPortsDistinctProxyModeDropsEdge(t *testing.T) {
+ env := map[string]string{"FLUXER_LIVEKIT_TCP_PORT": "443"}
+ if err := checkPortsDistinct(effectivePorts(env, settings.EdgeProxy)); err != nil {
+ t.Errorf("voice.tcp_port 443 is fine in proxy mode, got %v", err)
+ }
+}
+
+func samePorts(a, b []host.Port) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if a[i] != b[i] {
+ return false
+ }
+ }
+ return true
+}
diff --git a/fluxer_rexctl/internal/deploy/set.go b/fluxer_rexctl/internal/deploy/set.go
index 14b06b361..f9b2aa8b9 100644
--- a/fluxer_rexctl/internal/deploy/set.go
+++ b/fluxer_rexctl/internal/deploy/set.go
@@ -187,9 +187,14 @@ func Set(ctx context.Context, inst *instance.Instance, e *engine.Engine, changes
}
}
added, _ := portDiff(oldEnv, newEnv)
- if err := checkPortsFree(added); err != nil {
+ if err := checkPortsFree(ctx, e, inst.Project(), added); err != nil {
return nil, err
}
+ if portKeyChanged(changed) {
+ if err := checkPortsDistinct(effectivePorts(newEnv, next[settings.EdgeMode])); err != nil {
+ return nil, err
+ }
+ }
if o.Confirm != nil && !o.Confirm(preview) {
return nil, ErrDeclined
}
diff --git a/fluxer_rexctl/internal/engine/ps.go b/fluxer_rexctl/internal/engine/ps.go
index fe01ba6b4..f461060ed 100644
--- a/fluxer_rexctl/internal/engine/ps.go
+++ b/fluxer_rexctl/internal/engine/ps.go
@@ -148,6 +148,53 @@ func projectVolumes(ctx context.Context, c client.APIClient, project string) ([]
return items, nil
}
+type PortOwner struct {
+ Number int
+ Proto string
+ Project string
+}
+
+func (e *Engine) PublishedHostPorts(ctx context.Context) ([]PortOwner, error) {
+ c, err := e.api()
+ if err != nil {
+ return nil, err
+ }
+ res, err := c.ContainerList(ctx, client.ContainerListOptions{})
+ if err != nil {
+ return nil, &Error{Op: "ports", Class: ClassOf(err), Err: err}
+ }
+ seen := map[PortOwner]bool{}
+ out := make([]PortOwner, 0, len(res.Items))
+ for _, s := range res.Items {
+ project := s.Labels[api.ProjectLabel]
+ for _, p := range s.Ports {
+ if p.PublicPort == 0 {
+ continue
+ }
+ proto := strings.ToLower(p.Type)
+ if proto != "tcp" && proto != "udp" {
+ continue
+ }
+ po := PortOwner{Number: int(p.PublicPort), Proto: proto, Project: project}
+ if seen[po] {
+ continue
+ }
+ seen[po] = true
+ out = append(out, po)
+ }
+ }
+ slices.SortFunc(out, func(a, b PortOwner) int {
+ if a.Number != b.Number {
+ return a.Number - b.Number
+ }
+ if c := strings.Compare(a.Proto, b.Proto); c != 0 {
+ return c
+ }
+ return strings.Compare(a.Project, b.Project)
+ })
+ return out, nil
+}
+
func (e *Engine) Projects(ctx context.Context) ([]ProjectInfo, error) {
c, err := e.conn()
if err != nil {
diff --git a/fluxer_rexctl/internal/stack/services_test.go b/fluxer_rexctl/internal/stack/services_test.go
new file mode 100644
index 000000000..37cf9fdc0
--- /dev/null
+++ b/fluxer_rexctl/internal/stack/services_test.go
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package stack
+
+import (
+ "slices"
+ "strings"
+ "testing"
+)
+
+func TestPortsDefaults(t *testing.T) {
+ for _, env := range []map[string]string{nil, {}, {VoiceTCPPortKey: "", VoiceUDPPortKey: " "}} {
+ got := Ports(env)
+ if !slices.Equal(got, PublishedPorts) {
+ t.Errorf("Ports(%v) = %v, want defaults %v", env, got, PublishedPorts)
+ }
+ }
+}
+
+func TestPortsOverride(t *testing.T) {
+ got := Ports(map[string]string{VoiceTCPPortKey: "7883", VoiceUDPPortKey: "7884"})
+ want := []Port{
+ {Number: 80, Proto: "tcp"},
+ {Number: 443, Proto: "tcp"},
+ {Number: 443, Proto: "udp"},
+ {Number: 7883, Proto: "tcp"},
+ {Number: 7884, Proto: "udp"},
+ }
+ if !slices.Equal(got, want) {
+ t.Errorf("Ports override = %v, want %v", got, want)
+ }
+}
+
+func TestPortsInvalidKeepsDefault(t *testing.T) {
+ for _, bad := range []string{"0", "-1", "70000", "notaport"} {
+ got := Ports(map[string]string{VoiceTCPPortKey: bad, VoiceUDPPortKey: bad})
+ if got[3].Number != 7881 || got[4].Number != 7882 {
+ t.Errorf("Ports with %q = %v, want voice defaults 7881/7882", bad, got)
+ }
+ }
+}
+
+func TestComposeVoicePortsShareOneVar(t *testing.T) {
+ data, err := ReadFile(Embedded(), "docker-compose.yml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ s := string(data)
+ wants := []string{
+ "tcp_port: ${FLUXER_LIVEKIT_TCP_PORT:-7881}",
+ "udp_port: ${FLUXER_LIVEKIT_UDP_PORT:-7882}",
+ `"${FLUXER_LIVEKIT_TCP_PORT:-7881}:${FLUXER_LIVEKIT_TCP_PORT:-7881}"`,
+ `"${FLUXER_LIVEKIT_UDP_PORT:-7882}:${FLUXER_LIVEKIT_UDP_PORT:-7882}/udp"`,
+ }
+ for _, want := range wants {
+ if !strings.Contains(s, want) {
+ t.Errorf("docker-compose.yml is missing %q", want)
+ }
+ }
+ if !strings.Contains(s, "port: 7880") {
+ t.Error("docker-compose.yml should keep the livekit signal port 7880 fixed and internal")
+ }
+}