-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
247 lines (220 loc) · 5.9 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
244
245
246
247
package gorpc
import (
"encoding/json"
"errors"
"go-rpc/codec"
"io"
"net"
"net/http"
"reflect"
"strings"
"sync"
"time"
"github.com/sirupsen/logrus"
)
const (
connected = "200 connected to go rpc"
defaultRPCPath = "/go_rpc"
defaultDebugPath = "/debug/go_rpc"
)
type Option struct {
MagicNumber int
CodecType codec.Type
ConnectTimeout time.Duration
HandleTimeOout time.Duration
}
const MagicNumber = 0
var DefaultOption = &Option{
MagicNumber: MagicNumber,
CodecType: codec.GobType,
ConnectTimeout: time.Second * 10,
}
type Request struct {
header *codec.Header
argValue, replyValue reflect.Value
mt *MethodType
service *service
}
type Server struct {
serviceMap sync.Map
}
var invalidRequest = struct{}{}
func NewServer() *Server {
return new(Server)
}
var DefaultServer = NewServer()
func (s *Server) Accept(listener net.Listener) {
for {
conn, err := listener.Accept()
if err != nil {
logrus.Errorf("fail to accept rpc: %v", err)
return
}
go s.handleConn(conn)
}
}
func (s *Server) handleConn(conn io.ReadWriteCloser) {
defer conn.Close()
var option Option
if err := json.NewDecoder(conn).Decode(&option); err != nil {
logrus.Errorf("fail to decode option: %v", err)
return
}
if option.MagicNumber != MagicNumber {
logrus.Errorf("invalid magic number: %v", option.MagicNumber)
return
}
if err := json.NewEncoder(conn).Encode(option); err != nil {
logrus.Error(err)
return
}
codecfunc := codec.NewCodecFuncMap[option.CodecType]
if codecfunc == nil {
logrus.Errorf("invalid codec type: %v", option.CodecType)
return
}
s.handleCodec(codecfunc(conn), &option)
}
func Accept(listener net.Listener) {
DefaultServer.Accept(listener)
}
func (s *Server) handleCodec(codec codec.Codec, option *Option) {
sending := new(sync.Mutex)
wg := new(sync.WaitGroup)
for {
request, err := s.readRequest(codec)
if err != nil {
if request == nil {
break
}
request.header.Error = err.Error()
s.sendResponse(codec, request.header, invalidRequest, sending)
continue
}
wg.Add(1)
go s.handleRequest(codec, request, sending, wg, option.HandleTimeOout)
}
wg.Wait()
}
func (s *Server) readRequestHeader(cc codec.Codec) (*codec.Header, error) {
var header codec.Header
if err := cc.ReadHeader(&header); err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
return nil, err
}
logrus.Errorf("fail to read header: %v", err)
}
return &header, nil
}
func (s *Server) readRequest(codec codec.Codec) (*Request, error) {
header, err := s.readRequestHeader(codec)
if err != nil {
return nil, err
}
r := &Request{}
r.header = header
r.service, r.mt, err = s.FindService(header.ServiceMethod)
if err != nil {
return r, err
}
r.argValue = r.mt.newArgv()
r.replyValue = r.mt.newReplyv()
argV := r.argValue.Interface()
if r.argValue.Kind() != reflect.Ptr {
argV = r.argValue.Addr().Interface()
}
if err := codec.ReadBody(argV); err != nil {
logrus.Errorf("server: read request body err: %v", err)
return r, err
}
return r, nil
}
func (s *Server) sendResponse(codec codec.Codec, header *codec.Header, body interface{}, sending *sync.Mutex) {
sending.Lock()
defer sending.Unlock()
if err := codec.Write(header, body); err != nil {
logrus.Errorf("fail to write response: %v", err)
}
}
func (s *Server) handleRequest(codec codec.Codec, request *Request, sending *sync.Mutex, wg *sync.WaitGroup, timeout time.Duration) {
defer wg.Done()
// called := make(chan struct{})
sent := make(chan struct{})
go func() {
err := request.service.Call(request.mt, request.argValue, request.replyValue)
// called <- struct{}{}
if err != nil {
request.header.Error = err.Error()
s.sendResponse(codec, request.header, invalidRequest, sending)
sent <- struct{}{}
return
}
s.sendResponse(codec, request.header, request.replyValue.Interface(), sending)
sent <- struct{}{}
}()
if timeout == 0 {
// <-called
<-sent
return
}
select {
case <-time.After(timeout):
request.header.Error = "server: handle request timeout: expected within " + timeout.String()
s.sendResponse(codec, request.header, request.replyValue.Interface(), sending)
// case <-called:
// <-sent
case <-sent:
return
}
}
func (s *Server) Register(serviceStruct interface{}) error {
service := NewService(serviceStruct)
if _, ok := s.serviceMap.LoadOrStore(service.name, service); ok {
return errors.New("service all ready registered")
}
return nil
}
func Register(serviceStruct interface{}) error {
return DefaultServer.Register(serviceStruct)
}
func (s *Server) FindService(serviceMethod string) (*service, *MethodType, error) {
dot := strings.LastIndex(serviceMethod, ".")
if dot < 0 {
return nil, nil, errors.New("service method has illegal formate" + serviceMethod)
}
serviceName := serviceMethod[:dot]
methodName := serviceMethod[dot+1:]
serviceInter, ok := s.serviceMap.Load(serviceName)
if !ok {
return nil, nil, errors.New("server: service " + serviceName + " can't be found")
}
service := serviceInter.(*service)
methodType := service.method[methodName]
if methodType == nil {
return nil, nil, errors.New("server: service method " + methodName + " can't be found")
}
return service, methodType, nil
}
func (s *Server) ServeHTTP(w http.ResponseWriter, request *http.Request) {
if request.Method != "CONNECT" {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusMethodNotAllowed)
io.WriteString(w, "405 must CONNECT\n")
return
}
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
logrus.Error("rpc hijacking ", request.RemoteAddr, ": ", err.Error())
return
}
io.WriteString(conn, "HTTP/1.0 "+connected+"\n\n")
s.handleConn(conn)
}
func (s *Server) HandleHTTP() {
http.Handle(defaultRPCPath, s)
http.Handle(defaultDebugPath, debugHTTP{s})
logrus.Info("server debug path: ", defaultDebugPath)
}
func HandleHTTP() {
DefaultServer.HandleHTTP()
}