server.go 68 KB

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