server.go 38 KB

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