-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
339 lines (265 loc) · 7.13 KB
/
main.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
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"net"
"os/exec"
"regexp"
"runtime"
"strconv"
"strings"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
type k8s struct {
clientset kubernetes.Interface
}
func newK8s() (*k8s, error) {
config, err := rest.InClusterConfig()
if err != nil {
return nil, err
}
client := k8s{}
client.clientset, err = kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
return &client, nil
}
type Pod struct {
PodName string
PodIP string
HostName string
HostIP string
}
func (pod Pod) hash() string {
s, _ := json.Marshal(pod)
return string(s)
}
type PingRecord struct {
Timestamp string
Source Pod
Destination Pod
Message string
Elapsed_ms float64
Success bool
}
func (record *PingRecord) toString() string {
json, _ := json.Marshal(record)
return string(json)
//return fmt.Sprintf("%15s->%15s : %s", record.Source.PodIP, record.Destination.PodIP, record.Message)
}
func newPod(podName string, podIP string, hostName string, hostIP string) *Pod {
return &Pod{
PodName: podName,
PodIP: podIP,
HostName: hostName,
HostIP: hostIP,
}
}
func getUsedIPs() ([]string, error) {
ips := []string{}
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
ips = append(ips, fmt.Sprintf("%v", ip))
}
}
return ips, nil
}
func contains(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}
return false
}
func getPods(k8s *k8s, namespace string, podPrefix string) (map[string]Pod, error) {
result := make(map[string]Pod)
pods, err := k8s.clientset.CoreV1().Pods(namespace).List(metav1.ListOptions{})
if err != nil {
return nil, err
}
for _, pod := range pods.Items {
if strings.HasPrefix(strings.ToUpper(pod.GetName()), strings.ToUpper(podPrefix)) {
if pod.Status.Phase == "Running" {
pod := Pod{
PodName: pod.GetName(),
PodIP: pod.Status.PodIP,
HostName: pod.Spec.NodeName,
HostIP: pod.Status.HostIP}
result[pod.hash()] = pod
}
}
}
return result, nil
}
type Pinger struct {
Done chan struct{}
}
func (pinger *Pinger) Destroy() {
close(pinger.Done)
}
func run(cmd string, args []string) (*bufio.Scanner, error) {
fmt.Println(fmt.Sprintf("exec: %v %v", cmd, args))
command := exec.Command(cmd, args...)
commandOut, _ := command.StdoutPipe()
output_scanner := bufio.NewScanner(commandOut)
err := command.Start()
return output_scanner, err
}
func getParams(regEx, url string) (paramsMap map[string]string) {
var compRegEx = regexp.MustCompile(regEx)
match := compRegEx.FindStringSubmatch(url)
paramsMap = make(map[string]string)
for i, name := range compRegEx.SubexpNames() {
if i > 0 && i <= len(match) {
paramsMap[name] = match[i]
}
}
return
}
func newPinger(source Pod, destination Pod, intervalSec int, output chan PingRecord, run func(cmd string, arg []string) (*bufio.Scanner, error)) (*Pinger, error) {
pinger := Pinger{
Done: make(chan struct{}),
}
go func() {
args := []string{destination.PodIP, "-i", strconv.Itoa(intervalSec),"-O"}
scanner, err := run("/bin/ping", args)
if err != nil {
fmt.Println(fmt.Sprintf("pinger error %v", err))
} else {
fmt.Println(fmt.Sprintf("pinger for '%s' started", destination.PodName))
working:
for {
select {
case <-pinger.Done:
break working
default:
if scanner.Scan() {
text := scanner.Text()
if len(text) > 0 {
var elapsed float64 = 0
m := getParams(`.+\stime=(?P<elapsed>[-+]?[0-9]*\.?[0-9]*)\sms$`, text)
if _, ok := m["elapsed"]; ok {
e, err := strconv.ParseFloat(m["elapsed"], 64)
if err == nil {
elapsed = e
}
}
successMatched := strings.Contains(text,"bytes from")
record := PingRecord{
Timestamp: time.Now().Format(time.RFC3339),
Source: source,
Destination: destination,
Message: text,
Elapsed_ms: elapsed,
Success: successMatched}
output <- record
}
}
}
runtime.Gosched()
}
fmt.Println(fmt.Sprintf("pinger for '%v' finished", destination.PodName))
}
}()
return &pinger, nil
}
func newPingersPool(k8s *k8s, namespace string, podsPrefix string, output chan PingRecord, configRefreshInterval time.Duration, pingIntervalSec int, run func(cmd string, arg []string) (*bufio.Scanner, error)) {
pingers := map[string]*Pinger{}
ips, err := getUsedIPs()
if err != nil {
//time.Sleep(2 * time.Second) // do not restart pod immediately
panic(err)
}
fmt.Println(fmt.Sprintf("used ips: %v", ips))
for {
//fmt.Println(fmt.Sprintf("UsedIps:%v", strings.Join(ips,",\n")));
pods, err := getPods(k8s, namespace, podsPrefix)
if err != nil {
//time.Sleep(2 * time.Second) // do not restart pod immediately
fmt.Println(fmt.Sprintf("error: %v", err))
//panic(err)
} else {
fmt.Println(fmt.Sprintf("used pods: %v", pods))
// search current pod
for _, sourcePod := range pods {
if contains(ips, sourcePod.PodIP) {
s, _ := json.Marshal(sourcePod)
fmt.Println(fmt.Sprintf("current pod: %v", string(s)))
// add new pingers
for key, pod := range pods {
_, exist := pingers[key]
if !exist {
if !contains(ips, pod.PodIP) { // do not ping itself
pinger, _ := newPinger(sourcePod, pod, pingIntervalSec, output, run)
pingers[key] = pinger
}
}
}
// delete unused pingers
for key := range pingers {
_, exists := pods[key]
if !exists {
pingers[key].Destroy()
delete(pingers, key)
}
}
}
}
}
time.Sleep(configRefreshInterval)
}
}
func main() {
var updateConfigSecFlag *int
var pingIntervalSecFlag *int
var namespaceFlag *string
var podsPrefixFlag *string
updateConfigSecFlag = flag.Int("updateConfigIntervalSec", 30, "interval in seconds between asking cluster for ping pods configuration")
pingIntervalSecFlag = flag.Int("pingIntervalSec", 1, "equal ping -i parameter")
namespaceFlag = flag.String("namespace", "monitoring", "pods namespace")
podsPrefixFlag = flag.String("podsPrefix", "kubernetes-network-check", "pods prefix")
flag.Parse()
fmt.Println(fmt.Sprintf("updateConfigIntervalSec = %v", *updateConfigSecFlag))
fmt.Println(fmt.Sprintf("pingIntervalSec = %v", *pingIntervalSecFlag))
fmt.Println(fmt.Sprintf("namespace = %s", *namespaceFlag))
fmt.Println(fmt.Sprintf("podsPrefix = %s", *podsPrefixFlag))
k8s, err := newK8s()
if err != nil {
panic(err)
}
output := make(chan PingRecord)
go func() {
newPingersPool(k8s, *namespaceFlag, *podsPrefixFlag, output, time.Duration(*updateConfigSecFlag)*time.Second, *pingIntervalSecFlag, run)
}()
// write to output all records
for {
time.Sleep(10 * time.Millisecond)
record, ok := <-output
if !ok {
break
}
fmt.Println(record.toString())
}
}