-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
95 lines (73 loc) · 2.08 KB
/
main.go
File metadata and controls
95 lines (73 loc) · 2.08 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
package ping
import (
"context"
"fmt"
"github.com/go-ping/ping"
"github.com/scorify/schema"
)
type Schema struct {
// Target is the address to ping
Target string `key:"target"`
// Count is the number of ping requests to send
// Default is 1
Count int `key:"count" default:"1"`
// SuccessfulCount is the number of successful ping requests required
// Default is 1
// SuccessfulCount must be less than or equal to Count and greater than 0
SuccessfulCount int `key:"successful_count" default:"1"`
}
func Validate(config string) error {
conf := Schema{}
err := schema.Unmarshal([]byte(config), &conf)
if err != nil {
return err
}
if conf.Count < 1 || conf.Count > 10 {
return fmt.Errorf("invalid count; count must be between 1 and 10; count: %d", conf.Count)
}
if conf.SuccessfulCount < 1 || conf.SuccessfulCount > conf.Count {
return fmt.Errorf("invalid successful_count; successful_count must be between 1 and count; successful_count: %d, count: %d", conf.SuccessfulCount, conf.Count)
}
return nil
}
func Run(ctx context.Context, config string) error {
conf := Schema{}
err := schema.Unmarshal([]byte(config), &conf)
if err != nil {
return err
}
// create pinger
pinger, err := ping.NewPinger(conf.Target)
if err != nil {
return fmt.Errorf("failed to create pinger; err: %s", err)
}
pinger.Count = conf.Count
doneChan := make(chan error, 1)
// run ping
go func() {
defer close(doneChan)
doneChan <- pinger.Run()
}()
// handle ping output
select {
case err := <-doneChan:
if err != nil {
// error occurred during ping
return err
}
stats := pinger.Statistics()
if stats.PacketsRecv < conf.SuccessfulCount {
return fmt.Errorf("ping failed; received %d packets, expected at least %d", stats.PacketsRecv, conf.SuccessfulCount)
}
// ping successful
return nil
case <-ctx.Done():
pinger.Stop()
stats := pinger.Statistics()
if stats.PacketsRecv < conf.SuccessfulCount {
return fmt.Errorf("ping failed; received %d packets, expected at least %d", stats.PacketsRecv, conf.SuccessfulCount)
}
// ping successful
return nil
}
}