|
| 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