server.go 69 KB

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