Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "trim path" option which can be used to relocate sources. #366

Merged
merged 3 commits into from
May 3, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions internal/driver/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ var pprofVariables = variables{
"Using auto will scale each value independently to the most natural unit.")},
"compact_labels": &variable{boolKind, "f", "", "Show minimal headers"},
"source_path": &variable{stringKind, "", "", "Search path for source files"},
"trim_path": &variable{stringKind, "", "", "Path to trim from source paths before search"},

// Filtering options
"nodecount": &variable{intKind, "-1", "", helpText(
Expand Down
1 change: 1 addition & 0 deletions internal/driver/driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ func reportOptions(p *profile.Profile, numLabelUnits map[string]string, vars var
OutputUnit: vars["unit"].value,

SourcePath: vars["source_path"].stringValue(),
TrimPath: vars["trim_path"].stringValue(),
}

if len(p.Mapping) > 0 && p.Mapping[0].File != "" {
Expand Down
3 changes: 2 additions & 1 deletion internal/report/report.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ type Options struct {

Symbol *regexp.Regexp // Symbols to include on disassembly report.
SourcePath string // Search path for source files.
TrimPath string // Paths to trim from source file paths.
}

// Generate generates a report as directed by the Report.
Expand Down Expand Up @@ -238,7 +239,7 @@ func (rpt *Report) newGraph(nodes graph.NodeSet) *graph.Graph {
// Clean up file paths using heuristics.
prof := rpt.prof
for _, f := range prof.Function {
f.Filename = trimPath(f.Filename)
f.Filename = trimPath(f.Filename, o.TrimPath, o.SourcePath)
}
// Removes all numeric tags except for the bytes tag prior
// to making graph.
Expand Down
4 changes: 3 additions & 1 deletion internal/report/report_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ func TestSource(t *testing.T) {
&Options{
OutputFormat: List,
Symbol: regexp.MustCompile(`.`),
TrimPath: "/some/path",

SampleValue: sampleValue1,
SampleUnit: testProfile.SampleType[1].Unit,
Expand All @@ -60,6 +61,7 @@ func TestSource(t *testing.T) {
OutputFormat: Dot,
CallTree: true,
Symbol: regexp.MustCompile(`.`),
TrimPath: "/some/path",

SampleValue: sampleValue1,
SampleUnit: testProfile.SampleType[1].Unit,
Expand Down Expand Up @@ -119,7 +121,7 @@ var testF = []*profile.Function{
{
ID: 4,
Name: "tee",
Filename: "testdata/source2",
Filename: "/some/path/testdata/source2",
},
}

Expand Down
79 changes: 51 additions & 28 deletions internal/report/source.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func printSource(w io.Writer, rpt *Report) error {
}
sourcePath = wd
}
reader := newSourceReader(sourcePath)
reader := newSourceReader(sourcePath, o.TrimPath)

fmt.Fprintf(w, "Total: %s\n", rpt.formatValue(rpt.total))
for _, fn := range functions {
Expand Down Expand Up @@ -146,7 +146,7 @@ func PrintWebList(w io.Writer, rpt *Report, obj plugin.ObjTool, maxFiles int) er
}
sourcePath = wd
}
reader := newSourceReader(sourcePath)
reader := newSourceReader(sourcePath, o.TrimPath)

type fileFunction struct {
fileName, functionName string
Expand Down Expand Up @@ -263,7 +263,7 @@ func assemblyPerSourceLine(objSyms []*objSymbol, rs graph.Nodes, src string, obj
//
// E.g., suppose we are printing source code for F and this
// instruction is from H where F called G called H and both
// of those calls were inlined. We want to use the line
// of those calls were inlined. We want to use the line
// number from F, not from H (which is what Disasm gives us).
//
// So find the outer-most linenumber in the source file.
Expand Down Expand Up @@ -391,16 +391,15 @@ func printFunctionSourceLine(w io.Writer, fn *graph.Node, assembly []assemblyIns
continue
}
curCalls = nil
fname := trimPath(c.file)
fline, ok := reader.line(fname, c.line)
fline, ok := reader.line(c.file, c.line)
if !ok {
fline = ""
}
text := strings.Repeat(" ", srcIndent+4+4*j) + strings.TrimSpace(fline)
fmt.Fprintf(w, " %8s %10s %10s %8s <span class=inlinesrc>%s</span> <span class=unimportant>%s:%d</span>\n",
"", "", "", "",
template.HTMLEscapeString(fmt.Sprintf("%-80s", text)),
template.HTMLEscapeString(filepath.Base(fname)), c.line)
template.HTMLEscapeString(filepath.Base(c.file)), c.line)
}
curCalls = an.inlineCalls
text := strings.Repeat(" ", srcIndent+4+4*len(curCalls)) + an.instruction
Expand All @@ -426,7 +425,6 @@ func printPageClosing(w io.Writer) {
// file and annotates it with the samples in fns. Returns the sources
// as nodes, using the info.name field to hold the source code.
func getSourceFromFile(file string, reader *sourceReader, fns graph.Nodes, start, end int) (graph.Nodes, string, error) {
file = trimPath(file)
lineNodes := make(map[int]graph.Nodes)

// Collect source coordinates from profile.
Expand Down Expand Up @@ -516,20 +514,26 @@ func getMissingFunctionSource(filename string, asm map[int][]assemblyInstruction

// sourceReader provides access to source code with caching of file contents.
type sourceReader struct {
// searchPath is a filepath.ListSeparator-separated list of directories where
// source files should be searched.
searchPath string

// trimPath is a filepath.ListSeparator-separated list of paths to trim.
trimPath string

// files maps from path name to a list of lines.
// files[*][0] is unused since line numbering starts at 1.
files map[string][]string

// errors collects errors encountered per file. These errors are
// errors collects errors encountered per file. These errors are
// consulted before returning out of these module.
errors map[string]error
}

func newSourceReader(searchPath string) *sourceReader {
func newSourceReader(searchPath, trimPath string) *sourceReader {
return &sourceReader{
searchPath,
trimPath,
make(map[string][]string),
make(map[string]error),
}
Expand All @@ -544,7 +548,7 @@ func (reader *sourceReader) line(path string, lineno int) (string, bool) {
if !ok {
// Read and cache file contents.
lines = []string{""} // Skip 0th line
f, err := openSourceFile(path, reader.searchPath)
f, err := openSourceFile(path, reader.searchPath, reader.trimPath)
if err != nil {
reader.errors[path] = err
} else {
Expand All @@ -565,17 +569,20 @@ func (reader *sourceReader) line(path string, lineno int) (string, bool) {
return lines[lineno], true
}

// openSourceFile opens a source file from a name encoded in a
// profile. File names in a profile after often relative paths, so
// search them in each of the paths in searchPath (or CWD by default),
// and their parents.
func openSourceFile(path, searchPath string) (*os.File, error) {
// openSourceFile opens a source file from a name encoded in a profile. File
// names in a profile after can be relative paths, so search them in each of
// the paths in searchPath and their parents. In case the profile contains
// absolute paths, additional paths may be configured to trim from the source
// paths in the profile. This effectively turns the path into a relative path
// searching it using searchPath as usual).
func openSourceFile(path, searchPath, trim string) (*os.File, error) {
path = trimPath(path, trim, searchPath)
// If file is still absolute, require file to exist.
if filepath.IsAbs(path) {
f, err := os.Open(path)
return f, err
}

// Scan each component of the path
// Scan each component of the path.
for _, dir := range filepath.SplitList(searchPath) {
// Search up for every parent of each possible path.
for {
Expand All @@ -595,18 +602,34 @@ func openSourceFile(path, searchPath string) (*os.File, error) {
}

// trimPath cleans up a path by removing prefixes that are commonly
// found on profiles.
func trimPath(path string) string {
basePaths := []string{
"/proc/self/cwd/./",
"/proc/self/cwd/",
// found on profiles plus configured prefixes.
// TODO(aalexand): Consider optimizing out the redundant work done in this
// function if it proves to matter.
func trimPath(path, trimPath, searchPath string) string {
// Keep path variable intact as it's used below to form the return value.
sPath, searchPath := filepath.ToSlash(path), filepath.ToSlash(searchPath)
if trimPath == "" {
// If the trim path is not configured, try to guess it heuristically:
// search for basename of each search path in the original path and, if
// found, strip everything up to and including the basename. So, for
// example, given original path "/some/remote/path/my-project/foo/bar.c"
// and search path "/my/local/path/my-project" the heuristic will return
// "/my/local/path/my-project/foo/bar.c".
for _, dir := range filepath.SplitList(searchPath) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is a little painful doing this search for every filename,

We could remember the heuristic trimPath we've used so far and try to apply them to the next filename before trying the search. I assume in the general case we will only have one.

Up to you, though. We could leave as a TODO.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking into whether it's worth it, will ping the PR.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I collected a couple of profiles over pprof itself while generating a graph for some larger profiles passing it a number of paths in -source_path and didn't see trimPath to show up substantially (saw something like 0.3% and the number of samples was low). I am also a bit hesitant to implement simple caching just remembering last trimPath since in interactive sessions user could change source path and trim path so those need to be part of the hashing key probably. Just leaving a TODO for now.

want := "/" + filepath.Base(dir) + "/"
if found := strings.Index(sPath, want); found != -1 {
return path[found+len(want):]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here we use path, but I think we should be using sPath? If we change sPath to path above then this problem goes away.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we want path instead of sPath, as we want to return the system path.

However, maybe we should use FromSlash(sPath). Not sure if there is a guarantee that in all platforms the path separator is a single character.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From https://golang.org/src/path/filepath/path.go?s=4426:4458#L155 and from ToSlash documentation that says "ToSlash returns the result of replacing each separator character in path with a slash ('/') character. Multiple separators are replaced by multiple slashes." I am pretty confident that it's safe to slice the original path using the slashized one as the index.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer to see FromSlash(sPath[found+len(want):]). Just because the subtle juggling of different path values makes the code harder to read.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the trimPath function could have a policy of converting path and trimPath using ToSlash operating only on these and then explicitly converting any return value using FromSlash. This would avoid having to reason about whether the indexes line up between different versions of each path on different OSes.

I agree with @aalexand that the indexes very likely do line up in every case. But I think it is undesirable to have to think so carefully about the correctness of this function. It would be preferable if it was obviously correct.

This has the downside of increasing allocations inside the trimPath function. I profiled the pprof tool using such an explicit To/FromSlash policy and found that the allocations in trimPath do not appear at all in the profile generated.

For reference my method of profiling is run

pprof --http :8081 -source_path ${GOPATH}/src:${GOROOT}/src profile_output

on an existing server. Then using the web-ui navigate to the source view and then take a heap profile of the running pprof process. The profile is then viewed with --sample_index=alloc_objects.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I too would prefer to use FromSlash on the return, if only for symmetry.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO the documentation for ToSlash and FromSlash clearly says that these functions only replace character for character, so I think there is nothing to worry about. Function name is trimPath so I think it's only job is trimming. I can rename it to trimAndFromSlashPath and make the suggested change if it's everybody's preference (not mine).

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that trimPath call is also used to trim the paths before displaying in the graph or source / assembly view, so ToSlash'ing the path here would make Unix paths display with backslash if someone opens on a Windows machine a profile collected on Linux. This is an edge case but I think the behavior as coded now would be more reasonable.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good point. Since running FromSlash(ToSlash(somePath)) won't always produce a string identical to somePath then I am happy with the function as it is.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SGTM. Thanks

}
}
}

sPath := filepath.ToSlash(path)

for _, base := range basePaths {
if strings.HasPrefix(sPath, base) {
return filepath.FromSlash(sPath[len(base):])
// Trim configured trim prefixes.
trimPaths := append(filepath.SplitList(filepath.ToSlash(trimPath)), "/proc/self/cwd/./", "/proc/self/cwd/")
for _, trimPath := range trimPaths {
if !strings.HasSuffix(trimPath, "/") {
trimPath += "/"
}
if strings.HasPrefix(sPath, trimPath) {
return path[len(trimPath):]
}
}
return path
Expand Down
50 changes: 33 additions & 17 deletions internal/report/source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,40 +48,56 @@ func TestOpenSourceFile(t *testing.T) {
for _, tc := range []struct {
desc string
searchPath string
trimPath string
fs []string
path string
wantPath string // If empty, error is wanted.
}{
{
desc: "exact absolute path is found",
fs: []string{"foo/bar.txt"},
path: "$dir/foo/bar.txt",
wantPath: "$dir/foo/bar.txt",
fs: []string{"foo/bar.cc"},
path: "$dir/foo/bar.cc",
wantPath: "$dir/foo/bar.cc",
},
{
desc: "exact relative path is found",
searchPath: "$dir",
fs: []string{"foo/bar.txt"},
path: "foo/bar.txt",
wantPath: "$dir/foo/bar.txt",
fs: []string{"foo/bar.cc"},
path: "foo/bar.cc",
wantPath: "$dir/foo/bar.cc",
},
{
desc: "multiple search path",
searchPath: "some/path" + lsep + "$dir",
fs: []string{"foo/bar.txt"},
path: "foo/bar.txt",
wantPath: "$dir/foo/bar.txt",
fs: []string{"foo/bar.cc"},
path: "foo/bar.cc",
wantPath: "$dir/foo/bar.cc",
},
{
desc: "relative path is found in parent dir",
searchPath: "$dir/foo/bar",
fs: []string{"bar.txt", "foo/bar/baz.txt"},
path: "bar.txt",
wantPath: "$dir/bar.txt",
fs: []string{"bar.cc", "foo/bar/baz.cc"},
path: "bar.cc",
wantPath: "$dir/bar.cc",
},
{
desc: "trims configured prefix",
searchPath: "$dir",
trimPath: "some-path" + lsep + "/some/remote/path",
fs: []string{"my-project/foo/bar.cc"},
path: "/some/remote/path/my-project/foo/bar.cc",
wantPath: "$dir/my-project/foo/bar.cc",
},
{
desc: "trims heuristically",
searchPath: "$dir/my-project",
fs: []string{"my-project/foo/bar.cc"},
path: "/some/remote/path/my-project/foo/bar.cc",
wantPath: "$dir/my-project/foo/bar.cc",
},
{
desc: "error when not found",
path: "foo.txt",
path: "foo.cc",
},
} {
t.Run(tc.desc, func(t *testing.T) {
Expand All @@ -103,15 +119,15 @@ func TestOpenSourceFile(t *testing.T) {
tc.searchPath = filepath.FromSlash(strings.Replace(tc.searchPath, "$dir", tempdir, -1))
tc.path = filepath.FromSlash(strings.Replace(tc.path, "$dir", tempdir, 1))
tc.wantPath = filepath.FromSlash(strings.Replace(tc.wantPath, "$dir", tempdir, 1))
if file, err := openSourceFile(tc.path, tc.searchPath); err != nil && tc.wantPath != "" {
t.Errorf("openSourceFile(%q, %q) = err %v, want path %q", tc.path, tc.searchPath, err, tc.wantPath)
if file, err := openSourceFile(tc.path, tc.searchPath, tc.trimPath); err != nil && tc.wantPath != "" {
t.Errorf("openSourceFile(%q, %q, %q) = err %v, want path %q", tc.path, tc.searchPath, tc.trimPath, err, tc.wantPath)
} else if err == nil {
defer file.Close()
gotPath := file.Name()
if tc.wantPath == "" {
t.Errorf("openSourceFile(%q, %q) = %q, want error", tc.path, tc.searchPath, gotPath)
t.Errorf("openSourceFile(%q, %q, %q) = %q, want error", tc.path, tc.searchPath, tc.trimPath, gotPath)
} else if gotPath != tc.wantPath {
t.Errorf("openSourceFile(%q, %q) = %q, want path %q", tc.path, tc.searchPath, gotPath, tc.wantPath)
t.Errorf("openSourceFile(%q, %q, %q) = %q, want path %q", tc.path, tc.searchPath, tc.trimPath, gotPath, tc.wantPath)
}
}
})
Expand Down