server.go 64 KB

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