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
| type Config struct {
Addr string
IdleTimeout time.Duration
MaxConnections int
ReadTimeout time.Duration
WriteTimeout time.Duration
}
type Server struct {
cfg *Config
db *database.FincasDB
handler *handler.Handler
eventLoop netpoll.EventLoop
conns sync.Map
connWg sync.WaitGroup
stats *Stats
ctx context.Context
cancel context.CancelFunc
closed bool
closeMu sync.RWMutex
metricsTicker *time.Ticker
metricsCancel context.CancelFunc
node *node.Node
}
func New(db *database.FincasDB, address *string) (*Server, error) {
var (
addr = ":8911"
idleTimeout = 5 * time.Second
maxConnections = 1000
readTimeout = 10 * time.Second
writeTimeout = 10 * time.Second
)
// 省略配置获取部分
cfg := &Config{
Addr: addr,
IdleTimeout: idleTimeout,
MaxConnections: maxConnections,
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
}
ctx, cancel := context.WithCancel(context.Background())
s := &Server{
cfg: cfg,
db: db,
handler: handler.New(db),
stats: &Stats{StartTime: time.Now()},
ctx: ctx,
cancel: cancel,
}
eventLoop, err := netpoll.NewEventLoop(
func(ctx context.Context, conn netpoll.Connection) error {
return s.handleConnection(ctx, conn)
},
netpoll.WithOnPrepare(func(connection netpoll.Connection) context.Context {
return context.Background()
}),
netpoll.WithIdleTimeout(idleTimeout),
netpoll.WithReadTimeout(readTimeout),
netpoll.WithWriteTimeout(writeTimeout),
)
if err != nil {
return nil, fmt.Errorf("failed to create netpoll eventLoop: %v", err)
}
s.eventLoop = eventLoop
return s, nil
}
func (s *Server) Start() error {
s.closeMu.Lock()
if s.closed {
s.closeMu.Unlock()
return fmt.Errorf("server is already closed")
}
s.closeMu.Unlock()
s.startMetricsCollection()
listener, err := netpoll.CreateListener("tcp", s.cfg.Addr)
if err != nil {
return fmt.Errorf("failed to create listener: %v", err)
}
log.Printf("listening on %s", s.cfg.Addr)
if err := s.eventLoop.Serve(listener); err != nil {
return fmt.Errorf("failed to start eventLoop: %v", err)
}
return nil
}
func (s *Server) Stop() error {
s.closeMu.Lock()
if s.closed {
s.closeMu.Unlock()
return fmt.Errorf("server already closed")
}
s.closed = true
s.closeMu.Unlock()
s.cancel()
if s.metricsCancel != nil {
s.metricsCancel()
}
if s.node != nil {
if err := s.node.Shutdown(); err != nil {
log.Printf("failed to shutdown node: %v", err)
}
}
s.conns.Range(func(key, value interface{}) bool {
if c, ok := value.(conn.Connection); ok {
c.Close()
}
return true
})
s.connWg.Wait()
return s.eventLoop.Shutdown(context.Background())
}
func (s *Server) handleConnection(ctx context.Context, c netpoll.Connection) error {
if atomic.LoadInt64(&s.stats.ConnCount) >= int64(s.cfg.MaxConnections) {
c.Close()
return fmt.Errorf("max connections reached")
}
connection := conn.New(c)
s.conns.Store(c, connection)
s.connWg.Add(1)
defer func() {
connection.Close()
s.conns.Delete(c)
s.connWg.Done()
}()
for {
select {
case <-ctx.Done():
return nil
default:
start := time.Now()
cmd, err := connection.ReadCommand()
if err != nil {
if errors.Is(err, netpoll.ErrConnClosed) {
return nil
}
log.Printf("failed to read command: %v", err)
continue
}
// 处理 cluster 命令
if strings.ToUpper(cmd.Name) == "CLUSTER" {
if err := s.handleClusterCommand(connection, cmd); err != nil {
log.Printf("failed to handle cluster command: %v", err)
}
continue
}
// 禁止非Leader节点处理写操作
cmdP, ok := isWriteCommand(cmd.Name)
if ok && s.node != nil && !s.node.IsLeader() {
leaderAddr := s.node
return connection.WriteError(fmt.Errorf("redirect to leader: %s", leaderAddr))
}
if err := s.handler.Handle(connection, cmd); err != nil {
s.stats.IncrErrorCount()
log.Printf("failed to handle command: %v", err)
} else if s.node != nil {
err := s.node.Apply(command.New(cmdP.CmdType, cmdP.Method, cmd.Args))
if err != nil {
return fmt.Errorf("failed to apply command: %v", err)
}
}
}
}
}
func (s *Server) initCluster(conf *node.Config) error {
n, err := node.New(s.db, conf)
if err != nil { ... }
s.node = n
return nil
}
// 以下方法用于判断是否为写命令以及和 Cluster Handler 相对应
type cmdPair struct {
CmdType command.CmdTyp
Method command.MethodTyp
}
func isWriteCommand(cmd string) (cmdPair, bool) {
wCmds := map[string]cmdPair{
"SET": {command.CmdString, command.MethodSet}, "DEL": {command.CmdString, command.MethodDel}, "INCR": {command.CmdString, command.MethodIncr}, "INCRBY": {command.CmdString, command.MethodIncrBy},
"DECR": {command.CmdString, command.MethodDecr}, "DECRBY": {command.CmdString, command.MethodDecrBy}, "APPEND": {command.CmdString, command.MethodAppend}, "GETSET": {command.CmdString, command.MethodGetSet},
"SETNX": {command.CmdString, command.MethodSetNX}, "MSET": {command.CmdString, command.MethodMSet},
"HSET": {command.CmdHash, command.MethodHSet}, "HMSET": {command.CmdHash, command.MethodHMSet}, "HDEL": {command.CmdHash, command.MethodHDel}, "HINCRBY": {command.CmdHash, command.MethodHIncrBy},
"HINCRBYFLOAT": {command.CmdHash, command.MethodHIncrByFloat}, "HSETNX": {command.CmdHash, command.MethodHSetNX},
"LPUSH": {command.CmdList, command.MethodLPush}, "RPUSH": {command.CmdList, command.MethodRPush}, "LPOP": {command.CmdList, command.MethodLPop}, "RPOP": {command.CmdList, command.MethodRPop},
"LTRIM": {command.CmdList, command.MethodLTrim}, "LINSERT": {command.CmdList, command.MethodLInsert},
"SADD": {command.CmdSet, command.MethodSAdd}, "SREM": {command.CmdSet, command.MethodSRem}, "SPOP": {command.CmdSet, command.MethodSPop}, "SMOVE": {command.CmdSet, command.MethodSMove},
"ZADD": {command.CmdZSet, command.MethodZAdd}, "ZREM": {command.CmdZSet, command.MethodZRem}, "ZINCRBY": {command.CmdZSet, command.MethodZIncrBy},
"ZREMRANGEBYRANK": {command.CmdZSet, command.MethodZRemRangeByRank}, "ZREMRANGEBYSCORE": {command.CmdZSet, command.MethodZRemRangeByScore},
}
val, ok := wCmds[strings.ToUpper(cmd)]
return val, ok
}
|