-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
125 lines (107 loc) · 2.19 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package xcache
import (
"context"
"math/rand"
"net"
"go.uber.org/zap"
"xcache/protocol"
)
type ServerOptions struct {
id uint64
}
type ServerOption func(*ServerOptions)
func WithId(id uint64) ServerOption {
return func(options *ServerOptions) {
options.id = id
}
}
type Server interface {
Serve() error
ServeAsync(call func(err error))
Join(target *protocol.Node) error
Myself() *protocol.Node
NodeLen() int
Shutdown() error
Id() uint64
}
func NewServer(ctx context.Context, addr string, opts ...ServerOption) Server {
s := &server{addr: addr}
s.ctx, s.cancel = context.WithCancel(ctx)
s.id = rand.Uint64()
for _, opt := range opts {
opt(&s.ServerOptions)
}
s.router = &router{
cache: newCache(),
}
s.cluster = newCluster(s.ctx, s.id, s.addr, s.router)
s.router.cluster = s.cluster
return s
}
type server struct {
ServerOptions
ctx context.Context
cancel context.CancelFunc
addr string
cluster *cluster
listener net.Listener
router *router
}
func (s *server) Id() uint64 {
return s.id
}
func (s *server) Myself() *protocol.Node {
return s.cluster.Myself()
}
func (s *server) Serve() error {
lis, err := net.Listen("tcp", s.addr)
if err != nil {
return err
}
s.listener = lis
go s.cluster.workLoop()
if log.Level().Enabled(zap.DebugLevel) {
log.Debugf("server listen addr: %s", s.addr)
}
defer func() {
if log.Level().Enabled(zap.DebugLevel) {
log.Debugf("server shutdown addr: %s", s.addr)
}
}()
for {
select {
case <-s.ctx.Done():
return nil
default:
conn, err := lis.Accept()
if err != nil {
return err
}
if log.Level().Enabled(zap.DebugLevel) {
log.Debugf("server accept myself: %s local-addr: %s remote-addr: %s", s.addr, conn.LocalAddr(), conn.RemoteAddr())
}
c := &connection{
Conn: conn,
handler: s.router,
side: SideServer,
}
go c.serve(s.ctx)
}
}
}
func (s *server) ServeAsync(call func(err error)) {
go func() {
err := s.Serve()
call(err)
}()
}
func (s *server) Join(target *protocol.Node) error {
return s.cluster.Join(target)
}
func (s *server) NodeLen() int {
return s.cluster.Len()
}
func (s *server) Shutdown() error {
s.cancel()
return s.listener.Close()
}