File: stack.go

package info (click to toggle)
golang-github-containerd-errdefs 0.3.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 172 kB
  • sloc: makefile: 2
file content (296 lines) | stat: -rw-r--r-- 6,884 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/*
   Copyright The containerd Authors.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package stack

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"os"
	"path"
	"runtime"
	"strings"
	"sync/atomic"
	"unsafe"

	"github.com/containerd/typeurl/v2"

	"github.com/containerd/errdefs/pkg/internal/types"
)

func init() {
	typeurl.Register((*stack)(nil), "github.com/containerd/errdefs", "stack+json")
}

var (
	// Version is version of running process
	Version string = "dev"

	// Revision is the specific revision of the running process
	Revision string = "dirty"
)

type stack struct {
	decoded *Trace

	callers []uintptr
	helpers []uintptr
}

// Trace is a stack trace along with process information about the source
type Trace struct {
	Version  string   `json:"version,omitempty"`
	Revision string   `json:"revision,omitempty"`
	Cmdline  []string `json:"cmdline,omitempty"`
	Frames   []Frame  `json:"frames,omitempty"`
	Pid      int32    `json:"pid,omitempty"`
}

// Frame is a single frame of the trace representing a line of code
type Frame struct {
	Name string `json:"Name,omitempty"`
	File string `json:"File,omitempty"`
	Line int32  `json:"Line,omitempty"`
}

func (f Frame) Format(s fmt.State, verb rune) {
	switch verb {
	case 'v':
		switch {
		case s.Flag('+'):
			fmt.Fprintf(s, "%s\n\t%s:%d\n", f.Name, f.File, f.Line)
		default:
			fmt.Fprint(s, f.Name)
		}
	case 's':
		fmt.Fprint(s, path.Base(f.Name))
	case 'q':
		fmt.Fprintf(s, "%q", path.Base(f.Name))
	}
}

// callers returns the current stack, skipping over the number of frames mentioned
// Frames with skip=0:
//
//	frame[0] runtime.Callers
//	frame[1] <this function> github.com/containerd/errdefs/stack.callers
//	frame[2] <caller> (Use skip=2 to have this be first frame)
func callers(skip int) *stack {
	const depth = 32
	var pcs [depth]uintptr
	n := runtime.Callers(skip, pcs[:])
	return &stack{
		callers: pcs[0:n],
	}
}

func (s *stack) getDecoded() *Trace {
	if s.decoded == nil {
		var unsafeDecoded = (*unsafe.Pointer)(unsafe.Pointer(&s.decoded))

		var helpers map[string]struct{}
		if len(s.helpers) > 0 {
			helpers = make(map[string]struct{})
			frames := runtime.CallersFrames(s.helpers)
			for {
				frame, more := frames.Next()
				helpers[frame.Function] = struct{}{}
				if !more {
					break
				}
			}
		}

		f := make([]Frame, 0, len(s.callers))
		if len(s.callers) > 0 {
			frames := runtime.CallersFrames(s.callers)
			for {
				frame, more := frames.Next()
				if _, ok := helpers[frame.Function]; !ok {
					f = append(f, Frame{
						Name: frame.Function,
						File: frame.File,
						Line: int32(frame.Line),
					})
				}
				if !more {
					break
				}
			}
		}

		t := Trace{
			Version:  Version,
			Revision: Revision,
			Cmdline:  os.Args,
			Frames:   f,
			Pid:      int32(os.Getpid()),
		}

		atomic.StorePointer(unsafeDecoded, unsafe.Pointer(&t))
	}

	return s.decoded
}

func (s *stack) Error() string {
	return fmt.Sprintf("%+v", s.getDecoded())
}

func (s *stack) MarshalJSON() ([]byte, error) {
	return json.Marshal(s.getDecoded())
}

func (s *stack) UnmarshalJSON(b []byte) error {
	var unsafeDecoded = (*unsafe.Pointer)(unsafe.Pointer(&s.decoded))
	var t Trace

	if err := json.Unmarshal(b, &t); err != nil {
		return err
	}

	atomic.StorePointer(unsafeDecoded, unsafe.Pointer(&t))

	return nil
}

func (s *stack) Format(st fmt.State, verb rune) {
	switch verb {
	case 'v':
		if st.Flag('+') {
			t := s.getDecoded()
			fmt.Fprintf(st, "%d %s %s\n", t.Pid, t.Version, strings.Join(t.Cmdline, " "))
			for _, f := range t.Frames {
				f.Format(st, verb)
			}
			fmt.Fprintln(st)
			return
		}
	}
}

func (s *stack) StackTrace() Trace {
	return *s.getDecoded()
}

func (s *stack) CollapseError() {}

// ErrStack returns a new error for the callers stack,
// this can be wrapped or joined into an existing error.
// NOTE: When joined with errors.Join, the stack
// will show up in the error string output.
// Use with `stack.Join` to force addition of the
// error stack.
func ErrStack() error {
	return callers(3)
}

// Join adds a stack if there is no stack included to the errors
// and returns a joined error with the stack hidden from the error
// output. The stack error shows up when Unwrapped or formatted
// with `%+v`.
func Join(errs ...error) error {
	return joinErrors(nil, errs)
}

// WithStack will check if the error already has a stack otherwise
// return a new error with the error joined with a stack error
// Any helpers will be skipped.
func WithStack(ctx context.Context, errs ...error) error {
	return joinErrors(ctx.Value(helperKey{}), errs)
}

func joinErrors(helperVal any, errs []error) error {
	var filtered []error
	var collapsible []error
	var hasStack bool
	for _, err := range errs {
		if err != nil {
			if !hasStack && hasLocalStackTrace(err) {
				hasStack = true
			}
			if _, ok := err.(types.CollapsibleError); ok {
				collapsible = append(collapsible, err)
			} else {
				filtered = append(filtered, err)
			}

		}
	}
	if len(filtered) == 0 {
		return nil
	}
	if !hasStack {
		s := callers(4)
		if helpers, ok := helperVal.([]uintptr); ok {
			s.helpers = helpers
		}
		collapsible = append(collapsible, s)
	}
	var err error
	if len(filtered) > 1 {
		err = errors.Join(filtered...)
	} else {
		err = filtered[0]
	}
	if len(collapsible) == 0 {
		return err
	}

	return types.CollapsedError(err, collapsible...)
}

func hasLocalStackTrace(err error) bool {
	switch e := err.(type) {
	case *stack:
		return true
	case interface{ Unwrap() error }:
		if hasLocalStackTrace(e.Unwrap()) {
			return true
		}
	case interface{ Unwrap() []error }:
		for _, ue := range e.Unwrap() {
			if hasLocalStackTrace(ue) {
				return true
			}
		}
	}

	// TODO: Consider if pkg/errors compatibility is needed
	// NOTE: This was implemented before the standard error package
	// so it may unwrap and have this interface.
	//if _, ok := err.(interface{ StackTrace() pkgerrors.StackTrace }); ok {
	//	return true
	//}

	return false
}

type helperKey struct{}

// WithHelper marks the context as from a helper function
// This will add an additional skip to the error stack trace
func WithHelper(ctx context.Context) context.Context {
	helpers, _ := ctx.Value(helperKey{}).([]uintptr)
	var pcs [1]uintptr
	n := runtime.Callers(2, pcs[:])
	if n == 1 {
		ctx = context.WithValue(ctx, helperKey{}, append(helpers, pcs[0]))
	}
	return ctx
}