You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

server.go 44 kB

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