暫無描述

fetch_test.go 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. // Copyright 2014 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. "crypto/ecdsa"
  17. "crypto/elliptic"
  18. "crypto/rand"
  19. "crypto/tls"
  20. "crypto/x509"
  21. "encoding/pem"
  22. "fmt"
  23. "io/ioutil"
  24. "math/big"
  25. "net/http"
  26. "net/url"
  27. "os"
  28. "path/filepath"
  29. "reflect"
  30. "regexp"
  31. "runtime"
  32. "strings"
  33. "testing"
  34. "time"
  35. "github.com/google/pprof/internal/plugin"
  36. "github.com/google/pprof/internal/proftest"
  37. "github.com/google/pprof/profile"
  38. )
  39. func TestSymbolizationPath(t *testing.T) {
  40. if runtime.GOOS == "windows" {
  41. t.Skip("test assumes Unix paths")
  42. }
  43. // Save environment variables to restore after test
  44. saveHome := os.Getenv(homeEnv())
  45. savePath := os.Getenv("PPROF_BINARY_PATH")
  46. tempdir, err := ioutil.TempDir("", "home")
  47. if err != nil {
  48. t.Fatal("creating temp dir: ", err)
  49. }
  50. defer os.RemoveAll(tempdir)
  51. os.MkdirAll(filepath.Join(tempdir, "pprof", "binaries", "abcde10001"), 0700)
  52. os.Create(filepath.Join(tempdir, "pprof", "binaries", "abcde10001", "binary"))
  53. obj := testObj{tempdir}
  54. os.Setenv(homeEnv(), tempdir)
  55. for _, tc := range []struct {
  56. env, file, buildID, want string
  57. msgCount int
  58. }{
  59. {"", "/usr/bin/binary", "", "/usr/bin/binary", 0},
  60. {"", "/usr/bin/binary", "fedcb10000", "/usr/bin/binary", 0},
  61. {"/usr", "/bin/binary", "", "/usr/bin/binary", 0},
  62. {"", "/prod/path/binary", "abcde10001", filepath.Join(tempdir, "pprof/binaries/abcde10001/binary"), 0},
  63. {"/alternate/architecture", "/usr/bin/binary", "", "/alternate/architecture/binary", 0},
  64. {"/alternate/architecture", "/usr/bin/binary", "abcde10001", "/alternate/architecture/binary", 0},
  65. {"/nowhere:/alternate/architecture", "/usr/bin/binary", "fedcb10000", "/usr/bin/binary", 1},
  66. {"/nowhere:/alternate/architecture", "/usr/bin/binary", "abcde10002", "/usr/bin/binary", 1},
  67. } {
  68. os.Setenv("PPROF_BINARY_PATH", tc.env)
  69. p := &profile.Profile{
  70. Mapping: []*profile.Mapping{
  71. {
  72. File: tc.file,
  73. BuildID: tc.buildID,
  74. },
  75. },
  76. }
  77. s := &source{}
  78. locateBinaries(p, s, obj, &proftest.TestUI{T: t, Ignore: tc.msgCount})
  79. if file := p.Mapping[0].File; file != tc.want {
  80. t.Errorf("%s:%s:%s, want %s, got %s", tc.env, tc.file, tc.buildID, tc.want, file)
  81. }
  82. }
  83. os.Setenv(homeEnv(), saveHome)
  84. os.Setenv("PPROF_BINARY_PATH", savePath)
  85. }
  86. func TestCollectMappingSources(t *testing.T) {
  87. const startAddress uint64 = 0x40000
  88. const url = "http://example.com"
  89. for _, tc := range []struct {
  90. file, buildID string
  91. want plugin.MappingSources
  92. }{
  93. {"/usr/bin/binary", "buildId", mappingSources("buildId", url, startAddress)},
  94. {"/usr/bin/binary", "", mappingSources("/usr/bin/binary", url, startAddress)},
  95. {"", "", mappingSources(url, url, startAddress)},
  96. } {
  97. p := &profile.Profile{
  98. Mapping: []*profile.Mapping{
  99. {
  100. File: tc.file,
  101. BuildID: tc.buildID,
  102. Start: startAddress,
  103. },
  104. },
  105. }
  106. got := collectMappingSources(p, url)
  107. if !reflect.DeepEqual(got, tc.want) {
  108. t.Errorf("%s:%s, want %v, got %v", tc.file, tc.buildID, tc.want, got)
  109. }
  110. }
  111. }
  112. func TestUnsourceMappings(t *testing.T) {
  113. for _, tc := range []struct {
  114. file, buildID, want string
  115. }{
  116. {"/usr/bin/binary", "buildId", "/usr/bin/binary"},
  117. {"http://example.com", "", ""},
  118. } {
  119. p := &profile.Profile{
  120. Mapping: []*profile.Mapping{
  121. {
  122. File: tc.file,
  123. BuildID: tc.buildID,
  124. },
  125. },
  126. }
  127. unsourceMappings(p)
  128. if got := p.Mapping[0].File; got != tc.want {
  129. t.Errorf("%s:%s, want %s, got %s", tc.file, tc.buildID, tc.want, got)
  130. }
  131. }
  132. }
  133. type testObj struct {
  134. home string
  135. }
  136. func (o testObj) Open(file string, start, limit, offset uint64) (plugin.ObjFile, error) {
  137. switch file {
  138. case "/alternate/architecture/binary":
  139. return testFile{file, "abcde10001"}, nil
  140. case "/usr/bin/binary":
  141. return testFile{file, "fedcb10000"}, nil
  142. case filepath.Join(o.home, "pprof/binaries/abcde10001/binary"):
  143. return testFile{file, "abcde10001"}, nil
  144. }
  145. return nil, fmt.Errorf("not found: %s", file)
  146. }
  147. func (testObj) Demangler(_ string) func(names []string) (map[string]string, error) {
  148. return func(names []string) (map[string]string, error) { return nil, nil }
  149. }
  150. func (testObj) Disasm(file string, start, end uint64) ([]plugin.Inst, error) { return nil, nil }
  151. type testFile struct{ name, buildID string }
  152. func (f testFile) Name() string { return f.name }
  153. func (testFile) Base() uint64 { return 0 }
  154. func (f testFile) BuildID() string { return f.buildID }
  155. func (testFile) SourceLine(addr uint64) ([]plugin.Frame, error) { return nil, nil }
  156. func (testFile) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) { return nil, nil }
  157. func (testFile) Close() error { return nil }
  158. func TestFetch(t *testing.T) {
  159. const path = "testdata/"
  160. // Intercept http.Get calls from HTTPFetcher.
  161. savedHTTPGet := httpGet
  162. defer func() { httpGet = savedHTTPGet }()
  163. httpGet = stubHTTPGet
  164. type testcase struct {
  165. source, execName string
  166. }
  167. for _, tc := range []testcase{
  168. {path + "go.crc32.cpu", ""},
  169. {path + "go.nomappings.crash", "/bin/gotest.exe"},
  170. {"http://localhost/profile?file=cppbench.cpu", ""},
  171. } {
  172. p, _, _, err := grabProfile(&source{ExecName: tc.execName}, tc.source, 0, nil, testObj{}, &proftest.TestUI{T: t})
  173. if err != nil {
  174. t.Fatalf("%s: %s", tc.source, err)
  175. }
  176. if len(p.Sample) == 0 {
  177. t.Errorf("%s: want non-zero samples", tc.source)
  178. }
  179. if e := tc.execName; e != "" {
  180. switch {
  181. case len(p.Mapping) == 0 || p.Mapping[0] == nil:
  182. t.Errorf("%s: want mapping[0].execName == %s, got no mappings", tc.source, e)
  183. case p.Mapping[0].File != e:
  184. t.Errorf("%s: want mapping[0].execName == %s, got %s", tc.source, e, p.Mapping[0].File)
  185. }
  186. }
  187. }
  188. }
  189. // mappingSources creates MappingSources map with a single item.
  190. func mappingSources(key, source string, start uint64) plugin.MappingSources {
  191. return plugin.MappingSources{
  192. key: []struct {
  193. Source string
  194. Start uint64
  195. }{
  196. {Source: source, Start: start},
  197. },
  198. }
  199. }
  200. // stubHTTPGet intercepts a call to http.Get and rewrites it to use
  201. // "file://" to get the profile directly from a file.
  202. func stubHTTPGet(source string, _ time.Duration) (*http.Response, error) {
  203. url, err := url.Parse(source)
  204. if err != nil {
  205. return nil, err
  206. }
  207. values := url.Query()
  208. file := values.Get("file")
  209. if file == "" {
  210. return nil, fmt.Errorf("want .../file?profile, got %s", source)
  211. }
  212. t := &http.Transport{}
  213. t.RegisterProtocol("file", http.NewFileTransport(http.Dir("testdata/")))
  214. c := &http.Client{Transport: t}
  215. return c.Get("file:///" + file)
  216. }
  217. func TestHttpsInsecure(t *testing.T) {
  218. baseVars := pprofVariables
  219. pprofVariables = baseVars.makeCopy()
  220. defer func() { pprofVariables = baseVars }()
  221. tlsConfig := &tls.Config{Certificates: []tls.Certificate{selfSignedCert(t)}}
  222. l, err := tls.Listen("tcp", "localhost:0", tlsConfig)
  223. if err != nil {
  224. t.Fatalf("net.Listen: got error %v, want no error", err)
  225. }
  226. donec := make(chan error, 1)
  227. go func(donec chan<- error) {
  228. donec <- http.Serve(l, nil)
  229. }(donec)
  230. defer func() {
  231. if got, want := <-donec, "use of closed"; !strings.Contains(got.Error(), want) {
  232. t.Fatalf("Serve got error %v, want %q", got, want)
  233. }
  234. }()
  235. defer l.Close()
  236. go func() {
  237. deadline := time.Now().Add(5 * time.Second)
  238. for time.Now().Before(deadline) {
  239. // Simulate a hotspot function.
  240. }
  241. }()
  242. outputTempFile, err := ioutil.TempFile("", "profile_output")
  243. if err != nil {
  244. t.Fatalf("Failed to create tempfile: %v", err)
  245. }
  246. defer os.Remove(outputTempFile.Name())
  247. defer outputTempFile.Close()
  248. address := "https+insecure://" + l.Addr().String() + "/debug/pprof/profile?seconds=5"
  249. p, _, _, err := grabProfile(&source{}, address, 0, nil, testObj{}, &proftest.TestUI{T: t})
  250. if err != nil {
  251. t.Fatal(err)
  252. }
  253. if len(p.SampleType) == 0 {
  254. t.Fatalf("grabProfile(%s) got empty profile: len(p.SampleType)==0", address)
  255. }
  256. }
  257. func selfSignedCert(t *testing.T) tls.Certificate {
  258. privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  259. if err != nil {
  260. t.Fatalf("failed to generate private key: %v", err)
  261. }
  262. b, err := x509.MarshalECPrivateKey(privKey)
  263. if err != nil {
  264. t.Fatalf("failed to marshal private key: %v", err)
  265. }
  266. bk := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: b})
  267. tmpl := x509.Certificate{
  268. SerialNumber: big.NewInt(1),
  269. NotBefore: time.Now(),
  270. NotAfter: time.Now().Add(10 * time.Minute),
  271. }
  272. b, err = x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, privKey.Public(), privKey)
  273. if err != nil {
  274. t.Fatalf("failed to create cert: %v", err)
  275. }
  276. bc := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: b})
  277. cert, err := tls.X509KeyPair(bc, bk)
  278. if err != nil {
  279. t.Fatalf("failed to create TLS key pair: %v", err)
  280. }
  281. return cert
  282. }