-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
298 lines (275 loc) · 7.12 KB
/
Copy pathmain.go
File metadata and controls
298 lines (275 loc) · 7.12 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
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package main
import (
"bufio"
_ "embed"
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"sync"
"time"
)
//go:embed static/index.html
var indexHTML string
var tmpl = template.Must(template.New("page").Funcs(template.FuncMap{
"divf": func(a, b int64) float64 { return float64(a) / float64(b) },
}).Parse(indexHTML))
type Tunnel struct {
Name string `json:"name"`
Interface string `json:"interface"`
LocalIP string `json:"local_ip"`
PeerIP string `json:"peer_ip"`
Role string `json:"role"`
Status string `json:"status"`
PeerAlive bool `json:"peer_alive"`
BytesIn int64 `json:"bytes_in"`
BytesOut int64 `json:"bytes_out"`
RateIn float64 `json:"rate_in_kbps"`
RateOut float64 `json:"rate_out_kbps"`
}
type Service struct {
Name string `json:"name"`
Active bool `json:"active"`
}
type Status struct {
Hostname string `json:"hostname"`
RemoteName string `json:"remote_name"`
Timestamp string `json:"timestamp"`
Tunnels []Tunnel `json:"tunnels"`
Services []Service `json:"services"`
TotalIn int64 `json:"total_in_bytes"`
TotalOut int64 `json:"total_out_bytes"`
}
type TrafficSample struct {
BytesIn int64
BytesOut int64
Time time.Time
}
type Monitor struct {
mu sync.Mutex
status Status
prevTraffic map[string]TrafficSample
prevTunnelStatus map[string]string
lastNotify map[string]time.Time
mailTo string
}
var remoteNames = map[string]string{
"Phicomm-N1": "Panther-X2",
"Panther-X2": "Phicomm-N1",
}
func classifyTunnel(localIP string) (name, role string) {
switch {
case strings.HasPrefix(localIP, "10.99.0."):
return "S2S-主", "主"
case strings.HasPrefix(localIP, "10.99.1."):
return "S2S-备", "备"
case strings.HasPrefix(localIP, "10.9.0."), strings.HasPrefix(localIP, "10.10.0."):
return "VPN", "-"
default:
return "未知", "-"
}
}
func pingOK(addr string) bool {
return exec.Command("ping", "-c", "1", "-W", "2", addr).Run() == nil
}
func serviceActive(name string) bool {
out, err := exec.Command("systemctl", "is-active", name).Output()
return err == nil && strings.TrimSpace(string(out)) == "active"
}
func parseProcNetDev() map[string][2]int64 {
data, err := os.ReadFile("/proc/net/dev")
if err != nil {
return nil
}
r := make(map[string][2]int64)
s := bufio.NewScanner(strings.NewReader(string(data)))
for s.Scan() {
l := s.Text()
if !strings.Contains(l, ":") {
continue
}
f := strings.Fields(l)
iface := strings.TrimRight(f[0], ":")
if !strings.HasPrefix(iface, "tun") {
continue
}
in, _ := strconv.ParseInt(f[1], 10, 64)
out, _ := strconv.ParseInt(f[9], 10, 64)
r[iface] = [2]int64{in, out}
}
return r
}
func listTun() ([]string, error) {
d, err := os.ReadDir("/sys/class/net")
if err != nil {
return nil, err
}
var r []string
for _, e := range d {
if strings.HasPrefix(e.Name(), "tun") {
r = append(r, e.Name())
}
}
return r, nil
}
func tunInfo(iface string) (localIP, peerIP string, up bool) {
out, err := exec.Command("ip", "-o", "addr", "show", iface).Output()
if err != nil {
return "", "", false
}
s := string(out)
parts := strings.Split(s, "inet ")
if len(parts) < 2 {
return "", "", false
}
ff := strings.Fields(parts[1])
if len(ff) > 0 {
localIP = strings.Split(ff[0], "/")[0]
}
for i, v := range ff {
if v == "peer" && i+1 < len(ff) {
peerIP = strings.Split(ff[i+1], "/")[0]
break
}
}
out2, _ := exec.Command("ip", "link", "show", iface).Output()
up = strings.Contains(string(out2), "UP")
return
}
func (m *Monitor) collect() {
hostname, _ := os.Hostname()
remoteName := remoteNames[hostname]
if remoteName == "" {
remoteName = "远端"
}
ifaces, err := listTun()
if err != nil {
log.Printf("list tun: %v", err)
return
}
traffic := parseProcNetDev()
now := time.Now()
var tunnels []Tunnel
prev := make(map[string]TrafficSample)
var totalIn, totalOut int64
for _, iface := range ifaces {
localIP, peerIP, up := tunInfo(iface)
name, role := classifyTunnel(localIP)
t := Tunnel{
Name: name,
Interface: iface,
LocalIP: localIP,
PeerIP: peerIP,
Role: role,
Status: "down",
}
if up {
t.Status = "up"
}
if peerIP != "" && up {
t.PeerAlive = pingOK(peerIP)
}
if tr, ok := traffic[iface]; ok {
t.BytesIn = tr[0]
t.BytesOut = tr[1]
totalIn += tr[0]
totalOut += tr[1]
if p, ok := m.prevTraffic[iface]; ok {
elapsed := now.Sub(p.Time).Seconds()
if elapsed > 0 {
t.RateIn = float64(tr[0]-p.BytesIn) / elapsed / 1024
t.RateOut = float64(tr[1]-p.BytesOut) / elapsed / 1024
}
}
prev[iface] = TrafficSample{tr[0], tr[1], now}
}
tunnels = append(tunnels, t)
}
m.prevTraffic = prev
for _, t := range tunnels {
old, seen := m.prevTunnelStatus[t.Interface]
if seen && old != t.Status && t.Name != "未知" {
m.notify(t.Name, t.Interface, old, t.Status)
}
m.prevTunnelStatus[t.Interface] = t.Status
}
services := []Service{
{"openvpn-server@server", serviceActive("openvpn-server@server")},
{"openvpn-server@server-tcp", serviceActive("openvpn-server@server-tcp")},
{"openvpn-server@s2s", serviceActive("openvpn-server@s2s")},
{"openvpn-client@s2s-backup", serviceActive("openvpn-client@s2s-backup")},
}
m.mu.Lock()
m.status = Status{
Hostname: hostname,
RemoteName: remoteName,
Timestamp: now.Format("2006-01-02 15:04:05"),
Tunnels: tunnels,
Services: services,
TotalIn: totalIn,
TotalOut: totalOut,
}
m.mu.Unlock()
}
func (m *Monitor) notify(name, iface, oldStatus, newStatus string) {
if m.mailTo == "" {
return
}
if last, ok := m.lastNotify[iface]; ok && time.Since(last) < 60*time.Second {
return
}
m.lastNotify[iface] = time.Now()
hostname, _ := os.Hostname()
now := time.Now().Format("2006-01-02 15:04:05")
subject := fmt.Sprintf("[Tunnel] %s: %s→%s on %s", name, oldStatus, newStatus, hostname)
body := fmt.Sprintf("隧道: %s (%s)\n本机: %s\n旧状态: %s\n新状态: %s\n时间: %s",
name, iface, hostname, oldStatus, newStatus, now)
cmd := exec.Command("msmtp", m.mailTo)
cmd.Stdin = strings.NewReader(fmt.Sprintf("Subject: %s\n\n%s\n", subject, body))
if err := cmd.Run(); err != nil {
log.Printf("mail %s: %v", name, err)
}
}
func (m *Monitor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
m.mu.Lock()
s := m.status
m.mu.Unlock()
w.Header().Set("Access-Control-Allow-Origin", "*")
switch r.URL.Path {
case "/api/status":
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(s)
case "/":
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.Execute(w, s)
default:
http.NotFound(w, r)
}
}
func main() {
log.SetFlags(log.Lshortfile)
m := &Monitor{
prevTraffic: make(map[string]TrafficSample),
prevTunnelStatus: make(map[string]string),
lastNotify: make(map[string]time.Time),
mailTo: os.Getenv("MAIL_TO"),
}
m.collect()
go func() {
for {
time.Sleep(3 * time.Second)
m.collect()
}
}()
http.Handle("/", m)
addr := "127.0.0.1:8899"
log.Printf("listen %s", addr)
if err := http.ListenAndServe(addr, nil); err != nil {
log.Fatal(err)
}
}