forked from smallnest/rpcx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
442 lines (369 loc) · 10.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package rpcx
import (
"crypto/tls"
"io"
"log"
"net"
"net/http"
"net/rpc"
"regexp"
"strings"
"time"
"github.com/hashicorp/net-rpc-msgpackrpc"
)
const (
//DefaultRPCPath is the defaut HTTP RPC PATH
DefaultRPCPath = "/_goRPC_"
)
// ArgsContext contains net.Conn so services can get net.Conn info, for example, remote address.
type ArgsContext interface {
Value(key string) interface{}
SetValue(key string, value interface{})
}
type serverCodecWrapper struct {
rpc.ServerCodec
PluginContainer IServerPluginContainer
Conn net.Conn
Timeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
}
// newServerCodecWrapper wraps a rpc.ServerCodec.
func newServerCodecWrapper(pc IServerPluginContainer, c rpc.ServerCodec, Conn net.Conn) *serverCodecWrapper {
return &serverCodecWrapper{ServerCodec: c, PluginContainer: pc, Conn: Conn}
}
func (w *serverCodecWrapper) ReadRequestHeader(r *rpc.Request) error {
if w.Timeout > 0 {
w.Conn.SetDeadline(time.Now().Add(w.Timeout))
}
if w.ReadTimeout > 0 {
w.Conn.SetReadDeadline(time.Now().Add(w.ReadTimeout))
}
//pre
err := w.PluginContainer.DoPreReadRequestHeader(r)
if err != nil {
return err
}
err = w.ServerCodec.ReadRequestHeader(r)
if err != nil {
return err
}
//post
err = w.PluginContainer.DoPostReadRequestHeader(r)
return err
}
func (w *serverCodecWrapper) ReadRequestBody(body interface{}) error {
//pre
err := w.PluginContainer.DoPreReadRequestBody(body)
if err != nil {
return err
}
err = w.ServerCodec.ReadRequestBody(body)
if err != nil {
return err
}
if args, ok := body.(ArgsContext); ok {
args.SetValue("conn", w.Conn)
}
//post
err = w.PluginContainer.DoPostReadRequestBody(body)
return err
}
func (w *serverCodecWrapper) WriteResponse(resp *rpc.Response, body interface{}) (err error) {
if w.Timeout > 0 {
w.Conn.SetDeadline(time.Now().Add(w.Timeout))
}
if w.ReadTimeout > 0 {
w.Conn.SetWriteDeadline(time.Now().Add(w.WriteTimeout))
}
// pre
if err = w.PluginContainer.DoPreWriteResponse(resp, body); err != nil {
return
}
if err = w.ServerCodec.WriteResponse(resp, body); err != nil {
return
}
// post
return w.PluginContainer.DoPostWriteResponse(resp, body)
}
func (w *serverCodecWrapper) Close() (err error) {
//pre
err = w.ServerCodec.Close()
//post
return
}
// ServerCodecFunc is used to create a rpc.ServerCodec from net.Conn.
type ServerCodecFunc func(conn io.ReadWriteCloser) rpc.ServerCodec
// Server represents a RPC Server.
type Server struct {
ServerCodecFunc ServerCodecFunc
//PluginContainer must be configured before starting and Register plugins must be configured before invoking RegisterName method
PluginContainer IServerPluginContainer
//Metadata describes extra info about this service, for example, weight, active status
Metadata string
rpcServer *rpc.Server
listener net.Listener
Timeout time.Duration
ReadTimeout time.Duration
WriteTimeout time.Duration
}
// NewServer returns a new Server.
func NewServer() *Server {
return &Server{
rpcServer: rpc.NewServer(),
PluginContainer: &ServerPluginContainer{plugins: make([]IPlugin, 0)},
ServerCodecFunc: msgpackrpc.NewServerCodec,
}
}
// DefaultServer is the default instance of *Server.
var defaultServer = NewServer()
// Serve starts and listens RPC requests.
//It is blocked until receiving connectings from clients.
func Serve(n, address string) (err error) {
return defaultServer.Serve(n, address)
}
// ServeTLS starts and listens RPC requests.
//It is blocked until receiving connectings from clients.
func ServeTLS(n, address string, config *tls.Config) (err error) {
return defaultServer.ServeTLS(n, address, config)
}
// Start starts and listens RPC requests without blocking.
func Start(n, address string) (err error) {
return defaultServer.Start(n, address)
}
// StartTLS starts and listens RPC requests without blocking.
func StartTLS(n, address string, config *tls.Config) (err error) {
return defaultServer.StartTLS(n, address, config)
}
// ServeListener serve with a listener
func ServeListener(ln net.Listener) {
defaultServer.ServeListener(ln)
}
// ServeByHTTP implements RPC via HTTP
func ServeByHTTP(ln net.Listener) {
defaultServer.ServeByHTTP(ln, rpc.DefaultRPCPath)
}
// ServeByMux implements RPC via HTTP with customized mux
func ServeByMux(ln net.Listener, mux *http.ServeMux) {
defaultServer.ServeByMux(ln, rpc.DefaultRPCPath, mux)
}
// SetServerCodecFunc sets a ServerCodecFunc
func SetServerCodecFunc(fn ServerCodecFunc) {
defaultServer.ServerCodecFunc = fn
}
// Close closes RPC server.
func Close() error {
return defaultServer.Close()
}
//GetListenedAddress return the listening address.
func GetListenedAddress() string {
return defaultServer.Address()
}
// GetPluginContainer get PluginContainer of default server.
func GetPluginContainer() IServerPluginContainer {
return defaultServer.PluginContainer
}
// RegisterName publishes in the server the set of methods .
func RegisterName(name string, service interface{}, metadata ...string) {
defaultServer.RegisterName(name, service, metadata...)
}
// Auth sets authorization handler
func Auth(fn AuthorizationFunc) error {
p := &AuthorizationServerPlugin{AuthorizationFunc: fn}
return defaultServer.PluginContainer.Add(p)
}
func validIP4(ipAddress string) bool {
ipAddress = strings.Trim(ipAddress, " ")
i := strings.LastIndex(ipAddress, ":")
ipAddress = ipAddress[:i] //remove port
re, _ := regexp.Compile(`^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`)
if re.MatchString(ipAddress) {
return true
}
return false
}
// Serve starts and listens RPC requests.
//It is blocked until receiving connectings from clients.
func (s *Server) Serve(network, address string) (err error) {
var ln net.Listener
ln, err = makeListener(network, address)
if err != nil {
return
}
s.listener = ln
for {
c, err := ln.Accept()
if err != nil {
continue
}
var ok bool
if c, ok = s.PluginContainer.DoPostConnAccept(c); !ok {
continue
}
wrapper := newServerCodecWrapper(s.PluginContainer, s.ServerCodecFunc(c), c)
wrapper.Timeout = s.Timeout
wrapper.ReadTimeout = s.ReadTimeout
wrapper.WriteTimeout = s.WriteTimeout
go s.rpcServer.ServeCodec(wrapper)
}
}
// ServeTLS starts and listens RPC requests.
//It is blocked until receiving connectings from clients.
func (s *Server) ServeTLS(network, address string, config *tls.Config) (err error) {
ln, err := tls.Listen(network, address, config)
if err != nil {
return
}
s.listener = ln
for {
c, err := ln.Accept()
if err != nil {
continue
}
var ok bool
if c, ok = s.PluginContainer.DoPostConnAccept(c); !ok {
continue
}
wrapper := newServerCodecWrapper(s.PluginContainer, s.ServerCodecFunc(c), c)
wrapper.Timeout = s.Timeout
wrapper.ReadTimeout = s.ReadTimeout
wrapper.WriteTimeout = s.WriteTimeout
go s.rpcServer.ServeCodec(wrapper)
}
}
// ServeListener starts
func (s *Server) ServeListener(ln net.Listener) {
s.listener = ln
for {
c, err := ln.Accept()
if err != nil {
continue
}
var ok bool
if c, ok = s.PluginContainer.DoPostConnAccept(c); !ok {
continue
}
wrapper := newServerCodecWrapper(s.PluginContainer, s.ServerCodecFunc(c), c)
wrapper.Timeout = s.Timeout
wrapper.ReadTimeout = s.ReadTimeout
wrapper.WriteTimeout = s.WriteTimeout
go s.rpcServer.ServeCodec(wrapper)
}
}
// ServeByHTTP serves
func (s *Server) ServeByHTTP(ln net.Listener, rpcPath string) {
http.Handle(rpcPath, s)
srv := &http.Server{Handler: nil}
srv.Serve(ln)
}
// ServeByMux serves
func (s *Server) ServeByMux(ln net.Listener, rpcPath string, mux *http.ServeMux) {
mux.Handle(rpcPath, s)
srv := &http.Server{Handler: mux}
srv.Serve(ln)
}
var connected = "200 Connected to Go RPC"
//ServeHTTP implements net handler interface
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method != "CONNECT" {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusMethodNotAllowed)
io.WriteString(w, "405 must CONNECT\n")
return
}
c, _, err := w.(http.Hijacker).Hijack()
if err != nil {
log.Println("rpc hijacking ", req.RemoteAddr, ": ", err.Error())
return
}
io.WriteString(c, "HTTP/1.0 "+connected+"\n\n")
var ok bool
if c, ok = s.PluginContainer.DoPostConnAccept(c); !ok {
return
}
wrapper := newServerCodecWrapper(s.PluginContainer, s.ServerCodecFunc(c), c)
wrapper.Timeout = s.Timeout
wrapper.ReadTimeout = s.ReadTimeout
wrapper.WriteTimeout = s.WriteTimeout
s.rpcServer.ServeCodec(wrapper)
}
// Start starts and listens RPC requests without blocking.
func (s *Server) Start(network, address string) (err error) {
var ln net.Listener
ln, err = makeListener(network, address)
if err != nil {
return
}
s.listener = ln
go func() {
for {
c, err := ln.Accept()
if err != nil {
continue
}
var ok bool
if c, ok = s.PluginContainer.DoPostConnAccept(c); !ok {
continue
}
wrapper := newServerCodecWrapper(s.PluginContainer, s.ServerCodecFunc(c), c)
wrapper.Timeout = s.Timeout
wrapper.ReadTimeout = s.ReadTimeout
wrapper.WriteTimeout = s.WriteTimeout
go s.rpcServer.ServeCodec(wrapper)
}
}()
return
}
// StartTLS starts and listens RPC requests without blocking.
func (s *Server) StartTLS(network, address string, config *tls.Config) (err error) {
ln, err := tls.Listen(network, address, config)
if err != nil {
return
}
s.listener = ln
go func() {
for {
c, err := ln.Accept()
if err != nil {
continue
}
var ok bool
if c, ok = s.PluginContainer.DoPostConnAccept(c); !ok {
continue
}
wrapper := newServerCodecWrapper(s.PluginContainer, s.ServerCodecFunc(c), c)
wrapper.Timeout = s.Timeout
wrapper.ReadTimeout = s.ReadTimeout
wrapper.WriteTimeout = s.WriteTimeout
go s.rpcServer.ServeCodec(wrapper)
}
}()
return
}
// Close closes RPC server.
func (s *Server) Close() error {
return s.listener.Close()
}
// Address return the listening address.
func (s *Server) Address() string {
return s.listener.Addr().String()
}
// RegisterName publishes in the server the set of methods of the
// receiver value that satisfy the following conditions:
// - exported method of exported type
// - two arguments, both of exported type
// - the second argument is a pointer
// - one return value, of type error
// It returns an error if the receiver is not an exported type or has
// no suitable methods. It also logs the error using package log.
// The client accesses each method using a string of the form "Type.Method",
// where Type is the receiver's concrete type.
func (s *Server) RegisterName(name string, service interface{}, metadata ...string) {
s.rpcServer.RegisterName(name, service)
s.PluginContainer.DoRegister(name, service, metadata...)
}
//Auth sets authorization function
func (s *Server) Auth(fn AuthorizationFunc) error {
p := &AuthorizationServerPlugin{AuthorizationFunc: fn}
return s.PluginContainer.Add(p)
}