A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(rexctl): apply plans, pull images and detect stalls
Hampus77b1a5f8f503
diff --git a/fluxer_rexctl/internal/engine/apply.go b/fluxer_rexctl/internal/engine/apply.gonew file mode 100644index 000000000..c4f3ef855--- /dev/null+++ b/fluxer_rexctl/internal/engine/apply.go@@ -0,0 +1,367 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package engine++import (+ "context"+ "errors"+ "os"+ "path/filepath"+ "slices"+ "strings"+ "time"++ "github.com/compose-spec/compose-go/v2/types"+ "github.com/docker/compose/v5/pkg/api"+ "github.com/moby/moby/client"+)++func recreatePolicy(r Recreate) string {+ switch r {+ case RecreateAlways:+ return api.RecreateForce+ case RecreateNever:+ return api.RecreateNever+ }+ return api.RecreateDiverged+}++func (p *Project) Up(ctx context.Context, o UpOptions) error {+ if err := p.needModel("up"); err != nil {+ return err+ }+ if err := p.Engine.refuseTooOld("up"); err != nil {+ return err+ }+ c, err := p.Engine.conn()+ if err != nil {+ return err+ }+ if err := p.finishStop(ctx, c); err != nil {+ return err+ }+ plan, err := p.Plan(ctx)+ if err != nil {+ return err+ }+ if err := p.pullMissing(ctx, o.OnEvent); err != nil {+ return err+ }+ stop := c.bus.listen(p.Name, o.OnEvent)+ defer stop()+ model := copyModel(p.Model)+ if len(o.Services) == 0 {+ if len(plan.Remove) > 0 {+ if err := p.removeServices(ctx, c, plan.Remove); err != nil {+ return err+ }+ }+ if hashless, err := p.hashlessNetworks(ctx, plan.Networks); err != nil {+ return err+ } else if len(hashless) > 0 {+ detailf("engine: network %v has no config hash, taking the project down to recreate it", hashless)+ if err := c.svc.Down(ctx, p.Name, api.DownOptions{Project: model}); err != nil {+ return p.wrap("up", err)+ }+ }+ for _, key := range plan.LabelOnly {+ n := model.Networks[key]+ n.External = true+ model.Networks[key] = n+ }+ } else {+ var opts []types.DependencyOption+ if o.NoDeps {+ opts = append(opts, types.IgnoreDependencies)+ }+ model, err = model.WithSelectedServices(o.Services, opts...)+ if err != nil {+ return &Error{Op: "up", Class: ClassInvalidConfig, Err: err}+ }+ }+ policy := recreatePolicy(o.Recreate)+ opts := api.UpOptions{+ Create: api.CreateOptions{+ Recreate: policy,+ RecreateDependencies: policy,+ RemoveOrphans: o.RemoveOrphans,+ Inherit: true,+ QuietPull: true,+ },+ Start: api.StartOptions{+ Project: model,+ Wait: o.Wait,+ WaitTimeout: o.WaitTimeout,+ },+ }+ err = c.svc.Up(ctx, model, opts)+ if imageGone(err) {+ if err := p.pullMissing(ctx, o.OnEvent); err != nil {+ return err+ }+ err = c.svc.Up(ctx, model, opts)+ }+ return p.wrap("up", err)+}++func (p *Project) hashlessNetworks(ctx context.Context, keys []string) ([]string, error) {+ if len(keys) == 0 {+ return nil, nil+ }+ c, err := p.Engine.api()+ if err != nil {+ return nil, err+ }+ res, err := c.NetworkList(ctx, client.NetworkListOptions{Filters: projectFilter(p.Name)})+ if err != nil {+ return nil, p.wrap("up", err)+ }+ var out []string+ for _, n := range res.Items {+ if slices.Contains(keys, n.Labels[api.NetworkLabel]) && n.Labels[api.ConfigHashLabel] == "" {+ out = append(out, n.Labels[api.NetworkLabel])+ }+ }+ return out, nil+}++func (p *Project) removeServices(ctx context.Context, c *conn, services []string) error {+ err := c.svc.Remove(ctx, p.Name, api.RemoveOptions{Services: services, Stop: true, Force: true})+ if err != nil && !errors.Is(err, api.ErrNoResources) {+ return p.wrap("remove", err)+ }+ return nil+}++func (p *Project) Create(ctx context.Context) error {+ if err := p.needModel("create"); err != nil {+ return err+ }+ if err := p.Engine.refuseTooOld("create"); err != nil {+ return err+ }+ c, err := p.Engine.conn()+ if err != nil {+ return err+ }+ if err := p.pullMissing(ctx, nil); err != nil {+ return err+ }+ opts := api.CreateOptions{+ Recreate: api.RecreateDiverged,+ RecreateDependencies: api.RecreateDiverged,+ RemoveOrphans: true,+ Inherit: true,+ QuietPull: true,+ }+ err = c.svc.Create(ctx, copyModel(p.Model), opts)+ if imageGone(err) {+ if err := p.pullMissing(ctx, nil); err != nil {+ return err+ }+ err = c.svc.Create(ctx, copyModel(p.Model), opts)+ }+ return p.wrap("create", err)+}++func (p *Project) StartWatched(ctx context.Context, onEvent func(Event), services ...string) error {+ c, err := p.Engine.conn()+ if err != nil {+ return err+ }+ stop := c.bus.listen(p.Name, onEvent)+ defer stop()+ return p.Start(ctx, services...)+}++func (p *Project) Start(ctx context.Context, services ...string) error {+ c, err := p.Engine.conn()+ if err != nil {+ return err+ }+ if err := p.finishStop(ctx, c); err != nil {+ return err+ }+ if p.Model == nil && len(services) > 0 {+ return p.startNamed(ctx, c, services)+ }+ var model *types.Project+ if p.Model != nil {+ model = copyModel(p.Model)+ if len(services) > 0 {+ if model, err = model.WithSelectedServices(services); err != nil {+ return &Error{Op: "start", Class: ClassInvalidConfig, Err: err}+ }+ }+ }+ return p.wrap("start", c.svc.Start(ctx, p.Name, api.StartOptions{Project: model}))+}++func (p *Project) startNamed(ctx context.Context, c *conn, services []string) error {+ containers, err := p.PS(ctx)+ if err != nil {+ return err+ }+ labelled := true+ for _, ct := range containers {+ if slices.Contains(services, ct.Service) && ct.Labels[api.ConfigHashLabel] == "" {+ labelled = false+ }+ }+ if labelled {+ return p.wrap("start", c.svc.Start(ctx, p.Name, api.StartOptions{AttachTo: services}))+ }+ cli := c.cli.Client()+ for _, ct := range containers {+ if !slices.Contains(services, ct.Service) || ct.State == "running" {+ continue+ }+ if _, err := cli.ContainerStart(ctx, ct.ID, client.ContainerStartOptions{}); err != nil {+ return p.wrap("start", err)+ }+ }+ return nil+}++func (p *Project) present(ctx context.Context, op string, services []string) error {+ containers, err := p.PS(ctx)+ if err != nil {+ return err+ }+ for _, c := range containers {+ if len(services) == 0 || slices.Contains(services, c.Service) {+ return nil+ }+ }+ return &Error{Op: op, Class: ClassOther, Err: ErrNoContainers}+}++func (p *Project) Stop(ctx context.Context, services ...string) error {+ c, err := p.Engine.conn()+ if err != nil {+ return err+ }+ if err := p.present(ctx, "stop", services); errors.Is(err, ErrNoContainers) {+ return nil+ } else if err != nil {+ return err+ }+ if marker := p.stopMarker(); marker != "" && os.WriteFile(marker, []byte(strings.Join(services, "\n")), 0o600) == nil {+ defer os.Remove(marker)+ }+ if err := c.svc.Stop(ctx, p.Name, api.StopOptions{Project: p.modelOrNil(), Services: services}); err != nil {+ return p.wrap("stop", err)+ }+ return p.stopPodmanCompose(ctx, services)+}++const staleStopMarker = 5 * time.Minute++func (p *Project) stopMarker() string {+ if p.Dir == "" {+ return ""+ }+ dir := filepath.Join(p.Dir, ".rexctl")+ if info, err := os.Stat(dir); err != nil || !info.IsDir() {+ return ""+ }+ return filepath.Join(dir, "stopping")+}++func (p *Project) finishStop(ctx context.Context, c *conn) error {+ marker := p.stopMarker()+ if marker == "" {+ return nil+ }+ info, err := os.Stat(marker)+ if err != nil {+ return nil+ }+ if time.Since(info.ModTime()) < staleStopMarker {+ data, err := os.ReadFile(marker)+ if err != nil {+ return nil+ }+ services := strings.Fields(string(data))+ detailf("engine: an earlier stop of %v was interrupted, finishing it", services)+ if err := p.present(ctx, "stop", services); errors.Is(err, ErrNoContainers) {+ _ = os.Remove(marker)+ return nil+ } else if err != nil {+ return err+ }+ if err := c.svc.Stop(ctx, p.Name, api.StopOptions{Project: p.modelOrNil(), Services: services}); err != nil {+ return p.wrap("stop", err)+ }+ }+ _ = os.Remove(marker)+ return nil+}++func (p *Project) Restart(ctx context.Context, services ...string) error {+ return p.RestartWatched(ctx, nil, services...)+}++func (p *Project) RestartWatched(ctx context.Context, onEvent func(Event), services ...string) error {+ if err := p.Engine.refuseTooOld("restart"); err != nil {+ return err+ }+ c, err := p.Engine.conn()+ if err != nil {+ return err+ }+ if err := p.present(ctx, "restart", services); err != nil {+ return err+ }+ stop := c.bus.listen(p.Name, onEvent)+ defer stop()+ return p.wrap("restart", c.svc.Restart(ctx, p.Name, api.RestartOptions{Project: p.modelOrNil(), Services: services}))+}++func (p *Project) Remove(ctx context.Context, services ...string) error {+ c, err := p.Engine.conn()+ if err != nil {+ return err+ }+ return p.removeServices(ctx, c, services)+}++func (p *Project) Down(ctx context.Context, volumes bool) error {+ c, err := p.Engine.conn()+ if err != nil {+ return err+ }+ a, err := p.Engine.api()+ if err != nil {+ return err+ }+ if err := p.removeHelpers(ctx, a); err != nil {+ return err+ }+ return p.wrap("down", c.svc.Down(ctx, p.Name, api.DownOptions{Project: p.modelOrNil(), RemoveOrphans: true, Volumes: volumes}))+}++func (p *Project) modelOrNil() *types.Project {+ if p.Model == nil {+ return nil+ }+ return copyModel(p.Model)+}++func imageGone(err error) bool {+ return err != nil && strings.Contains(err.Error(), "No such image")+}++func (p *Project) wrap(op string, err error) error {+ if err == nil {+ return nil+ }+ var e *Error+ if errors.As(err, &e) {+ return err+ }+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {+ return err+ }+ return &Error{Op: op, Class: ClassOf(err), Err: err}+}diff --git a/fluxer_rexctl/internal/engine/pull.go b/fluxer_rexctl/internal/engine/pull.gonew file mode 100644index 000000000..d4da7ca63--- /dev/null+++ b/fluxer_rexctl/internal/engine/pull.go@@ -0,0 +1,128 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package engine++import (+ "context"+ "errors"+ "fmt"+ "strings"++ "github.com/distribution/reference"+ "github.com/docker/cli/cli/command"+ "github.com/moby/moby/client"+)++func (p *Project) Pull(ctx context.Context, onEvent func(Event)) error {+ if err := p.needModel("pull"); err != nil {+ return err+ }+ return p.pullMissing(ctx, onEvent)+}++func (p *Project) pullMissing(ctx context.Context, onEvent func(Event)) error {+ c, err := p.Engine.conn()+ if err != nil {+ return err+ }+ emit := func(ev Event) {+ if onEvent != nil {+ onEvent(ev)+ }+ }+ var missing []string+ for _, ref := range p.Images() {+ _, found, err := p.Engine.LocalImage(ctx, ref)+ if err != nil {+ return err+ }+ if !found {+ missing = append(missing, ref)+ }+ }+ for _, ref := range missing {+ emit(Event{ID: "Image " + ref, Kind: "image", Text: "Waiting", Status: EventWorking})+ }+ var errs []error+ var failed []string+ downHosts := map[string]bool{}+ for _, ref := range missing {+ id := "Image " + ref+ host := registryHost(ref)+ if downHosts[host] {+ emit(Event{ID: id, Kind: "image", Text: "Skipped because " + host + " failed for an earlier image", Status: EventError})+ failed = append(failed, ref)+ continue+ }+ emit(Event{ID: id, Kind: "image", Text: "Pulling", Status: EventWorking})+ if err := pullOne(ctx, c, ref, id, emit); err != nil {+ if ctx.Err() != nil {+ return ctx.Err()+ }+ emit(Event{ID: id, Kind: "image", Text: err.Error(), Status: EventError})+ errs = append(errs, fmt.Errorf("%s: %w", ref, err))+ failed = append(failed, ref)+ if registryDown(err) {+ downHosts[host] = true+ }+ continue+ }+ emit(Event{ID: id, Kind: "image", Text: "Pulled", Status: EventDone})+ }+ if len(errs) > 0 {+ err := errors.Join(errs...)+ return &Error{Op: "pull", Class: ClassOf(&Error{Op: "pull", Err: err}), Images: failed, Err: err}+ }+ return nil+}++func registryHost(ref string) string {+ named, err := reference.ParseNormalizedNamed(ref)+ if err != nil {+ return ref+ }+ return reference.Domain(named)+}++func registryDown(err error) bool {+ switch ClassOf(&Error{Op: "pull", Err: err}) {+ case ClassTimeout, ClassDNS, ClassTLS, ClassProxy, ClassRateLimit:+ return true+ }+ return strings.Contains(strings.ToLower(err.Error()), "connection refused")+}++func pullOne(ctx context.Context, c *conn, ref, id string, emit func(Event)) error {+ auth, err := command.RetrieveAuthTokenFromImage(c.cli.ConfigFile(), ref)+ if err != nil {+ detailf("engine: %s: registry credentials: %v. Pulling without them.", ref, err)+ auth = ""+ }+ api := c.cli.Client()+ resp, err := api.ImagePull(ctx, ref, client.ImagePullOptions{RegistryAuth: auth})+ if err != nil {+ return err+ }+ defer resp.Close()+ for msg, err := range resp.JSONMessages(ctx) {+ if err != nil {+ return err+ }+ if msg.Error != nil {+ return msg.Error+ }+ if msg.ID == "" || strings.HasPrefix(msg.Status, "Pulling from") {+ continue+ }+ ev := Event{ID: msg.ID, Parent: id, Kind: "layer", Text: msg.Status, Status: EventWorking}+ if msg.Progress != nil {+ ev.Current, ev.Total = msg.Progress.Current, msg.Progress.Total+ }+ switch msg.Status {+ case "Pull complete", "Already exists", "Download complete":+ ev.Status = EventDone+ }+ emit(ev)+ }+ return nil+}diff --git a/fluxer_rexctl/internal/engine/stall.go b/fluxer_rexctl/internal/engine/stall.gonew file mode 100644index 000000000..4a2ce2ce2--- /dev/null+++ b/fluxer_rexctl/internal/engine/stall.go@@ -0,0 +1,108 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++package engine++import (+ "bytes"+ "context"+ "errors"+ "io"+ "sync"+ "time"+)++const (+ helperStallLimit = 3 * time.Minute+ helperSilentLimit = 45 * time.Second+ heartbeatLine = "rexctl-alive"+ heartbeatScript = `(while sleep 10; do echo ` + heartbeatLine + ` >&2; done) & alive=$!+"$@"+s=$?+kill $alive 2>/dev/null+exit $s`+)++var ErrHelperStalled = errors.New("rexctl stopped the helper container after the engine stopped sending its output")++type activity struct {+ mu sync.Mutex+ start time.Time+ last time.Time+ busy int+}++func (a *activity) writer(w io.Writer) io.Writer { return activityWriter{a, w} }++type activityWriter struct {+ a *activity+ w io.Writer+}++func (w activityWriter) Write(b []byte) (int, error) {+ w.a.mu.Lock()+ w.a.busy+++ w.a.mu.Unlock()+ n, err := w.w.Write(b)+ w.a.mu.Lock()+ w.a.busy--+ w.a.last = time.Now()+ w.a.mu.Unlock()+ return n, err+}++func (a *activity) stalled(limit time.Duration) bool {+ a.mu.Lock()+ defer a.mu.Unlock()+ return a.busy == 0 && time.Since(a.last) > limit+}++func (a *activity) silent(limit time.Duration) bool {+ a.mu.Lock()+ defer a.mu.Unlock()+ return a.busy == 0 && a.last.Equal(a.start) && time.Since(a.start) > limit+}++func (a *activity) watch(ctx context.Context, cancel context.CancelCauseFunc) {+ t := time.NewTicker(10 * time.Second)+ defer t.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-t.C:+ if a.stalled(helperStallLimit) || a.silent(helperSilentLimit) {+ cancel(ErrHelperStalled)+ return+ }+ }+ }+}++type heartbeatFilter struct {+ w io.Writer+ partial []byte+}++func (f *heartbeatFilter) Write(b []byte) (int, error) {+ f.partial = append(f.partial, b...)+ for {+ i := bytes.IndexByte(f.partial, '\n')+ if i < 0 {+ return len(b), nil+ }+ line := f.partial[:i+1]+ if !bytes.Equal(bytes.TrimSpace(line), []byte(heartbeatLine)) {+ if _, err := f.w.Write(line); err != nil {+ return len(b), err+ }+ }+ f.partial = f.partial[i+1:]+ }+}++func (f *heartbeatFilter) flush() {+ if len(f.partial) > 0 {+ _, _ = f.w.Write(f.partial)+ f.partial = nil+ }+}