Без опису

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