server.go 34 KB

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