-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck.go
More file actions
133 lines (107 loc) · 2.27 KB
/
Copy pathcheck.go
File metadata and controls
133 lines (107 loc) · 2.27 KB
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package main
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"os"
"github.com/thekhanj/avail/config"
"github.com/thekhanj/avail/exec"
)
func NewCheckFromConfig(cfg config.Check) (Check, error) {
if cfg == nil {
return &StatusCheck{}, nil
}
if c, ok := cfg.(*config.ShellCheck); ok {
ret := &ShellCheck{
shell: c.Shell,
script: c.Script,
}
if c.Log {
ret.log = log.New(os.Stderr, "shell-check", 0)
}
return ret, nil
}
if c, ok := cfg.(*config.ExecCheck); ok {
ret := &ExecCheck{
command: c.Exec,
}
if c.Log {
ret.log = log.New(os.Stderr, "exec-check", 0)
}
return ret, nil
}
invalidErr := fmt.Errorf("Invalid check strategy: %v", cfg)
return nil, invalidErr
}
type Check interface {
IsUp(res *http.Response) (bool, error)
}
type StatusCheck struct{}
func (this *StatusCheck) IsUp(res *http.Response) (bool, error) {
return 200 <= res.StatusCode && res.StatusCode < 300, nil
}
var _ Check = (*StatusCheck)(nil)
type ExecCheck struct {
stdin io.Reader
command string
log *log.Logger
}
func (this *ExecCheck) IsUp(res *http.Response) (bool, error) {
name, err := this.writeRawHttp(res)
if err != nil {
return false, err
}
defer os.Remove(name)
e, err := exec.New(
exec.WithShlex(this.command),
exec.WithEnv(fmt.Sprintf("AVAIL_HTTP=%s", name)),
func(e *exec.Exec) error {
if this.log != nil {
return exec.WithLogger(this.log)(e)
}
return nil
},
func(e *exec.Exec) error {
if this.stdin != nil {
return exec.WithStdin(this.stdin)(e)
}
return nil
},
)
if err != nil {
return false, err
}
exitCode, err := e.Run()
if err != nil {
return false, err
}
return exitCode == 0, nil
}
func (this *ExecCheck) writeRawHttp(res *http.Response) (string, error) {
tmp, err := os.CreateTemp(os.TempDir(), "avail-http-*")
if err != nil {
return "", err
}
defer tmp.Close()
err = res.Write(tmp)
if err != nil {
return "", err
}
return tmp.Name(), nil
}
var _ Check = (*ExecCheck)(nil)
type ShellCheck struct {
shell string
script string
log *log.Logger
}
func (this *ShellCheck) IsUp(res *http.Response) (bool, error) {
e := ExecCheck{}
e.stdin = bytes.NewReader([]byte(this.script))
e.command = this.shell
e.log = this.log
return e.IsUp(res)
}
var _ Check = (*ShellCheck)(nil)