Skip to content

Commit f7b632c

Browse files
Gustedearl-warren
authored andcommitted
add slow SQL query warning
- Databases are one of the most important parts of Forgejo, every interaction uses the database in one way or another. Therefore, it is important to maintain the database and recognize when the server is not doing well with the database. There already is the option to log *every* SQL query along with its execution time, but monitoring becomes impractical for larger instances and takes up unnecessary storage in the logs. - Add a QoL enhancement that allows instance administrators to specify a threshold value beyond which query execution time is logged as a warning in the xorm logger. The default value is a conservative five seconds to avoid this becoming a source of spam in the logs. - The use case for this patch is that with an instance the size of Codeberg, monitoring SQL logs is not very fruitful and most of them are uninteresting. Recently, in the context of persistent deadlock issues (https://codeberg.org/forgejo/forgejo/issues/220), I have noticed that certain queries hold locks on tables like comment and issue for several seconds. This patch helps to identify which queries these are and when they happen. - Added unit test. (cherry picked from commit 9cf501f1af4cd870221cef6af489618785b71186)
1 parent 65eea1d commit f7b632c

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

models/db/engine.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,13 @@ import (
1111
"io"
1212
"reflect"
1313
"strings"
14+
"time"
1415

16+
"code.gitea.io/gitea/modules/log"
1517
"code.gitea.io/gitea/modules/setting"
1618

1719
"xorm.io/xorm"
20+
"xorm.io/xorm/contexts"
1821
"xorm.io/xorm/names"
1922
"xorm.io/xorm/schemas"
2023

@@ -146,6 +149,13 @@ func InitEngine(ctx context.Context) error {
146149
xormEngine.SetConnMaxLifetime(setting.Database.ConnMaxLifetime)
147150
xormEngine.SetDefaultContext(ctx)
148151

152+
if setting.Database.SlowQueryTreshold > 0 {
153+
xormEngine.AddHook(&SlowQueryHook{
154+
Treshold: setting.Database.SlowQueryTreshold,
155+
Logger: log.GetLogger("xorm"),
156+
})
157+
}
158+
149159
SetDefaultEngine(ctx, xormEngine)
150160
return nil
151161
}
@@ -299,3 +309,21 @@ func SetLogSQL(ctx context.Context, on bool) {
299309
sess.Engine().ShowSQL(on)
300310
}
301311
}
312+
313+
type SlowQueryHook struct {
314+
Treshold time.Duration
315+
Logger log.Logger
316+
}
317+
318+
var _ contexts.Hook = &SlowQueryHook{}
319+
320+
func (SlowQueryHook) BeforeProcess(c *contexts.ContextHook) (context.Context, error) {
321+
return c.Ctx, nil
322+
}
323+
324+
func (h *SlowQueryHook) AfterProcess(c *contexts.ContextHook) error {
325+
if c.ExecuteTime >= h.Treshold {
326+
h.Logger.Log(8, log.WARN, "[Slow SQL Query] %s %v - %v", c.SQL, c.Args, c.ExecuteTime)
327+
}
328+
return nil
329+
}

models/db/engine_test.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,19 @@ package db_test
66
import (
77
"path/filepath"
88
"testing"
9+
"time"
910

1011
"code.gitea.io/gitea/models/db"
1112
issues_model "code.gitea.io/gitea/models/issues"
1213
"code.gitea.io/gitea/models/unittest"
14+
"code.gitea.io/gitea/modules/log"
1315
"code.gitea.io/gitea/modules/setting"
16+
"code.gitea.io/gitea/modules/test"
1417

1518
_ "code.gitea.io/gitea/cmd" // for TestPrimaryKeys
1619

1720
"github.com/stretchr/testify/assert"
21+
"xorm.io/xorm"
1822
)
1923

2024
func TestDumpDatabase(t *testing.T) {
@@ -84,3 +88,37 @@ func TestPrimaryKeys(t *testing.T) {
8488
}
8589
}
8690
}
91+
92+
func TestSlowQuery(t *testing.T) {
93+
lc, cleanup := test.NewLogChecker("slow-query")
94+
lc.StopMark("[Slow SQL Query]")
95+
defer cleanup()
96+
97+
e := db.GetEngine(db.DefaultContext)
98+
engine, ok := e.(*xorm.Engine)
99+
assert.True(t, ok)
100+
101+
// It's not possible to clean this up with XORM, but it's luckily not harmful
102+
// to leave around.
103+
engine.AddHook(&db.SlowQueryHook{
104+
Treshold: time.Second * 10,
105+
Logger: log.GetLogger("slow-query"),
106+
})
107+
108+
// NOOP query.
109+
e.Exec("SELECT 1 WHERE false;")
110+
111+
_, stopped := lc.Check(100 * time.Millisecond)
112+
assert.False(t, stopped)
113+
114+
engine.AddHook(&db.SlowQueryHook{
115+
Treshold: 0, // Every query should be logged.
116+
Logger: log.GetLogger("slow-query"),
117+
})
118+
119+
// NOOP query.
120+
e.Exec("SELECT 1 WHERE false;")
121+
122+
_, stopped = lc.Check(100 * time.Millisecond)
123+
assert.True(t, stopped)
124+
}

modules/setting/database.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ var (
4444
ConnMaxLifetime time.Duration
4545
IterateBufferSize int
4646
AutoMigration bool
47+
SlowQueryTreshold time.Duration
4748
}{
4849
Timeout: 500,
4950
IterateBufferSize: 50,
@@ -86,6 +87,7 @@ func loadDBSetting(rootCfg ConfigProvider) {
8687
Database.DBConnectRetries = sec.Key("DB_RETRIES").MustInt(10)
8788
Database.DBConnectBackoff = sec.Key("DB_RETRY_BACKOFF").MustDuration(3 * time.Second)
8889
Database.AutoMigration = sec.Key("AUTO_MIGRATION").MustBool(true)
90+
Database.SlowQueryTreshold = sec.Key("SLOW_QUERY_TRESHOLD").MustDuration(5 * time.Second)
8991
}
9092

9193
// DBConnStr returns database connection string

0 commit comments

Comments
 (0)