Debian Codegraph @

vendor/google.golang.org/grpc/server.go

raw
1 /*
2 *
3 * Copyright 2014 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 package grpc
20
21 import (
22 "bytes"
23 "errors"
24 "fmt"
25 "io"
26 "math"
27 "net"
28 "net/http"
29 "reflect"
30 "runtime"
31 "strings"
32 "sync"
33 "time"
34
35 "golang.org/x/net/context"
36 "golang.org/x/net/http2"
37 "golang.org/x/net/trace"
38 "google.golang.org/grpc/codes"
39 "google.golang.org/grpc/credentials"
40 "google.golang.org/grpc/grpclog"
41 "google.golang.org/grpc/internal"
42 "google.golang.org/grpc/keepalive"
43 "google.golang.org/grpc/metadata"
44 "google.golang.org/grpc/stats"
45 "google.golang.org/grpc/status"
46 "google.golang.org/grpc/tap"
47 "google.golang.org/grpc/transport"
48 )
49
50 const (
51 defaultServerMaxReceiveMessageSize = 1024 * 1024 * 4
52 defaultServerMaxSendMessageSize = math.MaxInt32
53 )
54
55 type methodHandler func(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor UnaryServerInterceptor) (interface{}, error)
56
57 // MethodDesc represents an RPC service's method specification.
58 type MethodDesc struct {
59 MethodName string
60 Handler methodHandler
61 }
62
63 // ServiceDesc represents an RPC service's specification.
64 type ServiceDesc struct {
65 ServiceName string
66 // The pointer to the service interface. Used to check whether the user
67 // provided implementation satisfies the interface requirements.
68 HandlerType interface{}
69 Methods []MethodDesc
70 Streams []StreamDesc
71 Metadata interface{}
72 }
73
74 // service consists of the information of the server serving this service and
75 // the methods in this service.
76 type service struct {
77 server interface{} // the server for service methods
78 md map[string]*MethodDesc
79 sd map[string]*StreamDesc
80 mdata interface{}
81 }
82
83 // Server is a gRPC server to serve RPC requests.
84 type Server struct {
85 opts options
86
87 mu sync.Mutex // guards following
88 lis map[net.Listener]bool
89 conns map[io.Closer]bool
90 serve bool
91 drain bool
92 ctx context.Context
93 cancel context.CancelFunc
94 // A CondVar to let GracefulStop() blocks until all the pending RPCs are finished
95 // and all the transport goes away.
96 cv *sync.Cond
97 m map[string]*service // service name -> service info
98 events trace.EventLog
99 }
100
101 type options struct {
102 creds credentials.TransportCredentials
103 codec Codec
104 cp Compressor
105 dc Decompressor
106 unaryInt UnaryServerInterceptor
107 streamInt StreamServerInterceptor
108 inTapHandle tap.ServerInHandle
109 statsHandler stats.Handler
110 maxConcurrentStreams uint32
111 maxReceiveMessageSize int
112 maxSendMessageSize int
113 useHandlerImpl bool // use http.Handler-based server
114 unknownStreamDesc *StreamDesc
115 keepaliveParams keepalive.ServerParameters
116 keepalivePolicy keepalive.EnforcementPolicy
117 initialWindowSize int32
118 initialConnWindowSize int32
119 writeBufferSize int
120 readBufferSize int
121 connectionTimeout time.Duration
122 }
123
124 var defaultServerOptions = options{
125 maxReceiveMessageSize: defaultServerMaxReceiveMessageSize,
126 maxSendMessageSize: defaultServerMaxSendMessageSize,
127 connectionTimeout: 120 * time.Second,
128 }
129
130 // A ServerOption sets options such as credentials, codec and keepalive parameters, etc.
131 type ServerOption func(*options)
132
133 // WriteBufferSize lets you set the size of write buffer, this determines how much data can be batched
134 // before doing a write on the wire.
135 func WriteBufferSize(s int) ServerOption {
136 return func(o *options) {
137 o.writeBufferSize = s
138 }
139 }
140
141 // ReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most
142 // for one read syscall.
143 func ReadBufferSize(s int) ServerOption {
144 return func(o *options) {
145 o.readBufferSize = s
146 }
147 }
148
149 // InitialWindowSize returns a ServerOption that sets window size for stream.
150 // The lower bound for window size is 64K and any value smaller than that will be ignored.
151 func InitialWindowSize(s int32) ServerOption {
152 return func(o *options) {
153 o.initialWindowSize = s
154 }
155 }
156
157 // InitialConnWindowSize returns a ServerOption that sets window size for a connection.
158 // The lower bound for window size is 64K and any value smaller than that will be ignored.
159 func InitialConnWindowSize(s int32) ServerOption {
160 return func(o *options) {
161 o.initialConnWindowSize = s
162 }
163 }
164
165 // KeepaliveParams returns a ServerOption that sets keepalive and max-age parameters for the server.
166 func KeepaliveParams(kp keepalive.ServerParameters) ServerOption {
167 return func(o *options) {
168 o.keepaliveParams = kp
169 }
170 }
171
172 // KeepaliveEnforcementPolicy returns a ServerOption that sets keepalive enforcement policy for the server.
173 func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption {
174 return func(o *options) {
175 o.keepalivePolicy = kep
176 }
177 }
178
179 // CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.
180 func CustomCodec(codec Codec) ServerOption {
181 return func(o *options) {
182 o.codec = codec
183 }
184 }
185
186 // RPCCompressor returns a ServerOption that sets a compressor for outbound messages.
187 func RPCCompressor(cp Compressor) ServerOption {
188 return func(o *options) {
189 o.cp = cp
190 }
191 }
192
193 // RPCDecompressor returns a ServerOption that sets a decompressor for inbound messages.
194 func RPCDecompressor(dc Decompressor) ServerOption {
195 return func(o *options) {
196 o.dc = dc
197 }
198 }
199
200 // MaxMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
201 // If this is not set, gRPC uses the default limit. Deprecated: use MaxRecvMsgSize instead.
202 func MaxMsgSize(m int) ServerOption {
203 return MaxRecvMsgSize(m)
204 }
205
206 // MaxRecvMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
207 // If this is not set, gRPC uses the default 4MB.
208 func MaxRecvMsgSize(m int) ServerOption {
209 return func(o *options) {
210 o.maxReceiveMessageSize = m
211 }
212 }
213
214 // MaxSendMsgSize returns a ServerOption to set the max message size in bytes the server can send.
215 // If this is not set, gRPC uses the default 4MB.
216 func MaxSendMsgSize(m int) ServerOption {
217 return func(o *options) {
218 o.maxSendMessageSize = m
219 }
220 }
221
222 // MaxConcurrentStreams returns a ServerOption that will apply a limit on the number
223 // of concurrent streams to each ServerTransport.
224 func MaxConcurrentStreams(n uint32) ServerOption {
225 return func(o *options) {
226 o.maxConcurrentStreams = n
227 }
228 }
229
230 // Creds returns a ServerOption that sets credentials for server connections.
231 func Creds(c credentials.TransportCredentials) ServerOption {
232 return func(o *options) {
233 o.creds = c
234 }
235 }
236
237 // UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the
238 // server. Only one unary interceptor can be installed. The construction of multiple
239 // interceptors (e.g., chaining) can be implemented at the caller.
240 func UnaryInterceptor(i UnaryServerInterceptor) ServerOption {
241 return func(o *options) {
242 if o.unaryInt != nil {
243 panic("The unary server interceptor was already set and may not be reset.")
244 }
245 o.unaryInt = i
246 }
247 }
248
249 // StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the
250 // server. Only one stream interceptor can be installed.
251 func StreamInterceptor(i StreamServerInterceptor) ServerOption {
252 return func(o *options) {
253 if o.streamInt != nil {
254 panic("The stream server interceptor was already set and may not be reset.")
255 }
256 o.streamInt = i
257 }
258 }
259
260 // InTapHandle returns a ServerOption that sets the tap handle for all the server
261 // transport to be created. Only one can be installed.
262 func InTapHandle(h tap.ServerInHandle) ServerOption {
263 return func(o *options) {
264 if o.inTapHandle != nil {
265 panic("The tap handle was already set and may not be reset.")
266 }
267 o.inTapHandle = h
268 }
269 }
270
271 // StatsHandler returns a ServerOption that sets the stats handler for the server.
272 func StatsHandler(h stats.Handler) ServerOption {
273 return func(o *options) {
274 o.statsHandler = h
275 }
276 }
277
278 // UnknownServiceHandler returns a ServerOption that allows for adding a custom
279 // unknown service handler. The provided method is a bidi-streaming RPC service
280 // handler that will be invoked instead of returning the "unimplemented" gRPC
281 // error whenever a request is received for an unregistered service or method.
282 // The handling function has full access to the Context of the request and the
283 // stream, and the invocation bypasses interceptors.
284 func UnknownServiceHandler(streamHandler StreamHandler) ServerOption {
285 return func(o *options) {
286 o.unknownStreamDesc = &StreamDesc{
287 StreamName: "unknown_service_handler",
288 Handler: streamHandler,
289 // We need to assume that the users of the streamHandler will want to use both.
290 ClientStreams: true,
291 ServerStreams: true,
292 }
293 }
294 }
295
296 // ConnectionTimeout returns a ServerOption that sets the timeout for
297 // connection establishment (up to and including HTTP/2 handshaking) for all
298 // new connections. If this is not set, the default is 120 seconds. A zero or
299 // negative value will result in an immediate timeout.
300 func ConnectionTimeout(d time.Duration) ServerOption {
301 return func(o *options) {
302 o.connectionTimeout = d
303 }
304 }
305
306 // NewServer creates a gRPC server which has no service registered and has not
307 // started to accept requests yet.
308 func NewServer(opt ...ServerOption) *Server {
309 opts := defaultServerOptions
310 for _, o := range opt {
311 o(&opts)
312 }
313 if opts.codec == nil {
314 // Set the default codec.
315 opts.codec = protoCodec{}
316 }
317 s := &Server{
318 lis: make(map[net.Listener]bool),
319 opts: opts,
320 conns: make(map[io.Closer]bool),
321 m: make(map[string]*service),
322 }
323 s.cv = sync.NewCond(&s.mu)
324 s.ctx, s.cancel = context.WithCancel(context.Background())
325 if EnableTracing {
326 _, file, line, _ := runtime.Caller(1)
327 s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line))
328 }
329 return s
330 }
331
332 // printf records an event in s's event log, unless s has been stopped.
333 // REQUIRES s.mu is held.
334 func (s *Server) printf(format string, a ...interface{}) {
335 if s.events != nil {
336 s.events.Printf(format, a...)
337 }
338 }
339
340 // errorf records an error in s's event log, unless s has been stopped.
341 // REQUIRES s.mu is held.
342 func (s *Server) errorf(format string, a ...interface{}) {
343 if s.events != nil {
344 s.events.Errorf(format, a...)
345 }
346 }
347
348 // RegisterService registers a service and its implementation to the gRPC
349 // server. It is called from the IDL generated code. This must be called before
350 // invoking Serve.
351 func (s *Server) RegisterService(sd *ServiceDesc, ss interface{}) {
352 ht := reflect.TypeOf(sd.HandlerType).Elem()
353 st := reflect.TypeOf(ss)
354 if !st.Implements(ht) {
355 grpclog.Fatalf("grpc: Server.RegisterService found the handler of type %v that does not satisfy %v", st, ht)
356 }
357 s.register(sd, ss)
358 }
359
360 func (s *Server) register(sd *ServiceDesc, ss interface{}) {
361 s.mu.Lock()
362 defer s.mu.Unlock()
363 s.printf("RegisterService(%q)", sd.ServiceName)
364 if s.serve {
365 grpclog.Fatalf("grpc: Server.RegisterService after Server.Serve for %q", sd.ServiceName)
366 }
367 if _, ok := s.m[sd.ServiceName]; ok {
368 grpclog.Fatalf("grpc: Server.RegisterService found duplicate service registration for %q", sd.ServiceName)
369 }
370 srv := &service{
371 server: ss,
372 md: make(map[string]*MethodDesc),
373 sd: make(map[string]*StreamDesc),
374 mdata: sd.Metadata,
375 }
376 for i := range sd.Methods {
377 d := &sd.Methods[i]
378 srv.md[d.MethodName] = d
379 }
380 for i := range sd.Streams {
381 d := &sd.Streams[i]
382 srv.sd[d.StreamName] = d
383 }
384 s.m[sd.ServiceName] = srv
385 }
386
387 // MethodInfo contains the information of an RPC including its method name and type.
388 type MethodInfo struct {
389 // Name is the method name only, without the service name or package name.
390 Name string
391 // IsClientStream indicates whether the RPC is a client streaming RPC.
392 IsClientStream bool
393 // IsServerStream indicates whether the RPC is a server streaming RPC.
394 IsServerStream bool
395 }
396
397 // ServiceInfo contains unary RPC method info, streaming RPC method info and metadata for a service.
398 type ServiceInfo struct {
399 Methods []MethodInfo
400 // Metadata is the metadata specified in ServiceDesc when registering service.
401 Metadata interface{}
402 }
403
404 // GetServiceInfo returns a map from service names to ServiceInfo.
405 // Service names include the package names, in the form of <package>.<service>.
406 func (s *Server) GetServiceInfo() map[string]ServiceInfo {
407 ret := make(map[string]ServiceInfo)
408 for n, srv := range s.m {
409 methods := make([]MethodInfo, 0, len(srv.md)+len(srv.sd))
410 for m := range srv.md {
411 methods = append(methods, MethodInfo{
412 Name: m,
413 IsClientStream: false,
414 IsServerStream: false,
415 })
416 }
417 for m, d := range srv.sd {
418 methods = append(methods, MethodInfo{
419 Name: m,
420 IsClientStream: d.ClientStreams,
421 IsServerStream: d.ServerStreams,
422 })
423 }
424
425 ret[n] = ServiceInfo{
426 Methods: methods,
427 Metadata: srv.mdata,
428 }
429 }
430 return ret
431 }
432
433 var (
434 // ErrServerStopped indicates that the operation is now illegal because of
435 // the server being stopped.
436 ErrServerStopped = errors.New("grpc: the server has been stopped")
437 )
438
439 func (s *Server) useTransportAuthenticator(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
440 if s.opts.creds == nil {
441 return rawConn, nil, nil
442 }
443 return s.opts.creds.ServerHandshake(rawConn)
444 }
445
446 // Serve accepts incoming connections on the listener lis, creating a new
447 // ServerTransport and service goroutine for each. The service goroutines
448 // read gRPC requests and then call the registered handlers to reply to them.
449 // Serve returns when lis.Accept fails with fatal errors. lis will be closed when
450 // this method returns.
451 // Serve always returns non-nil error.
452 func (s *Server) Serve(lis net.Listener) error {
453 s.mu.Lock()
454 s.printf("serving")
455 s.serve = true
456 if s.lis == nil {
457 s.mu.Unlock()
458 lis.Close()
459 return ErrServerStopped
460 }
461 s.lis[lis] = true
462 s.mu.Unlock()
463 defer func() {
464 s.mu.Lock()
465 if s.lis != nil && s.lis[lis] {
466 lis.Close()
467 delete(s.lis, lis)
468 }
469 s.mu.Unlock()
470 }()
471
472 var tempDelay time.Duration // how long to sleep on accept failure
473
474 for {
475 rawConn, err := lis.Accept()
476 if err != nil {
477 if ne, ok := err.(interface {
478 Temporary() bool
479 }); ok && ne.Temporary() {
480 if tempDelay == 0 {
481 tempDelay = 5 * time.Millisecond
482 } else {
483 tempDelay *= 2
484 }
485 if max := 1 * time.Second; tempDelay > max {
486 tempDelay = max
487 }
488 s.mu.Lock()
489 s.printf("Accept error: %v; retrying in %v", err, tempDelay)
490 s.mu.Unlock()
491 timer := time.NewTimer(tempDelay)
492 select {
493 case <-timer.C:
494 case <-s.ctx.Done():
495 }
496 timer.Stop()
497 continue
498 }
499 s.mu.Lock()
500 s.printf("done serving; Accept = %v", err)
501 s.mu.Unlock()
502 return err
503 }
504 tempDelay = 0
505 // Start a new goroutine to deal with rawConn
506 // so we don't stall this Accept loop goroutine.
507 go s.handleRawConn(rawConn)
508 }
509 }
510
511 // handleRawConn is run in its own goroutine and handles a just-accepted
512 // connection that has not had any I/O performed on it yet.
513 func (s *Server) handleRawConn(rawConn net.Conn) {
514 rawConn.SetDeadline(time.Now().Add(s.opts.connectionTimeout))
515 conn, authInfo, err := s.useTransportAuthenticator(rawConn)
516 if err != nil {
517 s.mu.Lock()
518 s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err)
519 s.mu.Unlock()
520 grpclog.Warningf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err)
521 // If serverHandshake returns ErrConnDispatched, keep rawConn open.
522 if err != credentials.ErrConnDispatched {
523 rawConn.Close()
524 }
525 rawConn.SetDeadline(time.Time{})
526 return
527 }
528
529 s.mu.Lock()
530 if s.conns == nil {
531 s.mu.Unlock()
532 conn.Close()
533 return
534 }
535 s.mu.Unlock()
536
537 if s.opts.useHandlerImpl {
538 rawConn.SetDeadline(time.Time{})
539 s.serveUsingHandler(conn)
540 } else {
541 st := s.newHTTP2Transport(conn, authInfo)
542 if st == nil {
543 return
544 }
545 rawConn.SetDeadline(time.Time{})
546 s.serveStreams(st)
547 }
548 }
549
550 // newHTTP2Transport sets up a http/2 transport (using the
551 // gRPC http2 server transport in transport/http2_server.go).
552 func (s *Server) newHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) transport.ServerTransport {
553 config := &transport.ServerConfig{
554 MaxStreams: s.opts.maxConcurrentStreams,
555 AuthInfo: authInfo,
556 InTapHandle: s.opts.inTapHandle,
557 StatsHandler: s.opts.statsHandler,
558 KeepaliveParams: s.opts.keepaliveParams,
559 KeepalivePolicy: s.opts.keepalivePolicy,
560 InitialWindowSize: s.opts.initialWindowSize,
561 InitialConnWindowSize: s.opts.initialConnWindowSize,
562 WriteBufferSize: s.opts.writeBufferSize,
563 ReadBufferSize: s.opts.readBufferSize,
564 }
565 st, err := transport.NewServerTransport("http2", c, config)
566 if err != nil {
567 s.mu.Lock()
568 s.errorf("NewServerTransport(%q) failed: %v", c.RemoteAddr(), err)
569 s.mu.Unlock()
570 c.Close()
571 grpclog.Warningln("grpc: Server.Serve failed to create ServerTransport: ", err)
572 return nil
573 }
574 if !s.addConn(st) {
575 st.Close()
576 return nil
577 }
578 return st
579 }
580
581 func (s *Server) serveStreams(st transport.ServerTransport) {
582 defer s.removeConn(st)
583 defer st.Close()
584 var wg sync.WaitGroup
585 st.HandleStreams(func(stream *transport.Stream) {
586 wg.Add(1)
587 go func() {
588 defer wg.Done()
589 s.handleStream(st, stream, s.traceInfo(st, stream))
590 }()
591 }, func(ctx context.Context, method string) context.Context {
592 if !EnableTracing {
593 return ctx
594 }
595 tr := trace.New("grpc.Recv."+methodFamily(method), method)
596 return trace.NewContext(ctx, tr)
597 })
598 wg.Wait()
599 }
600
601 var _ http.Handler = (*Server)(nil)
602
603 // serveUsingHandler is called from handleRawConn when s is configured
604 // to handle requests via the http.Handler interface. It sets up a
605 // net/http.Server to handle the just-accepted conn. The http.Server
606 // is configured to route all incoming requests (all HTTP/2 streams)
607 // to ServeHTTP, which creates a new ServerTransport for each stream.
608 // serveUsingHandler blocks until conn closes.
609 //
610 // This codepath is only used when Server.TestingUseHandlerImpl has
611 // been configured. This lets the end2end tests exercise the ServeHTTP
612 // method as one of the environment types.
613 //
614 // conn is the *tls.Conn that's already been authenticated.
615 func (s *Server) serveUsingHandler(conn net.Conn) {
616 if !s.addConn(conn) {
617 conn.Close()
618 return
619 }
620 defer s.removeConn(conn)
621 h2s := &http2.Server{
622 MaxConcurrentStreams: s.opts.maxConcurrentStreams,
623 }
624 h2s.ServeConn(conn, &http2.ServeConnOpts{
625 Handler: s,
626 })
627 }
628
629 // ServeHTTP implements the Go standard library's http.Handler
630 // interface by responding to the gRPC request r, by looking up
631 // the requested gRPC method in the gRPC server s.
632 //
633 // The provided HTTP request must have arrived on an HTTP/2
634 // connection. When using the Go standard library's server,
635 // practically this means that the Request must also have arrived
636 // over TLS.
637 //
638 // To share one port (such as 443 for https) between gRPC and an
639 // existing http.Handler, use a root http.Handler such as:
640 //
641 // if r.ProtoMajor == 2 && strings.HasPrefix(
642 // r.Header.Get("Content-Type"), "application/grpc") {
643 // grpcServer.ServeHTTP(w, r)
644 // } else {
645 // yourMux.ServeHTTP(w, r)
646 // }
647 //
648 // Note that ServeHTTP uses Go's HTTP/2 server implementation which is totally
649 // separate from grpc-go's HTTP/2 server. Performance and features may vary
650 // between the two paths. ServeHTTP does not support some gRPC features
651 // available through grpc-go's HTTP/2 server, and it is currently EXPERIMENTAL
652 // and subject to change.
653 func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
654 st, err := transport.NewServerHandlerTransport(w, r)
655 if err != nil {
656 http.Error(w, err.Error(), http.StatusInternalServerError)
657 return
658 }
659 if !s.addConn(st) {
660 st.Close()
661 return
662 }
663 defer s.removeConn(st)
664 s.serveStreams(st)
665 }
666
667 // traceInfo returns a traceInfo and associates it with stream, if tracing is enabled.
668 // If tracing is not enabled, it returns nil.
669 func (s *Server) traceInfo(st transport.ServerTransport, stream *transport.Stream) (trInfo *traceInfo) {
670 tr, ok := trace.FromContext(stream.Context())
671 if !ok {
672 return nil
673 }
674
675 trInfo = &traceInfo{
676 tr: tr,
677 }
678 trInfo.firstLine.client = false
679 trInfo.firstLine.remoteAddr = st.RemoteAddr()
680
681 if dl, ok := stream.Context().Deadline(); ok {
682 trInfo.firstLine.deadline = dl.Sub(time.Now())
683 }
684 return trInfo
685 }
686
687 func (s *Server) addConn(c io.Closer) bool {
688 s.mu.Lock()
689 defer s.mu.Unlock()
690 if s.conns == nil || s.drain {
691 return false
692 }
693 s.conns[c] = true
694 return true
695 }
696
697 func (s *Server) removeConn(c io.Closer) {
698 s.mu.Lock()
699 defer s.mu.Unlock()
700 if s.conns != nil {
701 delete(s.conns, c)
702 s.cv.Broadcast()
703 }
704 }
705
706 func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options) error {
707 var (
708 cbuf *bytes.Buffer
709 outPayload *stats.OutPayload
710 )
711 if cp != nil {
712 cbuf = new(bytes.Buffer)
713 }
714 if s.opts.statsHandler != nil {
715 outPayload = &stats.OutPayload{}
716 }
717 hdr, data, err := encode(s.opts.codec, msg, cp, cbuf, outPayload)
718 if err != nil {
719 grpclog.Errorln("grpc: server failed to encode response: ", err)
720 return err
721 }
722 if len(data) > s.opts.maxSendMessageSize {
723 return status.Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(data), s.opts.maxSendMessageSize)
724 }
725 err = t.Write(stream, hdr, data, opts)
726 if err == nil && outPayload != nil {
727 outPayload.SentTime = time.Now()
728 s.opts.statsHandler.HandleRPC(stream.Context(), outPayload)
729 }
730 return err
731 }
732
733 func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, md *MethodDesc, trInfo *traceInfo) (err error) {
734 sh := s.opts.statsHandler
735 if sh != nil {
736 begin := &stats.Begin{
737 BeginTime: time.Now(),
738 }
739 sh.HandleRPC(stream.Context(), begin)
740 defer func() {
741 end := &stats.End{
742 EndTime: time.Now(),
743 }
744 if err != nil && err != io.EOF {
745 end.Error = toRPCErr(err)
746 }
747 sh.HandleRPC(stream.Context(), end)
748 }()
749 }
750 if trInfo != nil {
751 defer trInfo.tr.Finish()
752 trInfo.firstLine.client = false
753 trInfo.tr.LazyLog(&trInfo.firstLine, false)
754 defer func() {
755 if err != nil && err != io.EOF {
756 trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
757 trInfo.tr.SetError()
758 }
759 }()
760 }
761 if s.opts.cp != nil {
762 // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
763 stream.SetSendCompress(s.opts.cp.Type())
764 }
765 p := &parser{r: stream}
766 pf, req, err := p.recvMsg(s.opts.maxReceiveMessageSize)
767 if err == io.EOF {
768 // The entire stream is done (for unary RPC only).
769 return err
770 }
771 if err == io.ErrUnexpectedEOF {
772 err = Errorf(codes.Internal, io.ErrUnexpectedEOF.Error())
773 }
774 if err != nil {
775 if st, ok := status.FromError(err); ok {
776 if e := t.WriteStatus(stream, st); e != nil {
777 grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e)
778 }
779 } else {
780 switch st := err.(type) {
781 case transport.ConnectionError:
782 // Nothing to do here.
783 case transport.StreamError:
784 if e := t.WriteStatus(stream, status.New(st.Code, st.Desc)); e != nil {
785 grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e)
786 }
787 default:
788 panic(fmt.Sprintf("grpc: Unexpected error (%T) from recvMsg: %v", st, st))
789 }
790 }
791 return err
792 }
793
794 if err := checkRecvPayload(pf, stream.RecvCompress(), s.opts.dc); err != nil {
795 if st, ok := status.FromError(err); ok {
796 if e := t.WriteStatus(stream, st); e != nil {
797 grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e)
798 }
799 return err
800 }
801 if e := t.WriteStatus(stream, status.New(codes.Internal, err.Error())); e != nil {
802 grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e)
803 }
804
805 // TODO checkRecvPayload always return RPC error. Add a return here if necessary.
806 }
807 var inPayload *stats.InPayload
808 if sh != nil {
809 inPayload = &stats.InPayload{
810 RecvTime: time.Now(),
811 }
812 }
813 df := func(v interface{}) error {
814 if inPayload != nil {
815 inPayload.WireLength = len(req)
816 }
817 if pf == compressionMade {
818 var err error
819 req, err = s.opts.dc.Do(bytes.NewReader(req))
820 if err != nil {
821 return Errorf(codes.Internal, err.Error())
822 }
823 }
824 if len(req) > s.opts.maxReceiveMessageSize {
825 // TODO: Revisit the error code. Currently keep it consistent with
826 // java implementation.
827 return status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", len(req), s.opts.maxReceiveMessageSize)
828 }
829 if err := s.opts.codec.Unmarshal(req, v); err != nil {
830 return status.Errorf(codes.Internal, "grpc: error unmarshalling request: %v", err)
831 }
832 if inPayload != nil {
833 inPayload.Payload = v
834 inPayload.Data = req
835 inPayload.Length = len(req)
836 sh.HandleRPC(stream.Context(), inPayload)
837 }
838 if trInfo != nil {
839 trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true)
840 }
841 return nil
842 }
843 reply, appErr := md.Handler(srv.server, stream.Context(), df, s.opts.unaryInt)
844 if appErr != nil {
845 appStatus, ok := status.FromError(appErr)
846 if !ok {
847 // Convert appErr if it is not a grpc status error.
848 appErr = status.Error(convertCode(appErr), appErr.Error())
849 appStatus, _ = status.FromError(appErr)
850 }
851 if trInfo != nil {
852 trInfo.tr.LazyLog(stringer(appStatus.Message()), true)
853 trInfo.tr.SetError()
854 }
855 if e := t.WriteStatus(stream, appStatus); e != nil {
856 grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status: %v", e)
857 }
858 return appErr
859 }
860 if trInfo != nil {
861 trInfo.tr.LazyLog(stringer("OK"), false)
862 }
863 opts := &transport.Options{
864 Last: true,
865 Delay: false,
866 }
867 if err := s.sendResponse(t, stream, reply, s.opts.cp, opts); err != nil {
868 if err == io.EOF {
869 // The entire stream is done (for unary RPC only).
870 return err
871 }
872 if s, ok := status.FromError(err); ok {
873 if e := t.WriteStatus(stream, s); e != nil {
874 grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status: %v", e)
875 }
876 } else {
877 switch st := err.(type) {
878 case transport.ConnectionError:
879 // Nothing to do here.
880 case transport.StreamError:
881 if e := t.WriteStatus(stream, status.New(st.Code, st.Desc)); e != nil {
882 grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e)
883 }
884 default:
885 panic(fmt.Sprintf("grpc: Unexpected error (%T) from sendResponse: %v", st, st))
886 }
887 }
888 return err
889 }
890 if trInfo != nil {
891 trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true)
892 }
893 // TODO: Should we be logging if writing status failed here, like above?
894 // Should the logging be in WriteStatus? Should we ignore the WriteStatus
895 // error or allow the stats handler to see it?
896 return t.WriteStatus(stream, status.New(codes.OK, ""))
897 }
898
899 func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, sd *StreamDesc, trInfo *traceInfo) (err error) {
900 sh := s.opts.statsHandler
901 if sh != nil {
902 begin := &stats.Begin{
903 BeginTime: time.Now(),
904 }
905 sh.HandleRPC(stream.Context(), begin)
906 defer func() {
907 end := &stats.End{
908 EndTime: time.Now(),
909 }
910 if err != nil && err != io.EOF {
911 end.Error = toRPCErr(err)
912 }
913 sh.HandleRPC(stream.Context(), end)
914 }()
915 }
916 if s.opts.cp != nil {
917 stream.SetSendCompress(s.opts.cp.Type())
918 }
919 ss := &serverStream{
920 t: t,
921 s: stream,
922 p: &parser{r: stream},
923 codec: s.opts.codec,
924 cp: s.opts.cp,
925 dc: s.opts.dc,
926 maxReceiveMessageSize: s.opts.maxReceiveMessageSize,
927 maxSendMessageSize: s.opts.maxSendMessageSize,
928 trInfo: trInfo,
929 statsHandler: sh,
930 }
931 if trInfo != nil {
932 trInfo.tr.LazyLog(&trInfo.firstLine, false)
933 defer func() {
934 ss.mu.Lock()
935 if err != nil && err != io.EOF {
936 ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
937 ss.trInfo.tr.SetError()
938 }
939 ss.trInfo.tr.Finish()
940 ss.trInfo.tr = nil
941 ss.mu.Unlock()
942 }()
943 }
944 var appErr error
945 var server interface{}
946 if srv != nil {
947 server = srv.server
948 }
949 if s.opts.streamInt == nil {
950 appErr = sd.Handler(server, ss)
951 } else {
952 info := &StreamServerInfo{
953 FullMethod: stream.Method(),
954 IsClientStream: sd.ClientStreams,
955 IsServerStream: sd.ServerStreams,
956 }
957 appErr = s.opts.streamInt(server, ss, info, sd.Handler)
958 }
959 if appErr != nil {
960 appStatus, ok := status.FromError(appErr)
961 if !ok {
962 switch err := appErr.(type) {
963 case transport.StreamError:
964 appStatus = status.New(err.Code, err.Desc)
965 default:
966 appStatus = status.New(convertCode(appErr), appErr.Error())
967 }
968 appErr = appStatus.Err()
969 }
970 if trInfo != nil {
971 ss.mu.Lock()
972 ss.trInfo.tr.LazyLog(stringer(appStatus.Message()), true)
973 ss.trInfo.tr.SetError()
974 ss.mu.Unlock()
975 }
976 t.WriteStatus(ss.s, appStatus)
977 // TODO: Should we log an error from WriteStatus here and below?
978 return appErr
979 }
980 if trInfo != nil {
981 ss.mu.Lock()
982 ss.trInfo.tr.LazyLog(stringer("OK"), false)
983 ss.mu.Unlock()
984 }
985 return t.WriteStatus(ss.s, status.New(codes.OK, ""))
986
987 }
988
989 func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream, trInfo *traceInfo) {
990 sm := stream.Method()
991 if sm != "" && sm[0] == '/' {
992 sm = sm[1:]
993 }
994 pos := strings.LastIndex(sm, "/")
995 if pos == -1 {
996 if trInfo != nil {
997 trInfo.tr.LazyLog(&fmtStringer{"Malformed method name %q", []interface{}{sm}}, true)
998 trInfo.tr.SetError()
999 }
1000 errDesc := fmt.Sprintf("malformed method name: %q", stream.Method())
1001 if err := t.WriteStatus(stream, status.New(codes.ResourceExhausted, errDesc)); err != nil {
1002 if trInfo != nil {
1003 trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
1004 trInfo.tr.SetError()
1005 }
1006 grpclog.Warningf("grpc: Server.handleStream failed to write status: %v", err)
1007 }
1008 if trInfo != nil {
1009 trInfo.tr.Finish()
1010 }
1011 return
1012 }
1013 service := sm[:pos]
1014 method := sm[pos+1:]
1015 srv, ok := s.m[service]
1016 if !ok {
1017 if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil {
1018 s.processStreamingRPC(t, stream, nil, unknownDesc, trInfo)
1019 return
1020 }
1021 if trInfo != nil {
1022 trInfo.tr.LazyLog(&fmtStringer{"Unknown service %v", []interface{}{service}}, true)
1023 trInfo.tr.SetError()
1024 }
1025 errDesc := fmt.Sprintf("unknown service %v", service)
1026 if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil {
1027 if trInfo != nil {
1028 trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
1029 trInfo.tr.SetError()
1030 }
1031 grpclog.Warningf("grpc: Server.handleStream failed to write status: %v", err)
1032 }
1033 if trInfo != nil {
1034 trInfo.tr.Finish()
1035 }
1036 return
1037 }
1038 // Unary RPC or Streaming RPC?
1039 if md, ok := srv.md[method]; ok {
1040 s.processUnaryRPC(t, stream, srv, md, trInfo)
1041 return
1042 }
1043 if sd, ok := srv.sd[method]; ok {
1044 s.processStreamingRPC(t, stream, srv, sd, trInfo)
1045 return
1046 }
1047 if trInfo != nil {
1048 trInfo.tr.LazyLog(&fmtStringer{"Unknown method %v", []interface{}{method}}, true)
1049 trInfo.tr.SetError()
1050 }
1051 if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil {
1052 s.processStreamingRPC(t, stream, nil, unknownDesc, trInfo)
1053 return
1054 }
1055 errDesc := fmt.Sprintf("unknown method %v", method)
1056 if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil {
1057 if trInfo != nil {
1058 trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
1059 trInfo.tr.SetError()
1060 }
1061 grpclog.Warningf("grpc: Server.handleStream failed to write status: %v", err)
1062 }
1063 if trInfo != nil {
1064 trInfo.tr.Finish()
1065 }
1066 }
1067
1068 // Stop stops the gRPC server. It immediately closes all open
1069 // connections and listeners.
1070 // It cancels all active RPCs on the server side and the corresponding
1071 // pending RPCs on the client side will get notified by connection
1072 // errors.
1073 func (s *Server) Stop() {
1074 s.mu.Lock()
1075 listeners := s.lis
1076 s.lis = nil
1077 st := s.conns
1078 s.conns = nil
1079 // interrupt GracefulStop if Stop and GracefulStop are called concurrently.
1080 s.cv.Broadcast()
1081 s.mu.Unlock()
1082
1083 for lis := range listeners {
1084 lis.Close()
1085 }
1086 for c := range st {
1087 c.Close()
1088 }
1089
1090 s.mu.Lock()
1091 s.cancel()
1092 if s.events != nil {
1093 s.events.Finish()
1094 s.events = nil
1095 }
1096 s.mu.Unlock()
1097 }
1098
1099 // GracefulStop stops the gRPC server gracefully. It stops the server from
1100 // accepting new connections and RPCs and blocks until all the pending RPCs are
1101 // finished.
1102 func (s *Server) GracefulStop() {
1103 s.mu.Lock()
1104 defer s.mu.Unlock()
1105 if s.conns == nil {
1106 return
1107 }
1108 for lis := range s.lis {
1109 lis.Close()
1110 }
1111 s.lis = nil
1112 s.cancel()
1113 if !s.drain {
1114 for c := range s.conns {
1115 c.(transport.ServerTransport).Drain()
1116 }
1117 s.drain = true
1118 }
1119 for len(s.conns) != 0 {
1120 s.cv.Wait()
1121 }
1122 s.conns = nil
1123 if s.events != nil {
1124 s.events.Finish()
1125 s.events = nil
1126 }
1127 }
1128
1129 func init() {
1130 internal.TestingCloseConns = func(arg interface{}) {
1131 arg.(*Server).testingCloseConns()
1132 }
1133 internal.TestingUseHandlerImpl = func(arg interface{}) {
1134 arg.(*Server).opts.useHandlerImpl = true
1135 }
1136 }
1137
1138 // testingCloseConns closes all existing transports but keeps s.lis
1139 // accepting new connections.
1140 func (s *Server) testingCloseConns() {
1141 s.mu.Lock()
1142 for c := range s.conns {
1143 c.Close()
1144 delete(s.conns, c)
1145 }
1146 s.mu.Unlock()
1147 }
1148
1149 // SetHeader sets the header metadata.
1150 // When called multiple times, all the provided metadata will be merged.
1151 // All the metadata will be sent out when one of the following happens:
1152 // - grpc.SendHeader() is called;
1153 // - The first response is sent out;
1154 // - An RPC status is sent out (error or success).
1155 func SetHeader(ctx context.Context, md metadata.MD) error {
1156 if md.Len() == 0 {
1157 return nil
1158 }
1159 stream, ok := transport.StreamFromContext(ctx)
1160 if !ok {
1161 return Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
1162 }
1163 return stream.SetHeader(md)
1164 }
1165
1166 // SendHeader sends header metadata. It may be called at most once.
1167 // The provided md and headers set by SetHeader() will be sent.
1168 func SendHeader(ctx context.Context, md metadata.MD) error {
1169 stream, ok := transport.StreamFromContext(ctx)
1170 if !ok {
1171 return Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
1172 }
1173 t := stream.ServerTransport()
1174 if t == nil {
1175 grpclog.Fatalf("grpc: SendHeader: %v has no ServerTransport to send header metadata.", stream)
1176 }
1177 if err := t.WriteHeader(stream, md); err != nil {
1178 return toRPCErr(err)
1179 }
1180 return nil
1181 }
1182
1183 // SetTrailer sets the trailer metadata that will be sent when an RPC returns.
1184 // When called more than once, all the provided metadata will be merged.
1185 func SetTrailer(ctx context.Context, md metadata.MD) error {
1186 if md.Len() == 0 {
1187 return nil
1188 }
1189 stream, ok := transport.StreamFromContext(ctx)
1190 if !ok {
1191 return Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
1192 }
1193 return stream.SetTrailer(md)
1194 }