-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #18 from infiniteloopcloud/parse-panic
Add panic parser
- Loading branch information
Showing
6 changed files
with
255 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,6 @@ | ||
module github.com/infiniteloopcloud/go | ||
|
||
go 1.17 | ||
go 1.18 | ||
|
||
require ( | ||
github.com/aws/aws-sdk-go-v2 v1.17.3 | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
package middlewares | ||
|
||
import ( | ||
"fmt" | ||
"regexp" | ||
"runtime" | ||
"strconv" | ||
"strings" | ||
) | ||
|
||
var fileDetails = regexp.MustCompile(`^(/([\w-._]+/)*([\w-]+\.[a-z]+)):(\d+)\s(\+0x[0-9a-fA-F]+$)`) | ||
var tabsNewlinesRegexp = regexp.MustCompile(`[\t\n]+`) | ||
|
||
type stackFlags struct { | ||
Vendor bool | ||
Builtin bool | ||
} | ||
type stackLine struct { | ||
FunctionName string | ||
FilePath string | ||
FilePathShort string | ||
LineNumber int | ||
StackPosition string | ||
Flags stackFlags | ||
} | ||
|
||
func (sl stackLine) String() string { | ||
return fmt.Sprintf("%s:%d:%s", sl.FilePathShort, sl.LineNumber, sl.FunctionName) | ||
} | ||
|
||
type panicParser struct{} | ||
|
||
func (p panicParser) Parse(stack []byte) ([]stackLine, error) { | ||
str := strings.TrimSpace(string(stack)) | ||
// cut the header | ||
_, str, _ = strings.Cut(str, "\n") | ||
// replace new lines with tabs | ||
str = strings.ReplaceAll(str, "\n", "\t") | ||
// replace tab duplications with single tabs | ||
str = tabsNewlinesRegexp.ReplaceAllString(str, "\t") | ||
|
||
// nolint: prealloc | ||
var result []stackLine | ||
var tabCounter int | ||
var latestTabIndex int | ||
for i, r := range []rune(str) { | ||
if r != '\t' { | ||
// skip chars until reaching a tab | ||
continue | ||
} | ||
tabCounter++ | ||
if tabCounter%2 != 0 { | ||
// every second tab matters, odd tabs will be skipped | ||
continue | ||
} | ||
|
||
// take the part of the string between the even tabs | ||
line := p.substring(str, latestTabIndex, i) | ||
|
||
functionNameParams, fileData, found := strings.Cut(line, "\t") | ||
if !found { | ||
return nil, fmt.Errorf("error separating function name from file details: %s", line) | ||
} | ||
|
||
// remove last (...) | ||
functionName, _, found := p.cutLast(functionNameParams, "(") | ||
if !found { | ||
return nil, fmt.Errorf("error cutting params from the func definition: %s", functionNameParams) | ||
} | ||
|
||
fileDetailsRegexResult := fileDetails.FindAllStringSubmatch(fileData, -1) | ||
if len(fileDetailsRegexResult) == 0 || len(fileDetailsRegexResult[0]) != 6 { | ||
return nil, fmt.Errorf("error parsing file details of the stack line: %s", fileData) | ||
} | ||
|
||
lineNum, err := strconv.Atoi(fileDetailsRegexResult[0][4]) | ||
if err != nil { | ||
return nil, fmt.Errorf("error parsing line number: %w", err) | ||
} | ||
|
||
groot := runtime.GOROOT() | ||
result = append(result, stackLine{ | ||
FunctionName: functionName + "(...)", | ||
FilePath: fileDetailsRegexResult[0][1], | ||
FilePathShort: fileDetailsRegexResult[0][2] + fileDetailsRegexResult[0][3], | ||
LineNumber: lineNum, | ||
StackPosition: fileDetailsRegexResult[0][5], | ||
Flags: stackFlags{ | ||
Vendor: strings.Contains(fileDetailsRegexResult[0][1], "/vendor/"), | ||
Builtin: strings.Contains(fileDetailsRegexResult[0][1], groot), | ||
}, | ||
}) | ||
latestTabIndex = i | ||
} | ||
|
||
return result, nil | ||
} | ||
|
||
func (panicParser) substring(str string, i, j int) string { | ||
if i > 0 { | ||
i += 1 | ||
} | ||
return str[i:j] | ||
} | ||
|
||
func (panicParser) cutLast(str, sep string) (string, string, bool) { | ||
idx := strings.LastIndex(str, sep) | ||
if idx < 0 { | ||
return str, "", false | ||
} | ||
return str[:idx], str[idx+1:], true | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
package middlewares | ||
|
||
import ( | ||
"bytes" | ||
"context" | ||
"encoding/json" | ||
"net/http" | ||
"net/http/httptest" | ||
"os" | ||
"runtime/debug" | ||
"strconv" | ||
"strings" | ||
"testing" | ||
|
||
"github.com/go-chi/chi/v5" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
type panicParserWriter struct { | ||
b *bytes.Buffer | ||
} | ||
|
||
func (w *panicParserWriter) Write(b []byte) (n int, err error) { | ||
w.b.Write(b) | ||
w.b.WriteByte(byte('\n')) | ||
return len(b) + 1, nil | ||
} | ||
|
||
func TestPanicParser_Parse(t *testing.T) { | ||
r := chi.NewRouter() | ||
|
||
var parsed []stackLine | ||
oldRecovererErrorWriter := recovererErrorWriter | ||
defer func() { recovererErrorWriter = oldRecovererErrorWriter }() | ||
w := panicParserWriter{b: bytes.NewBuffer(nil)} | ||
recovererErrorWriter = &w | ||
|
||
r.Use(Recoverer) | ||
SetPrintPrettyStack(func(ctx context.Context, rvr interface{}) { | ||
debugStack := debug.Stack() | ||
var err error | ||
parsed, err = panicParser{}.Parse(debugStack) | ||
if err != nil { | ||
os.Stderr.Write(debugStack) | ||
return | ||
} | ||
multilinePrettyPrint(ctx, rvr, parsed) | ||
}) | ||
r.Get("/", panicingHandler) | ||
|
||
ts := httptest.NewServer(r) | ||
defer ts.Close() | ||
|
||
res, _ := testRequest(t, ts, "GET", "/", nil) | ||
assertEqual(t, res.StatusCode, http.StatusInternalServerError) | ||
|
||
assert.Len(t, parsed, 13) | ||
|
||
var latestPanicID string | ||
for _, line := range strings.Split(w.b.String(), "\n") { | ||
if line == "" { | ||
continue | ||
} | ||
var logLine map[string]any | ||
require.NoError(t, json.Unmarshal([]byte(line), &logLine)) | ||
panicID, ok := logLine["panic_id"] | ||
require.True(t, ok) | ||
if latestPanicID == "" { | ||
// nolint: errcheck | ||
latestPanicID = panicID.(string) | ||
} else { | ||
assert.Equal(t, latestPanicID, panicID) | ||
} | ||
lineNum, hasLineField := logLine["line_number"] | ||
require.True(t, hasLineField) | ||
// nolint: errcheck | ||
_, err := strconv.Atoi(lineNum.(string)) | ||
require.NoError(t, err) | ||
_, hasFnName := logLine["function_name"] | ||
require.True(t, hasFnName) | ||
_, hasFilePath := logLine["file_path"] | ||
require.True(t, hasFilePath) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters