暫無描述

fetch.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. "encoding/base64"
  18. "fmt"
  19. "io"
  20. "math/rand"
  21. "net/http"
  22. "net/url"
  23. "os"
  24. "os/exec"
  25. "path/filepath"
  26. "strconv"
  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. if err := setTmpDir(o.UI); err != nil {
  39. return nil, err
  40. }
  41. sources := make([]profileSource, 0, len(s.Sources)+len(s.Base))
  42. for _, src := range s.Sources {
  43. sources = append(sources, profileSource{
  44. addr: src,
  45. source: s,
  46. scale: 1,
  47. })
  48. }
  49. for _, src := range s.Base {
  50. sources = append(sources, profileSource{
  51. addr: src,
  52. source: s,
  53. scale: -1,
  54. })
  55. }
  56. p, msrcs, save, cnt, err := chunkedGrab(sources, o.Fetch, o.Obj, o.UI)
  57. if err != nil {
  58. return nil, err
  59. }
  60. if cnt == 0 {
  61. return nil, fmt.Errorf("failed to fetch any profiles")
  62. }
  63. if want, got := len(sources), cnt; want != got {
  64. o.UI.PrintErr(fmt.Sprintf("fetched %d profiles out of %d", got, want))
  65. }
  66. // Symbolize the merged profile.
  67. if err := o.Sym.Symbolize(s.Symbolize, msrcs, p); err != nil {
  68. return nil, err
  69. }
  70. p.RemoveUninteresting()
  71. // Save a copy of the merged profile if there is at least one remote source.
  72. if save {
  73. prefix := "pprof."
  74. if len(p.Mapping) > 0 && p.Mapping[0].File != "" {
  75. prefix += filepath.Base(p.Mapping[0].File) + "."
  76. }
  77. for _, s := range p.SampleType {
  78. prefix += s.Type + "."
  79. }
  80. dir := os.Getenv("PPROF_TMPDIR")
  81. tempFile, err := newTempFile(dir, prefix, ".pb.gz")
  82. if err == nil {
  83. if err = p.Write(tempFile); err == nil {
  84. o.UI.PrintErr("Saved profile in ", tempFile.Name())
  85. }
  86. }
  87. if err != nil {
  88. o.UI.PrintErr("Could not save profile: ", err)
  89. }
  90. }
  91. if err := p.CheckValid(); err != nil {
  92. return nil, err
  93. }
  94. return p, nil
  95. }
  96. // chunkedGrab fetches the profiles described in source and merges them into
  97. // a single profile. It fetches a chunk of profiles concurrently, with a maximum
  98. // chunk size to limit its memory usage.
  99. func chunkedGrab(sources []profileSource, fetch plugin.Fetcher, obj plugin.ObjTool, ui plugin.UI) (*profile.Profile, plugin.MappingSources, bool, int, error) {
  100. const chunkSize = 64
  101. var p *profile.Profile
  102. var msrc plugin.MappingSources
  103. var save bool
  104. var count int
  105. for start := 0; start < len(sources); start += chunkSize {
  106. end := start + chunkSize
  107. if end > len(sources) {
  108. end = len(sources)
  109. }
  110. chunkP, chunkMsrc, chunkSave, chunkCount, chunkErr := concurrentGrab(sources[start:end], fetch, obj, ui)
  111. switch {
  112. case chunkErr != nil:
  113. return nil, nil, false, 0, chunkErr
  114. case chunkP == nil:
  115. continue
  116. case p == nil:
  117. p, msrc, save, count = chunkP, chunkMsrc, chunkSave, chunkCount
  118. default:
  119. p, msrc, chunkErr = combineProfiles([]*profile.Profile{p, chunkP}, []plugin.MappingSources{msrc, chunkMsrc})
  120. if chunkErr != nil {
  121. return nil, nil, false, 0, chunkErr
  122. }
  123. if chunkSave {
  124. save = true
  125. }
  126. count += chunkCount
  127. }
  128. }
  129. return p, msrc, save, count, nil
  130. }
  131. // concurrentGrab fetches multiple profiles concurrently
  132. func concurrentGrab(sources []profileSource, fetch plugin.Fetcher, obj plugin.ObjTool, ui plugin.UI) (*profile.Profile, plugin.MappingSources, bool, int, error) {
  133. wg := sync.WaitGroup{}
  134. wg.Add(len(sources))
  135. for i := range sources {
  136. go func(s *profileSource) {
  137. defer wg.Done()
  138. s.p, s.msrc, s.remote, s.err = grabProfile(s.source, s.addr, s.scale, fetch, obj, ui)
  139. }(&sources[i])
  140. }
  141. wg.Wait()
  142. var save bool
  143. profiles := make([]*profile.Profile, 0, len(sources))
  144. msrcs := make([]plugin.MappingSources, 0, len(sources))
  145. for i := range sources {
  146. s := &sources[i]
  147. if err := s.err; err != nil {
  148. ui.PrintErr(s.addr + ": " + err.Error())
  149. continue
  150. }
  151. save = save || s.remote
  152. profiles = append(profiles, s.p)
  153. msrcs = append(msrcs, s.msrc)
  154. *s = profileSource{}
  155. }
  156. if len(profiles) == 0 {
  157. return nil, nil, false, 0, nil
  158. }
  159. p, msrc, err := combineProfiles(profiles, msrcs)
  160. if err != nil {
  161. return nil, nil, false, 0, err
  162. }
  163. return p, msrc, save, len(profiles), nil
  164. }
  165. func combineProfiles(profiles []*profile.Profile, msrcs []plugin.MappingSources) (*profile.Profile, plugin.MappingSources, error) {
  166. // Merge profiles.
  167. if err := measurement.ScaleProfiles(profiles); err != nil {
  168. return nil, nil, err
  169. }
  170. p, err := profile.Merge(profiles)
  171. if err != nil {
  172. return nil, nil, err
  173. }
  174. // Combine mapping sources.
  175. msrc := make(plugin.MappingSources)
  176. for _, ms := range msrcs {
  177. for m, s := range ms {
  178. msrc[m] = append(msrc[m], s...)
  179. }
  180. }
  181. return p, msrc, nil
  182. }
  183. type profileSource struct {
  184. addr string
  185. source *source
  186. scale float64
  187. p *profile.Profile
  188. msrc plugin.MappingSources
  189. remote bool
  190. err error
  191. }
  192. // setTmpDir sets the PPROF_TMPDIR environment variable with a new
  193. // temp directory, if not already set.
  194. func setTmpDir(ui plugin.UI) error {
  195. if profileDir := os.Getenv("PPROF_TMPDIR"); profileDir != "" {
  196. return nil
  197. }
  198. for _, tmpDir := range []string{os.Getenv("HOME") + "/pprof", "/tmp"} {
  199. if err := os.MkdirAll(tmpDir, 0755); err != nil {
  200. ui.PrintErr("Could not use temp dir ", tmpDir, ": ", err.Error())
  201. continue
  202. }
  203. os.Setenv("PPROF_TMPDIR", tmpDir)
  204. return 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. m.File = source
  260. key = source
  261. }
  262. ms[key] = append(ms[key], src)
  263. }
  264. return ms
  265. }
  266. // locateBinaries searches for binary files listed in the profile and, if found,
  267. // updates the profile accordingly.
  268. func locateBinaries(p *profile.Profile, s *source, obj plugin.ObjTool, ui plugin.UI) {
  269. // Construct search path to examine
  270. searchPath := os.Getenv("PPROF_BINARY_PATH")
  271. if searchPath == "" {
  272. // Use $HOME/pprof/binaries as default directory for local symbolization binaries
  273. searchPath = filepath.Join(os.Getenv("HOME"), "pprof", "binaries")
  274. }
  275. mapping:
  276. for i, m := range p.Mapping {
  277. var baseName string
  278. // Replace executable filename/buildID with the overrides from source.
  279. // Assumes the executable is the first Mapping entry.
  280. if i == 0 {
  281. if s.ExecName != "" {
  282. m.File = s.ExecName
  283. }
  284. if s.BuildID != "" {
  285. m.BuildID = s.BuildID
  286. }
  287. }
  288. if m.File != "" {
  289. baseName = filepath.Base(m.File)
  290. }
  291. for _, path := range filepath.SplitList(searchPath) {
  292. var fileNames []string
  293. if m.BuildID != "" {
  294. fileNames = []string{filepath.Join(path, m.BuildID, baseName)}
  295. if matches, err := filepath.Glob(filepath.Join(path, m.BuildID, "*")); err == nil {
  296. fileNames = append(fileNames, matches...)
  297. }
  298. }
  299. if baseName != "" {
  300. fileNames = append(fileNames, filepath.Join(path, baseName))
  301. }
  302. for _, name := range fileNames {
  303. if f, err := obj.Open(name, m.Start, m.Limit, m.Offset); err == nil {
  304. defer f.Close()
  305. fileBuildID := f.BuildID()
  306. if m.BuildID != "" && m.BuildID != fileBuildID {
  307. ui.PrintErr("Ignoring local file " + name + ": build-id mismatch (" + m.BuildID + " != " + fileBuildID + ")")
  308. } else {
  309. m.File = name
  310. continue mapping
  311. }
  312. }
  313. }
  314. }
  315. }
  316. }
  317. // fetch fetches a profile from source, within the timeout specified,
  318. // producing messages through the ui. It returns the profile and the
  319. // url of the actual source of the profile for remote profiles.
  320. func fetch(source string, duration, timeout time.Duration, ui plugin.UI) (p *profile.Profile, src string, err error) {
  321. var f io.ReadCloser
  322. if sourceURL, timeout := adjustURL(source, duration, timeout); sourceURL != "" {
  323. ui.Print("Fetching profile over HTTP from " + sourceURL)
  324. if duration > 0 {
  325. ui.Print(fmt.Sprintf("Please wait... (%v)", duration))
  326. }
  327. f, err = fetchURL(sourceURL, timeout)
  328. src = sourceURL
  329. } else {
  330. f, err = profileProtoReader(source, ui)
  331. }
  332. if err == nil {
  333. defer f.Close()
  334. p, err = profile.Parse(f)
  335. }
  336. return
  337. }
  338. // fetchURL fetches a profile from a URL using HTTP.
  339. func fetchURL(source string, timeout time.Duration) (io.ReadCloser, error) {
  340. resp, err := httpGet(source, timeout)
  341. if err != nil {
  342. return nil, fmt.Errorf("http fetch %s: %v", source, err)
  343. }
  344. if resp.StatusCode != http.StatusOK {
  345. return nil, fmt.Errorf("server response: %s", resp.Status)
  346. }
  347. return resp.Body, nil
  348. }
  349. // profileProtoReader takes a path, and using heuristics, will try to convert
  350. // the file to profile.proto format. It returns a ReadCloser to the
  351. // profile.proto data; however, if the file contents were unknown or conversion
  352. // failed, it may still not be a valid profile.proto.
  353. func profileProtoReader(path string, ui plugin.UI) (io.ReadCloser, error) {
  354. sourceFile, openErr := os.Open(path)
  355. if openErr != nil {
  356. return nil, openErr
  357. }
  358. // If the file is the output of a perf record command, it should begin
  359. // with the string PERFILE2.
  360. perfHeader := []byte("PERFILE2")
  361. actualHeader := make([]byte, len(perfHeader))
  362. _, readErr := sourceFile.Read(actualHeader)
  363. _, seekErr := sourceFile.Seek(0, 0)
  364. if seekErr != nil {
  365. return nil, seekErr
  366. }
  367. if readErr != nil && readErr != io.EOF{
  368. return nil, readErr
  369. }
  370. if bytes.Equal(actualHeader, perfHeader) {
  371. sourceFile.Close()
  372. profileFile, convertErr := convertPerfData(path, ui)
  373. if convertErr != nil {
  374. return nil, convertErr
  375. }
  376. return os.Open(profileFile)
  377. }
  378. return sourceFile, nil
  379. }
  380. // convertPerfData converts the file at path which should be in perf.data format
  381. // using the perf_to_profile tool and returns the path to a file containing the
  382. // profile.proto formatted data.
  383. func convertPerfData(perfPath string, ui plugin.UI) (string, error) {
  384. ui.Print(fmt.Sprintf(
  385. "Converting %s to a profile.proto... (May take a few minutes)",
  386. perfPath))
  387. randomBytes := make([]byte, 32)
  388. _, randErr := rand.Read(randomBytes)
  389. if randErr != nil {
  390. return "", randErr
  391. }
  392. randomFileName := "/tmp/pprof_" +
  393. base64.StdEncoding.EncodeToString(randomBytes)
  394. cmd := exec.Command("perf_to_profile", perfPath, randomFileName)
  395. if err := cmd.Run(); err != nil {
  396. return "", err
  397. }
  398. return randomFileName, nil
  399. }
  400. // adjustURL validates if a profile source is a URL and returns an
  401. // cleaned up URL and the timeout to use for retrieval over HTTP.
  402. // If the source cannot be recognized as a URL it returns an empty string.
  403. func adjustURL(source string, duration, timeout time.Duration) (string, time.Duration) {
  404. u, err := url.Parse(source)
  405. if err != nil || (u.Host == "" && u.Scheme != "" && u.Scheme != "file") {
  406. // Try adding http:// to catch sources of the form hostname:port/path.
  407. // url.Parse treats "hostname" as the scheme.
  408. u, err = url.Parse("http://" + source)
  409. }
  410. if err != nil || u.Host == "" {
  411. return "", 0
  412. }
  413. // Apply duration/timeout overrides to URL.
  414. values := u.Query()
  415. if duration > 0 {
  416. values.Set("seconds", fmt.Sprint(int(duration.Seconds())))
  417. } else {
  418. if urlSeconds := values.Get("seconds"); urlSeconds != "" {
  419. if us, err := strconv.ParseInt(urlSeconds, 10, 32); err == nil {
  420. duration = time.Duration(us) * time.Second
  421. }
  422. }
  423. }
  424. if timeout <= 0 {
  425. if duration > 0 {
  426. timeout = duration + duration/2
  427. } else {
  428. timeout = 60 * time.Second
  429. }
  430. }
  431. u.RawQuery = values.Encode()
  432. return u.String(), timeout
  433. }
  434. // httpGet is a wrapper around http.Get; it is defined as a variable
  435. // so it can be redefined during for testing.
  436. var httpGet = func(url string, timeout time.Duration) (*http.Response, error) {
  437. client := &http.Client{
  438. Transport: &http.Transport{
  439. ResponseHeaderTimeout: timeout + 5*time.Second,
  440. },
  441. }
  442. return client.Get(url)
  443. }