1
// Copyright (c) 2017 Uber Technologies, Inc.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a copy
4
// of this software and associated documentation files (the "Software"), to deal
5
// in the Software without restriction, including without limitation the rights
6
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
// copies of the Software, and to permit persons to whom the Software is
8
// furnished to do so, subject to the following conditions:
9
//
10
// The above copyright notice and this permission notice shall be included in
11
// all copies or substantial portions of the Software.
12
//
13
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
// THE SOFTWARE.
20

21
package stack
22

23
import (
24
	"bufio"
25
	"bytes"
26
	"fmt"
27
	"io"
28
	"runtime"
29
	"strconv"
30
	"strings"
31
)
32

33
const _defaultBufferSize = 64 * 1024 // 64 KiB
34

35
// Stack represents a single Goroutine's stack.
36
type Stack struct {
37
	id            int
38
	state         string
39
	firstFunction string
40
	fullStack     *bytes.Buffer
41
}
42

43
// ID returns the goroutine ID.
44
func (s Stack) ID() int {
45 2
	return s.id
46
}
47

48
// State returns the Goroutine's state.
49
func (s Stack) State() string {
50 2
	return s.state
51
}
52

53
// Full returns the full stack trace for this goroutine.
54
func (s Stack) Full() string {
55 2
	return s.fullStack.String()
56
}
57

58
// FirstFunction returns the name of the first function on the stack.
59
func (s Stack) FirstFunction() string {
60 2
	return s.firstFunction
61
}
62

63
func (s Stack) String() string {
64 2
	return fmt.Sprintf(
65 2
		"Goroutine %v in state %v, with %v on top of the stack:\n%s",
66 2
		s.id, s.state, s.firstFunction, s.Full())
67
}
68

69
func getStacks(all bool) []Stack {
70 2
	var stacks []Stack
71

72 2
	var curStack *Stack
73 2
	stackReader := bufio.NewReader(bytes.NewReader(getStackBuffer(all)))
74
	for {
75 2
		line, err := stackReader.ReadString('\n')
76 2
		if err == io.EOF {
77 2
			break
78
		}
79 2
		if err != nil {
80
			// We're reading using bytes.NewReader which should never fail.
81 0
			panic("bufio.NewReader failed on a fixed string")
82
		}
83

84
		// If we see the goroutine header, start a new stack.
85 2
		isFirstLine := false
86 2
		if strings.HasPrefix(line, "goroutine ") {
87
			// flush any previous stack
88 2
			if curStack != nil {
89 2
				stacks = append(stacks, *curStack)
90
			}
91 2
			id, goState := parseGoStackHeader(line)
92
			curStack = &Stack{
93 2
				id:        id,
94 2
				state:     goState,
95 2
				fullStack: &bytes.Buffer{},
96
			}
97 2
			isFirstLine = true
98
		}
99 2
		curStack.fullStack.WriteString(line)
100 2
		if !isFirstLine && curStack.firstFunction == "" {
101 2
			curStack.firstFunction = parseFirstFunc(line)
102
		}
103
	}
104

105 2
	if curStack != nil {
106 2
		stacks = append(stacks, *curStack)
107
	}
108 2
	return stacks
109
}
110

111
// All returns the stacks for all running goroutines.
112
func All() []Stack {
113 2
	return getStacks(true)
114
}
115

116
// Current returns the stack for the current goroutine.
117
func Current() Stack {
118 2
	return getStacks(false)[0]
119
}
120

121
func getStackBuffer(all bool) []byte {
122
	for i := _defaultBufferSize; ; i *= 2 {
123 2
		buf := make([]byte, i)
124 2
		if n := runtime.Stack(buf, all); n < i {
125 2
			return buf[:n]
126
		}
127
	}
128
}
129

130
func parseFirstFunc(line string) string {
131 2
	line = strings.TrimSpace(line)
132 2
	if idx := strings.LastIndex(line, "("); idx > 0 {
133 2
		return line[:idx]
134
	}
135 0
	panic(fmt.Sprintf("function calls missing parents: %q", line))
136
}
137

138
// parseGoStackHeader parses a stack header that looks like:
139
// goroutine 643 [runnable]:\n
140
// And returns the goroutine ID, and the state.
141
func parseGoStackHeader(line string) (goroutineID int, state string) {
142 2
	line = strings.TrimSuffix(line, ":\n")
143 2
	parts := strings.SplitN(line, " ", 3)
144 2
	if len(parts) != 3 {
145 0
		panic(fmt.Sprintf("unexpected stack header format: %q", line))
146
	}
147

148 2
	id, err := strconv.Atoi(parts[1])
149 2
	if err != nil {
150 0
		panic(fmt.Sprintf("failed to parse goroutine ID: %v in line %q", parts[1], line))
151
	}
152

153 2
	state = strings.TrimSuffix(strings.TrimPrefix(parts[2], "["), "]")
154 2
	return id, state
155
}

Read our documentation on viewing source code .

Loading