No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

218 líneas
5.1 KiB

  1. // Copyright 2018 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package proxy
  15. import (
  16. "bytes"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "io/ioutil"
  21. "log"
  22. "net/http"
  23. "reflect"
  24. "sync"
  25. "github.com/google/martian/martianlog"
  26. )
  27. // ForReplaying returns a Proxy configured to replay.
  28. func ForReplaying(filename string, port int) (*Proxy, error) {
  29. p, err := newProxy(filename)
  30. if err != nil {
  31. return nil, err
  32. }
  33. lg, err := readLog(filename)
  34. if err != nil {
  35. return nil, err
  36. }
  37. calls, err := constructCalls(lg)
  38. if err != nil {
  39. return nil, err
  40. }
  41. p.Initial = lg.Initial
  42. p.mproxy.SetRoundTripper(&replayRoundTripper{
  43. calls: calls,
  44. ignoreHeaders: p.ignoreHeaders,
  45. conv: lg.Converter,
  46. })
  47. // Debug logging.
  48. // TODO(jba): factor out from here and ForRecording.
  49. logger := martianlog.NewLogger()
  50. logger.SetDecode(true)
  51. p.mproxy.SetRequestModifier(logger)
  52. p.mproxy.SetResponseModifier(logger)
  53. if err := p.start(port); err != nil {
  54. return nil, err
  55. }
  56. return p, nil
  57. }
  58. func readLog(filename string) (*Log, error) {
  59. bytes, err := ioutil.ReadFile(filename)
  60. if err != nil {
  61. return nil, err
  62. }
  63. var lg Log
  64. if err := json.Unmarshal(bytes, &lg); err != nil {
  65. return nil, fmt.Errorf("%s: %v", filename, err)
  66. }
  67. if lg.Version != LogVersion {
  68. return nil, fmt.Errorf(
  69. "httpreplay: read log version %s but current version is %s; re-record the log",
  70. lg.Version, LogVersion)
  71. }
  72. return &lg, nil
  73. }
  74. // A call is an HTTP request and its matching response.
  75. type call struct {
  76. req *Request
  77. res *Response
  78. }
  79. func constructCalls(lg *Log) ([]*call, error) {
  80. ignoreIDs := map[string]bool{} // IDs of requests to ignore
  81. callsByID := map[string]*call{}
  82. var calls []*call
  83. for _, e := range lg.Entries {
  84. if ignoreIDs[e.ID] {
  85. continue
  86. }
  87. c, ok := callsByID[e.ID]
  88. switch {
  89. case !ok:
  90. if e.Request == nil {
  91. return nil, fmt.Errorf("first entry for ID %s does not have a request", e.ID)
  92. }
  93. if e.Request.Method == "CONNECT" {
  94. // Ignore CONNECT methods.
  95. ignoreIDs[e.ID] = true
  96. } else {
  97. c := &call{e.Request, e.Response}
  98. calls = append(calls, c)
  99. callsByID[e.ID] = c
  100. }
  101. case e.Request != nil:
  102. if e.Response != nil {
  103. return nil, errors.New("entry has both request and response")
  104. }
  105. c.req = e.Request
  106. case e.Response != nil:
  107. c.res = e.Response
  108. default:
  109. return nil, errors.New("entry has neither request nor response")
  110. }
  111. }
  112. for _, c := range calls {
  113. if c.req == nil || c.res == nil {
  114. return nil, fmt.Errorf("missing request or response: %+v", c)
  115. }
  116. }
  117. return calls, nil
  118. }
  119. type replayRoundTripper struct {
  120. mu sync.Mutex
  121. calls []*call
  122. ignoreHeaders map[string]bool
  123. conv *Converter
  124. }
  125. func (r *replayRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
  126. if req.Body != nil {
  127. defer req.Body.Close()
  128. }
  129. creq, err := r.conv.convertRequest(req)
  130. if err != nil {
  131. return nil, err
  132. }
  133. r.mu.Lock()
  134. defer r.mu.Unlock()
  135. for i, call := range r.calls {
  136. if call == nil {
  137. continue
  138. }
  139. if requestsMatch(creq, call.req, r.ignoreHeaders) {
  140. r.calls[i] = nil // nil out this call so we don't reuse it
  141. return toHTTPResponse(call.res, req), nil
  142. }
  143. }
  144. return nil, fmt.Errorf("no matching request for %+v", req)
  145. }
  146. // Report whether the incoming request in matches the candidate request cand.
  147. func requestsMatch(in, cand *Request, ignoreHeaders map[string]bool) bool {
  148. if in.Method != cand.Method {
  149. return false
  150. }
  151. if in.URL != cand.URL {
  152. return false
  153. }
  154. if in.MediaType != cand.MediaType {
  155. return false
  156. }
  157. if len(in.BodyParts) != len(cand.BodyParts) {
  158. return false
  159. }
  160. for i, p1 := range in.BodyParts {
  161. if !bytes.Equal(p1, cand.BodyParts[i]) {
  162. return false
  163. }
  164. }
  165. // Check headers last. See DebugHeaders.
  166. return headersMatch(in.Header, cand.Header, ignoreHeaders)
  167. }
  168. // DebugHeaders helps to determine whether a header should be ignored.
  169. // When true, if requests have the same method, URL and body but differ
  170. // in a header, the first mismatched header is logged.
  171. var DebugHeaders = false
  172. func headersMatch(in, cand http.Header, ignores map[string]bool) bool {
  173. for k1, v1 := range in {
  174. if ignores[k1] {
  175. continue
  176. }
  177. v2 := cand[k1]
  178. if v2 == nil {
  179. if DebugHeaders {
  180. log.Printf("header %s: present in incoming request but not candidate", k1)
  181. }
  182. return false
  183. }
  184. if !reflect.DeepEqual(v1, v2) {
  185. if DebugHeaders {
  186. log.Printf("header %s: incoming %v, candidate %v", k1, v1, v2)
  187. }
  188. return false
  189. }
  190. }
  191. for k2 := range cand {
  192. if ignores[k2] {
  193. continue
  194. }
  195. if in[k2] == nil {
  196. if DebugHeaders {
  197. log.Printf("header %s: not in incoming request but present in candidate", k2)
  198. }
  199. return false
  200. }
  201. }
  202. return true
  203. }