forked from siddontang/mixer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
105 lines (78 loc) · 1.59 KB
/
server.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
package proxy
import (
"github.com/siddontang/go-log/log"
"github.com/siddontang/mixer/config"
"net"
"runtime"
"strings"
)
type Server struct {
cfg *config.Config
addr string
user string
password string
running bool
listener net.Listener
nodes map[string]*Node
schemas map[string]*Schema
}
func NewServer(cfg *config.Config) (*Server, error) {
s := new(Server)
s.cfg = cfg
s.addr = cfg.Addr
s.user = cfg.User
s.password = cfg.Password
if err := s.parseNodes(); err != nil {
return nil, err
}
if err := s.parseSchemas(); err != nil {
return nil, err
}
var err error
netProto := "tcp"
if strings.Contains(netProto, "/") {
netProto = "unix"
}
s.listener, err = net.Listen(netProto, s.addr)
if err != nil {
return nil, err
}
log.Info("Server run MySql Protocol Listen(%s) at [%s]", netProto, s.addr)
return s, nil
}
func (s *Server) Run() error {
s.running = true
for s.running {
conn, err := s.listener.Accept()
if err != nil {
log.Error("accept error %s", err.Error())
continue
}
go s.onConn(conn)
}
return nil
}
func (s *Server) Close() {
s.running = false
if s.listener != nil {
s.listener.Close()
}
}
func (s *Server) onConn(c net.Conn) {
conn := s.newConn(c)
defer func() {
if err := recover(); err != nil {
const size = 4096
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
log.Error("onConn panic %v: %v\n%s", c.RemoteAddr().String(), err, buf)
}
conn.Close()
}()
if err := conn.Handshake(); err != nil {
log.Error("handshake error %s", err.Error())
c.Close()
return
}
conn.Run()
}