server.go 42 KB

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