server.go 43 KB

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