설명 없음

fetch_test.go 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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"
  26. "net/http"
  27. "os"
  28. "path/filepath"
  29. "reflect"
  30. "regexp"
  31. "runtime"
  32. "strings"
  33. "testing"
  34. "time"
  35. "github.com/google/pprof/pkg/binutils"
  36. "github.com/google/pprof/pkg/plugin"
  37. "github.com/google/pprof/pkg/proftest"
  38. "github.com/google/pprof/pkg/symbolizer"
  39. "github.com/google/pprof/pkg/transport"
  40. "github.com/google/pprof/profile"
  41. )
  42. func TestSymbolizationPath(t *testing.T) {
  43. if runtime.GOOS == "windows" {
  44. t.Skip("test assumes Unix paths")
  45. }
  46. // Save environment variables to restore after test
  47. saveHome := os.Getenv(homeEnv())
  48. savePath := os.Getenv("PPROF_BINARY_PATH")
  49. tempdir, err := ioutil.TempDir("", "home")
  50. if err != nil {
  51. t.Fatal("creating temp dir: ", err)
  52. }
  53. defer os.RemoveAll(tempdir)
  54. os.MkdirAll(filepath.Join(tempdir, "pprof", "binaries", "abcde10001"), 0700)
  55. os.Create(filepath.Join(tempdir, "pprof", "binaries", "abcde10001", "binary"))
  56. obj := testObj{tempdir}
  57. os.Setenv(homeEnv(), tempdir)
  58. for _, tc := range []struct {
  59. env, file, buildID, want string
  60. msgCount int
  61. }{
  62. {"", "/usr/bin/binary", "", "/usr/bin/binary", 0},
  63. {"", "/usr/bin/binary", "fedcb10000", "/usr/bin/binary", 0},
  64. {"/usr", "/bin/binary", "", "/usr/bin/binary", 0},
  65. {"", "/prod/path/binary", "abcde10001", filepath.Join(tempdir, "pprof/binaries/abcde10001/binary"), 0},
  66. {"/alternate/architecture", "/usr/bin/binary", "", "/alternate/architecture/binary", 0},
  67. {"/alternate/architecture", "/usr/bin/binary", "abcde10001", "/alternate/architecture/binary", 0},
  68. {"/nowhere:/alternate/architecture", "/usr/bin/binary", "fedcb10000", "/usr/bin/binary", 1},
  69. {"/nowhere:/alternate/architecture", "/usr/bin/binary", "abcde10002", "/usr/bin/binary", 1},
  70. } {
  71. os.Setenv("PPROF_BINARY_PATH", tc.env)
  72. p := &profile.Profile{
  73. Mapping: []*profile.Mapping{
  74. {
  75. File: tc.file,
  76. BuildID: tc.buildID,
  77. },
  78. },
  79. }
  80. s := &source{}
  81. locateBinaries(p, s, obj, &proftest.TestUI{T: t, Ignore: tc.msgCount})
  82. if file := p.Mapping[0].File; file != tc.want {
  83. t.Errorf("%s:%s:%s, want %s, got %s", tc.env, tc.file, tc.buildID, tc.want, file)
  84. }
  85. }
  86. os.Setenv(homeEnv(), saveHome)
  87. os.Setenv("PPROF_BINARY_PATH", savePath)
  88. }
  89. func TestCollectMappingSources(t *testing.T) {
  90. const startAddress uint64 = 0x40000
  91. const url = "http://example.com"
  92. for _, tc := range []struct {
  93. file, buildID string
  94. want plugin.MappingSources
  95. }{
  96. {"/usr/bin/binary", "buildId", mappingSources("buildId", url, startAddress)},
  97. {"/usr/bin/binary", "", mappingSources("/usr/bin/binary", url, startAddress)},
  98. {"", "", mappingSources(url, url, startAddress)},
  99. } {
  100. p := &profile.Profile{
  101. Mapping: []*profile.Mapping{
  102. {
  103. File: tc.file,
  104. BuildID: tc.buildID,
  105. Start: startAddress,
  106. },
  107. },
  108. }
  109. got := collectMappingSources(p, url)
  110. if !reflect.DeepEqual(got, tc.want) {
  111. t.Errorf("%s:%s, want %v, got %v", tc.file, tc.buildID, tc.want, got)
  112. }
  113. }
  114. }
  115. func TestUnsourceMappings(t *testing.T) {
  116. for _, tc := range []struct {
  117. file, buildID, want string
  118. }{
  119. {"/usr/bin/binary", "buildId", "/usr/bin/binary"},
  120. {"http://example.com", "", ""},
  121. } {
  122. p := &profile.Profile{
  123. Mapping: []*profile.Mapping{
  124. {
  125. File: tc.file,
  126. BuildID: tc.buildID,
  127. },
  128. },
  129. }
  130. unsourceMappings(p)
  131. if got := p.Mapping[0].File; got != tc.want {
  132. t.Errorf("%s:%s, want %s, got %s", tc.file, tc.buildID, tc.want, got)
  133. }
  134. }
  135. }
  136. type testObj struct {
  137. home string
  138. }
  139. func (o testObj) Open(file string, start, limit, offset uint64) (plugin.ObjFile, error) {
  140. switch file {
  141. case "/alternate/architecture/binary":
  142. return testFile{file, "abcde10001"}, nil
  143. case "/usr/bin/binary":
  144. return testFile{file, "fedcb10000"}, nil
  145. case filepath.Join(o.home, "pprof/binaries/abcde10001/binary"):
  146. return testFile{file, "abcde10001"}, nil
  147. }
  148. return nil, fmt.Errorf("not found: %s", file)
  149. }
  150. func (testObj) Demangler(_ string) func(names []string) (map[string]string, error) {
  151. return func(names []string) (map[string]string, error) { return nil, nil }
  152. }
  153. func (testObj) Disasm(file string, start, end uint64, intelSyntax bool) ([]plugin.Inst, error) {
  154. return nil, nil
  155. }
  156. type testFile struct{ name, buildID string }
  157. func (f testFile) Name() string { return f.name }
  158. func (testFile) Base() uint64 { return 0 }
  159. func (f testFile) BuildID() string { return f.buildID }
  160. func (testFile) SourceLine(addr uint64) ([]plugin.Frame, error) { return nil, nil }
  161. func (testFile) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) { return nil, nil }
  162. func (testFile) Close() error { return nil }
  163. func TestFetch(t *testing.T) {
  164. const path = "testdata/"
  165. type testcase struct {
  166. source, execName string
  167. }
  168. for _, tc := range []testcase{
  169. {path + "go.crc32.cpu", ""},
  170. {path + "go.nomappings.crash", "/bin/gotest.exe"},
  171. {"http://localhost/profile?file=cppbench.cpu", ""},
  172. } {
  173. p, _, _, err := grabProfile(&source{ExecName: tc.execName}, tc.source, nil, testObj{}, &proftest.TestUI{T: t}, &httpTransport{})
  174. if err != nil {
  175. t.Fatalf("%s: %s", tc.source, err)
  176. }
  177. if len(p.Sample) == 0 {
  178. t.Errorf("%s: want non-zero samples", tc.source)
  179. }
  180. if e := tc.execName; e != "" {
  181. switch {
  182. case len(p.Mapping) == 0 || p.Mapping[0] == nil:
  183. t.Errorf("%s: want mapping[0].execName == %s, got no mappings", tc.source, e)
  184. case p.Mapping[0].File != e:
  185. t.Errorf("%s: want mapping[0].execName == %s, got %s", tc.source, e, p.Mapping[0].File)
  186. }
  187. }
  188. }
  189. }
  190. func TestFetchWithBase(t *testing.T) {
  191. baseConfig := currentConfig()
  192. defer setCurrentConfig(baseConfig)
  193. type WantSample struct {
  194. values []int64
  195. labels map[string][]string
  196. }
  197. const path = "testdata/"
  198. type testcase struct {
  199. desc string
  200. sources []string
  201. bases []string
  202. diffBases []string
  203. normalize bool
  204. wantSamples []WantSample
  205. wantErrorMsg string
  206. }
  207. testcases := []testcase{
  208. {
  209. "not normalized base is same as source",
  210. []string{path + "cppbench.contention"},
  211. []string{path + "cppbench.contention"},
  212. nil,
  213. false,
  214. nil,
  215. "",
  216. },
  217. {
  218. "not normalized base is same as source",
  219. []string{path + "cppbench.contention"},
  220. []string{path + "cppbench.contention"},
  221. nil,
  222. false,
  223. nil,
  224. "",
  225. },
  226. {
  227. "not normalized single source, multiple base (all profiles same)",
  228. []string{path + "cppbench.contention"},
  229. []string{path + "cppbench.contention", path + "cppbench.contention"},
  230. nil,
  231. false,
  232. []WantSample{
  233. {
  234. values: []int64{-2700, -608881724},
  235. labels: map[string][]string{},
  236. },
  237. {
  238. values: []int64{-100, -23992},
  239. labels: map[string][]string{},
  240. },
  241. {
  242. values: []int64{-200, -179943},
  243. labels: map[string][]string{},
  244. },
  245. {
  246. values: []int64{-100, -17778444},
  247. labels: map[string][]string{},
  248. },
  249. {
  250. values: []int64{-100, -75976},
  251. labels: map[string][]string{},
  252. },
  253. {
  254. values: []int64{-300, -63568134},
  255. labels: map[string][]string{},
  256. },
  257. },
  258. "",
  259. },
  260. {
  261. "not normalized, different base and source",
  262. []string{path + "cppbench.contention"},
  263. []string{path + "cppbench.small.contention"},
  264. nil,
  265. false,
  266. []WantSample{
  267. {
  268. values: []int64{1700, 608878600},
  269. labels: map[string][]string{},
  270. },
  271. {
  272. values: []int64{100, 23992},
  273. labels: map[string][]string{},
  274. },
  275. {
  276. values: []int64{200, 179943},
  277. labels: map[string][]string{},
  278. },
  279. {
  280. values: []int64{100, 17778444},
  281. labels: map[string][]string{},
  282. },
  283. {
  284. values: []int64{100, 75976},
  285. labels: map[string][]string{},
  286. },
  287. {
  288. values: []int64{300, 63568134},
  289. labels: map[string][]string{},
  290. },
  291. },
  292. "",
  293. },
  294. {
  295. "normalized base is same as source",
  296. []string{path + "cppbench.contention"},
  297. []string{path + "cppbench.contention"},
  298. nil,
  299. true,
  300. nil,
  301. "",
  302. },
  303. {
  304. "normalized single source, multiple base (all profiles same)",
  305. []string{path + "cppbench.contention"},
  306. []string{path + "cppbench.contention", path + "cppbench.contention"},
  307. nil,
  308. true,
  309. nil,
  310. "",
  311. },
  312. {
  313. "normalized different base and source",
  314. []string{path + "cppbench.contention"},
  315. []string{path + "cppbench.small.contention"},
  316. nil,
  317. true,
  318. []WantSample{
  319. {
  320. values: []int64{-229, -370},
  321. labels: map[string][]string{},
  322. },
  323. {
  324. values: []int64{28, 0},
  325. labels: map[string][]string{},
  326. },
  327. {
  328. values: []int64{57, 0},
  329. labels: map[string][]string{},
  330. },
  331. {
  332. values: []int64{28, 80},
  333. labels: map[string][]string{},
  334. },
  335. {
  336. values: []int64{28, 0},
  337. labels: map[string][]string{},
  338. },
  339. {
  340. values: []int64{85, 287},
  341. labels: map[string][]string{},
  342. },
  343. },
  344. "",
  345. },
  346. {
  347. "not normalized diff base is same as source",
  348. []string{path + "cppbench.contention"},
  349. nil,
  350. []string{path + "cppbench.contention"},
  351. false,
  352. []WantSample{
  353. {
  354. values: []int64{2700, 608881724},
  355. labels: map[string][]string{},
  356. },
  357. {
  358. values: []int64{100, 23992},
  359. labels: map[string][]string{},
  360. },
  361. {
  362. values: []int64{200, 179943},
  363. labels: map[string][]string{},
  364. },
  365. {
  366. values: []int64{100, 17778444},
  367. labels: map[string][]string{},
  368. },
  369. {
  370. values: []int64{100, 75976},
  371. labels: map[string][]string{},
  372. },
  373. {
  374. values: []int64{300, 63568134},
  375. labels: map[string][]string{},
  376. },
  377. {
  378. values: []int64{-2700, -608881724},
  379. labels: map[string][]string{"pprof::base": {"true"}},
  380. },
  381. {
  382. values: []int64{-100, -23992},
  383. labels: map[string][]string{"pprof::base": {"true"}},
  384. },
  385. {
  386. values: []int64{-200, -179943},
  387. labels: map[string][]string{"pprof::base": {"true"}},
  388. },
  389. {
  390. values: []int64{-100, -17778444},
  391. labels: map[string][]string{"pprof::base": {"true"}},
  392. },
  393. {
  394. values: []int64{-100, -75976},
  395. labels: map[string][]string{"pprof::base": {"true"}},
  396. },
  397. {
  398. values: []int64{-300, -63568134},
  399. labels: map[string][]string{"pprof::base": {"true"}},
  400. },
  401. },
  402. "",
  403. },
  404. {
  405. "diff_base and base both specified",
  406. []string{path + "cppbench.contention"},
  407. []string{path + "cppbench.contention"},
  408. []string{path + "cppbench.contention"},
  409. false,
  410. nil,
  411. "-base and -diff_base flags cannot both be specified",
  412. },
  413. }
  414. for _, tc := range testcases {
  415. t.Run(tc.desc, func(t *testing.T) {
  416. setCurrentConfig(baseConfig)
  417. f := testFlags{
  418. stringLists: map[string][]string{
  419. "base": tc.bases,
  420. "diff_base": tc.diffBases,
  421. },
  422. bools: map[string]bool{
  423. "normalize": tc.normalize,
  424. },
  425. }
  426. f.args = tc.sources
  427. o := setDefaults(&plugin.Options{
  428. UI: &proftest.TestUI{T: t, AllowRx: "Local symbolization failed|Some binary filenames not available"},
  429. Flagset: f,
  430. HTTPTransport: transport.New(nil),
  431. })
  432. src, _, err := parseFlags(o)
  433. if tc.wantErrorMsg != "" {
  434. if err == nil {
  435. t.Fatalf("got nil, want error %q", tc.wantErrorMsg)
  436. }
  437. if gotErrMsg := err.Error(); gotErrMsg != tc.wantErrorMsg {
  438. t.Fatalf("got error %q, want error %q", gotErrMsg, tc.wantErrorMsg)
  439. }
  440. return
  441. }
  442. if err != nil {
  443. t.Fatalf("got error %q, want no error", err)
  444. }
  445. p, err := fetchProfiles(src, o)
  446. if err != nil {
  447. t.Fatalf("got error %q, want no error", err)
  448. }
  449. if got, want := len(p.Sample), len(tc.wantSamples); got != want {
  450. t.Fatalf("got %d samples want %d", got, want)
  451. }
  452. for i, sample := range p.Sample {
  453. if !reflect.DeepEqual(tc.wantSamples[i].values, sample.Value) {
  454. t.Errorf("for sample %d got values %v, want %v", i, sample.Value, tc.wantSamples[i])
  455. }
  456. if !reflect.DeepEqual(tc.wantSamples[i].labels, sample.Label) {
  457. t.Errorf("for sample %d got labels %v, want %v", i, sample.Label, tc.wantSamples[i].labels)
  458. }
  459. }
  460. })
  461. }
  462. }
  463. // mappingSources creates MappingSources map with a single item.
  464. func mappingSources(key, source string, start uint64) plugin.MappingSources {
  465. return plugin.MappingSources{
  466. key: []struct {
  467. Source string
  468. Start uint64
  469. }{
  470. {Source: source, Start: start},
  471. },
  472. }
  473. }
  474. type httpTransport struct{}
  475. func (tr *httpTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  476. values := req.URL.Query()
  477. file := values.Get("file")
  478. if file == "" {
  479. return nil, fmt.Errorf("want .../file?profile, got %s", req.URL.String())
  480. }
  481. t := &http.Transport{}
  482. t.RegisterProtocol("file", http.NewFileTransport(http.Dir("testdata/")))
  483. c := &http.Client{Transport: t}
  484. return c.Get("file:///" + file)
  485. }
  486. func closedError() string {
  487. if runtime.GOOS == "plan9" {
  488. return "listen hungup"
  489. }
  490. return "use of closed"
  491. }
  492. func TestHTTPSInsecure(t *testing.T) {
  493. if runtime.GOOS == "nacl" || runtime.GOOS == "js" {
  494. t.Skip("test assumes tcp available")
  495. }
  496. saveHome := os.Getenv(homeEnv())
  497. tempdir, err := ioutil.TempDir("", "home")
  498. if err != nil {
  499. t.Fatal("creating temp dir: ", err)
  500. }
  501. defer os.RemoveAll(tempdir)
  502. // pprof writes to $HOME/pprof by default which is not necessarily
  503. // writeable (e.g. on a Debian buildd) so set $HOME to something we
  504. // know we can write to for the duration of the test.
  505. os.Setenv(homeEnv(), tempdir)
  506. defer os.Setenv(homeEnv(), saveHome)
  507. baseConfig := currentConfig()
  508. defer setCurrentConfig(baseConfig)
  509. tlsCert, _, _ := selfSignedCert(t, "")
  510. tlsConfig := &tls.Config{Certificates: []tls.Certificate{tlsCert}}
  511. l, err := tls.Listen("tcp", "localhost:0", tlsConfig)
  512. if err != nil {
  513. t.Fatalf("net.Listen: got error %v, want no error", err)
  514. }
  515. donec := make(chan error, 1)
  516. go func(donec chan<- error) {
  517. donec <- http.Serve(l, nil)
  518. }(donec)
  519. defer func() {
  520. if got, want := <-donec, closedError(); !strings.Contains(got.Error(), want) {
  521. t.Fatalf("Serve got error %v, want %q", got, want)
  522. }
  523. }()
  524. defer l.Close()
  525. outputTempFile, err := ioutil.TempFile("", "profile_output")
  526. if err != nil {
  527. t.Fatalf("Failed to create tempfile: %v", err)
  528. }
  529. defer os.Remove(outputTempFile.Name())
  530. defer outputTempFile.Close()
  531. address := "https+insecure://" + l.Addr().String() + "/debug/pprof/goroutine"
  532. s := &source{
  533. Sources: []string{address},
  534. Timeout: 10,
  535. Symbolize: "remote",
  536. }
  537. o := &plugin.Options{
  538. Obj: &binutils.Binutils{},
  539. UI: &proftest.TestUI{T: t, AllowRx: "Saved profile in"},
  540. HTTPTransport: transport.New(nil),
  541. }
  542. o.Sym = &symbolizer.Symbolizer{Obj: o.Obj, UI: o.UI}
  543. p, err := fetchProfiles(s, o)
  544. if err != nil {
  545. t.Fatal(err)
  546. }
  547. if len(p.SampleType) == 0 {
  548. t.Fatalf("fetchProfiles(%s) got empty profile: len(p.SampleType)==0", address)
  549. }
  550. if len(p.Function) == 0 {
  551. t.Fatalf("fetchProfiles(%s) got non-symbolized profile: len(p.Function)==0", address)
  552. }
  553. if err := checkProfileHasFunction(p, "TestHTTPSInsecure"); err != nil {
  554. t.Fatalf("fetchProfiles(%s) %v", address, err)
  555. }
  556. }
  557. func TestHTTPSWithServerCertFetch(t *testing.T) {
  558. if runtime.GOOS == "nacl" || runtime.GOOS == "js" {
  559. t.Skip("test assumes tcp available")
  560. }
  561. saveHome := os.Getenv(homeEnv())
  562. tempdir, err := ioutil.TempDir("", "home")
  563. if err != nil {
  564. t.Fatal("creating temp dir: ", err)
  565. }
  566. defer os.RemoveAll(tempdir)
  567. // pprof writes to $HOME/pprof by default which is not necessarily
  568. // writeable (e.g. on a Debian buildd) so set $HOME to something we
  569. // know we can write to for the duration of the test.
  570. os.Setenv(homeEnv(), tempdir)
  571. defer os.Setenv(homeEnv(), saveHome)
  572. baseConfig := currentConfig()
  573. defer setCurrentConfig(baseConfig)
  574. cert, certBytes, keyBytes := selfSignedCert(t, "localhost")
  575. cas := x509.NewCertPool()
  576. cas.AppendCertsFromPEM(certBytes)
  577. tlsConfig := &tls.Config{
  578. RootCAs: cas,
  579. Certificates: []tls.Certificate{cert},
  580. ClientAuth: tls.RequireAndVerifyClientCert,
  581. ClientCAs: cas,
  582. }
  583. l, err := tls.Listen("tcp", "localhost:0", tlsConfig)
  584. if err != nil {
  585. t.Fatalf("net.Listen: got error %v, want no error", err)
  586. }
  587. donec := make(chan error, 1)
  588. go func(donec chan<- error) {
  589. donec <- http.Serve(l, nil)
  590. }(donec)
  591. defer func() {
  592. if got, want := <-donec, closedError(); !strings.Contains(got.Error(), want) {
  593. t.Fatalf("Serve got error %v, want %q", got, want)
  594. }
  595. }()
  596. defer l.Close()
  597. outputTempFile, err := ioutil.TempFile("", "profile_output")
  598. if err != nil {
  599. t.Fatalf("Failed to create tempfile: %v", err)
  600. }
  601. defer os.Remove(outputTempFile.Name())
  602. defer outputTempFile.Close()
  603. // Get port from the address, so request to the server can be made using
  604. // the host name specified in certificates.
  605. _, portStr, err := net.SplitHostPort(l.Addr().String())
  606. if err != nil {
  607. t.Fatalf("cannot get port from URL: %v", err)
  608. }
  609. address := "https://" + "localhost:" + portStr + "/debug/pprof/goroutine"
  610. s := &source{
  611. Sources: []string{address},
  612. Timeout: 10,
  613. Symbolize: "remote",
  614. }
  615. certTempFile, err := ioutil.TempFile("", "cert_output")
  616. if err != nil {
  617. t.Errorf("cannot create cert tempfile: %v", err)
  618. }
  619. defer os.Remove(certTempFile.Name())
  620. defer certTempFile.Close()
  621. certTempFile.Write(certBytes)
  622. keyTempFile, err := ioutil.TempFile("", "key_output")
  623. if err != nil {
  624. t.Errorf("cannot create key tempfile: %v", err)
  625. }
  626. defer os.Remove(keyTempFile.Name())
  627. defer keyTempFile.Close()
  628. keyTempFile.Write(keyBytes)
  629. f := &testFlags{
  630. strings: map[string]string{
  631. "tls_cert": certTempFile.Name(),
  632. "tls_key": keyTempFile.Name(),
  633. "tls_ca": certTempFile.Name(),
  634. },
  635. }
  636. o := &plugin.Options{
  637. Obj: &binutils.Binutils{},
  638. UI: &proftest.TestUI{T: t, AllowRx: "Saved profile in"},
  639. Flagset: f,
  640. HTTPTransport: transport.New(f),
  641. }
  642. o.Sym = &symbolizer.Symbolizer{Obj: o.Obj, UI: o.UI, Transport: o.HTTPTransport}
  643. p, err := fetchProfiles(s, o)
  644. if err != nil {
  645. t.Fatal(err)
  646. }
  647. if len(p.SampleType) == 0 {
  648. t.Fatalf("fetchProfiles(%s) got empty profile: len(p.SampleType)==0", address)
  649. }
  650. if len(p.Function) == 0 {
  651. t.Fatalf("fetchProfiles(%s) got non-symbolized profile: len(p.Function)==0", address)
  652. }
  653. if err := checkProfileHasFunction(p, "TestHTTPSWithServerCertFetch"); err != nil {
  654. t.Fatalf("fetchProfiles(%s) %v", address, err)
  655. }
  656. }
  657. func checkProfileHasFunction(p *profile.Profile, fname string) error {
  658. for _, f := range p.Function {
  659. if strings.Contains(f.Name, fname) {
  660. return nil
  661. }
  662. }
  663. return fmt.Errorf("got %s, want function %q", p.String(), fname)
  664. }
  665. // selfSignedCert generates a self-signed certificate, and returns the
  666. // generated certificate, and byte arrays containing the certificate and
  667. // key associated with the certificate.
  668. func selfSignedCert(t *testing.T, host string) (tls.Certificate, []byte, []byte) {
  669. privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  670. if err != nil {
  671. t.Fatalf("failed to generate private key: %v", err)
  672. }
  673. b, err := x509.MarshalECPrivateKey(privKey)
  674. if err != nil {
  675. t.Fatalf("failed to marshal private key: %v", err)
  676. }
  677. bk := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: b})
  678. tmpl := x509.Certificate{
  679. SerialNumber: big.NewInt(1),
  680. NotBefore: time.Now(),
  681. NotAfter: time.Now().Add(10 * time.Minute),
  682. IsCA: true,
  683. DNSNames: []string{host},
  684. }
  685. b, err = x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, privKey.Public(), privKey)
  686. if err != nil {
  687. t.Fatalf("failed to create cert: %v", err)
  688. }
  689. bc := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: b})
  690. cert, err := tls.X509KeyPair(bc, bk)
  691. if err != nil {
  692. t.Fatalf("failed to create TLS key pair: %v", err)
  693. }
  694. return cert, bc, bk
  695. }