forked from tuna/tunasync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exec_post_hook.go
98 lines (83 loc) · 1.89 KB
/
exec_post_hook.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
package worker
import (
"errors"
"fmt"
"github.com/anmitsu/go-shlex"
"github.com/codeskyblue/go-sh"
)
// hook to execute command after syncing
// typically setting timestamp, etc.
const (
execOnSuccess uint8 = iota
execOnFailure
)
type execPostHook struct {
emptyHook
// exec on success or on failure
execOn uint8
// command
command []string
}
func newExecPostHook(provider mirrorProvider, execOn uint8, command string) (*execPostHook, error) {
cmd, err := shlex.Split(command, true)
if err != nil {
// logger.Errorf("Failed to create exec-post-hook for command: %s", command)
return nil, err
}
if execOn != execOnSuccess && execOn != execOnFailure {
return nil, fmt.Errorf("Invalid option for exec-on: %d", execOn)
}
return &execPostHook{
emptyHook: emptyHook{
provider: provider,
},
execOn: execOn,
command: cmd,
}, nil
}
func (h *execPostHook) postSuccess() error {
if h.execOn == execOnSuccess {
return h.Do()
}
return nil
}
func (h *execPostHook) postFail() error {
if h.execOn == execOnFailure {
return h.Do()
}
return nil
}
func (h *execPostHook) Do() error {
p := h.provider
exitStatus := ""
if h.execOn == execOnSuccess {
exitStatus = "success"
} else {
exitStatus = "failure"
}
env := map[string]string{
"TUNASYNC_MIRROR_NAME": p.Name(),
"TUNASYNC_WORKING_DIR": p.WorkingDir(),
"TUNASYNC_UPSTREAM_URL": p.Upstream(),
"TUNASYNC_LOG_DIR": p.LogDir(),
"TUNASYNC_LOG_FILE": p.LogFile(),
"TUNASYNC_JOB_EXIT_STATUS": exitStatus,
}
session := sh.NewSession()
for k, v := range env {
session.SetEnv(k, v)
}
var cmd string
args := []interface{}{}
if len(h.command) == 1 {
cmd = h.command[0]
} else if len(h.command) > 1 {
cmd = h.command[0]
for _, arg := range h.command[1:] {
args = append(args, arg)
}
} else {
return errors.New("Invalid Command")
}
return session.Command(cmd, args...).Run()
}