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

286 lines
7.6 KiB

  1. // Copyright 2017 Google Inc. All Rights Reserved.
  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 driver
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "net"
  19. "net/http"
  20. "net/http/httptest"
  21. "net/url"
  22. "os/exec"
  23. "regexp"
  24. "runtime"
  25. "sync"
  26. "testing"
  27. "github.com/google/pprof/internal/plugin"
  28. "github.com/google/pprof/internal/proftest"
  29. "github.com/google/pprof/profile"
  30. )
  31. func TestWebInterface(t *testing.T) {
  32. if runtime.GOOS == "nacl" || runtime.GOOS == "js" {
  33. t.Skip("test assumes tcp available")
  34. }
  35. prof := makeFakeProfile()
  36. // Custom http server creator
  37. var server *httptest.Server
  38. serverCreated := make(chan bool)
  39. creator := func(a *plugin.HTTPServerArgs) error {
  40. server = httptest.NewServer(http.HandlerFunc(
  41. func(w http.ResponseWriter, r *http.Request) {
  42. if h := a.Handlers[r.URL.Path]; h != nil {
  43. h.ServeHTTP(w, r)
  44. }
  45. }))
  46. serverCreated <- true
  47. return nil
  48. }
  49. // Start server and wait for it to be initialized
  50. go serveWebInterface("unused:1234", prof, &plugin.Options{
  51. Obj: fakeObjTool{},
  52. UI: &proftest.TestUI{},
  53. HTTPServer: creator,
  54. }, false)
  55. <-serverCreated
  56. defer server.Close()
  57. haveDot := false
  58. if _, err := exec.LookPath("dot"); err == nil {
  59. haveDot = true
  60. }
  61. type testCase struct {
  62. path string
  63. want []string
  64. needDot bool
  65. }
  66. testcases := []testCase{
  67. {"/", []string{"F1", "F2", "F3", "testbin", "cpu"}, true},
  68. {"/top", []string{`"Name":"F2","InlineLabel":"","Flat":200,"Cum":300,"FlatFormat":"200ms","CumFormat":"300ms"}`}, false},
  69. {"/source?f=" + url.QueryEscape("F[12]"),
  70. []string{"F1", "F2", "300ms +line1"}, false},
  71. {"/peek?f=" + url.QueryEscape("F[12]"),
  72. []string{"300ms.*F1", "200ms.*300ms.*F2"}, false},
  73. {"/disasm?f=" + url.QueryEscape("F[12]"),
  74. []string{"f1:asm", "f2:asm"}, false},
  75. {"/flamegraph", []string{"File: testbin", "\"n\":\"root\"", "\"n\":\"F1\"", "var flamegraph = function", "function hierarchy"}, false},
  76. }
  77. for _, c := range testcases {
  78. if c.needDot && !haveDot {
  79. t.Log("skipping", c.path, "since dot (graphviz) does not seem to be installed")
  80. continue
  81. }
  82. res, err := http.Get(server.URL + c.path)
  83. if err != nil {
  84. t.Error("could not fetch", c.path, err)
  85. continue
  86. }
  87. data, err := ioutil.ReadAll(res.Body)
  88. if err != nil {
  89. t.Error("could not read response", c.path, err)
  90. continue
  91. }
  92. result := string(data)
  93. for _, w := range c.want {
  94. if match, _ := regexp.MatchString(w, result); !match {
  95. t.Errorf("response for %s does not match "+
  96. "expected pattern '%s'; "+
  97. "actual result:\n%s", c.path, w, result)
  98. }
  99. }
  100. }
  101. // Also fetch all the test case URLs in parallel to test thread
  102. // safety when run under the race detector.
  103. var wg sync.WaitGroup
  104. for _, c := range testcases {
  105. if c.needDot && !haveDot {
  106. continue
  107. }
  108. path := server.URL + c.path
  109. for count := 0; count < 2; count++ {
  110. wg.Add(1)
  111. go func() {
  112. defer wg.Done()
  113. res, err := http.Get(path)
  114. if err != nil {
  115. t.Error("could not fetch", c.path, err)
  116. return
  117. }
  118. if _, err = ioutil.ReadAll(res.Body); err != nil {
  119. t.Error("could not read response", c.path, err)
  120. }
  121. }()
  122. }
  123. }
  124. wg.Wait()
  125. }
  126. // Implement fake object file support.
  127. const addrBase = 0x1000
  128. const fakeSource = "testdata/file1000.src"
  129. type fakeObj struct{}
  130. func (f fakeObj) Close() error { return nil }
  131. func (f fakeObj) Name() string { return "testbin" }
  132. func (f fakeObj) Base() uint64 { return 0 }
  133. func (f fakeObj) BuildID() string { return "" }
  134. func (f fakeObj) SourceLine(addr uint64) ([]plugin.Frame, error) {
  135. return nil, fmt.Errorf("SourceLine unimplemented")
  136. }
  137. func (f fakeObj) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) {
  138. return []*plugin.Sym{
  139. {
  140. Name: []string{"F1"}, File: fakeSource,
  141. Start: addrBase, End: addrBase + 10,
  142. },
  143. {
  144. Name: []string{"F2"}, File: fakeSource,
  145. Start: addrBase + 10, End: addrBase + 20,
  146. },
  147. {
  148. Name: []string{"F3"}, File: fakeSource,
  149. Start: addrBase + 20, End: addrBase + 30,
  150. },
  151. }, nil
  152. }
  153. type fakeObjTool struct{}
  154. func (obj fakeObjTool) Open(file string, start, limit, offset uint64) (plugin.ObjFile, error) {
  155. return fakeObj{}, nil
  156. }
  157. func (obj fakeObjTool) Disasm(file string, start, end uint64) ([]plugin.Inst, error) {
  158. return []plugin.Inst{
  159. {Addr: addrBase + 0, Text: "f1:asm", Function: "F1"},
  160. {Addr: addrBase + 10, Text: "f2:asm", Function: "F2"},
  161. {Addr: addrBase + 20, Text: "d3:asm", Function: "F3"},
  162. }, nil
  163. }
  164. func makeFakeProfile() *profile.Profile {
  165. // Three functions: F1, F2, F3 with three lines, 11, 22, 33.
  166. funcs := []*profile.Function{
  167. {ID: 1, Name: "F1", Filename: fakeSource, StartLine: 3},
  168. {ID: 2, Name: "F2", Filename: fakeSource, StartLine: 5},
  169. {ID: 3, Name: "F3", Filename: fakeSource, StartLine: 7},
  170. }
  171. lines := []profile.Line{
  172. {Function: funcs[0], Line: 11},
  173. {Function: funcs[1], Line: 22},
  174. {Function: funcs[2], Line: 33},
  175. }
  176. mapping := []*profile.Mapping{
  177. {
  178. ID: 1,
  179. Start: addrBase,
  180. Limit: addrBase + 10,
  181. Offset: 0,
  182. File: "testbin",
  183. HasFunctions: true,
  184. HasFilenames: true,
  185. HasLineNumbers: true,
  186. },
  187. }
  188. // Three interesting addresses: base+{10,20,30}
  189. locs := []*profile.Location{
  190. {ID: 1, Address: addrBase + 10, Line: lines[0:1], Mapping: mapping[0]},
  191. {ID: 2, Address: addrBase + 20, Line: lines[1:2], Mapping: mapping[0]},
  192. {ID: 3, Address: addrBase + 30, Line: lines[2:3], Mapping: mapping[0]},
  193. }
  194. // Two stack traces.
  195. return &profile.Profile{
  196. PeriodType: &profile.ValueType{Type: "cpu", Unit: "milliseconds"},
  197. Period: 1,
  198. DurationNanos: 10e9,
  199. SampleType: []*profile.ValueType{
  200. {Type: "cpu", Unit: "milliseconds"},
  201. },
  202. Sample: []*profile.Sample{
  203. {
  204. Location: []*profile.Location{locs[2], locs[1], locs[0]},
  205. Value: []int64{100},
  206. },
  207. {
  208. Location: []*profile.Location{locs[1], locs[0]},
  209. Value: []int64{200},
  210. },
  211. },
  212. Location: locs,
  213. Function: funcs,
  214. Mapping: mapping,
  215. }
  216. }
  217. func TestGetHostAndPort(t *testing.T) {
  218. if runtime.GOOS == "nacl" || runtime.GOOS == "js" {
  219. t.Skip("test assumes tcp available")
  220. }
  221. type testCase struct {
  222. hostport string
  223. wantHost string
  224. wantPort int
  225. wantRandomPort bool
  226. }
  227. testCases := []testCase{
  228. {":", "localhost", 0, true},
  229. {":4681", "localhost", 4681, false},
  230. {"localhost:4681", "localhost", 4681, false},
  231. }
  232. for _, tc := range testCases {
  233. host, port, err := getHostAndPort(tc.hostport)
  234. if err != nil {
  235. t.Errorf("could not get host and port for %q: %v", tc.hostport, err)
  236. }
  237. if got, want := host, tc.wantHost; got != want {
  238. t.Errorf("for %s, got host %s, want %s", tc.hostport, got, want)
  239. continue
  240. }
  241. if !tc.wantRandomPort {
  242. if got, want := port, tc.wantPort; got != want {
  243. t.Errorf("for %s, got port %d, want %d", tc.hostport, got, want)
  244. continue
  245. }
  246. }
  247. }
  248. }
  249. func TestIsLocalHost(t *testing.T) {
  250. for _, s := range []string{"localhost:10000", "[::1]:10000", "127.0.0.1:10000"} {
  251. host, _, err := net.SplitHostPort(s)
  252. if err != nil {
  253. t.Error("unexpected error when splitting", s)
  254. continue
  255. }
  256. if !isLocalhost(host) {
  257. t.Errorf("host %s from %s not considered local", host, s)
  258. }
  259. }
  260. }