暂无描述

fetch.go 17KB

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