-
Notifications
You must be signed in to change notification settings - Fork 39
/
main.go
119 lines (97 loc) · 2.23 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
package main
import (
"errors"
"flag"
"fmt"
"io"
"log"
"net"
"strings"
"time"
)
var (
masterAddr *net.TCPAddr
raddr *net.TCPAddr
saddr *net.TCPAddr
localAddr = flag.String("listen", ":9999", "local address")
sentinelAddr = flag.String("sentinel", ":26379", "remote address")
masterName = flag.String("master", "", "name of the master redis node")
)
func main() {
flag.Parse()
laddr, err := net.ResolveTCPAddr("tcp", *localAddr)
if err != nil {
log.Fatal("Failed to resolve local address: %s", err)
}
saddr, err = net.ResolveTCPAddr("tcp", *sentinelAddr)
if err != nil {
log.Fatal("Failed to resolve sentinel address: %s", err)
}
go master()
listener, err := net.ListenTCP("tcp", laddr)
if err != nil {
log.Fatal(err)
}
for {
conn, err := listener.AcceptTCP()
if err != nil {
log.Println(err)
continue
}
go proxy(conn, masterAddr)
}
}
func master() {
var err error
for {
masterAddr, err = getMasterAddr(saddr, *masterName)
if err != nil {
log.Println(err)
}
time.Sleep(1 * time.Second)
}
}
func pipe(r io.Reader, w io.WriteCloser) {
io.Copy(w, r)
w.Close()
}
func proxy(local io.ReadWriteCloser, remoteAddr *net.TCPAddr) {
remote, err := net.DialTCP("tcp", nil, remoteAddr)
if err != nil {
log.Println(err)
local.Close()
return
}
go pipe(local, remote)
go pipe(remote, local)
}
func getMasterAddr(sentinelAddress *net.TCPAddr, masterName string) (*net.TCPAddr, error) {
conn, err := net.DialTCP("tcp", nil, sentinelAddress)
if err != nil {
return nil, err
}
defer conn.Close()
conn.Write([]byte(fmt.Sprintf("sentinel get-master-addr-by-name %s\n", masterName)))
b := make([]byte, 256)
_, err = conn.Read(b)
if err != nil {
log.Fatal(err)
}
parts := strings.Split(string(b), "\r\n")
if len(parts) < 5 {
err = errors.New("Couldn't get master address from sentinel")
return nil, err
}
//getting the string address for the master node
stringaddr := fmt.Sprintf("%s:%s", parts[2], parts[4])
addr, err := net.ResolveTCPAddr("tcp", stringaddr)
if err != nil {
return nil, err
}
//check that there's actually someone listening on that address
conn2, err := net.DialTCP("tcp", nil, addr)
if err == nil {
defer conn2.Close()
}
return addr, err
}