package main import ( "bufio" "context" "errors" "io" "os" "path/filepath" "strconv" "time" "amadan.net/oficina/equipo/internal/runner" "golang.org/x/sys/unix" ) // installBackup keeps what an install replaces until the install is done: // each path is moved aside, into one private directory on the same disk, // before anything new is written there. A failed install puts every path // back as it was (what did not exist is removed again); one that worked // drops what was kept. type installBackup struct { dir string moved []movedAside } type movedAside struct { path, aside string existed bool } func newInstallBackup(within string) (*installBackup, error) { dir, err := os.MkdirTemp(within, ".install-previous-") if err != nil { return nil, err } return &installBackup{dir: dir}, nil } // keep moves path aside; a path that does not exist yet is noted, so a // failed install removes what it wrote there. func (b *installBackup) keep(paths ...string) error { for _, path := range paths { aside := filepath.Join(b.dir, strconv.Itoa(len(b.moved))) err := os.Rename(path, aside) if os.IsNotExist(err) { b.moved = append(b.moved, movedAside{path: path}) continue } if err != nil { return err } b.moved = append(b.moved, movedAside{path: path, aside: aside, existed: true}) } return nil } // kept reports whether anything existed before (a runner to put back). func (b *installBackup) kept() bool { for _, m := range b.moved { if m.existed { return true } } return false } // restore puts every path back, last kept first, and reports whether all // of them went back. What could not go back stays in the backup // directory, which is then kept. func (b *installBackup) restore() bool { ok := true for i := len(b.moved) - 1; i >= 0; i-- { m := b.moved[i] if err := os.RemoveAll(m.path); err != nil { ok = false continue } if m.existed && os.Rename(m.aside, m.path) != nil { ok = false } } if ok { ok = os.Remove(b.dir) == nil } b.moved = nil return ok } // drop removes what was kept: the install worked. func (b *installBackup) drop() { _ = os.RemoveAll(b.dir) b.moved = nil } // asideOf is where path was moved aside, "" when it was not. func (b *installBackup) asideOf(path string) string { for _, m := range b.moved { if m.path == path && m.existed { return m.aside } } return "" } // errInstallBusy: another install holds the install lock. var errInstallBusy = errors.New("another install is running") // installLock is held for a whole install, from the check that the // runner works for no other Equipo until it is enrolled or put back, so // a second install of the same runner is refused (runner.install.busy) // rather than putting its backup back over what the first installed. // It is its own file in the state directory, apart from the runner's // lock, which the running runner holds and the enrolment takes. func installLock(state string) (*os.File, error) { if err := os.MkdirAll(state, 0700); err != nil { return nil, err } f, err := os.OpenFile(filepath.Join(state, "install.lock"), os.O_CREATE|os.O_RDWR|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0600) if err != nil { return nil, err } if err := unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { f.Close() if errors.Is(err, unix.EWOULDBLOCK) { return nil, errInstallBusy } return nil, err } return f, nil } // enrolAlone is a direct enrolment (equipo-runner enrol): refused while // an install holds the install lock, so an install that then fails // cannot put its earlier configuration back beside what this added. func enrolAlone(ctx context.Context, cfg runner.Config, out io.Writer, enrol func(context.Context, runner.Config, io.Writer) error) error { lock, err := installLock(cfg.StateDir) if err != nil { return err } defer lock.Close() return enrol(ctx, cfg, out) } // credentialBefore is the runner's credential file as it is before an // enrolment ("" when there is none). func credentialBefore(state string) string { raw, _ := os.ReadFile(filepath.Join(state, "credentials.json")) return string(raw) } // enrolOutcome is what an enrolment that answered an error left: // enrolled when it published a new credential for origin and instance // all the same (the directory sync after its rename failed), so what an // install kept aside must not be put back beside it; unknown when the // credential cannot be read, so whether it did is not known, and nothing // may be put back either. func enrolOutcome(state, origin, instance, before string) (enrolled, unknown bool) { raw, err := os.ReadFile(filepath.Join(state, "credentials.json")) if err != nil && !os.IsNotExist(err) { return false, true } if string(raw) == before { return false, false } enrolled, err = runner.EnrolledWith(state, origin, instance) return enrolled, err != nil } // detached is a context for putting things back: not ended by the // person's Ctrl-C, but bounded. func detached(ctx context.Context) (context.Context, context.CancelFunc) { return context.WithTimeout(context.WithoutCancel(ctx), time.Minute) } // lockKey is the line for an install lock that could not be taken. func lockKey(err error) string { if errors.Is(err, errInstallBusy) { return "runner.install.busy" } return "runner.install.destination" } // promptLines reads the person's answers a line at a time. A read waits // for the line or for ctx to end (Ctrl-C ends it), whichever is first, // so a prompt never holds an install that has something moved aside. type promptLines struct { lines chan promptLine } type promptLine struct { text string err error } func newPromptLines(input io.Reader) *promptLines { p := &promptLines{lines: make(chan promptLine)} go func() { r := bufio.NewReader(input) for { text, err := r.ReadString('\n') p.lines <- promptLine{text, err} if err != nil { close(p.lines) return } } }() return p } func (p *promptLines) read(ctx context.Context) (string, error) { select { case <-ctx.Done(): return "", ctx.Err() case l, ok := <-p.lines: if !ok { return "", io.EOF } return l.text, l.err } }