-
Notifications
You must be signed in to change notification settings - Fork 270
/
trace.go
294 lines (251 loc) · 8.88 KB
/
trace.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Portions of this file are additionally subject to the following
// copyright.
//
// Copyright (C) 2022 Matrix Origin.
//
// Modified the behavior and the interface of the step.
package motrace
import (
"context"
"sync/atomic"
"time"
"github.com/matrixorigin/matrixone/pkg/catalog"
"github.com/matrixorigin/matrixone/pkg/common/moerr"
"github.com/matrixorigin/matrixone/pkg/config"
"github.com/matrixorigin/matrixone/pkg/defines"
"github.com/matrixorigin/matrixone/pkg/logutil"
"github.com/matrixorigin/matrixone/pkg/util/batchpipe"
"github.com/matrixorigin/matrixone/pkg/util/errutil"
"github.com/matrixorigin/matrixone/pkg/util/executor"
db_holder "github.com/matrixorigin/matrixone/pkg/util/export/etl/db"
ie "github.com/matrixorigin/matrixone/pkg/util/internalExecutor"
"github.com/matrixorigin/matrixone/pkg/util/trace"
)
var gTracerProvider atomic.Value
var gTracer trace.Tracer
var gTraceContext atomic.Value
var gSpanContext atomic.Value
func init() {
SetDefaultSpanContext(&trace.SpanContext{})
SetDefaultContext(context.Background())
tp := newMOTracerProvider(EnableTracer(false))
gTracer = tp.Tracer("default")
SetTracerProvider(tp)
}
var inited uint32
func InitWithConfig(ctx context.Context, SV *config.ObservabilityParameters, opts ...TracerProviderOption) (error, bool) {
opts = append(opts,
withMOVersion(SV.MoVersion),
EnableTracer(!SV.DisableTrace),
WithExportInterval(SV.TraceExportInterval),
WithLongQueryTime(SV.LongQueryTime),
WithLongSpanTime(SV.LongSpanTime.Duration),
WithSpanDisable(SV.DisableSpan),
WithErrorDisable(SV.DisableError),
WithSkipRunningStmt(SV.SkipRunningStmt),
WithSQLWriterDisable(SV.DisableSqlWriter),
WithAggregatorDisable(SV.DisableStmtAggregation),
WithAggregatorWindow(SV.AggregationWindow.Duration),
WithSelectThreshold(SV.SelectAggrThreshold.Duration),
WithStmtMergeEnable(SV.EnableStmtMerge),
WithCUConfig(SV.CU, SV.CUv1),
WithTCPPacket(SV.TCPPacket),
WithLabels(SV.LabelSelector),
DebugMode(SV.EnableTraceDebug),
WithBufferSizeThreshold(SV.BufferSize),
)
return Init(ctx, opts...)
}
// Init initializes the tracer with the given options.
// If EnableTracer is set to false, this function does nothing.
// If EnableTracer is set to true, the tracer is initialized.
// Init only allow called once.
func Init(ctx context.Context, opts ...TracerProviderOption) (err error, act bool) {
// fix multi-init in standalone
if !atomic.CompareAndSwapUint32(&inited, 0, 1) {
return nil, false
}
// init TraceProvider
SetTracerProvider(newMOTracerProvider(opts...))
config := &GetTracerProvider().tracerProviderConfig
if !config.disableSpan {
// init Tracer
gTracer = GetTracerProvider().Tracer("MatrixOne")
_, span := gTracer.Start(ctx, "TraceInit")
defer span.End()
defer trace.SetDefaultTracer(gTracer)
}
if config.disableError {
DisableLogErrorReport(true)
}
// init DefaultContext / DefaultSpanContext
var spanId trace.SpanID
spanId.SetByUUID(config.getNodeResource().NodeUuid)
sc := trace.SpanContextWithIDs(trace.NilTraceID, spanId)
SetDefaultSpanContext(&sc)
serviceCtx := context.Background()
SetDefaultContext(trace.ContextWithSpanContext(serviceCtx, sc))
SetCuConfig(&config.cuConfig, &config.cuConfigV1)
// init Exporter
if err := initExporter(ctx, config); err != nil {
return err, true
}
// init all mo_ctl controlled spans
trace.InitMOCtledSpan()
// init tool dependence
logutil.SetLogReporter(&logutil.TraceReporter{ReportZap: ReportZap, ContextField: trace.ContextField})
logutil.SpanFieldKey.Store(trace.SpanFieldKey)
errutil.SetErrorReporter(ReportError)
// init db_hodler
db_holder.SetLabelSelector(config.labels)
logutil.Debugf("trace with LongQueryTime: %v", time.Duration(GetTracerProvider().longQueryTime))
logutil.Debugf("trace with LongSpanTime: %v", GetTracerProvider().longSpanTime)
logutil.Debugf("trace with DisableSpan: %v", GetTracerProvider().disableSpan)
return nil, true
}
func initExporter(ctx context.Context, config *tracerProviderConfig) error {
if !config.IsEnable() {
return nil
}
if config.needInit {
if err := InitSchema(ctx, config.sqlExecutor); err != nil {
return err
}
}
defaultReminder := batchpipe.NewConstantClock(config.exportInterval)
defaultOptions := []BufferOption{BufferWithReminder(defaultReminder), BufferWithSizeThreshold(config.bufferSizeThreshold)}
var p = config.batchProcessor
// init BatchProcess for trace/log/error
p.Register(&MOSpan{}, NewBufferPipe2CSVWorker(defaultOptions...))
p.Register(&MOZapLog{}, NewBufferPipe2CSVWorker(defaultOptions...))
p.Register(&StatementInfo{}, NewBufferPipe2CSVWorker(defaultOptions...))
p.Register(&MOErrorHolder{}, NewBufferPipe2CSVWorker(defaultOptions...))
logutil.Info("init GlobalBatchProcessor")
if !p.Start() {
return moerr.NewInternalError(ctx, "trace exporter already started")
}
config.spanProcessors = append(config.spanProcessors, NewBatchSpanProcessor(p))
logutil.Info("init trace span processor")
return nil
}
// InitSchema
// PS: only in standalone or CN node can init schema
func InitSchema(ctx context.Context, sqlExecutor func() ie.InternalExecutor) error {
ctx = defines.AttachAccount(ctx, catalog.System_Account, catalog.System_User, catalog.System_Role)
c := &GetTracerProvider().tracerProviderConfig
WithSQLExecutor(sqlExecutor).apply(c)
if err := InitSchemaByInnerExecutor(ctx, sqlExecutor); err != nil {
return err
}
return nil
}
// InitSchema2
// PS: only in system bootstrap init schema with `executor.TxnExecutor`
func InitSchemaWithTxn(ctx context.Context, txn executor.TxnExecutor) error {
_, err := txn.Exec(sqlCreateDBConst, executor.StatementOption{})
if err != nil {
return err
}
var createCost time.Duration
defer func() {
logutil.Debugf("[Trace] init tables: create cost %d ms", createCost.Milliseconds())
}()
instant := time.Now()
for _, tbl := range tables {
_, err = txn.Exec(tbl.ToCreateSql(ctx, true), executor.StatementOption{})
if err != nil {
return err
}
}
for _, v := range views {
_, err = txn.Exec(v.ToCreateSql(ctx, true), executor.StatementOption{})
if err != nil {
return err
}
}
createCost = time.Since(instant)
return nil
}
func Shutdown(ctx context.Context) error {
if !GetTracerProvider().IsEnable() {
return nil
}
GetTracerProvider().SetEnable(false)
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
for _, p := range GetTracerProvider().spanProcessors {
if err := p.Shutdown(shutdownCtx); err != nil {
return err
}
}
logutil.Info("Shutdown trace complete.")
return nil
}
type contextHolder struct {
ctx context.Context
}
func SetDefaultContext(ctx context.Context) {
gTraceContext.Store(&contextHolder{ctx})
}
func DefaultContext() context.Context {
return gTraceContext.Load().(*contextHolder).ctx
}
func SetDefaultSpanContext(sc *trace.SpanContext) {
gSpanContext.Store(sc)
}
func DefaultSpanContext() *trace.SpanContext {
return gSpanContext.Load().(*trace.SpanContext)
}
func GetNodeResource() *trace.MONodeResource {
return GetTracerProvider().getNodeResource()
}
func SetTracerProvider(p *MOTracerProvider) {
gTracerProvider.Store(p)
}
// GetTracerProvider returns the global TracerProvider.
// It will be initialized at startup.
var GetTracerProvider = func() *MOTracerProvider {
return gTracerProvider.Load().(*MOTracerProvider)
}
func GetSQLExecutorFactory() func() ie.InternalExecutor {
p := GetTracerProvider()
if p != nil {
p.mux.Lock()
defer p.mux.Unlock()
return p.tracerProviderConfig.sqlExecutor
}
return nil
}
type PipeImpl batchpipe.PipeImpl[batchpipe.HasName, any]
type BatchProcessor interface {
Collect(context.Context, batchpipe.HasName) error
Start() bool
Stop(graceful bool) error
Register(name batchpipe.HasName, impl PipeImpl)
}
type DiscardableCollector interface {
DiscardableCollect(context.Context, batchpipe.HasName) error
}
var _ BatchProcessor = &NoopBatchProcessor{}
type NoopBatchProcessor struct {
}
func (n NoopBatchProcessor) Collect(context.Context, batchpipe.HasName) error { return nil }
func (n NoopBatchProcessor) Start() bool { return true }
func (n NoopBatchProcessor) Stop(bool) error { return nil }
func (n NoopBatchProcessor) Register(batchpipe.HasName, PipeImpl) {}
func GetGlobalBatchProcessor() BatchProcessor {
return GetTracerProvider().batchProcessor
}