Nenhuma descrição

fetch.go 17KB

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