-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
901 lines (789 loc) · 27.1 KB
/
server.go
File metadata and controls
901 lines (789 loc) · 27.1 KB
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Package rrpc is a fork of standard library net/rpc, which has been frozen. While
original net/rpc API and major implementation are untouched, rrpc adds some rework
and enhancements listed below. User code could stay the same and use new features.
However because of change to message Header, it cannot interoperate with net/rpc,
thus uses a new name.
net/rpc original doc:
It provides access to the exported methods of an object across a
network or other I/O connection. A server registers an object, making it visible
as a service with the name of the type of the object. After registration, exported
methods of the object will be accessible remotely. A server may register multiple
objects (services) of different types but it is an error to register multiple
objects of the same type.
Only methods that satisfy these criteria will be made available for remote access;
other methods will be ignored:
- the method's type is exported.
- the method is exported.
- the method has two arguments, both exported (or builtin) types.
- the method's second argument is a pointer.
- the method has return type error.
In effect, the method must look schematically like
func (t *T) MethodName(argType T1, replyType *T2) error
where T1 and T2 can be marshaled by encoding/gob.
These requirements apply even if a different codec is used.
(In the future, these requirements may soften for custom codecs.)
The method's first argument represents the arguments provided by the caller; the
second argument represents the result parameters to be returned to the caller.
The method's return value, if non-nil, is passed back as a string that the client
sees as if created by errors.New. If an error is returned, the reply parameter
will not be sent back to the client.
The server may handle requests on a single connection by calling ServeConn. More
typically it will create a network listener and call Accept or, for an HTTP
listener, HandleHTTP and http.Serve.
A client wishing to use the service establishes a connection and then invokes
NewClient on the connection. The convenience function Dial (DialHTTP) performs
both steps for a raw network connection (an HTTP connection). The resulting
Client object has two methods, Call and Go, that specify the service and method to
call, a pointer containing the arguments, and a pointer to receive the result
parameters.
The Call method waits for the remote call to complete while the Go method
launches the call asynchronously and signals completion using the Call
structure's Done channel.
Unless an explicit codec is set up, package encoding/gob is used to
transport the data.
Here is a simple example. A server wishes to export an object of type Arith:
package server
import "errors"
type Args struct {
A, B int
}
type Quotient struct {
Quo, Rem int
}
type Arith int
func (t *Arith) Multiply(args *Args, reply *int) error {
*reply = args.A * args.B
return nil
}
func (t *Arith) Divide(args *Args, quo *Quotient) error {
if args.B == 0 {
return errors.New("divide by zero")
}
quo.Quo = args.A / args.B
quo.Rem = args.A % args.B
return nil
}
The server calls (for HTTP service):
arith := new(Arith)
rrpc.Register(arith)
rrpc.HandleHTTP()
l, e := net.Listen("tcp", ":1234")
if e != nil {
log.Fatal("listen error:", e)
}
go http.Serve(l, nil)
At this point, clients can see a service "Arith" with methods "Arith.Multiply" and
"Arith.Divide". To invoke one, a client first dials the server:
client, err := rrpc.DialHTTP("tcp", serverAddress + ":1234")
if err != nil {
log.Fatal("dialing:", err)
}
Then it can make a remote call:
// Synchronous call
args := &server.Args{7,8}
var reply int
err = client.Call("Arith.Multiply", args, &reply)
if err != nil {
log.Fatal("arith error:", err)
}
fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply)
or
// Asynchronous call
quotient := new(Quotient)
divCall := client.Go("Arith.Divide", args, quotient, nil)
replyCall := <-divCall.Done // will be equal to divCall
// check errors, print, etc.
A server implementation will often provide a simple, type-safe wrapper for the
client.
rrpc changes:
rrpc adds support for RPC call timeout and cancelation through context.
The service object could expose methods with context.Context as 1st argument, and
can check for timeout/cancelation signal:
func (t *Arith) AddWithContext(ctx context.Context, args Args, reply *Reply)
error {
reply.C = args.A + args.B
select {
case <-ctx.Done():
err = ctx.Err()
return err
...
}
Clients can invoke it using CallWithContext and GoWithContext with a Context object:
client.GoWithContext("Arith.AddWithContext", context, args, reply, nil)
client.CallWithContext("Arith.AddWithContext", context, args, reply)
Clients can create a Context object with Timeout or Deadline and pass it to above
methods, or invoke context's cancel() function to ask service methods stop and return
early. Cancelation and Deadline are propogated from Clients to Service methods,
but not context values.
rrpc allows you use different encoder/decoder for default connection setup process
(Dial, DialHTTP, Accept, HandleHTTP) by setting NewDefaultCodec function. The
default is Gob encoder/decoder (NewGobCodec), a JSON based NewJsonCodec is provided.
rrpc also supports bidirectional rpc over the same connection (DialBiDirection,
AcceptBiDirection, ConnectBiDirectionCodec), where there are servers active at
both ends of connection and serving clients at other end.
*/
package rrpc
import (
"context"
"errors"
"fmt"
"go/token"
"io"
"log"
"net"
"net/http"
"reflect"
"strings"
"sync"
"time"
)
const (
// Defaults used by HandleHTTP
DefaultRPCPath = "/_goRPC_"
DefaultDebugPath = "/debug/rpc"
)
// Precompute the reflect type for error. Can't use error directly
// because Typeof takes an empty interface value. This is annoying.
var typeOfError = reflect.TypeOf((*error)(nil)).Elem()
type MethodKind byte
const (
Method MethodKind = iota
MethodWithContext
NumMethodKind
)
var mKindNames = []string{"Method", "MethodWithContext", "Undefined"}
func (k MethodKind) String() string {
return mKindNames[k]
}
type methodType struct {
sync.Mutex // protects counters
methodKind MethodKind
method reflect.Method
ArgType reflect.Type
ReplyType reflect.Type
numCalls uint
}
type service struct {
name string // name of service
rcvr reflect.Value // receiver of methods for the service
typ reflect.Type // type of the receiver
method map[string]*methodType // registered methods
}
// Server represents an RPC Server.
type Server struct {
serviceMap sync.Map // map[string]*service
headerLock sync.Mutex // protects freeHeaders
freeHeaders *Header
doneCh chan struct{}
connLock sync.Mutex
closing bool
actCodecs map[*connDriver]struct{}
}
// NewServer returns a new Server.
func NewServer() *Server {
return &Server{
doneCh: make(chan struct{}),
actCodecs: make(map[*connDriver]struct{}),
}
}
// DefaultServer is the default instance of *Server.
var DefaultServer = NewServer()
// NewDefaultCodec is used to create codec used in default connection set up:
// Dial, DialHTTP, Accept, HandleHTTP,...
var NewDefaultCodec CodecMaker = NewGobCodec
// Close shutdown server
func (s *Server) Close() {
s.connLock.Lock()
s.closing = true
num := len(s.actCodecs)
for cd, _ := range s.actCodecs {
cd.Close()
}
s.connLock.Unlock()
for i := 0; i < num; i++ {
<-s.doneCh
}
}
func (s *Server) connShutdown(cd *connDriver) {
// Wait for all active call to finish before closing codec.
cd.wg.Wait()
cd.Close()
s.connLock.Lock()
closing := s.closing
delete(s.actCodecs, cd)
s.connLock.Unlock()
if closing {
//synchronize server closing
s.doneCh <- struct{}{}
}
}
// Is this type exported or a builtin?
func isExportedOrBuiltinType(t reflect.Type) bool {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
// PkgPath will be non-empty even for an exported type,
// so we need to check the type name as well.
return token.IsExported(t.Name()) || t.PkgPath() == ""
}
// Register 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 (server *Server) Register(rcvr interface{}) error {
return server.register(rcvr, "", false)
}
// RegisterName is like Register but uses the provided name for the type
// instead of the receiver's concrete type.
func (server *Server) RegisterName(name string, rcvr interface{}) error {
return server.register(rcvr, name, true)
}
func (server *Server) register(rcvr interface{}, name string, useName bool) error {
s := new(service)
s.typ = reflect.TypeOf(rcvr)
s.rcvr = reflect.ValueOf(rcvr)
sname := reflect.Indirect(s.rcvr).Type().Name()
if useName {
sname = name
}
if sname == "" {
s := "rpc.Register: no service name for type " + s.typ.String()
log.Print(s)
return errors.New(s)
}
if !token.IsExported(sname) && !useName {
s := "rpc.Register: type " + sname + " is not exported"
log.Print(s)
return errors.New(s)
}
s.name = sname
// Install the methods
s.method = suitableMethods(s.typ, true)
if len(s.method) == 0 {
str := ""
// To help the user, see if a pointer receiver would work.
method := suitableMethods(reflect.PtrTo(s.typ), false)
if len(method) != 0 {
str = "rpc.Register: type " + sname + " has no exported methods of suitable type (hint: pass a pointer to value of that type)"
} else {
str = "rpc.Register: type " + sname + " has no exported methods of suitable type"
}
log.Print(str)
return errors.New(str)
}
if _, dup := server.serviceMap.LoadOrStore(sname, s); dup {
return errors.New("rpc: service already defined: " + sname)
}
return nil
}
// suitableMethods returns suitable Rpc methods of typ, it will report
// error using log if reportErr is true.
func suitableMethods(typ reflect.Type, reportErr bool) map[string]*methodType {
methods := make(map[string]*methodType)
for m := 0; m < typ.NumMethod(); m++ {
method := typ.Method(m)
mtype := method.Type
mname := method.Name
// Method must be exported.
if method.PkgPath != "" {
continue
}
// Two kinds of methods:
// normal method needs three ins: receiver, *args, *reply.
// method with context has four ins: receiver, context, *args, *reply
var mKind MethodKind = Method
switch {
case mtype.NumIn() == 3:
mKind = Method
case mtype.NumIn() == 4:
mKind = MethodWithContext
default:
if reportErr {
log.Printf("rpc.Register: method %q has %d input parameters; needs exactly three or four\n", mname, mtype.NumIn())
}
continue
}
nextArg := 1
if mKind == MethodWithContext {
arg1Type := mtype.In(nextArg)
if arg1Type.Name() != "Context" || arg1Type.PkgPath() != "context" {
if reportErr {
log.Printf("rpc.Register: first argument type of method with context %q is not context.Context: %q\n", mname, arg1Type)
}
continue
}
nextArg++
}
// Request arg need not be a pointer.
argType := mtype.In(nextArg)
if !isExportedOrBuiltinType(argType) {
if reportErr {
log.Printf("rpc.Register: argument type of method %q is not exported: %q\n", mname, argType)
}
continue
}
// Reply arg must be a pointer.
nextArg++
replyType := mtype.In(nextArg)
if replyType.Kind() != reflect.Ptr {
if reportErr {
log.Printf("rpc.Register: reply type of method %q is not a pointer: %q\n", mname, replyType)
}
continue
}
// Reply type must be exported.
if !isExportedOrBuiltinType(replyType) {
if reportErr {
log.Printf("rpc.Register: reply type of method %q is not exported: %q\n", mname, replyType)
}
continue
}
// Method needs one out.
if mtype.NumOut() != 1 {
if reportErr {
log.Printf("rpc.Register: method %q has %d output parameters; needs exactly one\n", mname, mtype.NumOut())
}
continue
}
// The return type of the method must be error.
if returnType := mtype.Out(0); returnType != typeOfError {
if reportErr {
log.Printf("rpc.Register: return type of method %q is %q, must be error\n", mname, returnType)
}
continue
}
methods[mname] = &methodType{methodKind: mKind, method: method, ArgType: argType, ReplyType: replyType}
}
return methods
}
// A value sent as a placeholder for the server's response value when the server
// receives an invalid request. It is never decoded by the client since the Response
// contains an error when it is used.
var invalidRequest = struct{}{}
func (server *Server) sendResponse(conndrv *connDriver, req *Header, reply interface{}, errmsg string) {
resp := server.getHeader()
// Encode the response header
resp.ServiceMethod = req.ServiceMethod
resp.Seq = req.Seq
resp.Kind = Response
if errmsg != "" {
resp.Kind = Error
resp.Info = errmsg
reply = invalidRequest
}
conndrv.wlock.Lock()
err := conndrv.codec.WriteHeaderBody(resp, reply)
conndrv.wlock.Unlock()
if debugLog {
if err != nil {
log.Println("rpc: fail writing response:", err)
} else {
log.Printf("%p srv send: %s\n", server, resp)
}
}
server.freeHeader(resp)
}
func (m *methodType) NumCalls() (n uint) {
m.Lock()
n = m.numCalls
m.Unlock()
return n
}
func (s *service) call(server *Server, conndrv *connDriver, mtype *methodType, req *Header, argv, replyv reflect.Value) {
defer conndrv.wg.Done()
mtype.Lock()
mtype.numCalls++
mtype.Unlock()
function := mtype.method.Func
var returnValues []reflect.Value
// Invoke the method, providing a new value for the reply.
if mtype.methodKind == MethodWithContext {
ctxVal := reflect.ValueOf(req.Info)
returnValues = function.Call([]reflect.Value{s.rcvr, ctxVal, argv, replyv})
} else /*if mtype.methodKind==Method*/ {
returnValues = function.Call([]reflect.Value{s.rcvr, argv, replyv})
}
// The return value for the method is an error.
errInter := returnValues[0].Interface()
errmsg := ""
if errInter != nil {
errmsg = errInter.(error).Error()
}
server.sendResponse(conndrv, req, replyv.Interface(), errmsg)
if mtype.methodKind == MethodWithContext {
conndrv.RemoveCall(req.Seq)
}
server.freeHeader(req)
}
// ServeConn runs the server on a single connection.
// ServeConn blocks, serving the connection until the client hangs up.
// The caller typically invokes ServeConn in a go statement.
// ServeConn uses the gob wire format (see package gob) on the
// connection. To use an alternate codec, use ServeCodec.
// See NewClient's comment for information about concurrent access.
func (server *Server) ServeConn(conn io.ReadWriteCloser) {
server.ServeCodec(NewDefaultCodec(conn))
}
// ServeCodec is like ServeConn but uses the specified codec to
// decode requests and encode responses.
func (server *Server) ServeCodec(codec Codec) {
conndrv := newConnDriver(codec)
conndrv.server = server
conndrv.Loop()
}
func getSeqNum(v interface{}) uint64 {
if reflect.TypeOf(v).Kind() == reflect.Float64 {
//for encoding/json
return uint64(v.(float64))
}
return v.(uint64)
}
// handleRequest handles one request forwarded from connDriver
func (server *Server) handleRequest(conndrv *connDriver, req *Header) error {
if debugLog {
log.Printf("%p srv recv: %s\n", server, req)
}
if req.Kind == Cancel {
// discard empty body
conndrv.codec.ReadBody(nil)
// cancel req
seq := getSeqNum(req.Info)
conndrv.CancelCall(seq)
// no response sent for cancel
return nil
}
service, mtype, err := server.decodeRequestHeader(req)
if err != nil {
if debugLog {
log.Println("fail to decode req header: discard Body")
}
// discard body
conndrv.codec.ReadBody(nil)
server.sendResponse(conndrv, req, invalidRequest, err.Error())
server.freeHeader(req)
return err
}
if req.Kind == Request && mtype.methodKind != Method ||
req.Kind == RequestWithContext && mtype.methodKind != MethodWithContext {
err = fmt.Errorf("req.Kind and methodKind mismatch (discard Body): %v, %v\n", req.Kind, mtype.methodKind)
if debugLog {
log.Printf(err.Error())
}
// discard body
conndrv.codec.ReadBody(nil)
server.sendResponse(conndrv, req, invalidRequest, err.Error())
server.freeHeader(req)
return err
}
argv, replyv, err := server.readRequestBody(conndrv.codec, service, mtype, req)
if err != nil {
server.sendResponse(conndrv, req, invalidRequest, err.Error())
server.freeHeader(req)
return err
}
if mtype.methodKind == MethodWithContext {
cancel, err := setupCallContext(req)
if err != nil {
if debugLog {
log.Println(err.Error())
}
return err
}
conndrv.AddCall(req.Seq, cancel)
}
conndrv.wg.Add(1)
go service.call(server, conndrv, mtype, req, argv, replyv)
return nil
}
func setupCallContext(req *Header) (cancel context.CancelFunc, err error) {
deadline, err := time.Parse(time.RFC3339, req.Info.(string))
if err != nil {
err = fmt.Errorf("failed to parse deadline time: %v, %v", err, req.Info)
return
}
var ctx context.Context
if deadline.IsZero() {
ctx, cancel = context.WithCancel(context.Background())
} else {
ctx, cancel = context.WithDeadline(context.Background(), deadline)
}
req.Info = ctx //pack ctx for use inside call
return
}
// ServeRequest is like ServeCodec but synchronously serves a single request.
// It does not close the codec upon completion.
func (server *Server) ServeRequest(codec Codec) error {
//create a temp connDriver for one time use
//possible race if same codec/connection used in diff connDriver
tmpConnDrv := newConnDriver(codec)
tmpConnDrv.server = server
req, err := server.readRequestHeader(codec)
if err != nil {
server.freeHeader(req)
return err
}
if req.Kind == Cancel {
// discard empty body
codec.ReadBody(nil)
// cancel req
seq := getSeqNum(req.Info)
tmpConnDrv.CancelCall(seq)
// no response sent for cancel
return nil
}
service, mtype, err := server.decodeRequestHeader(req)
if err != nil {
if debugLog {
log.Println("fail to decode header: discard Body")
}
// discard body
codec.ReadBody(nil)
server.sendResponse(tmpConnDrv, req, invalidRequest, err.Error())
server.freeHeader(req)
return err
}
if req.Kind == Request && mtype.methodKind != Method ||
req.Kind == RequestWithContext && mtype.methodKind != MethodWithContext {
if debugLog {
log.Printf("req.Kind and methodKind mismatch (discard Body): %v, %v\n", req.Kind, mtype.methodKind)
}
// discard body
codec.ReadBody(nil)
server.sendResponse(tmpConnDrv, req, invalidRequest, err.Error())
server.freeHeader(req)
return err
}
argv, replyv, err := server.readRequestBody(codec, service, mtype, req)
if err != nil {
server.sendResponse(tmpConnDrv, req, invalidRequest, err.Error())
server.freeHeader(req)
return err
}
if mtype.methodKind == MethodWithContext {
cancel, err := setupCallContext(req)
if err != nil {
if debugLog {
log.Println(err.Error())
}
return err
}
tmpConnDrv.AddCall(req.Seq, cancel)
}
tmpConnDrv.wg.Add(1) //just for keep call() api consistent
service.call(server, tmpConnDrv, mtype, req, argv, replyv)
return nil
}
func (server *Server) readRequestBody(codec Codec, service *service, mtype *methodType, req *Header) (argv, replyv reflect.Value, err error) {
// Decode the argument value.
argIsValue := false // if true, need to indirect before calling.
if mtype.ArgType.Kind() == reflect.Ptr {
argv = reflect.New(mtype.ArgType.Elem())
} else {
argv = reflect.New(mtype.ArgType)
argIsValue = true
}
// argv guaranteed to be a pointer now.
if err = codec.ReadBody(argv.Interface()); err != nil {
return
}
if argIsValue {
argv = argv.Elem()
}
replyv = reflect.New(mtype.ReplyType.Elem())
switch mtype.ReplyType.Elem().Kind() {
case reflect.Map:
replyv.Elem().Set(reflect.MakeMap(mtype.ReplyType.Elem()))
case reflect.Slice:
replyv.Elem().Set(reflect.MakeSlice(mtype.ReplyType.Elem(), 0, 0))
}
return
}
func (server *Server) readRequestHeader(codec Codec) (req *Header, err error) {
// Grab the request header.
req = server.getHeader()
err = codec.ReadHeader(req)
if err != nil {
req = nil
if err == io.EOF || err == io.ErrUnexpectedEOF {
return
}
err = errors.New("rpc: server cannot decode header: " + err.Error())
return
}
// We read the header successfully. If we see an error now,
// we can still recover and move on to the next request.
return
}
func (server *Server) decodeRequestHeader(req *Header) (svc *service, mtype *methodType, err error) {
dot := strings.LastIndex(req.ServiceMethod, ".")
if dot < 0 {
err = errors.New("rpc: service/method request ill-formed: " + req.ServiceMethod)
return
}
serviceName := req.ServiceMethod[:dot]
methodName := req.ServiceMethod[dot+1:]
// Look up the request.
svci, ok := server.serviceMap.Load(serviceName)
if !ok {
err = errors.New("rpc: can't find service " + req.ServiceMethod)
return
}
svc = svci.(*service)
mtype = svc.method[methodName]
if mtype == nil {
err = errors.New("rpc: can't find method " + req.ServiceMethod)
}
return
}
func (server *Server) getHeader() *Header {
server.headerLock.Lock()
hdr := server.freeHeaders
if hdr == nil {
hdr = new(Header)
} else {
server.freeHeaders = hdr.next
*hdr = Header{}
}
server.headerLock.Unlock()
return hdr
}
func (server *Server) freeHeader(hdr *Header) {
server.headerLock.Lock()
hdr.next = server.freeHeaders
server.freeHeaders = hdr
server.headerLock.Unlock()
}
// Register publishes the receiver's methods in the DefaultServer.
func Register(rcvr interface{}) error { return DefaultServer.Register(rcvr) }
// RegisterName is like Register but uses the provided name for the type
// instead of the receiver's concrete type.
func RegisterName(name string, rcvr interface{}) error {
return DefaultServer.RegisterName(name, rcvr)
}
// ServeConn runs the DefaultServer on a single connection.
// ServeConn blocks, serving the connection until the client hangs up.
// The caller typically invokes ServeConn in a go statement.
// ServeConn uses the gob wire format (see package gob) on the
// connection. To use an alternate codec, use ServeCodec.
// See NewClient's comment for information about concurrent access.
func ServeConn(conn io.ReadWriteCloser) {
DefaultServer.ServeConn(conn)
}
// ServeCodec is like ServeConn but uses the specified codec to
// decode requests and encode responses.
func ServeCodec(codec Codec) {
DefaultServer.ServeCodec(codec)
}
// ServeRequest is like ServeCodec but synchronously serves a single request.
// It does not close the codec upon completion.
func ServeRequest(codec Codec) error {
return DefaultServer.ServeRequest(codec)
}
// ConnectBiDirectionCodec connects server and conn/codec to remote peer
// for bidirectional rpc. It will serve its registered obj/methods over conn,
// return client for invoking remote services.
func (server *Server) ConnectBiDirectionCodec(codec Codec) *Client {
conndrv := newConnDriver(codec)
conndrv.server = server
conndrv.client = newClient(conndrv)
go conndrv.Loop()
return conndrv.client
}
// AcceptBiDirection accept remote connection and setup bidirection rpc.
// It return client to invoke remote services and serve calls from
// remote client.
func (server *Server) AcceptBiDirection(lis net.Listener) (*Client, error) {
conn, err := lis.Accept()
if err != nil {
log.Print("rpc.BiDirection: accept:", err.Error())
return nil, err
}
return server.ConnectBiDirectionCodec(NewDefaultCodec(conn)), nil
}
// DialBiDirection connects to remote server and setup bidirection rpc.
// It return client to invoke remote services and serve calls from
// remote client.
func (server *Server) DialBiDirection(network, address string) (*Client, error) {
conn, err := net.Dial(network, address)
if err != nil {
log.Print("rpc.BiDirection: dial:", err.Error())
return nil, err
}
return server.ConnectBiDirectionCodec(NewDefaultCodec(conn)), nil
}
// Accept accepts connections on the listener and serves requests
// for each incoming connection. Accept blocks until the listener
// returns a non-nil error. The caller typically invokes Accept in a
// go statement.
func (server *Server) Accept(lis net.Listener) {
for {
conn, err := lis.Accept()
if err != nil {
log.Print("rpc.Serve: accept:", err.Error())
return
}
go server.ServeConn(conn)
}
}
// Accept accepts connections on the listener and serves requests
// to DefaultServer for each incoming connection.
// Accept blocks; the caller typically invokes it in a go statement.
func Accept(lis net.Listener) { DefaultServer.Accept(lis) }
// Can connect to RPC service using HTTP CONNECT to rpcPath.
var connected = "200 Connected to Go RPC"
// ServeHTTP implements an http.Handler that answers RPC requests.
func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if conn, err := hijackHTTPConn(w, req); err == nil {
server.ServeConn(conn)
}
}
// hijackHTTPConn hijacks a http conn to run RPC protocol,
// paired with client side func DialHTTPPathForConn()
func hijackHTTPConn(w http.ResponseWriter, req *http.Request) (net.Conn, error) {
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 nil, errors.New("405 must CONNECT")
}
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
log.Print("rpc hijacking ", req.RemoteAddr, ": ", err.Error())
return nil, err
}
io.WriteString(conn, "HTTP/1.0 "+connected+"\n\n")
return conn, nil
}
// HandleHTTP registers an HTTP handler for RPC messages on rpcPath,
// and a debugging handler on debugPath.
// It is still necessary to invoke http.Serve(), typically in a go statement.
func (server *Server) HandleHTTP(rpcPath, debugPath string) {
http.Handle(rpcPath, server)
http.Handle(debugPath, debugHTTP{server})
}
// HandleHTTP registers an HTTP handler for RPC messages to DefaultServer
// on DefaultRPCPath and a debugging handler on DefaultDebugPath.
// It is still necessary to invoke http.Serve(), typically in a go statement.
func HandleHTTP() {
DefaultServer.HandleHTTP(DefaultRPCPath, DefaultDebugPath)
}
// DialBiDirection connects to remote server and setup bidirection rpc, return client to
// invoke remote services and serve calls from remote client with DefaultServer
func DialBiDirection(network, address string) (*Client, error) {
return DefaultServer.DialBiDirection(network, address)
}
// AcceptBiDirection accept remote connection and setup bidirection rpc, return client to
// invoke remote services and serve calls from remote client with DefaultServer
func AcceptBiDirection(lis net.Listener) (*Client, error) {
return DefaultServer.AcceptBiDirection(lis)
}