server.go 42 KB

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