暫無描述

fetch_test.go 9.9KB

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