grpc-go源碼閱讀(1) grpc server的啟動(dòng)

正常啟動(dòng)一個(gè)grpcServer demo如下:

func main() {
    // 監(jiān)聽端口
    lis, err := net.Listen("tcp", port)
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }
    s := grpc.NewServer()
    pb.RegisterGreeterServer(s, &server{})
    // Register reflection service on gRPC server.
    reflection.Register(s)
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

1.grpc.NewServer

// NewServer creates a gRPC server which has no service registered and has not
// started to accept requests yet.
func NewServer(opt ...ServerOption) *Server {
    var opts options
    opts.maxMsgSize = defaultMaxMsgSize // 默認(rèn)4MB
    for _, o := range opt {
        o(&opts)
    }
    if opts.codec == nil {
        // Set the default codec.
        opts.codec = protoCodec{}
    }
    s := &Server{
        lis:   make(map[net.Listener]bool),
        opts:  opts,
        conns: make(map[io.Closer]bool),
        m:     make(map[string]*service),
    }
    s.cv = sync.NewCond(&s.mu) //  cond實(shí)例,可以喚醒等待mu鎖的goroutine
    s.ctx, s.cancel = context.WithCancel(context.Background())
    if EnableTracing {   //  controls whether to trace RPCs using the golang.org/x/net/trace package
        _, file, line, _ := runtime.Caller(1)   //  runtime庫(kù)的Caller函數(shù),可以返回運(yùn)行時(shí)正在執(zhí)行的文件名和行號(hào)
        s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line))
    }
    return s
}

  • ServerOption參數(shù)(Server的配置選項(xiàng)),啟動(dòng)時(shí)可不傳,結(jié)構(gòu)如下:
type options struct {
    creds                credentials.TransportCredentials  // cred證書
    codec                Codec       // Codec defines the interface gRPC uses to encode and decode messages,默認(rèn)為protobuf
    cp                   Compressor  // Compressor defines the interface gRPC uses to compress a message.
    dc                   Decompressor  //Decompressor defines the interface gRPC uses to decompress a message.

    maxMsgSize           int  // the max message size in bytes the server can receive,If this is not set, gRPC uses the default 4MB.(默認(rèn)4MB)
    unaryInt             UnaryServerInterceptor  //provides a hook to intercept the execution of a unary RPC on the server(攔截器)
    streamInt            StreamServerInterceptor  //provides a hook to intercept the execution of a streaming RPC on the server(攔截器)
    inTapHandle          tap.ServerInHandle  //sets the tap handle for all the server transport to be created
    statsHandler         stats.Handler
    maxConcurrentStreams uint32 //  一個(gè)連接中最大并發(fā)Stream數(shù)
    useHandlerImpl       bool   // use http.Handler-based server 
}
注釋來源:https://godoc.org/google.golang.org/grpc#UnaryInterceptor

credentials.TransportCredentials 是grpc提供認(rèn)證的證書

RPC 默認(rèn)提供了兩種認(rèn)證方式:

基于SSL/TLS認(rèn)證方式

  • 遠(yuǎn)程調(diào)用認(rèn)證方式

  • 兩種方式可以混合使用

具體詳情參考:https://segmentfault.com/a/1190000007933303

通過grpc.Creds(creds)設(shè)置該參數(shù)

options.useHandlerImpl 是控制處理RawConn的主要判別flag

g-.png

UnaryServerInterceptor/StreamServerInterceptor

詳情介紹:https://github.com/grpc-ecosystem/go-grpc-middleware / https://www.colabug.com/2496579.html

2.RegisterService

// RegisterService register a service and its implementation to the gRPC
// server. Called from the IDL generated code. This must be called before
// invoking Serve.
func (s *Server) RegisterService(sd *ServiceDesc, ss interface{}) {
    ht := reflect.TypeOf(sd.HandlerType).Elem()    // 獲取sd.HandlerType類型
    st := reflect.TypeOf(ss)                                      // 獲取ss類型
    if !st.Implements(ht) {  //ss接口必須繼承sd的處理類型接口
        grpclog.Fatalf("grpc: Server.RegisterService found the handler of type %v that does not satisfy %v", st, ht)
    }
    s.register(sd, ss)
}

func (s *Server) register(sd *ServiceDesc, ss interface{}) {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.printf("RegisterService(%q)", sd.ServiceName)  // proto的service struct名稱
    if _, ok := s.m[sd.ServiceName]; ok {  // serivce已注冊(cè)
        grpclog.Fatalf("grpc: Server.RegisterService found duplicate service registration for %q", sd.ServiceName)
    }
    srv := &service{  // 構(gòu)造service類,包括該service的information及method
        server: ss,
        md:     make(map[string]*MethodDesc),
        sd:     make(map[string]*StreamDesc),
        mdata:  sd.Metadata,
    }
    for i := range sd.Methods {  // 注冊(cè)pb中service方法對(duì)應(yīng)的handle
        d := &sd.Methods[i]
        srv.md[d.MethodName] = d
    }
    for i := range sd.Streams {  // 注冊(cè)stream對(duì)應(yīng)的handle
        d := &sd.Streams[i]
        srv.sd[d.StreamName] = d
    }
    s.m[sd.ServiceName] = srv  // 將service加入grpc server
}

3.Serve(lis net.Listener)

net.Error接口
//net.Error 
type Error interface {
    error
    Timeout() bool   // Is the error a timeout?
    Temporary() bool // Is the error temporary?
}
// Serve accepts incoming connections on the listener lis, creating a new
// ServerTransport and service goroutine for each. The service goroutines
// read gRPC requests and then call the registered handlers to reply to them.
// Serve returns when lis.Accept fails with fatal errors.  lis will be closed when
// this method returns.
// Serve always returns non-nil error.
func (s *Server) Serve(lis net.Listener) error {
    s.mu.Lock()
    s.printf("serving")
    if s.lis == nil {
        s.mu.Unlock()
        lis.Close()
        return ErrServerStopped
    }
    s.lis[lis] = true   // 設(shè)置grpcServer的lis為true
    s.mu.Unlock()
    defer func() {  // 退出函數(shù)時(shí)關(guān)閉lis,刪除grpcServer的lis
        s.mu.Lock()
        if s.lis != nil && s.lis[lis] {
            lis.Close()
            delete(s.lis, lis)
        }
        s.mu.Unlock()
    }()

    var tempDelay time.Duration // how long to sleep on accept failure

    for {
        rawConn, err := lis.Accept()
        if err != nil {
            if ne, ok := err.(interface {
                Temporary() bool
            }); ok && ne.Temporary() {
                if tempDelay == 0 {
                    tempDelay = 5 * time.Millisecond   // 第一次接受失敗retry,延遲5毫秒
                } else {
                    tempDelay *= 2                              // 之后每次retry遞增1倍時(shí)間
                }
                if max := 1 * time.Second; tempDelay > max {  // 最大等待1秒
                    tempDelay = max
                }
                s.mu.Lock()
                s.printf("Accept error: %v; retrying in %v", err, tempDelay)
                s.mu.Unlock()
                select {  //  等待時(shí)間超時(shí)或context cancle時(shí)才繼續(xù)往下
                case <-time.After(tempDelay):  
                case <-s.ctx.Done():
                }
                continue
            }
            s.mu.Lock()
            s.printf("done serving; Accept = %v", err)
            s.mu.Unlock()
            return err
        }
        tempDelay = 0
        // Start a new goroutine to deal with rawConn
        // so we don't stall this Accept loop goroutine.
        go s.handleRawConn(rawConn)  // 處理rawConn并不會(huì)導(dǎo)致grpc停止accept
    }
}

4.handleRawConn

// handleRawConn is run in its own goroutine and handles a just-accepted
// connection that has not had any I/O performed on it yet.
func (s *Server) handleRawConn(rawConn net.Conn) {
    conn, authInfo, err := s.useTransportAuthenticator(rawConn)
    if err != nil {
        s.mu.Lock()
        s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err)
        s.mu.Unlock()
        grpclog.Printf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err)
        // If serverHandShake returns ErrConnDispatched, keep rawConn open.
        if err != credentials.ErrConnDispatched {  // 如果是認(rèn)證error,保持rawConn open
            rawConn.Close()
        }
        return
    }

    s.mu.Lock()
    if s.conns == nil {
        s.mu.Unlock()
        conn.Close()
        return
    }
    s.mu.Unlock()

    if s.opts.useHandlerImpl {    // 選擇不同包的的http2服務(wù),默認(rèn)調(diào)用serveUsingHandler
        s.serveUsingHandler(conn)
    } else {
        s.serveHTTP2Transport(conn, authInfo)
    }
}
// serveUsingHandler is called from handleRawConn when s is configured
// to handle requests via the http.Handler interface. It sets up a
// net/http.Server to handle the just-accepted conn. The http.Server
// is configured to route all incoming requests (all HTTP/2 streams)
// to ServeHTTP, which creates a new ServerTransport for each stream.
// serveUsingHandler blocks until conn closes.
//
// This codepath is only used when Server.TestingUseHandlerImpl has
// been configured. This lets the end2end tests exercise the ServeHTTP
// method as one of the environment types.
//
// conn is the *tls.Conn that's already been authenticated.
func (s *Server) serveUsingHandler(conn net.Conn) {
    if !s.addConn(conn) {  // conn注冊(cè)到grpc server中
        conn.Close()
        return
    }
    defer s.removeConn(conn)
    h2s := &http2.Server{
        MaxConcurrentStreams: s.opts.maxConcurrentStreams,  //一個(gè)連接中最大并發(fā)Stream數(shù)
    }
    h2s.ServeConn(conn, &http2.ServeConnOpts{
        Handler: s,
    })
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容