Ingen beskrivning

fetch.go 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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, and, if
  250. // $HOME is not set, falls back to os.TempDir().
  251. func setTmpDir(ui plugin.UI) (string, error) {
  252. var dirs []string
  253. if profileDir := os.Getenv("PPROF_TMPDIR"); profileDir != "" {
  254. dirs = append(dirs, profileDir)
  255. }
  256. if homeDir := os.Getenv(homeEnv()); homeDir != "" {
  257. dirs = append(dirs, filepath.Join(homeDir, "pprof"))
  258. }
  259. dirs = append(dirs, os.TempDir())
  260. for _, tmpDir := range dirs {
  261. if err := os.MkdirAll(tmpDir, 0755); err != nil {
  262. ui.PrintErr("Could not use temp dir ", tmpDir, ": ", err.Error())
  263. continue
  264. }
  265. return tmpDir, nil
  266. }
  267. return "", fmt.Errorf("failed to identify temp dir")
  268. }
  269. const testSourceAddress = "pproftest.local"
  270. // grabProfile fetches a profile. Returns the profile, sources for the
  271. // profile mappings, a bool indicating if the profile was fetched
  272. // remotely, and an error.
  273. 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) {
  274. var src string
  275. duration, timeout := time.Duration(s.Seconds)*time.Second, time.Duration(s.Timeout)*time.Second
  276. if fetcher != nil {
  277. p, src, err = fetcher.Fetch(source, duration, timeout)
  278. if err != nil {
  279. return
  280. }
  281. }
  282. if err != nil || p == nil {
  283. // Fetch the profile over HTTP or from a file.
  284. p, src, err = fetch(source, duration, timeout, ui)
  285. if err != nil {
  286. return
  287. }
  288. }
  289. if err = p.CheckValid(); err != nil {
  290. return
  291. }
  292. // Update the binary locations from command line and paths.
  293. locateBinaries(p, s, obj, ui)
  294. // Collect the source URL for all mappings.
  295. if src != "" {
  296. msrc = collectMappingSources(p, src)
  297. remote = true
  298. if strings.HasPrefix(src, "http://"+testSourceAddress) {
  299. // Treat test inputs as local to avoid saving
  300. // testcase profiles during driver testing.
  301. remote = false
  302. }
  303. }
  304. return
  305. }
  306. // collectMappingSources saves the mapping sources of a profile.
  307. func collectMappingSources(p *profile.Profile, source string) plugin.MappingSources {
  308. ms := plugin.MappingSources{}
  309. for _, m := range p.Mapping {
  310. src := struct {
  311. Source string
  312. Start uint64
  313. }{
  314. source, m.Start,
  315. }
  316. key := m.BuildID
  317. if key == "" {
  318. key = m.File
  319. }
  320. if key == "" {
  321. // If there is no build id or source file, use the source as the
  322. // mapping file. This will enable remote symbolization for this
  323. // mapping, in particular for Go profiles on the legacy format.
  324. // The source is reset back to empty string by unsourceMapping
  325. // which is called after symbolization is finished.
  326. m.File = source
  327. key = source
  328. }
  329. ms[key] = append(ms[key], src)
  330. }
  331. return ms
  332. }
  333. // unsourceMappings iterates over the mappings in a profile and replaces file
  334. // set to the remote source URL by collectMappingSources back to empty string.
  335. func unsourceMappings(p *profile.Profile) {
  336. for _, m := range p.Mapping {
  337. if m.BuildID == "" {
  338. if u, err := url.Parse(m.File); err == nil && u.IsAbs() {
  339. m.File = ""
  340. }
  341. }
  342. }
  343. }
  344. // locateBinaries searches for binary files listed in the profile and, if found,
  345. // updates the profile accordingly.
  346. func locateBinaries(p *profile.Profile, s *source, obj plugin.ObjTool, ui plugin.UI) {
  347. // Construct search path to examine
  348. searchPath := os.Getenv("PPROF_BINARY_PATH")
  349. if searchPath == "" {
  350. // Use $HOME/pprof/binaries as default directory for local symbolization binaries
  351. searchPath = filepath.Join(os.Getenv(homeEnv()), "pprof", "binaries")
  352. }
  353. mapping:
  354. for _, m := range p.Mapping {
  355. var baseName string
  356. if m.File != "" {
  357. baseName = filepath.Base(m.File)
  358. }
  359. for _, path := range filepath.SplitList(searchPath) {
  360. var fileNames []string
  361. if m.BuildID != "" {
  362. fileNames = []string{filepath.Join(path, m.BuildID, baseName)}
  363. if matches, err := filepath.Glob(filepath.Join(path, m.BuildID, "*")); err == nil {
  364. fileNames = append(fileNames, matches...)
  365. }
  366. }
  367. if m.File != "" {
  368. // Try both the basename and the full path, to support the same directory
  369. // structure as the perf symfs option.
  370. if baseName != "" {
  371. fileNames = append(fileNames, filepath.Join(path, baseName))
  372. }
  373. fileNames = append(fileNames, filepath.Join(path, m.File))
  374. }
  375. for _, name := range fileNames {
  376. if f, err := obj.Open(name, m.Start, m.Limit, m.Offset); err == nil {
  377. defer f.Close()
  378. fileBuildID := f.BuildID()
  379. if m.BuildID != "" && m.BuildID != fileBuildID {
  380. ui.PrintErr("Ignoring local file " + name + ": build-id mismatch (" + m.BuildID + " != " + fileBuildID + ")")
  381. } else {
  382. m.File = name
  383. continue mapping
  384. }
  385. }
  386. }
  387. }
  388. }
  389. if len(p.Mapping) == 0 {
  390. // If there are no mappings, add a fake mapping to attempt symbolization.
  391. // This is useful for some profiles generated by the golang runtime, which
  392. // do not include any mappings. Symbolization with a fake mapping will only
  393. // be successful against a non-PIE binary.
  394. m := &profile.Mapping{ID: 1}
  395. p.Mapping = []*profile.Mapping{m}
  396. for _, l := range p.Location {
  397. l.Mapping = m
  398. }
  399. }
  400. // Replace executable filename/buildID with the overrides from source.
  401. // Assumes the executable is the first Mapping entry.
  402. if execName, buildID := s.ExecName, s.BuildID; execName != "" || buildID != "" {
  403. m := p.Mapping[0]
  404. if execName != "" {
  405. m.File = execName
  406. }
  407. if buildID != "" {
  408. m.BuildID = buildID
  409. }
  410. }
  411. }
  412. // fetch fetches a profile from source, within the timeout specified,
  413. // producing messages through the ui. It returns the profile and the
  414. // url of the actual source of the profile for remote profiles.
  415. func fetch(source string, duration, timeout time.Duration, ui plugin.UI) (p *profile.Profile, src string, err error) {
  416. var f io.ReadCloser
  417. if sourceURL, timeout := adjustURL(source, duration, timeout); sourceURL != "" {
  418. ui.Print("Fetching profile over HTTP from " + sourceURL)
  419. if duration > 0 {
  420. ui.Print(fmt.Sprintf("Please wait... (%v)", duration))
  421. }
  422. f, err = fetchURL(sourceURL, timeout)
  423. src = sourceURL
  424. } else if isPerfFile(source) {
  425. f, err = convertPerfData(source, ui)
  426. } else {
  427. f, err = os.Open(source)
  428. }
  429. if err == nil {
  430. defer f.Close()
  431. p, err = profile.Parse(f)
  432. }
  433. return
  434. }
  435. // fetchURL fetches a profile from a URL using HTTP.
  436. func fetchURL(source string, timeout time.Duration) (io.ReadCloser, error) {
  437. resp, err := httpGet(source, timeout)
  438. if err != nil {
  439. return nil, fmt.Errorf("http fetch: %v", err)
  440. }
  441. if resp.StatusCode != http.StatusOK {
  442. defer resp.Body.Close()
  443. return nil, statusCodeError(resp)
  444. }
  445. return resp.Body, nil
  446. }
  447. func statusCodeError(resp *http.Response) error {
  448. if resp.Header.Get("X-Go-Pprof") != "" && strings.Contains(resp.Header.Get("Content-Type"), "text/plain") {
  449. // error is from pprof endpoint
  450. if body, err := ioutil.ReadAll(resp.Body); err == nil {
  451. return fmt.Errorf("server response: %s - %s", resp.Status, body)
  452. }
  453. }
  454. return fmt.Errorf("server response: %s", resp.Status)
  455. }
  456. // isPerfFile checks if a file is in perf.data format. It also returns false
  457. // if it encounters an error during the check.
  458. func isPerfFile(path string) bool {
  459. sourceFile, openErr := os.Open(path)
  460. if openErr != nil {
  461. return false
  462. }
  463. defer sourceFile.Close()
  464. // If the file is the output of a perf record command, it should begin
  465. // with the string PERFILE2.
  466. perfHeader := []byte("PERFILE2")
  467. actualHeader := make([]byte, len(perfHeader))
  468. if _, readErr := sourceFile.Read(actualHeader); readErr != nil {
  469. return false
  470. }
  471. return bytes.Equal(actualHeader, perfHeader)
  472. }
  473. // convertPerfData converts the file at path which should be in perf.data format
  474. // using the perf_to_profile tool and returns the file containing the
  475. // profile.proto formatted data.
  476. func convertPerfData(perfPath string, ui plugin.UI) (*os.File, error) {
  477. ui.Print(fmt.Sprintf(
  478. "Converting %s to a profile.proto... (May take a few minutes)",
  479. perfPath))
  480. profile, err := newTempFile(os.TempDir(), "pprof_", ".pb.gz")
  481. if err != nil {
  482. return nil, err
  483. }
  484. deferDeleteTempFile(profile.Name())
  485. cmd := exec.Command("perf_to_profile", perfPath, profile.Name())
  486. if err := cmd.Run(); err != nil {
  487. profile.Close()
  488. return nil, fmt.Errorf("failed to convert perf.data file. Try github.com/google/perf_data_converter: %v", err)
  489. }
  490. return profile, nil
  491. }
  492. // adjustURL validates if a profile source is a URL and returns an
  493. // cleaned up URL and the timeout to use for retrieval over HTTP.
  494. // If the source cannot be recognized as a URL it returns an empty string.
  495. func adjustURL(source string, duration, timeout time.Duration) (string, time.Duration) {
  496. u, err := url.Parse(source)
  497. if err != nil || (u.Host == "" && u.Scheme != "" && u.Scheme != "file") {
  498. // Try adding http:// to catch sources of the form hostname:port/path.
  499. // url.Parse treats "hostname" as the scheme.
  500. u, err = url.Parse("http://" + source)
  501. }
  502. if err != nil || u.Host == "" {
  503. return "", 0
  504. }
  505. // Apply duration/timeout overrides to URL.
  506. values := u.Query()
  507. if duration > 0 {
  508. values.Set("seconds", fmt.Sprint(int(duration.Seconds())))
  509. } else {
  510. if urlSeconds := values.Get("seconds"); urlSeconds != "" {
  511. if us, err := strconv.ParseInt(urlSeconds, 10, 32); err == nil {
  512. duration = time.Duration(us) * time.Second
  513. }
  514. }
  515. }
  516. if timeout <= 0 {
  517. if duration > 0 {
  518. timeout = duration + duration/2
  519. } else {
  520. timeout = 60 * time.Second
  521. }
  522. }
  523. u.RawQuery = values.Encode()
  524. return u.String(), timeout
  525. }
  526. // httpGet is a wrapper around http.Get; it is defined as a variable
  527. // so it can be redefined during for testing.
  528. var httpGet = func(source string, timeout time.Duration) (*http.Response, error) {
  529. url, err := url.Parse(source)
  530. if err != nil {
  531. return nil, err
  532. }
  533. var tlsConfig *tls.Config
  534. if url.Scheme == "https+insecure" {
  535. tlsConfig = &tls.Config{
  536. InsecureSkipVerify: true,
  537. }
  538. url.Scheme = "https"
  539. source = url.String()
  540. }
  541. client := &http.Client{
  542. Transport: &http.Transport{
  543. ResponseHeaderTimeout: timeout + 5*time.Second,
  544. Proxy: http.ProxyFromEnvironment,
  545. TLSClientConfig: tlsConfig,
  546. },
  547. }
  548. return client.Get(source)
  549. }