暂无描述

fetch.go 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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. "bytes"
  17. "crypto/tls"
  18. "fmt"
  19. "io"
  20. "io/ioutil"
  21. "net/http"
  22. "net/url"
  23. "os"
  24. "os/exec"
  25. "path/filepath"
  26. "runtime"
  27. "strconv"
  28. "strings"
  29. "sync"
  30. "time"
  31. "github.com/google/pprof/internal/measurement"
  32. "github.com/google/pprof/internal/plugin"
  33. "github.com/google/pprof/profile"
  34. )
  35. // fetchProfiles fetches and symbolizes the profiles specified by s.
  36. // It will merge all the profiles it is able to retrieve, even if
  37. // there are some failures. It will return an error if it is unable to
  38. // fetch any profiles.
  39. func fetchProfiles(s *source, o *plugin.Options) (*profile.Profile, error) {
  40. sources := make([]profileSource, 0, len(s.Sources))
  41. for _, src := range s.Sources {
  42. sources = append(sources, profileSource{
  43. addr: src,
  44. source: s,
  45. })
  46. }
  47. bases := make([]profileSource, 0, len(s.Base))
  48. for _, src := range s.Base {
  49. bases = append(bases, profileSource{
  50. addr: src,
  51. source: s,
  52. })
  53. }
  54. p, pbase, m, mbase, save, err := grabSourcesAndBases(sources, bases, o.Fetch, o.Obj, o.UI)
  55. if err != nil {
  56. return nil, err
  57. }
  58. if pbase != nil {
  59. if s.DiffBase {
  60. pbase.SetLabel("pprof::base", []string{"true"})
  61. }
  62. if s.Normalize {
  63. err := p.Normalize(pbase)
  64. if err != nil {
  65. return nil, err
  66. }
  67. }
  68. pbase.Scale(-1)
  69. p, m, err = combineProfiles([]*profile.Profile{p, pbase}, []plugin.MappingSources{m, mbase})
  70. if err != nil {
  71. return nil, err
  72. }
  73. }
  74. // Symbolize the merged profile.
  75. if err := o.Sym.Symbolize(s.Symbolize, m, p); err != nil {
  76. return nil, err
  77. }
  78. p.RemoveUninteresting()
  79. unsourceMappings(p)
  80. if s.Comment != "" {
  81. p.Comments = append(p.Comments, s.Comment)
  82. }
  83. // Save a copy of the merged profile if there is at least one remote source.
  84. if save {
  85. dir, err := setTmpDir(o.UI)
  86. if err != nil {
  87. return nil, err
  88. }
  89. prefix := "pprof."
  90. if len(p.Mapping) > 0 && p.Mapping[0].File != "" {
  91. prefix += filepath.Base(p.Mapping[0].File) + "."
  92. }
  93. for _, s := range p.SampleType {
  94. prefix += s.Type + "."
  95. }
  96. tempFile, err := newTempFile(dir, prefix, ".pb.gz")
  97. if err == nil {
  98. if err = p.Write(tempFile); err == nil {
  99. o.UI.PrintErr("Saved profile in ", tempFile.Name())
  100. }
  101. }
  102. if err != nil {
  103. o.UI.PrintErr("Could not save profile: ", err)
  104. }
  105. }
  106. if err := p.CheckValid(); err != nil {
  107. return nil, err
  108. }
  109. return p, nil
  110. }
  111. func grabSourcesAndBases(sources, bases []profileSource, fetch plugin.Fetcher, obj plugin.ObjTool, ui plugin.UI) (*profile.Profile, *profile.Profile, plugin.MappingSources, plugin.MappingSources, bool, error) {
  112. wg := sync.WaitGroup{}
  113. wg.Add(2)
  114. var psrc, pbase *profile.Profile
  115. var msrc, mbase plugin.MappingSources
  116. var savesrc, savebase bool
  117. var errsrc, errbase error
  118. var countsrc, countbase int
  119. go func() {
  120. defer wg.Done()
  121. psrc, msrc, savesrc, countsrc, errsrc = chunkedGrab(sources, fetch, obj, ui)
  122. }()
  123. go func() {
  124. defer wg.Done()
  125. pbase, mbase, savebase, countbase, errbase = chunkedGrab(bases, fetch, obj, ui)
  126. }()
  127. wg.Wait()
  128. save := savesrc || savebase
  129. if errsrc != nil {
  130. return nil, nil, nil, nil, false, fmt.Errorf("problem fetching source profiles: %v", errsrc)
  131. }
  132. if errbase != nil {
  133. return nil, nil, nil, nil, false, fmt.Errorf("problem fetching base profiles: %v,", errbase)
  134. }
  135. if countsrc == 0 {
  136. return nil, nil, nil, nil, false, fmt.Errorf("failed to fetch any source profiles")
  137. }
  138. if countbase == 0 && len(bases) > 0 {
  139. return nil, nil, nil, nil, false, fmt.Errorf("failed to fetch any base profiles")
  140. }
  141. if want, got := len(sources), countsrc; want != got {
  142. ui.PrintErr(fmt.Sprintf("Fetched %d source profiles out of %d", got, want))
  143. }
  144. if want, got := len(bases), countbase; want != got {
  145. ui.PrintErr(fmt.Sprintf("Fetched %d base profiles out of %d", got, want))
  146. }
  147. return psrc, pbase, msrc, mbase, save, nil
  148. }
  149. // chunkedGrab fetches the profiles described in source and merges them into
  150. // a single profile. It fetches a chunk of profiles concurrently, with a maximum
  151. // chunk size to limit its memory usage.
  152. func chunkedGrab(sources []profileSource, fetch plugin.Fetcher, obj plugin.ObjTool, ui plugin.UI) (*profile.Profile, plugin.MappingSources, bool, int, error) {
  153. const chunkSize = 64
  154. var p *profile.Profile
  155. var msrc plugin.MappingSources
  156. var save bool
  157. var count int
  158. for start := 0; start < len(sources); start += chunkSize {
  159. end := start + chunkSize
  160. if end > len(sources) {
  161. end = len(sources)
  162. }
  163. chunkP, chunkMsrc, chunkSave, chunkCount, chunkErr := concurrentGrab(sources[start:end], fetch, obj, ui)
  164. switch {
  165. case chunkErr != nil:
  166. return nil, nil, false, 0, chunkErr
  167. case chunkP == nil:
  168. continue
  169. case p == nil:
  170. p, msrc, save, count = chunkP, chunkMsrc, chunkSave, chunkCount
  171. default:
  172. p, msrc, chunkErr = combineProfiles([]*profile.Profile{p, chunkP}, []plugin.MappingSources{msrc, chunkMsrc})
  173. if chunkErr != nil {
  174. return nil, nil, false, 0, chunkErr
  175. }
  176. if chunkSave {
  177. save = true
  178. }
  179. count += chunkCount
  180. }
  181. }
  182. return p, msrc, save, count, nil
  183. }
  184. // concurrentGrab fetches multiple profiles concurrently
  185. func concurrentGrab(sources []profileSource, fetch plugin.Fetcher, obj plugin.ObjTool, ui plugin.UI) (*profile.Profile, plugin.MappingSources, bool, int, error) {
  186. wg := sync.WaitGroup{}
  187. wg.Add(len(sources))
  188. for i := range sources {
  189. go func(s *profileSource) {
  190. defer wg.Done()
  191. s.p, s.msrc, s.remote, s.err = grabProfile(s.source, s.addr, fetch, obj, ui)
  192. }(&sources[i])
  193. }
  194. wg.Wait()
  195. var save bool
  196. profiles := make([]*profile.Profile, 0, len(sources))
  197. msrcs := make([]plugin.MappingSources, 0, len(sources))
  198. for i := range sources {
  199. s := &sources[i]
  200. if err := s.err; err != nil {
  201. ui.PrintErr(s.addr + ": " + err.Error())
  202. continue
  203. }
  204. save = save || s.remote
  205. profiles = append(profiles, s.p)
  206. msrcs = append(msrcs, s.msrc)
  207. *s = profileSource{}
  208. }
  209. if len(profiles) == 0 {
  210. return nil, nil, false, 0, nil
  211. }
  212. p, msrc, err := combineProfiles(profiles, msrcs)
  213. if err != nil {
  214. return nil, nil, false, 0, err
  215. }
  216. return p, msrc, save, len(profiles), nil
  217. }
  218. func combineProfiles(profiles []*profile.Profile, msrcs []plugin.MappingSources) (*profile.Profile, plugin.MappingSources, error) {
  219. // Merge profiles.
  220. if err := measurement.ScaleProfiles(profiles); err != nil {
  221. return nil, nil, err
  222. }
  223. p, err := profile.Merge(profiles)
  224. if err != nil {
  225. return nil, nil, err
  226. }
  227. // Combine mapping sources.
  228. msrc := make(plugin.MappingSources)
  229. for _, ms := range msrcs {
  230. for m, s := range ms {
  231. msrc[m] = append(msrc[m], s...)
  232. }
  233. }
  234. return p, msrc, nil
  235. }
  236. type profileSource struct {
  237. addr string
  238. source *source
  239. p *profile.Profile
  240. msrc plugin.MappingSources
  241. remote bool
  242. err error
  243. }
  244. func homeEnv() string {
  245. switch runtime.GOOS {
  246. case "windows":
  247. return "USERPROFILE"
  248. case "plan9":
  249. return "home"
  250. default:
  251. return "HOME"
  252. }
  253. }
  254. // setTmpDir prepares the directory to use to save profiles retrieved
  255. // remotely. It is selected from PPROF_TMPDIR, defaults to $HOME/pprof, and, if
  256. // $HOME is not set, falls back to os.TempDir().
  257. func setTmpDir(ui plugin.UI) (string, error) {
  258. var dirs []string
  259. if profileDir := os.Getenv("PPROF_TMPDIR"); profileDir != "" {
  260. dirs = append(dirs, profileDir)
  261. }
  262. if homeDir := os.Getenv(homeEnv()); homeDir != "" {
  263. dirs = append(dirs, filepath.Join(homeDir, "pprof"))
  264. }
  265. dirs = append(dirs, os.TempDir())
  266. for _, tmpDir := range dirs {
  267. if err := os.MkdirAll(tmpDir, 0755); err != nil {
  268. ui.PrintErr("Could not use temp dir ", tmpDir, ": ", err.Error())
  269. continue
  270. }
  271. return tmpDir, nil
  272. }
  273. return "", fmt.Errorf("failed to identify temp dir")
  274. }
  275. const testSourceAddress = "pproftest.local"
  276. // grabProfile fetches a profile. Returns the profile, sources for the
  277. // profile mappings, a bool indicating if the profile was fetched
  278. // remotely, and an error.
  279. func grabProfile(s *source, source string, fetcher plugin.Fetcher, obj plugin.ObjTool, ui plugin.UI) (p *profile.Profile, msrc plugin.MappingSources, remote bool, err error) {
  280. var src string
  281. duration, timeout := time.Duration(s.Seconds)*time.Second, time.Duration(s.Timeout)*time.Second
  282. if fetcher != nil {
  283. p, src, err = fetcher.Fetch(source, duration, timeout)
  284. if err != nil {
  285. return
  286. }
  287. }
  288. if err != nil || p == nil {
  289. // Fetch the profile over HTTP or from a file.
  290. p, src, err = fetch(source, duration, timeout, ui)
  291. if err != nil {
  292. return
  293. }
  294. }
  295. if err = p.CheckValid(); err != nil {
  296. return
  297. }
  298. // Update the binary locations from command line and paths.
  299. locateBinaries(p, s, obj, ui)
  300. // Collect the source URL for all mappings.
  301. if src != "" {
  302. msrc = collectMappingSources(p, src)
  303. remote = true
  304. if strings.HasPrefix(src, "http://"+testSourceAddress) {
  305. // Treat test inputs as local to avoid saving
  306. // testcase profiles during driver testing.
  307. remote = false
  308. }
  309. }
  310. return
  311. }
  312. // collectMappingSources saves the mapping sources of a profile.
  313. func collectMappingSources(p *profile.Profile, source string) plugin.MappingSources {
  314. ms := plugin.MappingSources{}
  315. for _, m := range p.Mapping {
  316. src := struct {
  317. Source string
  318. Start uint64
  319. }{
  320. source, m.Start,
  321. }
  322. key := m.BuildID
  323. if key == "" {
  324. key = m.File
  325. }
  326. if key == "" {
  327. // If there is no build id or source file, use the source as the
  328. // mapping file. This will enable remote symbolization for this
  329. // mapping, in particular for Go profiles on the legacy format.
  330. // The source is reset back to empty string by unsourceMapping
  331. // which is called after symbolization is finished.
  332. m.File = source
  333. key = source
  334. }
  335. ms[key] = append(ms[key], src)
  336. }
  337. return ms
  338. }
  339. // unsourceMappings iterates over the mappings in a profile and replaces file
  340. // set to the remote source URL by collectMappingSources back to empty string.
  341. func unsourceMappings(p *profile.Profile) {
  342. for _, m := range p.Mapping {
  343. if m.BuildID == "" {
  344. if u, err := url.Parse(m.File); err == nil && u.IsAbs() {
  345. m.File = ""
  346. }
  347. }
  348. }
  349. }
  350. // locateBinaries searches for binary files listed in the profile and, if found,
  351. // updates the profile accordingly.
  352. func locateBinaries(p *profile.Profile, s *source, obj plugin.ObjTool, ui plugin.UI) {
  353. // Construct search path to examine
  354. searchPath := os.Getenv("PPROF_BINARY_PATH")
  355. if searchPath == "" {
  356. // Use $HOME/pprof/binaries as default directory for local symbolization binaries
  357. searchPath = filepath.Join(os.Getenv(homeEnv()), "pprof", "binaries")
  358. }
  359. mapping:
  360. for _, m := range p.Mapping {
  361. var baseName string
  362. if m.File != "" {
  363. baseName = filepath.Base(m.File)
  364. }
  365. for _, path := range filepath.SplitList(searchPath) {
  366. var fileNames []string
  367. if m.BuildID != "" {
  368. fileNames = []string{filepath.Join(path, m.BuildID, baseName)}
  369. if matches, err := filepath.Glob(filepath.Join(path, m.BuildID, "*")); err == nil {
  370. fileNames = append(fileNames, matches...)
  371. }
  372. fileNames = append(fileNames, filepath.Join(path, m.File, m.BuildID)) // perf path format
  373. }
  374. if m.File != "" {
  375. // Try both the basename and the full path, to support the same directory
  376. // structure as the perf symfs option.
  377. if baseName != "" {
  378. fileNames = append(fileNames, filepath.Join(path, baseName))
  379. }
  380. fileNames = append(fileNames, filepath.Join(path, m.File))
  381. }
  382. for _, name := range fileNames {
  383. if f, err := obj.Open(name, m.Start, m.Limit, m.Offset); err == nil {
  384. defer f.Close()
  385. fileBuildID := f.BuildID()
  386. if m.BuildID != "" && m.BuildID != fileBuildID {
  387. ui.PrintErr("Ignoring local file " + name + ": build-id mismatch (" + m.BuildID + " != " + fileBuildID + ")")
  388. } else {
  389. m.File = name
  390. continue mapping
  391. }
  392. }
  393. }
  394. }
  395. }
  396. if len(p.Mapping) == 0 {
  397. // If there are no mappings, add a fake mapping to attempt symbolization.
  398. // This is useful for some profiles generated by the golang runtime, which
  399. // do not include any mappings. Symbolization with a fake mapping will only
  400. // be successful against a non-PIE binary.
  401. m := &profile.Mapping{ID: 1}
  402. p.Mapping = []*profile.Mapping{m}
  403. for _, l := range p.Location {
  404. l.Mapping = m
  405. }
  406. }
  407. // Replace executable filename/buildID with the overrides from source.
  408. // Assumes the executable is the first Mapping entry.
  409. if execName, buildID := s.ExecName, s.BuildID; execName != "" || buildID != "" {
  410. m := p.Mapping[0]
  411. if execName != "" {
  412. m.File = execName
  413. }
  414. if buildID != "" {
  415. m.BuildID = buildID
  416. }
  417. }
  418. }
  419. // fetch fetches a profile from source, within the timeout specified,
  420. // producing messages through the ui. It returns the profile and the
  421. // url of the actual source of the profile for remote profiles.
  422. func fetch(source string, duration, timeout time.Duration, ui plugin.UI) (p *profile.Profile, src string, err error) {
  423. var f io.ReadCloser
  424. if sourceURL, timeout := adjustURL(source, duration, timeout); sourceURL != "" {
  425. ui.Print("Fetching profile over HTTP from " + sourceURL)
  426. if duration > 0 {
  427. ui.Print(fmt.Sprintf("Please wait... (%v)", duration))
  428. }
  429. f, err = fetchURL(sourceURL, timeout)
  430. src = sourceURL
  431. } else if isPerfFile(source) {
  432. f, err = convertPerfData(source, ui)
  433. } else {
  434. f, err = os.Open(source)
  435. }
  436. if err == nil {
  437. defer f.Close()
  438. p, err = profile.Parse(f)
  439. }
  440. return
  441. }
  442. // fetchURL fetches a profile from a URL using HTTP.
  443. func fetchURL(source string, timeout time.Duration) (io.ReadCloser, error) {
  444. resp, err := httpGet(source, timeout)
  445. if err != nil {
  446. return nil, fmt.Errorf("http fetch: %v", err)
  447. }
  448. if resp.StatusCode != http.StatusOK {
  449. defer resp.Body.Close()
  450. return nil, statusCodeError(resp)
  451. }
  452. return resp.Body, nil
  453. }
  454. func statusCodeError(resp *http.Response) error {
  455. if resp.Header.Get("X-Go-Pprof") != "" && strings.Contains(resp.Header.Get("Content-Type"), "text/plain") {
  456. // error is from pprof endpoint
  457. if body, err := ioutil.ReadAll(resp.Body); err == nil {
  458. return fmt.Errorf("server response: %s - %s", resp.Status, body)
  459. }
  460. }
  461. return fmt.Errorf("server response: %s", resp.Status)
  462. }
  463. // isPerfFile checks if a file is in perf.data format. It also returns false
  464. // if it encounters an error during the check.
  465. func isPerfFile(path string) bool {
  466. sourceFile, openErr := os.Open(path)
  467. if openErr != nil {
  468. return false
  469. }
  470. defer sourceFile.Close()
  471. // If the file is the output of a perf record command, it should begin
  472. // with the string PERFILE2.
  473. perfHeader := []byte("PERFILE2")
  474. actualHeader := make([]byte, len(perfHeader))
  475. if _, readErr := sourceFile.Read(actualHeader); readErr != nil {
  476. return false
  477. }
  478. return bytes.Equal(actualHeader, perfHeader)
  479. }
  480. // convertPerfData converts the file at path which should be in perf.data format
  481. // using the perf_to_profile tool and returns the file containing the
  482. // profile.proto formatted data.
  483. func convertPerfData(perfPath string, ui plugin.UI) (*os.File, error) {
  484. ui.Print(fmt.Sprintf(
  485. "Converting %s to a profile.proto... (May take a few minutes)",
  486. perfPath))
  487. profile, err := newTempFile(os.TempDir(), "pprof_", ".pb.gz")
  488. if err != nil {
  489. return nil, err
  490. }
  491. deferDeleteTempFile(profile.Name())
  492. cmd := exec.Command("perf_to_profile", "-i", perfPath, "-o", profile.Name(), "-f")
  493. cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
  494. if err := cmd.Run(); err != nil {
  495. profile.Close()
  496. return nil, fmt.Errorf("failed to convert perf.data file. Try github.com/google/perf_data_converter: %v", err)
  497. }
  498. return profile, nil
  499. }
  500. // adjustURL validates if a profile source is a URL and returns an
  501. // cleaned up URL and the timeout to use for retrieval over HTTP.
  502. // If the source cannot be recognized as a URL it returns an empty string.
  503. func adjustURL(source string, duration, timeout time.Duration) (string, time.Duration) {
  504. u, err := url.Parse(source)
  505. if err != nil || (u.Host == "" && u.Scheme != "" && u.Scheme != "file") {
  506. // Try adding http:// to catch sources of the form hostname:port/path.
  507. // url.Parse treats "hostname" as the scheme.
  508. u, err = url.Parse("http://" + source)
  509. }
  510. if err != nil || u.Host == "" {
  511. return "", 0
  512. }
  513. // Apply duration/timeout overrides to URL.
  514. values := u.Query()
  515. if duration > 0 {
  516. values.Set("seconds", fmt.Sprint(int(duration.Seconds())))
  517. } else {
  518. if urlSeconds := values.Get("seconds"); urlSeconds != "" {
  519. if us, err := strconv.ParseInt(urlSeconds, 10, 32); err == nil {
  520. duration = time.Duration(us) * time.Second
  521. }
  522. }
  523. }
  524. if timeout <= 0 {
  525. if duration > 0 {
  526. timeout = duration + duration/2
  527. } else {
  528. timeout = 60 * time.Second
  529. }
  530. }
  531. u.RawQuery = values.Encode()
  532. return u.String(), timeout
  533. }
  534. // httpGet is a wrapper around http.Get; it is defined as a variable
  535. // so it can be redefined during for testing.
  536. var httpGet = func(source string, timeout time.Duration) (*http.Response, error) {
  537. url, err := url.Parse(source)
  538. if err != nil {
  539. return nil, err
  540. }
  541. var tlsConfig *tls.Config
  542. if url.Scheme == "https+insecure" {
  543. tlsConfig = &tls.Config{
  544. InsecureSkipVerify: true,
  545. }
  546. url.Scheme = "https"
  547. source = url.String()
  548. }
  549. client := &http.Client{
  550. Transport: &http.Transport{
  551. Proxy: http.ProxyFromEnvironment,
  552. TLSClientConfig: tlsConfig,
  553. ResponseHeaderTimeout: timeout + 5*time.Second,
  554. },
  555. }
  556. return client.Get(source)
  557. }