-
Notifications
You must be signed in to change notification settings - Fork 2
/
plugin.go
210 lines (176 loc) · 4.33 KB
/
plugin.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
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package scheme
import (
"bufio"
"context"
"errors"
"io"
"os"
"os/exec"
"strings"
"time"
"github.com/macrat/ayd/internal/scheme/textdecode"
api "github.com/macrat/ayd/lib-ayd"
)
var (
// currentTime returns the current time.
// This function can override for testing.
currentTime = time.Now
)
// PluginScheme is the plugin handler. This implements both of Prober interface and Alerter interface.
type PluginScheme struct {
target *api.URL
tracker *TargetTracker
}
// pluginCandidates makes scheme name candidates of plugin by URL scheme.
// The output is priority ascending order, which means the first candidate has the lowest priority.
func pluginCandidates(scheme, scope string) []string {
var xs []string
for i, x := range scheme {
if x == '-' || x == '+' {
xs = append(
xs,
"ayd-"+scheme[:i]+"-scheme",
"ayd-"+scheme[:i]+"-"+scope,
)
}
}
xs = append(
xs,
"ayd-"+scheme+"-scheme",
"ayd-"+scheme+"-"+scope,
)
return xs
}
// findPlugin finds a plugin for URL scheme.
// It choice the longest name plugin.
func findPlugin(scheme, scope string) (commandName string, err error) {
candidates := pluginCandidates(scheme, scope)
for i := range candidates {
commandName = candidates[len(candidates)-i-1]
_, err = exec.LookPath(commandName)
if err == nil || !errors.Is(err, exec.ErrNotFound) {
return
}
}
return "", ErrUnsupportedScheme
}
func NewPluginScheme(u *api.URL, scope string) (PluginScheme, error) {
scheme, _, _ := SplitScheme(u.Scheme)
if scheme == "ayd" || scheme == "alert" {
return PluginScheme{}, ErrUnsupportedScheme
}
p := PluginScheme{
target: u,
tracker: &TargetTracker{},
}
p.tracker.Activate(u)
if _, err := findPlugin(u.Scheme, scope); err != nil {
return PluginScheme{}, err
}
return p, nil
}
func NewPluginProbe(u *api.URL) (PluginScheme, error) {
return NewPluginScheme(u, "probe")
}
func NewPluginAlert(u *api.URL) (PluginScheme, error) {
return NewPluginScheme(u, "alert")
}
func (p PluginScheme) Target() *api.URL {
return p.target
}
func (p PluginScheme) execute(ctx context.Context, r Reporter, scope string, args []string) {
ctx, cancel := context.WithTimeout(ctx, 60*time.Minute)
defer cancel()
command, err := findPlugin(p.target.Scheme, scope)
if err != nil {
r.Report(p.target, api.Record{
Time: time.Now(),
Target: p.target,
Status: api.StatusUnknown,
Message: scope + " plugin for " + p.target.Scheme + " was not found",
})
return
}
rb, wb := io.Pipe()
defer rb.Close()
stime := time.Now()
var status api.Status
var latency time.Duration
go func() {
status, err = runExternalCommand(ctx, wb, command, args, os.Environ())
latency = time.Since(stime)
wb.Close()
}()
count := 0
var invalidLines []string
scanner := bufio.NewScanner(rb)
for scanner.Scan() {
text, err := textdecode.Bytes(scanner.Bytes())
if err != nil {
invalidLines = append(invalidLines, scanner.Text())
continue
}
text = strings.TrimSpace(text)
if text == "" {
continue
}
rec, err := api.ParseRecord(text)
if err != nil {
invalidLines = append(invalidLines, scanner.Text())
continue
}
rec.Time = rec.Time.Local()
current := currentTime()
if rec.Time.After(current) {
rec.Time = current
}
min := current.Add(-1 * time.Hour)
if rec.Time.Before(min) {
rec.Time = min
}
count++
r.Report(p.target, rec)
}
if invalidLines != nil {
r.Report(p.target, api.Record{
Time: stime,
Target: p.target,
Status: api.StatusUnknown,
Message: "the plugin reported invalid records",
Latency: latency,
Extra: map[string]any{
"raw_message": strings.Join(invalidLines, "\n"),
},
})
}
if err != nil || (invalidLines == nil && count == 0) {
msg := ""
if err != nil {
msg = err.Error()
}
r.Report(p.target, timeoutOr(ctx, api.Record{
Time: stime,
Target: p.target,
Status: status,
Message: msg,
Latency: latency,
}))
}
}
func (p PluginScheme) Probe(ctx context.Context, r Reporter) {
r = p.tracker.PrepareReporter(p.target, r)
p.execute(ctx, r, "probe", []string{p.target.String()})
r.DeactivateTarget(p.target, p.tracker.Inactives()...)
}
func (p PluginScheme) Alert(ctx context.Context, r Reporter, lastRecord api.Record) {
args := []string{
p.target.String(),
lastRecord.String(),
}
p.execute(
ctx,
AlertReporter{p.target, r},
"alert",
args,
)
}