handler_server.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /*
  2. * Copyright 2016, Google Inc.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are
  7. * met:
  8. *
  9. * * Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * * Redistributions in binary form must reproduce the above
  12. * copyright notice, this list of conditions and the following disclaimer
  13. * in the documentation and/or other materials provided with the
  14. * distribution.
  15. * * Neither the name of Google Inc. nor the names of its
  16. * contributors may be used to endorse or promote products derived from
  17. * this software without specific prior written permission.
  18. *
  19. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  20. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  21. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  22. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  23. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  24. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  25. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  26. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  27. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  28. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  29. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  30. *
  31. */
  32. // This file is the implementation of a gRPC server using HTTP/2 which
  33. // uses the standard Go http2 Server implementation (via the
  34. // http.Handler interface), rather than speaking low-level HTTP/2
  35. // frames itself. It is the implementation of *grpc.Server.ServeHTTP.
  36. package transport
  37. import (
  38. "errors"
  39. "fmt"
  40. "io"
  41. "net"
  42. "net/http"
  43. "strings"
  44. "sync"
  45. "time"
  46. "golang.org/x/net/context"
  47. "golang.org/x/net/http2"
  48. "google.golang.org/grpc/codes"
  49. "google.golang.org/grpc/credentials"
  50. "google.golang.org/grpc/metadata"
  51. "google.golang.org/grpc/peer"
  52. )
  53. // NewServerHandlerTransport returns a ServerTransport handling gRPC
  54. // from inside an http.Handler. It requires that the http Server
  55. // supports HTTP/2.
  56. func NewServerHandlerTransport(w http.ResponseWriter, r *http.Request) (ServerTransport, error) {
  57. if r.ProtoMajor != 2 {
  58. return nil, errors.New("gRPC requires HTTP/2")
  59. }
  60. if r.Method != "POST" {
  61. return nil, errors.New("invalid gRPC request method")
  62. }
  63. if !strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
  64. return nil, errors.New("invalid gRPC request content-type")
  65. }
  66. if _, ok := w.(http.Flusher); !ok {
  67. return nil, errors.New("gRPC requires a ResponseWriter supporting http.Flusher")
  68. }
  69. if _, ok := w.(http.CloseNotifier); !ok {
  70. return nil, errors.New("gRPC requires a ResponseWriter supporting http.CloseNotifier")
  71. }
  72. st := &serverHandlerTransport{
  73. rw: w,
  74. req: r,
  75. closedCh: make(chan struct{}),
  76. writes: make(chan func()),
  77. }
  78. if v := r.Header.Get("grpc-timeout"); v != "" {
  79. to, err := timeoutDecode(v)
  80. if err != nil {
  81. return nil, StreamErrorf(codes.Internal, "malformed time-out: %v", err)
  82. }
  83. st.timeoutSet = true
  84. st.timeout = to
  85. }
  86. var metakv []string
  87. for k, vv := range r.Header {
  88. k = strings.ToLower(k)
  89. if isReservedHeader(k) {
  90. continue
  91. }
  92. for _, v := range vv {
  93. if k == "user-agent" {
  94. // user-agent is special. Copying logic of http_util.go.
  95. if i := strings.LastIndex(v, " "); i == -1 {
  96. // There is no application user agent string being set
  97. continue
  98. } else {
  99. v = v[:i]
  100. }
  101. }
  102. metakv = append(metakv, k, v)
  103. }
  104. }
  105. st.headerMD = metadata.Pairs(metakv...)
  106. return st, nil
  107. }
  108. // serverHandlerTransport is an implementation of ServerTransport
  109. // which replies to exactly one gRPC request (exactly one HTTP request),
  110. // using the net/http.Handler interface. This http.Handler is guaranteed
  111. // at this point to be speaking over HTTP/2, so it's able to speak valid
  112. // gRPC.
  113. type serverHandlerTransport struct {
  114. rw http.ResponseWriter
  115. req *http.Request
  116. timeoutSet bool
  117. timeout time.Duration
  118. didCommonHeaders bool
  119. headerMD metadata.MD
  120. closeOnce sync.Once
  121. closedCh chan struct{} // closed on Close
  122. // writes is a channel of code to run serialized in the
  123. // ServeHTTP (HandleStreams) goroutine. The channel is closed
  124. // when WriteStatus is called.
  125. writes chan func()
  126. }
  127. func (ht *serverHandlerTransport) Close() error {
  128. ht.closeOnce.Do(ht.closeCloseChanOnce)
  129. return nil
  130. }
  131. func (ht *serverHandlerTransport) closeCloseChanOnce() { close(ht.closedCh) }
  132. func (ht *serverHandlerTransport) RemoteAddr() net.Addr { return strAddr(ht.req.RemoteAddr) }
  133. // strAddr is a net.Addr backed by either a TCP "ip:port" string, or
  134. // the empty string if unknown.
  135. type strAddr string
  136. func (a strAddr) Network() string {
  137. if a != "" {
  138. // Per the documentation on net/http.Request.RemoteAddr, if this is
  139. // set, it's set to the IP:port of the peer (hence, TCP):
  140. // https://golang.org/pkg/net/http/#Request
  141. //
  142. // If we want to support Unix sockets later, we can
  143. // add our own grpc-specific convention within the
  144. // grpc codebase to set RemoteAddr to a different
  145. // format, or probably better: we can attach it to the
  146. // context and use that from serverHandlerTransport.RemoteAddr.
  147. return "tcp"
  148. }
  149. return ""
  150. }
  151. func (a strAddr) String() string { return string(a) }
  152. // do runs fn in the ServeHTTP goroutine.
  153. func (ht *serverHandlerTransport) do(fn func()) error {
  154. select {
  155. case ht.writes <- fn:
  156. return nil
  157. case <-ht.closedCh:
  158. return ErrConnClosing
  159. }
  160. }
  161. func (ht *serverHandlerTransport) WriteStatus(s *Stream, statusCode codes.Code, statusDesc string) error {
  162. err := ht.do(func() {
  163. ht.writeCommonHeaders(s)
  164. // And flush, in case no header or body has been sent yet.
  165. // This forces a separation of headers and trailers if this is the
  166. // first call (for example, in end2end tests's TestNoService).
  167. ht.rw.(http.Flusher).Flush()
  168. h := ht.rw.Header()
  169. h.Set("Grpc-Status", fmt.Sprintf("%d", statusCode))
  170. if statusDesc != "" {
  171. h.Set("Grpc-Message", statusDesc)
  172. }
  173. if md := s.Trailer(); len(md) > 0 {
  174. for k, vv := range md {
  175. for _, v := range vv {
  176. // http2 ResponseWriter mechanism to
  177. // send undeclared Trailers after the
  178. // headers have possibly been written.
  179. h.Add(http2.TrailerPrefix+k, v)
  180. }
  181. }
  182. }
  183. })
  184. close(ht.writes)
  185. return err
  186. }
  187. // writeCommonHeaders sets common headers on the first write
  188. // call (Write, WriteHeader, or WriteStatus).
  189. func (ht *serverHandlerTransport) writeCommonHeaders(s *Stream) {
  190. if ht.didCommonHeaders {
  191. return
  192. }
  193. ht.didCommonHeaders = true
  194. h := ht.rw.Header()
  195. h["Date"] = nil // suppress Date to make tests happy; TODO: restore
  196. h.Set("Content-Type", "application/grpc")
  197. // Predeclare trailers we'll set later in WriteStatus (after the body).
  198. // This is a SHOULD in the HTTP RFC, and the way you add (known)
  199. // Trailers per the net/http.ResponseWriter contract.
  200. // See https://golang.org/pkg/net/http/#ResponseWriter
  201. // and https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
  202. h.Add("Trailer", "Grpc-Status")
  203. h.Add("Trailer", "Grpc-Message")
  204. if s.sendCompress != "" {
  205. h.Set("Grpc-Encoding", s.sendCompress)
  206. }
  207. }
  208. func (ht *serverHandlerTransport) Write(s *Stream, data []byte, opts *Options) error {
  209. return ht.do(func() {
  210. ht.writeCommonHeaders(s)
  211. ht.rw.Write(data)
  212. if !opts.Delay {
  213. ht.rw.(http.Flusher).Flush()
  214. }
  215. })
  216. }
  217. func (ht *serverHandlerTransport) WriteHeader(s *Stream, md metadata.MD) error {
  218. return ht.do(func() {
  219. ht.writeCommonHeaders(s)
  220. h := ht.rw.Header()
  221. for k, vv := range md {
  222. for _, v := range vv {
  223. h.Add(k, v)
  224. }
  225. }
  226. ht.rw.WriteHeader(200)
  227. ht.rw.(http.Flusher).Flush()
  228. })
  229. }
  230. func (ht *serverHandlerTransport) HandleStreams(startStream func(*Stream)) {
  231. // With this transport type there will be exactly 1 stream: this HTTP request.
  232. var ctx context.Context
  233. var cancel context.CancelFunc
  234. if ht.timeoutSet {
  235. ctx, cancel = context.WithTimeout(context.Background(), ht.timeout)
  236. } else {
  237. ctx, cancel = context.WithCancel(context.Background())
  238. }
  239. // requestOver is closed when either the request's context is done
  240. // or the status has been written via WriteStatus.
  241. requestOver := make(chan struct{})
  242. // clientGone receives a single value if peer is gone, either
  243. // because the underlying connection is dead or because the
  244. // peer sends an http2 RST_STREAM.
  245. clientGone := ht.rw.(http.CloseNotifier).CloseNotify()
  246. go func() {
  247. select {
  248. case <-requestOver:
  249. return
  250. case <-ht.closedCh:
  251. case <-clientGone:
  252. }
  253. cancel()
  254. }()
  255. req := ht.req
  256. s := &Stream{
  257. id: 0, // irrelevant
  258. windowHandler: func(int) {}, // nothing
  259. cancel: cancel,
  260. buf: newRecvBuffer(),
  261. st: ht,
  262. method: req.URL.Path,
  263. recvCompress: req.Header.Get("grpc-encoding"),
  264. }
  265. pr := &peer.Peer{
  266. Addr: ht.RemoteAddr(),
  267. }
  268. if req.TLS != nil {
  269. pr.AuthInfo = credentials.TLSInfo{*req.TLS}
  270. }
  271. ctx = metadata.NewContext(ctx, ht.headerMD)
  272. ctx = peer.NewContext(ctx, pr)
  273. s.ctx = newContextWithStream(ctx, s)
  274. s.dec = &recvBufferReader{ctx: s.ctx, recv: s.buf}
  275. // readerDone is closed when the Body.Read-ing goroutine exits.
  276. readerDone := make(chan struct{})
  277. go func() {
  278. defer close(readerDone)
  279. // TODO: minimize garbage, optimize recvBuffer code/ownership
  280. const readSize = 8196
  281. for buf := make([]byte, readSize); ; {
  282. n, err := req.Body.Read(buf)
  283. if n > 0 {
  284. s.buf.put(&recvMsg{data: buf[:n:n]})
  285. buf = buf[n:]
  286. }
  287. if err != nil {
  288. s.buf.put(&recvMsg{err: mapRecvMsgError(err)})
  289. return
  290. }
  291. if len(buf) == 0 {
  292. buf = make([]byte, readSize)
  293. }
  294. }
  295. }()
  296. // startStream is provided by the *grpc.Server's serveStreams.
  297. // It starts a goroutine serving s and exits immediately.
  298. // The goroutine that is started is the one that then calls
  299. // into ht, calling WriteHeader, Write, WriteStatus, Close, etc.
  300. startStream(s)
  301. ht.runStream()
  302. close(requestOver)
  303. // Wait for reading goroutine to finish.
  304. req.Body.Close()
  305. <-readerDone
  306. }
  307. func (ht *serverHandlerTransport) runStream() {
  308. for {
  309. select {
  310. case fn, ok := <-ht.writes:
  311. if !ok {
  312. return
  313. }
  314. fn()
  315. case <-ht.closedCh:
  316. return
  317. }
  318. }
  319. }
  320. // mapRecvMsgError returns the non-nil err into the appropriate
  321. // error value as expected by callers of *grpc.parser.recvMsg.
  322. // In particular, in can only be:
  323. // * io.EOF
  324. // * io.ErrUnexpectedEOF
  325. // * of type transport.ConnectionError
  326. // * of type transport.StreamError
  327. func mapRecvMsgError(err error) error {
  328. if err == io.EOF || err == io.ErrUnexpectedEOF {
  329. return err
  330. }
  331. if se, ok := err.(http2.StreamError); ok {
  332. if code, ok := http2ErrConvTab[se.Code]; ok {
  333. return StreamError{
  334. Code: code,
  335. Desc: se.Error(),
  336. }
  337. }
  338. }
  339. return ConnectionError{Desc: err.Error()}
  340. }