| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "strconv" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/runner" |
| 14 | "golang.org/x/sys/unix" |
| 15 | ) |
| 16 | |
| 17 | // installBackup keeps what an install replaces until the install is done: |
| 18 | // each path is moved aside, into one private directory on the same disk, |
| 19 | // before anything new is written there. A failed install puts every path |
| 20 | // back as it was (what did not exist is removed again); one that worked |
| 21 | // drops what was kept. |
| 22 | type installBackup struct { |
| 23 | dir string |
| 24 | moved []movedAside |
| 25 | } |
| 26 | |
| 27 | type movedAside struct { |
| 28 | path, aside string |
| 29 | existed bool |
| 30 | } |
| 31 | |
| 32 | func newInstallBackup(within string) (*installBackup, error) { |
| 33 | dir, err := os.MkdirTemp(within, ".install-previous-") |
| 34 | if err != nil { |
| 35 | return nil, err |
| 36 | } |
| 37 | return &installBackup{dir: dir}, nil |
| 38 | } |
| 39 | |
| 40 | // keep moves path aside; a path that does not exist yet is noted, so a |
| 41 | // failed install removes what it wrote there. |
| 42 | func (b *installBackup) keep(paths ...string) error { |
| 43 | for _, path := range paths { |
| 44 | aside := filepath.Join(b.dir, strconv.Itoa(len(b.moved))) |
| 45 | err := os.Rename(path, aside) |
| 46 | if os.IsNotExist(err) { |
| 47 | b.moved = append(b.moved, movedAside{path: path}) |
| 48 | continue |
| 49 | } |
| 50 | if err != nil { |
| 51 | return err |
| 52 | } |
| 53 | b.moved = append(b.moved, movedAside{path: path, aside: aside, existed: true}) |
| 54 | } |
| 55 | return nil |
| 56 | } |
| 57 | |
| 58 | // kept reports whether anything existed before (a runner to put back). |
| 59 | func (b *installBackup) kept() bool { |
| 60 | for _, m := range b.moved { |
| 61 | if m.existed { |
| 62 | return true |
| 63 | } |
| 64 | } |
| 65 | return false |
| 66 | } |
| 67 | |
| 68 | // restore puts every path back, last kept first, and reports whether all |
| 69 | // of them went back. What could not go back stays in the backup |
| 70 | // directory, which is then kept. |
| 71 | func (b *installBackup) restore() bool { |
| 72 | ok := true |
| 73 | for i := len(b.moved) - 1; i >= 0; i-- { |
| 74 | m := b.moved[i] |
| 75 | if err := os.RemoveAll(m.path); err != nil { |
| 76 | ok = false |
| 77 | continue |
| 78 | } |
| 79 | if m.existed && os.Rename(m.aside, m.path) != nil { |
| 80 | ok = false |
| 81 | } |
| 82 | } |
| 83 | if ok { |
| 84 | ok = os.Remove(b.dir) == nil |
| 85 | } |
| 86 | b.moved = nil |
| 87 | return ok |
| 88 | } |
| 89 | |
| 90 | // drop removes what was kept: the install worked. |
| 91 | func (b *installBackup) drop() { |
| 92 | _ = os.RemoveAll(b.dir) |
| 93 | b.moved = nil |
| 94 | } |
| 95 | |
| 96 | // asideOf is where path was moved aside, "" when it was not. |
| 97 | func (b *installBackup) asideOf(path string) string { |
| 98 | for _, m := range b.moved { |
| 99 | if m.path == path && m.existed { |
| 100 | return m.aside |
| 101 | } |
| 102 | } |
| 103 | return "" |
| 104 | } |
| 105 | |
| 106 | // errInstallBusy: another install holds the install lock. |
| 107 | var errInstallBusy = errors.New("another install is running") |
| 108 | |
| 109 | // installLock is held for a whole install, from the check that the |
| 110 | // runner works for no other Equipo until it is enrolled or put back, so |
| 111 | // a second install of the same runner is refused (runner.install.busy) |
| 112 | // rather than putting its backup back over what the first installed. |
| 113 | // It is its own file in the state directory, apart from the runner's |
| 114 | // lock, which the running runner holds and the enrolment takes. |
| 115 | func installLock(state string) (*os.File, error) { |
| 116 | if err := os.MkdirAll(state, 0700); err != nil { |
| 117 | return nil, err |
| 118 | } |
| 119 | f, err := os.OpenFile(filepath.Join(state, "install.lock"), os.O_CREATE|os.O_RDWR|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0600) |
| 120 | if err != nil { |
| 121 | return nil, err |
| 122 | } |
| 123 | if err := unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { |
| 124 | f.Close() |
| 125 | if errors.Is(err, unix.EWOULDBLOCK) { |
| 126 | return nil, errInstallBusy |
| 127 | } |
| 128 | return nil, err |
| 129 | } |
| 130 | return f, nil |
| 131 | } |
| 132 | |
| 133 | // enrolAlone is a direct enrolment (equipo-runner enrol): refused while |
| 134 | // an install holds the install lock, so an install that then fails |
| 135 | // cannot put its earlier configuration back beside what this added. |
| 136 | func enrolAlone(ctx context.Context, cfg runner.Config, out io.Writer, enrol func(context.Context, runner.Config, io.Writer) error) error { |
| 137 | lock, err := installLock(cfg.StateDir) |
| 138 | if err != nil { |
| 139 | return err |
| 140 | } |
| 141 | defer lock.Close() |
| 142 | return enrol(ctx, cfg, out) |
| 143 | } |
| 144 | |
| 145 | // credentialBefore is the runner's credential file as it is before an |
| 146 | // enrolment ("" when there is none). |
| 147 | func credentialBefore(state string) string { |
| 148 | raw, _ := os.ReadFile(filepath.Join(state, "credentials.json")) |
| 149 | return string(raw) |
| 150 | } |
| 151 | |
| 152 | // enrolOutcome is what an enrolment that answered an error left: |
| 153 | // enrolled when it published a new credential for origin and instance |
| 154 | // all the same (the directory sync after its rename failed), so what an |
| 155 | // install kept aside must not be put back beside it; unknown when the |
| 156 | // credential cannot be read, so whether it did is not known, and nothing |
| 157 | // may be put back either. |
| 158 | func enrolOutcome(state, origin, instance, before string) (enrolled, unknown bool) { |
| 159 | raw, err := os.ReadFile(filepath.Join(state, "credentials.json")) |
| 160 | if err != nil && !os.IsNotExist(err) { |
| 161 | return false, true |
| 162 | } |
| 163 | if string(raw) == before { |
| 164 | return false, false |
| 165 | } |
| 166 | enrolled, err = runner.EnrolledWith(state, origin, instance) |
| 167 | return enrolled, err != nil |
| 168 | } |
| 169 | |
| 170 | // detached is a context for putting things back: not ended by the |
| 171 | // person's Ctrl-C, but bounded. |
| 172 | func detached(ctx context.Context) (context.Context, context.CancelFunc) { |
| 173 | return context.WithTimeout(context.WithoutCancel(ctx), time.Minute) |
| 174 | } |
| 175 | |
| 176 | // lockKey is the line for an install lock that could not be taken. |
| 177 | func lockKey(err error) string { |
| 178 | if errors.Is(err, errInstallBusy) { |
| 179 | return "runner.install.busy" |
| 180 | } |
| 181 | return "runner.install.destination" |
| 182 | } |
| 183 | |
| 184 | // promptLines reads the person's answers a line at a time. A read waits |
| 185 | // for the line or for ctx to end (Ctrl-C ends it), whichever is first, |
| 186 | // so a prompt never holds an install that has something moved aside. |
| 187 | type promptLines struct { |
| 188 | lines chan promptLine |
| 189 | } |
| 190 | |
| 191 | type promptLine struct { |
| 192 | text string |
| 193 | err error |
| 194 | } |
| 195 | |
| 196 | func newPromptLines(input io.Reader) *promptLines { |
| 197 | p := &promptLines{lines: make(chan promptLine)} |
| 198 | go func() { |
| 199 | r := bufio.NewReader(input) |
| 200 | for { |
| 201 | text, err := r.ReadString('\n') |
| 202 | p.lines <- promptLine{text, err} |
| 203 | if err != nil { |
| 204 | close(p.lines) |
| 205 | return |
| 206 | } |
| 207 | } |
| 208 | }() |
| 209 | return p |
| 210 | } |
| 211 | |
| 212 | func (p *promptLines) read(ctx context.Context) (string, error) { |
| 213 | select { |
| 214 | case <-ctx.Done(): |
| 215 | return "", ctx.Err() |
| 216 | case l, ok := <-p.lines: |
| 217 | if !ok { |
| 218 | return "", io.EOF |
| 219 | } |
| 220 | return l.text, l.err |
| 221 | } |
| 222 | } |
| 223 | |