25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1493 lines
42 KiB

  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. package grpc
  19. import (
  20. "context"
  21. "errors"
  22. "fmt"
  23. "io"
  24. "math"
  25. "net"
  26. "net/http"
  27. "reflect"
  28. "runtime"
  29. "strings"
  30. "sync"
  31. "sync/atomic"
  32. "time"
  33. "golang.org/x/net/trace"
  34. "google.golang.org/grpc/codes"
  35. "google.golang.org/grpc/credentials"
  36. "google.golang.org/grpc/encoding"
  37. "google.golang.org/grpc/encoding/proto"
  38. "google.golang.org/grpc/grpclog"
  39. "google.golang.org/grpc/internal/binarylog"
  40. "google.golang.org/grpc/internal/channelz"
  41. "google.golang.org/grpc/internal/transport"
  42. "google.golang.org/grpc/keepalive"
  43. "google.golang.org/grpc/metadata"
  44. "google.golang.org/grpc/peer"
  45. "google.golang.org/grpc/stats"
  46. "google.golang.org/grpc/status"
  47. "google.golang.org/grpc/tap"
  48. )
  49. const (
  50. defaultServerMaxReceiveMessageSize = 1024 * 1024 * 4
  51. defaultServerMaxSendMessageSize = math.MaxInt32
  52. )
  53. type methodHandler func(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor UnaryServerInterceptor) (interface{}, error)
  54. // MethodDesc represents an RPC service's method specification.
  55. type MethodDesc struct {
  56. MethodName string
  57. Handler methodHandler
  58. }
  59. // ServiceDesc represents an RPC service's specification.
  60. type ServiceDesc struct {
  61. ServiceName string
  62. // The pointer to the service interface. Used to check whether the user
  63. // provided implementation satisfies the interface requirements.
  64. HandlerType interface{}
  65. Methods []MethodDesc
  66. Streams []StreamDesc
  67. Metadata interface{}
  68. }
  69. // service consists of the information of the server serving this service and
  70. // the methods in this service.
  71. type service struct {
  72. server interface{} // the server for service methods
  73. md map[string]*MethodDesc
  74. sd map[string]*StreamDesc
  75. mdata interface{}
  76. }
  77. // Server is a gRPC server to serve RPC requests.
  78. type Server struct {
  79. opts options
  80. mu sync.Mutex // guards following
  81. lis map[net.Listener]bool
  82. conns map[io.Closer]bool
  83. serve bool
  84. drain bool
  85. cv *sync.Cond // signaled when connections close for GracefulStop
  86. m map[string]*service // service name -> service info
  87. events trace.EventLog
  88. quit chan struct{}
  89. done chan struct{}
  90. quitOnce sync.Once
  91. doneOnce sync.Once
  92. channelzRemoveOnce sync.Once
  93. serveWG sync.WaitGroup // counts active Serve goroutines for GracefulStop
  94. channelzID int64 // channelz unique identification number
  95. czData *channelzData
  96. }
  97. type options struct {
  98. creds credentials.TransportCredentials
  99. codec baseCodec
  100. cp Compressor
  101. dc Decompressor
  102. unaryInt UnaryServerInterceptor
  103. streamInt StreamServerInterceptor
  104. inTapHandle tap.ServerInHandle
  105. statsHandler stats.Handler
  106. maxConcurrentStreams uint32
  107. maxReceiveMessageSize int
  108. maxSendMessageSize int
  109. unknownStreamDesc *StreamDesc
  110. keepaliveParams keepalive.ServerParameters
  111. keepalivePolicy keepalive.EnforcementPolicy
  112. initialWindowSize int32
  113. initialConnWindowSize int32
  114. writeBufferSize int
  115. readBufferSize int
  116. connectionTimeout time.Duration
  117. maxHeaderListSize *uint32
  118. }
  119. var defaultServerOptions = options{
  120. maxReceiveMessageSize: defaultServerMaxReceiveMessageSize,
  121. maxSendMessageSize: defaultServerMaxSendMessageSize,
  122. connectionTimeout: 120 * time.Second,
  123. writeBufferSize: defaultWriteBufSize,
  124. readBufferSize: defaultReadBufSize,
  125. }
  126. // A ServerOption sets options such as credentials, codec and keepalive parameters, etc.
  127. type ServerOption func(*options)
  128. // WriteBufferSize determines how much data can be batched before doing a write on the wire.
  129. // The corresponding memory allocation for this buffer will be twice the size to keep syscalls low.
  130. // The default value for this buffer is 32KB.
  131. // Zero will disable the write buffer such that each write will be on underlying connection.
  132. // Note: A Send call may not directly translate to a write.
  133. func WriteBufferSize(s int) ServerOption {
  134. return func(o *options) {
  135. o.writeBufferSize = s
  136. }
  137. }
  138. // ReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most
  139. // for one read syscall.
  140. // The default value for this buffer is 32KB.
  141. // Zero will disable read buffer for a connection so data framer can access the underlying
  142. // conn directly.
  143. func ReadBufferSize(s int) ServerOption {
  144. return func(o *options) {
  145. o.readBufferSize = s
  146. }
  147. }
  148. // InitialWindowSize returns a ServerOption that sets window size for stream.
  149. // The lower bound for window size is 64K and any value smaller than that will be ignored.
  150. func InitialWindowSize(s int32) ServerOption {
  151. return func(o *options) {
  152. o.initialWindowSize = s
  153. }
  154. }
  155. // InitialConnWindowSize returns a ServerOption that sets window size for a connection.
  156. // The lower bound for window size is 64K and any value smaller than that will be ignored.
  157. func InitialConnWindowSize(s int32) ServerOption {
  158. return func(o *options) {
  159. o.initialConnWindowSize = s
  160. }
  161. }
  162. // KeepaliveParams returns a ServerOption that sets keepalive and max-age parameters for the server.
  163. func KeepaliveParams(kp keepalive.ServerParameters) ServerOption {
  164. if kp.Time > 0 && kp.Time < time.Second {
  165. grpclog.Warning("Adjusting keepalive ping interval to minimum period of 1s")
  166. kp.Time = time.Second
  167. }
  168. return func(o *options) {
  169. o.keepaliveParams = kp
  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. // CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.
  179. //
  180. // This will override any lookups by content-subtype for Codecs registered with RegisterCodec.
  181. func CustomCodec(codec Codec) ServerOption {
  182. return func(o *options) {
  183. o.codec = codec
  184. }
  185. }
  186. // RPCCompressor returns a ServerOption that sets a compressor for outbound
  187. // messages. For backward compatibility, all outbound messages will be sent
  188. // using this compressor, regardless of incoming message compression. By
  189. // default, server messages will be sent using the same compressor with which
  190. // request messages were sent.
  191. //
  192. // Deprecated: use encoding.RegisterCompressor instead.
  193. func RPCCompressor(cp Compressor) ServerOption {
  194. return func(o *options) {
  195. o.cp = cp
  196. }
  197. }
  198. // RPCDecompressor returns a ServerOption that sets a decompressor for inbound
  199. // messages. It has higher priority than decompressors registered via
  200. // encoding.RegisterCompressor.
  201. //
  202. // Deprecated: use encoding.RegisterCompressor instead.
  203. func RPCDecompressor(dc Decompressor) ServerOption {
  204. return func(o *options) {
  205. o.dc = dc
  206. }
  207. }
  208. // MaxMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
  209. // If this is not set, gRPC uses the default limit.
  210. //
  211. // Deprecated: use MaxRecvMsgSize instead.
  212. func MaxMsgSize(m int) ServerOption {
  213. return MaxRecvMsgSize(m)
  214. }
  215. // MaxRecvMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
  216. // If this is not set, gRPC uses the default 4MB.
  217. func MaxRecvMsgSize(m int) ServerOption {
  218. return func(o *options) {
  219. o.maxReceiveMessageSize = m
  220. }
  221. }
  222. // MaxSendMsgSize returns a ServerOption to set the max message size in bytes the server can send.
  223. // If this is not set, gRPC uses the default `math.MaxInt32`.
  224. func MaxSendMsgSize(m int) ServerOption {
  225. return func(o *options) {
  226. o.maxSendMessageSize = m
  227. }
  228. }
  229. // MaxConcurrentStreams returns a ServerOption that will apply a limit on the number
  230. // of concurrent streams to each ServerTransport.
  231. func MaxConcurrentStreams(n uint32) ServerOption {
  232. return func(o *options) {
  233. o.maxConcurrentStreams = n
  234. }
  235. }
  236. // Creds returns a ServerOption that sets credentials for server connections.
  237. func Creds(c credentials.TransportCredentials) ServerOption {
  238. return func(o *options) {
  239. o.creds = c
  240. }
  241. }
  242. // UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the
  243. // server. Only one unary interceptor can be installed. The construction of multiple
  244. // interceptors (e.g., chaining) can be implemented at the caller.
  245. func UnaryInterceptor(i UnaryServerInterceptor) ServerOption {
  246. return func(o *options) {
  247. if o.unaryInt != nil {
  248. panic("The unary server interceptor was already set and may not be reset.")
  249. }
  250. o.unaryInt = i
  251. }
  252. }
  253. // StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the
  254. // server. Only one stream interceptor can be installed.
  255. func StreamInterceptor(i StreamServerInterceptor) ServerOption {
  256. return func(o *options) {
  257. if o.streamInt != nil {
  258. panic("The stream server interceptor was already set and may not be reset.")
  259. }
  260. o.streamInt = i
  261. }
  262. }
  263. // InTapHandle returns a ServerOption that sets the tap handle for all the server
  264. // transport to be created. Only one can be installed.
  265. func InTapHandle(h tap.ServerInHandle) ServerOption {
  266. return func(o *options) {
  267. if o.inTapHandle != nil {
  268. panic("The tap handle was already set and may not be reset.")
  269. }
  270. o.inTapHandle = h
  271. }
  272. }
  273. // StatsHandler returns a ServerOption that sets the stats handler for the server.
  274. func StatsHandler(h stats.Handler) ServerOption {
  275. return func(o *options) {
  276. o.statsHandler = h
  277. }
  278. }
  279. // UnknownServiceHandler returns a ServerOption that allows for adding a custom
  280. // unknown service handler. The provided method is a bidi-streaming RPC service
  281. // handler that will be invoked instead of returning the "unimplemented" gRPC
  282. // error whenever a request is received for an unregistered service or method.
  283. // The handling function has full access to the Context of the request and the
  284. // stream, and the invocation bypasses interceptors.
  285. func UnknownServiceHandler(streamHandler StreamHandler) ServerOption {
  286. return func(o *options) {
  287. o.unknownStreamDesc = &StreamDesc{
  288. StreamName: "unknown_service_handler",
  289. Handler: streamHandler,
  290. // We need to assume that the users of the streamHandler will want to use both.
  291. ClientStreams: true,
  292. ServerStreams: true,
  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. //
  301. // This API is EXPERIMENTAL.
  302. func ConnectionTimeout(d time.Duration) ServerOption {
  303. return func(o *options) {
  304. o.connectionTimeout = d
  305. }
  306. }
  307. // MaxHeaderListSize returns a ServerOption that sets the max (uncompressed) size
  308. // of header list that the server is prepared to accept.
  309. func MaxHeaderListSize(s uint32) ServerOption {
  310. return func(o *options) {
  311. o.maxHeaderListSize = &s
  312. }
  313. }
  314. // NewServer creates a gRPC server which has no service registered and has not
  315. // started to accept requests yet.
  316. func NewServer(opt ...ServerOption) *Server {
  317. opts := defaultServerOptions
  318. for _, o := range opt {
  319. o(&opts)
  320. }
  321. s := &Server{
  322. lis: make(map[net.Listener]bool),
  323. opts: opts,
  324. conns: make(map[io.Closer]bool),
  325. m: make(map[string]*service),
  326. quit: make(chan struct{}),
  327. done: make(chan struct{}),
  328. czData: new(channelzData),
  329. }
  330. s.cv = sync.NewCond(&s.mu)
  331. if EnableTracing {
  332. _, file, line, _ := runtime.Caller(1)
  333. s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line))
  334. }
  335. if channelz.IsOn() {
  336. s.channelzID = channelz.RegisterServer(&channelzServer{s}, "")
  337. }
  338. return s
  339. }
  340. // printf records an event in s's event log, unless s has been stopped.
  341. // REQUIRES s.mu is held.
  342. func (s *Server) printf(format string, a ...interface{}) {
  343. if s.events != nil {
  344. s.events.Printf(format, a...)
  345. }
  346. }
  347. // errorf records an error in s's event log, unless s has been stopped.
  348. // REQUIRES s.mu is held.
  349. func (s *Server) errorf(format string, a ...interface{}) {
  350. if s.events != nil {
  351. s.events.Errorf(format, a...)
  352. }
  353. }
  354. // RegisterService registers a service and its implementation to the gRPC
  355. // server. It is called from the IDL generated code. This must be called before
  356. // invoking Serve.
  357. func (s *Server) RegisterService(sd *ServiceDesc, ss interface{}) {
  358. ht := reflect.TypeOf(sd.HandlerType).Elem()
  359. st := reflect.TypeOf(ss)
  360. if !st.Implements(ht) {
  361. grpclog.Fatalf("grpc: Server.RegisterService found the handler of type %v that does not satisfy %v", st, ht)
  362. }
  363. s.register(sd, ss)
  364. }
  365. func (s *Server) register(sd *ServiceDesc, ss interface{}) {
  366. s.mu.Lock()
  367. defer s.mu.Unlock()
  368. s.printf("RegisterService(%q)", sd.ServiceName)
  369. if s.serve {
  370. grpclog.Fatalf("grpc: Server.RegisterService after Server.Serve for %q", sd.ServiceName)
  371. }
  372. if _, ok := s.m[sd.ServiceName]; ok {
  373. grpclog.Fatalf("grpc: Server.RegisterService found duplicate service registration for %q", sd.ServiceName)
  374. }
  375. srv := &service{
  376. server: ss,
  377. md: make(map[string]*MethodDesc),
  378. sd: make(map[string]*StreamDesc),
  379. mdata: sd.Metadata,
  380. }
  381. for i := range sd.Methods {
  382. d := &sd.Methods[i]
  383. srv.md[d.MethodName] = d
  384. }
  385. for i := range sd.Streams {
  386. d := &sd.Streams[i]
  387. srv.sd[d.StreamName] = d
  388. }
  389. s.m[sd.ServiceName] = srv
  390. }
  391. // MethodInfo contains the information of an RPC including its method name and type.
  392. type MethodInfo struct {
  393. // Name is the method name only, without the service name or package name.
  394. Name string
  395. // IsClientStream indicates whether the RPC is a client streaming RPC.
  396. IsClientStream bool
  397. // IsServerStream indicates whether the RPC is a server streaming RPC.
  398. IsServerStream bool
  399. }
  400. // ServiceInfo contains unary RPC method info, streaming RPC method info and metadata for a service.
  401. type ServiceInfo struct {
  402. Methods []MethodInfo
  403. // Metadata is the metadata specified in ServiceDesc when registering service.
  404. Metadata interface{}
  405. }
  406. // GetServiceInfo returns a map from service names to ServiceInfo.
  407. // Service names include the package names, in the form of <package>.<service>.
  408. func (s *Server) GetServiceInfo() map[string]ServiceInfo {
  409. ret := make(map[string]ServiceInfo)
  410. for n, srv := range s.m {
  411. methods := make([]MethodInfo, 0, len(srv.md)+len(srv.sd))
  412. for m := range srv.md {
  413. methods = append(methods, MethodInfo{
  414. Name: m,
  415. IsClientStream: false,
  416. IsServerStream: false,
  417. })
  418. }
  419. for m, d := range srv.sd {
  420. methods = append(methods, MethodInfo{
  421. Name: m,
  422. IsClientStream: d.ClientStreams,
  423. IsServerStream: d.ServerStreams,
  424. })
  425. }
  426. ret[n] = ServiceInfo{
  427. Methods: methods,
  428. Metadata: srv.mdata,
  429. }
  430. }
  431. return ret
  432. }
  433. // ErrServerStopped indicates that the operation is now illegal because of
  434. // the server being stopped.
  435. var ErrServerStopped = errors.New("grpc: the server has been stopped")
  436. func (s *Server) useTransportAuthenticator(rawConn net.Conn) (net.Conn, credentials.AuthInfo, error) {
  437. if s.opts.creds == nil {
  438. return rawConn, nil, nil
  439. }
  440. return s.opts.creds.ServerHandshake(rawConn)
  441. }
  442. type listenSocket struct {
  443. net.Listener
  444. channelzID int64
  445. }
  446. func (l *listenSocket) ChannelzMetric() *channelz.SocketInternalMetric {
  447. return &channelz.SocketInternalMetric{
  448. SocketOptions: channelz.GetSocketOption(l.Listener),
  449. LocalAddr: l.Listener.Addr(),
  450. }
  451. }
  452. func (l *listenSocket) Close() error {
  453. err := l.Listener.Close()
  454. if channelz.IsOn() {
  455. channelz.RemoveEntry(l.channelzID)
  456. }
  457. return err
  458. }
  459. // Serve accepts incoming connections on the listener lis, creating a new
  460. // ServerTransport and service goroutine for each. The service goroutines
  461. // read gRPC requests and then call the registered handlers to reply to them.
  462. // Serve returns when lis.Accept fails with fatal errors. lis will be closed when
  463. // this method returns.
  464. // Serve will return a non-nil error unless Stop or GracefulStop is called.
  465. func (s *Server) Serve(lis net.Listener) error {
  466. s.mu.Lock()
  467. s.printf("serving")
  468. s.serve = true
  469. if s.lis == nil {
  470. // Serve called after Stop or GracefulStop.
  471. s.mu.Unlock()
  472. lis.Close()
  473. return ErrServerStopped
  474. }
  475. s.serveWG.Add(1)
  476. defer func() {
  477. s.serveWG.Done()
  478. select {
  479. // Stop or GracefulStop called; block until done and return nil.
  480. case <-s.quit:
  481. <-s.done
  482. default:
  483. }
  484. }()
  485. ls := &listenSocket{Listener: lis}
  486. s.lis[ls] = true
  487. if channelz.IsOn() {
  488. ls.channelzID = channelz.RegisterListenSocket(ls, s.channelzID, lis.Addr().String())
  489. }
  490. s.mu.Unlock()
  491. defer func() {
  492. s.mu.Lock()
  493. if s.lis != nil && s.lis[ls] {
  494. ls.Close()
  495. delete(s.lis, ls)
  496. }
  497. s.mu.Unlock()
  498. }()
  499. var tempDelay time.Duration // how long to sleep on accept failure
  500. for {
  501. rawConn, err := lis.Accept()
  502. if err != nil {
  503. if ne, ok := err.(interface {
  504. Temporary() bool
  505. }); ok && ne.Temporary() {
  506. if tempDelay == 0 {
  507. tempDelay = 5 * time.Millisecond
  508. } else {
  509. tempDelay *= 2
  510. }
  511. if max := 1 * time.Second; tempDelay > max {
  512. tempDelay = max
  513. }
  514. s.mu.Lock()
  515. s.printf("Accept error: %v; retrying in %v", err, tempDelay)
  516. s.mu.Unlock()
  517. timer := time.NewTimer(tempDelay)
  518. select {
  519. case <-timer.C:
  520. case <-s.quit:
  521. timer.Stop()
  522. return nil
  523. }
  524. continue
  525. }
  526. s.mu.Lock()
  527. s.printf("done serving; Accept = %v", err)
  528. s.mu.Unlock()
  529. select {
  530. case <-s.quit:
  531. return nil
  532. default:
  533. }
  534. return err
  535. }
  536. tempDelay = 0
  537. // Start a new goroutine to deal with rawConn so we don't stall this Accept
  538. // loop goroutine.
  539. //
  540. // Make sure we account for the goroutine so GracefulStop doesn't nil out
  541. // s.conns before this conn can be added.
  542. s.serveWG.Add(1)
  543. go func() {
  544. s.handleRawConn(rawConn)
  545. s.serveWG.Done()
  546. }()
  547. }
  548. }
  549. // handleRawConn forks a goroutine to handle a just-accepted connection that
  550. // has not had any I/O performed on it yet.
  551. func (s *Server) handleRawConn(rawConn net.Conn) {
  552. rawConn.SetDeadline(time.Now().Add(s.opts.connectionTimeout))
  553. conn, authInfo, err := s.useTransportAuthenticator(rawConn)
  554. if err != nil {
  555. // ErrConnDispatched means that the connection was dispatched away from
  556. // gRPC; those connections should be left open.
  557. if err != credentials.ErrConnDispatched {
  558. s.mu.Lock()
  559. s.errorf("ServerHandshake(%q) failed: %v", rawConn.RemoteAddr(), err)
  560. s.mu.Unlock()
  561. grpclog.Warningf("grpc: Server.Serve failed to complete security handshake from %q: %v", rawConn.RemoteAddr(), err)
  562. rawConn.Close()
  563. }
  564. rawConn.SetDeadline(time.Time{})
  565. return
  566. }
  567. s.mu.Lock()
  568. if s.conns == nil {
  569. s.mu.Unlock()
  570. conn.Close()
  571. return
  572. }
  573. s.mu.Unlock()
  574. // Finish handshaking (HTTP2)
  575. st := s.newHTTP2Transport(conn, authInfo)
  576. if st == nil {
  577. return
  578. }
  579. rawConn.SetDeadline(time.Time{})
  580. if !s.addConn(st) {
  581. return
  582. }
  583. go func() {
  584. s.serveStreams(st)
  585. s.removeConn(st)
  586. }()
  587. }
  588. // newHTTP2Transport sets up a http/2 transport (using the
  589. // gRPC http2 server transport in transport/http2_server.go).
  590. func (s *Server) newHTTP2Transport(c net.Conn, authInfo credentials.AuthInfo) transport.ServerTransport {
  591. config := &transport.ServerConfig{
  592. MaxStreams: s.opts.maxConcurrentStreams,
  593. AuthInfo: authInfo,
  594. InTapHandle: s.opts.inTapHandle,
  595. StatsHandler: s.opts.statsHandler,
  596. KeepaliveParams: s.opts.keepaliveParams,
  597. KeepalivePolicy: s.opts.keepalivePolicy,
  598. InitialWindowSize: s.opts.initialWindowSize,
  599. InitialConnWindowSize: s.opts.initialConnWindowSize,
  600. WriteBufferSize: s.opts.writeBufferSize,
  601. ReadBufferSize: s.opts.readBufferSize,
  602. ChannelzParentID: s.channelzID,
  603. MaxHeaderListSize: s.opts.maxHeaderListSize,
  604. }
  605. st, err := transport.NewServerTransport("http2", c, config)
  606. if err != nil {
  607. s.mu.Lock()
  608. s.errorf("NewServerTransport(%q) failed: %v", c.RemoteAddr(), err)
  609. s.mu.Unlock()
  610. c.Close()
  611. grpclog.Warningln("grpc: Server.Serve failed to create ServerTransport: ", err)
  612. return nil
  613. }
  614. return st
  615. }
  616. func (s *Server) serveStreams(st transport.ServerTransport) {
  617. defer st.Close()
  618. var wg sync.WaitGroup
  619. st.HandleStreams(func(stream *transport.Stream) {
  620. wg.Add(1)
  621. go func() {
  622. defer wg.Done()
  623. s.handleStream(st, stream, s.traceInfo(st, stream))
  624. }()
  625. }, func(ctx context.Context, method string) context.Context {
  626. if !EnableTracing {
  627. return ctx
  628. }
  629. tr := trace.New("grpc.Recv."+methodFamily(method), method)
  630. return trace.NewContext(ctx, tr)
  631. })
  632. wg.Wait()
  633. }
  634. var _ http.Handler = (*Server)(nil)
  635. // ServeHTTP implements the Go standard library's http.Handler
  636. // interface by responding to the gRPC request r, by looking up
  637. // the requested gRPC method in the gRPC server s.
  638. //
  639. // The provided HTTP request must have arrived on an HTTP/2
  640. // connection. When using the Go standard library's server,
  641. // practically this means that the Request must also have arrived
  642. // over TLS.
  643. //
  644. // To share one port (such as 443 for https) between gRPC and an
  645. // existing http.Handler, use a root http.Handler such as:
  646. //
  647. // if r.ProtoMajor == 2 && strings.HasPrefix(
  648. // r.Header.Get("Content-Type"), "application/grpc") {
  649. // grpcServer.ServeHTTP(w, r)
  650. // } else {
  651. // yourMux.ServeHTTP(w, r)
  652. // }
  653. //
  654. // Note that ServeHTTP uses Go's HTTP/2 server implementation which is totally
  655. // separate from grpc-go's HTTP/2 server. Performance and features may vary
  656. // between the two paths. ServeHTTP does not support some gRPC features
  657. // available through grpc-go's HTTP/2 server, and it is currently EXPERIMENTAL
  658. // and subject to change.
  659. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  660. st, err := transport.NewServerHandlerTransport(w, r, s.opts.statsHandler)
  661. if err != nil {
  662. http.Error(w, err.Error(), http.StatusInternalServerError)
  663. return
  664. }
  665. if !s.addConn(st) {
  666. return
  667. }
  668. defer s.removeConn(st)
  669. s.serveStreams(st)
  670. }
  671. // traceInfo returns a traceInfo and associates it with stream, if tracing is enabled.
  672. // If tracing is not enabled, it returns nil.
  673. func (s *Server) traceInfo(st transport.ServerTransport, stream *transport.Stream) (trInfo *traceInfo) {
  674. tr, ok := trace.FromContext(stream.Context())
  675. if !ok {
  676. return nil
  677. }
  678. trInfo = &traceInfo{
  679. tr: tr,
  680. }
  681. trInfo.firstLine.client = false
  682. trInfo.firstLine.remoteAddr = st.RemoteAddr()
  683. if dl, ok := stream.Context().Deadline(); ok {
  684. trInfo.firstLine.deadline = time.Until(dl)
  685. }
  686. return trInfo
  687. }
  688. func (s *Server) addConn(c io.Closer) bool {
  689. s.mu.Lock()
  690. defer s.mu.Unlock()
  691. if s.conns == nil {
  692. c.Close()
  693. return false
  694. }
  695. if s.drain {
  696. // Transport added after we drained our existing conns: drain it
  697. // immediately.
  698. c.(transport.ServerTransport).Drain()
  699. }
  700. s.conns[c] = true
  701. return true
  702. }
  703. func (s *Server) removeConn(c io.Closer) {
  704. s.mu.Lock()
  705. defer s.mu.Unlock()
  706. if s.conns != nil {
  707. delete(s.conns, c)
  708. s.cv.Broadcast()
  709. }
  710. }
  711. func (s *Server) channelzMetric() *channelz.ServerInternalMetric {
  712. return &channelz.ServerInternalMetric{
  713. CallsStarted: atomic.LoadInt64(&s.czData.callsStarted),
  714. CallsSucceeded: atomic.LoadInt64(&s.czData.callsSucceeded),
  715. CallsFailed: atomic.LoadInt64(&s.czData.callsFailed),
  716. LastCallStartedTimestamp: time.Unix(0, atomic.LoadInt64(&s.czData.lastCallStartedTime)),
  717. }
  718. }
  719. func (s *Server) incrCallsStarted() {
  720. atomic.AddInt64(&s.czData.callsStarted, 1)
  721. atomic.StoreInt64(&s.czData.lastCallStartedTime, time.Now().UnixNano())
  722. }
  723. func (s *Server) incrCallsSucceeded() {
  724. atomic.AddInt64(&s.czData.callsSucceeded, 1)
  725. }
  726. func (s *Server) incrCallsFailed() {
  727. atomic.AddInt64(&s.czData.callsFailed, 1)
  728. }
  729. func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options, comp encoding.Compressor) error {
  730. data, err := encode(s.getCodec(stream.ContentSubtype()), msg)
  731. if err != nil {
  732. grpclog.Errorln("grpc: server failed to encode response: ", err)
  733. return err
  734. }
  735. compData, err := compress(data, cp, comp)
  736. if err != nil {
  737. grpclog.Errorln("grpc: server failed to compress response: ", err)
  738. return err
  739. }
  740. hdr, payload := msgHeader(data, compData)
  741. // TODO(dfawley): should we be checking len(data) instead?
  742. if len(payload) > s.opts.maxSendMessageSize {
  743. return status.Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(payload), s.opts.maxSendMessageSize)
  744. }
  745. err = t.Write(stream, hdr, payload, opts)
  746. if err == nil && s.opts.statsHandler != nil {
  747. s.opts.statsHandler.HandleRPC(stream.Context(), outPayload(false, msg, data, payload, time.Now()))
  748. }
  749. return err
  750. }
  751. func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, md *MethodDesc, trInfo *traceInfo) (err error) {
  752. if channelz.IsOn() {
  753. s.incrCallsStarted()
  754. defer func() {
  755. if err != nil && err != io.EOF {
  756. s.incrCallsFailed()
  757. } else {
  758. s.incrCallsSucceeded()
  759. }
  760. }()
  761. }
  762. sh := s.opts.statsHandler
  763. if sh != nil {
  764. beginTime := time.Now()
  765. begin := &stats.Begin{
  766. BeginTime: beginTime,
  767. }
  768. sh.HandleRPC(stream.Context(), begin)
  769. defer func() {
  770. end := &stats.End{
  771. BeginTime: beginTime,
  772. EndTime: time.Now(),
  773. }
  774. if err != nil && err != io.EOF {
  775. end.Error = toRPCErr(err)
  776. }
  777. sh.HandleRPC(stream.Context(), end)
  778. }()
  779. }
  780. if trInfo != nil {
  781. defer trInfo.tr.Finish()
  782. trInfo.firstLine.client = false
  783. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  784. defer func() {
  785. if err != nil && err != io.EOF {
  786. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  787. trInfo.tr.SetError()
  788. }
  789. }()
  790. }
  791. binlog := binarylog.GetMethodLogger(stream.Method())
  792. if binlog != nil {
  793. ctx := stream.Context()
  794. md, _ := metadata.FromIncomingContext(ctx)
  795. logEntry := &binarylog.ClientHeader{
  796. Header: md,
  797. MethodName: stream.Method(),
  798. PeerAddr: nil,
  799. }
  800. if deadline, ok := ctx.Deadline(); ok {
  801. logEntry.Timeout = time.Until(deadline)
  802. if logEntry.Timeout < 0 {
  803. logEntry.Timeout = 0
  804. }
  805. }
  806. if a := md[":authority"]; len(a) > 0 {
  807. logEntry.Authority = a[0]
  808. }
  809. if peer, ok := peer.FromContext(ctx); ok {
  810. logEntry.PeerAddr = peer.Addr
  811. }
  812. binlog.Log(logEntry)
  813. }
  814. // comp and cp are used for compression. decomp and dc are used for
  815. // decompression. If comp and decomp are both set, they are the same;
  816. // however they are kept separate to ensure that at most one of the
  817. // compressor/decompressor variable pairs are set for use later.
  818. var comp, decomp encoding.Compressor
  819. var cp Compressor
  820. var dc Decompressor
  821. // If dc is set and matches the stream's compression, use it. Otherwise, try
  822. // to find a matching registered compressor for decomp.
  823. if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc {
  824. dc = s.opts.dc
  825. } else if rc != "" && rc != encoding.Identity {
  826. decomp = encoding.GetCompressor(rc)
  827. if decomp == nil {
  828. st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc)
  829. t.WriteStatus(stream, st)
  830. return st.Err()
  831. }
  832. }
  833. // If cp is set, use it. Otherwise, attempt to compress the response using
  834. // the incoming message compression method.
  835. //
  836. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
  837. if s.opts.cp != nil {
  838. cp = s.opts.cp
  839. stream.SetSendCompress(cp.Type())
  840. } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity {
  841. // Legacy compressor not specified; attempt to respond with same encoding.
  842. comp = encoding.GetCompressor(rc)
  843. if comp != nil {
  844. stream.SetSendCompress(rc)
  845. }
  846. }
  847. var payInfo *payloadInfo
  848. if sh != nil || binlog != nil {
  849. payInfo = &payloadInfo{}
  850. }
  851. d, err := recvAndDecompress(&parser{r: stream}, stream, dc, s.opts.maxReceiveMessageSize, payInfo, decomp)
  852. if err != nil {
  853. if st, ok := status.FromError(err); ok {
  854. if e := t.WriteStatus(stream, st); e != nil {
  855. grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status %v", e)
  856. }
  857. }
  858. return err
  859. }
  860. if channelz.IsOn() {
  861. t.IncrMsgRecv()
  862. }
  863. df := func(v interface{}) error {
  864. if err := s.getCodec(stream.ContentSubtype()).Unmarshal(d, v); err != nil {
  865. return status.Errorf(codes.Internal, "grpc: error unmarshalling request: %v", err)
  866. }
  867. if sh != nil {
  868. sh.HandleRPC(stream.Context(), &stats.InPayload{
  869. RecvTime: time.Now(),
  870. Payload: v,
  871. Data: d,
  872. Length: len(d),
  873. })
  874. }
  875. if binlog != nil {
  876. binlog.Log(&binarylog.ClientMessage{
  877. Message: d,
  878. })
  879. }
  880. if trInfo != nil {
  881. trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true)
  882. }
  883. return nil
  884. }
  885. ctx := NewContextWithServerTransportStream(stream.Context(), stream)
  886. reply, appErr := md.Handler(srv.server, ctx, df, s.opts.unaryInt)
  887. if appErr != nil {
  888. appStatus, ok := status.FromError(appErr)
  889. if !ok {
  890. // Convert appErr if it is not a grpc status error.
  891. appErr = status.Error(codes.Unknown, appErr.Error())
  892. appStatus, _ = status.FromError(appErr)
  893. }
  894. if trInfo != nil {
  895. trInfo.tr.LazyLog(stringer(appStatus.Message()), true)
  896. trInfo.tr.SetError()
  897. }
  898. if e := t.WriteStatus(stream, appStatus); e != nil {
  899. grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status: %v", e)
  900. }
  901. if binlog != nil {
  902. if h, _ := stream.Header(); h.Len() > 0 {
  903. // Only log serverHeader if there was header. Otherwise it can
  904. // be trailer only.
  905. binlog.Log(&binarylog.ServerHeader{
  906. Header: h,
  907. })
  908. }
  909. binlog.Log(&binarylog.ServerTrailer{
  910. Trailer: stream.Trailer(),
  911. Err: appErr,
  912. })
  913. }
  914. return appErr
  915. }
  916. if trInfo != nil {
  917. trInfo.tr.LazyLog(stringer("OK"), false)
  918. }
  919. opts := &transport.Options{Last: true}
  920. if err := s.sendResponse(t, stream, reply, cp, opts, comp); err != nil {
  921. if err == io.EOF {
  922. // The entire stream is done (for unary RPC only).
  923. return err
  924. }
  925. if s, ok := status.FromError(err); ok {
  926. if e := t.WriteStatus(stream, s); e != nil {
  927. grpclog.Warningf("grpc: Server.processUnaryRPC failed to write status: %v", e)
  928. }
  929. } else {
  930. switch st := err.(type) {
  931. case transport.ConnectionError:
  932. // Nothing to do here.
  933. default:
  934. panic(fmt.Sprintf("grpc: Unexpected error (%T) from sendResponse: %v", st, st))
  935. }
  936. }
  937. if binlog != nil {
  938. h, _ := stream.Header()
  939. binlog.Log(&binarylog.ServerHeader{
  940. Header: h,
  941. })
  942. binlog.Log(&binarylog.ServerTrailer{
  943. Trailer: stream.Trailer(),
  944. Err: appErr,
  945. })
  946. }
  947. return err
  948. }
  949. if binlog != nil {
  950. h, _ := stream.Header()
  951. binlog.Log(&binarylog.ServerHeader{
  952. Header: h,
  953. })
  954. binlog.Log(&binarylog.ServerMessage{
  955. Message: reply,
  956. })
  957. }
  958. if channelz.IsOn() {
  959. t.IncrMsgSent()
  960. }
  961. if trInfo != nil {
  962. trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true)
  963. }
  964. // TODO: Should we be logging if writing status failed here, like above?
  965. // Should the logging be in WriteStatus? Should we ignore the WriteStatus
  966. // error or allow the stats handler to see it?
  967. err = t.WriteStatus(stream, status.New(codes.OK, ""))
  968. if binlog != nil {
  969. binlog.Log(&binarylog.ServerTrailer{
  970. Trailer: stream.Trailer(),
  971. Err: appErr,
  972. })
  973. }
  974. return err
  975. }
  976. func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transport.Stream, srv *service, sd *StreamDesc, trInfo *traceInfo) (err error) {
  977. if channelz.IsOn() {
  978. s.incrCallsStarted()
  979. defer func() {
  980. if err != nil && err != io.EOF {
  981. s.incrCallsFailed()
  982. } else {
  983. s.incrCallsSucceeded()
  984. }
  985. }()
  986. }
  987. sh := s.opts.statsHandler
  988. if sh != nil {
  989. beginTime := time.Now()
  990. begin := &stats.Begin{
  991. BeginTime: beginTime,
  992. }
  993. sh.HandleRPC(stream.Context(), begin)
  994. defer func() {
  995. end := &stats.End{
  996. BeginTime: beginTime,
  997. EndTime: time.Now(),
  998. }
  999. if err != nil && err != io.EOF {
  1000. end.Error = toRPCErr(err)
  1001. }
  1002. sh.HandleRPC(stream.Context(), end)
  1003. }()
  1004. }
  1005. ctx := NewContextWithServerTransportStream(stream.Context(), stream)
  1006. ss := &serverStream{
  1007. ctx: ctx,
  1008. t: t,
  1009. s: stream,
  1010. p: &parser{r: stream},
  1011. codec: s.getCodec(stream.ContentSubtype()),
  1012. maxReceiveMessageSize: s.opts.maxReceiveMessageSize,
  1013. maxSendMessageSize: s.opts.maxSendMessageSize,
  1014. trInfo: trInfo,
  1015. statsHandler: sh,
  1016. }
  1017. ss.binlog = binarylog.GetMethodLogger(stream.Method())
  1018. if ss.binlog != nil {
  1019. md, _ := metadata.FromIncomingContext(ctx)
  1020. logEntry := &binarylog.ClientHeader{
  1021. Header: md,
  1022. MethodName: stream.Method(),
  1023. PeerAddr: nil,
  1024. }
  1025. if deadline, ok := ctx.Deadline(); ok {
  1026. logEntry.Timeout = time.Until(deadline)
  1027. if logEntry.Timeout < 0 {
  1028. logEntry.Timeout = 0
  1029. }
  1030. }
  1031. if a := md[":authority"]; len(a) > 0 {
  1032. logEntry.Authority = a[0]
  1033. }
  1034. if peer, ok := peer.FromContext(ss.Context()); ok {
  1035. logEntry.PeerAddr = peer.Addr
  1036. }
  1037. ss.binlog.Log(logEntry)
  1038. }
  1039. // If dc is set and matches the stream's compression, use it. Otherwise, try
  1040. // to find a matching registered compressor for decomp.
  1041. if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc {
  1042. ss.dc = s.opts.dc
  1043. } else if rc != "" && rc != encoding.Identity {
  1044. ss.decomp = encoding.GetCompressor(rc)
  1045. if ss.decomp == nil {
  1046. st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc)
  1047. t.WriteStatus(ss.s, st)
  1048. return st.Err()
  1049. }
  1050. }
  1051. // If cp is set, use it. Otherwise, attempt to compress the response using
  1052. // the incoming message compression method.
  1053. //
  1054. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
  1055. if s.opts.cp != nil {
  1056. ss.cp = s.opts.cp
  1057. stream.SetSendCompress(s.opts.cp.Type())
  1058. } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity {
  1059. // Legacy compressor not specified; attempt to respond with same encoding.
  1060. ss.comp = encoding.GetCompressor(rc)
  1061. if ss.comp != nil {
  1062. stream.SetSendCompress(rc)
  1063. }
  1064. }
  1065. if trInfo != nil {
  1066. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  1067. defer func() {
  1068. ss.mu.Lock()
  1069. if err != nil && err != io.EOF {
  1070. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  1071. ss.trInfo.tr.SetError()
  1072. }
  1073. ss.trInfo.tr.Finish()
  1074. ss.trInfo.tr = nil
  1075. ss.mu.Unlock()
  1076. }()
  1077. }
  1078. var appErr error
  1079. var server interface{}
  1080. if srv != nil {
  1081. server = srv.server
  1082. }
  1083. if s.opts.streamInt == nil {
  1084. appErr = sd.Handler(server, ss)
  1085. } else {
  1086. info := &StreamServerInfo{
  1087. FullMethod: stream.Method(),
  1088. IsClientStream: sd.ClientStreams,
  1089. IsServerStream: sd.ServerStreams,
  1090. }
  1091. appErr = s.opts.streamInt(server, ss, info, sd.Handler)
  1092. }
  1093. if appErr != nil {
  1094. appStatus, ok := status.FromError(appErr)
  1095. if !ok {
  1096. appStatus = status.New(codes.Unknown, appErr.Error())
  1097. appErr = appStatus.Err()
  1098. }
  1099. if trInfo != nil {
  1100. ss.mu.Lock()
  1101. ss.trInfo.tr.LazyLog(stringer(appStatus.Message()), true)
  1102. ss.trInfo.tr.SetError()
  1103. ss.mu.Unlock()
  1104. }
  1105. t.WriteStatus(ss.s, appStatus)
  1106. if ss.binlog != nil {
  1107. ss.binlog.Log(&binarylog.ServerTrailer{
  1108. Trailer: ss.s.Trailer(),
  1109. Err: appErr,
  1110. })
  1111. }
  1112. // TODO: Should we log an error from WriteStatus here and below?
  1113. return appErr
  1114. }
  1115. if trInfo != nil {
  1116. ss.mu.Lock()
  1117. ss.trInfo.tr.LazyLog(stringer("OK"), false)
  1118. ss.mu.Unlock()
  1119. }
  1120. err = t.WriteStatus(ss.s, status.New(codes.OK, ""))
  1121. if ss.binlog != nil {
  1122. ss.binlog.Log(&binarylog.ServerTrailer{
  1123. Trailer: ss.s.Trailer(),
  1124. Err: appErr,
  1125. })
  1126. }
  1127. return err
  1128. }
  1129. func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream, trInfo *traceInfo) {
  1130. sm := stream.Method()
  1131. if sm != "" && sm[0] == '/' {
  1132. sm = sm[1:]
  1133. }
  1134. pos := strings.LastIndex(sm, "/")
  1135. if pos == -1 {
  1136. if trInfo != nil {
  1137. trInfo.tr.LazyLog(&fmtStringer{"Malformed method name %q", []interface{}{sm}}, true)
  1138. trInfo.tr.SetError()
  1139. }
  1140. errDesc := fmt.Sprintf("malformed method name: %q", stream.Method())
  1141. if err := t.WriteStatus(stream, status.New(codes.ResourceExhausted, errDesc)); err != nil {
  1142. if trInfo != nil {
  1143. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  1144. trInfo.tr.SetError()
  1145. }
  1146. grpclog.Warningf("grpc: Server.handleStream failed to write status: %v", err)
  1147. }
  1148. if trInfo != nil {
  1149. trInfo.tr.Finish()
  1150. }
  1151. return
  1152. }
  1153. service := sm[:pos]
  1154. method := sm[pos+1:]
  1155. if srv, ok := s.m[service]; ok {
  1156. if md, ok := srv.md[method]; ok {
  1157. s.processUnaryRPC(t, stream, srv, md, trInfo)
  1158. return
  1159. }
  1160. if sd, ok := srv.sd[method]; ok {
  1161. s.processStreamingRPC(t, stream, srv, sd, trInfo)
  1162. return
  1163. }
  1164. }
  1165. // Unknown service, or known server unknown method.
  1166. if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil {
  1167. s.processStreamingRPC(t, stream, nil, unknownDesc, trInfo)
  1168. return
  1169. }
  1170. if trInfo != nil {
  1171. trInfo.tr.LazyLog(&fmtStringer{"Unknown service %v", []interface{}{service}}, true)
  1172. trInfo.tr.SetError()
  1173. }
  1174. errDesc := fmt.Sprintf("unknown service %v", service)
  1175. if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil {
  1176. if trInfo != nil {
  1177. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  1178. trInfo.tr.SetError()
  1179. }
  1180. grpclog.Warningf("grpc: Server.handleStream failed to write status: %v", err)
  1181. }
  1182. if trInfo != nil {
  1183. trInfo.tr.Finish()
  1184. }
  1185. }
  1186. // The key to save ServerTransportStream in the context.
  1187. type streamKey struct{}
  1188. // NewContextWithServerTransportStream creates a new context from ctx and
  1189. // attaches stream to it.
  1190. //
  1191. // This API is EXPERIMENTAL.
  1192. func NewContextWithServerTransportStream(ctx context.Context, stream ServerTransportStream) context.Context {
  1193. return context.WithValue(ctx, streamKey{}, stream)
  1194. }
  1195. // ServerTransportStream is a minimal interface that a transport stream must
  1196. // implement. This can be used to mock an actual transport stream for tests of
  1197. // handler code that use, for example, grpc.SetHeader (which requires some
  1198. // stream to be in context).
  1199. //
  1200. // See also NewContextWithServerTransportStream.
  1201. //
  1202. // This API is EXPERIMENTAL.
  1203. type ServerTransportStream interface {
  1204. Method() string
  1205. SetHeader(md metadata.MD) error
  1206. SendHeader(md metadata.MD) error
  1207. SetTrailer(md metadata.MD) error
  1208. }
  1209. // ServerTransportStreamFromContext returns the ServerTransportStream saved in
  1210. // ctx. Returns nil if the given context has no stream associated with it
  1211. // (which implies it is not an RPC invocation context).
  1212. //
  1213. // This API is EXPERIMENTAL.
  1214. func ServerTransportStreamFromContext(ctx context.Context) ServerTransportStream {
  1215. s, _ := ctx.Value(streamKey{}).(ServerTransportStream)
  1216. return s
  1217. }
  1218. // Stop stops the gRPC server. It immediately closes all open
  1219. // connections and listeners.
  1220. // It cancels all active RPCs on the server side and the corresponding
  1221. // pending RPCs on the client side will get notified by connection
  1222. // errors.
  1223. func (s *Server) Stop() {
  1224. s.quitOnce.Do(func() {
  1225. close(s.quit)
  1226. })
  1227. defer func() {
  1228. s.serveWG.Wait()
  1229. s.doneOnce.Do(func() {
  1230. close(s.done)
  1231. })
  1232. }()
  1233. s.channelzRemoveOnce.Do(func() {
  1234. if channelz.IsOn() {
  1235. channelz.RemoveEntry(s.channelzID)
  1236. }
  1237. })
  1238. s.mu.Lock()
  1239. listeners := s.lis
  1240. s.lis = nil
  1241. st := s.conns
  1242. s.conns = nil
  1243. // interrupt GracefulStop if Stop and GracefulStop are called concurrently.
  1244. s.cv.Broadcast()
  1245. s.mu.Unlock()
  1246. for lis := range listeners {
  1247. lis.Close()
  1248. }
  1249. for c := range st {
  1250. c.Close()
  1251. }
  1252. s.mu.Lock()
  1253. if s.events != nil {
  1254. s.events.Finish()
  1255. s.events = nil
  1256. }
  1257. s.mu.Unlock()
  1258. }
  1259. // GracefulStop stops the gRPC server gracefully. It stops the server from
  1260. // accepting new connections and RPCs and blocks until all the pending RPCs are
  1261. // finished.
  1262. func (s *Server) GracefulStop() {
  1263. s.quitOnce.Do(func() {
  1264. close(s.quit)
  1265. })
  1266. defer func() {
  1267. s.doneOnce.Do(func() {
  1268. close(s.done)
  1269. })
  1270. }()
  1271. s.channelzRemoveOnce.Do(func() {
  1272. if channelz.IsOn() {
  1273. channelz.RemoveEntry(s.channelzID)
  1274. }
  1275. })
  1276. s.mu.Lock()
  1277. if s.conns == nil {
  1278. s.mu.Unlock()
  1279. return
  1280. }
  1281. for lis := range s.lis {
  1282. lis.Close()
  1283. }
  1284. s.lis = nil
  1285. if !s.drain {
  1286. for c := range s.conns {
  1287. c.(transport.ServerTransport).Drain()
  1288. }
  1289. s.drain = true
  1290. }
  1291. // Wait for serving threads to be ready to exit. Only then can we be sure no
  1292. // new conns will be created.
  1293. s.mu.Unlock()
  1294. s.serveWG.Wait()
  1295. s.mu.Lock()
  1296. for len(s.conns) != 0 {
  1297. s.cv.Wait()
  1298. }
  1299. s.conns = nil
  1300. if s.events != nil {
  1301. s.events.Finish()
  1302. s.events = nil
  1303. }
  1304. s.mu.Unlock()
  1305. }
  1306. // contentSubtype must be lowercase
  1307. // cannot return nil
  1308. func (s *Server) getCodec(contentSubtype string) baseCodec {
  1309. if s.opts.codec != nil {
  1310. return s.opts.codec
  1311. }
  1312. if contentSubtype == "" {
  1313. return encoding.GetCodec(proto.Name)
  1314. }
  1315. codec := encoding.GetCodec(contentSubtype)
  1316. if codec == nil {
  1317. return encoding.GetCodec(proto.Name)
  1318. }
  1319. return codec
  1320. }
  1321. // SetHeader sets the header metadata.
  1322. // When called multiple times, all the provided metadata will be merged.
  1323. // All the metadata will be sent out when one of the following happens:
  1324. // - grpc.SendHeader() is called;
  1325. // - The first response is sent out;
  1326. // - An RPC status is sent out (error or success).
  1327. func SetHeader(ctx context.Context, md metadata.MD) error {
  1328. if md.Len() == 0 {
  1329. return nil
  1330. }
  1331. stream := ServerTransportStreamFromContext(ctx)
  1332. if stream == nil {
  1333. return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  1334. }
  1335. return stream.SetHeader(md)
  1336. }
  1337. // SendHeader sends header metadata. It may be called at most once.
  1338. // The provided md and headers set by SetHeader() will be sent.
  1339. func SendHeader(ctx context.Context, md metadata.MD) error {
  1340. stream := ServerTransportStreamFromContext(ctx)
  1341. if stream == nil {
  1342. return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  1343. }
  1344. if err := stream.SendHeader(md); err != nil {
  1345. return toRPCErr(err)
  1346. }
  1347. return nil
  1348. }
  1349. // SetTrailer sets the trailer metadata that will be sent when an RPC returns.
  1350. // When called more than once, all the provided metadata will be merged.
  1351. func SetTrailer(ctx context.Context, md metadata.MD) error {
  1352. if md.Len() == 0 {
  1353. return nil
  1354. }
  1355. stream := ServerTransportStreamFromContext(ctx)
  1356. if stream == nil {
  1357. return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  1358. }
  1359. return stream.SetTrailer(md)
  1360. }
  1361. // Method returns the method string for the server context. The returned
  1362. // string is in the format of "/service/method".
  1363. func Method(ctx context.Context) (string, bool) {
  1364. s := ServerTransportStreamFromContext(ctx)
  1365. if s == nil {
  1366. return "", false
  1367. }
  1368. return s.Method(), true
  1369. }
  1370. type channelzServer struct {
  1371. s *Server
  1372. }
  1373. func (c *channelzServer) ChannelzMetric() *channelz.ServerInternalMetric {
  1374. return c.s.channelzMetric()
  1375. }