-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
recording.go
91 lines (85 loc) · 2.17 KB
/
recording.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
Package recording implements a wrapper around a given recording command.
It provides functionality to start, stop, automatically restart and to wait for
the command to finish.
*/
package recording
import (
"context"
"io"
"log"
"os"
"os/exec"
"time"
)
var exitStatusZero error
// WaitFunc waits for the command execution to stop.
// It returns an error explaining the stop.
type WaitFunc func() error
// StartFunc executes the recording command with the given args and writes the
// output to the provided writer. It returns a function to stop the recording
// and a function to wait for the recording to stop.
type StartFunc func(command string, args []string, w io.Writer) (
stop context.CancelFunc,
wait WaitFunc,
)
func run(
ctx context.Context,
command string,
args []string,
w io.Writer,
status chan error,
) {
cmd := exec.CommandContext(ctx, command, args...)
cmd.Stderr = os.Stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Println(err)
status <- err
close(status)
return
}
err = cmd.Start()
if err != nil {
log.Println(err)
status <- err
close(status)
return
}
go io.Copy(w, stdout)
startTime := time.Now()
log.Println("Recording started")
err = cmd.Wait()
log.Println("Recording stopped")
canceled := ctx.Err()
if err != exitStatusZero && canceled != context.Canceled {
// Command has stopped unexpectedly.
log.Println(err)
if time.Since(startTime).Seconds() > 1 {
// Command ran long enough for this not to be an argument error, restart.
run(ctx, command, args, w, status)
} else {
status <- err
close(status)
}
} else {
status <- canceled
close(status)
}
}
// Start executes the recording command with the given args and writes the
// output to the provided writer. It returns a function to stop the recording
// and a function to wait for the recording to stop.
// If the recording command fails unexpectedly, it is restarted automatically.
func Start(command string, args []string, w io.Writer) (
stop context.CancelFunc,
wait WaitFunc,
) {
ctx, stop := context.WithCancel(context.Background())
status := make(chan error)
wait = func() error {
return <-status
}
go run(ctx, command, args, w, status)
return
}