Skip to content

Commit 1dac859

Browse files
authored
feat: Add database transaction monitoring logs (#11406)
1 parent 71fd123 commit 1dac859

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

agent/utils/common/sqlite.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"log"
66
"os"
77
"path"
8+
"strings"
89
"time"
910

1011
"github.com/1Panel-dev/1Panel/agent/global"
@@ -67,6 +68,9 @@ func GetDBWithPath(dbPath string) (*gorm.DB, error) {
6768
if err != nil {
6869
return nil, err
6970
}
71+
if strings.HasSuffix(dbPath, "core.db") || strings.HasSuffix(dbPath, "agent.db") {
72+
initializeTxWatch(db)
73+
}
7074
sqlDB, dbError := db.DB()
7175
if dbError != nil {
7276
return nil, dbError
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package common
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"runtime"
7+
"strings"
8+
"time"
9+
10+
"github.com/1Panel-dev/1Panel/agent/global"
11+
"gorm.io/gorm"
12+
)
13+
14+
type contextKey string
15+
16+
func initializeTxWatch(db *gorm.DB) {
17+
_ = db.Callback().Create().Before("gorm:begin_transaction").Register(
18+
"my_plugin:before_begin",
19+
func(db *gorm.DB) {
20+
var caller []string
21+
for i := 0; ; i++ {
22+
pc, file, line, ok := runtime.Caller(i)
23+
if !ok {
24+
break
25+
}
26+
funcName := runtime.FuncForPC(pc).Name()
27+
if !strings.HasPrefix(funcName, "github.com/1Panel-dev/1Panel") {
28+
continue
29+
}
30+
fileParts := strings.Split(file, "/")
31+
fileName := fileParts[len(fileParts)-1]
32+
caller = append(caller, fmt.Sprintf("%s/%s:%d", funcName, fileName, line))
33+
}
34+
txID := generateTransactionID()
35+
db.Statement.Context = context.WithValue(
36+
db.Statement.Context,
37+
contextKey("tx_id"), txID,
38+
)
39+
db.Statement.Context = context.WithValue(
40+
db.Statement.Context,
41+
contextKey("tx_start"), time.Now(),
42+
)
43+
global.LOG.Debugf("[%s] tx start \n%s", txID, strings.Join(caller, "\n"))
44+
},
45+
)
46+
47+
_ = db.Callback().Create().After("gorm:commit_or_rollback_transaction").Register(
48+
"my_plugin:after_commit_or_rollback",
49+
func(db *gorm.DB) {
50+
ctx := db.Statement.Context
51+
txID, _ := ctx.Value(contextKey("tx_id")).(string)
52+
startTime, _ := ctx.Value(contextKey("tx_start")).(time.Time)
53+
if txID != "" {
54+
duration := time.Since(startTime)
55+
if db.Error != nil {
56+
global.LOG.Debugf("[%s] tx rollback! time: %v, err: %v", txID, duration, db.Error)
57+
} else {
58+
global.LOG.Debugf("[%s] tx commit! time: %v", txID, duration)
59+
}
60+
}
61+
},
62+
)
63+
}
64+
65+
func generateTransactionID() string {
66+
return fmt.Sprintf("tx_%d", time.Now().UnixNano())
67+
}

0 commit comments

Comments
 (0)