panicparse: github.com/maruel/panicparse/stack Index | Examples | Files | Directories

package stack

import "github.com/maruel/panicparse/stack"

Package stack analyzes stack dump of Go processes and simplifies it.

It is mostly useful on servers will large number of identical goroutines, making the crash dump harder to read than strictly necessary.

Code:

// Optional: Check for GOTRACEBACK being set, in particular if there is only
// one goroutine returned.
in := bytes.NewBufferString(crash)
s, suffix, err := stack.ScanSnapshot(in, os.Stdout, stack.DefaultOpts())
// io.EOF is returned when the whole stream was read, otherwise there could
// still be input data left.
if err != nil && err != io.EOF {
    return
}

// Find out similar goroutine traces and group them into buckets.
buckets := stack.Aggregate(s.Goroutines, stack.AnyValue)

// Calculate alignment.
srcLen := 0
pkgLen := 0
for _, bucket := range buckets {
    for _, line := range bucket.Signature.Stack.Calls {
        if l := len(fmt.Sprintf("%s:%d", line.SrcName, line.Line)); l > srcLen {
            srcLen = l
        }
        if l := len(filepath.Base(line.Func.ImportPath)); l > pkgLen {
            pkgLen = l
        }
    }
}

for _, bucket := range buckets {
    // Print the goroutine header.
    extra := ""
    if s := bucket.SleepString(); s != "" {
        extra += " [" + s + "]"
    }
    if bucket.Locked {
        extra += " [locked]"
    }

    if len(bucket.CreatedBy.Calls) != 0 {
        extra += fmt.Sprintf(" [Created by %s.%s @ %s:%d]", bucket.CreatedBy.Calls[0].Func.DirName, bucket.CreatedBy.Calls[0].Func.Name, bucket.CreatedBy.Calls[0].SrcName, bucket.CreatedBy.Calls[0].Line)
    }
    fmt.Printf("%d: %s%s\n", len(bucket.IDs), bucket.State, extra)

    // Print the stack lines.
    for _, line := range bucket.Stack.Calls {
        fmt.Printf(
            "    %-*s %-*s %s(%s)\n",
            pkgLen, line.Func.DirName, srcLen,
            fmt.Sprintf("%s:%d", line.SrcName, line.Line),
            line.Func.Name, &line.Args)
    }
    if bucket.Stack.Elided {
        io.WriteString(os.Stdout, "    (...)\n")
    }
}
// If there was any remaining data in the pipe, dump it now.
if len(suffix) != 0 {
    os.Stdout.Write(suffix)
}
if err == nil {
    io.Copy(os.Stdout, in)
}

Output:

panic: oh no!

1: running
         panic.go:464 panic(0, 0)
    main main.go:45   crash2(0x7fe50b49d028, 0xc82000a1e0)
    main main.go:50   main()
Extraneous output.

Code:

// Stream of stack traces:
var r io.Reader
var w io.Writer
opts := stack.DefaultOpts()
for {
    s, suffix, err := stack.ScanSnapshot(r, w, opts)
    if s != nil {
        // Process the snapshot...
    }

    if err != nil && err != io.EOF {
        if len(suffix) != 0 {
            w.Write(suffix)
        }
        return
    }
    // Prepend the suffix that was read to the rest of the input stream to
    // catch the next snapshot signature:
    r = io.MultiReader(bytes.NewReader(suffix), r)
}

Index

Examples

Package Files

bucket.go context.go go1.13.go reader.go source.go stack.go state_string.go

func Augment Uses

func Augment(goroutines []*Goroutine)

Augment processes source files to improve calls to be more descriptive.

It modifies goroutines in place. It requires calling GuessPaths() to work properly.

type Arg Uses

type Arg struct {
    // Value is the raw value as found in the stack trace
    Value uint64
    // Name is a pseudo name given to the argument
    Name string
    // IsPtr is true if we guess it's a pointer. It's only a guess, it can be
    // easily be confused by a bitmask.
    IsPtr bool
    // contains filtered or unexported fields
}

Arg is an argument on a Call.

func (*Arg) String Uses

func (a *Arg) String() string

String prints the argument as the name if present, otherwise as the value.

type Args Uses

type Args struct {
    // Values is the arguments as shown on the stack trace. They are mangled via
    // simplification.
    Values []Arg
    // Processed is the arguments generated from processing the source files. It
    // can have a length lower than Values.
    Processed []string
    // Elided when set means there was a trailing ", ...".
    Elided bool
    // contains filtered or unexported fields
}

Args is a series of function call arguments.

func (*Args) String Uses

func (a *Args) String() string

type Bucket Uses

type Bucket struct {
    // Signature is the generalized signature for this bucket.
    Signature
    // IDs is the ID of each Goroutine with this Signature.
    IDs []int
    // First is true if this Bucket contains the first goroutine, e.g. the one
    // Signature that likely generated the panic() call, if any.
    First bool
    // contains filtered or unexported fields
}

Bucket is a stack trace signature and the list of goroutines that fits this signature.

func Aggregate Uses

func Aggregate(goroutines []*Goroutine, similar Similarity) []*Bucket

Aggregate merges similar goroutines into buckets.

The buckets are ordered in library provided order of relevancy. You can reorder at your choosing.

type Call Uses

type Call struct {

    // Func is the fully qualified function name (encoded).
    Func Func
    // Args is the call arguments.
    Args Args

    // RemoteSrcPath is the full path name of the source file as seen in the
    // trace.
    RemoteSrcPath string
    // Line is the line number.
    Line int
    // SrcName is the base file name of the source file.
    SrcName string
    // DirSrc is one directory plus the file name of the source file. It is a
    // subset of RemoteSrcPath.
    DirSrc string

    // LocalSrcPath is the full path name of the source file as seen in the host,
    // if found.
    LocalSrcPath string
    // RelSrcPath is the relative path to GOROOT, GOPATH or LocalGoMods.
    RelSrcPath string
    // ImportPath is the fully qualified import path as found on disk (when
    // GuessPaths() was called). Defaults to Func.ImportPath otherwise.
    //
    // In the case of package "main", it returns the underlying path to the main
    // package instead of "main" if GuessPaths() was called.
    ImportPath string
    // IsStdlib is true if it is a Go standard library function. This includes
    // the 'go test' generated main executable.
    IsStdlib bool
    // contains filtered or unexported fields
}

Call is an item in the stack trace.

All paths in this struct are in POSIX format, using "/" as path separator.

type Func Uses

type Func struct {
    // Complete is the complete reference. It can be ambiguous in case where a
    // path contains dots.
    Complete string
    // ImportPath is the directory name for this function reference, or "main" if
    // it was in package main. The package name may not match.
    ImportPath string
    // DirName is the directory name containing the package in which the function
    // is. Normally this matches the package name, but sometimes there's smartass
    // folks that use a different directory name than the package name.
    DirName string
    // Name is the function name or fully quality method name.
    Name string
    // IsExported is true if the function is exported.
    IsExported bool
    // IsPkgMain is true if it is in the main package.
    IsPkgMain bool
    // contains filtered or unexported fields
}

Func is a function call in a goroutine stack trace.

func (*Func) Init Uses

func (f *Func) Init(raw string) error

Init parses the raw function call line from a goroutine stack trace.

Go stack traces print a mangled function call, this wrapper unmangle the string before printing and adds other filtering methods.

The main caveat is that for calls in package main, the package import URL is left out.

func (*Func) String Uses

func (f *Func) String() string

String returns Complete.

type Goroutine Uses

type Goroutine struct {
    // Signature is the stack trace, internal bits, state, which call site
    // created it, etc.
    Signature
    // ID is the goroutine id.
    ID  int
    // First is the goroutine first printed, normally the one that crashed.
    First bool

    // RaceWrite is true if a race condition was detected, and this goroutine was
    // race on a write operation, otherwise it was a read.
    RaceWrite bool
    // RaceAddr is set to the address when a data race condition was detected.
    // Otherwise it is 0.
    RaceAddr uint64
    // contains filtered or unexported fields
}

Goroutine represents the state of one goroutine, including the stack trace.

type Opts Uses

type Opts struct {
    // LocalGOROOT is GOROOT with "/" as path separator. No trailing "/". Can be
    // unset.
    LocalGOROOT string
    // LocalGOPATHs is GOPATH with "/" as path separator. No trailing "/". Can be
    // unset.
    LocalGOPATHs []string
    // contains filtered or unexported fields
}

Opts represents options to process the snapshot.

func DefaultOpts Uses

func DefaultOpts() *Opts

DefaultOpts returns default options to process the snapshot.

type Signature Uses

type Signature struct {
    // State is the goroutine state at the time of the snapshot.
    //
    // Use git grep 'gopark(|unlock)\(' to find them all plus everything listed
    // in runtime/traceback.go. Valid values includes:
    //     - chan send, chan receive, select
    //     - finalizer wait, mark wait (idle),
    //     - Concurrent GC wait, GC sweep wait, force gc (idle)
    //     - IO wait, panicwait
    //     - semacquire, semarelease
    //     - sleep, timer goroutine (idle)
    //     - trace reader (blocked)
    // Stuck cases:
    //     - chan send (nil chan), chan receive (nil chan), select (no cases)
    // Runnable states:
    //    - idle, runnable, running, syscall, waiting, dead, enqueue, copystack,
    // Scan states:
    //    - scan, scanrunnable, scanrunning, scansyscall, scanwaiting, scandead,
    //      scanenqueue
    //
    // When running under the race detector, the values are 'running' or
    // 'finished'.
    State string
    // CreatedBy is the call stack that created this goroutine, if applicable.
    //
    // Normally, the stack is a single Call.
    //
    // When the race detector is enabled, a full stack snapshot is available.
    CreatedBy Stack
    // SleepMin is the wait time in minutes, if applicable.
    //
    // Not set when running under the race detector.
    SleepMin int
    // SleepMax is the wait time in minutes, if applicable.
    //
    // Not set when running under the race detector.
    SleepMax int
    // Stack is the call stack.
    Stack Stack
    // Locked is set if the goroutine was locked to an OS thread.
    //
    // Not set when running under the race detector.
    Locked bool
    // contains filtered or unexported fields
}

Signature represents the signature of one or multiple goroutines.

It is effectively the stack trace plus the goroutine internal bits, like it's state, if it is thread locked, which call site created this goroutine, etc.

func (*Signature) SleepString Uses

func (s *Signature) SleepString() string

SleepString returns a string "N-M minutes" if the goroutine(s) slept for a long time.

Returns an empty string otherwise.

type Similarity Uses

type Similarity int

Similarity is the level at which two call lines arguments must match to be considered similar enough to coalesce them.

const (
    // ExactFlags requires same bits (e.g. Locked).
    ExactFlags Similarity = iota
    // ExactLines requests the exact same arguments on the call line.
    ExactLines
    // AnyPointer considers different pointers a similar call line.
    AnyPointer
    // AnyValue accepts any value as similar call line.
    AnyValue
)

type Snapshot Uses

type Snapshot struct {
    // Goroutines is the Goroutines found.
    //
    // They are in the order that they were printed.
    Goroutines []*Goroutine

    // LocalGOROOT is copied from Opts.
    LocalGOROOT string
    // LocalGOPATHs is copied from Opts.
    LocalGOPATHs []string

    // RemoteGOROOT is the GOROOT as detected in the traceback, not the on the
    // host.
    //
    // It can be empty if no root was determined, for example the traceback
    // contains only non-stdlib source references.
    RemoteGOROOT string
    // RemoteGOPATHs is the GOPATH as detected in the traceback, with the value
    // being the corresponding path mapped to the host if found.
    //
    // It can be empty if only stdlib code is in the traceback or if no local
    // sources were matched up. In the general case there is only one entry in
    // the map.
    RemoteGOPATHs map[string]string

    // LocalGomods are the root directories containing go.mod or that directly
    // contained source code as detected in the traceback, with the value being
    // the corresponding import path found in the go.mod file.
    //
    // Uses "/" as path separator. No trailing "/".
    //
    // Because of the "replace" statement in go.mod, there can be multiple root
    // directories. A file run by "go run" is also considered a go module to (a
    // certain extent).
    //
    // It is initialized by findRoots().
    //
    // Unlike GOROOT and GOPATH, it only works with stack traces created in the
    // local file system, hence "Local" prefix.
    LocalGomods map[string]string
    // contains filtered or unexported fields
}

Snapshot is a parsed runtime.Stack() or race detector dump.

func ScanSnapshot Uses

func ScanSnapshot(in io.Reader, prefix io.Writer, opts *Opts) (*Snapshot, []byte, error)

ScanSnapshot scans the Reader for the output from runtime.Stack() in br.

Returns nil *Snapshot if no stack trace was detected.

If a Snapshot is returned, you can call the function again to find another trace, or do io.Copy(br, out) to flush the rest of the stream.

ParseSnapshot processes the output from runtime.Stack() or the race detector.

Returns a nil *Snapshot if no stack trace was detected and SearchSnapshot() was a false positive.

Returns io.EOF if all of reader was read.

The suffix of the stack trace is returned as []byte.

It pipes anything not detected as a panic stack trace from r into out. It assumes there is junk before the actual stack trace. The junk is streamed to out.

func (*Snapshot) GuessPaths Uses

func (s *Snapshot) GuessPaths() bool

GuessPaths guesses local RemoteGOROOT and GOPATH for what was found in the snapshot.

Initializes RemoteGOROOT, RemoteGOPATHs, LocalGomoduleRoot and GomodImportPath.

This is done by scanning the local disk, so be warned of performance impact.

type Stack Uses

type Stack struct {
    // Calls is the call stack. First is original function, last is leaf
    // function.
    Calls []Call
    // Elided is set when there's >100 items in Stack, currently hardcoded in
    // package runtime.
    Elided bool
    // contains filtered or unexported fields
}

Stack is a call stack.

Directories

PathSynopsis
webstackPackage webstack provides a http.HandlerFunc that serves a snapshot similar to net/http/pprof.Index().

Package stack imports 22 packages (graph) and is imported by 39 packages. Updated 2020-08-05. Refresh now. Tools for package owners.