intake/core/execute.go

203 lines
4.5 KiB
Go
Raw Normal View History

2025-01-17 21:49:23 +00:00
package core
import (
"bufio"
"context"
"encoding/json"
"errors"
2025-01-30 07:14:00 +00:00
"fmt"
2025-01-17 21:49:23 +00:00
"io"
"log"
"os"
"os/exec"
"strings"
"time"
)
2025-02-10 06:59:04 +00:00
func readPipe(
f io.ReadCloser,
send chan []byte,
done chan int,
2025-02-05 21:21:31 +00:00
) {
2025-02-10 06:59:04 +00:00
defer func() {
done <- 0
}()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
data := scanner.Bytes()
send <- data
2025-01-17 21:49:23 +00:00
}
}
func Execute(
2025-01-23 20:26:21 +00:00
source string,
2025-01-17 21:49:23 +00:00
argv []string,
env []string,
state []byte,
2025-01-17 21:49:23 +00:00
input string,
timeout time.Duration,
2025-02-05 21:21:31 +00:00
postProcess func(item Item) Item,
2025-02-10 06:59:04 +00:00
) (
items []Item,
newState []byte,
err error,
) {
2025-01-30 07:51:06 +00:00
log.Printf("executing %v", argv)
2025-01-17 21:49:23 +00:00
if len(argv) == 0 {
return nil, nil, errors.New("empty argv")
2025-01-17 21:49:23 +00:00
}
2025-01-29 15:39:00 +00:00
if source == "" {
return nil, nil, errors.New("empty source")
2025-01-29 15:39:00 +00:00
}
2025-01-17 21:49:23 +00:00
stateFile, err := os.CreateTemp("", "intake_state_*")
if err != nil {
return nil, nil, fmt.Errorf("error: failed to create temp state file: %v", err)
}
defer func() {
if err := os.Remove(stateFile.Name()); err != nil {
log.Printf("error: failed to delete %s", stateFile.Name())
}
}()
_, err = stateFile.Write(state)
if err != nil {
return nil, nil, fmt.Errorf("error: failed to write state file: %v", err)
}
env = append(env, "STATE_PATH="+stateFile.Name())
2025-01-17 21:49:23 +00:00
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
cmd := exec.CommandContext(ctx, argv[0], argv[1:]...)
cmd.Env = append(os.Environ(), env...)
cmd.WaitDelay = time.Second * 5
// Open pipes to the command
stdin, err := cmd.StdinPipe()
if err != nil {
return nil, nil, err
2025-01-17 21:49:23 +00:00
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, nil, err
2025-01-17 21:49:23 +00:00
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, nil, err
2025-01-17 21:49:23 +00:00
}
2025-02-10 06:59:04 +00:00
cout := make(chan []byte)
cerr := make(chan []byte)
coutDone := make(chan int)
cerrDone := make(chan int)
2025-01-17 21:49:23 +00:00
// Routines handling the process i/o
2025-02-10 06:59:04 +00:00
go readPipe(stdout, cout, coutDone)
go readPipe(stderr, cerr, cerrDone)
2025-01-17 21:49:23 +00:00
// Kick off the command
err = cmd.Start()
if err != nil {
return nil, nil, err
2025-01-17 21:49:23 +00:00
}
2025-02-10 06:59:04 +00:00
// Write any input to stdin and close it
io.WriteString(stdin, input)
stdin.Close()
// Collect outputs until std{out,err} close
parseError := false
stdoutDone := false
stderrDone := false
monitor:
for {
select {
case data := <-cout:
var item Item
err := json.Unmarshal(data, &item)
if err != nil || item.Id == "" {
log.Printf("[%s: stdout] %s", source, strings.TrimSpace(string(data)))
parseError = true
} else {
if postProcess != nil {
item = postProcess(item)
}
item.Active = true // These fields aren't up to
item.Created = 0 // the action to set and
item.Source = source // shouldn't be overrideable
log.Printf("[%s: item] %s\n", source, item.Id)
items = append(items, item)
}
case data := <-cerr:
log.Printf("[%s: stderr] %s\n", source, data)
case <-coutDone:
stdoutDone = true
if stdoutDone && stderrDone {
break monitor
}
case <-cerrDone:
stderrDone = true
if stdoutDone && stderrDone {
break monitor
}
}
}
2025-01-17 21:49:23 +00:00
err = cmd.Wait()
if ctx.Err() == context.DeadlineExceeded {
log.Printf("Timed out after %v\n", timeout)
return nil, nil, err
2025-01-17 21:49:23 +00:00
} else if exiterr, ok := err.(*exec.ExitError); ok {
log.Printf("error: %s failed with exit code %d\n", argv[0], exiterr.ExitCode())
return nil, nil, err
2025-01-17 21:49:23 +00:00
} else if err != nil {
log.Printf("error: %s failed with error: %s\n", argv[0], err)
return nil, nil, err
2025-01-17 21:49:23 +00:00
}
if parseError {
log.Printf("error: could not parse item\n")
return nil, nil, errors.New("invalid JSON")
}
2025-02-10 06:59:04 +00:00
newState, err = os.ReadFile(stateFile.Name())
if err != nil {
return nil, nil, fmt.Errorf("error: failed to read state file: %v", err)
2025-01-17 21:49:23 +00:00
}
2025-02-10 06:59:04 +00:00
return
2025-01-17 21:49:23 +00:00
}
2025-01-30 07:14:00 +00:00
// Execute an action that takes an item as input and returns the item modified.
// This is basically just a wrapper over [Execute] that handles the input and backfilling.
2025-01-30 07:14:00 +00:00
func ExecuteItemAction(
item Item,
argv []string,
2025-01-30 07:51:06 +00:00
env []string,
state []byte,
2025-01-30 07:14:00 +00:00
timeout time.Duration,
2025-02-05 21:21:31 +00:00
postProcess func(item Item) Item,
) (Item, []byte, error) {
2025-01-30 07:14:00 +00:00
itemJson, err := json.Marshal(item)
if err != nil {
return Item{}, nil, fmt.Errorf("failed to serialize item: %v", err)
2025-01-30 07:14:00 +00:00
}
2025-02-05 21:21:31 +00:00
res, newState, err := Execute(item.Source, argv, env, state, string(itemJson), timeout, postProcess)
2025-01-30 07:14:00 +00:00
if err != nil {
return Item{}, nil, fmt.Errorf("failed to execute action for %s/%s: %v", item.Source, item.Id, err)
2025-01-30 07:14:00 +00:00
}
if len(res) != 1 {
return Item{}, nil, fmt.Errorf("expected action to produce exactly one item, got %d", len(res))
2025-01-30 07:14:00 +00:00
}
newItem := res[0]
BackfillItem(&newItem, &item)
return newItem, newState, nil
2025-01-30 07:14:00 +00:00
}