backtrace-go: github.com/backtrace-labs/backtrace-go Index | Files | Directories

package bt

import "github.com/backtrace-labs/backtrace-go"

Package bt provides integration with out-of-process tracers. Using the provided Tracer interface, applications may invoke tracer execution on demand. Panic and signal handling integrations are provided.

The Tracer interface is generic and will support any out-of-process tracer implementing it. A default Tracer implementation, which uses the Backtrace I/O platform, is provided.

Index

Package Files

bcd.go bcd_sys_linux.go main.go tracer.go

Constants

const (
    LogDebug = 1 << iota
    LogWarning
    LogError
    LogMax = (1 << iota) - 1
)
const VersionMajor = 0
const VersionMinor = 0
const VersionPatch = 0

Variables

var Version = fmt.Sprintf("%d.%d.%d", VersionMajor, VersionMinor, VersionPatch)

func AppendOptionWithPrefix Uses

func AppendOptionWithPrefix(options []string, prefix string, v string) []string

Append to an option with given prefix

func EnableTracing Uses

func EnableTracing() error

Call this function to allow other (non-parent) processes to trace this one. Alternatively, set kernel.yama.ptrace_scope = 0 in /etc/sysctl.d/10-ptrace.conf.

This is a Linux-specific utility function.

func FinishSendingReports Uses

func FinishSendingReports()

func Recover Uses

func Recover(t Tracer, repanic bool, options *TraceOptions)

Establishes a panic handler that will execute the specified Tracer in response. If repanic is true, this will repanic again after Tracer execution completes (with the original value returned by recover()). This must be used with Go's defer, panic, and recover pattern; see https://blog.golang.org/defer-panic-and-recover.

func Register Uses

func Register(t TracerSig)

Registers a signal handler to execute the specified Tracer upon receipt of any signal in the set specified by TracerSig.Sigset(). If the GlobalConfiguration value ResendSignal is true, then when a signal is received through this handler, all handlers for that signal will be reset with signal.Reset(s) after tracer execution completes. The signal will then be resent to the default Go handler for that signal.

func Report Uses

func Report(object interface{}, extra_attributes map[string]interface{})

func ReportAndRecoverPanic Uses

func ReportAndRecoverPanic(extra_attributes map[string]interface{})

func ReportPanic Uses

func ReportPanic(extra_attributes map[string]interface{})

func Trace Uses

func Trace(t Tracer, e error, traceOptions *TraceOptions) (err error)

Executes the specified Tracer on the current process.

If e is non-nil, it will be used to augment the trace according to the TraceOptions. If traceOptions is non-nil, it will be used instead of the Tracer's DefaultTraceOptions(). See TraceOptions for details on the various options.

This is goroutine-safe; multiple goroutines may share the same Tracer and execute Trace() concurrently. Only one tracer will be allowed to run at any point; others will wait to acquire resources (locks) or timeout (if timeouts are not disabled). Trace execution will be rate-limited according to the GlobalConfig settings.

This may also be called in a new goroutine via go Trace(...). In that case, ensure TraceOptions.CallerOnly is false (you will likely also want to set TraceOptions.Faulted to false); otherwise, only the newly spawned goroutine will be traced.

Output of specific Tracer execution depends on the implementation; most Tracers will have options for specifying output paths.

func Unregister Uses

func Unregister(t TracerSig)

Stops the specified TracerSig from handling any signals it was previously registered to handle via bt.Register().

func UpdateConfig Uses

func UpdateConfig(c GlobalConfig)

Update global Tracer configuration.

type BTTracer Uses

type BTTracer struct {
    // contains filtered or unexported fields
}

func New Uses

func New(options NewOptions) *BTTracer

Returns a new object implementing the bt.Tracer and bt.TracerSig interfaces using the Backtrace debugging platform. Currently, only Linux and FreeBSD are supported.

Relevant default values:

Tracer path: /opt/backtrace/bin/ptrace.

Output directory: Current working directory of process.

Signal set: ABRT, FPE, SEGV, ILL, BUS. Note: Go converts BUS, FPE, and SEGV arising from process execution into run-time panics, which cannot be handled by signal handlers. These signals are caught when sent from os.Process.Kill or similar.

The default logger prints to stderr.

DefaultTraceOptions:

Faulted: true

CallerOnly: false

ErrClassification: true

Timeout: 120s

func (*BTTracer) AddCallerGo Uses

func (t *BTTracer) AddCallerGo(options []string, goid int) []string

See bt.Tracer.AddCallerGo().

func (*BTTracer) AddClassifier Uses

func (t *BTTracer) AddClassifier(options []string, classifier string) []string

See bt.Tracer.AddClassifier().

func (*BTTracer) AddFaultedThread Uses

func (t *BTTracer) AddFaultedThread(options []string, tid int) []string

See bt.Tracer.AddFaultedThread().

func (*BTTracer) AddKV Uses

func (t *BTTracer) AddKV(options []string, key, val string) []string

See bt.Tracer.AddKV().

func (*BTTracer) AddOptions Uses

func (t *BTTracer) AddOptions(options []string, v ...string) []string

See bt.Tracer.AddOptions().

func (*BTTracer) AddThreadFilter Uses

func (t *BTTracer) AddThreadFilter(options []string, tid int) []string

See bt.Tracer.AddThreadFilter().

func (*BTTracer) AppendOptionWithPrefix Uses

func (t *BTTracer) AppendOptionWithPrefix(options []string, prefix string, v string) []string

func (*BTTracer) ClearOptions Uses

func (t *BTTracer) ClearOptions()

See bt.Tracer.ClearOptions().

func (*BTTracer) ConfigurePut Uses

func (t *BTTracer) ConfigurePut(endpoint, token string, options PutOptions) error

Configures the uploading of a generated snapshot file to a remote Backtrace coronerd object store.

Uploads use simple one-shot semantics and won't retry on failures. For more robust snapshot uploading and directory monitoring, consider using coroner daemon, as described at https://documentation.backtrace.io/snapshot/#daemon.

endpoint: The URL of the server. It must be a valid HTTP endpoint as according to url.Parse() (which is based on RFC 3986). The default scheme and port are https and 6098, respectively, and are used if left unspecified.

token: The hash associated with the coronerd project to which this application belongs; see https://documentation.backtrace.io/coronerd_setup/#authentication-tokens for more details.

options: Modifies behavior of the Put action; see PutOptions documentation for more details.

func (*BTTracer) DefaultTraceOptions Uses

func (t *BTTracer) DefaultTraceOptions() *TraceOptions

See bt.Tracer.DefaultTraceOptions().

func (*BTTracer) Finalize Uses

func (t *BTTracer) Finalize(options []string) *exec.Cmd

See bt.Tracer.Finalize().

func (*BTTracer) Logf Uses

func (t *BTTracer) Logf(level LogPriority, format string, v ...interface{})

func (*BTTracer) Options Uses

func (t *BTTracer) Options() []string

See bt.Tracer.Options().

func (*BTTracer) Put Uses

func (t *BTTracer) Put(snapshot []byte) error

See bt.Tracer.Put().

func (*BTTracer) PutDir Uses

func (t *BTTracer) PutDir(path string) error

Synchronously uploads snapshots contained in the specified directory. It is safe to spawn a goroutine to run BTTracer.PutDir().

ConfigurePut should have returned successfully before calling BTTracer.PutDir().

Only files with the '.btt' suffix will be uploaded.

The first error encountered terminates the directory walk, thus skipping snapshots which would have been processed later in the walk.

func (*BTTracer) PutOnTrace Uses

func (t *BTTracer) PutOnTrace() bool

See bt.Tracer.PutOnTrace().

func (*BTTracer) SetLogLevel Uses

func (t *BTTracer) SetLogLevel(level LogPriority)

func (*BTTracer) SetLogger Uses

func (t *BTTracer) SetLogger(logger Log)

Sets the logger for the tracer.

func (*BTTracer) SetOutputPath Uses

func (t *BTTracer) SetOutputPath(path string, perm os.FileMode) error

Sets the output path for generated snapshots. The directory will be created with the specified permission bits if it does not already exist.

If perm is 0, a default of 0755 will be used.

func (*BTTracer) SetPipes Uses

func (t *BTTracer) SetPipes(stdin io.Reader, stderr io.Writer)

Sets the input and output pipes for the tracer. Stdout is not redirected; it is instead passed to the tracer's Put command.

func (*BTTracer) SetSigchan Uses

func (t *BTTracer) SetSigchan(sc chan os.Signal)

See bt.TracerSig.SetSigchan().

func (*BTTracer) SetSigset Uses

func (t *BTTracer) SetSigset(sigs ...os.Signal)

See bt.TracerSig.SetSigset().

func (*BTTracer) SetTracerPath Uses

func (t *BTTracer) SetTracerPath(path string)

Sets the executable path for the tracer.

func (*BTTracer) Sigchan Uses

func (t *BTTracer) Sigchan() chan os.Signal

See bt.TracerSig.Sigchan().

func (*BTTracer) Sigset Uses

func (t *BTTracer) Sigset() []os.Signal

See bt.TracerSig.Sigset().

func (*BTTracer) String Uses

func (t *BTTracer) String() string

type GlobalConfig Uses

type GlobalConfig struct {
    // If the tracer's timeout expires and the tracer cannot be killed,
    // generate a run-time panic.
    //
    // Defaults to true.
    PanicOnKillFailure bool

    // Upon receipt of a signal and execution of the tracer, re-sends the
    // signal to the default Go signal handler for the signal and stops
    // listening for the signal.
    // Note: this will call signal.Reset(signal) on the received signal,
    // which undoes the effect of any signal.Notify() calls for the signal.
    //
    // Defaults to true.
    ResendSignal bool

    // Length of time to wait after completion of a tracer's
    // execution before allowing the next tracer to run.
    //
    // Defaults to 3 seconds.
    RateLimit time.Duration

    // If bt.Trace() has been configured to attempt an upload immediately,
    // wait for the Tracer to finish uploading its results (instead of
    // asynchronously uploading in a new goroutine) before returning
    // from bt.Trace().
    //
    // Defaults to true.
    SynchronousPut bool
}

type Log Uses

type Log interface {
    // Logs the specified message if the specified log level is enabled.
    Logf(level LogPriority, format string, v ...interface{})

    // Sets the log level to the specified bitmask of LogPriorities; all
    // priorities excluded from the mask are ignored.
    SetLogLevel(level LogPriority)
}

type LogPriority Uses

type LogPriority int

type NewOptions Uses

type NewOptions struct {
    // If false, system goroutines (i.e. those started and used by the Go
    // runtime) are excluded.
    IncludeSystemGs bool
}

type OptionsStruct Uses

type OptionsStruct struct {
    Endpoint string
    Token    string
    // SendEnvVars gathers and sends all environment variables with every report if true. Default false.
    SendEnvVars bool

    CaptureAllGoroutines bool
    TabWidth             int
    ContextLineCount     int
    Attributes           map[string]interface{}
    DebugBacktrace       bool
}
var Options OptionsStruct

type PutOptions Uses

type PutOptions struct {
    // If set to true, tracer results (i.e. generated snapshot files)
    // will be unlinked from the filesystem after successful puts.
    Unlink bool

    // The http.Client to use for uploading. The default will be used
    // if left unspecified.
    Client http.Client

    // If set to true, tracer results will be uploaded after each
    // successful Trace request.
    OnTrace bool
}

type TraceOptions Uses

type TraceOptions struct {
    // If true, the calling thread/goroutine will be marked as faulted
    // (i.e. the cause of the error or trace request).
    //
    // This is a Linux-specific option; it results in a noop on other
    // systems.
    Faulted bool

    // If true, only the calling thread/goroutine will be traced; all others
    // will be excluded from the generated snapshot.
    //
    // This is a Linux-specific option; it results in a noop on other
    // systems.
    CallerOnly bool

    // If true and a non-nil error object is passed to bt.Trace(), a
    // classifier will be added based on the specified error's type.
    ErrClassification bool

    // If non-nil, all contained strings will be added as classifiers to
    // the generated snapshot.
    Classifications []string

    // Amount of time to wait for the tracer to finish execution.
    // If 0 is specified, Tracer.DefaultTraceOptions()'s timeout will be
    // used. If <0 is specified, no timeout will be used; the Tracer command
    // will run until it exits.
    Timeout time.Duration

    // If non-nil, any goroutines spawned during the Trace() request will
    // be added to the wait group. This facilitates waiting for things like
    // asynchronous snapshot uploads to complete before exiting the
    // application.
    SpawnedGs *sync.WaitGroup
}

Options determining actions taken during Tracer execution.

type Tracer Uses

type Tracer interface {
    // Store the options provided by v.
    //
    // If the options slice is non-nil, the provided options should be
    // stored in it; otherwise, the options are added to the Tracer's
    // base set of options.
    // Returns the final options slice if the provided options slice is
    // non-nil.
    AddOptions(options []string, v ...string) []string

    // Add a key-value attribute.
    //
    // See AddOptions for rules regarding the specified options slice and
    // the return value.
    AddKV(options []string, key, val string) []string

    // Add a thread filter option using the specified tid. If any thread
    // filter options are added, all non-matching threads and goroutines
    // are expected to be excluded from the generated snapshot.
    //
    // See AddOptions for rules regarding the specified options slice and
    // the return value.
    AddThreadFilter(options []string, tid int) []string

    // Add a faulted thread option using the specified tid. Threads and
    // goroutines matching any faulted thread options are marked as faulted
    // and subject to analysis and grouping.
    //
    // See AddOptions for rules regarding the specified options slice and
    // the return value.
    AddFaultedThread(options []string, tid int) []string

    // Add a caller goroutine option using the specified goid.
    //
    // See AddOptions for rules regarding the specified options slice and
    // the return value.
    AddCallerGo(options []string, goid int) []string

    // Add a classification to the generated snapshot.
    //
    // See AddOptions for rules regarding the specified options slice and
    // the return value.
    AddClassifier(options []string, classifier string) []string

    // Returns a copy of the base set of options for the Tracer.
    Options() []string

    // Clears the base set of options for the Tracer.
    ClearOptions()

    // Returns the default TraceOptions used in bt.Trace() if an override
    // is not specified as an argument to it.
    DefaultTraceOptions() *TraceOptions

    // Accepts a final set of options and returns a Command object
    // representing a tracer that is ready to run. This will be executed
    // on the current process.
    Finalize(options []string) *exec.Cmd

    // Determines when and to what the Tracer will log.
    Log

    // String representation of a Tracer.
    fmt.Stringer

    // Returns whether the Tracer should upload its results to a remote
    // server after successful tracer execution.
    PutOnTrace() bool

    // Uploads Tracer results given by the snapshot argument, which is
    // the stdout of the Tracer process, to the configured remote server.
    //
    // As this is part of the generic Tracer interface, callers know
    // nothing about the contents of the output; thus, it is passed
    // unfiltered to the specific underlying implementation.
    Put(snapshot []byte) error
}

A generic out-of-process tracer interface.

This is used primarily by the top-level functions of the bt package, like bt.Trace, to handle execution and synchronization of various generic tracers.

Tracers are not limited to this interface and may provide additional utility methods; see specific tracer implementation (e.g. BTTracer) documentation for details.

The methods in this interface are expected to be goroutine safe; multiple trace requests (which ultimately call into these methods) from different goroutines may run concurrently.

type TracerSig Uses

type TracerSig interface {
    Tracer

    // Sets the desired set of signals for which to invoke the Tracer upon
    // receipt of the signal.
    SetSigset(sigs ...os.Signal)

    // Returns the desired signal set.
    Sigset() []os.Signal

    // Sets the channel through which the Tracer will respond to signals.
    SetSigchan(sc chan os.Signal)

    // Returns the channel through which the Tracer will respond to signals.
    Sigchan() chan os.Signal
}

This is a superset of the generic Tracer interface for those that wish to support signal handling. The methods unique to this interface are not expected to be goroutine-safe.

Directories

PathSynopsis
examples

Package bt imports 24 packages (graph) and is imported by 1 packages. Updated 2020-05-22. Refresh now. Tools for package owners.