Нет описания

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