server.go 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980
  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"
  40. "google.golang.org/grpc/internal/binarylog"
  41. "google.golang.org/grpc/internal/channelz"
  42. "google.golang.org/grpc/internal/grpcrand"
  43. "google.golang.org/grpc/internal/grpcsync"
  44. "google.golang.org/grpc/internal/transport"
  45. "google.golang.org/grpc/keepalive"
  46. "google.golang.org/grpc/metadata"
  47. "google.golang.org/grpc/peer"
  48. "google.golang.org/grpc/stats"
  49. "google.golang.org/grpc/status"
  50. "google.golang.org/grpc/tap"
  51. )
  52. const (
  53. defaultServerMaxReceiveMessageSize = 1024 * 1024 * 4
  54. defaultServerMaxSendMessageSize = math.MaxInt32
  55. // Server transports are tracked in a map which is keyed on listener
  56. // address. For regular gRPC traffic, connections are accepted in Serve()
  57. // through a call to Accept(), and we use the actual listener address as key
  58. // when we add it to the map. But for connections received through
  59. // ServeHTTP(), we do not have a listener and hence use this dummy value.
  60. listenerAddressForServeHTTP = "listenerAddressForServeHTTP"
  61. )
  62. func init() {
  63. internal.GetServerCredentials = func(srv *Server) credentials.TransportCredentials {
  64. return srv.opts.creds
  65. }
  66. internal.DrainServerTransports = func(srv *Server, addr string) {
  67. srv.drainServerTransports(addr)
  68. }
  69. internal.AddGlobalServerOptions = func(opt ...ServerOption) {
  70. extraServerOptions = append(extraServerOptions, opt...)
  71. }
  72. internal.ClearGlobalServerOptions = func() {
  73. extraServerOptions = nil
  74. }
  75. internal.BinaryLogger = binaryLogger
  76. internal.JoinServerOptions = newJoinServerOption
  77. }
  78. var statusOK = status.New(codes.OK, "")
  79. var logger = grpclog.Component("core")
  80. type methodHandler func(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor UnaryServerInterceptor) (interface{}, error)
  81. // MethodDesc represents an RPC service's method specification.
  82. type MethodDesc struct {
  83. MethodName string
  84. Handler methodHandler
  85. }
  86. // ServiceDesc represents an RPC service's specification.
  87. type ServiceDesc struct {
  88. ServiceName string
  89. // The pointer to the service interface. Used to check whether the user
  90. // provided implementation satisfies the interface requirements.
  91. HandlerType interface{}
  92. Methods []MethodDesc
  93. Streams []StreamDesc
  94. Metadata interface{}
  95. }
  96. // serviceInfo wraps information about a service. It is very similar to
  97. // ServiceDesc and is constructed from it for internal purposes.
  98. type serviceInfo struct {
  99. // Contains the implementation for the methods in this service.
  100. serviceImpl interface{}
  101. methods map[string]*MethodDesc
  102. streams map[string]*StreamDesc
  103. mdata interface{}
  104. }
  105. type serverWorkerData struct {
  106. st transport.ServerTransport
  107. wg *sync.WaitGroup
  108. stream *transport.Stream
  109. }
  110. // Server is a gRPC server to serve RPC requests.
  111. type Server struct {
  112. opts serverOptions
  113. mu sync.Mutex // guards following
  114. lis map[net.Listener]bool
  115. // conns contains all active server transports. It is a map keyed on a
  116. // listener address with the value being the set of active transports
  117. // belonging to that listener.
  118. conns map[string]map[transport.ServerTransport]bool
  119. serve bool
  120. drain bool
  121. cv *sync.Cond // signaled when connections close for GracefulStop
  122. services map[string]*serviceInfo // service name -> service info
  123. events trace.EventLog
  124. quit *grpcsync.Event
  125. done *grpcsync.Event
  126. channelzRemoveOnce sync.Once
  127. serveWG sync.WaitGroup // counts active Serve goroutines for GracefulStop
  128. channelzID *channelz.Identifier
  129. czData *channelzData
  130. serverWorkerChannels []chan *serverWorkerData
  131. }
  132. type serverOptions struct {
  133. creds credentials.TransportCredentials
  134. codec baseCodec
  135. cp Compressor
  136. dc Decompressor
  137. unaryInt UnaryServerInterceptor
  138. streamInt StreamServerInterceptor
  139. chainUnaryInts []UnaryServerInterceptor
  140. chainStreamInts []StreamServerInterceptor
  141. binaryLogger binarylog.Logger
  142. inTapHandle tap.ServerInHandle
  143. statsHandlers []stats.Handler
  144. maxConcurrentStreams uint32
  145. maxReceiveMessageSize int
  146. maxSendMessageSize int
  147. unknownStreamDesc *StreamDesc
  148. keepaliveParams keepalive.ServerParameters
  149. keepalivePolicy keepalive.EnforcementPolicy
  150. initialWindowSize int32
  151. initialConnWindowSize int32
  152. writeBufferSize int
  153. readBufferSize int
  154. connectionTimeout time.Duration
  155. maxHeaderListSize *uint32
  156. headerTableSize *uint32
  157. numServerWorkers uint32
  158. }
  159. var defaultServerOptions = serverOptions{
  160. maxReceiveMessageSize: defaultServerMaxReceiveMessageSize,
  161. maxSendMessageSize: defaultServerMaxSendMessageSize,
  162. connectionTimeout: 120 * time.Second,
  163. writeBufferSize: defaultWriteBufSize,
  164. readBufferSize: defaultReadBufSize,
  165. }
  166. var extraServerOptions []ServerOption
  167. // A ServerOption sets options such as credentials, codec and keepalive parameters, etc.
  168. type ServerOption interface {
  169. apply(*serverOptions)
  170. }
  171. // EmptyServerOption does not alter the server configuration. It can be embedded
  172. // in another structure to build custom server options.
  173. //
  174. // # Experimental
  175. //
  176. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  177. // later release.
  178. type EmptyServerOption struct{}
  179. func (EmptyServerOption) apply(*serverOptions) {}
  180. // funcServerOption wraps a function that modifies serverOptions into an
  181. // implementation of the ServerOption interface.
  182. type funcServerOption struct {
  183. f func(*serverOptions)
  184. }
  185. func (fdo *funcServerOption) apply(do *serverOptions) {
  186. fdo.f(do)
  187. }
  188. func newFuncServerOption(f func(*serverOptions)) *funcServerOption {
  189. return &funcServerOption{
  190. f: f,
  191. }
  192. }
  193. // joinServerOption provides a way to combine arbitrary number of server
  194. // options into one.
  195. type joinServerOption struct {
  196. opts []ServerOption
  197. }
  198. func (mdo *joinServerOption) apply(do *serverOptions) {
  199. for _, opt := range mdo.opts {
  200. opt.apply(do)
  201. }
  202. }
  203. func newJoinServerOption(opts ...ServerOption) ServerOption {
  204. return &joinServerOption{opts: opts}
  205. }
  206. // WriteBufferSize determines how much data can be batched before doing a write on the wire.
  207. // The corresponding memory allocation for this buffer will be twice the size to keep syscalls low.
  208. // The default value for this buffer is 32KB.
  209. // Zero will disable the write buffer such that each write will be on underlying connection.
  210. // Note: A Send call may not directly translate to a write.
  211. func WriteBufferSize(s int) ServerOption {
  212. return newFuncServerOption(func(o *serverOptions) {
  213. o.writeBufferSize = s
  214. })
  215. }
  216. // ReadBufferSize lets you set the size of read buffer, this determines how much data can be read at most
  217. // for one read syscall.
  218. // The default value for this buffer is 32KB.
  219. // Zero will disable read buffer for a connection so data framer can access the underlying
  220. // conn directly.
  221. func ReadBufferSize(s int) ServerOption {
  222. return newFuncServerOption(func(o *serverOptions) {
  223. o.readBufferSize = s
  224. })
  225. }
  226. // InitialWindowSize returns a ServerOption that sets window size for stream.
  227. // The lower bound for window size is 64K and any value smaller than that will be ignored.
  228. func InitialWindowSize(s int32) ServerOption {
  229. return newFuncServerOption(func(o *serverOptions) {
  230. o.initialWindowSize = s
  231. })
  232. }
  233. // InitialConnWindowSize returns a ServerOption that sets window size for a connection.
  234. // The lower bound for window size is 64K and any value smaller than that will be ignored.
  235. func InitialConnWindowSize(s int32) ServerOption {
  236. return newFuncServerOption(func(o *serverOptions) {
  237. o.initialConnWindowSize = s
  238. })
  239. }
  240. // KeepaliveParams returns a ServerOption that sets keepalive and max-age parameters for the server.
  241. func KeepaliveParams(kp keepalive.ServerParameters) ServerOption {
  242. if kp.Time > 0 && kp.Time < time.Second {
  243. logger.Warning("Adjusting keepalive ping interval to minimum period of 1s")
  244. kp.Time = time.Second
  245. }
  246. return newFuncServerOption(func(o *serverOptions) {
  247. o.keepaliveParams = kp
  248. })
  249. }
  250. // KeepaliveEnforcementPolicy returns a ServerOption that sets keepalive enforcement policy for the server.
  251. func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption {
  252. return newFuncServerOption(func(o *serverOptions) {
  253. o.keepalivePolicy = kep
  254. })
  255. }
  256. // CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling.
  257. //
  258. // This will override any lookups by content-subtype for Codecs registered with RegisterCodec.
  259. //
  260. // Deprecated: register codecs using encoding.RegisterCodec. The server will
  261. // automatically use registered codecs based on the incoming requests' headers.
  262. // See also
  263. // https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec.
  264. // Will be supported throughout 1.x.
  265. func CustomCodec(codec Codec) ServerOption {
  266. return newFuncServerOption(func(o *serverOptions) {
  267. o.codec = codec
  268. })
  269. }
  270. // ForceServerCodec returns a ServerOption that sets a codec for message
  271. // marshaling and unmarshaling.
  272. //
  273. // This will override any lookups by content-subtype for Codecs registered
  274. // with RegisterCodec.
  275. //
  276. // See Content-Type on
  277. // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for
  278. // more details. Also see the documentation on RegisterCodec and
  279. // CallContentSubtype for more details on the interaction between encoding.Codec
  280. // and content-subtype.
  281. //
  282. // This function is provided for advanced users; prefer to register codecs
  283. // using encoding.RegisterCodec.
  284. // The server will automatically use registered codecs based on the incoming
  285. // requests' headers. See also
  286. // https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec.
  287. // Will be supported throughout 1.x.
  288. //
  289. // # Experimental
  290. //
  291. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  292. // later release.
  293. func ForceServerCodec(codec encoding.Codec) ServerOption {
  294. return newFuncServerOption(func(o *serverOptions) {
  295. o.codec = codec
  296. })
  297. }
  298. // RPCCompressor returns a ServerOption that sets a compressor for outbound
  299. // messages. For backward compatibility, all outbound messages will be sent
  300. // using this compressor, regardless of incoming message compression. By
  301. // default, server messages will be sent using the same compressor with which
  302. // request messages were sent.
  303. //
  304. // Deprecated: use encoding.RegisterCompressor instead. Will be supported
  305. // throughout 1.x.
  306. func RPCCompressor(cp Compressor) ServerOption {
  307. return newFuncServerOption(func(o *serverOptions) {
  308. o.cp = cp
  309. })
  310. }
  311. // RPCDecompressor returns a ServerOption that sets a decompressor for inbound
  312. // messages. It has higher priority than decompressors registered via
  313. // encoding.RegisterCompressor.
  314. //
  315. // Deprecated: use encoding.RegisterCompressor instead. Will be supported
  316. // throughout 1.x.
  317. func RPCDecompressor(dc Decompressor) ServerOption {
  318. return newFuncServerOption(func(o *serverOptions) {
  319. o.dc = dc
  320. })
  321. }
  322. // MaxMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
  323. // If this is not set, gRPC uses the default limit.
  324. //
  325. // Deprecated: use MaxRecvMsgSize instead. Will be supported throughout 1.x.
  326. func MaxMsgSize(m int) ServerOption {
  327. return MaxRecvMsgSize(m)
  328. }
  329. // MaxRecvMsgSize returns a ServerOption to set the max message size in bytes the server can receive.
  330. // If this is not set, gRPC uses the default 4MB.
  331. func MaxRecvMsgSize(m int) ServerOption {
  332. return newFuncServerOption(func(o *serverOptions) {
  333. o.maxReceiveMessageSize = m
  334. })
  335. }
  336. // MaxSendMsgSize returns a ServerOption to set the max message size in bytes the server can send.
  337. // If this is not set, gRPC uses the default `math.MaxInt32`.
  338. func MaxSendMsgSize(m int) ServerOption {
  339. return newFuncServerOption(func(o *serverOptions) {
  340. o.maxSendMessageSize = m
  341. })
  342. }
  343. // MaxConcurrentStreams returns a ServerOption that will apply a limit on the number
  344. // of concurrent streams to each ServerTransport.
  345. func MaxConcurrentStreams(n uint32) ServerOption {
  346. return newFuncServerOption(func(o *serverOptions) {
  347. o.maxConcurrentStreams = n
  348. })
  349. }
  350. // Creds returns a ServerOption that sets credentials for server connections.
  351. func Creds(c credentials.TransportCredentials) ServerOption {
  352. return newFuncServerOption(func(o *serverOptions) {
  353. o.creds = c
  354. })
  355. }
  356. // UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the
  357. // server. Only one unary interceptor can be installed. The construction of multiple
  358. // interceptors (e.g., chaining) can be implemented at the caller.
  359. func UnaryInterceptor(i UnaryServerInterceptor) ServerOption {
  360. return newFuncServerOption(func(o *serverOptions) {
  361. if o.unaryInt != nil {
  362. panic("The unary server interceptor was already set and may not be reset.")
  363. }
  364. o.unaryInt = i
  365. })
  366. }
  367. // ChainUnaryInterceptor returns a ServerOption that specifies the chained interceptor
  368. // for unary RPCs. The first interceptor will be the outer most,
  369. // while the last interceptor will be the inner most wrapper around the real call.
  370. // All unary interceptors added by this method will be chained.
  371. func ChainUnaryInterceptor(interceptors ...UnaryServerInterceptor) ServerOption {
  372. return newFuncServerOption(func(o *serverOptions) {
  373. o.chainUnaryInts = append(o.chainUnaryInts, interceptors...)
  374. })
  375. }
  376. // StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the
  377. // server. Only one stream interceptor can be installed.
  378. func StreamInterceptor(i StreamServerInterceptor) ServerOption {
  379. return newFuncServerOption(func(o *serverOptions) {
  380. if o.streamInt != nil {
  381. panic("The stream server interceptor was already set and may not be reset.")
  382. }
  383. o.streamInt = i
  384. })
  385. }
  386. // ChainStreamInterceptor returns a ServerOption that specifies the chained interceptor
  387. // for streaming RPCs. The first interceptor will be the outer most,
  388. // while the last interceptor will be the inner most wrapper around the real call.
  389. // All stream interceptors added by this method will be chained.
  390. func ChainStreamInterceptor(interceptors ...StreamServerInterceptor) ServerOption {
  391. return newFuncServerOption(func(o *serverOptions) {
  392. o.chainStreamInts = append(o.chainStreamInts, interceptors...)
  393. })
  394. }
  395. // InTapHandle returns a ServerOption that sets the tap handle for all the server
  396. // transport to be created. Only one can be installed.
  397. //
  398. // # Experimental
  399. //
  400. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  401. // later release.
  402. func InTapHandle(h tap.ServerInHandle) ServerOption {
  403. return newFuncServerOption(func(o *serverOptions) {
  404. if o.inTapHandle != nil {
  405. panic("The tap handle was already set and may not be reset.")
  406. }
  407. o.inTapHandle = h
  408. })
  409. }
  410. // StatsHandler returns a ServerOption that sets the stats handler for the server.
  411. func StatsHandler(h stats.Handler) ServerOption {
  412. return newFuncServerOption(func(o *serverOptions) {
  413. if h == nil {
  414. logger.Error("ignoring nil parameter in grpc.StatsHandler ServerOption")
  415. // Do not allow a nil stats handler, which would otherwise cause
  416. // panics.
  417. return
  418. }
  419. o.statsHandlers = append(o.statsHandlers, h)
  420. })
  421. }
  422. // binaryLogger returns a ServerOption that can set the binary logger for the
  423. // server.
  424. func binaryLogger(bl binarylog.Logger) ServerOption {
  425. return newFuncServerOption(func(o *serverOptions) {
  426. o.binaryLogger = bl
  427. })
  428. }
  429. // UnknownServiceHandler returns a ServerOption that allows for adding a custom
  430. // unknown service handler. The provided method is a bidi-streaming RPC service
  431. // handler that will be invoked instead of returning the "unimplemented" gRPC
  432. // error whenever a request is received for an unregistered service or method.
  433. // The handling function and stream interceptor (if set) have full access to
  434. // the ServerStream, including its Context.
  435. func UnknownServiceHandler(streamHandler StreamHandler) ServerOption {
  436. return newFuncServerOption(func(o *serverOptions) {
  437. o.unknownStreamDesc = &StreamDesc{
  438. StreamName: "unknown_service_handler",
  439. Handler: streamHandler,
  440. // We need to assume that the users of the streamHandler will want to use both.
  441. ClientStreams: true,
  442. ServerStreams: true,
  443. }
  444. })
  445. }
  446. // ConnectionTimeout returns a ServerOption that sets the timeout for
  447. // connection establishment (up to and including HTTP/2 handshaking) for all
  448. // new connections. If this is not set, the default is 120 seconds. A zero or
  449. // negative value will result in an immediate timeout.
  450. //
  451. // # Experimental
  452. //
  453. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  454. // later release.
  455. func ConnectionTimeout(d time.Duration) ServerOption {
  456. return newFuncServerOption(func(o *serverOptions) {
  457. o.connectionTimeout = d
  458. })
  459. }
  460. // MaxHeaderListSize returns a ServerOption that sets the max (uncompressed) size
  461. // of header list that the server is prepared to accept.
  462. func MaxHeaderListSize(s uint32) ServerOption {
  463. return newFuncServerOption(func(o *serverOptions) {
  464. o.maxHeaderListSize = &s
  465. })
  466. }
  467. // HeaderTableSize returns a ServerOption that sets the size of dynamic
  468. // header table for stream.
  469. //
  470. // # Experimental
  471. //
  472. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  473. // later release.
  474. func HeaderTableSize(s uint32) ServerOption {
  475. return newFuncServerOption(func(o *serverOptions) {
  476. o.headerTableSize = &s
  477. })
  478. }
  479. // NumStreamWorkers returns a ServerOption that sets the number of worker
  480. // goroutines that should be used to process incoming streams. Setting this to
  481. // zero (default) will disable workers and spawn a new goroutine for each
  482. // stream.
  483. //
  484. // # Experimental
  485. //
  486. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  487. // later release.
  488. func NumStreamWorkers(numServerWorkers uint32) ServerOption {
  489. // TODO: If/when this API gets stabilized (i.e. stream workers become the
  490. // only way streams are processed), change the behavior of the zero value to
  491. // a sane default. Preliminary experiments suggest that a value equal to the
  492. // number of CPUs available is most performant; requires thorough testing.
  493. return newFuncServerOption(func(o *serverOptions) {
  494. o.numServerWorkers = numServerWorkers
  495. })
  496. }
  497. // serverWorkerResetThreshold defines how often the stack must be reset. Every
  498. // N requests, by spawning a new goroutine in its place, a worker can reset its
  499. // stack so that large stacks don't live in memory forever. 2^16 should allow
  500. // each goroutine stack to live for at least a few seconds in a typical
  501. // workload (assuming a QPS of a few thousand requests/sec).
  502. const serverWorkerResetThreshold = 1 << 16
  503. // serverWorkers blocks on a *transport.Stream channel forever and waits for
  504. // data to be fed by serveStreams. This allows different requests to be
  505. // processed by the same goroutine, removing the need for expensive stack
  506. // re-allocations (see the runtime.morestack problem [1]).
  507. //
  508. // [1] https://github.com/golang/go/issues/18138
  509. func (s *Server) serverWorker(ch chan *serverWorkerData) {
  510. // To make sure all server workers don't reset at the same time, choose a
  511. // random number of iterations before resetting.
  512. threshold := serverWorkerResetThreshold + grpcrand.Intn(serverWorkerResetThreshold)
  513. for completed := 0; completed < threshold; completed++ {
  514. data, ok := <-ch
  515. if !ok {
  516. return
  517. }
  518. s.handleStream(data.st, data.stream, s.traceInfo(data.st, data.stream))
  519. data.wg.Done()
  520. }
  521. go s.serverWorker(ch)
  522. }
  523. // initServerWorkers creates worker goroutines and channels to process incoming
  524. // connections to reduce the time spent overall on runtime.morestack.
  525. func (s *Server) initServerWorkers() {
  526. s.serverWorkerChannels = make([]chan *serverWorkerData, s.opts.numServerWorkers)
  527. for i := uint32(0); i < s.opts.numServerWorkers; i++ {
  528. s.serverWorkerChannels[i] = make(chan *serverWorkerData)
  529. go s.serverWorker(s.serverWorkerChannels[i])
  530. }
  531. }
  532. func (s *Server) stopServerWorkers() {
  533. for i := uint32(0); i < s.opts.numServerWorkers; i++ {
  534. close(s.serverWorkerChannels[i])
  535. }
  536. }
  537. // NewServer creates a gRPC server which has no service registered and has not
  538. // started to accept requests yet.
  539. func NewServer(opt ...ServerOption) *Server {
  540. opts := defaultServerOptions
  541. for _, o := range extraServerOptions {
  542. o.apply(&opts)
  543. }
  544. for _, o := range opt {
  545. o.apply(&opts)
  546. }
  547. s := &Server{
  548. lis: make(map[net.Listener]bool),
  549. opts: opts,
  550. conns: make(map[string]map[transport.ServerTransport]bool),
  551. services: make(map[string]*serviceInfo),
  552. quit: grpcsync.NewEvent(),
  553. done: grpcsync.NewEvent(),
  554. czData: new(channelzData),
  555. }
  556. chainUnaryServerInterceptors(s)
  557. chainStreamServerInterceptors(s)
  558. s.cv = sync.NewCond(&s.mu)
  559. if EnableTracing {
  560. _, file, line, _ := runtime.Caller(1)
  561. s.events = trace.NewEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line))
  562. }
  563. if s.opts.numServerWorkers > 0 {
  564. s.initServerWorkers()
  565. }
  566. s.channelzID = channelz.RegisterServer(&channelzServer{s}, "")
  567. channelz.Info(logger, s.channelzID, "Server created")
  568. return s
  569. }
  570. // printf records an event in s's event log, unless s has been stopped.
  571. // REQUIRES s.mu is held.
  572. func (s *Server) printf(format string, a ...interface{}) {
  573. if s.events != nil {
  574. s.events.Printf(format, a...)
  575. }
  576. }
  577. // errorf records an error in s's event log, unless s has been stopped.
  578. // REQUIRES s.mu is held.
  579. func (s *Server) errorf(format string, a ...interface{}) {
  580. if s.events != nil {
  581. s.events.Errorf(format, a...)
  582. }
  583. }
  584. // ServiceRegistrar wraps a single method that supports service registration. It
  585. // enables users to pass concrete types other than grpc.Server to the service
  586. // registration methods exported by the IDL generated code.
  587. type ServiceRegistrar interface {
  588. // RegisterService registers a service and its implementation to the
  589. // concrete type implementing this interface. It may not be called
  590. // once the server has started serving.
  591. // desc describes the service and its methods and handlers. impl is the
  592. // service implementation which is passed to the method handlers.
  593. RegisterService(desc *ServiceDesc, impl interface{})
  594. }
  595. // RegisterService registers a service and its implementation to the gRPC
  596. // server. It is called from the IDL generated code. This must be called before
  597. // invoking Serve. If ss is non-nil (for legacy code), its type is checked to
  598. // ensure it implements sd.HandlerType.
  599. func (s *Server) RegisterService(sd *ServiceDesc, ss interface{}) {
  600. if ss != nil {
  601. ht := reflect.TypeOf(sd.HandlerType).Elem()
  602. st := reflect.TypeOf(ss)
  603. if !st.Implements(ht) {
  604. logger.Fatalf("grpc: Server.RegisterService found the handler of type %v that does not satisfy %v", st, ht)
  605. }
  606. }
  607. s.register(sd, ss)
  608. }
  609. func (s *Server) register(sd *ServiceDesc, ss interface{}) {
  610. s.mu.Lock()
  611. defer s.mu.Unlock()
  612. s.printf("RegisterService(%q)", sd.ServiceName)
  613. if s.serve {
  614. logger.Fatalf("grpc: Server.RegisterService after Server.Serve for %q", sd.ServiceName)
  615. }
  616. if _, ok := s.services[sd.ServiceName]; ok {
  617. logger.Fatalf("grpc: Server.RegisterService found duplicate service registration for %q", sd.ServiceName)
  618. }
  619. info := &serviceInfo{
  620. serviceImpl: ss,
  621. methods: make(map[string]*MethodDesc),
  622. streams: make(map[string]*StreamDesc),
  623. mdata: sd.Metadata,
  624. }
  625. for i := range sd.Methods {
  626. d := &sd.Methods[i]
  627. info.methods[d.MethodName] = d
  628. }
  629. for i := range sd.Streams {
  630. d := &sd.Streams[i]
  631. info.streams[d.StreamName] = d
  632. }
  633. s.services[sd.ServiceName] = info
  634. }
  635. // MethodInfo contains the information of an RPC including its method name and type.
  636. type MethodInfo struct {
  637. // Name is the method name only, without the service name or package name.
  638. Name string
  639. // IsClientStream indicates whether the RPC is a client streaming RPC.
  640. IsClientStream bool
  641. // IsServerStream indicates whether the RPC is a server streaming RPC.
  642. IsServerStream bool
  643. }
  644. // ServiceInfo contains unary RPC method info, streaming RPC method info and metadata for a service.
  645. type ServiceInfo struct {
  646. Methods []MethodInfo
  647. // Metadata is the metadata specified in ServiceDesc when registering service.
  648. Metadata interface{}
  649. }
  650. // GetServiceInfo returns a map from service names to ServiceInfo.
  651. // Service names include the package names, in the form of <package>.<service>.
  652. func (s *Server) GetServiceInfo() map[string]ServiceInfo {
  653. ret := make(map[string]ServiceInfo)
  654. for n, srv := range s.services {
  655. methods := make([]MethodInfo, 0, len(srv.methods)+len(srv.streams))
  656. for m := range srv.methods {
  657. methods = append(methods, MethodInfo{
  658. Name: m,
  659. IsClientStream: false,
  660. IsServerStream: false,
  661. })
  662. }
  663. for m, d := range srv.streams {
  664. methods = append(methods, MethodInfo{
  665. Name: m,
  666. IsClientStream: d.ClientStreams,
  667. IsServerStream: d.ServerStreams,
  668. })
  669. }
  670. ret[n] = ServiceInfo{
  671. Methods: methods,
  672. Metadata: srv.mdata,
  673. }
  674. }
  675. return ret
  676. }
  677. // ErrServerStopped indicates that the operation is now illegal because of
  678. // the server being stopped.
  679. var ErrServerStopped = errors.New("grpc: the server has been stopped")
  680. type listenSocket struct {
  681. net.Listener
  682. channelzID *channelz.Identifier
  683. }
  684. func (l *listenSocket) ChannelzMetric() *channelz.SocketInternalMetric {
  685. return &channelz.SocketInternalMetric{
  686. SocketOptions: channelz.GetSocketOption(l.Listener),
  687. LocalAddr: l.Listener.Addr(),
  688. }
  689. }
  690. func (l *listenSocket) Close() error {
  691. err := l.Listener.Close()
  692. channelz.RemoveEntry(l.channelzID)
  693. channelz.Info(logger, l.channelzID, "ListenSocket deleted")
  694. return err
  695. }
  696. // Serve accepts incoming connections on the listener lis, creating a new
  697. // ServerTransport and service goroutine for each. The service goroutines
  698. // read gRPC requests and then call the registered handlers to reply to them.
  699. // Serve returns when lis.Accept fails with fatal errors. lis will be closed when
  700. // this method returns.
  701. // Serve will return a non-nil error unless Stop or GracefulStop is called.
  702. func (s *Server) Serve(lis net.Listener) error {
  703. s.mu.Lock()
  704. s.printf("serving")
  705. s.serve = true
  706. if s.lis == nil {
  707. // Serve called after Stop or GracefulStop.
  708. s.mu.Unlock()
  709. lis.Close()
  710. return ErrServerStopped
  711. }
  712. s.serveWG.Add(1)
  713. defer func() {
  714. s.serveWG.Done()
  715. if s.quit.HasFired() {
  716. // Stop or GracefulStop called; block until done and return nil.
  717. <-s.done.Done()
  718. }
  719. }()
  720. ls := &listenSocket{Listener: lis}
  721. s.lis[ls] = true
  722. defer func() {
  723. s.mu.Lock()
  724. if s.lis != nil && s.lis[ls] {
  725. ls.Close()
  726. delete(s.lis, ls)
  727. }
  728. s.mu.Unlock()
  729. }()
  730. var err error
  731. ls.channelzID, err = channelz.RegisterListenSocket(ls, s.channelzID, lis.Addr().String())
  732. if err != nil {
  733. s.mu.Unlock()
  734. return err
  735. }
  736. s.mu.Unlock()
  737. channelz.Info(logger, ls.channelzID, "ListenSocket created")
  738. var tempDelay time.Duration // how long to sleep on accept failure
  739. for {
  740. rawConn, err := lis.Accept()
  741. if err != nil {
  742. if ne, ok := err.(interface {
  743. Temporary() bool
  744. }); ok && ne.Temporary() {
  745. if tempDelay == 0 {
  746. tempDelay = 5 * time.Millisecond
  747. } else {
  748. tempDelay *= 2
  749. }
  750. if max := 1 * time.Second; tempDelay > max {
  751. tempDelay = max
  752. }
  753. s.mu.Lock()
  754. s.printf("Accept error: %v; retrying in %v", err, tempDelay)
  755. s.mu.Unlock()
  756. timer := time.NewTimer(tempDelay)
  757. select {
  758. case <-timer.C:
  759. case <-s.quit.Done():
  760. timer.Stop()
  761. return nil
  762. }
  763. continue
  764. }
  765. s.mu.Lock()
  766. s.printf("done serving; Accept = %v", err)
  767. s.mu.Unlock()
  768. if s.quit.HasFired() {
  769. return nil
  770. }
  771. return err
  772. }
  773. tempDelay = 0
  774. // Start a new goroutine to deal with rawConn so we don't stall this Accept
  775. // loop goroutine.
  776. //
  777. // Make sure we account for the goroutine so GracefulStop doesn't nil out
  778. // s.conns before this conn can be added.
  779. s.serveWG.Add(1)
  780. go func() {
  781. s.handleRawConn(lis.Addr().String(), rawConn)
  782. s.serveWG.Done()
  783. }()
  784. }
  785. }
  786. // handleRawConn forks a goroutine to handle a just-accepted connection that
  787. // has not had any I/O performed on it yet.
  788. func (s *Server) handleRawConn(lisAddr string, rawConn net.Conn) {
  789. if s.quit.HasFired() {
  790. rawConn.Close()
  791. return
  792. }
  793. rawConn.SetDeadline(time.Now().Add(s.opts.connectionTimeout))
  794. // Finish handshaking (HTTP2)
  795. st := s.newHTTP2Transport(rawConn)
  796. rawConn.SetDeadline(time.Time{})
  797. if st == nil {
  798. return
  799. }
  800. if !s.addConn(lisAddr, st) {
  801. return
  802. }
  803. go func() {
  804. s.serveStreams(st)
  805. s.removeConn(lisAddr, st)
  806. }()
  807. }
  808. func (s *Server) drainServerTransports(addr string) {
  809. s.mu.Lock()
  810. conns := s.conns[addr]
  811. for st := range conns {
  812. st.Drain()
  813. }
  814. s.mu.Unlock()
  815. }
  816. // newHTTP2Transport sets up a http/2 transport (using the
  817. // gRPC http2 server transport in transport/http2_server.go).
  818. func (s *Server) newHTTP2Transport(c net.Conn) transport.ServerTransport {
  819. config := &transport.ServerConfig{
  820. MaxStreams: s.opts.maxConcurrentStreams,
  821. ConnectionTimeout: s.opts.connectionTimeout,
  822. Credentials: s.opts.creds,
  823. InTapHandle: s.opts.inTapHandle,
  824. StatsHandlers: s.opts.statsHandlers,
  825. KeepaliveParams: s.opts.keepaliveParams,
  826. KeepalivePolicy: s.opts.keepalivePolicy,
  827. InitialWindowSize: s.opts.initialWindowSize,
  828. InitialConnWindowSize: s.opts.initialConnWindowSize,
  829. WriteBufferSize: s.opts.writeBufferSize,
  830. ReadBufferSize: s.opts.readBufferSize,
  831. ChannelzParentID: s.channelzID,
  832. MaxHeaderListSize: s.opts.maxHeaderListSize,
  833. HeaderTableSize: s.opts.headerTableSize,
  834. }
  835. st, err := transport.NewServerTransport(c, config)
  836. if err != nil {
  837. s.mu.Lock()
  838. s.errorf("NewServerTransport(%q) failed: %v", c.RemoteAddr(), err)
  839. s.mu.Unlock()
  840. // ErrConnDispatched means that the connection was dispatched away from
  841. // gRPC; those connections should be left open.
  842. if err != credentials.ErrConnDispatched {
  843. // Don't log on ErrConnDispatched and io.EOF to prevent log spam.
  844. if err != io.EOF {
  845. channelz.Info(logger, s.channelzID, "grpc: Server.Serve failed to create ServerTransport: ", err)
  846. }
  847. c.Close()
  848. }
  849. return nil
  850. }
  851. return st
  852. }
  853. func (s *Server) serveStreams(st transport.ServerTransport) {
  854. defer st.Close()
  855. var wg sync.WaitGroup
  856. var roundRobinCounter uint32
  857. st.HandleStreams(func(stream *transport.Stream) {
  858. wg.Add(1)
  859. if s.opts.numServerWorkers > 0 {
  860. data := &serverWorkerData{st: st, wg: &wg, stream: stream}
  861. select {
  862. case s.serverWorkerChannels[atomic.AddUint32(&roundRobinCounter, 1)%s.opts.numServerWorkers] <- data:
  863. default:
  864. // If all stream workers are busy, fallback to the default code path.
  865. go func() {
  866. s.handleStream(st, stream, s.traceInfo(st, stream))
  867. wg.Done()
  868. }()
  869. }
  870. } else {
  871. go func() {
  872. defer wg.Done()
  873. s.handleStream(st, stream, s.traceInfo(st, stream))
  874. }()
  875. }
  876. }, func(ctx context.Context, method string) context.Context {
  877. if !EnableTracing {
  878. return ctx
  879. }
  880. tr := trace.New("grpc.Recv."+methodFamily(method), method)
  881. return trace.NewContext(ctx, tr)
  882. })
  883. wg.Wait()
  884. }
  885. var _ http.Handler = (*Server)(nil)
  886. // ServeHTTP implements the Go standard library's http.Handler
  887. // interface by responding to the gRPC request r, by looking up
  888. // the requested gRPC method in the gRPC server s.
  889. //
  890. // The provided HTTP request must have arrived on an HTTP/2
  891. // connection. When using the Go standard library's server,
  892. // practically this means that the Request must also have arrived
  893. // over TLS.
  894. //
  895. // To share one port (such as 443 for https) between gRPC and an
  896. // existing http.Handler, use a root http.Handler such as:
  897. //
  898. // if r.ProtoMajor == 2 && strings.HasPrefix(
  899. // r.Header.Get("Content-Type"), "application/grpc") {
  900. // grpcServer.ServeHTTP(w, r)
  901. // } else {
  902. // yourMux.ServeHTTP(w, r)
  903. // }
  904. //
  905. // Note that ServeHTTP uses Go's HTTP/2 server implementation which is totally
  906. // separate from grpc-go's HTTP/2 server. Performance and features may vary
  907. // between the two paths. ServeHTTP does not support some gRPC features
  908. // available through grpc-go's HTTP/2 server.
  909. //
  910. // # Experimental
  911. //
  912. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  913. // later release.
  914. func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  915. st, err := transport.NewServerHandlerTransport(w, r, s.opts.statsHandlers)
  916. if err != nil {
  917. http.Error(w, err.Error(), http.StatusInternalServerError)
  918. return
  919. }
  920. if !s.addConn(listenerAddressForServeHTTP, st) {
  921. return
  922. }
  923. defer s.removeConn(listenerAddressForServeHTTP, st)
  924. s.serveStreams(st)
  925. }
  926. // traceInfo returns a traceInfo and associates it with stream, if tracing is enabled.
  927. // If tracing is not enabled, it returns nil.
  928. func (s *Server) traceInfo(st transport.ServerTransport, stream *transport.Stream) (trInfo *traceInfo) {
  929. if !EnableTracing {
  930. return nil
  931. }
  932. tr, ok := trace.FromContext(stream.Context())
  933. if !ok {
  934. return nil
  935. }
  936. trInfo = &traceInfo{
  937. tr: tr,
  938. firstLine: firstLine{
  939. client: false,
  940. remoteAddr: st.RemoteAddr(),
  941. },
  942. }
  943. if dl, ok := stream.Context().Deadline(); ok {
  944. trInfo.firstLine.deadline = time.Until(dl)
  945. }
  946. return trInfo
  947. }
  948. func (s *Server) addConn(addr string, st transport.ServerTransport) bool {
  949. s.mu.Lock()
  950. defer s.mu.Unlock()
  951. if s.conns == nil {
  952. st.Close()
  953. return false
  954. }
  955. if s.drain {
  956. // Transport added after we drained our existing conns: drain it
  957. // immediately.
  958. st.Drain()
  959. }
  960. if s.conns[addr] == nil {
  961. // Create a map entry if this is the first connection on this listener.
  962. s.conns[addr] = make(map[transport.ServerTransport]bool)
  963. }
  964. s.conns[addr][st] = true
  965. return true
  966. }
  967. func (s *Server) removeConn(addr string, st transport.ServerTransport) {
  968. s.mu.Lock()
  969. defer s.mu.Unlock()
  970. conns := s.conns[addr]
  971. if conns != nil {
  972. delete(conns, st)
  973. if len(conns) == 0 {
  974. // If the last connection for this address is being removed, also
  975. // remove the map entry corresponding to the address. This is used
  976. // in GracefulStop() when waiting for all connections to be closed.
  977. delete(s.conns, addr)
  978. }
  979. s.cv.Broadcast()
  980. }
  981. }
  982. func (s *Server) channelzMetric() *channelz.ServerInternalMetric {
  983. return &channelz.ServerInternalMetric{
  984. CallsStarted: atomic.LoadInt64(&s.czData.callsStarted),
  985. CallsSucceeded: atomic.LoadInt64(&s.czData.callsSucceeded),
  986. CallsFailed: atomic.LoadInt64(&s.czData.callsFailed),
  987. LastCallStartedTimestamp: time.Unix(0, atomic.LoadInt64(&s.czData.lastCallStartedTime)),
  988. }
  989. }
  990. func (s *Server) incrCallsStarted() {
  991. atomic.AddInt64(&s.czData.callsStarted, 1)
  992. atomic.StoreInt64(&s.czData.lastCallStartedTime, time.Now().UnixNano())
  993. }
  994. func (s *Server) incrCallsSucceeded() {
  995. atomic.AddInt64(&s.czData.callsSucceeded, 1)
  996. }
  997. func (s *Server) incrCallsFailed() {
  998. atomic.AddInt64(&s.czData.callsFailed, 1)
  999. }
  1000. func (s *Server) sendResponse(t transport.ServerTransport, stream *transport.Stream, msg interface{}, cp Compressor, opts *transport.Options, comp encoding.Compressor) error {
  1001. data, err := encode(s.getCodec(stream.ContentSubtype()), msg)
  1002. if err != nil {
  1003. channelz.Error(logger, s.channelzID, "grpc: server failed to encode response: ", err)
  1004. return err
  1005. }
  1006. compData, err := compress(data, cp, comp)
  1007. if err != nil {
  1008. channelz.Error(logger, s.channelzID, "grpc: server failed to compress response: ", err)
  1009. return err
  1010. }
  1011. hdr, payload := msgHeader(data, compData)
  1012. // TODO(dfawley): should we be checking len(data) instead?
  1013. if len(payload) > s.opts.maxSendMessageSize {
  1014. return status.Errorf(codes.ResourceExhausted, "grpc: trying to send message larger than max (%d vs. %d)", len(payload), s.opts.maxSendMessageSize)
  1015. }
  1016. err = t.Write(stream, hdr, payload, opts)
  1017. if err == nil {
  1018. for _, sh := range s.opts.statsHandlers {
  1019. sh.HandleRPC(stream.Context(), outPayload(false, msg, data, payload, time.Now()))
  1020. }
  1021. }
  1022. return err
  1023. }
  1024. // chainUnaryServerInterceptors chains all unary server interceptors into one.
  1025. func chainUnaryServerInterceptors(s *Server) {
  1026. // Prepend opts.unaryInt to the chaining interceptors if it exists, since unaryInt will
  1027. // be executed before any other chained interceptors.
  1028. interceptors := s.opts.chainUnaryInts
  1029. if s.opts.unaryInt != nil {
  1030. interceptors = append([]UnaryServerInterceptor{s.opts.unaryInt}, s.opts.chainUnaryInts...)
  1031. }
  1032. var chainedInt UnaryServerInterceptor
  1033. if len(interceptors) == 0 {
  1034. chainedInt = nil
  1035. } else if len(interceptors) == 1 {
  1036. chainedInt = interceptors[0]
  1037. } else {
  1038. chainedInt = chainUnaryInterceptors(interceptors)
  1039. }
  1040. s.opts.unaryInt = chainedInt
  1041. }
  1042. func chainUnaryInterceptors(interceptors []UnaryServerInterceptor) UnaryServerInterceptor {
  1043. return func(ctx context.Context, req interface{}, info *UnaryServerInfo, handler UnaryHandler) (interface{}, error) {
  1044. // the struct ensures the variables are allocated together, rather than separately, since we
  1045. // know they should be garbage collected together. This saves 1 allocation and decreases
  1046. // time/call by about 10% on the microbenchmark.
  1047. var state struct {
  1048. i int
  1049. next UnaryHandler
  1050. }
  1051. state.next = func(ctx context.Context, req interface{}) (interface{}, error) {
  1052. if state.i == len(interceptors)-1 {
  1053. return interceptors[state.i](ctx, req, info, handler)
  1054. }
  1055. state.i++
  1056. return interceptors[state.i-1](ctx, req, info, state.next)
  1057. }
  1058. return state.next(ctx, req)
  1059. }
  1060. }
  1061. func (s *Server) processUnaryRPC(t transport.ServerTransport, stream *transport.Stream, info *serviceInfo, md *MethodDesc, trInfo *traceInfo) (err error) {
  1062. shs := s.opts.statsHandlers
  1063. if len(shs) != 0 || trInfo != nil || channelz.IsOn() {
  1064. if channelz.IsOn() {
  1065. s.incrCallsStarted()
  1066. }
  1067. var statsBegin *stats.Begin
  1068. for _, sh := range shs {
  1069. beginTime := time.Now()
  1070. statsBegin = &stats.Begin{
  1071. BeginTime: beginTime,
  1072. IsClientStream: false,
  1073. IsServerStream: false,
  1074. }
  1075. sh.HandleRPC(stream.Context(), statsBegin)
  1076. }
  1077. if trInfo != nil {
  1078. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  1079. }
  1080. // The deferred error handling for tracing, stats handler and channelz are
  1081. // combined into one function to reduce stack usage -- a defer takes ~56-64
  1082. // bytes on the stack, so overflowing the stack will require a stack
  1083. // re-allocation, which is expensive.
  1084. //
  1085. // To maintain behavior similar to separate deferred statements, statements
  1086. // should be executed in the reverse order. That is, tracing first, stats
  1087. // handler second, and channelz last. Note that panics *within* defers will
  1088. // lead to different behavior, but that's an acceptable compromise; that
  1089. // would be undefined behavior territory anyway.
  1090. defer func() {
  1091. if trInfo != nil {
  1092. if err != nil && err != io.EOF {
  1093. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  1094. trInfo.tr.SetError()
  1095. }
  1096. trInfo.tr.Finish()
  1097. }
  1098. for _, sh := range shs {
  1099. end := &stats.End{
  1100. BeginTime: statsBegin.BeginTime,
  1101. EndTime: time.Now(),
  1102. }
  1103. if err != nil && err != io.EOF {
  1104. end.Error = toRPCErr(err)
  1105. }
  1106. sh.HandleRPC(stream.Context(), end)
  1107. }
  1108. if channelz.IsOn() {
  1109. if err != nil && err != io.EOF {
  1110. s.incrCallsFailed()
  1111. } else {
  1112. s.incrCallsSucceeded()
  1113. }
  1114. }
  1115. }()
  1116. }
  1117. var binlogs []binarylog.MethodLogger
  1118. if ml := binarylog.GetMethodLogger(stream.Method()); ml != nil {
  1119. binlogs = append(binlogs, ml)
  1120. }
  1121. if s.opts.binaryLogger != nil {
  1122. if ml := s.opts.binaryLogger.GetMethodLogger(stream.Method()); ml != nil {
  1123. binlogs = append(binlogs, ml)
  1124. }
  1125. }
  1126. if len(binlogs) != 0 {
  1127. ctx := stream.Context()
  1128. md, _ := metadata.FromIncomingContext(ctx)
  1129. logEntry := &binarylog.ClientHeader{
  1130. Header: md,
  1131. MethodName: stream.Method(),
  1132. PeerAddr: nil,
  1133. }
  1134. if deadline, ok := ctx.Deadline(); ok {
  1135. logEntry.Timeout = time.Until(deadline)
  1136. if logEntry.Timeout < 0 {
  1137. logEntry.Timeout = 0
  1138. }
  1139. }
  1140. if a := md[":authority"]; len(a) > 0 {
  1141. logEntry.Authority = a[0]
  1142. }
  1143. if peer, ok := peer.FromContext(ctx); ok {
  1144. logEntry.PeerAddr = peer.Addr
  1145. }
  1146. for _, binlog := range binlogs {
  1147. binlog.Log(logEntry)
  1148. }
  1149. }
  1150. // comp and cp are used for compression. decomp and dc are used for
  1151. // decompression. If comp and decomp are both set, they are the same;
  1152. // however they are kept separate to ensure that at most one of the
  1153. // compressor/decompressor variable pairs are set for use later.
  1154. var comp, decomp encoding.Compressor
  1155. var cp Compressor
  1156. var dc Decompressor
  1157. // If dc is set and matches the stream's compression, use it. Otherwise, try
  1158. // to find a matching registered compressor for decomp.
  1159. if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc {
  1160. dc = s.opts.dc
  1161. } else if rc != "" && rc != encoding.Identity {
  1162. decomp = encoding.GetCompressor(rc)
  1163. if decomp == nil {
  1164. st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc)
  1165. t.WriteStatus(stream, st)
  1166. return st.Err()
  1167. }
  1168. }
  1169. // If cp is set, use it. Otherwise, attempt to compress the response using
  1170. // the incoming message compression method.
  1171. //
  1172. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
  1173. if s.opts.cp != nil {
  1174. cp = s.opts.cp
  1175. stream.SetSendCompress(cp.Type())
  1176. } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity {
  1177. // Legacy compressor not specified; attempt to respond with same encoding.
  1178. comp = encoding.GetCompressor(rc)
  1179. if comp != nil {
  1180. stream.SetSendCompress(rc)
  1181. }
  1182. }
  1183. var payInfo *payloadInfo
  1184. if len(shs) != 0 || len(binlogs) != 0 {
  1185. payInfo = &payloadInfo{}
  1186. }
  1187. d, err := recvAndDecompress(&parser{r: stream}, stream, dc, s.opts.maxReceiveMessageSize, payInfo, decomp)
  1188. if err != nil {
  1189. if e := t.WriteStatus(stream, status.Convert(err)); e != nil {
  1190. channelz.Warningf(logger, s.channelzID, "grpc: Server.processUnaryRPC failed to write status %v", e)
  1191. }
  1192. return err
  1193. }
  1194. if channelz.IsOn() {
  1195. t.IncrMsgRecv()
  1196. }
  1197. df := func(v interface{}) error {
  1198. if err := s.getCodec(stream.ContentSubtype()).Unmarshal(d, v); err != nil {
  1199. return status.Errorf(codes.Internal, "grpc: error unmarshalling request: %v", err)
  1200. }
  1201. for _, sh := range shs {
  1202. sh.HandleRPC(stream.Context(), &stats.InPayload{
  1203. RecvTime: time.Now(),
  1204. Payload: v,
  1205. WireLength: payInfo.wireLength + headerLen,
  1206. Data: d,
  1207. Length: len(d),
  1208. })
  1209. }
  1210. if len(binlogs) != 0 {
  1211. cm := &binarylog.ClientMessage{
  1212. Message: d,
  1213. }
  1214. for _, binlog := range binlogs {
  1215. binlog.Log(cm)
  1216. }
  1217. }
  1218. if trInfo != nil {
  1219. trInfo.tr.LazyLog(&payload{sent: false, msg: v}, true)
  1220. }
  1221. return nil
  1222. }
  1223. ctx := NewContextWithServerTransportStream(stream.Context(), stream)
  1224. reply, appErr := md.Handler(info.serviceImpl, ctx, df, s.opts.unaryInt)
  1225. if appErr != nil {
  1226. appStatus, ok := status.FromError(appErr)
  1227. if !ok {
  1228. // Convert non-status application error to a status error with code
  1229. // Unknown, but handle context errors specifically.
  1230. appStatus = status.FromContextError(appErr)
  1231. appErr = appStatus.Err()
  1232. }
  1233. if trInfo != nil {
  1234. trInfo.tr.LazyLog(stringer(appStatus.Message()), true)
  1235. trInfo.tr.SetError()
  1236. }
  1237. if e := t.WriteStatus(stream, appStatus); e != nil {
  1238. channelz.Warningf(logger, s.channelzID, "grpc: Server.processUnaryRPC failed to write status: %v", e)
  1239. }
  1240. if len(binlogs) != 0 {
  1241. if h, _ := stream.Header(); h.Len() > 0 {
  1242. // Only log serverHeader if there was header. Otherwise it can
  1243. // be trailer only.
  1244. sh := &binarylog.ServerHeader{
  1245. Header: h,
  1246. }
  1247. for _, binlog := range binlogs {
  1248. binlog.Log(sh)
  1249. }
  1250. }
  1251. st := &binarylog.ServerTrailer{
  1252. Trailer: stream.Trailer(),
  1253. Err: appErr,
  1254. }
  1255. for _, binlog := range binlogs {
  1256. binlog.Log(st)
  1257. }
  1258. }
  1259. return appErr
  1260. }
  1261. if trInfo != nil {
  1262. trInfo.tr.LazyLog(stringer("OK"), false)
  1263. }
  1264. opts := &transport.Options{Last: true}
  1265. if err := s.sendResponse(t, stream, reply, cp, opts, comp); err != nil {
  1266. if err == io.EOF {
  1267. // The entire stream is done (for unary RPC only).
  1268. return err
  1269. }
  1270. if sts, ok := status.FromError(err); ok {
  1271. if e := t.WriteStatus(stream, sts); e != nil {
  1272. channelz.Warningf(logger, s.channelzID, "grpc: Server.processUnaryRPC failed to write status: %v", e)
  1273. }
  1274. } else {
  1275. switch st := err.(type) {
  1276. case transport.ConnectionError:
  1277. // Nothing to do here.
  1278. default:
  1279. panic(fmt.Sprintf("grpc: Unexpected error (%T) from sendResponse: %v", st, st))
  1280. }
  1281. }
  1282. if len(binlogs) != 0 {
  1283. h, _ := stream.Header()
  1284. sh := &binarylog.ServerHeader{
  1285. Header: h,
  1286. }
  1287. st := &binarylog.ServerTrailer{
  1288. Trailer: stream.Trailer(),
  1289. Err: appErr,
  1290. }
  1291. for _, binlog := range binlogs {
  1292. binlog.Log(sh)
  1293. binlog.Log(st)
  1294. }
  1295. }
  1296. return err
  1297. }
  1298. if len(binlogs) != 0 {
  1299. h, _ := stream.Header()
  1300. sh := &binarylog.ServerHeader{
  1301. Header: h,
  1302. }
  1303. sm := &binarylog.ServerMessage{
  1304. Message: reply,
  1305. }
  1306. for _, binlog := range binlogs {
  1307. binlog.Log(sh)
  1308. binlog.Log(sm)
  1309. }
  1310. }
  1311. if channelz.IsOn() {
  1312. t.IncrMsgSent()
  1313. }
  1314. if trInfo != nil {
  1315. trInfo.tr.LazyLog(&payload{sent: true, msg: reply}, true)
  1316. }
  1317. // TODO: Should we be logging if writing status failed here, like above?
  1318. // Should the logging be in WriteStatus? Should we ignore the WriteStatus
  1319. // error or allow the stats handler to see it?
  1320. err = t.WriteStatus(stream, statusOK)
  1321. if len(binlogs) != 0 {
  1322. st := &binarylog.ServerTrailer{
  1323. Trailer: stream.Trailer(),
  1324. Err: appErr,
  1325. }
  1326. for _, binlog := range binlogs {
  1327. binlog.Log(st)
  1328. }
  1329. }
  1330. return err
  1331. }
  1332. // chainStreamServerInterceptors chains all stream server interceptors into one.
  1333. func chainStreamServerInterceptors(s *Server) {
  1334. // Prepend opts.streamInt to the chaining interceptors if it exists, since streamInt will
  1335. // be executed before any other chained interceptors.
  1336. interceptors := s.opts.chainStreamInts
  1337. if s.opts.streamInt != nil {
  1338. interceptors = append([]StreamServerInterceptor{s.opts.streamInt}, s.opts.chainStreamInts...)
  1339. }
  1340. var chainedInt StreamServerInterceptor
  1341. if len(interceptors) == 0 {
  1342. chainedInt = nil
  1343. } else if len(interceptors) == 1 {
  1344. chainedInt = interceptors[0]
  1345. } else {
  1346. chainedInt = chainStreamInterceptors(interceptors)
  1347. }
  1348. s.opts.streamInt = chainedInt
  1349. }
  1350. func chainStreamInterceptors(interceptors []StreamServerInterceptor) StreamServerInterceptor {
  1351. return func(srv interface{}, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error {
  1352. // the struct ensures the variables are allocated together, rather than separately, since we
  1353. // know they should be garbage collected together. This saves 1 allocation and decreases
  1354. // time/call by about 10% on the microbenchmark.
  1355. var state struct {
  1356. i int
  1357. next StreamHandler
  1358. }
  1359. state.next = func(srv interface{}, ss ServerStream) error {
  1360. if state.i == len(interceptors)-1 {
  1361. return interceptors[state.i](srv, ss, info, handler)
  1362. }
  1363. state.i++
  1364. return interceptors[state.i-1](srv, ss, info, state.next)
  1365. }
  1366. return state.next(srv, ss)
  1367. }
  1368. }
  1369. func (s *Server) processStreamingRPC(t transport.ServerTransport, stream *transport.Stream, info *serviceInfo, sd *StreamDesc, trInfo *traceInfo) (err error) {
  1370. if channelz.IsOn() {
  1371. s.incrCallsStarted()
  1372. }
  1373. shs := s.opts.statsHandlers
  1374. var statsBegin *stats.Begin
  1375. if len(shs) != 0 {
  1376. beginTime := time.Now()
  1377. statsBegin = &stats.Begin{
  1378. BeginTime: beginTime,
  1379. IsClientStream: sd.ClientStreams,
  1380. IsServerStream: sd.ServerStreams,
  1381. }
  1382. for _, sh := range shs {
  1383. sh.HandleRPC(stream.Context(), statsBegin)
  1384. }
  1385. }
  1386. ctx := NewContextWithServerTransportStream(stream.Context(), stream)
  1387. ss := &serverStream{
  1388. ctx: ctx,
  1389. t: t,
  1390. s: stream,
  1391. p: &parser{r: stream},
  1392. codec: s.getCodec(stream.ContentSubtype()),
  1393. maxReceiveMessageSize: s.opts.maxReceiveMessageSize,
  1394. maxSendMessageSize: s.opts.maxSendMessageSize,
  1395. trInfo: trInfo,
  1396. statsHandler: shs,
  1397. }
  1398. if len(shs) != 0 || trInfo != nil || channelz.IsOn() {
  1399. // See comment in processUnaryRPC on defers.
  1400. defer func() {
  1401. if trInfo != nil {
  1402. ss.mu.Lock()
  1403. if err != nil && err != io.EOF {
  1404. ss.trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  1405. ss.trInfo.tr.SetError()
  1406. }
  1407. ss.trInfo.tr.Finish()
  1408. ss.trInfo.tr = nil
  1409. ss.mu.Unlock()
  1410. }
  1411. if len(shs) != 0 {
  1412. end := &stats.End{
  1413. BeginTime: statsBegin.BeginTime,
  1414. EndTime: time.Now(),
  1415. }
  1416. if err != nil && err != io.EOF {
  1417. end.Error = toRPCErr(err)
  1418. }
  1419. for _, sh := range shs {
  1420. sh.HandleRPC(stream.Context(), end)
  1421. }
  1422. }
  1423. if channelz.IsOn() {
  1424. if err != nil && err != io.EOF {
  1425. s.incrCallsFailed()
  1426. } else {
  1427. s.incrCallsSucceeded()
  1428. }
  1429. }
  1430. }()
  1431. }
  1432. if ml := binarylog.GetMethodLogger(stream.Method()); ml != nil {
  1433. ss.binlogs = append(ss.binlogs, ml)
  1434. }
  1435. if s.opts.binaryLogger != nil {
  1436. if ml := s.opts.binaryLogger.GetMethodLogger(stream.Method()); ml != nil {
  1437. ss.binlogs = append(ss.binlogs, ml)
  1438. }
  1439. }
  1440. if len(ss.binlogs) != 0 {
  1441. md, _ := metadata.FromIncomingContext(ctx)
  1442. logEntry := &binarylog.ClientHeader{
  1443. Header: md,
  1444. MethodName: stream.Method(),
  1445. PeerAddr: nil,
  1446. }
  1447. if deadline, ok := ctx.Deadline(); ok {
  1448. logEntry.Timeout = time.Until(deadline)
  1449. if logEntry.Timeout < 0 {
  1450. logEntry.Timeout = 0
  1451. }
  1452. }
  1453. if a := md[":authority"]; len(a) > 0 {
  1454. logEntry.Authority = a[0]
  1455. }
  1456. if peer, ok := peer.FromContext(ss.Context()); ok {
  1457. logEntry.PeerAddr = peer.Addr
  1458. }
  1459. for _, binlog := range ss.binlogs {
  1460. binlog.Log(logEntry)
  1461. }
  1462. }
  1463. // If dc is set and matches the stream's compression, use it. Otherwise, try
  1464. // to find a matching registered compressor for decomp.
  1465. if rc := stream.RecvCompress(); s.opts.dc != nil && s.opts.dc.Type() == rc {
  1466. ss.dc = s.opts.dc
  1467. } else if rc != "" && rc != encoding.Identity {
  1468. ss.decomp = encoding.GetCompressor(rc)
  1469. if ss.decomp == nil {
  1470. st := status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", rc)
  1471. t.WriteStatus(ss.s, st)
  1472. return st.Err()
  1473. }
  1474. }
  1475. // If cp is set, use it. Otherwise, attempt to compress the response using
  1476. // the incoming message compression method.
  1477. //
  1478. // NOTE: this needs to be ahead of all handling, https://github.com/grpc/grpc-go/issues/686.
  1479. if s.opts.cp != nil {
  1480. ss.cp = s.opts.cp
  1481. stream.SetSendCompress(s.opts.cp.Type())
  1482. } else if rc := stream.RecvCompress(); rc != "" && rc != encoding.Identity {
  1483. // Legacy compressor not specified; attempt to respond with same encoding.
  1484. ss.comp = encoding.GetCompressor(rc)
  1485. if ss.comp != nil {
  1486. stream.SetSendCompress(rc)
  1487. }
  1488. }
  1489. ss.ctx = newContextWithRPCInfo(ss.ctx, false, ss.codec, ss.cp, ss.comp)
  1490. if trInfo != nil {
  1491. trInfo.tr.LazyLog(&trInfo.firstLine, false)
  1492. }
  1493. var appErr error
  1494. var server interface{}
  1495. if info != nil {
  1496. server = info.serviceImpl
  1497. }
  1498. if s.opts.streamInt == nil {
  1499. appErr = sd.Handler(server, ss)
  1500. } else {
  1501. info := &StreamServerInfo{
  1502. FullMethod: stream.Method(),
  1503. IsClientStream: sd.ClientStreams,
  1504. IsServerStream: sd.ServerStreams,
  1505. }
  1506. appErr = s.opts.streamInt(server, ss, info, sd.Handler)
  1507. }
  1508. if appErr != nil {
  1509. appStatus, ok := status.FromError(appErr)
  1510. if !ok {
  1511. // Convert non-status application error to a status error with code
  1512. // Unknown, but handle context errors specifically.
  1513. appStatus = status.FromContextError(appErr)
  1514. appErr = appStatus.Err()
  1515. }
  1516. if trInfo != nil {
  1517. ss.mu.Lock()
  1518. ss.trInfo.tr.LazyLog(stringer(appStatus.Message()), true)
  1519. ss.trInfo.tr.SetError()
  1520. ss.mu.Unlock()
  1521. }
  1522. t.WriteStatus(ss.s, appStatus)
  1523. if len(ss.binlogs) != 0 {
  1524. st := &binarylog.ServerTrailer{
  1525. Trailer: ss.s.Trailer(),
  1526. Err: appErr,
  1527. }
  1528. for _, binlog := range ss.binlogs {
  1529. binlog.Log(st)
  1530. }
  1531. }
  1532. // TODO: Should we log an error from WriteStatus here and below?
  1533. return appErr
  1534. }
  1535. if trInfo != nil {
  1536. ss.mu.Lock()
  1537. ss.trInfo.tr.LazyLog(stringer("OK"), false)
  1538. ss.mu.Unlock()
  1539. }
  1540. err = t.WriteStatus(ss.s, statusOK)
  1541. if len(ss.binlogs) != 0 {
  1542. st := &binarylog.ServerTrailer{
  1543. Trailer: ss.s.Trailer(),
  1544. Err: appErr,
  1545. }
  1546. for _, binlog := range ss.binlogs {
  1547. binlog.Log(st)
  1548. }
  1549. }
  1550. return err
  1551. }
  1552. func (s *Server) handleStream(t transport.ServerTransport, stream *transport.Stream, trInfo *traceInfo) {
  1553. sm := stream.Method()
  1554. if sm != "" && sm[0] == '/' {
  1555. sm = sm[1:]
  1556. }
  1557. pos := strings.LastIndex(sm, "/")
  1558. if pos == -1 {
  1559. if trInfo != nil {
  1560. trInfo.tr.LazyLog(&fmtStringer{"Malformed method name %q", []interface{}{sm}}, true)
  1561. trInfo.tr.SetError()
  1562. }
  1563. errDesc := fmt.Sprintf("malformed method name: %q", stream.Method())
  1564. if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil {
  1565. if trInfo != nil {
  1566. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  1567. trInfo.tr.SetError()
  1568. }
  1569. channelz.Warningf(logger, s.channelzID, "grpc: Server.handleStream failed to write status: %v", err)
  1570. }
  1571. if trInfo != nil {
  1572. trInfo.tr.Finish()
  1573. }
  1574. return
  1575. }
  1576. service := sm[:pos]
  1577. method := sm[pos+1:]
  1578. srv, knownService := s.services[service]
  1579. if knownService {
  1580. if md, ok := srv.methods[method]; ok {
  1581. s.processUnaryRPC(t, stream, srv, md, trInfo)
  1582. return
  1583. }
  1584. if sd, ok := srv.streams[method]; ok {
  1585. s.processStreamingRPC(t, stream, srv, sd, trInfo)
  1586. return
  1587. }
  1588. }
  1589. // Unknown service, or known server unknown method.
  1590. if unknownDesc := s.opts.unknownStreamDesc; unknownDesc != nil {
  1591. s.processStreamingRPC(t, stream, nil, unknownDesc, trInfo)
  1592. return
  1593. }
  1594. var errDesc string
  1595. if !knownService {
  1596. errDesc = fmt.Sprintf("unknown service %v", service)
  1597. } else {
  1598. errDesc = fmt.Sprintf("unknown method %v for service %v", method, service)
  1599. }
  1600. if trInfo != nil {
  1601. trInfo.tr.LazyPrintf("%s", errDesc)
  1602. trInfo.tr.SetError()
  1603. }
  1604. if err := t.WriteStatus(stream, status.New(codes.Unimplemented, errDesc)); err != nil {
  1605. if trInfo != nil {
  1606. trInfo.tr.LazyLog(&fmtStringer{"%v", []interface{}{err}}, true)
  1607. trInfo.tr.SetError()
  1608. }
  1609. channelz.Warningf(logger, s.channelzID, "grpc: Server.handleStream failed to write status: %v", err)
  1610. }
  1611. if trInfo != nil {
  1612. trInfo.tr.Finish()
  1613. }
  1614. }
  1615. // The key to save ServerTransportStream in the context.
  1616. type streamKey struct{}
  1617. // NewContextWithServerTransportStream creates a new context from ctx and
  1618. // attaches stream to it.
  1619. //
  1620. // # Experimental
  1621. //
  1622. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  1623. // later release.
  1624. func NewContextWithServerTransportStream(ctx context.Context, stream ServerTransportStream) context.Context {
  1625. return context.WithValue(ctx, streamKey{}, stream)
  1626. }
  1627. // ServerTransportStream is a minimal interface that a transport stream must
  1628. // implement. This can be used to mock an actual transport stream for tests of
  1629. // handler code that use, for example, grpc.SetHeader (which requires some
  1630. // stream to be in context).
  1631. //
  1632. // See also NewContextWithServerTransportStream.
  1633. //
  1634. // # Experimental
  1635. //
  1636. // Notice: This type is EXPERIMENTAL and may be changed or removed in a
  1637. // later release.
  1638. type ServerTransportStream interface {
  1639. Method() string
  1640. SetHeader(md metadata.MD) error
  1641. SendHeader(md metadata.MD) error
  1642. SetTrailer(md metadata.MD) error
  1643. }
  1644. // ServerTransportStreamFromContext returns the ServerTransportStream saved in
  1645. // ctx. Returns nil if the given context has no stream associated with it
  1646. // (which implies it is not an RPC invocation context).
  1647. //
  1648. // # Experimental
  1649. //
  1650. // Notice: This API is EXPERIMENTAL and may be changed or removed in a
  1651. // later release.
  1652. func ServerTransportStreamFromContext(ctx context.Context) ServerTransportStream {
  1653. s, _ := ctx.Value(streamKey{}).(ServerTransportStream)
  1654. return s
  1655. }
  1656. // Stop stops the gRPC server. It immediately closes all open
  1657. // connections and listeners.
  1658. // It cancels all active RPCs on the server side and the corresponding
  1659. // pending RPCs on the client side will get notified by connection
  1660. // errors.
  1661. func (s *Server) Stop() {
  1662. s.quit.Fire()
  1663. defer func() {
  1664. s.serveWG.Wait()
  1665. s.done.Fire()
  1666. }()
  1667. s.channelzRemoveOnce.Do(func() { channelz.RemoveEntry(s.channelzID) })
  1668. s.mu.Lock()
  1669. listeners := s.lis
  1670. s.lis = nil
  1671. conns := s.conns
  1672. s.conns = nil
  1673. // interrupt GracefulStop if Stop and GracefulStop are called concurrently.
  1674. s.cv.Broadcast()
  1675. s.mu.Unlock()
  1676. for lis := range listeners {
  1677. lis.Close()
  1678. }
  1679. for _, cs := range conns {
  1680. for st := range cs {
  1681. st.Close()
  1682. }
  1683. }
  1684. if s.opts.numServerWorkers > 0 {
  1685. s.stopServerWorkers()
  1686. }
  1687. s.mu.Lock()
  1688. if s.events != nil {
  1689. s.events.Finish()
  1690. s.events = nil
  1691. }
  1692. s.mu.Unlock()
  1693. }
  1694. // GracefulStop stops the gRPC server gracefully. It stops the server from
  1695. // accepting new connections and RPCs and blocks until all the pending RPCs are
  1696. // finished.
  1697. func (s *Server) GracefulStop() {
  1698. s.quit.Fire()
  1699. defer s.done.Fire()
  1700. s.channelzRemoveOnce.Do(func() { channelz.RemoveEntry(s.channelzID) })
  1701. s.mu.Lock()
  1702. if s.conns == nil {
  1703. s.mu.Unlock()
  1704. return
  1705. }
  1706. for lis := range s.lis {
  1707. lis.Close()
  1708. }
  1709. s.lis = nil
  1710. if !s.drain {
  1711. for _, conns := range s.conns {
  1712. for st := range conns {
  1713. st.Drain()
  1714. }
  1715. }
  1716. s.drain = true
  1717. }
  1718. // Wait for serving threads to be ready to exit. Only then can we be sure no
  1719. // new conns will be created.
  1720. s.mu.Unlock()
  1721. s.serveWG.Wait()
  1722. s.mu.Lock()
  1723. for len(s.conns) != 0 {
  1724. s.cv.Wait()
  1725. }
  1726. s.conns = nil
  1727. if s.events != nil {
  1728. s.events.Finish()
  1729. s.events = nil
  1730. }
  1731. s.mu.Unlock()
  1732. }
  1733. // contentSubtype must be lowercase
  1734. // cannot return nil
  1735. func (s *Server) getCodec(contentSubtype string) baseCodec {
  1736. if s.opts.codec != nil {
  1737. return s.opts.codec
  1738. }
  1739. if contentSubtype == "" {
  1740. return encoding.GetCodec(proto.Name)
  1741. }
  1742. codec := encoding.GetCodec(contentSubtype)
  1743. if codec == nil {
  1744. return encoding.GetCodec(proto.Name)
  1745. }
  1746. return codec
  1747. }
  1748. // SetHeader sets the header metadata to be sent from the server to the client.
  1749. // The context provided must be the context passed to the server's handler.
  1750. //
  1751. // Streaming RPCs should prefer the SetHeader method of the ServerStream.
  1752. //
  1753. // When called multiple times, all the provided metadata will be merged. All
  1754. // the metadata will be sent out when one of the following happens:
  1755. //
  1756. // - grpc.SendHeader is called, or for streaming handlers, stream.SendHeader.
  1757. // - The first response message is sent. For unary handlers, this occurs when
  1758. // the handler returns; for streaming handlers, this can happen when stream's
  1759. // SendMsg method is called.
  1760. // - An RPC status is sent out (error or success). This occurs when the handler
  1761. // returns.
  1762. //
  1763. // SetHeader will fail if called after any of the events above.
  1764. //
  1765. // The error returned is compatible with the status package. However, the
  1766. // status code will often not match the RPC status as seen by the client
  1767. // application, and therefore, should not be relied upon for this purpose.
  1768. func SetHeader(ctx context.Context, md metadata.MD) error {
  1769. if md.Len() == 0 {
  1770. return nil
  1771. }
  1772. stream := ServerTransportStreamFromContext(ctx)
  1773. if stream == nil {
  1774. return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  1775. }
  1776. return stream.SetHeader(md)
  1777. }
  1778. // SendHeader sends header metadata. It may be called at most once, and may not
  1779. // be called after any event that causes headers to be sent (see SetHeader for
  1780. // a complete list). The provided md and headers set by SetHeader() will be
  1781. // sent.
  1782. //
  1783. // The error returned is compatible with the status package. However, the
  1784. // status code will often not match the RPC status as seen by the client
  1785. // application, and therefore, should not be relied upon for this purpose.
  1786. func SendHeader(ctx context.Context, md metadata.MD) error {
  1787. stream := ServerTransportStreamFromContext(ctx)
  1788. if stream == nil {
  1789. return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  1790. }
  1791. if err := stream.SendHeader(md); err != nil {
  1792. return toRPCErr(err)
  1793. }
  1794. return nil
  1795. }
  1796. // SetTrailer sets the trailer metadata that will be sent when an RPC returns.
  1797. // When called more than once, all the provided metadata will be merged.
  1798. //
  1799. // The error returned is compatible with the status package. However, the
  1800. // status code will often not match the RPC status as seen by the client
  1801. // application, and therefore, should not be relied upon for this purpose.
  1802. func SetTrailer(ctx context.Context, md metadata.MD) error {
  1803. if md.Len() == 0 {
  1804. return nil
  1805. }
  1806. stream := ServerTransportStreamFromContext(ctx)
  1807. if stream == nil {
  1808. return status.Errorf(codes.Internal, "grpc: failed to fetch the stream from the context %v", ctx)
  1809. }
  1810. return stream.SetTrailer(md)
  1811. }
  1812. // Method returns the method string for the server context. The returned
  1813. // string is in the format of "/service/method".
  1814. func Method(ctx context.Context) (string, bool) {
  1815. s := ServerTransportStreamFromContext(ctx)
  1816. if s == nil {
  1817. return "", false
  1818. }
  1819. return s.Method(), true
  1820. }
  1821. type channelzServer struct {
  1822. s *Server
  1823. }
  1824. func (c *channelzServer) ChannelzMetric() *channelz.ServerInternalMetric {
  1825. return c.s.channelzMetric()
  1826. }