server.go 32 KB

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