Нет описания

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. "net/http"
  21. "net/url"
  22. "os"
  23. "os/exec"
  24. "path/filepath"
  25. "strconv"
  26. "sync"
  27. "time"
  28. "github.com/google/pprof/internal/measurement"
  29. "github.com/google/pprof/internal/plugin"
  30. "github.com/google/pprof/profile"
  31. )
  32. // fetchProfiles fetches and symbolizes the profiles specified by s.
  33. // It will merge all the profiles it is able to retrieve, even if
  34. // there are some failures. It will return an error if it is unable to
  35. // fetch any profiles.
  36. func fetchProfiles(s *source, o *plugin.Options) (*profile.Profile, error) {
  37. sources := make([]profileSource, 0, len(s.Sources)+len(s.Base))
  38. for _, src := range s.Sources {
  39. sources = append(sources, profileSource{
  40. addr: src,
  41. source: s,
  42. scale: 1,
  43. })
  44. }
  45. for _, src := range s.Base {
  46. sources = append(sources, profileSource{
  47. addr: src,
  48. source: s,
  49. scale: -1,
  50. })
  51. }
  52. p, msrcs, save, cnt, err := chunkedGrab(sources, o.Fetch, o.Obj, o.UI)
  53. if err != nil {
  54. return nil, err
  55. }
  56. if cnt == 0 {
  57. return nil, fmt.Errorf("failed to fetch any profiles")
  58. }
  59. if want, got := len(sources), cnt; want != got {
  60. o.UI.PrintErr(fmt.Sprintf("fetched %d profiles out of %d", got, want))
  61. }
  62. // Symbolize the merged profile.
  63. if err := o.Sym.Symbolize(s.Symbolize, msrcs, p); err != nil {
  64. return nil, err
  65. }
  66. p.RemoveUninteresting()
  67. unsourceMappings(p)
  68. // Save a copy of the merged profile if there is at least one remote source.
  69. if save {
  70. dir, err := setTmpDir(o.UI)
  71. if err != nil {
  72. return nil, err
  73. }
  74. prefix := "pprof."
  75. if len(p.Mapping) > 0 && p.Mapping[0].File != "" {
  76. prefix += filepath.Base(p.Mapping[0].File) + "."
  77. }
  78. for _, s := range p.SampleType {
  79. prefix += s.Type + "."
  80. }
  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 prepares the directory to use to save profiles retrieved
  193. // remotely. It is selected from PPROF_TMPDIR, defaults to $HOME/pprof.
  194. func setTmpDir(ui plugin.UI) (string, error) {
  195. if profileDir := os.Getenv("PPROF_TMPDIR"); profileDir != "" {
  196. return profileDir, nil
  197. }
  198. for _, tmpDir := range []string{os.Getenv("HOME") + "/pprof", os.TempDir()} {
  199. if err := os.MkdirAll(tmpDir, 0755); err != nil {
  200. ui.PrintErr("Could not use temp dir ", tmpDir, ": ", err.Error())
  201. continue
  202. }
  203. return tmpDir, nil
  204. }
  205. return "", fmt.Errorf("failed to identify temp dir")
  206. }
  207. // grabProfile fetches a profile. Returns the profile, sources for the
  208. // profile mappings, a bool indicating if the profile was fetched
  209. // remotely, and an error.
  210. 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) {
  211. var src string
  212. duration, timeout := time.Duration(s.Seconds)*time.Second, time.Duration(s.Timeout)*time.Second
  213. if fetcher != nil {
  214. p, src, err = fetcher.Fetch(source, duration, timeout)
  215. if err != nil {
  216. return
  217. }
  218. }
  219. if err != nil || p == nil {
  220. // Fetch the profile over HTTP or from a file.
  221. p, src, err = fetch(source, duration, timeout, ui)
  222. if err != nil {
  223. return
  224. }
  225. }
  226. if err = p.CheckValid(); err != nil {
  227. return
  228. }
  229. // Apply local changes to the profile.
  230. p.Scale(scale)
  231. // Update the binary locations from command line and paths.
  232. locateBinaries(p, s, obj, ui)
  233. // Collect the source URL for all mappings.
  234. if src != "" {
  235. msrc = collectMappingSources(p, src)
  236. remote = true
  237. }
  238. return
  239. }
  240. // collectMappingSources saves the mapping sources of a profile.
  241. func collectMappingSources(p *profile.Profile, source string) plugin.MappingSources {
  242. ms := plugin.MappingSources{}
  243. for _, m := range p.Mapping {
  244. src := struct {
  245. Source string
  246. Start uint64
  247. }{
  248. source, m.Start,
  249. }
  250. key := m.BuildID
  251. if key == "" {
  252. key = m.File
  253. }
  254. if key == "" {
  255. // If there is no build id or source file, use the source as the
  256. // mapping file. This will enable remote symbolization for this
  257. // mapping, in particular for Go profiles on the legacy format.
  258. // The source is reset back to empty string by unsourceMapping
  259. // which is called after symbolization is finished.
  260. m.File = source
  261. key = source
  262. }
  263. ms[key] = append(ms[key], src)
  264. }
  265. return ms
  266. }
  267. // unsourceMappings iterates over the mappings in a profile and replaces file
  268. // set to the remote source URL by collectMappingSources back to empty string.
  269. func unsourceMappings(p *profile.Profile) {
  270. for _, m := range p.Mapping {
  271. if m.BuildID == "" {
  272. if u, err := url.Parse(m.File); err == nil && u.IsAbs() {
  273. m.File = ""
  274. }
  275. }
  276. }
  277. }
  278. // locateBinaries searches for binary files listed in the profile and, if found,
  279. // updates the profile accordingly.
  280. func locateBinaries(p *profile.Profile, s *source, obj plugin.ObjTool, ui plugin.UI) {
  281. // Construct search path to examine
  282. searchPath := os.Getenv("PPROF_BINARY_PATH")
  283. if searchPath == "" {
  284. // Use $HOME/pprof/binaries as default directory for local symbolization binaries
  285. searchPath = filepath.Join(os.Getenv("HOME"), "pprof", "binaries")
  286. }
  287. mapping:
  288. for i, m := range p.Mapping {
  289. var baseName string
  290. // Replace executable filename/buildID with the overrides from source.
  291. // Assumes the executable is the first Mapping entry.
  292. if i == 0 {
  293. if s.ExecName != "" {
  294. m.File = s.ExecName
  295. }
  296. if s.BuildID != "" {
  297. m.BuildID = s.BuildID
  298. }
  299. }
  300. if m.File != "" {
  301. baseName = filepath.Base(m.File)
  302. }
  303. for _, path := range filepath.SplitList(searchPath) {
  304. var fileNames []string
  305. if m.BuildID != "" {
  306. fileNames = []string{filepath.Join(path, m.BuildID, baseName)}
  307. if matches, err := filepath.Glob(filepath.Join(path, m.BuildID, "*")); err == nil {
  308. fileNames = append(fileNames, matches...)
  309. }
  310. }
  311. if baseName != "" {
  312. fileNames = append(fileNames, filepath.Join(path, baseName))
  313. }
  314. for _, name := range fileNames {
  315. if f, err := obj.Open(name, m.Start, m.Limit, m.Offset); err == nil {
  316. defer f.Close()
  317. fileBuildID := f.BuildID()
  318. if m.BuildID != "" && m.BuildID != fileBuildID {
  319. ui.PrintErr("Ignoring local file " + name + ": build-id mismatch (" + m.BuildID + " != " + fileBuildID + ")")
  320. } else {
  321. m.File = name
  322. continue mapping
  323. }
  324. }
  325. }
  326. }
  327. }
  328. }
  329. // fetch fetches a profile from source, within the timeout specified,
  330. // producing messages through the ui. It returns the profile and the
  331. // url of the actual source of the profile for remote profiles.
  332. func fetch(source string, duration, timeout time.Duration, ui plugin.UI) (p *profile.Profile, src string, err error) {
  333. var f io.ReadCloser
  334. if sourceURL, timeout := adjustURL(source, duration, timeout); sourceURL != "" {
  335. ui.Print("Fetching profile over HTTP from " + sourceURL)
  336. if duration > 0 {
  337. ui.Print(fmt.Sprintf("Please wait... (%v)", duration))
  338. }
  339. f, err = fetchURL(sourceURL, timeout)
  340. src = sourceURL
  341. } else if isPerfFile(source) {
  342. f, err = convertPerfData(source, ui)
  343. } else {
  344. f, err = os.Open(source)
  345. }
  346. if err == nil {
  347. defer f.Close()
  348. p, err = profile.Parse(f)
  349. }
  350. return
  351. }
  352. // fetchURL fetches a profile from a URL using HTTP.
  353. func fetchURL(source string, timeout time.Duration) (io.ReadCloser, error) {
  354. resp, err := httpGet(source, timeout)
  355. if err != nil {
  356. return nil, fmt.Errorf("http fetch: %v", err)
  357. }
  358. if resp.StatusCode != http.StatusOK {
  359. return nil, fmt.Errorf("server response: %s", resp.Status)
  360. }
  361. return resp.Body, nil
  362. }
  363. // isPerfFile checks if a file is in perf.data format. It also returns false
  364. // if it encounters an error during the check.
  365. func isPerfFile(path string) bool {
  366. sourceFile, openErr := os.Open(path)
  367. if openErr != nil {
  368. return false
  369. }
  370. defer sourceFile.Close()
  371. // If the file is the output of a perf record command, it should begin
  372. // with the string PERFILE2.
  373. perfHeader := []byte("PERFILE2")
  374. actualHeader := make([]byte, len(perfHeader))
  375. if _, readErr := sourceFile.Read(actualHeader); readErr != nil {
  376. return false
  377. }
  378. return bytes.Equal(actualHeader, perfHeader)
  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 file containing the
  382. // profile.proto formatted data.
  383. func convertPerfData(perfPath string, ui plugin.UI) (*os.File, error) {
  384. ui.Print(fmt.Sprintf(
  385. "Converting %s to a profile.proto... (May take a few minutes)",
  386. perfPath))
  387. profile, err := newTempFile(os.TempDir(), "pprof_", ".pb.gz")
  388. if err != nil {
  389. return nil, err
  390. }
  391. deferDeleteTempFile(profile.Name())
  392. cmd := exec.Command("perf_to_profile", perfPath, profile.Name())
  393. if err := cmd.Run(); err != nil {
  394. profile.Close()
  395. return nil, fmt.Errorf("failed to convert perf.data file. Try github.com/google/perf_data_converter: %v", err)
  396. }
  397. return profile, nil
  398. }
  399. // adjustURL validates if a profile source is a URL and returns an
  400. // cleaned up URL and the timeout to use for retrieval over HTTP.
  401. // If the source cannot be recognized as a URL it returns an empty string.
  402. func adjustURL(source string, duration, timeout time.Duration) (string, time.Duration) {
  403. u, err := url.Parse(source)
  404. if err != nil || (u.Host == "" && u.Scheme != "" && u.Scheme != "file") {
  405. // Try adding http:// to catch sources of the form hostname:port/path.
  406. // url.Parse treats "hostname" as the scheme.
  407. u, err = url.Parse("http://" + source)
  408. }
  409. if err != nil || u.Host == "" {
  410. return "", 0
  411. }
  412. // Apply duration/timeout overrides to URL.
  413. values := u.Query()
  414. if duration > 0 {
  415. values.Set("seconds", fmt.Sprint(int(duration.Seconds())))
  416. } else {
  417. if urlSeconds := values.Get("seconds"); urlSeconds != "" {
  418. if us, err := strconv.ParseInt(urlSeconds, 10, 32); err == nil {
  419. duration = time.Duration(us) * time.Second
  420. }
  421. }
  422. }
  423. if timeout <= 0 {
  424. if duration > 0 {
  425. timeout = duration + duration/2
  426. } else {
  427. timeout = 60 * time.Second
  428. }
  429. }
  430. u.RawQuery = values.Encode()
  431. return u.String(), timeout
  432. }
  433. // httpGet is a wrapper around http.Get; it is defined as a variable
  434. // so it can be redefined during for testing.
  435. var httpGet = func(source string, timeout time.Duration) (*http.Response, error) {
  436. url, err := url.Parse(source)
  437. if err != nil {
  438. return nil, err
  439. }
  440. var tlsConfig *tls.Config
  441. if url.Scheme == "https+insecure" {
  442. tlsConfig = &tls.Config{
  443. InsecureSkipVerify: true,
  444. }
  445. url.Scheme = "https"
  446. source = url.String()
  447. }
  448. client := &http.Client{
  449. Transport: &http.Transport{
  450. ResponseHeaderTimeout: timeout + 5*time.Second,
  451. Proxy: http.ProxyFromEnvironment,
  452. TLSClientConfig: tlsConfig,
  453. },
  454. }
  455. return client.Get(source)
  456. }