Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: use an error recorder to track internal errors (#2397)

ZhengX85cc69727135
diff --git a/api/debug.go b/api/debug.go
index 824405514a..621305b552 100644
--- a/api/debug.go
+++ b/api/debug.go
@@ -1,5 +1,10 @@
package api
+import (
+ "container/ring"
+ "sync"
+)
+
// Debug is the API message for debug info.
type Debug struct {
IsDebug bool `jsonapi:"attr,isDebug"`
@@ -9,3 +14,36 @@ type Debug struct {
type DebugPatch struct {
IsDebug bool `jsonapi:"attr,isDebug"`
}
+
+// errorRecordMaximum is the count limit for error records.
+const errorRecordMaximum = 100
+
+// ErrorRecordRing is the struct to store error records in memory.
+type ErrorRecordRing struct {
+ Ring *ring.Ring
+ sync.RWMutex
+}
+
+// NewErrorRecordRing creates an error record ring.
+func NewErrorRecordRing() ErrorRecordRing {
+ return ErrorRecordRing{
+ Ring: ring.New(errorRecordMaximum),
+ RWMutex: sync.RWMutex{},
+ }
+}
+
+// ErrorRecord is the struct to record an error's useful details.
+type ErrorRecord struct {
+ RecordTs int64 `jsonapi:"attr,recordTs"`
+ Method string `jsonapi:"attr,method"`
+ RequestPath string `jsonapi:"attr,requestPath"`
+ Role `jsonapi:"attr,role"`
+ Error string `jsonapi:"attr,error"`
+ StackTrace string `jsonapi:"attr,stackTrace"`
+}
+
+// DebugLog is the API message for debug log.
+type DebugLog struct {
+ ID int `jsonapi:"primary,debugLog"`
+ ErrorRecord `jsonapi:"attr,errorRecord"`
+}
diff --git a/server/acl_casbin_policy_dba.csv b/server/acl_casbin_policy_dba.csv
index 4ec143dc60..2853d7e97d 100644
--- a/server/acl_casbin_policy_dba.csv
+++ b/server/acl_casbin_policy_dba.csv
@@ -105,3 +105,4 @@ p, DBA, /sheet/{id}/organizer, PATCH
p, DBA, /sheet/project/{projectID}/sync, POST
p, DBA, /debug, GET
p, DBA, /debug, PATCH
+p, DBA, /debug/log, GET
diff --git a/server/acl_casbin_policy_developer.csv b/server/acl_casbin_policy_developer.csv
index d2440118cd..647d29b11a 100644
--- a/server/acl_casbin_policy_developer.csv
+++ b/server/acl_casbin_policy_developer.csv
@@ -91,3 +91,4 @@ p, DEVELOPER, /sheet/{id}, DELETE_SELF
p, DEVELOPER, /sheet/{id}/organizer, PATCH
p, DEVELOPER, /sheet/project/{projectID}/sync, POST
p, DEVELOPER, /debug, GET
+p, DEVELOPER, /debug/log, GET
diff --git a/server/acl_casbin_policy_owner.csv b/server/acl_casbin_policy_owner.csv
index 2d3aee33f2..80347eede6 100644
--- a/server/acl_casbin_policy_owner.csv
+++ b/server/acl_casbin_policy_owner.csv
@@ -111,3 +111,4 @@ p, OWNER, /sheet/{id}/organizer, PATCH
p, OWNER, /sheet/project/{projectID}/sync, POST
p, OWNER, /debug, GET
p, OWNER, /debug, PATCH
+p, OWNER, /debug/log, GET
diff --git a/server/debug.go b/server/debug.go
index 2de732c384..2cf5e8831f 100644
--- a/server/debug.go
+++ b/server/debug.go
@@ -30,6 +30,37 @@ func (s *Server) registerDebugRoutes(g *echo.Group) {
return currentDebugState(c)
})
+
+ g.GET("/debug/log", func(c echo.Context) error {
+ var errorRecordList []*api.DebugLog
+ // incrementID is used as primary key in jsonapi.
+ var incrementID int
+
+ s.errorRecordRing.RWMutex.RLock()
+ defer s.errorRecordRing.RWMutex.RUnlock()
+
+ s.errorRecordRing.Ring.Do(func(p interface{}) {
+ if p == nil {
+ return
+ }
+ errRecord, ok := p.(*api.ErrorRecord)
+ if !ok {
+ return
+ }
+ errorRecordList = append(errorRecordList, &api.DebugLog{
+ ID: incrementID,
+ ErrorRecord: *errRecord,
+ })
+ incrementID++
+ })
+
+ c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSONCharsetUTF8)
+ if err := jsonapi.MarshalPayload(c.Response().Writer, errorRecordList); err != nil {
+ return echo.NewHTTPError(http.StatusInternalServerError, "Failed to marshal debug log response").SetInternal(err)
+ }
+
+ return nil
+ })
}
func currentDebugState(c echo.Context) error {
diff --git a/server/error_recorder.go b/server/error_recorder.go
new file mode 100644
index 0000000000..18a1b1682d
--- /dev/null
+++ b/server/error_recorder.go
@@ -0,0 +1,48 @@
+package server
+
+import (
+ "net/http"
+ "runtime/debug"
+ "time"
+
+ "github.com/bytebase/bytebase/api"
+
+ "github.com/labstack/echo/v4"
+)
+
+func errorRecorderMiddleware(err error, s *Server, c echo.Context, e *echo.Echo) {
+ e.DefaultHTTPErrorHandler(err, c)
+
+ he, isHTTPError := err.(*echo.HTTPError)
+
+ if c.Response().Status == http.StatusInternalServerError {
+ var role api.Role
+ if r, ok := c.Get(getRoleContextKey()).(api.Role); ok {
+ role = r
+ }
+
+ var stackTrace string
+ // There're basically two kinds of errors: internal HTTP errors and runtime panics.
+ // If we encounter runtime panics, we can report the stack trace for debugging.
+ if !isHTTPError || he.Internal == nil {
+ // Get a snapshot of the stack trace here, which will include where the panic occurred.
+ // We only do this for runtime errors. Because for internal HTTP errors,
+ // the stack trace here won't indicate where the internal error is from.
+ // To debug internal errors, we mainly check the error mesasges.
+ stackTrace = string(debug.Stack())
+ }
+
+ s.errorRecordRing.RWMutex.Lock()
+ defer s.errorRecordRing.RWMutex.Unlock()
+
+ s.errorRecordRing.Ring.Value = &api.ErrorRecord{
+ RecordTs: time.Now().Unix(),
+ Method: c.Request().Method,
+ RequestPath: c.Request().URL.Path,
+ Role: role,
+ Error: err.Error(),
+ StackTrace: stackTrace,
+ }
+ s.errorRecordRing.Ring = s.errorRecordRing.Ring.Next()
+ }
+}
diff --git a/server/server.go b/server/server.go
index 01c3c17814..01a45ae527 100644
--- a/server/server.go
+++ b/server/server.go
@@ -57,13 +57,14 @@ type Server struct {
LicenseService enterpriseAPI.LicenseService
subscription enterpriseAPI.Subscription
- profile Profile
- e *echo.Echo
- pgInstance *postgres.Instance
- metaDB *store.MetadataDB
- store *store.Store
- startedTs int64
- secret string
+ profile Profile
+ e *echo.Echo
+ pgInstance *postgres.Instance
+ metaDB *store.MetadataDB
+ store *store.Store
+ startedTs int64
+ secret string
+ errorRecordRing api.ErrorRecordRing
s3Client *s3bb.Client
@@ -105,8 +106,9 @@ var casbinDeveloperPolicy string
// NewServer creates a server.
func NewServer(ctx context.Context, prof Profile) (*Server, error) {
s := &Server{
- profile: prof,
- startedTs: time.Now().Unix(),
+ profile: prof,
+ startedTs: time.Now().Unix(),
+ errorRecordRing: api.NewErrorRecordRing(),
}
// Display config
@@ -284,6 +286,10 @@ func NewServer(ctx context.Context, prof Profile) (*Server, error) {
}
// Middleware
+ e.HTTPErrorHandler = func(err error, c echo.Context) {
+ errorRecorderMiddleware(err, s, c, e)
+ }
+
e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Skipper: func(c echo.Context) bool {
if s.profile.Mode == common.ReleaseModeProd && !s.profile.Debug {