server.go 40 KB

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