This repository has been archived by the owner on Dec 9, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
monitor_widget.go
122 lines (100 loc) · 2.38 KB
/
monitor_widget.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
package internal
import (
"fmt"
"net/http"
"net/url"
goping "github.com/go-ping/ping"
"github.com/pkg/errors"
)
const (
boxPing = "mon.box_ping"
boxAvailability = "mon.box_availability"
)
type monitorWidget struct {
tui *Tui
address string
}
// NewMonitorWidget with the address of the website to monitor.
func NewMonitorWidget(address string) (*monitorWidget, error) {
return &monitorWidget{
address: address,
}, nil
}
// CreateWidgets for the monitor service.
func (m *monitorWidget) CreateWidgets(widget Widget, tui *Tui) (f func() error, err error) {
m.tui = tui
switch widget.Name {
case boxPing:
f, err = m.pingWidget(widget)
case boxAvailability:
f, err = m.availabilityWidget(widget)
default:
return nil, errors.New("can't find the widget " + widget.Name)
}
return
}
func (m *monitorWidget) pingWidget(widget Widget) (f func() error, err error) {
u := m.address
if _, ok := widget.Options[optionAddress]; ok {
u = widget.Options[optionAddress]
}
URL, err := url.Parse(u)
if err != nil {
return nil, err
}
pinger, err := goping.NewPinger(URL.Host)
if err != nil {
return nil, err
}
pinger.Count = 1
pinger.Run() // blocks until finished
stats := pinger.Statistics() // get send/receive/rtt stats
title := " Availability "
if _, ok := widget.Options[optionTitle]; ok {
title = widget.Options[optionTitle]
}
f = func() error {
return m.tui.AddTextBox(
fmt.Sprintf("Sent: %d / Received: %d / Time: %d", stats.PacketsSent, stats.PacketsRecv, stats.AvgRtt),
title,
widget.Options,
)
}
return
}
func (m *monitorWidget) availabilityWidget(widget Widget) (f func() error, err error) {
u := m.address
if _, ok := widget.Options[optionAddress]; ok {
u = widget.Options[optionAddress]
}
req, err := http.NewRequest(http.MethodGet, u, nil)
if err != nil {
return nil, err
}
client := &http.Client{}
res, err := client.Do(req)
status := "online"
statusCode := http.StatusOK
if err != nil || statusCode != res.StatusCode {
if res == nil {
statusCode = 0
} else {
statusCode = res.StatusCode
}
status = "offline"
} else {
defer res.Body.Close()
}
title := " Availability "
if _, ok := widget.Options[optionTitle]; ok {
title = widget.Options[optionTitle]
}
f = func() error {
return m.tui.AddTextBox(
fmt.Sprintf("%s (%d)", status, statusCode),
title,
widget.Options,
)
}
return
}