-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolver.go
84 lines (75 loc) · 1.5 KB
/
resolver.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
package toxy
import (
"fmt"
"log"
"net"
"sync"
"time"
)
type ResolverService struct {
Port int
Hostname string
Name string
State string
}
type Resolver struct {
Services []*ResolverService
Quit chan int
sync sync.Mutex
interval int
}
func ServiceResolver(config Config) *Resolver {
r := &Resolver{
Services: []*ResolverService{},
Quit: make(chan int, 1),
interval: config.ResolveInterval,
}
for _, serv := range config.Server {
for _, v := range serv {
r.Services = append(r.Services, &ResolverService{
Port: v.Port,
Hostname: v.Hostname,
Name: v.Name,
State: ServiceUnknown,
})
}
}
return r
}
func (r *Resolver) Resolve() {
ticker := time.NewTicker(time.Duration(r.interval) * time.Second)
for _, v := range r.Services {
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", v.Hostname, v.Port))
if err != nil {
log.Printf("Error dialing service %s -> %v", v.Name, err)
v.State = ServiceDown
continue
}
v.State = ServiceUp
conn.Close()
}
for {
select {
case <-ticker.C:
r.sync.Lock()
for _, v := range r.Services {
conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", v.Hostname, v.Port))
if err != nil {
log.Printf("Error dialing service %s -> %v", v.Name, err)
v.State = ServiceDown
continue
}
v.State = ServiceUp
conn.Close()
}
r.sync.Unlock()
case <-r.Quit:
ticker.Stop()
r.sync.Unlock()
return
}
}
}
func (r *Resolver) StopResolver() {
r.Quit <- 1
}