summaryrefslogtreecommitdiff
path: root/src/pkg/rpc/server.go
diff options
context:
space:
mode:
Diffstat (limited to 'src/pkg/rpc/server.go')
-rw-r--r--src/pkg/rpc/server.go191
1 files changed, 126 insertions, 65 deletions
diff --git a/src/pkg/rpc/server.go b/src/pkg/rpc/server.go
index d14f6ded2..5c50bcc3a 100644
--- a/src/pkg/rpc/server.go
+++ b/src/pkg/rpc/server.go
@@ -3,9 +3,9 @@
// license that can be found in the LICENSE file.
/*
- The rpc package provides access to the public methods of an object across a
+ The rpc package 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, public
+ 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.
@@ -13,8 +13,8 @@
Only methods that satisfy these criteria will be made available for remote access;
other methods will be ignored:
- - the method receiver and name are publicly visible, that is, begin with an upper case letter.
- - the method has two arguments, both pointers to publicly visible types.
+ - the method receiver and name are exported, that is, begin with an upper case letter.
+ - the method has two arguments, both pointers to exported types.
- the method has return type os.Error.
The method's first argument represents the arguments provided by the caller; the
@@ -123,6 +123,12 @@ import (
"utf8"
)
+const (
+ // Defaults used by HandleHTTP
+ DefaultRPCPath = "/_goRPC_"
+ DefaultDebugPath = "/debug/rpc"
+)
+
// Precompute the reflect type for os.Error. Can't use os.Error directly
// because Typeof takes an empty interface value. This is annoying.
var unusedError *os.Error
@@ -131,8 +137,8 @@ var typeOfOsError = reflect.Typeof(unusedError).(*reflect.PtrType).Elem()
type methodType struct {
sync.Mutex // protects counters
method reflect.Method
- argType *reflect.PtrType
- replyType *reflect.PtrType
+ ArgType *reflect.PtrType
+ ReplyType *reflect.PtrType
numCalls uint
}
@@ -166,23 +172,46 @@ type ClientInfo struct {
RemoteAddr string
}
-type serverType struct {
+// Server represents an RPC Server.
+type Server struct {
sync.Mutex // protects the serviceMap
serviceMap map[string]*service
}
-// This variable is a global whose "public" methods are really private methods
-// called from the global functions of this package: rpc.Register, rpc.ServeConn, etc.
-// For example, rpc.Register() calls server.add().
-var server = &serverType{serviceMap: make(map[string]*service)}
+// NewServer returns a new Server.
+func NewServer() *Server {
+ return &Server{serviceMap: make(map[string]*service)}
+}
-// Is this a publicly visible - upper case - name?
-func isPublic(name string) bool {
+// DefaultServer is the default instance of *Server.
+var DefaultServer = NewServer()
+
+// Is this an exported - upper case - name?
+func isExported(name string) bool {
rune, _ := utf8.DecodeRuneInString(name)
return unicode.IsUpper(rune)
}
-func (server *serverType) register(rcvr interface{}) os.Error {
+// Register publishes in the server the set of methods of the
+// receiver value that satisfy the following conditions:
+// - exported method
+// - two arguments, both pointers to exported structs
+// - one return value, of type os.Error
+// It returns an error if the receiver is not an exported type or has no
+// suitable methods.
+// 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{}) os.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{}) os.Error {
+ return server.register(rcvr, name, true)
+}
+
+func (server *Server) register(rcvr interface{}, name string, useName bool) os.Error {
server.Lock()
defer server.Unlock()
if server.serviceMap == nil {
@@ -192,12 +221,15 @@ func (server *serverType) register(rcvr interface{}) os.Error {
s.typ = reflect.Typeof(rcvr)
s.rcvr = reflect.NewValue(rcvr)
sname := reflect.Indirect(s.rcvr).Type().Name()
+ if useName {
+ sname = name
+ }
if sname == "" {
log.Exit("rpc: no service name for type", s.typ.String())
}
- if s.typ.PkgPath() != "" && !isPublic(sname) {
- s := "rpc Register: type " + sname + " is not public"
- log.Stderr(s)
+ if s.typ.PkgPath() != "" && !isExported(sname) && !useName {
+ s := "rpc Register: type " + sname + " is not exported"
+ log.Print(s)
return os.ErrorString(s)
}
if _, present := server.serviceMap[sname]; present {
@@ -211,54 +243,54 @@ func (server *serverType) register(rcvr interface{}) os.Error {
method := s.typ.Method(m)
mtype := method.Type
mname := method.Name
- if mtype.PkgPath() != "" && !isPublic(mname) {
+ if mtype.PkgPath() != "" || !isExported(mname) {
continue
}
// Method needs three ins: receiver, *args, *reply.
if mtype.NumIn() != 3 {
- log.Stderr("method", mname, "has wrong number of ins:", mtype.NumIn())
+ log.Println("method", mname, "has wrong number of ins:", mtype.NumIn())
continue
}
argType, ok := mtype.In(1).(*reflect.PtrType)
if !ok {
- log.Stderr(mname, "arg type not a pointer:", mtype.In(1))
+ log.Println(mname, "arg type not a pointer:", mtype.In(1))
continue
}
replyType, ok := mtype.In(2).(*reflect.PtrType)
if !ok {
- log.Stderr(mname, "reply type not a pointer:", mtype.In(2))
+ log.Println(mname, "reply type not a pointer:", mtype.In(2))
continue
}
- if argType.Elem().PkgPath() != "" && !isPublic(argType.Elem().Name()) {
- log.Stderr(mname, "argument type not public:", argType)
+ if argType.Elem().PkgPath() != "" && !isExported(argType.Elem().Name()) {
+ log.Println(mname, "argument type not exported:", argType)
continue
}
- if replyType.Elem().PkgPath() != "" && !isPublic(replyType.Elem().Name()) {
- log.Stderr(mname, "reply type not public:", replyType)
+ if replyType.Elem().PkgPath() != "" && !isExported(replyType.Elem().Name()) {
+ log.Println(mname, "reply type not exported:", replyType)
continue
}
if mtype.NumIn() == 4 {
t := mtype.In(3)
if t != reflect.Typeof((*ClientInfo)(nil)) {
- log.Stderr(mname, "last argument not *ClientInfo")
+ log.Println(mname, "last argument not *ClientInfo")
continue
}
}
// Method needs one out: os.Error.
if mtype.NumOut() != 1 {
- log.Stderr("method", mname, "has wrong number of outs:", mtype.NumOut())
+ log.Println("method", mname, "has wrong number of outs:", mtype.NumOut())
continue
}
if returnType := mtype.Out(0); returnType != typeOfOsError {
- log.Stderr("method", mname, "returns", returnType.String(), "not os.Error")
+ log.Println("method", mname, "returns", returnType.String(), "not os.Error")
continue
}
- s.method[mname] = &methodType{method: method, argType: argType, replyType: replyType}
+ s.method[mname] = &methodType{method: method, ArgType: argType, ReplyType: replyType}
}
if len(s.method) == 0 {
- s := "rpc Register: type " + sname + " has no public methods of suitable type"
- log.Stderr(s)
+ s := "rpc Register: type " + sname + " has no exported methods of suitable type"
+ log.Print(s)
return os.ErrorString(s)
}
server.serviceMap[s.name] = s
@@ -289,11 +321,18 @@ func sendResponse(sending *sync.Mutex, req *Request, reply interface{}, codec Se
sending.Lock()
err := codec.WriteResponse(resp, reply)
if err != nil {
- log.Stderr("rpc: writing response: ", err)
+ log.Println("rpc: writing response:", err)
}
sending.Unlock()
}
+func (m *methodType) NumCalls() (n uint) {
+ m.Lock()
+ n = m.numCalls
+ m.Unlock()
+ return n
+}
+
func (s *service) call(sending *sync.Mutex, mtype *methodType, req *Request, argv, replyv reflect.Value, codec ServerCodec) {
mtype.Lock()
mtype.numCalls++
@@ -335,7 +374,19 @@ func (c *gobServerCodec) Close() os.Error {
return c.rwc.Close()
}
-func (server *serverType) input(codec ServerCodec) {
+
+// 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.
+func (server *Server) ServeConn(conn io.ReadWriteCloser) {
+ server.ServeCodec(&gobServerCodec{conn, gob.NewDecoder(conn), gob.NewEncoder(conn)})
+}
+
+// ServeCodec is like ServeConn but uses the specified codec to
+// decode requests and encode responses.
+func (server *Server) ServeCodec(codec ServerCodec) {
sending := new(sync.Mutex)
for {
// Grab the request header.
@@ -344,7 +395,7 @@ func (server *serverType) input(codec ServerCodec) {
if err != nil {
if err == os.EOF || err == io.ErrUnexpectedEOF {
if err == io.ErrUnexpectedEOF {
- log.Stderr("rpc: ", err)
+ log.Println("rpc:", err)
}
break
}
@@ -374,11 +425,11 @@ func (server *serverType) input(codec ServerCodec) {
continue
}
// Decode the argument value.
- argv := _new(mtype.argType)
- replyv := _new(mtype.replyType)
+ argv := _new(mtype.ArgType)
+ replyv := _new(mtype.ReplyType)
err = codec.ReadRequestBody(argv.Interface())
if err != nil {
- log.Stderr("rpc: tearing down", serviceMethod[0], "connection:", err)
+ log.Println("rpc: tearing down", serviceMethod[0], "connection:", err)
sendResponse(sending, req, replyv.Interface(), codec, err.String())
break
}
@@ -387,24 +438,27 @@ func (server *serverType) input(codec ServerCodec) {
codec.Close()
}
-func (server *serverType) accept(lis net.Listener) {
+// Accept accepts connections on the listener and serves requests
+// for each incoming connection. Accept blocks; the caller typically
+// invokes it in a go statement.
+func (server *Server) Accept(lis net.Listener) {
for {
conn, err := lis.Accept()
if err != nil {
log.Exit("rpc.Serve: accept:", err.String()) // TODO(r): exit?
}
- go ServeConn(conn)
+ go server.ServeConn(conn)
}
}
-// Register publishes in the server the set of methods of the
-// receiver value that satisfy the following conditions:
-// - public method
-// - two arguments, both pointers to public structs
-// - one return value of type os.Error
-// It returns an error if the receiver is not public or has no
-// suitable methods.
-func Register(rcvr interface{}) os.Error { return server.register(rcvr) }
+// Register publishes the receiver's methods in the DefaultServer.
+func Register(rcvr interface{}) os.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{}) os.Error {
+ return DefaultServer.RegisterName(name, rcvr)
+}
// A ServerCodec implements reading of RPC requests and writing of
// RPC responses for the server side of an RPC session.
@@ -420,50 +474,57 @@ type ServerCodec interface {
Close() os.Error
}
-// ServeConn runs the server on a single connection.
+// 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.
func ServeConn(conn io.ReadWriteCloser) {
- ServeCodec(&gobServerCodec{conn, gob.NewDecoder(conn), gob.NewEncoder(conn)})
+ DefaultServer.ServeConn(conn)
}
// ServeCodec is like ServeConn but uses the specified codec to
// decode requests and encode responses.
func ServeCodec(codec ServerCodec) {
- server.input(codec)
+ DefaultServer.ServeCodec(codec)
}
// Accept accepts connections on the listener and serves requests
-// for each incoming connection. Accept blocks; the caller typically
-// invokes it in a go statement.
-func Accept(lis net.Listener) { server.accept(lis) }
+// 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 rpcPath string = "/_goRPC_"
-var debugPath string = "/debug/rpc"
var connected = "200 Connected to Go RPC"
-func serveHTTP(c *http.Conn, req *http.Request) {
+// ServeHTTP implements an http.Handler that answers RPC requests.
+func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method != "CONNECT" {
- c.SetHeader("Content-Type", "text/plain; charset=utf-8")
- c.WriteHeader(http.StatusMethodNotAllowed)
- io.WriteString(c, "405 must CONNECT to "+rpcPath+"\n")
+ w.SetHeader("Content-Type", "text/plain; charset=utf-8")
+ w.WriteHeader(http.StatusMethodNotAllowed)
+ io.WriteString(w, "405 must CONNECT\n")
return
}
- conn, _, err := c.Hijack()
+ conn, _, err := w.Hijack()
if err != nil {
- log.Stderr("rpc hijacking ", c.RemoteAddr, ": ", err.String())
+ log.Print("rpc hijacking ", w.RemoteAddr(), ": ", err.String())
return
}
io.WriteString(conn, "HTTP/1.0 "+connected+"\n\n")
- ServeConn(conn)
+ server.ServeConn(conn)
+}
+
+// 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.
+// 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() {
- http.Handle(rpcPath, http.HandlerFunc(serveHTTP))
- http.Handle(debugPath, http.HandlerFunc(debugHTTP))
+ DefaultServer.HandleHTTP(DefaultRPCPath, DefaultDebugPath)
}