| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "os" |
| 9 | "os/exec" |
| 10 | "os/signal" |
| 11 | "strings" |
| 12 | "sync" |
| 13 | "syscall" |
| 14 | "time" |
| 15 | |
| 16 | "github.com/creack/pty" |
| 17 | ) |
| 18 | |
| 19 | // A Reflex is a single watch + command to execute. |
| 20 | type Reflex struct { |
| 21 | id int |
| 22 | source string // Describes what config/line defines this Reflex |
| 23 | startService bool |
| 24 | backlog Backlog |
| 25 | matcher Matcher |
| 26 | onlyFiles bool |
| 27 | onlyDirs bool |
| 28 | command []string |
| 29 | subSymbol string |
| 30 | done chan struct{} |
| 31 | |
| 32 | mu *sync.Mutex // protects killed and running |
| 33 | killed bool |
| 34 | running bool |
| 35 | timeout time.Duration |
| 36 | |
| 37 | // Used for services (startService = true) |
| 38 | cmd *exec.Cmd |
| 39 | tty *os.File |
| 40 | } |
| 41 | |
| 42 | // NewReflex prepares a Reflex from a Config, with sanity checking. |
| 43 | func NewReflex(c *Config) (*Reflex, error) { |
| 44 | matcher, err := ParseMatchers(c.regexes, c.inverseRegexes, c.globs, c.inverseGlobs) |
| 45 | if err != nil { |
| 46 | return nil, fmt.Errorf("error parsing glob/regex: %s", err) |
| 47 | } |
| 48 | if !c.allFiles { |
| 49 | matcher = multiMatcher{defaultExcludeMatcher, matcher} |
| 50 | } |
| 51 | if len(c.command) == 0 { |
| 52 | return nil, errors.New("must give command to execute") |
| 53 | } |
| 54 | |
| 55 | if c.subSymbol == "" { |
| 56 | return nil, errors.New("substitution symbol must be non-empty") |
| 57 | } |
| 58 | |
| 59 | substitution := false |
| 60 | for _, part := range c.command { |
| 61 | if strings.Contains(part, c.subSymbol) { |
| 62 | substitution = true |
| 63 | break |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | var backlog Backlog |
| 68 | if substitution { |
| 69 | if c.startService { |
| 70 | return nil, errors.New("using --start-service does not work with a command that has a substitution symbol") |
| 71 | } |
| 72 | backlog = NewUniqueFilesBacklog() |
| 73 | } else { |
| 74 | backlog = NewUnifiedBacklog() |
| 75 | } |
| 76 | |
| 77 | if c.onlyFiles && c.onlyDirs { |
| 78 | return nil, errors.New("cannot specify both --only-files and --only-dirs") |
| 79 | } |
| 80 | |
| 81 | if c.shutdownTimeout <= 0 { |
| 82 | return nil, errors.New("shutdown timeout cannot be <= 0") |
| 83 | } |
| 84 | |
| 85 | reflex := &Reflex{ |
| 86 | id: reflexID, |
| 87 | source: c.source, |
| 88 | startService: c.startService, |
| 89 | backlog: backlog, |
| 90 | matcher: matcher, |
| 91 | onlyFiles: c.onlyFiles, |
| 92 | onlyDirs: c.onlyDirs, |
| 93 | command: c.command, |
| 94 | subSymbol: c.subSymbol, |
| 95 | done: make(chan struct{}), |
| 96 | timeout: c.shutdownTimeout, |
| 97 | mu: &sync.Mutex{}, |
| 98 | } |
| 99 | reflexID++ |
| 100 | |
| 101 | return reflex, nil |
| 102 | } |
| 103 | |
| 104 | func (r *Reflex) String() string { |
| 105 | var buf bytes.Buffer |
| 106 | fmt.Fprintln(&buf, "Reflex from", r.source) |
| 107 | fmt.Fprintln(&buf, "| ID:", r.id) |
| 108 | for _, matcherInfo := range strings.Split(r.matcher.String(), "\n") { |
| 109 | fmt.Fprintln(&buf, "|", matcherInfo) |
| 110 | } |
| 111 | if r.onlyFiles { |
| 112 | fmt.Fprintln(&buf, "| Only matching files.") |
| 113 | } else if r.onlyDirs { |
| 114 | fmt.Fprintln(&buf, "| Only matching directories.") |
| 115 | } |
| 116 | if !r.startService { |
| 117 | fmt.Fprintln(&buf, "| Substitution symbol", r.subSymbol) |
| 118 | } |
| 119 | replacer := strings.NewReplacer(r.subSymbol, "<filename>") |
| 120 | command := make([]string, len(r.command)) |
| 121 | for i, part := range r.command { |
| 122 | command[i] = replacer.Replace(part) |
| 123 | } |
| 124 | fmt.Fprintln(&buf, "| Command:", command) |
| 125 | fmt.Fprintln(&buf, "+---------") |
| 126 | return buf.String() |
| 127 | } |
| 128 | |
| 129 | // filterMatching passes on messages matching the regex/glob. |
| 130 | func (r *Reflex) filterMatching(out chan<- string, in <-chan string) { |
| 131 | for name := range in { |
| 132 | if !r.matcher.Match(name) { |
| 133 | continue |
| 134 | } |
| 135 | |
| 136 | if r.onlyFiles || r.onlyDirs { |
| 137 | stat, err := os.Stat(name) |
| 138 | if err != nil { |
| 139 | continue |
| 140 | } |
| 141 | if (r.onlyFiles && stat.IsDir()) || (r.onlyDirs && !stat.IsDir()) { |
| 142 | continue |
| 143 | } |
| 144 | } |
| 145 | out <- name |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | // batch receives file notification events and batches them up. It's a bit |
| 150 | // tricky, but here's what it accomplishes: |
| 151 | // * When we initially get a message, wait a bit and batch messages before |
| 152 | // trying to send anything. This is because the file events come in bursts. |
| 153 | // * Once it's time to send, don't do it until the out channel is unblocked. |
| 154 | // In the meantime, keep batching. When we've sent off all the batched |
| 155 | // messages, go back to the beginning. |
| 156 | func (r *Reflex) batch(out chan<- string, in <-chan string) { |
| 157 | |
| 158 | const silenceInterval = 300 * time.Millisecond |
| 159 | |
| 160 | for name := range in { |
| 161 | r.backlog.Add(name) |
| 162 | timer := time.NewTimer(silenceInterval) |
| 163 | outer: |
| 164 | for { |
| 165 | select { |
| 166 | case name := <-in: |
| 167 | r.backlog.Add(name) |
| 168 | if !timer.Stop() { |
| 169 | <-timer.C |
| 170 | } |
| 171 | timer.Reset(silenceInterval) |
| 172 | case <-timer.C: |
| 173 | for { |
| 174 | select { |
| 175 | case name := <-in: |
| 176 | r.backlog.Add(name) |
| 177 | case out <- r.backlog.Next(): |
| 178 | if r.backlog.RemoveOne() { |
| 179 | break outer |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | // runEach runs the command on each name that comes through the names channel. |
| 189 | // Each {} is replaced by the name of the file. The output of the command is |
| 190 | // passed line-by-line to the stdout chan. |
| 191 | func (r *Reflex) runEach(names <-chan string) { |
| 192 | for name := range names { |
| 193 | if r.startService { |
| 194 | if r.Running() { |
| 195 | infoPrintln(r.id, "Killing service") |
| 196 | r.terminate() |
| 197 | } |
| 198 | infoPrintln(r.id, "Starting service") |
| 199 | r.runCommand(name, stdout) |
| 200 | } else { |
| 201 | r.runCommand(name, stdout) |
| 202 | <-r.done |
| 203 | r.mu.Lock() |
| 204 | r.running = false |
| 205 | r.mu.Unlock() |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | func (r *Reflex) terminate() { |
| 211 | r.mu.Lock() |
| 212 | r.killed = true |
| 213 | r.mu.Unlock() |
| 214 | // Write ascii 3 (what you get from ^C) to the controlling pty. |
| 215 | // (This won't do anything if the process already died as the write will |
| 216 | // simply fail.) |
| 217 | r.tty.Write([]byte{3}) |
| 218 | |
| 219 | timer := time.NewTimer(r.timeout) |
| 220 | sig := syscall.SIGINT |
| 221 | for { |
| 222 | select { |
| 223 | case <-r.done: |
| 224 | return |
| 225 | case <-timer.C: |
| 226 | if sig == syscall.SIGINT { |
| 227 | infoPrintln(r.id, "Sending SIGINT signal...") |
| 228 | } else { |
| 229 | infoPrintln(r.id, "Sending SIGKILL signal...") |
| 230 | } |
| 231 | |
| 232 | // Instead of killing the process, we want to kill its |
| 233 | // whole pgroup in order to clean up any children the |
| 234 | // process may have created. |
| 235 | if err := syscall.Kill(-1*r.cmd.Process.Pid, sig); err != nil { |
| 236 | infoPrintln(r.id, "Error killing:", err) |
| 237 | if err.(syscall.Errno) == syscall.ESRCH { // no such process |
| 238 | return |
| 239 | } |
| 240 | } |
| 241 | // After SIGINT doesn't do anything, try SIGKILL next. |
| 242 | timer.Reset(r.timeout) |
| 243 | sig = syscall.SIGKILL |
| 244 | } |
| 245 | } |
| 246 | } |
| 247 | |
| 248 | func replaceSubSymbol(command []string, subSymbol string, name string) []string { |
| 249 | replacer := strings.NewReplacer(subSymbol, name) |
| 250 | newCommand := make([]string, len(command)) |
| 251 | for i, c := range command { |
| 252 | newCommand[i] = replacer.Replace(c) |
| 253 | } |
| 254 | return newCommand |
| 255 | } |
| 256 | |
| 257 | var seqCommands = &sync.Mutex{} |
| 258 | |
| 259 | // runCommand runs the given Command. All output is passed line-by-line to the |
| 260 | // stdout channel. |
| 261 | func (r *Reflex) runCommand(name string, stdout chan<- OutMsg) { |
| 262 | command := replaceSubSymbol(r.command, r.subSymbol, name) |
| 263 | cmd := exec.Command(command[0], command[1:]...) |
| 264 | r.cmd = cmd |
| 265 | |
| 266 | if flagSequential { |
| 267 | seqCommands.Lock() |
| 268 | } |
| 269 | |
| 270 | tty, err := pty.Start(cmd) |
| 271 | if err != nil { |
| 272 | infoPrintln(r.id, err) |
| 273 | return |
| 274 | } |
| 275 | r.tty = tty |
| 276 | |
| 277 | // Handle pty size. |
| 278 | chResize := make(chan os.Signal, 1) |
| 279 | signal.Notify(chResize, syscall.SIGWINCH) |
| 280 | go func() { |
| 281 | for range chResize { |
| 282 | // Intentionally ignore errors in case stdout is not a tty |
| 283 | pty.InheritSize(os.Stdout, tty) |
| 284 | } |
| 285 | }() |
| 286 | chResize <- syscall.SIGWINCH // Initial resize. |
| 287 | |
| 288 | go func() { |
| 289 | scanner := bufio.NewScanner(tty) |
| 290 | // Allow for lines up to 100 MB. |
| 291 | scanner.Buffer(nil, 100e6) |
| 292 | for scanner.Scan() { |
| 293 | stdout <- OutMsg{r.id, scanner.Text()} |
| 294 | } |
| 295 | if err := scanner.Err(); errors.Is(err, bufio.ErrTooLong) { |
| 296 | infoPrintln(r.id, "Error: subprocess emitted a line longer than 100 MB") |
| 297 | } |
| 298 | // Intentionally ignore other scanner errors. Unfortunately, |
| 299 | // the pty returns a read error when the child dies naturally, |
| 300 | // so I'm just going to ignore errors here unless I can find a |
| 301 | // better way to handle it. |
| 302 | }() |
| 303 | |
| 304 | r.mu.Lock() |
| 305 | r.running = true |
| 306 | r.mu.Unlock() |
| 307 | go func() { |
| 308 | err := cmd.Wait() |
| 309 | if !r.Killed() && err != nil { |
| 310 | stdout <- OutMsg{r.id, fmt.Sprintf("(error exit: %s)", err)} |
| 311 | } |
| 312 | r.done <- struct{}{} |
| 313 | |
| 314 | signal.Stop(chResize) |
| 315 | close(chResize) |
| 316 | |
| 317 | if flagSequential { |
| 318 | seqCommands.Unlock() |
| 319 | } |
| 320 | }() |
| 321 | } |
| 322 | |
| 323 | func (r *Reflex) Start(changes <-chan string) { |
| 324 | filtered := make(chan string) |
| 325 | batched := make(chan string) |
| 326 | go r.filterMatching(filtered, changes) |
| 327 | go r.batch(batched, filtered) |
| 328 | go r.runEach(batched) |
| 329 | if r.startService { |
| 330 | // Easy hack to kick off the initial start. |
| 331 | infoPrintln(r.id, "Starting service") |
| 332 | r.runCommand("", stdout) |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | func (r *Reflex) Killed() bool { |
| 337 | r.mu.Lock() |
| 338 | defer r.mu.Unlock() |
| 339 | return r.killed |
| 340 | } |
| 341 | |
| 342 | func (r *Reflex) Running() bool { |
| 343 | r.mu.Lock() |
| 344 | defer r.mu.Unlock() |
| 345 | return r.running |
| 346 | } |