-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
243 lines (216 loc) · 6.15 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
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package gee_rpc
import (
"encoding/json"
"errors"
"fmt"
"github.com/futhergo/gee-rpc/codec"
"io"
"log"
"net"
"net/http"
"reflect"
"strings"
"sync"
"time"
)
const MagicNumber = 0x9a7ccda
type Option struct {
MagicNumber int
CodecType codec.Type
ConnTimeOut time.Duration
HandleTimeOut time.Duration
}
var DefaultOption = &Option{
MagicNumber: MagicNumber,
CodecType: codec.GobType,
ConnTimeOut: 10 * time.Second,
}
type Server struct {
serviceMap sync.Map
}
func NewServer() *Server {
return &Server{}
}
var DefaultServer = NewServer()
func Accept(l net.Listener) {
DefaultServer.Accept(l)
}
func Register(rcsv interface{}) error {
return DefaultServer.Register(rcsv)
}
func (s *Server) Accept(l net.Listener) {
// 传入listener
for {
conn, err := l.Accept() // 建立tcp connect
if err != nil {
log.Printf("connect accept failed %v", err)
continue
}
go s.ServeConn(conn) // 开启协程处理connect
}
}
func (s *Server) Register(rcsv interface{}) error {
svc := newService(rcsv)
if _, dup := s.serviceMap.LoadOrStore(svc.Name, svc); dup {
log.Fatalf("duplicate register service of %v", rcsv)
return errors.New(fmt.Sprintf("duplicate register service of %v", rcsv))
}
return nil
}
func (s *Server) findService(serviceMethod string) (*service, *methodType, error) {
dotIdx := strings.Index(serviceMethod, ".")
if dotIdx < 0 {
return nil, nil, errors.New("error format of call service Method")
}
serviceName, methodName := serviceMethod[:dotIdx], serviceMethod[dotIdx+1:]
svci, ok := s.serviceMap.Load(serviceName)
if !ok {
return nil, nil, errors.New(fmt.Sprintf("non register service of %s", serviceName))
}
svc := svci.(*service)
mType, ok := svc.method[methodName]
if !ok {
return nil, nil, errors.New(fmt.Sprintf("%s not found Method %s", serviceName, methodName))
}
return svc, mType, nil
}
func (s *Server) ServeConn(conn io.ReadWriteCloser) {
defer func() {
_ = conn.Close()
}()
var opt Option
if err := json.NewDecoder(conn).Decode(&opt); err != nil { // 解析option,
log.Printf("decode option failed: %v", err)
return
}
if opt.MagicNumber != MagicNumber { // 判断MagicNumber
log.Printf("option magic number error %d", opt.MagicNumber)
return
}
f := codec.NewCodecFuncMap[opt.CodecType] // 获取对应codecType的func
if f == nil {
log.Printf("null register codec func of %v", opt.CodecType)
return
}
// 用conn初始化对应的编解码器Codec
// 开始处理Codec
s.serveCodec(f(conn))
}
var invalidRequest = struct{}{}
func (s *Server) serveCodec(cc codec.Codec) {
mu := &sync.Mutex{} // 并发锁,多个handleRequest的goroutine同时间只允许一个在sendResponse,即向tcp连接写response
wg := &sync.WaitGroup{} // waitGroup,等待所有的handleRequest处理完成
for {
req, err := s.readRequest(cc) // 尝试从tcp中读取request并反序列化
if err != nil {
if req == nil {
break
}
req.h.Err = err.Error()
s.sendResponse(cc, req.h, invalidRequest, mu)
continue
}
wg.Add(1)
go s.handleRequest(cc, req, mu, wg, time.Second * 10) // 处理request,传入并发锁控制多个request并发写response;waitGroup,通知关闭编解码器cc.Close()
}
wg.Wait()
_ = cc.Close()
}
type request struct {
h *codec.Header
argv, replyv reflect.Value
svc *service
mType *methodType
}
func (s *Server) readRequest(cc codec.Codec) (*request, error) {
h, err := s.readRequestHeader(cc) // 从tcp连接中读取header并反序列化
if err != nil { // 如果失败,返回request为空,代表无法读取到header
return nil, err
}
req := &request{
h: h,
}
req.svc, req.mType, err = s.findService(h.ServiceMethod)
if err != nil {
return req, err
}
req.argv, req.replyv = req.mType.newArgv(), req.mType.newReplyv()
argvi := req.argv.Interface()
if req.argv.Type().Kind() != reflect.Ptr {
argvi = req.argv.Addr().Interface()
}
if err = cc.ReadBody(argvi); err != nil { // 解析参数, 失败尝试也返回request
log.Printf("read request argv failed %v", err)
}
return req, nil
}
func (s *Server) readRequestHeader(cc codec.Codec) (*codec.Header, error) {
var ch codec.Header
if err := cc.ReadHeader(&ch); err != nil { // 读取header,用gob.decode
return nil, err
}
return &ch, nil
}
func (s *Server) handleRequest(cc codec.Codec, r *request, mu *sync.Mutex, wg *sync.WaitGroup, timeOut time.Duration) {
defer wg.Done() // 通知当前request处理完成
called := make(chan struct{}) // 函数调用完成 -> 控制调用超时
sent := make(chan struct{}) // response发送完成 -> 函数返回
go func() {
err := r.svc.call(r.mType, r.argv, r.replyv)
called <- struct{}{}
if err != nil {
r.h.Err = err.Error()
s.sendResponse(cc, r.h, invalidRequest, mu)
sent <- struct{}{}
return
}
s.sendResponse(cc, r.h, r.replyv.Interface(), mu) // 写入连接
sent <- struct{}{}
}()
if timeOut == 0 {
<-called
<-sent
return
}
select {
case <-time.After(timeOut):
r.h.Err = fmt.Sprintf("rpc server: request handle timeout: expect within %s", timeOut)
s.sendResponse(cc, r.h, invalidRequest, mu)
case <-called:
<-sent
}
}
func (s *Server) sendResponse(cc codec.Codec, h *codec.Header, body interface{}, mu *sync.Mutex) {
mu.Lock() // 互斥处理
defer mu.Unlock()
if err := cc.Write(h, body); err != nil { // 用gob.encode序列化header和body,然后写入
log.Printf("write response body failed %v", err)
}
}
const (
connected = "200 connected to gee rpc"
defaultRPCPath = "/_geerpc/"
defaultDebugPath = "/debug/geerpc"
)
func (s *Server)ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "CONNECT" {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusMethodNotAllowed)
_, _ = io.WriteString(w, "Method must be CONNECT")
return
}
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
log.Print("rpc hijacking ", r.RemoteAddr, ": ", err.Error())
return
}
_, _ = io.WriteString(conn, "HTTP/1.0 " + connected + "\n\n")
s.ServeConn(conn)
}
func (s *Server)HandleHTTP() {
http.Handle(defaultRPCPath, s)
http.Handle(defaultDebugPath, debugHTTP{s})
}
func HandleHTTP() {
DefaultServer.HandleHTTP()
}