Skip to content

Commit 1a35576

Browse files
committed
fix
1 parent 2a828e2 commit 1a35576

File tree

18 files changed

+384
-56
lines changed

18 files changed

+384
-56
lines changed

models/db/engine_hook.go

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,23 +7,33 @@ import (
77
"context"
88
"time"
99

10+
"code.gitea.io/gitea/modules/gtprof"
1011
"code.gitea.io/gitea/modules/log"
12+
"code.gitea.io/gitea/modules/setting"
1113

1214
"xorm.io/xorm/contexts"
1315
)
1416

15-
type SlowQueryHook struct {
17+
type EngineHook struct {
1618
Threshold time.Duration
1719
Logger log.Logger
1820
}
1921

20-
var _ contexts.Hook = (*SlowQueryHook)(nil)
22+
var _ contexts.Hook = (*EngineHook)(nil)
2123

22-
func (*SlowQueryHook) BeforeProcess(c *contexts.ContextHook) (context.Context, error) {
23-
return c.Ctx, nil
24+
func (*EngineHook) BeforeProcess(c *contexts.ContextHook) (context.Context, error) {
25+
ctx, _ := gtprof.GetTracer().Start(c.Ctx, gtprof.TraceSpanDatabase)
26+
return ctx, nil
2427
}
2528

26-
func (h *SlowQueryHook) AfterProcess(c *contexts.ContextHook) error {
29+
func (h *EngineHook) AfterProcess(c *contexts.ContextHook) error {
30+
span := gtprof.GetContextSpan(c.Ctx)
31+
if span != nil {
32+
span.SetAttributeString(gtprof.TraceAttrDbSql, c.SQL)
33+
span.End()
34+
} else {
35+
setting.PanicInDevOrTesting("span in database engine hook is nil")
36+
}
2737
if c.ExecuteTime >= h.Threshold {
2838
// 8 is the amount of skips passed to runtime.Caller, so that in the log the correct function
2939
// is being displayed (the function that ultimately wants to execute the query in the code)

models/db/engine_init.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ func InitEngine(ctx context.Context) error {
7272
xe.SetDefaultContext(ctx)
7373

7474
if setting.Database.SlowQueryThreshold > 0 {
75-
xe.AddHook(&SlowQueryHook{
75+
xe.AddHook(&EngineHook{
7676
Threshold: setting.Database.SlowQueryThreshold,
7777
Logger: log.GetLogger("xorm"),
7878
})

modules/git/command.go

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import (
1818
"time"
1919

2020
"code.gitea.io/gitea/modules/git/internal" //nolint:depguard // only this file can use the internal type CmdArg, other files and packages should use AddXxx functions
21+
"code.gitea.io/gitea/modules/gtprof"
2122
"code.gitea.io/gitea/modules/log"
2223
"code.gitea.io/gitea/modules/process"
2324
"code.gitea.io/gitea/modules/util"
@@ -54,7 +55,7 @@ func logArgSanitize(arg string) string {
5455
} else if filepath.IsAbs(arg) {
5556
base := filepath.Base(arg)
5657
dir := filepath.Dir(arg)
57-
return filepath.Join(filepath.Base(dir), base)
58+
return ".../" + filepath.Join(filepath.Base(dir), base)
5859
}
5960
return arg
6061
}
@@ -275,29 +276,36 @@ func (c *Command) Run(opts *RunOpts) error {
275276
}
276277

277278
func (c *Command) run(skip int, opts *RunOpts) error {
278-
if len(c.brokenArgs) != 0 {
279-
log.Error("git command is broken: %s, broken args: %s", c.LogString(), strings.Join(c.brokenArgs, " "))
280-
return ErrBrokenCommand
281-
}
282279
if opts == nil {
283280
opts = &RunOpts{}
284281
}
285282

286-
// We must not change the provided options
287-
timeout := opts.Timeout
288-
if timeout <= 0 {
289-
timeout = defaultCommandExecutionTimeout
290-
}
291-
292-
var desc string
293283
callerInfo := util.CallerFuncName(1 /* util */ + 1 /* this */ + skip /* parent */)
294284
if pos := strings.LastIndex(callerInfo, "/"); pos >= 0 {
295285
callerInfo = callerInfo[pos+1:]
296286
}
287+
297288
// these logs are for debugging purposes only, so no guarantee of correctness or stability
298-
desc = fmt.Sprintf("git.Run(by:%s, repo:%s): %s", callerInfo, logArgSanitize(opts.Dir), c.LogString())
289+
cmdLogString := c.LogString()
290+
desc := fmt.Sprintf("git.Run(by:%s, repo:%s): %s", callerInfo, logArgSanitize(opts.Dir), cmdLogString)
299291
log.Debug("git.Command: %s", desc)
300292

293+
_, span := gtprof.GetTracer().Start(c.parentContext, gtprof.TraceSpanGitRun)
294+
defer span.End()
295+
span.SetAttributeString(gtprof.TraceAttrFuncCaller, callerInfo)
296+
span.SetAttributeString(gtprof.TraceAttrGitCommand, cmdLogString)
297+
298+
if len(c.brokenArgs) != 0 {
299+
log.Error("git command is broken: %s, broken args: %s", c.LogString(), strings.Join(c.brokenArgs, " "))
300+
return ErrBrokenCommand
301+
}
302+
303+
// We must not change the provided options
304+
timeout := opts.Timeout
305+
if timeout <= 0 {
306+
timeout = defaultCommandExecutionTimeout
307+
}
308+
301309
var ctx context.Context
302310
var cancel context.CancelFunc
303311
var finished context.CancelFunc

modules/gtprof/trace.go

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
// Copyright 2024 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package gtprof
5+
6+
import (
7+
"context"
8+
"fmt"
9+
"sync"
10+
"time"
11+
12+
"code.gitea.io/gitea/modules/util"
13+
)
14+
15+
type contextKey struct {
16+
name string
17+
}
18+
19+
var ContextKeySpan = &contextKey{"span"}
20+
21+
type traceStarter interface {
22+
start(ctx context.Context, traceSpan *TraceSpan, internalSpanIdx int) (context.Context, traceSpanInternal)
23+
}
24+
25+
type traceSpanInternal interface {
26+
end()
27+
}
28+
29+
type TraceSpan struct {
30+
mu sync.Mutex
31+
32+
parent *TraceSpan
33+
34+
name string
35+
startTime time.Time
36+
endTime time.Time
37+
attributes []TraceAttribute
38+
39+
children []*TraceSpan
40+
41+
internalSpans []traceSpanInternal
42+
}
43+
44+
type TraceAttribute struct {
45+
Key string
46+
Value TraceValue
47+
}
48+
49+
type TraceValue struct {
50+
v any
51+
}
52+
53+
func (t *TraceValue) AsString() string {
54+
return fmt.Sprint(t.v)
55+
}
56+
57+
func (t *TraceValue) AsInt64() int64 {
58+
v, _ := util.ToInt64(t.v)
59+
return v
60+
}
61+
62+
func (t *TraceValue) AsFloat64() float64 {
63+
v, _ := util.ToFloat64(t.v)
64+
return v
65+
}
66+
67+
var globalTraceStarters []traceStarter
68+
69+
type Tracer struct {
70+
starters []traceStarter
71+
}
72+
73+
func (s *TraceSpan) SetAttributeString(key, value string) *TraceSpan {
74+
s.mu.Lock()
75+
defer s.mu.Unlock()
76+
77+
s.attributes = append(s.attributes, TraceAttribute{Key: key, Value: TraceValue{v: value}})
78+
return s
79+
}
80+
81+
func (t *Tracer) Start(ctx context.Context, spanName string) (context.Context, *TraceSpan) {
82+
starters := t.starters
83+
if starters == nil {
84+
starters = globalTraceStarters
85+
}
86+
ts := &TraceSpan{name: spanName, startTime: time.Now()}
87+
ts.parent, _ = ctx.Value(ContextKeySpan).(*TraceSpan)
88+
if ts.parent != nil {
89+
ts.parent.children = append(ts.parent.children, ts)
90+
}
91+
for i, tsp := range starters {
92+
var internalSpan traceSpanInternal
93+
ctx, internalSpan = tsp.start(ctx, ts, i)
94+
ts.internalSpans = append(ts.internalSpans, internalSpan)
95+
}
96+
ctx = context.WithValue(ctx, ContextKeySpan, ts)
97+
return ctx, ts
98+
}
99+
100+
func (s *TraceSpan) End() {
101+
s.mu.Lock()
102+
defer s.mu.Unlock()
103+
104+
s.endTime = time.Now()
105+
for _, tsp := range s.internalSpans {
106+
tsp.end()
107+
}
108+
}
109+
110+
func GetTracer() *Tracer {
111+
return &Tracer{}
112+
}
113+
114+
func GetContextSpan(ctx context.Context) *TraceSpan {
115+
ts, _ := ctx.Value(ContextKeySpan).(*TraceSpan)
116+
return ts
117+
}

modules/gtprof/trace_builtin.go

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// Copyright 2024 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package gtprof
5+
6+
import (
7+
"context"
8+
"fmt"
9+
"strings"
10+
"time"
11+
12+
"code.gitea.io/gitea/modules/tailmsg"
13+
)
14+
15+
type traceBuiltinStarter struct{}
16+
17+
type traceBuiltinSpan struct {
18+
ts *TraceSpan
19+
20+
internalSpanIdx int
21+
}
22+
23+
func (t *traceBuiltinSpan) toString(out *strings.Builder, indent int) {
24+
out.WriteString(strings.Repeat(" ", indent))
25+
out.WriteString(t.ts.name)
26+
if t.ts.endTime.IsZero() {
27+
out.WriteString(fmt.Sprintf(" duration: (not ended)"))
28+
} else {
29+
out.WriteString(fmt.Sprintf(" duration: %.4fs", t.ts.endTime.Sub(t.ts.startTime).Seconds()))
30+
}
31+
out.WriteString("\n")
32+
for _, a := range t.ts.attributes {
33+
out.WriteString(strings.Repeat(" ", indent+2))
34+
out.WriteString(a.Key)
35+
out.WriteString(": ")
36+
out.WriteString(a.Value.AsString())
37+
out.WriteString("\n")
38+
}
39+
for _, c := range t.ts.children {
40+
span := c.internalSpans[t.internalSpanIdx].(*traceBuiltinSpan)
41+
span.toString(out, indent+2)
42+
}
43+
}
44+
45+
func (t *traceBuiltinSpan) end() {
46+
if t.ts.parent == nil {
47+
// FIXME: debug purpose only
48+
// FIXME: it should distinguish between http response network lag and actual processing time
49+
if len(t.ts.children) > 3 || t.ts.endTime.Sub(t.ts.startTime) > 100*time.Millisecond {
50+
sb := &strings.Builder{}
51+
t.toString(sb, 0)
52+
tailmsg.GetManager().GetTraceRecorder().Record(sb.String())
53+
}
54+
}
55+
}
56+
57+
func (t *traceBuiltinStarter) start(ctx context.Context, traceSpan *TraceSpan, internalSpanIdx int) (context.Context, traceSpanInternal) {
58+
return ctx, &traceBuiltinSpan{ts: traceSpan, internalSpanIdx: internalSpanIdx}
59+
}
60+
61+
func init() {
62+
globalTraceStarters = append(globalTraceStarters, &traceBuiltinStarter{})
63+
}

modules/gtprof/trace_const.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Copyright 2024 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package gtprof
5+
6+
// Some interesting names could be found in https://github.com/open-telemetry/opentelemetry-go/tree/main/semconv
7+
8+
const (
9+
TraceSpanHTTP = "http"
10+
TraceSpanGitRun = "git-run"
11+
TraceSpanDatabase = "database"
12+
)
13+
14+
const (
15+
TraceAttrFuncCaller = "func.caller"
16+
TraceAttrDbSql = "db.sql"
17+
TraceAttrGitCommand = "git.command"
18+
TraceAttrHTTPRoute = "http.route"
19+
)

modules/tailmsg/taillog.go

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// Copyright 2024 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package tailmsg
5+
6+
import (
7+
"sync"
8+
"time"
9+
)
10+
11+
type MsgRecord struct {
12+
Time time.Time
13+
Content string
14+
}
15+
16+
type MsgRecorder interface {
17+
Record(content string)
18+
GetRecords() []*MsgRecord
19+
}
20+
21+
type memoryMsgRecorder struct {
22+
mu sync.RWMutex
23+
msgs []*MsgRecord
24+
limit int
25+
}
26+
27+
// TODO: use redis for a clustered environment
28+
29+
func (m *memoryMsgRecorder) Record(content string) {
30+
m.mu.Lock()
31+
defer m.mu.Unlock()
32+
m.msgs = append(m.msgs, &MsgRecord{
33+
Time: time.Now(),
34+
Content: content,
35+
})
36+
if len(m.msgs) > m.limit {
37+
m.msgs = m.msgs[len(m.msgs)-m.limit:]
38+
}
39+
}
40+
41+
func (m *memoryMsgRecorder) GetRecords() []*MsgRecord {
42+
m.mu.RLock()
43+
defer m.mu.RUnlock()
44+
ret := make([]*MsgRecord, len(m.msgs))
45+
copy(ret, m.msgs)
46+
return ret
47+
}
48+
49+
func NewMsgRecorder(limit int) MsgRecorder {
50+
return &memoryMsgRecorder{
51+
limit: limit,
52+
}
53+
}
54+
55+
type Manager struct {
56+
traceRecorder MsgRecorder
57+
logRecorder MsgRecorder
58+
}
59+
60+
func (m *Manager) GetTraceRecorder() MsgRecorder {
61+
return m.traceRecorder
62+
}
63+
64+
func (m *Manager) GetLogRecorder() MsgRecorder {
65+
return m.logRecorder
66+
}
67+
68+
var GetManager = sync.OnceValue(func() *Manager {
69+
return &Manager{
70+
traceRecorder: NewMsgRecorder(100),
71+
logRecorder: NewMsgRecorder(1000),
72+
}
73+
})

0 commit comments

Comments
 (0)