-
Notifications
You must be signed in to change notification settings - Fork 0
/
guided-command.go
101 lines (80 loc) · 2.17 KB
/
guided-command.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
92
93
94
95
96
97
98
99
100
101
package main
import (
"context"
"errors"
"fmt"
"math/rand"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
ctx, cancelCtx := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill, syscall.SIGTERM)
defer cancelCtx()
if len(os.Args) < 4 {
fmt.Fprintf(os.Stderr, "Usage: %s <startedPath> <unlockPath> <donePath> [<doneText>]", os.Args[0])
os.Exit(1)
}
startedPath := os.Args[1]
unlockPath := os.Args[2]
donePath := os.Args[3]
doneText := "done"
if len(os.Args) == 5 {
doneText = os.Args[4]
}
pidStr := fmt.Sprintf("%d", os.Getpid())
err := writeFileAtomic(startedPath, []byte(pidStr), 0o666)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to create 'i'm started' file %q: %v", startedPath, err)
os.Exit(1)
}
WaitForUnblockFile:
for {
select {
case <-ctx.Done():
err = os.Remove(startedPath)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to remove 'i'm started' file %q after stop signal: %v", startedPath, err)
os.Exit(1)
}
os.Exit(0)
case <-time.After(10 * time.Millisecond):
_, err = os.Stat(unlockPath)
if err == nil {
break WaitForUnblockFile
}
if errors.Is(err, os.ErrNotExist) {
continue
}
fmt.Fprintf(os.Stderr, "failed wait for 'unlock' file %q: %v", unlockPath, err)
os.Exit(1)
}
}
err = writeFileAtomic(donePath, []byte(doneText), 0o666)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to create 'i'm done' file %q: %v", donePath, err)
os.Exit(1)
}
}
func writeFileAtomic(filePath string, data []byte, mode os.FileMode) error {
filePathTmp := fmt.Sprintf("%s.%s", filePath, randStr(5))
err := os.WriteFile(filePathTmp, data, mode)
if err != nil {
return fmt.Errorf("failed to create intermediate tmp file for %q: %w", filePathTmp, err)
}
err = os.Rename(filePathTmp, filePath)
if err != nil {
return fmt.Errorf("failed to rename intermediate tmp file %q to %q: %w", filePathTmp, filePath, err)
}
return nil
}
func randStr(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
variety := len(charset)
ret := make([]byte, length)
for i := range ret {
ret[i] = charset[rand.Intn(variety)]
}
return string(ret)
}