server.go 34 KB

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