// SPDX-License-Identifier: AGPL-3.0-or-later package instance import ( "bytes" "context" "errors" "fmt" "maps" "os" "path/filepath" "reflect" "slices" "strings" "github.com/compose-spec/compose-go/v2/types" "github.com/docker/compose/v5/pkg/api" "go.yaml.in/yaml/v4" "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/engine" "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/envfile" "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/stack" "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui" ) const ( PreMoveSuffix = ".pre-move" edgeService = "edge" ) type SharedRoot struct { Project string `json:"project"` Dir string `json:"dir"` Files []string `json:"files"` EnvFiles []string `json:"env_files,omitempty"` Fluxer []string `json:"fluxer_files"` Included bool `json:"included,omitempty"` Services []string `json:"services"` Others []string `json:"others"` Volumes []string `json:"volumes,omitempty"` Network string `json:"network,omitempty"` Joined []string `json:"joined,omitempty"` Aliases []string `json:"aliases,omitempty"` Stubs []StubFile `json:"stubs,omitempty"` Restart map[string]string `json:"restart,omitempty"` } type StubFile struct { Name string `json:"name"` SHA256 string `json:"sha256"` } func (i *Instance) Shared() *SharedRoot { if i == nil || i.State == nil || i.State.HandRun == nil { return nil } return i.State.HandRun.Shared } func (s *SharedRoot) Stubbed() bool { return s != nil && len(s.Stubs) > 0 } func (s *SharedRoot) RootCommand() string { cmd := "docker compose" for _, f := range s.Files { if filepath.Dir(f) != s.Dir || !slices.Contains(defaultComposeNames, filepath.Base(f)) || len(s.Files) > 1 { cmd += " -f " + relPath(s.Dir, f) } } return cmd + " up -d" } func (h *HandRunFolder) includedHere(p engine.ProjectInfo) bool { var files []string for f := range strings.SplitSeq(p.ConfigFiles, ",") { if f = strings.TrimSpace(f); f != "" { files = append(files, f) } } if len(files) == 0 { return false } if slices.ContainsFunc(files, func(f string) bool { return within(h.Dir, f) }) { return true } l, err := walkComposeRefs(files, nil) return err == nil && slices.ContainsFunc(l.compose, func(f string) bool { return within(h.Dir, f) }) } func sharedRefusal(msg, fix string) error { return ui.Refused(msg, fix) } func (h *HandRunFolder) readShared(ctx context.Context, e *engine.Engine, others []string) error { containers, err := e.Named(h.Project, "").PS(ctx) if err != nil { return err } s := &SharedRoot{Project: h.Project} var files, envFiles string for _, c := range containers { if c.Labels[api.OneoffLabel] == "True" || !slices.Contains(others, c.Service) { continue } wd := c.Labels[api.WorkingDirLabel] switch { case wd == "": case s.Dir == "": s.Dir, files, envFiles = filepath.Clean(wd), c.Labels[api.ConfigFilesLabel], c.Labels[api.EnvironmentFileLabel] case filepath.Clean(wd) != s.Dir: return sharedRefusal(fmt.Sprintf("The compose project %s runs containers from %s and %s, and rexctl can't tell which files run Fluxer.", h.Project, s.Dir, wd), "Start the project from one folder with docker compose up -d, then run this again.") } } if s.Dir == "" || files == "" { return sharedRefusal(fmt.Sprintf("The compose project %s also runs %s, and rexctl can't find the compose files that start them.", h.Project, ui.JoinAnd(others)), fmt.Sprintf("Start them with docker compose up -d from their folder, then run this again. Or move by hand with docker compose and fluxerd import, as in %s.", MoveByHandDocs)) } for f := range strings.SplitSeq(files, ",") { if f = strings.TrimSpace(f); f != "" { s.Files = append(s.Files, filepath.Clean(f)) } } for f := range strings.SplitSeq(envFiles, ",") { if f = strings.TrimSpace(f); f != "" && isFile(f) { s.EnvFiles = append(s.EnvFiles, filepath.Clean(f)) } } if dotEnv := filepath.Join(s.Dir, ".env"); strings.TrimSpace(envFiles) == "" && isFile(dotEnv) { s.EnvFiles = []string{dotEnv} } env, err := readEnvFiles(s.EnvFiles) if err != nil { return err } for _, f := range s.Files { if !isFile(f) { return sharedRefusal(fmt.Sprintf("The compose project %s was started from %s, and that file is missing.", h.Project, f), "Put the file back, then run this again.") } } l, err := walkComposeRefs(s.Files, env) if err != nil { return &ui.ExitError{Code: ui.ExitRefused, Msg: fmt.Sprintf("rexctl can't read the compose files in %s.", s.Dir), Fix: "Check that docker compose config works in that folder, then run this again.", Err: err} } for _, f := range s.Files { if within(h.Dir, f) { s.Fluxer = append(s.Fluxer, relPath(h.Dir, f)) } } if len(s.Fluxer) == 0 { s.Included = true for _, f := range l.compose { if within(h.Dir, f) && !within(filepath.Join(h.Dir, StateDirName), f) { s.Fluxer = append(s.Fluxer, relPath(h.Dir, f)) } } } if len(s.Fluxer) == 0 { return sharedRefusal(fmt.Sprintf("The compose project %s runs Fluxer, and none of its compose files in %s include the files in %s.", h.Project, s.Dir, h.Dir), fmt.Sprintf("Move by hand with docker compose and fluxerd import, as in %s.", MoveByHandDocs)) } if s.Included { if err := h.extendsFluxer(s, l, env); err != nil { return err } } root, err := engine.LoadRoot(ctx, engine.Spec{Name: h.Project, Dir: s.Dir, Files: s.Files, Env: env}) if err != nil { return &ui.ExitError{Code: ui.ExitRefused, Msg: fmt.Sprintf("rexctl can't read the compose files in %s.", s.Dir), Fix: "Check that docker compose config works in that folder, then run this again.", Err: err} } own, err := engine.LoadRoot(ctx, engine.Spec{Name: h.Project, Dir: h.Dir, Files: h.sharedFiles(s), Env: h.Env}) if err != nil { return &ui.ExitError{Code: ui.ExitRefused, Msg: fmt.Sprintf("rexctl can't read the compose files in %s.", h.Dir), Fix: "Check that docker compose config works in that folder, then run this again.", Err: err} } s.Services = slices.Sorted(maps.Keys(own.Model.Services)) var foreign []string for _, name := range slices.Concat(s.Services, slices.Sorted(maps.Keys(own.Model.DisabledServices))) { if !slices.Contains(stack.Services, name) { foreign = append(foreign, name) } } if len(foreign) > 0 { return sharedRefusal(fmt.Sprintf("The compose files in %s also run %s, which %s not part of Fluxer, and the move would stop and remove %s with Fluxer.", h.Dir, ui.JoinAnd(foreign), oneOrMany(len(foreign), "is", "are"), oneOrMany(len(foreign), "it", "them")), fmt.Sprintf("Move %s to compose files outside %s, run docker compose up -d in %s, then run this again.", ui.JoinAnd(foreign), h.Dir, s.Dir)) } for name := range root.Model.Services { if !slices.Contains(s.Services, name) { s.Others = append(s.Others, name) } } slices.Sort(s.Others) if err := s.check(root.Model, own.Model, h.Dir); err != nil { return err } if err := h.sameAsRoot(ctx, s, root.Model, own.Model, env); err != nil { return err } for _, v := range own.Model.Volumes { if !bool(v.External) && v.Name != "" && !slices.Contains(s.Volumes, v.Name) { s.Volumes = append(s.Volumes, v.Name) } } slices.Sort(s.Volumes) h.listed, h.lookup, h.Shared = s.Fluxer, false, s return h.readLayout(h.sharedFiles(s)) } func (h *HandRunFolder) sharedFiles(s *SharedRoot) []string { out := make([]string, len(s.Fluxer)) for i, f := range s.Fluxer { out[i] = filepath.Join(h.Dir, f) } return out } func readEnvFiles(files []string) (map[string]string, error) { out := map[string]string{} for _, f := range files { data, err := os.ReadFile(f) if err != nil { return nil, err } env, _, err := parseEnv(data) if err != nil { return nil, &ui.ExitError{Code: ui.ExitRefused, Msg: fmt.Sprintf("rexctl can't read %s.", f), Fix: "Fix that file so docker compose config works, then run this again.", Err: err} } maps.Copy(out, env) } return out, nil } func (s *SharedRoot) check(root, own *types.Project, dir string) error { all := maps.Clone(root.Services) for name, svc := range root.DisabledServices { if _, fluxer := own.DisabledServices[name]; !fluxer && !slices.Contains(s.Services, name) { all[name] = svc } } for _, name := range slices.Sorted(maps.Keys(all)) { svc := all[name] if slices.Contains(s.Services, name) { continue } for _, ref := range serviceRefs(svc) { if slices.Contains(s.Services, ref) { return sharedRefusal(fmt.Sprintf("%s in the compose project %s depends on %s, which is part of Fluxer, and the move takes %s out of that project.", name, s.Project, ref, ref), fmt.Sprintf("Take %s out of the depends_on, links, volumes_from or network_mode of %s, run docker compose up -d in %s, then run this again.", ref, name, s.Dir)) } } for _, v := range svc.Volumes { if v.Type != types.VolumeTypeVolume { continue } if _, ok := own.Volumes[v.Source]; ok { return sharedRefusal(fmt.Sprintf("%s in the compose project %s mounts the volume %s, which holds Fluxer's data.", name, s.Project, v.Source), fmt.Sprintf("Take that volume out of %s, run docker compose up -d in %s, then run this again.", name, s.Dir)) } } } var shared []string joined := map[string][]string{} for _, name := range s.Others { for key := range root.Services[name].Networks { if _, ok := own.Networks[key]; ok { if !slices.Contains(shared, key) { shared = append(shared, key) } joined[key] = append(joined[key], name) } } } switch len(shared) { case 0: return nil case 1: s.Network, s.Joined = root.Networks[shared[0]].Name, joined[shared[0]] default: slices.Sort(shared) return sharedRefusal(fmt.Sprintf("%s in the compose project %s share the networks %s with Fluxer, and rexctl can put Fluxer's container on one of them.", ui.JoinAnd(s.Others), s.Project, ui.JoinAnd(shared)), fmt.Sprintf("Have them use one network for Fluxer, run docker compose up -d in %s, then run this again.", s.Dir)) } if _, ok := own.Services[edgeService]; ok { s.Aliases = []string{edgeService} } return nil } func (h *HandRunFolder) extendsFluxer(s *SharedRoot, l composeLayout, env map[string]string) error { for _, f := range slices.Concat(s.Files, l.compose) { if within(h.Dir, f) || !isFile(f) { continue } r, err := readComposeRefs(f, env) if err != nil { return &ui.ExitError{Code: ui.ExitRefused, Msg: fmt.Sprintf("rexctl can't read %s.", f), Fix: "Check that docker compose config works in " + s.Dir + ", then run this again.", Err: err} } for _, x := range r.extends { if within(h.Dir, x) { return sharedRefusal(fmt.Sprintf("%s takes a service from %s with extends, and the move empties that file.", f, x), fmt.Sprintf("Copy that service from %s into %s, run docker compose up -d in %s, then run this again.", x, f, s.Dir)) } } } return nil } func rootPart(root *types.Project, services []string) *types.Project { part := &types.Project{Services: types.Services{}} for _, name := range services { if svc, ok := root.Services[name]; ok { part.Services[name] = svc } } return part } func (h *HandRunFolder) sameAsRoot(ctx context.Context, s *SharedRoot, root, own *types.Project, env map[string]string) error { diff := modelDiff(rootPart(root, s.Services), own, h.Dir) if len(diff) == 0 { return nil } var vars []string for _, k := range slices.Sorted(maps.Keys(env)) { if v, ok := h.Env[k]; ok && v == env[k] { continue } with := maps.Clone(h.Env) if with == nil { with = map[string]string{} } with[k] = env[k] m, err := engine.LoadRoot(ctx, engine.Spec{Name: h.Project, Dir: h.Dir, Files: h.sharedFiles(s), Env: with}) if err != nil || len(modelDiff(m.Model, own, h.Dir)) > 0 { vars = append(vars, k) } } if len(vars) > 0 { return sharedRefusal(fmt.Sprintf("%s sets %s, which docker compose uses for Fluxer's files in place of the %s in %s.", ui.JoinAnd(s.EnvFiles), ui.JoinAnd(vars), oneOrMany(len(vars), "value", "values"), filepath.Join(h.Dir, ".env")), fmt.Sprintf("Set %s in %s to the same %s as in %s, then run this again.", ui.JoinAnd(vars), filepath.Join(h.Dir, ".env"), oneOrMany(len(vars), "value", "values"), ui.JoinAnd(s.EnvFiles))) } var where []string for _, d := range diff { svc, _, _ := strings.Cut(d, " ") if !slices.Contains(where, svc) { where = append(where, svc) } } return sharedRefusal(fmt.Sprintf("The compose files in %s change %s, and rexctl moves Fluxer only as the files in %s run it.", s.Dir, ui.JoinAnd(where), h.Dir), fmt.Sprintf("Move those changes into %s in %s, run docker compose up -d in %s, then run this again.", CustomCompose, h.Dir, s.Dir)) } func oneOrMany(n int, one, many string) string { if n == 1 { return one } return many } func serviceRefs(svc types.ServiceConfig) []string { out := slices.Collect(maps.Keys(svc.DependsOn)) for _, l := range svc.Links { name, _, _ := strings.Cut(l, ":") out = append(out, name) } for _, v := range svc.VolumesFrom { if name, ok := strings.CutPrefix(v, "container:"); ok { out = append(out, name) continue } name, _, _ := strings.Cut(v, ":") out = append(out, name) } if name, ok := strings.CutPrefix(svc.NetworkMode, types.ServicePrefix); ok { out = append(out, name) } slices.Sort(out) return out } func (i *Instance) StubFiles(ctx context.Context) ([]string, error) { s := i.Shared() if s == nil || s.Stubbed() { return nil, nil } if !s.Included { return nil, errors.New("instance: the root lists Fluxer's files itself") } env, err := readEnvFiles(s.EnvFiles) if err != nil { return nil, err } before, err := engine.LoadRoot(ctx, engine.Spec{Name: s.Project, Dir: s.Dir, Files: s.Files, Env: env}) if err != nil { return nil, err } stubs := map[string][]byte{} for n, f := range s.Fluxer { text := []byte("{}\n") if n == 0 && s.Network != "" { if text, err = networkStub(before.Model, s.Network); err != nil { return nil, err } } stubs[f] = text } var done []string restore := func(cause error) ([]string, error) { var errs []error for _, f := range done { errs = append(errs, os.Rename(i.Path(f)+PreMoveSuffix, i.Path(f))) } return nil, errors.Join(append([]error{cause}, errs...)...) } for _, f := range s.Fluxer { path := i.Path(f) if exists(path + PreMoveSuffix) { return restore(fmt.Errorf("instance: %s is already there", path+PreMoveSuffix)) } data, err := os.ReadFile(path) if err != nil { return restore(err) } if err := envfile.WriteFileAtomic(path+PreMoveSuffix, data, false); err != nil { return restore(err) } done = append(done, f) if err := envfile.WriteFileAtomic(path, stubs[f], false); err != nil { return restore(err) } } after, err := engine.LoadRoot(ctx, engine.Spec{Name: s.Project, Dir: s.Dir, Files: s.Files, Env: env}) if err != nil { return restore(err) } if err := sameRest(before.Model, after.Model, s); err != nil { return restore(err) } s.Stubs = nil for _, f := range s.Fluxer { sum, err := fileSum(i.Path(f)) if err != nil { return restore(err) } s.Stubs = append(s.Stubs, StubFile{Name: f, SHA256: sum}) } if err := i.Save(); err != nil { s.Stubs = nil return restore(err) } return slices.Clone(s.Fluxer), nil } func networkStub(model *types.Project, name string) ([]byte, error) { for key, n := range model.Networks { if n.Name != name { continue } var b bytes.Buffer enc := yaml.NewEncoder(&b) enc.SetIndent(2) if err := enc.Encode(map[string]any{"networks": map[string]types.NetworkConfig{key: n}}); err != nil { return nil, err } return b.Bytes(), enc.Close() } return nil, fmt.Errorf("instance: the compose files don't define the network %s", name) } func sameRest(before, after *types.Project, s *SharedRoot) error { for _, name := range s.Services { if _, ok := after.Services[name]; ok { return fmt.Errorf("instance: %s still runs %s", s.Dir, name) } } for _, name := range s.Others { a, b := before.Services[name], after.Services[name] if !reflect.DeepEqual(asMap(a), asMap(b)) { return fmt.Errorf("instance: %s changed", name) } } if s.Network == "" { return nil } for key, n := range before.Networks { if n.Name == s.Network && !reflect.DeepEqual(asAny(map[string]types.NetworkConfig{key: n}), asAny(map[string]types.NetworkConfig{key: after.Networks[key]})) { return fmt.Errorf("instance: the network %s changed", s.Network) } } return nil } func (i *Instance) RestoreStubs() ([]string, error) { s := i.Shared() if !s.Stubbed() { return nil, nil } var back []string for _, f := range s.Stubs { path := i.Path(f.Name) if !isFile(path + PreMoveSuffix) { continue } if err := os.Rename(path+PreMoveSuffix, path); err != nil { return back, err } back = append(back, f.Name) } s.Stubs = nil return back, i.Save() } func (s *SharedRoot) stubSum(name string) (string, bool) { if s == nil { return "", false } for _, f := range s.Stubs { if f.Name == name { return f.SHA256, true } } return "", false }